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
.. _mcumgr_smp_group_1:
Application/software image management group
###########################################
Application/software image management group defines following commands:
.. table::
:align: center
+-------------------+-----------------------------------------------+
| ``Command ID`` | Command description |
+===================+===============================================+
| ``0`` | State of images |
+-------------------+-----------------------------------------------+
| ``1`` | Image upload |
+-------------------+-----------------------------------------------+
| ``2`` | File |
| | (reserved but not supported by Zephyr) |
+-------------------+-----------------------------------------------+
| ``3`` | Corelist |
| | (reserved but not supported by Zephyr) |
+-------------------+-----------------------------------------------+
| ``4`` | Coreload |
| | (reserved but not supported by Zephyr) |
+-------------------+-----------------------------------------------+
| ``5`` | Image erase |
+-------------------+-----------------------------------------------+
Notion of "slots" and "images" in Zephyr
****************************************
The "slot" and "image" definition comes from mcuboot where "image" would
consist of two "slots", further named "primary" and "secondary"; the application
is supposed to run from the "primary slot" and update is supposed to be
uploaded to the "secondary slot"; the mcuboot is responsible in swapping
slots on boot.
This means that pair of slots is dedicated to single upgradable application.
In case of Zephyr this gets a little bit confusing because DTS will use
"slot0_partition" and "slot1_partition", as label of ``fixed-partition`` dedicated
to single application, but will name them as "image-0" and "image-1" respectively.
Currently Zephyr supports at most two images, in which case mapping is as follows:
.. table::
:align: center
+-------------+-------------------+---------------+
| Image | Slot labels | Slot Names |
+=============+===================+===============+
| 1 | "slot0_partition" | "image-0" |
| | "slot1_partition" | "image-1" |
+-------------+-------------------+---------------+
| 2 | "slot2_partition" | "image-2" |
| | "slot3_partition" | "image-3" |
+-------------+-------------------+---------------+
State of images
***************
The command is used to set state of images and obtain list of images
with their current state.
Get state of images request
===========================
Get state of images request header fields:
.. table::
:align: center
+--------+--------------+----------------+
| ``OP`` | ``Group ID`` | ``Command ID`` |
+========+==============+================+
| ``0`` | ``1`` | ``0`` |
+--------+--------------+----------------+
The command sends an empty CBOR map as data.
.. _mcumgr_smp_protocol_op_1_grp_1_cmd_0:
Get state of images response
============================
Get state of images response header fields:
.. table::
:align: center
+--------+--------------+----------------+
| ``OP`` | ``Group ID`` | ``Command ID`` |
+========+==============+================+
| ``1`` | ``1`` | ``0`` |
+--------+--------------+----------------+
.. note::
Below definition of the response contains "image" field that has been marked
as optional(opt): the field may not appear in response when target application
does not support more than one image. The field is mandatory when application
supports more than one application image to allow identifying which image
information is listed.
A response will only contain information for valid images, if an image can not
be identified as valid it is simply skipped.
CBOR data of successful response:
.. code-block:: none
{
(str)"images" : [
{
(str,opt)"image" : (uint)
(str)"slot" : (uint)
(str)"version" : (str)
(str,opt*)"hash" : (byte str)
(str,opt)"bootable" : (bool)
(str,opt)"pending" : (bool)
(str,opt)"confirmed" : (bool)
(str,opt)"active" : (bool)
(str,opt)"permanent" : (bool)
}
...
]
(str,opt)"splitStatus" : (int)
}
In case of error the CBOR data takes the form:
.. tabs::
.. group-tab:: SMP version 2
.. code-block:: none
{
(str)"err" : {
(str)"group" : (uint)
(str)"rc" : (uint)
}
}
.. group-tab:: SMP version 1 (and non-group SMP version 2)
.. code-block:: none
{
(str)"rc" : (int)
(str,opt)"rsn" : (str)
}
where:
.. table::
:align: center
+------------------+your_sha256_hash---------+
| "image" | semi-optional image number; the field is not required when only one |
| | image is supported by the running application. |
+------------------+your_sha256_hash---------+
| "slot" | slot number within "image"; each image has two slots : primary (running |
| | one) = 0 and secondary (for DFU dual-bank purposes) = 1. |
+------------------+your_sha256_hash---------+
| "version" | string representing image version, as set with ``imgtool``. |
+------------------+your_sha256_hash---------+
| "hash" | SHA256 hash of the image header and body. Note that this will not be |
| | the same as the SHA256 of the whole file, it is the field in the |
| | MCUboot TLV section that contains a hash of the data which is used for |
| | signature verification purposes. This field is optional but only |
| | optional when using MCUboot's serial recovery feature with one pair of |
| | image slots, Kconfig :kconfig:option:`CONFIG_BOOT_SERIAL_IMG_GRP_HASH` |
| | can be disabled to remove support for hashes in this configuration. |
| | MCUmgr in applications must support sending hashes. |
| | |
| | .. note:: |
| | See ``IMAGE_TLV_SHA256`` in the MCUboot image format documentation |
| | link below. |
+------------------+your_sha256_hash---------+
| "bootable" | true if image has bootable flag set; this field does not have to be |
| | present if false. |
+------------------+your_sha256_hash---------+
| "pending" | true if image is set for next swap; this field does not have to be |
| | present if false. |
+------------------+your_sha256_hash---------+
| "confirmed" | true if image has been confirmed; this field does not have to be |
| | present if false. |
+------------------+your_sha256_hash---------+
| "active" | true if image is currently active application; this field does not have |
| | to be present if false. |
+------------------+your_sha256_hash---------+
| "permanent" | true if image is to stay in primary slot after the next boot; this |
| | does not have to be present if false. |
+------------------+your_sha256_hash---------+
| "splitStatus" | states whether loader of split image is compatible with application |
| | part; this is unused by Zephyr. |
+------------------+your_sha256_hash---------+
| "err" -> "group" | :c:enum:`mcumgr_group_t` group of the group-based error code. Only |
| | appears if an error is returned when using SMP version 2. |
+------------------+your_sha256_hash---------+
| "err" -> "rc" | contains the index of the group-based error code. Only appears if |
| | non-zero (error condition) when using SMP version 2. |
+------------------+your_sha256_hash---------+
| "rc" | :c:enum:`mcumgr_err_t` only appears if non-zero (error condition) when |
| | using SMP version 1 or for SMP errors when using SMP version 2. |
+------------------+your_sha256_hash---------+
| "rsn" | optional string that clarifies reason for an error; specifically useful |
| | when ``rc`` is :c:enumerator:`MGMT_ERR_EUNKNOWN`. |
+------------------+your_sha256_hash---------+
.. note::
For more information on how does image/slots function, please refer to
the MCUBoot documentation
path_to_url#image-slots
For information on MCUboot image format, please reset to the MCUboot
documentation path_to_url#image-format
Set state of image request
==========================
Set state of image request header fields:
.. table::
:align: center
+--------+--------------+----------------+
| ``OP`` | ``Group ID`` | ``Command ID`` |
+========+==============+================+
| ``2`` | ``1`` | ``0`` |
+--------+--------------+----------------+
CBOR data of request:
.. code-block:: none
{
(str,opt)"hash" : (str)
(str)"confirm" : (bool)
}
If "confirm" is false or not provided, an image with the "hash" will be set for
test, which means that it will not be marked as permanent and upon hard reset
the previous application will be restored to the primary slot.
In case when "confirm" is true, the "hash" is optional as the currently running
application will be assumed as target for confirmation.
Set state of image response
============================
The response takes the same format as :ref:`mcumgr_smp_protocol_op_1_grp_1_cmd_0`
Image upload
************
The image upload command allows to update application image.
Image upload request
====================
The image upload request is sent for each chunk of image that is uploaded, until
complete image gets uploaded to a device.
Image upload request header fields:
.. table::
:align: center
+--------+--------------+----------------+
| ``OP`` | ``Group ID`` | ``Command ID`` |
+========+==============+================+
| ``2`` | ``1`` | ``1`` |
+--------+--------------+----------------+
CBOR data of request:
.. code-block:: none
{
(str,opt)"image" : (uint)
(str,opt)"len" : (uint)
(str)"off" : (uint)
(str,opt)"sha" : (byte str)
(str)"data" : (byte str)
(str,opt)"upgrade" : (bool)
}
where:
.. table::
:align: center
+-----------+your_sha256_hash----------------+
| "image" | optional image number, it does not have to appear in request at all, in which |
| | case it is assumed to be 0. Should only be present when "off" is 0. |
+-----------+your_sha256_hash----------------+
| "len" | optional length of an image. Must appear when "off" is 0. |
+-----------+your_sha256_hash----------------+
| "off" | offset of image chunk the request carries. |
+-----------+your_sha256_hash----------------+
| "sha" | SHA256 hash of an upload; this is used to identify an upload session (e.g. to |
| | allow MCUmgr to continue a broken session), and for image verification |
| | purposes. This must be a full SHA256 hash of the whole image being uploaded, |
| | or not included if the hash is not available (in which case, upload session |
| | continuation and image verification functionality will be unavailable). Should |
| | only be present when "off" is 0. |
+-----------+your_sha256_hash----------------+
| "data" | image data to write at provided offset. |
+-----------+your_sha256_hash----------------+
| "upgrade" | optional flag that states that only upgrade should be allowed, so if the |
| | version of uploaded software is not higher then already on a device, the image |
| | upload will be rejected. Zephyr compares major, minor and revision (x.y.z) by |
| | default unless |
| | :kconfig:option:`CONFIG_MCUMGR_GRP_IMG_VERSION_CMP_USE_BUILD_NUMBER` is set, |
| | whereby it will compare build numbers too. Should only be present when "off" |
| | is 0. |
+-----------+your_sha256_hash----------------+
.. note::
There is no field representing size of chunk that is carried as "data" because
that information is embedded within "data" field itself.
.. note::
It is possible that a server will respond to an upload with "off" of 0, this
may happen if an upload on another transport (or outside of MCUmgr entirely)
is started, if the device has rebooted or if a packet has been lost. If this
happens, a client must re-send all the required and optional fields that it
sent in the original first packet so that the upload state can be re-created
by the server. If the original fields are not included, the upload will be
unable to continue.
The MCUmgr library uses "sha" field to tag ongoing update session, to be able
to continue it in case when it gets broken, and for upload verification
purposes.
If library gets request with "off" equal zero it checks stored "sha" within its
state and if it matches it will respond to update client application with
offset that it should continue with.
If this hash is not available (e.g. because a file is being streamed) then it
must not be provided, image verification and upload session continuation
features will be unavailable in this case.
Image upload response
=====================
Image upload response header fields:
.. table::
:align: center
+--------+--------------+----------------+
| ``OP`` | ``Group ID`` | ``Command ID`` |
+========+==============+================+
| ``3`` | ``1`` | ``1`` |
+--------+--------------+----------------+
CBOR data of successful response:
.. code-block:: none
{
(str,opt)"off" : (uint)
(str,opt)"match" : (bool)
}
In case of error the CBOR data takes the form:
.. tabs::
.. group-tab:: SMP version 2
.. code-block:: none
{
(str)"err" : {
(str)"group" : (uint)
(str)"rc" : (uint)
}
}
.. group-tab:: SMP version 1 (and non-group SMP version 2)
.. code-block:: none
{
(str)"rc" : (int)
(str,opt)"rsn" : (str)
}
where:
.. table::
:align: center
+------------------+your_sha256_hash---------+
| "off" | offset of last successfully written byte of update. |
+------------------+your_sha256_hash---------+
| "match" | indicates if the uploaded data successfully matches the provided SHA256 |
| | hash or not, only sent in the final packet if |
| | :kconfig:option:`CONFIG_IMG_ENABLE_IMAGE_CHECK` is enabled. |
+------------------+your_sha256_hash---------+
| "err" -> "group" | :c:enum:`mcumgr_group_t` group of the group-based error code. Only |
| | appears if an error is returned when using SMP version 2. |
+------------------+your_sha256_hash---------+
| "err" -> "rc" | contains the index of the group-based error code. Only appears if |
| | non-zero (error condition) when using SMP version 2. |
+------------------+your_sha256_hash---------+
| "rc" | :c:enum:`mcumgr_err_t` only appears if non-zero (error condition) when |
| | using SMP version 1 or for SMP errors when using SMP version 2. |
+------------------+your_sha256_hash---------+
| "rsn" | optional string that clarifies reason for an error; specifically useful |
| | when ``rc`` is :c:enumerator:`MGMT_ERR_EUNKNOWN`. |
+------------------+your_sha256_hash---------+
The "off" field is only included in responses to successfully processed requests;
if "rc" is negative then "off" may not appear.
Image erase
***********
The command is used for erasing image slot on a target device.
.. note::
This is synchronous command which means that a sender of request will not
receive response until the command completes, which can take a long time.
Image erase request
===================
Image erase request header fields:
.. table::
:align: center
+--------+--------------+----------------+
| ``OP`` | ``Group ID`` | ``Command ID`` |
+========+==============+================+
| ``2`` | ``1`` | ``5`` |
+--------+--------------+----------------+
CBOR data of request:
.. code-block:: none
{
(str,opt)"slot" : (uint)
}
where:
.. table::
:align: center
+---------+your_sha256_hash-+
| "slot" | optional slot number, it does not have to appear in the request |
| | at all, in which case it is assumed to be 1. |
+---------+your_sha256_hash-+
Image erase response
====================
Image erase response header fields:
.. table::
:align: center
+--------+--------------+----------------+
| ``OP`` | ``Group ID`` | ``Command ID`` |
+========+==============+================+
| ``3`` | ``1`` | ``5`` |
+--------+--------------+----------------+
The command sends an empty CBOR map as data if successful. In case of error the
CBOR data takes the form:
.. tabs::
.. group-tab:: SMP version 2
.. code-block:: none
{
(str)"err" : {
(str)"group" : (uint)
(str)"rc" : (uint)
}
}
.. group-tab:: SMP version 1 (and non-group SMP version 2)
.. code-block:: none
{
(str)"rc" : (int)
(str,opt)"rsn" : (str)
}
where:
.. table::
:align: center
+------------------+your_sha256_hash---------+
| "err" -> "group" | :c:enum:`mcumgr_group_t` group of the group-based error code. Only |
| | appears if an error is returned when using SMP version 2. |
+------------------+your_sha256_hash---------+
| "err" -> "rc" | contains the index of the group-based error code. Only appears if |
| | non-zero (error condition) when using SMP version 2. |
+------------------+your_sha256_hash---------+
| "rc" | :c:enum:`mcumgr_err_t` only appears if non-zero (error condition) when |
| | using SMP version 1 or for SMP errors when using SMP version 2. |
+------------------+your_sha256_hash---------+
| "rsn" | optional string that clarifies reason for an error; specifically useful |
| | when ``rc`` is :c:enumerator:`MGMT_ERR_EUNKNOWN`. |
+------------------+your_sha256_hash---------+
.. note::
Response from Zephyr running device may have "rc" value of
:c:enumerator:`MGMT_ERR_EBADSTATE`, which means that the secondary
image has been marked for next boot already and may not be erased.
``` | /content/code_sandbox/doc/services/device_mgmt/smp_groups/smp_group_1.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 4,620 |
```restructuredtext
.. _input:
Input
#####
The input subsystem provides an API for dispatching input events from input
devices to the application.
Input Events
************
The subsystem is built around the :c:struct:`input_event` structure. An input
event represents a change in an individual event entity, for example the state
of a single button, or a movement in a single axis.
The :c:struct:`input_event` structure describes the specific event, and
includes a synchronization bit to indicate that the device reached a stable
state, for example when the events corresponding to multiple axes of a
multi-axis device have been reported.
Input Devices
*************
An input device can report input events directly using :c:func:`input_report`
or any related function; for example buttons or other on-off input entities
would use :c:func:`input_report_key`.
Complex devices may use a combination of multiple events, and set the ``sync``
bit once the output is stable.
The ``input_report*`` functions take a :c:struct:`device` pointer, which is
used to indicate which device reported the event and can be used by subscribers
to only receive events from a specific device. If there's no actual device
associated with the event, it can be set to ``NULL``, in which case only
subscribers with no device filter will receive the event.
Application API
***************
An application can register a callback using the
:c:macro:`INPUT_CALLBACK_DEFINE` macro. If a device node is specified, the
callback is only invoked for events from the specific device, otherwise the
callback will receive all the events in the system. This is the only type of
filtering supported, any more complex filtering logic has to be implemented in
the callback itself.
The subsystem can operate synchronously or by using an event queue, depending
on the :kconfig:option:`CONFIG_INPUT_MODE` option. If the input thread is used,
all the events are added to a queue and executed in a common ``input`` thread.
If the thread is not used, the callback are invoked directly in the input
driver context.
The synchronous mode can be used in a simple application to keep a minimal
footprint, or in a complex application with an existing event model, where the
callback is just a wrapper to pipe back the event in a more complex application
specific event system.
HID code mapping
****************
A common use case for input devices is to use them to generate HID reports. For
this purpose, the :c:func:`input_to_hid_code` and
:c:func:`input_to_hid_modifier` functions can be used to map input codes to HID
codes and modifiers.
Kscan Compatibility
*******************
Input devices generating X/Y/Touch events can be used in existing applications
based on the :ref:`kscan_api` API by enabling both
:kconfig:option:`CONFIG_INPUT` and :kconfig:option:`CONFIG_KSCAN`, defining a
:dtcompatible:`zephyr,kscan-input` node as a child node of the corresponding
input device and pointing the ``zephyr,keyboard-scan`` chosen node to the
compatibility device node, for example:
.. code-block:: devicetree
chosen {
zephyr,keyboard-scan = &kscan_input;
};
ft5336@38 {
...
kscan_input: kscan-input {
compatible = "zephyr,kscan-input";
};
};
General Purpose Drivers
***********************
- :dtcompatible:`adc-keys`: for buttons connected to a resistor ladder.
- :dtcompatible:`analog-axis`: for absolute position devices connected to an
ADC input (thumbsticks, sliders...).
- :dtcompatible:`gpio-kbd-matrix`: for GPIO-connected keyboard matrices.
- :dtcompatible:`gpio-keys`: for switches directly connected to a GPIO,
implements button debouncing.
- :dtcompatible:`gpio-qdec`: for GPIO-connected quadrature encoders.
- :dtcompatible:`input-keymap`: maps row/col/touch events from a keyboard
matrix to key events.
- :dtcompatible:`zephyr,input-longpress`: listens for key events, emits events
for short and long press.
- :dtcompatible:`zephyr,input-double-tap`: listens for key events, emits events
for input double taps
- :dtcompatible:`zephyr,lvgl-button-input`
:dtcompatible:`zephyr,lvgl-encoder-input`
:dtcompatible:`zephyr,lvgl-keypad-input`
:dtcompatible:`zephyr,lvgl-pointer-input`: listens for input events and
translates those to various types of LVGL input devices.
Detailed Driver Documentation
*****************************
.. toctree::
:maxdepth: 1
gpio-kbd.rst
API Reference
*************
.. doxygengroup:: input_interface
Input Event Definitions
***********************
.. doxygengroup:: input_events
Analog Axis API Reference
*************************
.. doxygengroup:: input_analog_axis
``` | /content/code_sandbox/doc/services/input/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,062 |
```restructuredtext
.. _gpio-kbd:
GPIO Keyboard Matrix
####################
The :dtcompatible:`gpio-kbd-matrix` driver supports a large variety of keyboard
matrix hardware configurations and has numerous options to change its behavior.
This is an overview of some common setups and how they can be supported by the
driver.
The conventional configuration for all of these is that the driver reads on the
row GPIOs (inputs) and selects on the columns GPIOs (output).
Base use case, no isolation diodes, interrupt capable GPIOs
***********************************************************
This is the common configuration found on consumer keyboards with membrane
switches and flexible circuit boards, no isolation diodes, requires ghosting
detection (which is enabled by default).
.. figure:: no-diodes.svg
:align: center
:width: 50%
A 3x3 matrix, no diodes
The system must support GPIO interrupts, and the interrupt can be enabled on all
row GPIOs at the same time.
.. code-block:: devicetree
kbd-matrix {
compatible = "gpio-kbd-matrix";
row-gpios = <&gpio0 0 (GPIO_PULL_UP | GPIO_ACTIVE_LOW)>,
<&gpio0 1 (GPIO_PULL_UP | GPIO_ACTIVE_LOW)>,
<&gpio0 2 (GPIO_PULL_UP | GPIO_ACTIVE_LOW)>;
col-gpios = <&gpio0 3 GPIO_ACTIVE_LOW>,
<&gpio0 4 GPIO_ACTIVE_LOW>,
<&gpio0 5 GPIO_ACTIVE_LOW>;
};
In this configuration the matrix scanning library enters idle mode once all
keys are released, and the keyboard matrix thread only wakes up when a key has
been pressed.
GPIOs for columns that are not currently selected are configured in high
impedance mode. This means that the row state may need some time to settle to
avoid misreading the key state from a column to the following one. The settle
time can be tweaked by changing the ``settle-time-us`` property.
Isolation diodes
****************
If the matrix has isolation diodes for every key, then it's possible to:
- disable ghosting detection, allowing any key combination to be detected
- configuring the driver to drive unselected columns GPIO to inactive state
rather than high impedance, this allows to reduce the settle time
(potentially down to 0), and use the more efficient port wide GPIO read APIs
(happens automatically if the GPIO pins are sequential)
Matrixes with diodes going from rows to columns must use pull-ups on rows and
active low columns.
.. figure:: diodes-rc.svg
:align: center
:width: 50%
A 3x3 matrix with row to column isolation diodes.
.. code-block:: devicetree
kbd-matrix {
compatible = "gpio-kbd-matrix";
row-gpios = <&gpio0 0 (GPIO_PULL_UP | GPIO_ACTIVE_LOW)>,
<&gpio0 1 (GPIO_PULL_UP | GPIO_ACTIVE_LOW)>,
<&gpio0 2 (GPIO_PULL_UP | GPIO_ACTIVE_LOW)>;
col-gpios = <&gpio0 3 GPIO_ACTIVE_LOW>,
<&gpio0 4 GPIO_ACTIVE_LOW>,
<&gpio0 5 GPIO_ACTIVE_LOW>;
col-drive-inactive;
settle-time-us = <0>;
no-ghostkey-check;
};
Matrixes with diodes going from columns to rows must use pull-downs on rows and
active high columns.
.. figure:: diodes-cr.svg
:align: center
:width: 50%
A 3x3 matrix with column to row isolation diodes.
.. code-block:: devicetree
kbd-matrix {
compatible = "gpio-kbd-matrix";
row-gpios = <&gpio0 0 (GPIO_PULL_DOWN | GPIO_ACTIVE_HIGH)>,
<&gpio0 1 (GPIO_PULL_DOWN | GPIO_ACTIVE_HIGH)>,
<&gpio0 2 (GPIO_PULL_DOWN | GPIO_ACTIVE_HIGH)>;
col-gpios = <&gpio0 3 GPIO_ACTIVE_HIGH>,
<&gpio0 4 GPIO_ACTIVE_HIGH>,
<&gpio0 5 GPIO_ACTIVE_HIGH>;
col-drive-inactive;
settle-time-us = <0>;
no-ghostkey-check;
};
GPIO with no interrupt support
******************************
Some GPIO controllers have limitations on GPIO interrupts, and may not support
enabling interrupts on all row GPIOs at the same time.
In this case, the driver can be configured to not use interrupt at all, and
instead idle by selecting all columns and keep polling on the row GPIOs, which
is a single GPIO API operation if the pins are sequential.
This configuration can be enabled by setting the ``idle-mode`` property to
``poll``:
.. code-block:: devicetree
kbd-matrix {
compatible = "gpio-kbd-matrix";
...
idle-mode = "poll";
};
GPIO multiplexer
****************
In more extreme cases, such as if the columns are using a multiplexer and it's
impossible to select all of them at the same time, the driver can be configured
to scan continuously.
This can be done by setting ``idle-mode`` to ``scan`` and ``poll-timeout-ms``
to ``0``.
.. code-block:: devicetree
kbd-matrix {
compatible = "gpio-kbd-matrix";
...
poll-timeout-ms = <0>;
idle-mode = "scan";
};
Row and column GPIO selection
*****************************
If the row GPIOs are sequential and on the same gpio controller, the driver
automatically switches API to read from the whole GPIO port rather than the
individual pins. This is particularly useful if the GPIOs are not memory
mapped, for example on an I2C or SPI port expander, as this significantly
reduces the number of transactions on the corresponding bus.
The same is true for column GPIOs, but only if the matrix is configured for
``col-drive-inactive``, so that is only usable for matrixes with isolation
diodes.
16-bit row support
******************
The driver uses an 8-bit datatype to store the row state by default, which
limits the matrix row size to 8. This can be increased to 16 by enabling the
:kconfig:option:`CONFIG_INPUT_KBD_MATRIX_16_BIT_ROW` option.
Actual key mask configuration
*****************************
If the key matrix is not complete, a map of the keys that are actually
populated can be specified using the `actual-key-mask` property. This allows
the matrix state to be filtered to remove keys that are not present before
ghosting detection, potentially allowing key combinations that would otherwise
be blocked by it.
For example for a 3x3 matrix missing a key:
.. figure:: no-sw4.svg
:align: center
:width: 50%
A 3x3 matrix missing a key.
.. code-block:: devicetree
kbd-matrix {
compatible = "gpio-kbd-matrix";
...
actual-key-mask = <0x07 0x05 0x07>;
};
This would allow, for example, to detect pressing ``Sw1``, ``SW2`` and ``SW4``
at the same time without triggering anti ghosting.
The actual key mask can be changed at runtime by enabling
:kconfig:option:`CONFIG_INPUT_KBD_ACTUAL_KEY_MASK_DYNAMIC` and the using the
:c:func:`input_kbd_matrix_actual_key_mask_set` API.
Keymap configuration
********************
Keyboard matrix devices report a series of x/y/touch events. These can be
mapped to normal key events using the :dtcompatible:`input-keymap` driver.
For example, the following would setup a ``keymap`` device that take the
x/y/touch events as an input and generate corresponding key events as an
output:
.. code-block:: devicetree
kbd {
...
keymap {
compatible = "input-keymap";
keymap = <
MATRIX_KEY(0, 0, INPUT_KEY_1)
MATRIX_KEY(0, 1, INPUT_KEY_2)
MATRIX_KEY(0, 2, INPUT_KEY_3)
MATRIX_KEY(1, 0, INPUT_KEY_4)
MATRIX_KEY(1, 1, INPUT_KEY_5)
MATRIX_KEY(1, 2, INPUT_KEY_6)
MATRIX_KEY(2, 0, INPUT_KEY_7)
MATRIX_KEY(2, 1, INPUT_KEY_8)
MATRIX_KEY(2, 2, INPUT_KEY_9)
>;
row-size = <3>;
col-size = <3>;
};
};
Keyboard matrix shell commands
******************************
The shell command ``kbd_matrix_state_dump`` can be used to test the
functionality of any keyboard matrix driver implemented using the keyboard
matrix library. Once enabled it logs the state of the matrix every time it
changes, and once disabled it prints an or-mask of any key that has been
detected, which can be used to set the ``actual-key-mask`` property.
The command can be enabled using the
:kconfig:option:`CONFIG_INPUT_SHELL_KBD_MATRIX_STATE`.
Example usage:
.. code-block:: console
uart:~$ device list
devices:
- kbd-matrix (READY)
uart:~$ input kbd_matrix_state_dump kbd-matrix
Keyboard state logging enabled for kbd-matrix
[00:01:41.678,466] <inf> input: kbd-matrix state [01 -- -- --] (1)
[00:01:41.784,912] <inf> input: kbd-matrix state [-- -- -- --] (0)
...
press more buttons
...
uart:~$ input kbd_matrix_state_dump off
Keyboard state logging disabled
[00:01:47.967,651] <inf> input: kbd-matrix key-mask [07 05 07 --] (8)
Keyboard matrix library
***********************
The GPIO keyboard matrix driver is based on a generic keyboard matrix library,
which implements the core functionalities such as scanning delays, debouncing,
idle mode etc. This can be reused to implement other keyboard matrix drivers,
potentially application specific.
.. doxygengroup:: input_kbd_matrix
``` | /content/code_sandbox/doc/services/input/gpio-kbd.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 2,212 |
```restructuredtext
.. _smf:
State Machine Framework
#######################
.. highlight:: c
Overview
========
The State Machine Framework (SMF) is an application agnostic framework that
provides an easy way for developers to integrate state machines into their
application. The framework can be added to any project by enabling the
:kconfig:option:`CONFIG_SMF` option.
State Creation
==============
A state is represented by three functions, where one function implements the
Entry actions, another function implements the Run actions, and the last
function implements the Exit actions. The prototype for these functions is as
follows: ``void funct(void *obj)``, where the ``obj`` parameter is a user
defined structure that has the state machine context, :c:struct:`smf_ctx`, as
its first member. For example::
struct user_object {
struct smf_ctx ctx;
/* All User Defined Data Follows */
};
The :c:struct:`smf_ctx` member must be first because the state machine
framework's functions casts the user defined object to the :c:struct:`smf_ctx`
type with the :c:macro:`SMF_CTX` macro.
For example instead of doing this ``(struct smf_ctx *)&user_obj``, you could
use ``SMF_CTX(&user_obj)``.
By default, a state can have no ancestor states, resulting in a flat state
machine. But to enable the creation of a hierarchical state machine, the
:kconfig:option:`CONFIG_SMF_ANCESTOR_SUPPORT` option must be enabled.
By default, the hierarchical state machines do not support initial transitions
to child states on entering a superstate. To enable them the
:kconfig:option:`CONFIG_SMF_INITIAL_TRANSITION` option must be enabled.
The following macro can be used for easy state creation:
* :c:macro:`SMF_CREATE_STATE` Create a state
State Machine Creation
======================
A state machine is created by defining a table of states that's indexed by an
enum. For example, the following creates three flat states::
enum demo_state { S0, S1, S2 };
const struct smf_state demo_states[] = {
[S0] = SMF_CREATE_STATE(s0_entry, s0_run, s0_exit, NULL, NULL),
[S1] = SMF_CREATE_STATE(s1_entry, s1_run, s1_exit, NULL, NULL),
[S2] = SMF_CREATE_STATE(s2_entry, s2_run, s2_exit, NULL, NULL)
};
And this example creates three hierarchical states::
enum demo_state { S0, S1, S2 };
const struct smf_state demo_states[] = {
[S0] = SMF_CREATE_STATE(s0_entry, s0_run, s0_exit, parent_s0, NULL),
[S1] = SMF_CREATE_STATE(s1_entry, s1_run, s1_exit, parent_s12, NULL),
[S2] = SMF_CREATE_STATE(s2_entry, s2_run, s2_exit, parent_s12, NULL)
};
This example creates three hierarchical states with an initial transition
from parent state S0 to child state S2::
enum demo_state { S0, S1, S2 };
/* Forward declaration of state table */
const struct smf_state demo_states[];
const struct smf_state demo_states[] = {
[S0] = SMF_CREATE_STATE(s0_entry, s0_run, s0_exit, NULL, demo_states[S2]),
[S1] = SMF_CREATE_STATE(s1_entry, s1_run, s1_exit, demo_states[S0], NULL),
[S2] = SMF_CREATE_STATE(s2_entry, s2_run, s2_exit, demo_states[S0], NULL)
};
To set the initial state, the :c:func:`smf_set_initial` function should be
called.
To transition from one state to another, the :c:func:`smf_set_state`
function is used.
.. note:: If :kconfig:option:`CONFIG_SMF_INITIAL_TRANSITION` is not set,
:c:func:`smf_set_initial` and :c:func:`smf_set_state` function should
not be passed a parent state as the parent state does not know which
child state to transition to. Transitioning to a parent state is OK
if an initial transition to a child state is defined. A well-formed
HSM should have initial transitions defined for all parent states.
.. note:: While the state machine is running, :c:func:`smf_set_state` should
only be called from the Entry or Run function. Calling
:c:func:`smf_set_state` from Exit functions will generate a warning in the
log and no transition will occur.
State Machine Execution
=======================
To run the state machine, the :c:func:`smf_run_state` function should be
called in some application dependent way. An application should cease calling
smf_run_state if it returns a non-zero value.
Preventing Parent Run Actions
=============================
Calling :c:func:`smf_set_handled` prevents calling the run action of parent
states. It is not required to call :c:func:`smf_set_handled` if the state
calls :c:func:`smf_set_state`.
State Machine Termination
=========================
To terminate the state machine, the :c:func:`smf_set_terminate` function
should be called. It can be called from the entry, run, or exit actions. The
function takes a non-zero user defined value that will be returned by the
:c:func:`smf_run_state` function.
UML State Machines
==================
SMF follows UML hierarchical state machine rules for transitions i.e., the
entry and exit actions of the least common ancestor are not executed on
transition, unless said transition is a transition to self.
The UML Specification for StateMachines may be found in chapter 14 of the UML
specification available here: path_to_url
SMF breaks from UML rules in:
1. Executing the actions associated with the transition within the context
of the source state, rather than after the exit actions are performed.
2. Only allowing external transitions to self, not to sub-states. A transition
from a superstate to a child state is treated as a local transition.
3. Prohibiting transitions using :c:func:`smf_set_state` in exit actions.
SMF also does not provide any pseudostates except the Initial Pseudostate.
Terminate pseudostates can be modelled by calling :c:func:`smf_set_terminate`
from the entry action of a 'terminate' state. Orthogonal regions are modelled
by calling :c:func:`smf_run_state` for each region.
State Machine Examples
======================
Flat State Machine Example
**************************
This example turns the following state diagram into code using the SMF, where
the initial state is S0.
.. graphviz::
:caption: Flat state machine diagram
digraph smf_flat {
node [style=rounded];
init [shape = point];
STATE_S0 [shape = box];
STATE_S1 [shape = box];
STATE_S2 [shape = box];
init -> STATE_S0;
STATE_S0 -> STATE_S1;
STATE_S1 -> STATE_S2;
STATE_S2 -> STATE_S0;
}
Code::
#include <zephyr/smf.h>
/* Forward declaration of state table */
static const struct smf_state demo_states[];
/* List of demo states */
enum demo_state { S0, S1, S2 };
/* User defined object */
struct s_object {
/* This must be first */
struct smf_ctx ctx;
/* Other state specific data add here */
} s_obj;
/* State S0 */
static void s0_entry(void *o)
{
/* Do something */
}
static void s0_run(void *o)
{
smf_set_state(SMF_CTX(&s_obj), &demo_states[S1]);
}
static void s0_exit(void *o)
{
/* Do something */
}
/* State S1 */
static void s1_run(void *o)
{
smf_set_state(SMF_CTX(&s_obj), &demo_states[S2]);
}
static void s1_exit(void *o)
{
/* Do something */
}
/* State S2 */
static void s2_entry(void *o)
{
/* Do something */
}
static void s2_run(void *o)
{
smf_set_state(SMF_CTX(&s_obj), &demo_states[S0]);
}
/* Populate state table */
static const struct smf_state demo_states[] = {
[S0] = SMF_CREATE_STATE(s0_entry, s0_run, s0_exit, NULL, NULL),
/* State S1 does not have an entry action */
[S1] = SMF_CREATE_STATE(NULL, s1_run, s1_exit, NULL, NULL),
/* State S2 does not have an exit action */
[S2] = SMF_CREATE_STATE(s2_entry, s2_run, NULL, NULL, NULL),
};
int main(void)
{
int32_t ret;
/* Set initial state */
smf_set_initial(SMF_CTX(&s_obj), &demo_states[S0]);
/* Run the state machine */
while(1) {
/* State machine terminates if a non-zero value is returned */
ret = smf_run_state(SMF_CTX(&s_obj));
if (ret) {
/* handle return code and terminate state machine */
break;
}
k_msleep(1000);
}
}
Hierarchical State Machine Example
**********************************
This example turns the following state diagram into code using the SMF, where
S0 and S1 share a parent state and S0 is the initial state.
.. graphviz::
:caption: Hierarchical state machine diagram
digraph smf_hierarchical {
node [style = rounded];
init [shape = point];
STATE_S0 [shape = box];
STATE_S1 [shape = box];
STATE_S2 [shape = box];
subgraph cluster_0 {
label = "PARENT";
style = rounded;
STATE_S0 -> STATE_S1;
}
init -> STATE_S0;
STATE_S1 -> STATE_S2;
STATE_S2 -> STATE_S0;
}
Code::
#include <zephyr/smf.h>
/* Forward declaration of state table */
static const struct smf_state demo_states[];
/* List of demo states */
enum demo_state { PARENT, S0, S1, S2 };
/* User defined object */
struct s_object {
/* This must be first */
struct smf_ctx ctx;
/* Other state specific data add here */
} s_obj;
/* Parent State */
static void parent_entry(void *o)
{
/* Do something */
}
static void parent_exit(void *o)
{
/* Do something */
}
/* State S0 */
static void s0_run(void *o)
{
smf_set_state(SMF_CTX(&s_obj), &demo_states[S1]);
}
/* State S1 */
static void s1_run(void *o)
{
smf_set_state(SMF_CTX(&s_obj), &demo_states[S2]);
}
/* State S2 */
static void s2_run(void *o)
{
smf_set_state(SMF_CTX(&s_obj), &demo_states[S0]);
}
/* Populate state table */
static const struct smf_state demo_states[] = {
/* Parent state does not have a run action */
[PARENT] = SMF_CREATE_STATE(parent_entry, NULL, parent_exit, NULL, NULL),
/* Child states do not have entry or exit actions */
[S0] = SMF_CREATE_STATE(NULL, s0_run, NULL, &demo_states[PARENT], NULL),
[S1] = SMF_CREATE_STATE(NULL, s1_run, NULL, &demo_states[PARENT], NULL),
/* State S2 do ot have entry or exit actions and no parent */
[S2] = SMF_CREATE_STATE(NULL, s2_run, NULL, NULL, NULL),
};
int main(void)
{
int32_t ret;
/* Set initial state */
smf_set_initial(SMF_CTX(&s_obj), &demo_states[S0]);
/* Run the state machine */
while(1) {
/* State machine terminates if a non-zero value is returned */
ret = smf_run_state(SMF_CTX(&s_obj));
if (ret) {
/* handle return code and terminate state machine */
break;
}
k_msleep(1000);
}
}
When designing hierarchical state machines, the following should be considered:
- Ancestor entry actions are executed before the sibling entry actions. For
example, the parent_entry function is called before the s0_entry function.
- Transitioning from one sibling to another with a shared ancestry does not
re-execute the ancestor\'s entry action or execute the exit action.
For example, the parent_entry function is not called when transitioning
from S0 to S1, nor is the parent_exit function called.
- Ancestor exit actions are executed after the exit action of the current
state. For example, the s1_exit function is called before the parent_exit
function is called.
- The parent_run function only executes if the child_run function does not
call either :c:func:`smf_set_state` or :c:func:`smf_set_handled`.
Event Driven State Machine Example
**********************************
Events are not explicitly part of the State Machine Framework but an event driven
state machine can be implemented using Zephyr :ref:`events`.
.. graphviz::
:caption: Event driven state machine diagram
digraph smf_flat {
node [style=rounded];
init [shape = point];
STATE_S0 [shape = box];
STATE_S1 [shape = box];
init -> STATE_S0;
STATE_S0 -> STATE_S1 [label = "BTN EVENT"];
STATE_S1 -> STATE_S0 [label = "BTN EVENT"];
}
Code::
#include <zephyr/kernel.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/smf.h>
#define SW0_NODE DT_ALIAS(sw0)
/* List of events */
#define EVENT_BTN_PRESS BIT(0)
static const struct gpio_dt_spec button =
GPIO_DT_SPEC_GET_OR(SW0_NODE, gpios, {0});
static struct gpio_callback button_cb_data;
/* Forward declaration of state table */
static const struct smf_state demo_states[];
/* List of demo states */
enum demo_state { S0, S1 };
/* User defined object */
struct s_object {
/* This must be first */
struct smf_ctx ctx;
/* Events */
struct k_event smf_event;
int32_t events;
/* Other state specific data add here */
} s_obj;
/* State S0 */
static void s0_entry(void *o)
{
printk("STATE0\n");
}
static void s0_run(void *o)
{
struct s_object *s = (struct s_object *)o;
/* Change states on Button Press Event */
if (s->events & EVENT_BTN_PRESS) {
smf_set_state(SMF_CTX(&s_obj), &demo_states[S1]);
}
}
/* State S1 */
static void s1_entry(void *o)
{
printk("STATE1\n");
}
static void s1_run(void *o)
{
struct s_object *s = (struct s_object *)o;
/* Change states on Button Press Event */
if (s->events & EVENT_BTN_PRESS) {
smf_set_state(SMF_CTX(&s_obj), &demo_states[S0]);
}
}
/* Populate state table */
static const struct smf_state demo_states[] = {
[S0] = SMF_CREATE_STATE(s0_entry, s0_run, NULL, NULL, NULL),
[S1] = SMF_CREATE_STATE(s1_entry, s1_run, NULL, NULL, NULL),
};
void button_pressed(const struct device *dev,
struct gpio_callback *cb, uint32_t pins)
{
/* Generate Button Press Event */
k_event_post(&s_obj.smf_event, EVENT_BTN_PRESS);
}
int main(void)
{
int ret;
if (!gpio_is_ready_dt(&button)) {
printk("Error: button device %s is not ready\n",
button.port->name);
return;
}
ret = gpio_pin_configure_dt(&button, GPIO_INPUT);
if (ret != 0) {
printk("Error %d: failed to configure %s pin %d\n",
ret, button.port->name, button.pin);
return;
}
ret = gpio_pin_interrupt_configure_dt(&button,
GPIO_INT_EDGE_TO_ACTIVE);
if (ret != 0) {
printk("Error %d: failed to configure interrupt on %s pin %d\n",
ret, button.port->name, button.pin);
return;
}
gpio_init_callback(&button_cb_data, button_pressed, BIT(button.pin));
gpio_add_callback(button.port, &button_cb_data);
/* Initialize the event */
k_event_init(&s_obj.smf_event);
/* Set initial state */
smf_set_initial(SMF_CTX(&s_obj), &demo_states[S0]);
/* Run the state machine */
while(1) {
/* Block until an event is detected */
s_obj.events = k_event_wait(&s_obj.smf_event,
EVENT_BTN_PRESS, true, K_FOREVER);
/* State machine terminates if a non-zero value is returned */
ret = smf_run_state(SMF_CTX(&s_obj));
if (ret) {
/* handle return code and terminate state machine */
break;
}
}
}
State Machine Example With Initial Transitions And Transition To Self
*********************************************************************
:zephyr_file:`tests/lib/smf/src/test_lib_self_transition_smf.c` defines a state
machine for testing the initial transitions and transitions to self in a parent
state. The statechart for this test is below.
.. graphviz::
:caption: Test state machine for UML State Transitions
digraph smf_hierarchical_initial {
compound=true;
node [style = rounded];
"smf_set_initial()" [shape=plaintext fontname=Courier];
ab_init_state [shape = point];
STATE_A [shape = box];
STATE_B [shape = box];
STATE_C [shape = box];
STATE_D [shape = box];
DC[shape=point height=0 width=0 label=<>]
subgraph cluster_root {
label = "ROOT";
style = rounded;
subgraph cluster_ab {
label = "PARENT_AB";
style = rounded;
ab_init_state -> STATE_A;
STATE_A -> STATE_B;
}
subgraph cluster_c {
label = "PARENT_C";
style = rounded;
STATE_B -> STATE_C [ltail=cluster_ab]
}
STATE_C -> DC [ltail=cluster_c, dir=none];
DC -> STATE_C [lhead=cluster_c];
STATE_C -> STATE_D
}
"smf_set_initial()" -> STATE_A [lhead=cluster_ab]
}
API Reference
=============
.. doxygengroup:: smf
``` | /content/code_sandbox/doc/services/smf/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 4,260 |
```restructuredtext
.. _tracing:
Tracing
#######
Overview
********
The tracing feature provides hooks that permits you to collect data from
your application and allows :ref:`tools` running on a host to visualize the inner-working of
the kernel and various subsystems.
Every system has application-specific events to trace out. Historically,
that has implied:
1. Determining the application-specific payload,
2. Choosing suitable serialization-format,
3. Writing the on-target serialization code,
4. Deciding on and writing the I/O transport mechanics,
5. Writing the PC-side deserializer/parser,
6. Writing custom ad-hoc tools for filtering and presentation.
An application can use one of the existing formats or define a custom format by
overriding the macros declared in :zephyr_file:`include/zephyr/tracing/tracing.h`.
Different formats, transports and host tools are available and supported in
Zephyr.
In fact, I/O varies greatly from system to system. Therefore, it is
instructive to create a taxonomy for I/O types when we must ensure the
interface between payload/format (Top Layer) and the transport mechanics
(bottom Layer) is generic and efficient enough to model these. See the
*I/O taxonomy* section below.
Serialization Formats
**********************
.. _ctf:
Common Trace Format (CTF) Support
=================================
Common Trace Format, CTF, is an open format and language to describe trace
formats. This enables tool reuse, of which line-textual (babeltrace) and
graphical (TraceCompass) variants already exist.
CTF should look familiar to C programmers but adds stronger typing.
See `CTF - A Flexible, High-performance Binary Trace Format
<path_to_url`_.
CTF allows us to formally describe application specific payload and the
serialization format, which enables common infrastructure for host tools
and parsers and tools for filtering and presentation.
A Generic Interface
--------------------
In CTF, an event is serialized to a packet containing one or more fields.
As seen from *I/O taxonomy* section below, a bottom layer may:
- perform actions at transaction-start (e.g. mutex-lock),
- process each field in some way (e.g. sync-push emit, concat, enqueue to
thread-bound FIFO),
- perform actions at transaction-stop (e.g. mutex-release, emit of concat
buffer).
CTF Top-Layer Example
----------------------
The CTF_EVENT macro will serialize each argument to a field::
/* Example for illustration */
static inline void ctf_top_foo(uint32_t thread_id, ctf_bounded_string_t name)
{
CTF_EVENT(
CTF_LITERAL(uint8_t, 42),
thread_id,
name,
"hello, I was emitted from function: ",
__func__ /* __func__ is standard since C99 */
);
}
How to serialize and emit fields as well as handling alignment, can be done
internally and statically at compile-time in the bottom-layer.
The CTF top layer is enabled using the configuration option
:kconfig:option:`CONFIG_TRACING_CTF` and can be used with the different transport
backends both in synchronous and asynchronous modes.
.. _tools:
Tracing Tools
*************
Zephyr includes support for several popular tracing tools, presented below in alphabetical order.
Percepio Tracealyzer Support
============================
Zephyr includes support for `Percepio Tracealyzer`_ that offers trace visualization for
simplified analysis, report generation and other analysis features. Tracealyzer allows for trace
streaming over various interfaces and also snapshot tracing, where the events are kept in a RAM
buffer.
.. _Percepio Tracealyzer: path_to_url
.. figure:: percepio_tracealyzer.png
:align: center
:alt: Percepio Tracealyzer
:figclass: align-center
:width: 80%
Zephyr kernel events are captured automatically when Tracealyzer tracing is enabled.
Tracealyzer also provides extensive support for application logging, where you call the tracing
library from your application code. This lets you visualize kernel events and application events
together, for example as data plots or state diagrams on logged variables.
Learn more in the Tracealyzer User Manual provided with the application.
Percepio TraceRecorder and Stream Ports
---------------------------------------
The tracing library for Tracealyzer (TraceRecorder) is included in the Zephyr manifest and
provided under the same license (Apache 2.0). This is enabled by adding the following
configuration options in your prj.conf:
.. code-block:: cfg
CONFIG_TRACING=y
CONFIG_PERCEPIO_TRACERECORDER=y
Or using menuconfig:
* Enable :menuselection:`Subsystems and OS Services --> Tracing Support`
* Under :menuselection:`Subsystems and OS Services --> Tracing Support --> Tracing Format`, select
:guilabel:`Percepio Tracealyzer`
Some additional settings are needed to configure TraceRecorder. The most important configuration
is to select the right "stream port". This specifies how to output the trace data.
As of July 2024, the following stream ports are available in the Zephyr configuration system:
* **Ring Buffer**: The trace data is kept in a circular RAM buffer.
* **RTT**: Trace streaming via Segger RTT on J-Link debug probes.
* **ITM**: Trace streaming via the ITM function on Arm Cortex-M devices.
* **Semihost**: For tracing on QEMU. Streams the trace data to a host file.
Select the stream port in menuconfig under
:menuselection:`Modules --> percepio --> TraceRecorder --> Stream Port`.
Or simply add one of the following options in your prj.conf:
.. code-block:: cfg
CONFIG_PERCEPIO_TRC_CFG_STREAM_PORT_RINGBUFFER=y
CONFIG_PERCEPIO_TRC_CFG_STREAM_PORT_RTT=y
CONFIG_PERCEPIO_TRC_CFG_STREAM_PORT_ITM=y
CONFIG_PERCEPIO_TRC_CFG_STREAM_PORT_ZEPHYR_SEMIHOST=y
Make sure to only include ONE of these configuration options.
The stream port modules have individual configuration options. In menuconfig these are found
under :menuselection:`Modules --> percepio --> TraceRecorder --> (Stream Port) Config`.
The most important options for each stream port are described below.
Tracealyzer Snapshot Tracing (Ring Buffer)
------------------------------------------
The "Ring Buffer" stream port keeps the trace data in a RAM buffer on the device.
By default, this is a circular buffer, meaning that it always contains the most recent data.
This is used to dump "snapshots" of the trace data, e.g. by using the debugger. This usually only
allows for short traces, unless you have megabytes of RAM to spare, so it is not suitable for
profiling. However, it can be quite useful for debugging in combination with breakpoints.
For example, if you set a breakpoint in an error handler, a snapshot trace can show the sequence
of events leading up to the error. Snapshot tracing is also easy to begin with, since it doesn't
depend on any particular debug probe or other development tool.
To use the Ring Buffer option, make sure to have the following configuration options in your
prj.cnf:
.. code-block:: cfg
CONFIG_TRACING=y
CONFIG_PERCEPIO_TRACERECORDER=y
CONFIG_PERCEPIO_TRC_START_MODE_START=y
CONFIG_PERCEPIO_TRC_CFG_STREAM_PORT_RINGBUFFER=y
CONFIG_PERCEPIO_TRC_CFG_STREAM_PORT_RINGBUFFER_SIZE=<size in bytes>
Or if using menuconfig:
* Enable :menuselection:`Subsystems and OS Services --> Tracing Support`
* Under :menuselection:`Subsystems and OS Services --> Tracing Support --> Tracing Format`, select
:guilabel:`Percepio Tracealyzer`
* Under :menuselection:`Modules --> percepio --> TraceRecorder --> Recorder Start Mode`, select
:guilabel:`Start`
* Under :menuselection:`Modules --> percepio --> TraceRecorder --> Stream Port`, select
:guilabel:`Ring Buffer`
* Under :menuselection:`Modules --> percepio --> TraceRecorder --> Ring Buffer Config --> Buffer Size`,
set the buffer size in bytes.
The default buffer size can be reduced if you are tight on RAM, or increased if you have RAM to
spare and want longer traces. You may also optimize the Tracing Configuration settings to get
longer traces by filtering out less important events.
In menuconfig, see
:menuselection:`Subsystems and OS Services --> Tracing Support --> Tracing Configuration`.
To view the trace data, the easiest way is to start your debugger (west debug) and run the
following GDB command::
dump binary value trace.bin *RecorderDataPtr
The resulting file is typically found in the root of the build folder, unless a different path is
specified. Open this file in Tracealyzer by selecting :menuselection:`File --> Open --> Open File`.
Tracealyzer Streaming with SEGGER RTT
-------------------------------------
Tracealyzer has built-in support for SEGGER RTT to receive trace data using a J-Link probe.
This allows for recording very long traces. To configure Zephyr for RTT streaming to Tracealyzer,
add the following configuration options in your prj.cnf:
.. code-block:: cfg
CONFIG_TRACING=y
CONFIG_PERCEPIO_TRACERECORDER=y
CONFIG_PERCEPIO_TRC_START_MODE_START_FROM_HOST=y
CONFIG_PERCEPIO_TRC_CFG_STREAM_PORT_RTT=y
CONFIG_PERCEPIO_TRC_CFG_STREAM_PORT_RTT_UP_BUFFER_SIZE=<size in bytes>
Or if using menuconfig:
* Enable :menuselection:`Subsystems and OS Services --> Tracing Support`
* Under :menuselection:`Subsystems and OS Services --> Tracing Support --> Tracing Format`, select
:guilabel:`Percepio Tracealyzer`
* Under :menuselection:`Modules --> percepio --> TraceRecorder --> Recorder Start Mode`, select
:guilabel:`Start From Host`
* Under :menuselection:`Modules --> percepio --> TraceRecorder --> Stream Port`, select
:guilabel:`RTT`
* Under :menuselection:`Modules --> percepio --> TraceRecorder --> RTT Config`, set the size of the
RTT "up" buffer in bytes.
The setting :guilabel:`RTT buffer size up` sets the size of the RTT transmission buffer. This is important
for throughput. By default this buffer is quite large, 5000 bytes, to give decent performance
also on onboard J-Link debuggers (they are not as fast as the stand-alone probes).
If you are tight on RAM, you may consider reducing this setting. If using a regular J-Link probe
it is often sufficient with a much smaller buffer, e.g. 1 KB or less.
Learn more about RTT streaming in the Tracealyzer User Manual.
See Creating and Loading Traces -> Percepio TraceRecorder -> Using TraceRecorder v4.6 or later ->
Stream ports (or search for RTT).
Tracealyzer Streaming with Arm ITM
----------------------------------
This stream port is for Arm Cortex-M devices featuring the ITM unit. It is recommended to use a
fast debug probe that allows for SWO speeds of 10 MHz or higher. To use this stream port,
apply the following configuration options:
.. code-block:: cfg
CONFIG_TRACING=y
CONFIG_PERCEPIO_TRACERECORDER=y
CONFIG_PERCEPIO_TRC_START_MODE_START=y
CONFIG_PERCEPIO_TRC_CFG_STREAM_PORT_ITM=y
CONFIG_PERCEPIO_TRC_CFG_ITM_PORT=1
Or if using menuconfig:
* Enable :menuselection:`Subsystems and OS Services --> Tracing Support`
* Under :menuselection:`Subsystems and OS Services --> Tracing Support --> Tracing Format`, select
:guilabel:`Percepio Tracealyzer`
* Under :menuselection:`Modules --> percepio --> TraceRecorder --> Recorder Start Mode`, select
:guilabel:`Start`
* Under :menuselection:`Modules --> percepio --> TraceRecorder --> Stream Port`, select
:guilabel:`ITM`
* Under :menuselection:`Modules --> percepio --> TraceRecorder --> ITM Config`, set the ITM port to
1.
The main setting for the ITM stream port is the ITM port (0-31). A dedicated channel is needed
for Tracealyzer. Port 0 is usually reserved for printf logging, so channel 1 is used by default.
The option :guilabel:`Use internal buffer` should typically remain disabled. It buffers the data in RAM
before transmission and defers the data transmission to the periodic TzCtrl thread.
The host-side setup depends on what debug probe you are using. Learn more in the Tracealyzer
User Manual.
See :menuselection:`Creating and Loading Traces --> Percepio TraceRecorder --> Using TraceRecorder v4.6 or later --> Stream ports (or search for ITM)`.
Tracealyzer Streaming from QEMU (Semihost)
------------------------------------------
This stream port is designed for Zephyr tracing in QEMU. This can be an easy way to get started
with tracing and try out streaming trace without needing a fast debug probe. The data is streamed
to a host file using semihosting. To use this option, apply the following configuration options:
.. code-block:: cfg
CONFIG_SEMIHOST=y
CONFIG_TRACING=y
CONFIG_PERCEPIO_TRACERECORDER=y
CONFIG_PERCEPIO_TRC_START_MODE_START=y
CONFIG_PERCEPIO_TRC_CFG_STREAM_PORT_ZEPHYR_SEMIHOST=y
Using menuconfig
* Enable :menuselection:`General Architecture Options --> Semihosting support for Arm and RISC-V targets`
* Enable :menuselection:`Subsystems and OS Services --> Tracing Support`
* Under :menuselection:`Subsystems and OS Services --> Tracing Support --> Tracing Format`, select
:guilabel:`Percepio Tracealyzer`
* Under :menuselection:`Modules --> percepio --> TraceRecorder --> Recorder Start Mode`, select
:guilabel:`Start`
* Under :menuselection:`Modules --> percepio --> TraceRecorder --> Stream Port`, select
:guilabel:`Semihost`
By default, the resulting trace file is found in :file:`./trace.psf` in the root of the build folder,
unless a different path is specified. Open this file in `Percepio Tracealyzer`_ by selecting
:menuselection:`File --> Open --> Open File`.
Recorder Start Mode
-------------------
You may have noticed the :guilabel:`Recorder Start Mode` option in the Tracealyzer examples above.
This decides when the tracing starts. With the option :guilabel:`Start`, the tracing begins directly
at startup, once the TraceRecorder library has been initialized. This is recommended when using the
Ring Buffer and Semihost stream ports.
For streaming via RTT or ITM you may also use :guilabel:`Start From Host` or
:guilabel:`Start Await Host`. Both listens for start commands from the Tracealyzer application. The
latter option, :guilabel:`Start Await Host`, causes the TraceRecorder initialization to block until
the start command is received from the Tracealyzer application.
Custom Stream Ports for Tracealyzer
-----------------------------------
The stream ports are small modules within TraceRecorder that define what functions to call to
output the trace data and (optionally) how to read start/stop commands from Tracealyzer.
It is fairly easy to make custom stream ports to implement your own data transport and
Tracealyzer can receive trace streams over various interfaces, including files, sockets,
COM ports, named pipes and more. Note that additional stream port modules are available in the
TraceRecorder repo (e.g. lwIP), although they might require modifications to work with Zephyr.
Learning More
-------------
Learn more about how to get started in the `Tracealyzer Getting Started Guides`_.
.. _Tracealyzer Getting Started Guides: path_to_url
SEGGER SystemView Support
=========================
Zephyr provides built-in support for `SEGGER SystemView`_ that can be enabled in
any application for platforms that have the required hardware support.
The payload and format used with SystemView is custom to the application and
relies on RTT as a transport. Newer versions of SystemView support other
transports, for example UART or using snapshot mode (both still not
supported in Zephyr).
To enable tracing support with `SEGGER SystemView`_ add the configuration option
:kconfig:option:`CONFIG_SEGGER_SYSTEMVIEW` to your project configuration file and set
it to *y*. For example, this can be added to the
:zephyr:code-sample:`synchronization` sample to visualize fast switching between threads.
SystemView can also be used for post-mortem tracing, which can be enabled with
`CONFIG_SEGGER_SYSVIEW_POST_MORTEM_MODE`. In this mode, a debugger can
be attached after the system has crashed using ``west attach`` after which the
latest data from the internal RAM buffer can be loaded into SystemView::
CONFIG_STDOUT_CONSOLE=y
# enable to use thread names
CONFIG_THREAD_NAME=y
CONFIG_SEGGER_SYSTEMVIEW=y
CONFIG_USE_SEGGER_RTT=y
CONFIG_TRACING=y
# enable for post-mortem tracing
CONFIG_SEGGER_SYSVIEW_POST_MORTEM_MODE=n
.. figure:: segger_systemview.png
:align: center
:alt: SEGGER SystemView
:figclass: align-center
:width: 80%
.. _SEGGER SystemView: path_to_url
Recent versions of `SEGGER SystemView`_ come with an API translation table for
Zephyr which is incomplete and does not match the current level of support
available in Zephyr. To use the latest Zephyr API description table, copy the
file available in the tree to your local configuration directory to override the
builtin table::
# On Linux and MacOS
cp $ZEPHYR_BASE/subsys/tracing/sysview/SYSVIEW_Zephyr.txt ~/.config/SEGGER/
TraceCompass
=============
TraceCompass is an open source tool that visualizes CTF events such as thread
scheduling and interrupts, and is helpful to find unintended interactions and
resource conflicts on complex systems.
See also the presentation by Ericsson,
`Advanced Trouble-shooting Of Real-time Systems
<path_to_url`_.
User-Defined Tracing
====================
This tracing format allows the user to define functions to perform any work desired
when a task is switched in or out, when an interrupt is entered or exited, and when the cpu
is idle.
Examples include:
- simple toggling of GPIO for external scope tracing while minimizing extra cpu load
- generating/outputting trace data in a non-standard or proprietary format that can
not be supported by the other tracing systems
The following functions can be defined by the user:
.. code-block:: c
void sys_trace_thread_create_user(struct k_thread *thread);
void sys_trace_thread_abort_user(struct k_thread *thread);
void sys_trace_thread_suspend_user(struct k_thread *thread);
void sys_trace_thread_resume_user(struct k_thread *thread);
void sys_trace_thread_name_set_user(struct k_thread *thread);
void sys_trace_thread_switched_in_user(struct k_thread *thread);
void sys_trace_thread_switched_out_user(struct k_thread *thread);
void sys_trace_thread_info_user(struct k_thread *thread);
void sys_trace_thread_sched_ready_user(struct k_thread *thread);
void sys_trace_thread_pend_user(struct k_thread *thread);
void sys_trace_thread_priority_set_user(struct k_thread *thread, int prio);
void sys_trace_isr_enter_user(int nested_interrupts);
void sys_trace_isr_exit_user(int nested_interrupts);
void sys_trace_idle_user();
Enable this format with the :kconfig:option:`CONFIG_TRACING_USER` option.
Transport Backends
******************
The following backends are currently supported:
* UART
* USB
* File (Using the native port with POSIX architecture based targets)
* RTT (With SystemView)
* RAM (buffer to be retrieved by a debugger)
Using Tracing
*************
The sample :zephyr_file:`samples/subsys/tracing` demonstrates tracing with
different formats and backends.
To get started, the simplest way is to use the CTF format with the :ref:`native_sim <native_sim>`
port, build the sample as follows:
.. zephyr-app-commands::
:tool: all
:app: samples/subsys/tracing
:board: native_sim
:gen-args: -DCONF_FILE=prj_native_ctf.conf
:goals: build
You can then run the resulting binary with the option ``-trace-file`` to generate
the tracing data::
mkdir data
cp $ZEPHYR_BASE/subsys/tracing/ctf/tsdl/metadata data/
./build/zephyr/zephyr.exe -trace-file=data/channel0_0
The resulting CTF output can be visualized using babeltrace or TraceCompass
by pointing the tool to the ``data`` directory with the metadata and trace files.
Using RAM backend
=================
For devices that do not have available I/O for tracing such as USB or UART but have
enough RAM to collect trace data, the ram backend can be enabled with configuration
:kconfig:option:`CONFIG_TRACING_BACKEND_RAM`.
Adjust :kconfig:option:`CONFIG_RAM_TRACING_BUFFER_SIZE` to be able to record enough traces for your needs.
Then thanks to a runtime debugger such as gdb this buffer can be fetched from the target
to an host computer::
(gdb) dump binary memory data/channel0_0 <ram_tracing_start> <ram_tracing_end>
The resulting channel0_0 file have to be placed in a directory with the ``metadata``
file like the other backend.
Future LTTng Inspiration
************************
Currently, the top-layer provided here is quite simple and bare-bones,
and needlessly copied from Zephyr's Segger SystemView debug module.
For an OS like Zephyr, it would make sense to draw inspiration from
Linux's LTTng and change the top-layer to serialize to the same format.
Doing this would enable direct reuse of TraceCompass' canned analyses
for Linux. Alternatively, LTTng-analyses in TraceCompass could be
customized to Zephyr. It is ongoing work to enable TraceCompass
visibility of Zephyr in a target-agnostic and open source way.
I/O Taxonomy
=============
- Atomic Push/Produce/Write/Enqueue:
- synchronous:
means data-transmission has completed with the return of the
call.
- asynchronous:
means data-transmission is pending or ongoing with the return
of the call. Usually, interrupts/callbacks/signals or polling
is used to determine completion.
- buffered:
means data-transmissions are copied and grouped together to
form a larger ones. Usually for amortizing overhead (burst
dequeue) or jitter-mitigation (steady dequeue).
Examples:
- sync unbuffered
E.g. PIO via GPIOs having steady stream, no extra FIFO memory needed.
Low jitter but may be less efficient (can't amortize the overhead of
writing).
- sync buffered
E.g. ``fwrite()`` or enqueuing into FIFO.
Blockingly burst the FIFO when its buffer-waterlevel exceeds threshold.
Jitter due to bursts may lead to missed deadlines.
- async unbuffered
E.g. DMA, or zero-copying in shared memory.
Be careful of data hazards, race conditions, etc!
- async buffered
E.g. enqueuing into FIFO.
- Atomic Pull/Consume/Read/Dequeue:
- synchronous:
means data-reception has completed with the return of the call.
- asynchronous:
means data-reception is pending or ongoing with the return of
the call. Usually, interrupts/callbacks/signals or polling is
used to determine completion.
- buffered:
means data is copied-in in larger chunks than request-size.
Usually for amortizing wait-time.
Examples:
- sync unbuffered
E.g. Blocking read-call, ``fread()`` or SPI-read, zero-copying in shared
memory.
- sync buffered
E.g. Blocking read-call with caching applied.
Makes sense if read pattern exhibits spatial locality.
- async unbuffered
E.g. zero-copying in shared memory.
Be careful of data hazards, race conditions, etc!
- async buffered
E.g. ``aio_read()`` or DMA.
Unfortunately, I/O may not be atomic and may, therefore, require locking.
Locking may not be needed if multiple independent channels are available.
- The system has non-atomic write and one shared channel
E.g. UART. Locking required.
``lock(); emit(a); emit(b); emit(c); release();``
- The system has non-atomic write but many channels
E.g. Multi-UART. Lock-free if the bottom-layer maps each Zephyr
thread+ISR to its own channel, thus alleviating races as each
thread is sequentially consistent with itself.
``emit(a,thread_id); emit(b,thread_id); emit(c,thread_id);``
- The system has atomic write but one shared channel
E.g. ``native_sim`` or board with DMA. May or may not need locking.
``emit(a ## b ## c); /* Concat to buffer */``
``lock(); emit(a); emit(b); emit(c); release(); /* No extra mem */``
- The system has atomic write and many channels
E.g. native_sim or board with multi-channel DMA. Lock-free.
``emit(a ## b ## c, thread_id);``
Object tracking
***************
The kernel can also maintain lists of objects that can be used to track
their usage. Currently, the following lists can be enabled::
struct k_timer *_track_list_k_timer;
struct k_mem_slab *_track_list_k_mem_slab;
struct k_sem *_track_list_k_sem;
struct k_mutex *_track_list_k_mutex;
struct k_stack *_track_list_k_stack;
struct k_msgq *_track_list_k_msgq;
struct k_mbox *_track_list_k_mbox;
struct k_pipe *_track_list_k_pipe;
struct k_queue *_track_list_k_queue;
struct k_event *_track_list_k_event;
Those global variables are the head of each list - they can be traversed
with the help of macro ``SYS_PORT_TRACK_NEXT``. For instance, to traverse
all initialized mutexes, one can write::
struct k_mutex *cur = _track_list_k_mutex;
while (cur != NULL) {
/* Do something */
cur = SYS_PORT_TRACK_NEXT(cur);
}
To enable object tracking, enable :kconfig:option:`CONFIG_TRACING_OBJECT_TRACKING`.
Note that each list can be enabled or disabled via their tracing
configuration. For example, to disable tracking of semaphores, one can
disable :kconfig:option:`CONFIG_TRACING_SEMAPHORE`.
Object tracking is behind tracing configuration as it currently leverages
tracing infrastructure to perform the tracking.
API
***
Common
======
.. doxygengroup:: subsys_tracing_apis
Threads
=======
.. doxygengroup:: subsys_tracing_apis_thread
Work Queues
===========
.. doxygengroup:: subsys_tracing_apis_work
Poll
====
.. doxygengroup:: subsys_tracing_apis_poll
Semaphore
=========
.. doxygengroup:: subsys_tracing_apis_sem
Mutex
=====
.. doxygengroup:: subsys_tracing_apis_mutex
Condition Variables
===================
.. doxygengroup:: subsys_tracing_apis_condvar
Queues
======
.. doxygengroup:: subsys_tracing_apis_queue
FIFO
====
.. doxygengroup:: subsys_tracing_apis_fifo
LIFO
====
.. doxygengroup:: subsys_tracing_apis_lifo
Stacks
======
.. doxygengroup:: subsys_tracing_apis_stack
Message Queues
==============
.. doxygengroup:: subsys_tracing_apis_msgq
Mailbox
=======
.. doxygengroup:: subsys_tracing_apis_mbox
Pipes
======
.. doxygengroup:: subsys_tracing_apis_pipe
Heaps
=====
.. doxygengroup:: subsys_tracing_apis_heap
Memory Slabs
============
.. doxygengroup:: subsys_tracing_apis_mslab
Timers
======
.. doxygengroup:: subsys_tracing_apis_timer
Object tracking
===============
.. doxygengroup:: subsys_tracing_object_tracking
Syscalls
========
.. doxygengroup:: subsys_tracing_apis_syscall
Network tracing
===============
.. doxygengroup:: subsys_tracing_apis_net
Network socket tracing
======================
.. doxygengroup:: subsys_tracing_apis_socket
``` | /content/code_sandbox/doc/services/tracing/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 6,248 |
```restructuredtext
.. _psa_crypto:
PSA Crypto
##########
Overview
********
The PSA (Platform Security Architecture) Crypto API offers a portable
programming interface for cryptographic operations and key storage
across a wide range of hardware. It is designed to be user-friendly
while still providing access to the low-level primitives essential for
modern cryptography.
It is created and maintained by Arm. Arm developed the PSA as a
comprehensive security framework to address the increasing security
needs of connected devices.
In Zephyr, the PSA Crypto API is implemented using Mbed TLS, an
open-source cryptographic library that provides the underlying
cryptographic functions.
Design Goals
************
The interface is suitable for a vast range of devices: from
special-purpose cryptographic processors that process data with a
built-in key, to constrained devices running custom application code,
such as microcontrollers, and multi-application devices, such as
servers. It follows the principle of cryptographic agility.
Algorithm Flexibility
The PSA Crypto API supports a wide range of cryptographic algorithms,
allowing developers to switch between different cryptographic
methods as needed. This flexibility is crucial for maintaining
security as new algorithms emerge and existing ones become obsolete.
Key Management
The PSA Crypto API includes robust key management features that
support the creation, storage, and use of cryptographic keys in a
secure and flexible manner. It uses opaque key identifiers, which
allows for easy key replacement and updates without exposing key
material.
Implementation Independence
The PSA Crypto API abstracts the underlying cryptographic library,
meaning that the specific implementation can be changed without
affecting the application code. This abstraction supports
cryptographic agility by enabling the use of different cryptographic
libraries or hardware accelerators as needed.
Future-Proofing
By adhering to cryptographic agility, PSA Crypto ensures that
applications can quickly adapt to new cryptographic standards and
practices, enhancing long-term security and compliance.
Examples of Applications
************************
Network Security (TLS)
The API provides all of the cryptographic primitives needed to establish TLS connections.
Secure Storage
The API provides all primitives related to storage encryption, block
or file-based, with master encryption keys stored inside a key store.
Network Credentials
The API provides network credential management inside a key store,
for example, for X.509-based authentication or pre-shared keys on
enterprise networks.
Device Pairing
The API provides support for key agreement protocols that are often
used for secure pairing of devices over wireless channels. For
example, the pairing of an NFC token or a Bluetooth device might use
key agreement protocols upon first use.
Secure Boot
The API provides primitives for use during firmware integrity and
authenticity validation, during a secure or trusted boot process.
Attestation
The API provides primitives used in attestation
activities. Attestation is the ability for a device to sign an array
of bytes with a device private key and return the result to the
caller. There are several use cases; ranging from attestation of the
device state, to the ability to generate a key pair and prove that it
has been generated inside a secure key store. The API provides access
to the algorithms commonly used for attestation.
Factory Provisioning
Most IoT devices receive a unique identity during the factory
provisioning process, or once they have been deployed to the
field. This API provides the APIs necessary for populating a device
with keys that represent that identity.
Usage considerations
********************
Always check for errors
Most functions in the PSA Crypto API can return errors. All functions
that can fail have the return type ``psa_status_t``. A few functions
cannot fail, and thus, return void or some other type.
If an error occurs, unless otherwise specified, the content of the
output parameters is undefined and must not be used.
Some common causes of errors include:
* In implementations where the keys are stored and processed in a
separate environment from the application, all functions that need
to access the cryptography processing environment might fail due
to an error in the communication between the two environments.
* If an algorithm is implemented with a hardware accelerator, which
is logically separate from the application processor, the
accelerator might fail, even when the application processor keeps
running normally.
* Most functions might fail due to a lack of resources. However,
some implementations guarantee that certain functions always have
sufficient memory.
* All functions that access persistent keys might fail due to a
storage failure.
* All functions that require randomness might fail due to a lack of
entropy. Implementations are encouraged to seed the random
generator with sufficient entropy during the execution of
``psa_crypto_init()``. However, some security standards require
periodic reseeding from a hardware random generator, which can
fail.
Shared memory and concurrency
Some environments allow applications to be multithreaded, while
others do not. In some environments, applications can share memory
with a different security context. In environments with
multithreaded applications or shared memory, applications must be
written carefully to avoid data corruption or leakage. This
specification requires the application to obey certain constraints.
In general, the PSA Crypto API allows either one writer or any number of
simultaneous readers, on any given object. In other words, if two or
more calls access the same object concurrently, then the behavior is
only well-defined if all the calls are only reading from the object
and do not modify it. Read accesses include reading memory by input
parameters and reading keystore content by using a key. For more
details, refer to `Concurrent calls
<path_to_url#concurrent-calls>`_
If an application shares memory with another security context, it
can pass shared memory blocks as input buffers or output buffers,
but not as non-buffer parameters. For more details, refer to
`Stability of parameters <path_to_url#stability-of-parameters>`_.
Cleaning up after use
To minimize impact if the system is compromised, it is recommended
that applications wipe all sensitive data from memory when it is no
longer used. That way, only data that is currently in use can be
leaked, and past data is not compromised.
Wiping sensitive data includes:
* Clearing temporary buffers in the stack or on the heap.
* Aborting operations if they will not be finished.
* Destroying keys that are no longer used.
References
**********
* `PSA Crypto`_
.. _PSA Crypto:
path_to_url
* `Mbed TLS`_
.. _Mbed TLS:
path_to_url
``` | /content/code_sandbox/doc/services/crypto/psa_crypto.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,425 |
```restructuredtext
.. _cryptography:
Cryptography
############
The crypto section contains information regarding the cryptographic primitives
supported by the Zephyr kernel. Use the information to understand the principles
behind the operation of the different algorithms and how they were implemented.
The following crypto libraries have been included:
.. toctree::
:maxdepth: 1
psa_crypto.rst
random/index.rst
api/index.rst
``` | /content/code_sandbox/doc/services/crypto/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 91 |
```restructuredtext
.. _rtio:
Real Time I/O (RTIO)
####################
.. contents::
:local:
:depth: 2
.. image:: rings.png
:width: 800
:alt: Submissions and Completion Ring Queues
RTIO provides a framework for doing asynchronous operation chains with event
driven I/O. This section covers the RTIO API, queues, executor, iodev,
and common usage patterns with peripheral devices.
RTIO takes a lot of inspiration from Linux's io_uring in its operations and API
as that API matches up well with hardware transfer queues and descriptions such as
DMA transfer lists.
Problem
*******
An application wishing to do complex DMA or interrupt driven operations today
in Zephyr requires direct knowledge of the hardware and how it works. There is
no understanding in the DMA API of other Zephyr devices and how they relate.
This means doing complex audio, video, or sensor streaming requires direct
hardware knowledge or leaky abstractions over DMA controllers. Neither is ideal.
To enable asynchronous operations, especially with DMA, a description of what
to do rather than direct operations through C and callbacks is needed. Enabling
DMA features such as channels with priority, and sequences of transfers requires
more than a simple list of descriptions.
Using DMA and/or interrupt driven I/O shouldn't dictate whether or not the
call is blocking or not.
Inspiration, introducing io_uring
*********************************
It's better not to reinvent the wheel (or ring in this case) and io_uring as an
API from the Linux kernel provides a winning model. In io_uring there are two
lock-free ring buffers acting as queues shared between the kernel and a userland
application. One queue for submission entries which may be chained and flushed to
create concurrent sequential requests. A second queue for completion queue events.
Only a single syscall is actually required to execute many operations, the
io_uring_submit call. This call may block the caller when a number of
operations to wait on is given.
This model maps well to DMA and interrupt driven transfers. A request to do a
sequence of operations in an asynchronous way directly relates
to the way hardware typically works with interrupt driven state machines
potentially involving multiple peripheral IPs like bus and DMA controllers.
Submission Queue
****************
The submission queue (sq), is the description of the operations
to perform in concurrent chains.
For example imagine a typical SPI transfer where you wish to write a
register address to then read from. So the sequence of operations might be...
1. Chip Select
2. Clock Enable
3. Write register address into SPI transmit register
4. Read from the SPI receive register into a buffer
5. Disable clock
6. Disable Chip Select
If anything in this chain of operations fails give up. Some of those operations
can be embodied in a device abstraction that understands a read or write
implicitly means setup the clock and chip select. The transactional nature of
the request also needs to be embodied in some manner. Of the operations above
perhaps the read could be done using DMA as its large enough make sense. That
requires an understanding of how to setup the device's particular DMA to do so.
The above sequence of operations is embodied in RTIO as chain of
submission queue entries (sqe). Chaining is done by setting a bitflag in
an sqe to signify the next sqe must wait on the current one.
Because the chip select and clocking is common to a particular SPI controller
and device on the bus it is embodied in what RTIO calls an iodev.
Multiple operations against the same iodev are done in the order provided as
soon as possible. If two operation chains have varying points using the same
device its possible one chain will have to wait for another to complete.
Completion Queue
****************
In order to know when a sqe has completed there is a completion
queue (cq) with completion queue events (cqe). A sqe once completed results in
a cqe being pushed into the cq. The ordering of cqe may not be the same order of
sqe. A chain of sqe will however ensure ordering and failure cascading.
Other potential schemes are possible but a completion queue is a well trod
idea with io_uring and other similar operating system APIs.
Executor
********
The RTIO executor is a low overhead concurrent I/O task scheduler. It ensures
certain request flags provide the expected behavior. It takes a list of
submissions working through them in order. Various flags allow for changing the
behavior of how submissions are worked through. Flags to form in order chains of
submissions, transactional sets of submissions, or create multi-shot
(continuously producing) requests are all possible!
IO Device
*********
Turning submission queue entries (sqe) into completion queue events (cqe) is the
job of objects implementing the iodev (IO device) API. This API accepts requests
in the form of the iodev submit API call. It is the io devices job to work
through its internal queue of submissions and convert them into completions. In
effect every io device can be viewed as an independent, event driven actor like
object, that accepts a never ending queue of I/O like requests. How the iodev
does this work is up to the author of the iodev, perhaps the entire queue of
operations can be converted to a set of DMA transfer descriptors, meaning the
hardware does almost all of the real work.
Cancellation
************
Canceling an already queued operation is possible but not guaranteed. If the
SQE has not yet started, it's likely that a call to :c:func:`rtio_sqe_cancel`
will remove the SQE and never run it. If, however, the SQE already started
running, the cancel request will be ignored.
Memory pools
************
In some cases requests to read may not know how much data will be produced.
Alternatively, a reader might be handling data from multiple io devices where
the frequency of the data is unpredictable. In these cases it may be wasteful
to bind memory to in flight read requests. Instead with memory pools the memory
to read into is left to the iodev to allocate from a memory pool associated with
the RTIO context that the read was associated with. To create such an RTIO
context the :c:macro:`RTIO_DEFINE_WITH_MEMPOOL` can be used. It allows creating
an RTIO context with a dedicated pool of "memory blocks" which can be consumed by
the iodev. Below is a snippet setting up the RTIO context with a memory pool.
The memory pool has 128 blocks, each block has the size of 16 bytes, and the data
is 4 byte aligned.
.. code-block:: C
#include <zephyr/rtio/rtio.h>
#define SQ_SIZE 4
#define CQ_SIZE 4
#define MEM_BLK_COUNT 128
#define MEM_BLK_SIZE 16
#define MEM_BLK_ALIGN 4
RTIO_DEFINE_WITH_MEMPOOL(rtio_context,
SQ_SIZE, CQ_SIZE, MEM_BLK_COUNT, MEM_BLK_SIZE, MEM_BLK_ALIGN);
When a read is needed, the caller simply needs to replace the call
:c:func:`rtio_sqe_prep_read` (which takes a pointer to a buffer and a length)
with a call to :c:func:`rtio_sqe_prep_read_with_pool`. The iodev requires
only a small change which works with both pre-allocated data buffers as well as
the mempool. When the read is ready, instead of getting the buffers directly
from the :c:struct:`rtio_iodev_sqe`, the iodev should get the buffer and count
by calling :c:func:`rtio_sqe_rx_buf` like so:
.. code-block:: C
uint8_t *buf;
uint32_t buf_len;
int rc = rtio_sqe_rx_buff(iodev_sqe, MIN_BUF_LEN, DESIRED_BUF_LEN, &buf, &buf_len);
if (rc != 0) {
LOG_ERR("Failed to get buffer of at least %u bytes", MIN_BUF_LEN);
return;
}
Finally, the consumer will be able to access the allocated buffer via
:c:func:`rtio_cqe_get_mempool_buffer`.
.. code-block:: C
uint8_t *buf;
uint32_t buf_len;
int rc = rtio_cqe_get_mempool_buffer(&rtio_context, &cqe, &buf, &buf_len);
if (rc != 0) {
LOG_ERR("Failed to get mempool buffer");
return rc;
}
/* Release the cqe events (note that the buffer is not released yet */
rtio_cqe_release_all(&rtio_context);
/* Do something with the memory */
/* Release the mempool buffer */
rtio_release_buffer(&rtio_context, buf);
When to Use
***********
RTIO is useful in cases where concurrent or batch like I/O flows are useful.
From the driver/hardware perspective the API enables batching of I/O requests, potentially in an optimal way.
Many requests to the same SPI peripheral for example might be translated to hardware command queues or DMA transfer
descriptors entirely. Meaning the hardware can potentially do more than ever.
There is a small cost to each RTIO context and iodev. This cost could be weighed
against using a thread for each concurrent I/O operation or custom queues and
threads per peripheral. RTIO is much lower cost than that.
API Reference
*************
.. doxygengroup:: rtio
``` | /content/code_sandbox/doc/services/rtio/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 2,052 |
```restructuredtext
.. _random_api:
Random Number Generation
########################
The random API subsystem provides random number generation APIs in both
cryptographically and non-cryptographically secure instances. Which
random API to use is based on the cryptographic requirements of the
random number. The non-cryptographic APIs will return random values
much faster if non-cryptographic values are needed.
The cryptographically secure random functions shall be compliant to the
FIPS 140-2 [NIST02]_ recommended algorithms. Hardware based random-number
generators (RNG) can be used on platforms with appropriate hardware support.
Platforms without hardware RNG support shall use the `CTR-DRBG algorithm
<path_to_url`_.
The algorithm can be provided by `TinyCrypt <path_to_url`_
or `mbedTLS <path_to_url`_ depending on
your application performance and resource requirements.
.. note::
The CTR-DRBG generator needs an entropy source to establish and
maintain the cryptographic security of the PRNG.
.. _random_kconfig:
Kconfig Options
***************
These options can be found in the following path :zephyr_file:`subsys/random/Kconfig`.
:kconfig:option:`CONFIG_TEST_RANDOM_GENERATOR`
For testing, this option allows a non-random number generator to be used and
permits random number APIs to return values that are not truly random.
The random number generator choice group allows selection of the RNG
source function for the system via the RNG_GENERATOR_CHOICE choice group.
An override of the default value can be specified in the SOC or board
.defconfig file by using:
.. code-block:: none
choice RNG_GENERATOR_CHOICE
default XOSHIRO_RANDOM_GENERATOR
endchoice
The random number generators available include:
:kconfig:option:`CONFIG_TIMER_RANDOM_GENERATOR`
enables number generator based on system timer clock. This number
generator is not random and used for testing only.
:kconfig:option:`CONFIG_ENTROPY_DEVICE_RANDOM_GENERATOR`
enables a random number generator that uses the enabled hardware
entropy gathering driver to generate random numbers.
:kconfig:option:`CONFIG_XOSHIRO_RANDOM_GENERATOR`
enables the Xoshiro128++ pseudo-random number generator, that uses the
entropy driver as a seed source.
The CSPRNG_GENERATOR_CHOICE choice group provides selection of the
cryptographically secure random number generator source function. An
override of the default value can be specified in the SOC or board
.defconfig file by using:
.. code-block:: none
choice CSPRNG_GENERATOR_CHOICE
default CTR_DRBG_CSPRNG_GENERATOR
endchoice
The cryptographically secure random number generators available include:
:kconfig:option:`CONFIG_HARDWARE_DEVICE_CS_GENERATOR`
enables a cryptographically secure random number generator using the
hardware random generator driver
:kconfig:option:`CONFIG_CTR_DRBG_CSPRNG_GENERATOR`
enables the CTR-DRBG pseudo-random number generator. The CTR-DRBG is
a FIPS140-2 recommended cryptographically secure random number generator.
Personalization data can be provided in addition to the entropy source
to make the initialization of the CTR-DRBG as unique as possible.
:kconfig:option:`CONFIG_CS_CTR_DRBG_PERSONALIZATION`
CTR-DRBG Initialization Personalization string
API Reference
*************
.. doxygengroup:: random_api
``` | /content/code_sandbox/doc/services/crypto/random/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 706 |
```restructuredtext
.. _crypto_api:
Crypto APIs
###########
Overview
********
API Reference
*************
Generic API for crypto drivers
==============================
.. doxygengroup:: crypto
Ciphers API
===========
.. doxygengroup:: crypto_cipher
``` | /content/code_sandbox/doc/services/crypto/api/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 52 |
```restructuredtext
.. _storage_reference:
Storage
#######
.. toctree::
:maxdepth: 1
nvs/nvs.rst
disk/access.rst
flash_map/flash_map.rst
fcb/fcb.rst
stream/stream_flash.rst
``` | /content/code_sandbox/doc/services/storage/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 61 |
```restructuredtext
.. _fcb_api:
Flash Circular Buffer (FCB)
###########################
Flash circular buffer provides an abstraction through which you can treat
flash like a FIFO. You append entries to the end, and read data from the
beginning.
.. note::
As of Zephyr release 2.1 the :ref:`NVS <nvs_api>` storage API is
recommended over FCB for use as a back-end for the :ref:`settings API
<settings_api>`.
Description
***********
Entries in the flash contain the length of the entry, the data within
the entry, and checksum over the entry contents.
Storage of entries in flash is done in a FIFO fashion. When you
request space for the next entry, space is located at the end of the
used area. When you start reading, the first entry served is the
oldest entry in flash.
Entries can be appended to the end of the area until storage space is
exhausted. You have control over what happens next; either erase oldest
block of data, thereby freeing up some space, or stop writing new data
until existing data has been collected. FCB treats underlying storage as
an array of flash sectors; when it erases old data, it does this a
sector at a time.
Entries in the flash are checksummed. That is how FCB detects whether
writing entry to flash completed ok. It will skip over entries which
don't have a valid checksum.
Usage
*****
To add an entry to circular buffer:
- Call :c:func:`fcb_append` to get the location where data can be written. If
this fails due to lack of space, you can call :c:func:`fcb_rotate` to erase
the oldest sector which will make the space. And then call
:c:func:`fcb_append` again.
- Use :c:func:`flash_area_write` to write entry contents.
- Call :c:func:`fcb_append_finish` when done. This completes the writing of the
entry by calculating the checksum.
To read contents of the circular buffer:
- Call :c:func:`fcb_walk` with a pointer to your callback function.
- Within callback function copy in data from the entry using
:c:func:`flash_area_read`. You can tell when all data from within a sector
has been read by monitoring the returned entry's area pointer. Then you
can call :c:func:`fcb_rotate`, if you're done with that data.
Alternatively:
- Call :c:func:`fcb_getnext` with 0 in entry offset to get the pointer to
the oldest entry.
- Use :c:func:`flash_area_read` to read entry contents.
- Call :c:func:`fcb_getnext` with pointer to current entry to get the next one.
And so on.
API Reference
*************
The FCB subsystem APIs are provided by ``fcb.h``:
Data structures
===============
.. doxygengroup:: fcb_data_structures
API functions
=============
.. doxygengroup:: fcb_api
``` | /content/code_sandbox/doc/services/storage/fcb/fcb.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 656 |
```restructuredtext
.. _mem_mgmt_api:
Memory Attributes
#################
It is possible in the devicetree to mark the memory regions with attributes by
using the ``zephyr,memory-attr`` property. This property and the related memory
region can then be retrieved at run-time by leveraging a provided helper
library.
The set of general attributes that can be specified in the property are defined
and explained in :zephyr_file:`include/zephyr/dt-bindings/memory-attr/memory-attr.h`.
For example, to mark a memory region in the devicetree as non-volatile, cacheable,
out-of-order:
.. code-block:: devicetree
mem: memory@10000000 {
compatible = "mmio-sram";
reg = <0x10000000 0x1000>;
zephyr,memory-attr = <( DT_MEM_NON_VOLATILE | DT_MEM_CACHEABLE | DT_MEM_OOO )>;
};
.. note::
The ``zephyr,memory-attr`` usage does not result in any memory region
actually created. When it is needed to create an actual section out of the
devicetree defined memory region, it is possible to use the compatible
:dtcompatible:`zephyr,memory-region` that will result (only when supported
by the architecture) in a new linker section and region.
The ``zephyr,memory-attr`` property can also be used to set
architecture-specific and software-specific custom attributes that can be
interpreted at run time. This is leveraged, among other things, to create MPU
regions out of devicetree defined memory regions, for example:
.. code-block:: devicetree
mem: memory@10000000 {
compatible = "mmio-sram";
reg = <0x10000000 0x1000>;
zephyr,memory-region = "NOCACHE_REGION";
zephyr,memory-attr = <( DT_MEM_ARM(ATTR_MPU_RAM_NOCACHE) )>;
};
See :zephyr_file:`include/zephyr/dt-bindings/memory-attr/memory-attr-arm.h` and
:ref:`arm_cortex_m_developer_guide` for more details about MPU usage.
The conventional and recommended way to deal and manage with memory regions
marked with attributes is by using the provided ``mem-attr`` helper library by
enabling :kconfig:option:`CONFIG_MEM_ATTR`. When this option is enabled the
list of memory regions and their attributes are compiled in a user-accessible
array and a set of functions is made available that can be used to query, probe
and act on regions and attributes (see next section for more details).
.. note::
The ``zephyr,memory-attr`` property is only a descriptive property of the
capabilities of the associated memory region, but it does not result in any
actual setting for the memory to be set. The user, code or subsystem willing
to use this information to do some work (for example creating an MPU region
out of the property) must use either the provided ``mem-attr`` library or
the usual devicetree helpers to perform the required work / setting.
A test for the ``mem-attr`` library and its usage is provided in
``tests/subsys/mem_mgmt/mem_attr/``.
Migration guide from `zephyr,memory-region-mpu`
***********************************************
When the ``zephyr,memory-attr`` property was introduced, the
``zephyr,memory-region-mpu`` property was removed and deprecated.
The developers that are still using the deprecated property can move to the new
one by renaming the property and changing its value according to the following list:
.. code-block:: none
"RAM" -> <( DT_ARM_MPU(ATTR_MPU_RAM) )>
"RAM_NOCACHE" -> <( DT_ARM_MPU(ATTR_MPU_RAM_NOCACHE) )>
"FLASH" -> <( DT_ARM_MPU(ATTR_MPU_FLASH) )>
"PPB" -> <( DT_ARM_MPU(ATTR_MPU_PPB) )>
"IO" -> <( DT_ARM_MPU(ATTR_MPU_IO) )>
"EXTMEM" -> <( DT_ARM_MPU(ATTR_MPU_EXTMEM) )>
Memory Attributes Heap Allocator
********************************
It is possible to leverage the memory attribute property ``zephyr,memory-attr``
to define and create a set of memory heaps from which the user can allocate
memory from with certain attributes / capabilities.
When the :kconfig:option:`CONFIG_MEM_ATTR_HEAP` is set, every region marked
with one of the memory attributes listed in
:zephyr_file:`include/zephyr/dt-bindings/memory-attr/memory-attr-sw.h` is added
to a pool of memory heaps used for dynamic allocation of memory buffers with
certain attributes.
Here a non exhaustive list of possible attributes:
.. code-block:: none
DT_MEM_SW_ALLOC_CACHE
DT_MEM_SW_ALLOC_NON_CACHE
DT_MEM_SW_ALLOC_DMA
For example we can define several memory regions with different attributes and
use the appropriate attribute to indicate that it is possible to dynamically
allocate memory from those regions:
.. code-block:: devicetree
mem_cacheable: memory@10000000 {
compatible = "mmio-sram";
reg = <0x10000000 0x1000>;
zephyr,memory-attr = <( DT_MEM_CACHEABLE | DT_MEM_SW_ALLOC_CACHE )>;
};
mem_non_cacheable: memory@20000000 {
compatible = "mmio-sram";
reg = <0x20000000 0x1000>;
zephyr,memory-attr = <( DT_MEM_NON_CACHEABLE | ATTR_SW_ALLOC_NON_CACHE )>;
};
mem_cacheable_big: memory@30000000 {
compatible = "mmio-sram";
reg = <0x30000000 0x10000>;
zephyr,memory-attr = <( DT_MEM_CACHEABLE | DT_MEM_OOO | DT_MEM_SW_ALLOC_CACHE )>;
};
mem_cacheable_dma: memory@40000000 {
compatible = "mmio-sram";
reg = <0x40000000 0x10000>;
zephyr,memory-attr = <( DT_MEM_CACHEABLE | DT_MEM_DMA |
DT_MEM_SW_ALLOC_CACHE | DT_MEM_SW_ALLOC_DMA )>;
};
The user can then dynamically carve memory out of those regions using the
provided functions, the library will take care of allocating memory from the
correct heap depending on the provided attribute and size:
.. code-block:: c
// Init the pool
mem_attr_heap_pool_init();
// Allocate 0x100 bytes of cacheable memory from `mem_cacheable`
block = mem_attr_heap_alloc(DT_MEM_SW_ALLOC_CACHE, 0x100);
// Allocate 0x200 bytes of non-cacheable memory aligned to 32 bytes
// from `mem_non_cacheable`
block = mem_attr_heap_aligned_alloc(ATTR_SW_ALLOC_NON_CACHE, 0x100, 32);
// Allocate 0x100 bytes of cacheable and dma-able memory from `mem_cacheable_dma`
block = mem_attr_heap_alloc(DT_MEM_SW_ALLOC_CACHE | DT_MEM_SW_ALLOC_DMA, 0x100);
When several regions are marked with the same attributes, the memory is allocated:
1. From the regions where the ``zephyr,memory-attr`` property has the requested
property (or properties).
2. Among the regions as at point 1, from the smallest region if there is any
unallocated space left for the requested size
3. If there is not enough space, from the next bigger region able to
accommodate the requested size
The following example shows the point 3:
.. code-block:: c
// This memory is allocated from `mem_non_cacheable`
block = mem_attr_heap_alloc(DT_MEM_SW_ALLOC_NON_CACHE, 0x100);
// This memory is allocated from `mem_cacheable_big`
block = mem_attr_heap_alloc(DT_MEM_SW_ALLOC_CACHE, 0x5000);
.. note::
The framework is assuming that the memory regions used to create the heaps
are usable by the code and available at init time. The user must take of
initializing and setting the memory area before calling
:c:func:`mem_attr_heap_pool_init`.
That means that the region must be correctly configured in terms of MPU /
MMU (if needed) and that an actual heap can be created out of it, for
example by leveraging the ``zephyr,memory-region`` property to create a
proper linker section to accommodate the heap.
API Reference
*************
.. doxygengroup:: memory_attr_interface
.. doxygengroup:: memory_attr_heap
``` | /content/code_sandbox/doc/services/mem_mgmt/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,913 |
```restructuredtext
.. _flash_map_api:
Flash map
#########
The ``<zephyr/storage/flash_map.h>`` API allows accessing information about device
flash partitions via :c:struct:`flash_area` structures.
Each :c:struct:`flash_area` describes a flash partition. The API provides access
to a "flash map", which contains predefined flash areas accessible via globally
unique ID numbers. The map is created from "fixed-partition" compatible entries
in DTS file. Users may also create :c:struct:`flash_area` objects at runtime
for application-specific purposes.
This documentation uses "flash area" when referencing single "fixed-partition"
entities.
The :c:struct:`flash_area` contains a pointer to a :c:struct:`device`,
which can be used to access the flash device an area is placed on directly
with the :ref:`flash API <flash_api>`.
Each flash area is characterized by a device it is placed on, offset
from the beginning of the device and size on the device.
An additional identifier parameter is used by the :c:func:`flash_area_open`
function to find flash area in flash map.
The flash_map.h API provides functions for operating on a :c:struct:`flash_area`.
The main examples are :c:func:`flash_area_read` and :c:func:`flash_area_write`.
These functions are basically wrappers around the flash API with additional
offset and size checks, to limit flash operations to a predefined area.
Most ``<zephyr/storage/flash_map.h>`` API functions require a :c:struct:`flash_area` object pointer
characterizing the flash area they will be working on. There are two possible
methods to obtain such a pointer:
* obtain it using `flash_area_open`;
* defining a :c:struct:`flash_area` type object, which requires providing
a valid :c:struct:`device` object pointer with offset and size of the area
within the flash device.
:c:func:`flash_area_open` uses numeric identifiers to search flash map for
:c:struct:`flash_area` objects and returns, if found, a pointer to an object
representing area with given ID.
The ID number for a flash area can be obtained from a fixed-partition
DTS node label using :c:macro:`FIXED_PARTITION_ID()`; these labels are obtained
from the devicetree as described below.
Relationship with Devicetree
****************************
The flash_map.h API uses data generated from the :ref:`devicetree_api`, in
particular its :ref:`devicetree-flash-api`. Zephyr additionally has some
partitioning conventions used for :ref:`dfu` via the MCUboot bootloader, as
well as defining partitions usable by :ref:`file systems <file_system_api>` or
other nonvolatile :ref:`storage <storage_reference>`.
Here is an example devicetree fragment which uses fixed flash partitions for
both MCUboot and a storage partition. Some details were left out for clarity.
.. literalinclude:: example_fragment.dts
:language: DTS
:start-after: start-after-here
Partition offset shall be expressed in relation to the flash memory beginning
address, to which the partition belongs to.
The ``boot_partition``, ``slot0_partition``, ``slot1_partition``, and
``scratch_partition`` node labels are defined for MCUboot, though not all MCUboot
configurations require all of them to be defined. See the `MCUboot
documentation`_ for more details.
The ``storage_partition`` node is defined for use by a file system or other
nonvolatile storage API.
.. _MCUboot documentation: path_to_url
Numeric flash area ID is obtained by passing DTS node label to
:c:macro:`FIXED_PARTITION_ID()`; for example to obtain ID number
for ``slot0_partition``, user would invoke ``FIXED_PARTITION_ID(slot0_partition)``.
All :code:`FIXED_PARTITION_*` macros take DTS node labels as partition
identifiers.
Users do not have to obtain a :c:struct:`flash_area` object pointer
using :c:func:`flash_map_open` to get information on flash area size, offset
or device, if such area is defined in DTS file. Knowing the DTS node label
of an area, users may use :c:macro:`FIXED_PARTITION_OFFSET()`,
:c:macro:`FIXED_PARTITION_SIZE()` or :c:macro:`FIXED_PARTITION_DEVICE()`
respectively to obtain such information directly from DTS node definition.
For example to obtain offset of ``storage_partition`` it is enough to
invoke ``FIXED_PARTITION_OFFSET(storage_partition)``.
Below example shows how to obtain a :c:struct:`flash_area` object pointer
using :c:func:`flash_area_open` and DTS node label:
.. code-block:: c
const struct flash_area *my_area;
int err = flash_area_open(FIXED_PARTITION_ID(slot0_partition), &my_area);
if (err != 0) {
handle_the_error(err);
} else {
flash_area_read(my_area, ...);
}
API Reference
*************
.. doxygengroup:: flash_area_api
``` | /content/code_sandbox/doc/services/storage/flash_map/flash_map.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,098 |
```unknown
/*
*/
/* start-after-here */
/ {
soc {
flashctrl: flash-controller@deadbeef {
flash0: flash@0 {
compatible = "soc-nv-flash";
reg = <0x0 0x100000>;
partitions {
compatible = "fixed-partitions";
#address-cells = <0x1>;
#size-cells = <0x1>;
boot_partition: partition@0 {
reg = <0x0 0x10000>;
read-only;
};
storage_partition: partition@1e000 {
reg = <0x1e000 0x2000>;
};
slot0_partition: partition@20000 {
reg = <0x20000 0x60000>;
};
slot1_partition: partition@80000 {
reg = <0x80000 0x60000>;
};
scratch_partition: partition@e0000 {
reg = <0xe0000 0x20000>;
};
};
};
};
};
};
``` | /content/code_sandbox/doc/services/storage/flash_map/example_fragment.dts | unknown | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 245 |
```restructuredtext
.. _stream_flash:
Stream Flash
############
The Stream Flash module takes contiguous fragments of a stream of data (e.g.
from radio packets), aggregates them into a user-provided buffer, then when the
buffer fills (or stream ends) writes it to a raw flash partition. It supports
providing the read-back buffer to the client to use in validating the persisted
stream content.
One typical use of a stream write operation is when receiving a new firmware
image to be used in a DFU operation.
There are several reasons why one might want to use buffered writes instead of
writing the data directly as it is made available. Some devices have hardware
limitations which does not allow flash writes to be performed in parallel with
other operations, such as radio RX and TX. Also, fewer write operations result
in faster response times seen from the application.
Persistent stream write progress
********************************
Some stream write operations, such as DFU operations, may run for a long time.
When performing such long running operations it can be useful to be able to save
the stream write progress to persistent storage so that the operation can resume
at the same point after an unexpected interruption.
The Stream Flash module offers an API for loading, saving and clearing stream
write progress to persistent storage using the :ref:`Settings <settings_api>`
module. The API can be enabled using :kconfig:option:`CONFIG_STREAM_FLASH_PROGRESS`.
API Reference
*************
.. doxygengroup:: stream_flash
``` | /content/code_sandbox/doc/services/storage/stream/stream_flash.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 306 |
```restructuredtext
.. _disk_nvme:
NVMe
####
NVMe is a standardized logical device interface on PCIe bus exposing storage devices.
NVMe controllers and disks are supported. Disks can be accessed via the :ref:`Disk Access API <disk_access_api>` they expose
and thus be used through the :ref:`File System API <file_system_api>`.
Driver design
*************
The driver is sliced up in 3 main parts:
- NVMe controller: :zephyr_file:`drivers/disk/nvme/nvme_controller.c`
- NVMe commands: :zephyr_file:`drivers/disk/nvme/nvme_cmd.c`
- NVMe namespace: :zephyr_file:`drivers/disk/nvme/nvme_namespace.c`
Where the NVMe controller is the root of the device driver. This is the one that will get device driver instances.
Note that this is only what DTS describes: the NVMe controller, and none of its namespaces (disks).
The NVMe command is the generic logic used to communicate with the controller and the namespaces it exposes.
Finally the NVMe namespace is the dedicated part to deal with an actual namespace which, in turn, enables applications
accessing each ones through the Disk Access API :zephyr_file:`drivers/disk/nvme/nvme_disk.c`.
If a controller exposes more than 1 namespace (disk), it will be possible to raise the amount of built-in namespace support
by tweaking the configuration option CONFIG_NVME_MAX_NAMESPACES (see below).
Each exposed disk, via it's related disk_info structure, will be distinguished by its name which is inherited from
it's related namespace. As such, the disk name follows NVMe naming which is nvme<k>n<n> where k is the controller number
and n the namespame number. Most of the time, if only one NVMe disk is plugged into the system, one will see 'nvme0n0' as
an exposed disk.
NVMe configuration
******************
DTS
===
Any board exposing an NVMe disk should provide a DTS overlay to enable its use within Zephyr
.. code-block:: devicetree
#include <zephyr/dt-bindings/pcie/pcie.h>
/ {
pcie0 {
nvme0: nvme0 {
compatible = "nvme-controller";
vendor-id = <VENDOR_ID>;
device-id = <DEVICE_ID>;
status = "okay";
};
};
};
Where VENDOR_ID and DEVICE_ID are the ones from the exposed NVMe controller.
Options
=======
* :kconfig:option:`CONFIG_NVME`
Note that NVME requires the target to support PCIe multi-vector MSI-X in order to function.
* :kconfig:option:`CONFIG_NVME_MAX_NAMESPACES`
Important note for users
************************
NVMe specifications mandate the data buffer to be placed in a dword (4 bytes) aligned address.
While this is not a problem for advanced OS managing virtual memory and dynamic allocations
below the user processes, this can become an issue in Zephyr as soon as buffer addresses
map directly to physical memory.
At this stage then, it is up to the user to make sure the buffer address being provided to
:c:func:`disk_access_read` and :c:func:`disk_access_write` are dword aligned.
``` | /content/code_sandbox/doc/services/storage/disk/nvme.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 706 |
```restructuredtext
.. _disk_access_api:
Disk Access
###########
Overview
********
The disk access API provides access to storage devices.
Initializing Disks
******************
Since many disk devices (such as SD cards) are hotpluggable, the disk access
API provides IOCTLs to initialize and de-initialize the disk. They are
as follows:
* :c:macro:`DISK_IOCTL_CTRL_INIT`: Initialize the disk. Must be called before
additional I/O operations can be run on the disk device. Equivalent to
calling the legacy function :c:func:`disk_access_init`.
* :c:macro:`DISK_IOCTL_CTRL_DEINIT`: De-initialize the disk. Once this IOCTL
is issued, the :c:macro:`DISK_IOCTL_CTRL_INIT` must be issued before
the disk can be used for addition I/O operations.
Init/deinit IOCTL calls are balanced, so a disk will not de-initialize until
an equal number of deinit IOCTLs have been issued as init IOCTLs.
It is also possible to force a disk de-initialization by passing a
pointer to a boolean set to ``true`` as a parameter to the
:c:macro:`DISK_IOCTL_CTRL_DEINIT` IOCTL. This is an unsafe operation which
each disk driver may handle differently, but it will always return
a value indicating success.
Note that de-initializing a disk is a low level operation- typically the
de-initialization and initialization calls should be left to the filesystem
implementation, and the user application should not need to manually
de-initialize the disk and can instead call :c:func:`fs_unmount`
SD Card support
***************
Zephyr has support for some SD card controllers and support for interfacing
SD cards via SPI. These drivers use disk driver interface and a file system
can access the SD cards via disk access API.
Both standard and high-capacity SD cards are supported.
.. note:: FAT filesystems are not power safe so the filesystem may become
corrupted if power is lost or if the card is removed without unmounting
the filesystem
SD Memory Card subsystem
========================
Zephyr supports SD memory cards via the disk driver API, or via the SDMMC
subsystem. This subsystem can be used transparently via the disk driver API,
but also supports direct block level access to cards. The SDMMC subsystem
interacts with the :ref:`sd host controller api <sdhc_api>` to communicate
with attached SD cards.
SD Card support via SPI
=======================
Example devicetree fragment below shows how to add SD card node to ``spi1``
interface. Example uses pin ``PA27`` for chip select, and runs the SPI bus
at 24 MHz once the SD card has been initialized:
.. code-block:: devicetree
&spi1 {
status = "okay";
cs-gpios = <&porta 27 GPIO_ACTIVE_LOW>;
sdhc0: sdhc@0 {
compatible = "zephyr,sdhc-spi-slot";
reg = <0>;
status = "okay";
mmc {
compatible = "zephyr,sdmmc-disk";
status = "okay";
};
spi-max-frequency = <24000000>;
};
};
The SD card will be automatically detected and initialized by the
filesystem driver when the board boots.
To read and write files and directories, see the :ref:`file_system_api` in
:zephyr_file:`include/zephyr/fs/fs.h` such as :c:func:`fs_open()`,
:c:func:`fs_read()`, and :c:func:`fs_write()`.
eMMC Device Support
*******************
Zephyr also has support for eMMC devices using the Disk Access API.
MMC in zephyr is implemented using the SD subsystem because the MMC bus
shares a lot of similarity with the SD bus. MMC controllers also use the
SDHC device driver API.
Emulated block device on flash partition support
************************************************
Zephyr flashdisk driver makes it possible to use flash memory partition as
a block device. The flashdisk instances are defined in devicetree:
.. code-block:: devicetree
/ {
msc_disk0 {
compatible = "zephyr,flash-disk";
partition = <&storage_partition>;
disk-name = "NAND";
cache-size = <4096>;
};
};
The cache size specified in :dtcompatible:`zephyr,flash-disk` node should be
equal to backing partition minimum erasable block size.
NVMe disk support
=================
NVMe disks are also supported
.. toctree::
:maxdepth: 1
nvme.rst
Disk Access API Configuration Options
*************************************
Related configuration options:
* :kconfig:option:`CONFIG_DISK_ACCESS`
API Reference
*************
.. doxygengroup:: disk_access_interface
Disk Driver Configuration Options
*********************************
Related driver configuration options:
* :kconfig:option:`CONFIG_DISK_DRIVERS`
Disk Driver Interface
*********************
.. doxygengroup:: disk_driver_interface
``` | /content/code_sandbox/doc/services/storage/disk/access.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,074 |
```restructuredtext
.. _nvs_api:
Non-Volatile Storage (NVS)
##########################
Elements, represented as id-data pairs, are stored in flash using a
FIFO-managed circular buffer. The flash area is divided into sectors. Elements
are appended to a sector until storage space in the sector is exhausted. Then a
new sector in the flash area is prepared for use (erased). Before erasing the
sector it is checked that identifier - data pairs exist in the sectors in use,
if not the id-data pair is copied.
The id is a 16-bit unsigned number. NVS ensures that for each used id there is
at least one id-data pair stored in flash at all time.
NVS allows storage of binary blobs, strings, integers, longs, and any
combination of these.
Each element is stored in flash as metadata (8 byte) and data. The metadata is
written in a table starting from the end of a nvs sector, the data is
written one after the other from the start of the sector. The metadata consists
of: id, data offset in sector, data length, part (unused), and a CRC. This CRC is
only calculated over the metadata and only ensures that a write has been
completed. The actual data of the element can be protected by a different (and optional)
CRC-32. Use the :kconfig:option:`CONFIG_NVS_DATA_CRC` configuration item to enable
the data part CRC.
.. note:: The data CRC is checked only when the whole data of the element is read.
The data CRC is not checked for a partial read, as it is stored at the end of the
element data area.
.. note:: Enabling the data CRC feature on a previously existing NVS content without
data CRC will make all existing data invalid.
A write of data to nvs always starts with writing the data, followed by a write
of the metadata. Data that is written in flash without metadata is ignored
during initialization.
During initialization NVS will verify the data stored in flash, if it
encounters an error it will ignore any data with missing/incorrect metadata.
NVS checks the id-data pair before writing data to flash. If the id-data pair
is unchanged no write to flash is performed.
To protect the flash area against frequent erases it is important that there is
sufficient free space. NVS has a protection mechanism to avoid getting in a
endless loop of flash page erases when there is limited free space. When such
a loop is detected NVS returns that there is no more space available.
For NVS the file system is declared as:
.. code-block:: c
static struct nvs_fs fs = {
.flash_device = NVS_FLASH_DEVICE,
.sector_size = NVS_SECTOR_SIZE,
.sector_count = NVS_SECTOR_COUNT,
.offset = NVS_STORAGE_OFFSET,
};
where
- ``NVS_FLASH_DEVICE`` is a reference to the flash device that will be used. The
device needs to be operational.
- ``NVS_SECTOR_SIZE`` is the sector size, it has to be a multiple of
the flash erase page size and a power of 2.
- ``NVS_SECTOR_COUNT`` is the number of sectors, it is at least 2, one
sector is always kept empty to allow copying of existing data.
- ``NVS_STORAGE_OFFSET`` is the offset of the storage area in flash.
Flash wear
**********
When writing data to flash a study of the flash wear is important. Flash has a
limited life which is determined by the number of times flash can be erased.
Flash is erased one page at a time and the pagesize is determined by the
hardware. As an example a nRF51822 device has a pagesize of 1024 bytes and each
page can be erased about 20,000 times.
Calculating expected device lifetime
====================================
Suppose we use a 4 bytes state variable that is changed every minute and
needs to be restored after reboot. NVS has been defined with a sector_size
equal to the pagesize (1024 bytes) and 2 sectors have been defined.
Each write of the state variable requires 12 bytes of flash storage: 8 bytes
for the metadata and 4 bytes for the data. When storing the data the
first sector will be full after 1024/12 = 85.33 minutes. After another 85.33
minutes, the second sector is full. When this happens, because we're using
only two sectors, the first sector will be used for storage and will be erased
after 171 minutes of system time. With the expected device life of 20,000
writes, with two sectors writing every 171 minutes, the device should last
about 171 * 20,000 minutes, or about 6.5 years.
More generally then, with
- ``NS`` as the number of storage requests per minute,
- ``DS`` as the data size in bytes,
- ``SECTOR_SIZE`` in bytes, and
- ``PAGE_ERASES`` as the number of times the page can be erased,
the expected device life (in minutes) can be calculated as::
SECTOR_COUNT * SECTOR_SIZE * PAGE_ERASES / (NS * (DS+8)) minutes
From this formula it is also clear what to do in case the expected life is too
short: increase ``SECTOR_COUNT`` or ``SECTOR_SIZE``.
Flash write block size migration
********************************
It is possible that during a DFU process, the flash driver used by the NVS
changes the supported minimal write block size.
The NVS in-flash image will stay compatible unless the
physical ATE size changes.
Especially, migration between 1,2,4,8-bytes write block sizes is allowed.
Sample
******
A sample of how NVS can be used is supplied in ``samples/subsys/nvs``.
Troubleshooting
***************
MPU fault while using NVS, or ``-ETIMEDOUT`` error returned
NVS can use the internal flash of the SoC. While the MPU is enabled,
the flash driver requires MPU RWX access to flash memory, configured
using :kconfig:option:`CONFIG_MPU_ALLOW_FLASH_WRITE`. If this option is
disabled, the NVS application will get an MPU fault if it references
the internal SoC flash and it's the only thread running. In a
multi-threaded application, another thread might intercept the fault
and the NVS API will return an ``-ETIMEDOUT`` error.
API Reference
*************
The NVS subsystem APIs are provided by ``nvs.h``:
.. doxygengroup:: nvs_data_structures
.. doxygengroup:: nvs_high_level_api
.. comment
not documenting
.. doxygengroup:: nvs
``` | /content/code_sandbox/doc/services/storage/nvs/nvs.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,454 |
```restructuredtext
.. _modem:
Modem modules
#############
This service provides modules necessary to communicate with modems.
Modems are self-contained devices that implement the hardware and
software necessary to perform RF (Radio-Frequency) communication,
including GNSS, Cellular, WiFi etc.
The modem modules are inter-connected dynamically using
data-in/data-out pipes making them independently testable and
highly flexible, ensuring stability and scalability.
Modem pipe
**********
This module is used to abstract data-in/data-out communication over
a variety of mechanisms, like UART and CMUX DLCI channels, in a
thread-safe manner.
A modem backend will internally contain an instance of a modem_pipe
structure, alongside any buffers and additional structures required
to abstract away its underlying mechanism.
The modem backend will return a pointer to its internal modem_pipe
structure when initialized, which will be used to interact with the
backend through the modem pipe API.
.. doxygengroup:: modem_pipe
Modem PPP
*********
This module defines and binds a L2 PPP network interface, described in
:ref:`net_l2_interface`, to a modem backend. The L2 PPP interface sends
and receives network packets. These network packets have to be wrapped
in PPP frames before being transported via a modem backend. This module
performs said wrapping.
.. doxygengroup:: modem_ppp
Modem CMUX
**********
This module is an implementation of CMUX following the 3GPP 27.010
specification. CMUX is a multiplexing protocol, allowing for multiple
bi-directional streams of data, called DLCI channels. The module
attaches to a single modem backend, exposing multiple modem backends,
each representing a DLCI channel.
.. doxygengroup:: modem_cmux
Modem pipelink
**************
This module is used to share modem pipes globally. This module aims to
decouple the creation and setup of modem pipes in device drivers from
the users of said pipes. See
:zephyr_file:`drivers/modem/modem_at_shell.c` and
:zephyr_file:`drivers/modem/modem_cellular.c` for examples of how to
use the modem pipelink between device driver and application.
.. doxygengroup:: modem_pipelink
``` | /content/code_sandbox/doc/services/modem/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 479 |
```restructuredtext
.. _cmsis_rtos_v2:
CMSIS RTOS v2
##########################
Cortex-M Software Interface Standard (CMSIS) RTOS is a vendor-independent
hardware abstraction layer for the ARM Cortex-M processor series and defines
generic tool interfaces. Though it was originally defined for ARM Cortex-M
microcontrollers alone, it could be easily extended to other microcontrollers
making it generic. For more information on CMSIS RTOS v2, please refer to the
`CMSIS-RTOS2 Documentation <path_to_url`_.
Features not supported in Zephyr implementation
***********************************************
Kernel
``osKernelGetState``, ``osKernelSuspend``, ``osKernelResume``, ``osKernelInitialize``
and ``osKernelStart`` are not supported.
Mutex
``osMutexPrioInherit`` is supported by default and is not configurable,
you cannot select/unselect this attribute.
``osMutexRecursive`` is also supported by default. If this attribute is
not set, an error is thrown when the same thread tries to acquire
it the second time.
``osMutexRobust`` is not supported in Zephyr.
Return values not supported in the Zephyr implementation
********************************************************
``osKernelUnlock``, ``osKernelLock``, ``osKernelRestoreLock``
``osError`` (Unspecified error) is not supported.
``osSemaphoreDelete``
``osErrorResource`` (the semaphore specified by parameter
semaphore_id is in an invalid semaphore state) is not supported.
``osMutexDelete``
``osErrorResource`` (mutex specified by parameter mutex_id
is in an invalid mutex state) is not supported.
``osTimerDelete``
``osErrorResource`` (the timer specified by parameter timer_id
is in an invalid timer state) is not supported.
``osMessageQueueReset``
``osErrorResource`` (the message queue specified by
parameter msgq_id is in an invalid message queue state)
is not supported.
``osMessageQueueDelete``
``osErrorResource`` (the message queue specified by
parameter msgq_id is in an invalid message queue state)
is not supported.
``osMemoryPoolFree``
``osErrorResource`` (the memory pool specified by
parameter mp_id is in an invalid memory pool state) is
not supported.
``osMemoryPoolDelete``
``osErrorResource`` (the memory pool specified by
parameter mp_id is in an invalid memory pool state) is
not supported.
``osEventFlagsSet``, ``osEventFlagsClear``
``osFlagsErrorUnknown`` (Unspecified error)
and osFlagsErrorResource (Event flags object specified by
parameter ef_id is not ready to be used) are not supported.
``osEventFlagsDelete``
``osErrorParameter`` (the value of the parameter ef_id is
incorrect) is not supported.
``osThreadFlagsSet``
``osFlagsErrorUnknown`` (Unspecified error) and
``osFlagsErrorResource`` (Thread specified by parameter
thread_id is not active to receive flags) are not supported.
``osThreadFlagsClear``
``osFlagsErrorResource`` (Running thread is not active to
receive flags) is not supported.
``osDelayUntil``
``osParameter`` (the time cannot be handled) is not supported.
``` | /content/code_sandbox/doc/services/portability/cmsis_rtos_v2.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 706 |
```restructuredtext
.. _osal:
OS Abstraction
##############
OS abstraction layers (OSAL) provide wrapper function APIs that
encapsulate common system functions offered by any operating system.
These APIs make it easier and quicker to develop for, and port code to
multiple software and hardware platforms.
These sections describe the software and hardware abstraction layers
supported by the Zephyr RTOS.
.. toctree::
:maxdepth: 1
posix/index.rst
cmsis_rtos_v1.rst
cmsis_rtos_v2.rst
``` | /content/code_sandbox/doc/services/portability/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 116 |
```restructuredtext
.. _cmsis_rtos_v1:
CMSIS RTOS v1
##########################
Cortex-M Software Interface Standard (CMSIS) RTOS is a vendor-independent
hardware abstraction layer for the ARM Cortex-M processor series and defines
generic tool interfaces. Though it was originally defined for ARM Cortex-M
microcontrollers alone, it could be easily extended to other microcontrollers
making it generic. For more information on CMSIS RTOS v1, please refer
path_to_url
``` | /content/code_sandbox/doc/services/portability/cmsis_rtos_v1.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 99 |
```restructuredtext
.. _posix_support:
POSIX
#####
.. toctree::
:maxdepth: 2
overview/index.rst
conformance/index.rst
aep/index.rst
implementation/index.rst
option_groups/index.rst
kconfig/index.rst
``` | /content/code_sandbox/doc/services/portability/posix/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 64 |
```restructuredtext
.. _posix_overview:
Overview
########
The Portable Operating System Interface (POSIX) is a family of standards specified by the
`IEEE Computer Society`_ for maintaining compatibility between operating systems. Zephyr
implements a subset of the standard POSIX API specified by `IEEE 1003.1-2017`_ (also known as
POSIX-1.2017).
.. figure:: posix.svg
:align: center
:alt: POSIX Support in Zephyr
POSIX support in Zephyr
.. note::
This page does not document Zephyr's :ref:`POSIX architecture<Posix arch>`, which is used to
run Zephyr as a native application under the host operating system for prototyping,
test, and diagnostic purposes.
With the POSIX support available in Zephyr, an existing POSIX conformant
application can be ported to run on the Zephyr kernel, and therefore leverage
Zephyr features and functionality. Additionally, a library designed to be
POSIX conformant can be ported to Zephyr kernel based applications with no changes.
The POSIX API is an increasingly popular OSAL (operating system abstraction layer) for IoT and
embedded applications, as can be seen in Zephyr, AWS:FreeRTOS, TI-RTOS, and NuttX.
Benefits of POSIX support in Zephyr include:
- Offering a familiar API to non-embedded programmers, especially from Linux
- Enabling reuse (portability) of existing libraries based on POSIX APIs
- Providing an efficient API subset appropriate for small (MCU) embedded systems
.. _posix_subprofiles:
POSIX Subprofiles
=================
While Zephyr supports running multiple :ref:`threads <threads_v2>` (possibly in an
:ref:`SMP <smp_arch>` configuration), as well as
:ref:`Virtual Memory and MMUs <memory_management_api>`, Zephyr code and data normally share a
common address space that is partitioned into separate :ref:`Memory Domains <memory_domain>`. The
Zephyr kernel executable code and the application executable code are typically compiled into the
same binary artifact. From that perspective, Zephyr apps can be seen as running in the context of
a single process.
While multi-purpose operating systems (OS) offer full POSIX conformance, Real-Time Operating
Systems (RTOS) such as Zephyr typically serve a fixed-purpose, have limited hardware resources,
and experience limited user interaction. In such systems, full POSIX conformance can be
impractical and unnecessary.
For that reason, POSIX defined the following :ref:`Application Environment Profiles (AEP)<posix_aep>`
as part of `IEEE 1003.13-2003`_ (also known as POSIX.13-2003). Each AEP adds incrementally more
features over the required :ref:`POSIX System Interfaces <posix_system_interfaces>`.
.. figure:: aep.svg
:align: center
:scale: 150%
:alt: POSIX Application Environment Profiles (AEP)
POSIX Application Environment Profiles (AEP)
* Minimal Realtime System Profile (:ref:`PSE51 <posix_aep_pse51>`)
* Realtime Controller System Profile (:ref:`PSE52 <posix_aep_pse52>`)
* Dedicated Realtime System Profile (:ref:`PSE53 <posix_aep_pse53>`)
* Multi-Purpose Realtime System (PSE54)
POSIX.13-2003 AEP were formalized in 2003 via "Units of Functionality" but the specification is now
inactive (for reference only). Nevertheless, the intent is still captured as part of POSIX-1.2017
via :ref:`Options<posix_options>` and :ref:`Option Groups<posix_option_groups>`.
For more information, please see `IEEE 1003.1-2017, Section E, Subprofiling Considerations`_.
.. _posix_apps:
POSIX Applications in Zephyr
============================
A POSIX app in Zephyr is :ref:`built like any other app<application>` and therefore requires the
usual :file:`prj.conf`, :file:`CMakeLists.txt`, and source code. For example, the app below
leverages the ``nanosleep()`` and ``perror()`` POSIX functions.
.. code-block:: cfg
:caption: `prj.conf` for a simple POSIX app in Zephyr
CONFIG_POSIX_API=y
.. code-block:: c
:caption: A simple app that uses Zephyr's POSIX API
#include <stddef.h>
#include <stdio.h>
#include <time.h>
void megasleep(size_t megaseconds)
{
struct timespec ts = {
.tv_sec = megaseconds * 1000000,
.tv_nsec = 0,
};
printf("See you in a while!\n");
if (nanosleep(&ts, NULL) == -1) {
perror("nanosleep");
}
}
int main()
{
megasleep(42);
return 0;
}
For more examples of POSIX applications, please see the :ref:`POSIX sample applications<posix-samples>`.
.. _posix_config:
Configuration
=============
Like most features in Zephyr, POSIX features are
:ref:`highly configurable<zephyr_intro_configurability>` but disabled by default. Users must
explicitly choose to enable POSIX options via :ref:`Kconfig<kconfig>` selection.
Subprofiles
+++++++++++
Enable one of the Kconfig options below to quickly configure a pre-defined
:ref:`POSIX subprofile <posix_subprofiles>`.
* :kconfig:option:`CONFIG_POSIX_AEP_CHOICE_BASE` (:ref:`Base <posix_system_interfaces_required>`)
* :kconfig:option:`CONFIG_POSIX_AEP_CHOICE_PSE51` (:ref:`PSE51 <posix_aep_pse51>`)
* :kconfig:option:`CONFIG_POSIX_AEP_CHOICE_PSE52` (:ref:`PSE52 <posix_aep_pse52>`)
* :kconfig:option:`CONFIG_POSIX_AEP_CHOICE_PSE53` (:ref:`PSE53 <posix_aep_pse53>`)
Additional POSIX :ref:`Options and Option Groups <posix_option_groups>` may be enabled as needed
via Kconfig (e.g. ``CONFIG_POSIX_C_LIB_EXT=y``). Further fine-tuning may be accomplished via
:ref:`additional POSIX-related Kconfig options <posix_kconfig_options>`.
Subprofiles, Options, and Option Groups should be considered the preferred way to configure POSIX
in Zephyr going forward.
Legacy
++++++
Historically, Zephyr used :kconfig:option:`CONFIG_POSIX_API` to configure a set of POSIX features
that was overloaded and always increasing in size.
* :kconfig:option:`CONFIG_POSIX_API`
The option is now frozen, and can be considered equivalent to the following:
* :kconfig:option:`CONFIG_POSIX_AEP_CHOICE_PSE51`
* :kconfig:option:`CONFIG_POSIX_FD_MGMT`
* :kconfig:option:`CONFIG_POSIX_MESSAGE_PASSING`
* :kconfig:option:`CONFIG_POSIX_NETWORKING`
However, :kconfig:option:`CONFIG_POSIX_API` should be considered legacy and should not be used for
new Zephyr applications.
.. _IEEE: path_to_url
.. _IEEE Computer Society: path_to_url
.. _IEEE 1003.1-2017: path_to_url
.. _IEEE 1003.13-2003: path_to_url
.. _IEEE 1003.1-2017, Section E, Subprofiling Considerations:
path_to_url
``` | /content/code_sandbox/doc/services/portability/posix/overview/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,654 |
```restructuredtext
.. _posix_details:
Implementation Details
######################
In many ways, Zephyr provides support like any POSIX OS; API bindings are provided in the C
programming language, POSIX headers are available in the standard include path, when configured.
Unlike other multi-purpose POSIX operating systems
- Zephyr is not "a POSIX OS". The Zephyr kernel was not designed around the POSIX standard, and
POSIX support is an opt-in feature
- Zephyr apps are not linked separately, nor do they execute as subprocesses
- Zephyr, libraries, and application code are compiled and linked together, running similarly to
a single-process application, in a single (possibly virtual) address space
- Zephyr does not provide a POSIX shell, compiler, utilities, and is not self-hosting.
.. note::
Unlike the Linux kernel or FreeBSD, Zephyr does not maintain a static table of system call
numbers for each supported architecture, but instead generates system calls dynamically at
build time. See :ref:`System Calls <syscalls>` for more information.
Design
======
As a library, Zephyr's POSIX API implementation makes an effort to be a thin abstraction layer
between the application, middleware, and the Zephyr kernel.
Some general design considerations:
- The POSIX interface and implementations should be part of Zephyr's POSIX library, and not
elsewhere, unless required both by the POSIX API implementation and some other feature. An
example where the implementation should remain part of the POSIX implementation is
``getopt()``. Examples where the implementation should be part of separate libraries are
multithreading and networking.
- When the POSIX API and another Zephyr subsystem both rely on a feature, the implementation of
that feature should be as a separate Zephyr library that can be used by both the POSIX API and
the other library or subsystem. This reduces the likelihood of dependency cycles in code. When
practical, that rule should expand to include macros. In the example below, ``libposix``
depends on ``libzfoo`` for the implementation of some functionality "foo" in Zephyr. If
``libzfoo`` also depends on ``libposix``, then there is a dependency cycle. The cycle can be
removed via mutual dependency, ``libcommon``.
.. graphviz::
:caption: Dependency cycle between POSIX and another Zephyr library
digraph {
node [shape=rect, style=rounded];
rankdir=LR;
libposix [fillcolor="#d5e8d4"];
libzfoo [fillcolor="#dae8fc"];
libposix -> libzfoo;
libzfoo -> libposix;
}
.. graphviz::
:caption: Mutual dependencies between POSIX and other Zephyr libraries
digraph {
node [shape=rect, style=rounded];
rankdir=LR;
libposix [fillcolor="#d5e8d4"];
libzfoo [fillcolor="#dae8fc"];
libcommon [fillcolor="#f8cecc"];
libposix -> libzfoo;
libposix -> libcommon;
libzfoo -> libcommon;
}
- POSIX API calls should be provided as regular callable C functions; if a Zephyr
:ref:`System Call <syscalls>` is needed as part of the implementation, the declaration and the
implementation of that system call should be hidden behind the POSIX API.
``` | /content/code_sandbox/doc/services/portability/posix/implementation/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 733 |
```restructuredtext
.. _posix_aep:
POSIX Application Environment Profiles (AEP)
############################################
Although inactive, `IEEE 1003.13-2003`_ defined a number of AEP that inspired the modern
subprofiling options of `IEEE 1003.1-2017`_. The single-purpose realtime system profiles
are listed below, for reference, in terms that agree with the current POSIX-1 standard. PSE54
is not considered at this time.
System Interfaces
=================
The required POSIX :ref:`System Interfaces<posix_system_interfaces_required>` are supported for
each Application Environment Profile.
.. figure:: si.svg
:align: center
:scale: 150%
:alt: Required System Interfaces
System Interfaces
.. _posix_aep_pse51:
Minimal Realtime System Profile (PSE51)
=======================================
The *Minimal Realtime System Profile* (PSE51) includes all of the
:ref:`System Interfaces<posix_system_interfaces_required>` along with several additional features.
.. figure:: aep-pse51.svg
:align: center
:scale: 150%
:alt: Minimal Realtime System Profile (PSE51)
Minimal Realtime System Profile (PSE51)
.. Conforming implementations shall define _POSIX_AEP_REALTIME_MINIMAL to the value 200312L
.. csv-table:: PSE51 System Interfaces
:header: Symbol, Support, Remarks
:widths: 50, 10, 50
_POSIX_AEP_REALTIME_MINIMAL, -1, :kconfig:option:`CONFIG_POSIX_AEP_REALTIME_MINIMAL`
.. csv-table:: PSE51 Option Groups
:header: Symbol, Support, Remarks
:widths: 50, 10, 50
:ref:`POSIX_C_LANG_JUMP <posix_option_group_c_lang_jump>`, yes,
:ref:`POSIX_C_LANG_SUPPORT <posix_option_group_c_lang_support>`, yes,
:ref:`POSIX_DEVICE_IO <posix_option_group_device_io>`,, :kconfig:option:`CONFIG_POSIX_DEVICE_IO`
:ref:`POSIX_SIGNALS <posix_option_group_signals>`,, :kconfig:option:`CONFIG_POSIX_SIGNALS`
:ref:`POSIX_SINGLE_PROCESS <posix_option_group_single_process>`, yes, :kconfig:option:`CONFIG_POSIX_SINGLE_PROCESS`
:ref:`XSI_THREADS_EXT <posix_option_group_xsi_threads_ext>`, yes, :kconfig:option:`CONFIG_XSI_THREADS_EXT`
.. csv-table:: PSE51 Option Requirements
:header: Symbol, Support, Remarks
:widths: 50, 10, 50
:ref:`_POSIX_FSYNC <posix_option_fsync>`, 200809L, :kconfig:option:`CONFIG_POSIX_FSYNC`
:ref:`_POSIX_MEMLOCK <posix_option_memlock>`, 200809L, :kconfig:option:`CONFIG_POSIX_MEMLOCK` :ref:`<posix_undefined_behaviour>`
:ref:`_POSIX_MEMLOCK_RANGE <posix_option_memlock_range>`, 200809L, :kconfig:option:`CONFIG_POSIX_MEMLOCK_RANGE`
:ref:`_POSIX_MONOTONIC_CLOCK <posix_option_monotonic_clock>`, 200809L, :kconfig:option:`CONFIG_POSIX_MONOTONIC_CLOCK`
:ref:`_POSIX_SHARED_MEMORY_OBJECTS <posix_shared_memory_objects>`, 200809L, :kconfig:option:`CONFIG_POSIX_SHARED_MEMORY_OBJECTS`
:ref:`_POSIX_SYNCHRONIZED_IO <posix_option_synchronized_io>`, 200809L, :kconfig:option:`CONFIG_POSIX_SYNCHRONIZED_IO`
:ref:`_POSIX_THREAD_ATTR_STACKADDR<posix_option_thread_attr_stackaddr>`, 200809L, :kconfig:option:`CONFIG_POSIX_THREAD_ATTR_STACKADDR`
:ref:`_POSIX_THREAD_ATTR_STACKSIZE<posix_option_thread_attr_stacksize>`, 200809L, :kconfig:option:`CONFIG_POSIX_THREAD_ATTR_STACKSIZE`
:ref:`_POSIX_THREAD_CPUTIME <posix_option_thread_cputime>`, 200809L, :kconfig:option:`CONFIG_POSIX_CPUTIME`
:ref:`_POSIX_THREAD_PRIO_INHERIT <posix_option_thread_prio_inherit>`, 200809L, :kconfig:option:`CONFIG_POSIX_THREAD_PRIO_INHERIT`
:ref:`_POSIX_THREAD_PRIO_PROTECT <posix_option_thread_prio_protect>`, 200809L, :kconfig:option:`CONFIG_POSIX_THREAD_PRIO_PROTECT`
:ref:`_POSIX_THREAD_PRIORITY_SCHEDULING <posix_option_thread_priority_scheduling>`, 200809L, :kconfig:option:`CONFIG_POSIX_THREAD_PRIORITY_SCHEDULING`
_POSIX_THREAD_SPORADIC_SERVER, -1,
.. _posix_aep_pse52:
Realtime Controller System Profile (PSE52)
==========================================
The *Realtime Controller System Profile* (PSE52) includes all features from PSE51 and the
:ref:`System Interfaces<posix_system_interfaces_required>`.
.. figure:: aep-pse52.svg
:align: center
:scale: 150%
:alt: Realtime Controller System Profile (PSE52)
Realtime Controller System Profile (PSE52)
.. Conforming implementations shall define _POSIX_AEP_REALTIME_CONTROLLER to the value 200312L
.. csv-table:: PSE52 System Interfaces
:header: Symbol, Support, Remarks
:widths: 50, 10, 50
_POSIX_AEP_REALTIME_CONTROLLER, -1, :kconfig:option:`CONFIG_POSIX_AEP_REALTIME_CONTROLLER`
.. csv-table:: PSE52 Option Groups
:header: Symbol, Support, Remarks
:widths: 50, 10, 50
:ref:`POSIX_C_LANG_MATH <posix_option_group_c_lang_math>`, yes,
:ref:`POSIX_FD_MGMT <posix_option_group_fd_mgmt>`,, :kconfig:option:`CONFIG_POSIX_FD_MGMT`
:ref:`POSIX_FILE_SYSTEM <posix_option_group_file_system>`,, :kconfig:option:`CONFIG_POSIX_FILE_SYSTEM`
.. csv-table:: PSE52 Option Requirements
:header: Symbol, Support, Remarks
:widths: 50, 10, 50
:ref:`_POSIX_MESSAGE_PASSING <posix_option_message_passing>`, 200809L, :kconfig:option:`CONFIG_POSIX_MESSAGE_PASSING`
_POSIX_TRACE, -1,
_POSIX_TRACE_EVENT_FILTER, -1,
_POSIX_TRACE_LOG, -1,
.. _posix_aep_pse53:
Dedicated Realtime System Profile (PSE53)
=========================================
The *Dedicated Realtime System Profile* (PSE53) includes all features from PSE52, PSE51, and the
:ref:`System Interfaces<posix_system_interfaces_required>`.
.. figure:: aep-pse53.svg
:align: center
:scale: 150%
:alt: Dedicated Realtime System Profile (PSE53)
Dedicated Realtime System Profile (PSE53)
.. Conforming implementations shall define _POSIX_AEP_REALTIME_DEDICATED to the value 200312L
.. csv-table:: PSE53 System Interfaces
:header: Symbol, Support, Remarks
:widths: 50, 10, 50
_POSIX_AEP_REALTIME_DEDICATED, -1, :kconfig:option:`CONFIG_POSIX_AEP_REALTIME_DEDICATED`
.. csv-table:: PSE53 Option Groups
:header: Symbol, Support, Remarks
:widths: 50, 10, 50
:ref:`POSIX_MULTI_PROCESS<posix_option_group_multi_process>`,, :kconfig:option:`CONFIG_POSIX_MULTI_PROCESS`:ref:`<posix_undefined_behaviour>`
:ref:`POSIX_NETWORKING <posix_option_group_networking>`, yes, :kconfig:option:`CONFIG_POSIX_NETWORKING`
:ref:`POSIX_PIPE <posix_option_group_pipe>`,,
:ref:`POSIX_SIGNAL_JUMP <posix_option_group_signal_jump>`,,
.. csv-table:: PSE53 Option Requirements
:header: Symbol, Support, Remarks
:widths: 50, 10, 50
:ref:`_POSIX_CPUTIME <posix_option_cputime>`, 200809L, :kconfig:option:`CONFIG_POSIX_CPUTIME`
_POSIX_PRIORITIZED_IO, -1,
:ref:`_POSIX_PRIORITY_SCHEDULING <posix_option_priority_scheduling>`, -1,
:ref:`_POSIX_RAW_SOCKETS <posix_option_raw_sockets>`, 200809L, :kconfig:option:`CONFIG_POSIX_RAW_SOCKETS`
_POSIX_SPAWN, -1, :ref:`<posix_undefined_behaviour>`
_POSIX_SPORADIC_SERVER, -1, :ref:`<posix_undefined_behaviour>`
.. _IEEE 1003.1-2017: path_to_url
.. _IEEE 1003.13-2003: path_to_url
``` | /content/code_sandbox/doc/services/portability/posix/aep/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 2,027 |
```restructuredtext
.. _logging_api:
Logging
#######
.. contents::
:local:
:depth: 2
The logging API provides a common interface to process messages issued by
developers. Messages are passed through a frontend and are then
processed by active backends.
Custom frontend and backends can be used if needed.
Summary of the logging features:
- Deferred logging reduces the time needed to log a message by shifting time
consuming operations to a known context instead of processing and sending
the log message when called.
- Multiple backends supported (up to 9 backends).
- Custom frontend support. It can work together with backends.
- Compile time filtering on module level.
- Run time filtering independent for each backend.
- Additional run time filtering on module instance level.
- Timestamping with user provided function. Timestamp can have 32 or 64 bits.
- Dedicated API for dumping data.
- Dedicated API for handling transient strings.
- Panic support - in panic mode logging switches to blocking, synchronous
processing.
- Printk support - printk message can be redirected to the logging.
- Design ready for multi-domain/multi-processor system.
- Support for logging floating point variables and long long arguments.
- Built-in copying of transient strings used as arguments.
- Support for multi-domain logging.
Logging API is highly configurable at compile time as well as at run time. Using
Kconfig options (see :ref:`logging_kconfig`) logs can be gradually removed from
compilation to reduce image size and execution time when logs are not needed.
During compilation logs can be filtered out on module basis and severity level.
Logs can also be compiled in but filtered on run time using dedicate API. Run
time filtering is independent for each backend and each source of log messages.
Source of log messages can be a module or specific instance of the module.
There are four severity levels available in the system: error, warning, info
and debug. For each severity level the logging API (:zephyr_file:`include/zephyr/logging/log.h`)
has set of dedicated macros. Logger API also has macros for logging data.
For each level the following set of macros are available:
- ``LOG_X`` for standard printf-like messages, e.g. :c:macro:`LOG_ERR`.
- ``LOG_HEXDUMP_X`` for dumping data, e.g. :c:macro:`LOG_HEXDUMP_WRN`.
- ``LOG_INST_X`` for standard printf-like message associated with the
particular instance, e.g. :c:macro:`LOG_INST_INF`.
- ``LOG_INST_HEXDUMP_X`` for dumping data associated with the particular
instance, e.g. :c:macro:`LOG_INST_HEXDUMP_DBG`
The warning level also exposes the following additional macro:
- :c:macro:`LOG_WRN_ONCE` for warnings where only the first occurrence is of interest.
There are two configuration categories: configurations per module and global
configuration. When logging is enabled globally, it works for modules. However,
modules can disable logging locally. Every module can specify its own logging
level. The module must define the :c:macro:`LOG_LEVEL` macro before using the
API. Unless a global override is set, the module logging level will be honored.
The global override can only increase the logging level. It cannot be used to
lower module logging levels that were previously set higher. It is also possible
to globally limit logs by providing maximal severity level present in the
system, where maximal means lowest severity (e.g. if maximal level in the system
is set to info, it means that errors, warnings and info levels are present but
debug messages are excluded).
Each module which is using the logging must specify its unique name and
register itself to the logging. If module consists of more than one file,
registration is performed in one file but each file must define a module name.
Logger's default frontend is designed to be thread safe and minimizes time needed
to log the message. Time consuming operations like string formatting or access to the
transport are not performed by default when logging API is called. When logging
API is called a message is created and added to the list. Dedicated,
configurable buffer for pool of log messages is used. There are 2 types of messages:
standard and hexdump. Each message contain source ID (module or instance ID and
domain ID which might be used for multiprocessor systems), timestamp and
severity level. Standard message contains pointer to the string and arguments.
Hexdump message contains copied data and string.
.. _logging_kconfig:
Global Kconfig Options
**********************
These options can be found in the following path :zephyr_file:`subsys/logging/Kconfig`.
:kconfig:option:`CONFIG_LOG`: Global switch, turns on/off the logging.
Mode of operations:
:kconfig:option:`CONFIG_LOG_MODE_DEFERRED`: Deferred mode.
:kconfig:option:`CONFIG_LOG_MODE_IMMEDIATE`: Immediate (synchronous) mode.
:kconfig:option:`CONFIG_LOG_MODE_MINIMAL`: Minimal footprint mode.
Filtering options:
:kconfig:option:`CONFIG_LOG_RUNTIME_FILTERING`: Enables runtime reconfiguration of the
filtering.
:kconfig:option:`CONFIG_LOG_DEFAULT_LEVEL`: Default level, sets the logging level
used by modules that are not setting their own logging level.
:kconfig:option:`CONFIG_LOG_OVERRIDE_LEVEL`: It overrides module logging level when
it is not set or set lower than the override value.
:kconfig:option:`CONFIG_LOG_MAX_LEVEL`: Maximal (lowest severity) level which is
compiled in.
Processing options:
:kconfig:option:`CONFIG_LOG_MODE_OVERFLOW`: When new message cannot be allocated,
oldest one are discarded.
:kconfig:option:`CONFIG_LOG_BLOCK_IN_THREAD`: If enabled and new log message cannot
be allocated thread context will block for up to
:kconfig:option:`CONFIG_LOG_BLOCK_IN_THREAD_TIMEOUT_MS` or until log message is
allocated.
:kconfig:option:`CONFIG_LOG_PRINTK`: Redirect printk calls to the logging.
:kconfig:option:`CONFIG_LOG_PROCESS_TRIGGER_THRESHOLD`: When the number of buffered log
messages reaches the threshold, the dedicated thread (see :c:func:`log_thread_set`)
is woken up. If :kconfig:option:`CONFIG_LOG_PROCESS_THREAD` is enabled then this
threshold is used by the internal thread.
:kconfig:option:`CONFIG_LOG_PROCESS_THREAD`: When enabled, logging thread is created
which handles log processing.
:kconfig:option:`CONFIG_LOG_PROCESS_THREAD_STARTUP_DELAY_MS`: Delay in milliseconds
after which logging thread is started.
:kconfig:option:`CONFIG_LOG_BUFFER_SIZE`: Number of bytes dedicated for the circular
packet buffer.
:kconfig:option:`CONFIG_LOG_FRONTEND`: Direct logs to a custom frontend.
:kconfig:option:`CONFIG_LOG_FRONTEND_ONLY`: No backends are used when messages goes to frontend.
:kconfig:option:`CONFIG_LOG_FRONTEND_OPT_API`: Optional API optimized for the most common
simple messages.
:kconfig:option:`CONFIG_LOG_CUSTOM_HEADER`: Injects an application provided header into log.h
:kconfig:option:`CONFIG_LOG_TIMESTAMP_64BIT`: 64 bit timestamp.
:kconfig:option:`CONFIG_LOG_SIMPLE_MSG_OPTIMIZE`: Optimizes simple log messages for size
and performance. Option available only for 32 bit architectures.
Formatting options:
:kconfig:option:`CONFIG_LOG_FUNC_NAME_PREFIX_ERR`: Prepend standard ERROR log messages
with function name. Hexdump messages are not prepended.
:kconfig:option:`CONFIG_LOG_FUNC_NAME_PREFIX_WRN`: Prepend standard WARNING log messages
with function name. Hexdump messages are not prepended.
:kconfig:option:`CONFIG_LOG_FUNC_NAME_PREFIX_INF`: Prepend standard INFO log messages
with function name. Hexdump messages are not prepended.
:kconfig:option:`CONFIG_LOG_FUNC_NAME_PREFIX_DBG`: Prepend standard DEBUG log messages
with function name. Hexdump messages are not prepended.
:kconfig:option:`CONFIG_LOG_BACKEND_SHOW_COLOR`: Enables coloring of errors (red)
and warnings (yellow).
:kconfig:option:`CONFIG_LOG_BACKEND_FORMAT_TIMESTAMP`: If enabled timestamp is
formatted to *hh:mm:ss:mmm,uuu*. Otherwise is printed in raw format.
Backend options:
:kconfig:option:`CONFIG_LOG_BACKEND_UART`: Enabled built-in UART backend.
.. _log_usage:
Usage
*****
Logging in a module
===================
In order to use logging in the module, a unique name of a module must be
specified and module must be registered using :c:macro:`LOG_MODULE_REGISTER`.
Optionally, a compile time log level for the module can be specified as the
second parameter. Default log level (:kconfig:option:`CONFIG_LOG_DEFAULT_LEVEL`) is used
if custom log level is not provided.
.. code-block:: c
#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(foo, CONFIG_FOO_LOG_LEVEL);
If the module consists of multiple files, then ``LOG_MODULE_REGISTER()`` should
appear in exactly one of them. Each other file should use
:c:macro:`LOG_MODULE_DECLARE` to declare its membership in the module.
Optionally, a compile time log level for the module can be specified as
the second parameter. Default log level (:kconfig:option:`CONFIG_LOG_DEFAULT_LEVEL`)
is used if custom log level is not provided.
.. code-block:: c
#include <zephyr/logging/log.h>
/* In all files comprising the module but one */
LOG_MODULE_DECLARE(foo, CONFIG_FOO_LOG_LEVEL);
In order to use logging API in a function implemented in a header file
:c:macro:`LOG_MODULE_DECLARE` macro must be used in the function body
before logging API is called. Optionally, a compile time log level for the module
can be specified as the second parameter. Default log level
(:kconfig:option:`CONFIG_LOG_DEFAULT_LEVEL`) is used if custom log level is not
provided.
.. code-block:: c
#include <zephyr/logging/log.h>
static inline void foo(void)
{
LOG_MODULE_DECLARE(foo, CONFIG_FOO_LOG_LEVEL);
LOG_INF("foo");
}
Dedicated Kconfig template (:zephyr_file:`subsys/logging/Kconfig.template.log_config`)
can be used to create local log level configuration.
Example below presents usage of the template. As a result CONFIG_FOO_LOG_LEVEL
will be generated:
.. code-block:: none
module = FOO
module-str = foo
source "subsys/logging/Kconfig.template.log_config"
Logging in a module instance
============================
In case of modules which are multi-instance and instances are widely used
across the system enabling logs will lead to flooding. The logger provides the tools
which can be used to provide filtering on instance level rather than module
level. In that case logging can be enabled for particular instance.
In order to use instance level filtering following steps must be performed:
- a pointer to specific logging structure is declared in instance structure.
:c:macro:`LOG_INSTANCE_PTR_DECLARE` is used for that.
.. code-block:: c
#include <zephyr/logging/log_instance.h>
struct foo_object {
LOG_INSTANCE_PTR_DECLARE(log);
uint32_t id;
}
- module must provide macro for instantiation. In that macro, logging instance
is registered and log instance pointer is initialized in the object structure.
.. code-block:: c
#define FOO_OBJECT_DEFINE(_name) \
LOG_INSTANCE_REGISTER(foo, _name, CONFIG_FOO_LOG_LEVEL) \
struct foo_object _name = { \
LOG_INSTANCE_PTR_INIT(log, foo, _name) \
}
Note that when logging is disabled logging instance and pointer to that instance
are not created.
In order to use the instance logging API in a source file, a compile-time log
level must be set using :c:macro:`LOG_LEVEL_SET`.
.. code-block:: c
LOG_LEVEL_SET(CONFIG_FOO_LOG_LEVEL);
void foo_init(foo_object *f)
{
LOG_INST_INF(f->log, "Initialized.");
}
In order to use the instance logging API in a header file, a compile-time log
level must be set using :c:macro:`LOG_LEVEL_SET`.
.. code-block:: c
static inline void foo_init(foo_object *f)
{
LOG_LEVEL_SET(CONFIG_FOO_LOG_LEVEL);
LOG_INST_INF(f->log, "Initialized.");
}
Controlling the logging
=======================
By default, logging processing in deferred mode is handled internally by the
dedicated task which starts automatically. However, it might not be available
if multithreading is disabled. It can also be disabled by unsetting
:kconfig:option:`CONFIG_LOG_PROCESS_TRIGGER_THRESHOLD`. In that case, logging can
be controlled using the API defined in :zephyr_file:`include/zephyr/logging/log_ctrl.h`.
Logging must be initialized before it can be used. Optionally, the user can provide
a function which returns the timestamp value. If not provided, :c:macro:`k_cycle_get`
or :c:macro:`k_cycle_get_32` is used for timestamping.
The :c:func:`log_process` function is used to trigger processing of one log
message (if pending), and returns true if there are more messages pending.
However, it is recommended to use macro wrappers (:c:macro:`LOG_INIT` and
:c:macro:`LOG_PROCESS`) which handle the case where logging is disabled.
The following snippet shows how logging can be processed in simple forever loop.
.. code-block:: c
#include <zephyr/logging/log_ctrl.h>
int main(void)
{
LOG_INIT();
/* If multithreading is enabled provide thread id to the logging. */
log_thread_set(k_current_get());
while (1) {
if (LOG_PROCESS() == false) {
/* sleep */
}
}
}
If logs are processed from a thread (user or internal) then it is possible to enable
a feature which will wake up processing thread when certain amount of log messages are
buffered (see :kconfig:option:`CONFIG_LOG_PROCESS_TRIGGER_THRESHOLD`).
.. _logging_panic:
Logging panic
*************
In case of error condition system usually can no longer rely on scheduler or
interrupts. In that situation deferred log message processing is not an option.
Logger controlling API provides a function for entering into panic mode
(:c:func:`log_panic`) which should be called in such situation.
When :c:func:`log_panic` is called, _panic_ notification is sent to all active
backends. Once all backends are notified, all buffered messages are flushed. Since
that moment all logs are processed in a blocking way.
.. _logging_printk:
Printk
******
Typically, logging and :c:func:`printk` use the same output, which they compete
for. This can lead to issues if the output does not support preemption but it may
also result in corrupted output because logging data is interleaved with printk
data. However, it is possible to redirect printk messages to the
logging subsystem by enabling :kconfig:option:`CONFIG_LOG_PRINTK`. In that case,
printk entries are treated as log messages with level 0 (they cannot be disabled).
When enabled, logging manages the output so there is no interleaving. However,
in deferred mode the printk behaviour is changed since the output is delayed
until the logging thread processes the data. :kconfig:option:`CONFIG_LOG_PRINTK`
is enabled by default.
.. _log_architecture:
Architecture
************
Logging consists of 3 main parts:
- Frontend
- Core
- Backends
Log message is generated by a source of logging which can be a module or
instance of a module.
Default Frontend
================
Default frontend is engaged when the logging API is called in a source of logging (e.g.
:c:macro:`LOG_INF`) and is responsible for filtering a message (compile and run
time), allocating a buffer for the message, creating the message and committing that
message. Since the logging API can be called in an interrupt, the frontend is optimized
to log the message as fast as possible.
Log message
-----------
A log message contains a message descriptor (source, domain and level), timestamp,
formatted string details (see :ref:`cbprintf_packaging`) and optional data.
Log messages are stored in a continuous block of memory.
Memory is allocated from a circular packet buffer (:ref:`mpsc_pbuf`), which has
a few consequences:
* Each message is a self-contained, continuous block of memory thus it is suited
for copying the message (e.g. for offline processing).
* Messages must be sequentially freed. Backend processing is synchronous. Backend
can make a copy for deferred processing.
A log message has following format:
+------------------+----------------------------------------------------+
| Message Header | 2 bits: MPSC packet buffer header |
| +----------------------------------------------------+
| | 1 bit: Trace/Log message flag |
| +----------------------------------------------------+
| | 3 bits: Domain ID |
| +----------------------------------------------------+
| | 3 bits: Level |
| +----------------------------------------------------+
| | 10 bits: Cbprintf Package Length |
| +----------------------------------------------------+
| | 12 bits: Data length |
| +----------------------------------------------------+
| | 1 bit: Reserved |
| +----------------------------------------------------+
| | pointer: Pointer to the source descriptor [#l0]_ |
| +----------------------------------------------------+
| | 32 or 64 bits: Timestamp [#l0]_ |
| +----------------------------------------------------+
| | Optional padding [#l1]_ |
+------------------+----------------------------------------------------+
| Cbprintf | Header |
| +----------------------------------------------------+
| | package | Arguments |
| | (optional) +----------------------------------------------------+
| | Appended strings |
+------------------+----------------------------------------------------+
| Hexdump data (optional) |
+------------------+----------------------------------------------------+
| Alignment padding (optional) |
+------------------+----------------------------------------------------+
.. rubric:: Footnotes
.. [#l0] Depending on the platform and the timestamp size fields may be swapped.
.. [#l1] It may be required for cbprintf package alignment
Log message allocation
----------------------
It may happen that the frontend cannot allocate a message. This happens if the
system is generating more log messages than it can process in certain time
frame. There are two strategies to handle that case:
- No overflow - the new log is dropped if space for a message cannot be allocated.
- Overflow - the oldest pending messages are freed, until the new message can be
allocated. Enabled by :kconfig:option:`CONFIG_LOG_MODE_OVERFLOW`. Note that it degrades
performance thus it is recommended to adjust buffer size and amount of enabled
logs to limit dropping.
.. _logging_runtime_filtering:
Run-time filtering
------------------
If run-time filtering is enabled, then for each source of logging a filter
structure in RAM is declared. Such filter is using 32 bits divided into ten 3
bit slots. Except *slot 0*, each slot stores current filter for one backend in
the system. *Slot 0* (bits 0-2) is used to aggregate maximal filter setting for
given source of logging. Aggregate slot determines if log message is created
for given entry since it indicates if there is at least one backend expecting
that log entry. Backend slots are examined when message is processed by the core
to determine if message is accepted by the given backend. Contrary to compile
time filtering, binary footprint is increased because logs are compiled in.
In the example below backend 1 is set to receive errors (*slot 1*) and backend
2 up to info level (*slot 2*). Slots 3-9 are not used. Aggregated filter
(*slot 0*) is set to info level and up to this level message from that
particular source will be buffered.
+------+------+------+------+-----+------+
|slot 0|slot 1|slot 2|slot 3| ... |slot 9|
+------+------+------+------+-----+------+
| INF | ERR | INF | OFF | ... | OFF |
+------+------+------+------+-----+------+
Custom Frontend
===============
Custom frontend is enabled using :kconfig:option:`CONFIG_LOG_FRONTEND`. Logs are directed
to functions declared in :zephyr_file:`include/zephyr/logging/log_frontend.h`.
If option :kconfig:option:`CONFIG_LOG_FRONTEND_ONLY` is enabled then log message is not
created and no backend is handled. Otherwise, custom frontend can coexist with
backends.
In some cases, logs need to be redirected at the macro level. For these cases,
:kconfig:option:`CONFIG_LOG_CUSTOM_HEADER` can be used to inject an application provided
header named `zephyr_custom_log.h` at the end of :zephyr_file:`include/zephyr/logging/log.h`.
.. _logging_strings:
Logging strings
===============
String arguments are handled by :ref:`cbprintf_packaging`. See
:ref:`cbprintf_packaging_limitations` for limitations and recommendations.
Multi-domain support
====================
More complex systems can consist of multiple domains where each domain is an
independent binary. Examples of domains are a core in a multicore SoC or one
of the binaries (Secure or Nonsecure) on an ARM TrustZone core.
Tracing and debugging on a multi-domain system is more complex and requires an efficient logging
system. Two approaches can be used to structure this logging system:
* Log inside each domain independently.
This option is not always possible as it requires that each domain has an available backend
(for example, UART). This approach can also be troublesome to use and not scalable,
as logs are presented on independent outputs.
* Use a multi-domain logging system where log messages from each domain end up in one root domain,
where they are processed exactly as in a single domain case.
In this approach, log messages are passed between domains using a connection between domains
created from the backend on one side and linked to the other.
The Log link is an interface introduced in this multi-domain approach. The Log link is
responsible for receiving any log message from another domain, creating a copy, and
putting that local log message copy (including remote data) into the message queue.
This specific log link implementation matches the complementary backend implementation
to allow log messages exchange and logger control like configuring filtering, getting log
source names, and so on.
There are three types of domains in a multi-domain system:
* The *end domain* has the logging core implementation and a cross-domain
backend. It can also have other backends in parallel.
* The *relay domain* has one or more links to other domains but does not
have backends that output logs to the user. It has a cross-domain backend either to
another relay or to the root domain.
* The *root domain* has one or multiple links and a backend that outputs logs
to the user.
See the following image for an example of a multi-domain setup:
.. figure:: images/multidomain.png
Multi-domain example
In this architecture, a link can handle multiple domains.
For example, let's consider an SoC with two ARM Cortex-M33 cores with TrustZone: cores A and B (see
the example illustrated above). There are four domains in the system, as
each core has both a Secure and a Nonsecure domain. If *core A nonsecure* (A_NS) is the
root domain, it has two links: one to *core A secure* (A_NS-A_S) and one to
*core B nonsecure* (A_NS-B_NS). *B_NS* domain has one link, to *core B secure*
*B_NS-B_S*), and a backend to *A_NS*.
Since in all instances there is a standard logging subsystem, it is always possible
to have multiple backends and simultaneously output messages to them. An example of this is shown
in the illustration above as a dotted UART backend on the *B_NS* domain.
Domain ID
---------
The source of each log message can be identified by the following fields in the header:
``source_id`` and ``domain_id``.
The value assigned to the ``domain_id`` is relative. Whenever a domain creates a log message,
it sets its ``domain_id`` to ``0``.
When a message crosses the domain, ``domain_id`` changes as it is increased by the link offset.
The link offset is assigned during the initialization, where the logger core is iterating
over all the registered links and assigned offsets.
The first link has the offset set to 1.
The following offset equals the previous link offset plus the number of domains in the previous
link.
The following example is shown below, where
the assigned ``domain_ids`` are shown for each domain:
.. figure:: images/domain_ids.png
Domain IDs assigning example
Let's consider a log message created on the *B_S* domain:
1. Initially, it has its ``domain_id`` set to ``0``.
#. When the *B_NS-B_S* link receives the message, it increases the ``domain_id``
to ``1`` by adding the *B_NS-B_S* offset.
#. The message is passed to *A_NS*.
#. When the *A_NS-B_NS* link receives the message, it adds the offset (``2``) to the ``domain_id``.
The message ends up with the ``domain_id`` set to ``3``, which uniquely identifies the message
originator.
Cross-domain log message
------------------------
In most cases, the address space of each domain is unique, and one domain
cannot access directly the data in another domain. For this reason, the backend can
partially process the message before it is passed to another domain. Partial
processing can include converting a string package to a *fully self-contained*
version (copying read-only strings to the package body).
Each domain can have a different timestamp source in terms of frequency and
offset. Logging does not perform any timestamp conversion.
Runtime filtering
-----------------
In the single-domain case, each log source has a dedicated variable with runtime
filtering for each backend in the system. In the multi-domain case, the originator of
the log message is not aware of the number of backends in the root domain.
As such, to filter logs in multiple domains, each source requires a runtime
filtering setting in each domain on the way to the root domain. As the number of
sources in other domains is not known during the compilation, the runtime filtering
of remote sources must use dynamically allocated memory (one word per
source). When a backend in the root domain changes the filtering of the module from a
remote domain, the local filter is updated. After the update, the aggregated
filter (the maximum from all the local backends) is checked and, if changed, the remote domain is
informed about this change. With this approach, the runtime filtering works identically
in both multi-domain and single-domain scenarios.
Message ordering
----------------
Logging does not provide any mechanism for synchronizing timestamps across multiple
domains:
* If domains have different timestamp sources, messages will be
processed in the order of arrival to the buffer in the root domain.
* If domains have the same timestamp source or if there is an out-of-bound mechanism that
recalculates timestamps, there are 2 options:
* Messages are processed as they arrive in the buffer in the root domain.
Messages are unordered but they can be sorted by the host as the timestamp
indicates the time of the message generation.
* Links have dedicated buffers. During processing, the head of each buffer is checked
and the oldest message is processed first.
With this approach, it is possible to maintain the order of the messages at the cost
of a suboptimal memory utilization (since the buffer is not shared) and increased processing
latency (see :kconfig:option:`CONFIG_LOG_PROCESSING_LATENCY_US`).
Logging backends
================
Logging backends are registered using :c:macro:`LOG_BACKEND_DEFINE`. The macro
creates an instance in the dedicated memory section. Backends can be dynamically
enabled (:c:func:`log_backend_enable`) and disabled. When
:ref:`logging_runtime_filtering` is enabled, :c:func:`log_filter_set` can be used
to dynamically change filtering of a module logs for given backend. Module is
identified by source ID and domain ID. Source ID can be retrieved if source name
is known by iterating through all registered sources.
Logging supports up to 9 concurrent backends. Log message is passed to the
each backend in processing phase. Additionally, backend is notified when logging
enter panic mode with :c:func:`log_backend_panic`. On that call backend should
switch to synchronous, interrupt-less operation or shut down itself if that is
not supported. Occasionally, logging may inform backend about number of dropped
messages with :c:func:`log_backend_dropped`. Message processing API is version
specific.
:c:func:`log_backend_msg_process` is used for processing message. It is common for
standard and hexdump messages because log message hold string with arguments
and data. It is also common for deferred and immediate logging.
Message formatting
------------------
Logging provides set of function that can be used by the backend to format a
message. Helper functions are available in :zephyr_file:`include/zephyr/logging/log_output.h`.
Example message formatted using :c:func:`log_output_msg_process`.
.. code-block:: console
[00:00:00.000,274] <info> sample_instance.inst1: logging message
.. _logging_guide_dictionary:
Dictionary-based Logging
========================
Dictionary-based logging, instead of human readable texts, outputs the log
messages in binary format. This binary format encodes arguments to formatted
strings in their native storage formats which can be more compact than their
text equivalents. For statically defined strings (including the format
strings and any string arguments), references to the ELF file are encoded
instead of the whole strings. A dictionary created at build time contains
the mappings between these references and the actual strings. This allows
the offline parser to obtain the strings from the dictionary to parse
the log messages. This binary format allows a more compact representation
of log messages in certain scenarios. However, this requires the use of
an offline parser and is not as intuitive to use as text-based log messages.
Note that ``long double`` is not supported by Python's ``struct`` module.
Therefore, log messages with ``long double`` will not display the correct
values.
Configuration
-------------
Here are kconfig options related to dictionary-based logging:
- :kconfig:option:`CONFIG_LOG_DICTIONARY_SUPPORT` enables dictionary-based logging
support. This should be selected by the backends which require it.
- The UART backend can be used for dictionary-based logging. These are
additional config for the UART backend:
- :kconfig:option:`CONFIG_LOG_BACKEND_UART_OUTPUT_DICTIONARY_HEX` tells
the UART backend to output hexadecimal characters for dictionary based
logging. This is useful when the log data needs to be captured manually
via terminals and consoles.
- :kconfig:option:`CONFIG_LOG_BACKEND_UART_OUTPUT_DICTIONARY_BIN` tells
the UART backend to output binary data.
Usage
-----
When dictionary-based logging is enabled via enabling related logging backends,
a JSON database file, named :file:`log_dictionary.json`, will be created
in the build directory. This database file contains information for the parser
to correctly parse the log data. Note that this database file only works
with the same build, and cannot be used for any other builds.
To use the log parser:
.. code-block:: console
./scripts/logging/dictionary/log_parser.py <build dir>/log_dictionary.json <log data file>
The parser takes two required arguments, where the first one is the full path
to the JSON database file, and the second part is the file containing log data.
Add an optional argument ``--hex`` to the end if the log data file contains
hexadecimal characters
(e.g. when ``CONFIG_LOG_BACKEND_UART_OUTPUT_DICTIONARY_HEX=y``). This tells
the parser to convert the hexadecimal characters to binary before parsing.
Please refer to the :zephyr:code-sample:`logging-dictionary` sample to learn more on how to use
the log parser.
Recommendations
***************
The are following recommendations:
* Enable :kconfig:option:`CONFIG_LOG_SPEED` to slightly speed up deferred logging at the
cost of slight increase in memory footprint.
* Compiler with C11 ``_Generic`` keyword support is recommended. Logging
performance is significantly degraded without it. See :ref:`cbprintf_packaging`.
* It is recommended to cast pointer to ``const char *`` when it is used with ``%s``
format specifier and it points to a constant string.
* It is recommended to cast pointer to ``char *`` when it is used with ``%s``
format specifier and it points to a transient string.
* It is recommended to cast character pointer to non character pointer
(e.g., ``void *``) when it is used with ``%p`` format specifier.
.. code-block:: c
LOG_WRN("%s", str);
LOG_WRN("%p", (void *)str);
Benchmark
*********
Benchmark numbers from :zephyr_file:`tests/subsys/logging/log_benchmark` performed
on ``qemu_x86``. It is a rough comparison to give a general overview.
+--------------------------------------------+------------------+
| Feature | |
+============================================+==================+
| Kernel logging | 7us [#f0]_/11us |
| | |
+--------------------------------------------+------------------+
| User logging | 13us |
| | |
+--------------------------------------------+------------------+
| kernel logging with overwrite | 10us [#f0]_/15us |
+--------------------------------------------+------------------+
| Logging transient string | 42us |
+--------------------------------------------+------------------+
| Logging transient string from user | 50us |
+--------------------------------------------+------------------+
| Memory utilization [#f1]_ | 518 |
| | |
+--------------------------------------------+------------------+
| Memory footprint (test) [#f2]_ | 2k |
+--------------------------------------------+------------------+
| Memory footprint (application) [#f3]_ | 3.5k |
+--------------------------------------------+------------------+
| Message footprint [#f4]_ | 47 [#f0]_/32 |
| | bytes |
+--------------------------------------------+------------------+
.. rubric:: Benchmark details
.. [#f0] :kconfig:option:`CONFIG_LOG_SPEED` enabled.
.. [#f1] Number of log messages with various number of arguments that fits in 2048
bytes dedicated for logging.
.. [#f2] Logging subsystem memory footprint in :zephyr_file:`tests/subsys/logging/log_benchmark`
where filtering and formatting features are not used.
.. [#f3] Logging subsystem memory footprint in :zephyr_file:`samples/subsys/logging/logger`.
.. [#f4] Average size of a log message (excluding string) with 2 arguments on ``Cortex M3``
Stack usage
***********
When logging is enabled it impacts stack usage of the context that uses logging API. If stack
is optimized it may lead to stack overflow. Stack usage depends on mode and optimization. It
also significantly varies between platforms. In general, when :kconfig:option:`CONFIG_LOG_MODE_DEFERRED`
is used stack usage is smaller since logging is limited to creating and storing log message.
When :kconfig:option:`CONFIG_LOG_MODE_IMMEDIATE` is used then log message is processed by the backend
which includes string formatting. In case of that mode, stack usage will depend on which backends
are used.
:zephyr_file:`tests/subsys/logging/log_stack` test is used to characterize stack usage depending
on mode, optimization and platform used. Test is using only the default backend.
Some of the platforms characterization for log message with two ``integer`` arguments listed below:
+---------------+----------+----------------------------+-----------+-----------------------------+
| Platform | Deferred | Deferred (no optimization) | Immediate | Immediate (no optimization) |
+===============+==========+============================+===========+=============================+
| ARM Cortex-M3 | 40 | 152 | 412 | 783 |
+---------------+----------+----------------------------+-----------+-----------------------------+
| x86 | 12 | 224 | 388 | 796 |
+---------------+----------+----------------------------+-----------+-----------------------------+
| riscv32 | 24 | 208 | 456 | 844 |
+---------------+----------+----------------------------+-----------+-----------------------------+
| xtensa | 72 | 336 | 504 | 944 |
+---------------+----------+----------------------------+-----------+-----------------------------+
| x86_64 | 32 | 528 | 1088 | 1440 |
+---------------+----------+----------------------------+-----------+-----------------------------+
API Reference
*************
Logger API
==========
.. doxygengroup:: log_api
Logger control
==============
.. doxygengroup:: log_ctrl
Log message
===========
.. doxygengroup:: log_msg
Logger backend interface
========================
.. doxygengroup:: log_backend
Logger output formatting
========================
.. doxygengroup:: log_output
``` | /content/code_sandbox/doc/services/logging/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 7,922 |
```restructuredtext
.. _posix_conformance:
POSIX Conformance
#################
As per `IEEE 1003.1-2017`, this section details Zephyr's POSIX conformance.
.. _posix_system_interfaces:
POSIX System Interfaces
=======================
.. The following have values greater than -1 in Zephyr, conformant with the POSIX specification.
.. csv-table:: POSIX System Interfaces
:header: Symbol, Support, Remarks
:widths: 50, 10, 50
_POSIX_CHOWN_RESTRICTED, 0,
_POSIX_NO_TRUNC, 0,
_POSIX_VDISABLE, ``'\0'``,
.. TODO: POSIX_ASYNCHRONOUS_IO, and other interfaces below, are mandatory. That means that a
strictly conforming application need not be modified in order to compile against Zephyr.
However, we may add implementations that simply fail with ENOSYS as long as the functional
modification is clearly documented. The implementation is not required for PSE51 or PSE52
and beyond that POSIX async I/O functions are rarely used in practice.
.. _posix_system_interfaces_required:
.. csv-table:: POSIX System Interfaces
:header: Symbol, Support, Remarks
:widths: 50, 10, 50
_POSIX_VERSION, 200809L,
:ref:`_POSIX_ASYNCHRONOUS_IO<posix_option_asynchronous_io>`, 200809L, :kconfig:option:`CONFIG_POSIX_ASYNCHRONOUS_IO`:ref:`<posix_undefined_behaviour>`
:ref:`_POSIX_BARRIERS<posix_option_group_barriers>`, 200809L, :kconfig:option:`CONFIG_POSIX_BARRIERS`
:ref:`_POSIX_CLOCK_SELECTION<posix_option_group_clock_selection>`, 200809L, :kconfig:option:`CONFIG_POSIX_CLOCK_SELECTION`
:ref:`_POSIX_MAPPED_FILES<posix_option_group_mapped_files>`, 200809L, :kconfig:option:`CONFIG_POSIX_MAPPED_FILES`
:ref:`_POSIX_MEMORY_PROTECTION<posix_option_group_memory_protection>`, 200809L, :kconfig:option:`CONFIG_POSIX_MEMORY_PROTECTION` :ref:`<posix_undefined_behaviour>`
:ref:`_POSIX_READER_WRITER_LOCKS<posix_option_reader_writer_locks>`, 200809L, :kconfig:option:`CONFIG_POSIX_READER_WRITER_LOCKS`
:ref:`_POSIX_REALTIME_SIGNALS<posix_option_group_realtime_signals>`, -1, :kconfig:option:`CONFIG_POSIX_REALTIME_SIGNALS`
:ref:`_POSIX_SEMAPHORES<posix_option_group_semaphores>`, 200809L, :kconfig:option:`CONFIG_POSIX_SEMAPHORES`
:ref:`_POSIX_SPIN_LOCKS<posix_option_group_spin_locks>`, 200809L, :kconfig:option:`CONFIG_POSIX_SPIN_LOCKS`
:ref:`_POSIX_THREAD_SAFE_FUNCTIONS<posix_thread_safe_functions>`, -1, :kconfig:option:`CONFIG_POSIX_THREAD_SAFE_FUNCTIONS`
:ref:`_POSIX_THREADS<posix_option_group_threads_base>`, -1, :kconfig:option:`CONFIG_POSIX_THREADS`
:ref:`_POSIX_TIMEOUTS<posix_option_timeouts>`, 200809L, :kconfig:option:`CONFIG_POSIX_TIMEOUTS`
:ref:`_POSIX_TIMERS<posix_option_group_timers>`, 200809L, :kconfig:option:`CONFIG_POSIX_TIMERS`
_POSIX2_C_BIND, 200809L,
.. The following should be valued greater than zero in Zephyr, in order to be strictly conformant
with the POSIX specification.
.. csv-table:: POSIX System Interfaces (Unsupported)
:header: Symbol, Support, Remarks
:widths: 50, 10, 50
_POSIX_JOB_CONTROL, -1, :ref:`<posix_undefined_behaviour>`
_POSIX_REGEXP, -1, :ref:`<posix_undefined_behaviour>`
_POSIX_SAVED_IDS, -1, :ref:`<posix_undefined_behaviour>`
_POSIX_SHELL, -1, :ref:`<posix_undefined_behaviour>`
.. csv-table:: POSIX System Interfaces (Optional)
:header: Symbol, Support, Remarks
:widths: 50, 10, 50
_POSIX_ADVISORY_INFO, -1,
:ref:`_POSIX_CPUTIME<posix_option_cputime>`, 200809L, :kconfig:option:`CONFIG_POSIX_CPUTIME`
:ref:`_POSIX_FSYNC<posix_option_fsync>`, 200809L, :kconfig:option:`CONFIG_POSIX_FSYNC`
:ref:`_POSIX_IPV6<posix_option_ipv6>`, 200809L, :kconfig:option:`CONFIG_POSIX_IPV6`
:ref:`_POSIX_MEMLOCK <posix_option_memlock>`, 200809L, :kconfig:option:`CONFIG_POSIX_MEMLOCK` :ref:`<posix_undefined_behaviour>`
:ref:`_POSIX_MEMLOCK_RANGE <posix_option_memlock_range>`, 200809L, :kconfig:option:`CONFIG_POSIX_MEMLOCK_RANGE`
:ref:`_POSIX_MESSAGE_PASSING<posix_option_message_passing>`, 200809L, :kconfig:option:`CONFIG_POSIX_MESSAGE_PASSING`
:ref:`_POSIX_MONOTONIC_CLOCK<posix_option_monotonic_clock>`, 200809L, :kconfig:option:`CONFIG_POSIX_MONOTONIC_CLOCK`
_POSIX_PRIORITIZED_IO, -1,
:ref:`_POSIX_PRIORITY_SCHEDULING<posix_option_priority_scheduling>`, 200809L, :kconfig:option:`CONFIG_POSIX_PRIORITY_SCHEDULING`
:ref:`_POSIX_RAW_SOCKETS<posix_option_raw_sockets>`, 200809L, :kconfig:option:`CONFIG_POSIX_RAW_SOCKETS`
:ref:`_POSIX_SHARED_MEMORY_OBJECTS <posix_shared_memory_objects>`, 200809L, :kconfig:option:`CONFIG_POSIX_SHARED_MEMORY_OBJECTS`
_POSIX_SPAWN, -1, :ref:`<posix_undefined_behaviour>`
_POSIX_SPORADIC_SERVER, -1, :ref:`<posix_undefined_behaviour>`
:ref:`_POSIX_SYNCHRONIZED_IO <posix_option_synchronized_io>`, 200809L, :kconfig:option:`CONFIG_POSIX_SYNCHRONIZED_IO`
:ref:`_POSIX_THREAD_ATTR_STACKADDR<posix_option_thread_attr_stackaddr>`, 200809L, :kconfig:option:`CONFIG_POSIX_THREAD_ATTR_STACKADDR`
:ref:`_POSIX_THREAD_ATTR_STACKSIZE<posix_option_thread_attr_stacksize>`, 200809L, :kconfig:option:`CONFIG_POSIX_THREAD_ATTR_STACKSIZE`
:ref:`_POSIX_THREAD_CPUTIME <posix_option_thread_cputime>`, 200809L, :kconfig:option:`CONFIG_POSIX_CPUTIME`
:ref:`_POSIX_THREAD_PRIO_INHERIT <posix_option_thread_prio_inherit>`, 200809L, :kconfig:option:`CONFIG_POSIX_THREAD_PRIO_INHERIT`
:ref:`_POSIX_THREAD_PRIO_PROTECT <posix_option_thread_prio_protect>`, 200809L, :kconfig:option:`CONFIG_POSIX_THREAD_PRIO_PROTECT`
:ref:`_POSIX_THREAD_PRIORITY_SCHEDULING <posix_option_thread_priority_scheduling>`, 200809L, :kconfig:option:`CONFIG_POSIX_THREAD_PRIORITY_SCHEDULING`
_POSIX_THREAD_PROCESS_SHARED, -1,
_POSIX_THREAD_SPORADIC_SERVER, -1,
_POSIX_TRACE, -1,
_POSIX_TRACE_EVENT_FILTER, -1,
_POSIX_TRACE_INHERIT, -1,
_POSIX_TRACE_LOG, -1,
_POSIX_TYPED_MEMORY_OBJECTS, -1,
_XOPEN_CRYPT, -1,
_XOPEN_REALTIME, -1,
_XOPEN_REALTIME_THREADS, -1,
:ref:`_XOPEN_STREAMS<posix_option_xopen_streams>`, 200809L, :kconfig:option:`CONFIG_XOPEN_STREAMS`
_XOPEN_UNIX, -1,
POSIX Shell and Utilities
=========================
Zephyr does not support a POSIX shell or utilities at this time.
.. csv-table:: POSIX Shell and Utilities
:header: Symbol, Support, Remarks
:widths: 50, 10, 50
_POSIX2_C_DEV, -1, :ref:`<posix_undefined_behaviour>`
_POSIX2_CHAR_TERM, -1, :ref:`<posix_undefined_behaviour>`
_POSIX2_FORT_DEV, -1, :ref:`<posix_undefined_behaviour>`
_POSIX2_FORT_RUN, -1, :ref:`<posix_undefined_behaviour>`
_POSIX2_LOCALEDEF, -1, :ref:`<posix_undefined_behaviour>`
_POSIX2_PBS, -1, :ref:`<posix_undefined_behaviour>`
_POSIX2_PBS_ACCOUNTING, -1, :ref:`<posix_undefined_behaviour>`
_POSIX2_PBS_LOCATE, -1, :ref:`<posix_undefined_behaviour>`
_POSIX2_PBS_MESSAGE, -1, :ref:`<posix_undefined_behaviour>`
_POSIX2_PBS_TRACK, -1, :ref:`<posix_undefined_behaviour>`
_POSIX2_SW_DEV, -1, :ref:`<posix_undefined_behaviour>`
_POSIX2_UPE, -1, :ref:`<posix_undefined_behaviour>`
_POSIX2_UNIX, -1, :ref:`<posix_undefined_behaviour>`
_POSIX2_UUCP, -1, :ref:`<posix_undefined_behaviour>`
XSI Conformance
###############
X/Open System Interfaces
========================
.. csv-table:: X/Open System Interfaces
:header: Symbol, Support, Remarks
:widths: 50, 10, 50
:ref:`_POSIX_FSYNC<posix_option_fsync>`, 200809L, :kconfig:option:`CONFIG_POSIX_FSYNC`
:ref:`_POSIX_THREAD_ATTR_STACKADDR<posix_option_thread_attr_stackaddr>`, 200809L, :kconfig:option:`CONFIG_POSIX_THREAD_ATTR_STACKADDR`
:ref:`_POSIX_THREAD_ATTR_STACKSIZE<posix_option_thread_attr_stacksize>`, 200809L, :kconfig:option:`CONFIG_POSIX_THREAD_ATTR_STACKSIZE`
_POSIX_THREAD_PROCESS_SHARED, -1,
.. _posix_undefined_behaviour:
.. note::
Some features may exhibit undefined behaviour as they fall beyond the scope of Zephyr's current
design and capabilities. For example, multi-processing, ad-hoc memory-mapping, multiple users,
or regular expressions are features that are uncommon in low-footprint embedded systems.
Such undefined behaviour is denoted with the (obelus) symbol. Additional details
:ref:`here <posix_option_groups>`.
.. _posix_libc_provided:
.. note::
Features listed in various POSIX Options or Option Groups may be provided in whole or in part
by a conformant C library implementation. This includes (but is not limited to) POSIX
Extensions to the ISO C Standard (`CX`_).
.. _CX: path_to_url
``` | /content/code_sandbox/doc/services/portability/posix/conformance/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 2,551 |
```restructuredtext
.. _posix_kconfig_options:
Additional Configuration Options
********************************
Below is a non-exhaustive list of additional :ref:`kconfig` options relating to Zephyr's
implementation of the POSIX API.
* :kconfig:option:`CONFIG_DYNAMIC_THREAD`
* :kconfig:option:`CONFIG_DYNAMIC_THREAD_POOL_SIZE`
* :kconfig:option:`CONFIG_EVENTFD`
* :kconfig:option:`CONFIG_FDTABLE`
* :kconfig:option:`CONFIG_GETOPT_LONG`
* :kconfig:option:`CONFIG_MAX_PTHREAD_SPINLOCK_COUNT`
* :kconfig:option:`CONFIG_MQUEUE_NAMELEN_MAX`
* :kconfig:option:`CONFIG_POSIX_MQ_OPEN_MAX`
* :kconfig:option:`CONFIG_MSG_SIZE_MAX`
* :kconfig:option:`CONFIG_NET_SOCKETPAIR`
* :kconfig:option:`CONFIG_NET_SOCKETS`
* :kconfig:option:`CONFIG_NET_SOCKETS_POLL_MAX`
* :kconfig:option:`CONFIG_ZVFS_OPEN_MAX`
* :kconfig:option:`CONFIG_POSIX_API`
* :kconfig:option:`CONFIG_POSIX_OPEN_MAX`
* :kconfig:option:`CONFIG_POSIX_PTHREAD_ATTR_GUARDSIZE_BITS`
* :kconfig:option:`CONFIG_POSIX_PTHREAD_ATTR_GUARDSIZE_DEFAULT`
* :kconfig:option:`CONFIG_POSIX_PTHREAD_ATTR_STACKSIZE_BITS`
* :kconfig:option:`CONFIG_POSIX_RTSIG_MAX`
* :kconfig:option:`CONFIG_POSIX_SIGNAL_STRING_DESC`
* :kconfig:option:`CONFIG_POSIX_THREAD_KEYS_MAX`
* :kconfig:option:`CONFIG_POSIX_THREAD_THREADS_MAX`
* :kconfig:option:`CONFIG_POSIX_UNAME_NODENAME_LEN`
* :kconfig:option:`CONFIG_POSIX_UNAME_VERSION_LEN`
* :kconfig:option:`CONFIG_PTHREAD_CREATE_BARRIER`
* :kconfig:option:`CONFIG_PTHREAD_RECYCLER_DELAY_MS`
* :kconfig:option:`CONFIG_POSIX_SEM_NAMELEN_MAX`
* :kconfig:option:`CONFIG_POSIX_SEM_NSEMS_MAX`
* :kconfig:option:`CONFIG_POSIX_SEM_VALUE_MAX`
* :kconfig:option:`CONFIG_TIMER_CREATE_WAIT`
* :kconfig:option:`CONFIG_THREAD_STACK_INFO`
* :kconfig:option:`CONFIG_ZVFS_EVENTFD_MAX`
``` | /content/code_sandbox/doc/services/portability/posix/kconfig/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 497 |
```restructuredtext
.. _zdsp_api:
Digital Signal Processing (DSP)
###############################
.. contents::
:local:
:depth: 2
The DSP API provides an architecture agnostic way for signal processing.
Currently, the API will work on any architecture but will likely not be
optimized. The status of the various architectures can be found below:
============ =============
Architecture Status
============ =============
ARC Optimized
ARM Optimized
ARM64 Optimized
MIPS Unoptimized
NIOS2 Unoptimized
POSIX Unoptimized
RISCV Unoptimized
RISCV64 Unoptimized
SPARC Unoptimized
X86 Unoptimized
XTENSA Unoptimized
============ =============
Using zDSP
**********
zDSP provides various backend options which are selected automatically for the
application. By default, including the CMSIS module will enable all
architectures to use the zDSP APIs. This can be done by setting::
CONFIG_CMSIS_DSP=y
If your application requires some additional customization, it's possible to
enable :kconfig:option:`CONFIG_DSP_BACKEND_CUSTOM` which means that the
application is responsible for providing the implementation of the zDSP
library.
Optimizing for your architecture
********************************
If your architecture is showing as ``Unoptimized``, it's possible to add a new
zDSP backend to better support it. To do that, a new Kconfig option should be
added to :file:`subsys/dsp/Kconfig` along with the required dependencies and the
``default`` set for ``DSP_BACKEND`` Kconfig choice.
Next, the implementation should be added at ``subsys/dsp/<backend>/`` and
linked in at :file:`subsys/dsp/CMakeLists.txt`. To add architecture-specific attributes,
its corresponding Kconfig option should be added to :file:`subsys/dsp/Kconfig` and use
them to update ``DSP_DATA`` and ``DSP_STATIC_DATA`` in :file:`include/zephyr/dsp/dsp.h`.
API Reference
*************
.. doxygengroup:: math_dsp
.. _subsys/dsp/Kconfig: path_to_url
.. _subsys/dsp/CMakeLists.txt: path_to_url
.. _include/zephyr/dsp/dsp.h: path_to_url
``` | /content/code_sandbox/doc/services/dsp/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 483 |
```restructuredtext
.. _task_wdt_api:
Task Watchdog
#############
Overview
********
Many microcontrollers feature a hardware watchdog timer peripheral. Its purpose
is to trigger an action (usually a system reset) in case of severe software
malfunctions. Once initialized, the watchdog timer has to be restarted ("fed")
in regular intervals to prevent it from timing out. If the software got stuck
and does not manage to feed the watchdog anymore, the corrective action is
triggered to bring the system back to normal operation.
In real-time operating systems with multiple tasks running in parallel, a
single watchdog instance may not be sufficient anymore, as it can be used for
only one task. This software watchdog based on kernel timers provides a method
to supervise multiple threads or tasks (called watchdog channels).
An existing hardware watchdog can be used as an optional fallback if the task
watchdog itself or the scheduler has a malfunction.
The task watchdog uses a kernel timer as its backend. If configured properly,
the timer ISR is never actually called during normal operation, as the timer is
continuously updated in the feed calls.
It's currently not possible to have multiple instances of task watchdogs.
Instead, the task watchdog API can be accessed globally to add or delete new
channels without passing around a context or device pointer in the firmware.
The maximum number of channels is predefined via Kconfig and should be adjusted
to match exactly the number of channels required by the application.
Configuration Options
*********************
Related configuration options can be found under
:zephyr_file:`subsys/task_wdt/Kconfig`.
* :kconfig:option:`CONFIG_TASK_WDT`
* :kconfig:option:`CONFIG_TASK_WDT_CHANNELS`
* :kconfig:option:`CONFIG_TASK_WDT_HW_FALLBACK`
* :kconfig:option:`CONFIG_TASK_WDT_MIN_TIMEOUT`
* :kconfig:option:`CONFIG_TASK_WDT_HW_FALLBACK_DELAY`
API Reference
*************
.. doxygengroup:: task_wdt_api
``` | /content/code_sandbox/doc/services/task_wdt/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 410 |
```restructuredtext
.. _ipc_service_api:
Interprocessor Communication (IPC)
##################################
.. toctree::
:maxdepth: 1
ipc_service/ipc_service.rst
``` | /content/code_sandbox/doc/services/ipc/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 37 |
```restructuredtext
POSIX Option and Option Group Details
#####################################
.. _posix_option_groups:
POSIX Option Groups
===================
.. _posix_option_group_barriers:
POSIX_BARRIERS
++++++++++++++
Enable this option group with :kconfig:option:`CONFIG_POSIX_BARRIERS`.
.. csv-table:: POSIX_BARRIERS
:header: API, Supported
:widths: 50,10
pthread_barrier_destroy(),yes
pthread_barrier_init(),yes
pthread_barrier_wait(),yes
pthread_barrierattr_destroy(),yes
pthread_barrierattr_init(),yes
.. _posix_option_group_c_lang_jump:
POSIX_C_LANG_JUMP
+++++++++++++++++
The ``POSIX_C_LANG_JUMP`` Option Group is included in the ISO C standard.
.. note::
When using Newlib, Picolibc, or other C libraries conforming to the ISO C Standard, the
``POSIX_C_LANG_JUMP`` Option Group is considered supported.
.. csv-table:: POSIX_C_LANG_JUMP
:header: API, Supported
:widths: 50,10
setjmp(), yes
longjmp(), yes
.. _posix_option_group_c_lang_math:
POSIX_C_LANG_MATH
+++++++++++++++++
The ``POSIX_C_LANG_MATH`` Option Group is included in the ISO C standard.
.. note::
When using Newlib, Picolibc, or other C libraries conforming to the ISO C Standard, the
``POSIX_C_LANG_MATH`` Option Group is considered supported.
Please refer to `Subprofiling Considerations`_ for details on the ``POSIX_C_LANG_MATH`` Option
Group.
.. _posix_option_group_c_lang_support:
POSIX_C_LANG_SUPPORT
++++++++++++++++++++
The POSIX_C_LANG_SUPPORT option group contains the general ISO C Library.
.. note::
When using Newlib, Picolibc, or other C libraries conforming to the ISO C Standard, the entire
``POSIX_C_LANG_SUPPORT`` Option Group is considered supported.
Please refer to `Subprofiling Considerations`_ for details on the ``POSIX_C_LANG_SUPPORT`` Option
Group.
For more information on developing Zephyr applications in the C programming language, please refer
to :ref:`details<language_support>`.
.. _posix_option_group_c_lib_ext:
POSIX_C_LIB_EXT
+++++++++++++++
Enable this option group with :kconfig:option:`CONFIG_POSIX_C_LIB_EXT`.
.. csv-table:: POSIX_C_LIB_EXT
:header: API, Supported
:widths: 50,10
fnmatch(), yes
getopt(), yes
getsubopt(),
optarg, yes
opterr, yes
optind, yes
optopt, yes
stpcpy(),
stpncpy(),
strcasecmp(),
strdup(),
strfmon(),
strncasecmp(), yes
strndup(),
strnlen(), yes
.. _posix_option_group_clock_selection:
POSIX_CLOCK_SELECTION
+++++++++++++++++++++
Enable this option group with :kconfig:option:`CONFIG_POSIX_CLOCK_SELECTION`.
.. csv-table:: POSIX_CLOCK_SELECTION
:header: API, Supported
:widths: 50,10
pthread_condattr_getclock(),yes
pthread_condattr_setclock(),yes
clock_nanosleep(),yes
.. _posix_option_group_device_io:
POSIX_DEVICE_IO
+++++++++++++++
Enable this option group with :kconfig:option:`CONFIG_POSIX_DEVICE_IO`.
.. csv-table:: POSIX_DEVICE_IO
:header: API, Supported
:widths: 50,10
FD_CLR(),yes
FD_ISSET(),yes
FD_SET(),yes
FD_ZERO(),yes
clearerr(),yes
close(),yes
fclose(),
fdopen(),
feof(),
ferror(),
fflush(),
fgetc(),
fgets(),
fileno(),
fopen(),
fprintf(),yes
fputc(),yes
fputs(),yes
fread(),
freopen(),
fscanf(),
fwrite(),yes
getc(),
getchar(),
gets(),
open(),yes
perror(),yes
poll(),yes
printf(),yes
pread(),
pselect(),
putc(),yes
putchar(),yes
puts(),yes
pwrite(),
read(),yes
scanf(),
select(),yes
setbuf(),
setvbuf(),
stderr,
stdin,
stdout,
ungetc(),
vfprintf(),yes
vfscanf(),
vprintf(),yes
vscanf(),
write(),yes
.. _posix_option_group_fd_mgmt:
POSIX_FD_MGMT
+++++++++++++
Enable this option group with :kconfig:option:`CONFIG_POSIX_FD_MGMT`.
.. csv-table:: POSIX_FD_MGMT
:header: API, Supported
:widths: 50,10
dup(),
dup2(),
fcntl(),
fgetpos(),
fseek(),
fseeko(),
fsetpos(),
ftell(),
ftello(),
ftruncate(),yes
lseek(),
rewind(),
.. _posix_option_group_file_locking:
POSIX_FILE_LOCKING
++++++++++++++++++
.. csv-table:: POSIX_FILE_LOCKING
:header: API, Supported
:widths: 50,10
flockfile(),
ftrylockfile(),
funlockfile(),
getc_unlocked(),
getchar_unlocked(),
putc_unlocked(),
putchar_unlocked(),
.. _posix_option_group_file_system:
POSIX_FILE_SYSTEM
+++++++++++++++++
Enable this option group with :kconfig:option:`CONFIG_POSIX_FILE_SYSTEM`.
.. csv-table:: POSIX_FILE_SYSTEM
:header: API, Supported
:widths: 50,10
access(),
chdir(),
closedir(), yes
creat(),
fchdir(),
fpathconf(),
fstat(), yes
fstatvfs(),
getcwd(),
link(),
mkdir(), yes
mkstemp(),
opendir(), yes
pathconf(),
readdir(), yes
remove(),
rename(), yes
rewinddir(),
rmdir(),
stat(), yes
statvfs(),
tmpfile(),
tmpnam(),
truncate(),
unlink(), yes
utime(),
.. _posix_option_group_mapped_files:
POSIX_MAPPED_FILES
++++++++++++++++++
Enable this option group with :kconfig:option:`CONFIG_POSIX_MAPPED_FILES`.
.. csv-table:: POSIX_MAPPED_FILES
:header: API, Supported
:widths: 50,10
mmap(),yes
msync(),yes
munmap(),yes
.. _posix_option_group_memory_protection:
POSIX_MEMORY_PROTECTION
+++++++++++++++++++++++
Enable this option group with :kconfig:option:`CONFIG_POSIX_MEMORY_PROTECTION`.
.. csv-table:: POSIX_MEMORY_PROTECTION
:header: API, Supported
:widths: 50,10
mprotect(), yes :ref:`<posix_undefined_behaviour>`
.. _posix_option_group_multi_process:
POSIX_MULTI_PROCESS
+++++++++++++++++++
Enable this option group with :kconfig:option:`CONFIG_POSIX_MULTI_PROCESS`.
.. csv-table:: POSIX_MULTI_PROCESS
:header: API, Supported
:widths: 50,10
_Exit(), yes
_exit(), yes
assert(), yes
atexit(),:ref:`<posix_undefined_behaviour>`
clock(),
execl(),:ref:`<posix_undefined_behaviour>`
execle(),:ref:`<posix_undefined_behaviour>`
execlp(),:ref:`<posix_undefined_behaviour>`
execv(),:ref:`<posix_undefined_behaviour>`
execve(),:ref:`<posix_undefined_behaviour>`
execvp(),:ref:`<posix_undefined_behaviour>`
exit(), yes
fork(),:ref:`<posix_undefined_behaviour>`
getpgrp(),:ref:`<posix_undefined_behaviour>`
getpgid(),:ref:`<posix_undefined_behaviour>`
getpid(), yes :ref:`<posix_undefined_behaviour>`
getppid(),:ref:`<posix_undefined_behaviour>`
getsid(),:ref:`<posix_undefined_behaviour>`
setsid(),:ref:`<posix_undefined_behaviour>`
sleep(),yes
times(),
wait(),:ref:`<posix_undefined_behaviour>`
waitid(),:ref:`<posix_undefined_behaviour>`
waitpid(),:ref:`<posix_undefined_behaviour>`
.. _posix_option_group_networking:
POSIX_NETWORKING
++++++++++++++++
The function ``sockatmark()`` is not yet supported and is expected to fail setting ``errno``
to ``ENOSYS`` :ref:`<posix_undefined_behaviour>`.
Enable this option group with :kconfig:option:`CONFIG_POSIX_NETWORKING`.
.. csv-table:: POSIX_NETWORKING
:header: API, Supported
:widths: 50,10
accept(),yes
bind(),yes
connect(),yes
endhostent(),yes
endnetent(),yes
endprotoent(),yes
endservent(),yes
freeaddrinfo(),yes
gai_strerror(),yes
getaddrinfo(),yes
gethostent(),yes
gethostname(),yes
getnameinfo(),yes
getnetbyaddr(),yes
getnetbyname(),yes
getnetent(),yes
getpeername(),yes
getprotobyname(),yes
getprotobynumber(),yes
getprotoent(),yes
getservbyname(),yes
getservbyport(),yes
getservent(),yes
getsockname(),yes
getsockopt(),yes
htonl(),yes
htons(),yes
if_freenameindex(),yes
if_indextoname(),yes
if_nameindex(),yes
if_nametoindex(),yes
inet_addr(),yes
inet_ntoa(),yes
inet_ntop(),yes
inet_pton(),yes
listen(),yes
ntohl(),yes
ntohs(),yes
recv(),yes
recvfrom(),yes
recvmsg(),yes
send(),yes
sendmsg(),yes
sendto(),yes
sethostent(),yes
setnetent(),yes
setprotoent(),yes
setservent(),yes
setsockopt(),yes
shutdown(),yes
socket(),yes
sockatmark(),yes :ref:`<posix_undefined_behaviour>`
socketpair(),yes
.. _posix_option_group_pipe:
POSIX_PIPE
++++++++++
.. csv-table:: POSIX_PIPE
:header: API, Supported
:widths: 50,10
pipe(),
.. _posix_option_group_realtime_signals:
POSIX_REALTIME_SIGNALS
++++++++++++++++++++++
Enable this option group with :kconfig:option:`CONFIG_POSIX_REALTIME_SIGNALS`.
.. csv-table:: POSIX_REALTIME_SIGNALS
:header: API, Supported
:widths: 50,10
sigqueue(),
sigtimedwait(),
sigwaitinfo(),
.. _posix_option_group_semaphores:
POSIX_SEMAPHORES
++++++++++++++++
Enable this option group with :kconfig:option:`CONFIG_POSIX_SEMAPHORES`.
.. csv-table:: POSIX_SEMAPHORES
:header: API, Supported
:widths: 50,10
sem_close(),yes
sem_destroy(),yes
sem_getvalue(),yes
sem_init(),yes
sem_open(),yes
sem_post(),yes
sem_trywait(),yes
sem_unlink(),yes
sem_wait(),yes
.. _posix_option_group_signal_jump:
POSIX_SIGNAL_JUMP
+++++++++++++++++
.. csv-table:: POSIX_SIGNAL_JUMP
:header: API, Supported
:widths: 50,10
siglongjmp(),
sigsetjmp(),
.. _posix_option_group_signals:
POSIX_SIGNALS
+++++++++++++
Signal services are a basic mechanism within POSIX-based systems and are
required for error and event handling.
Enable this option group with :kconfig:option:`CONFIG_POSIX_SIGNALS`.
.. csv-table:: POSIX_SIGNALS
:header: API, Supported
:widths: 50,10
abort(),yes
alarm(),
kill(),
pause(),
raise(),
sigaction(),
sigaddset(),yes
sigdelset(),yes
sigemptyset(),yes
sigfillset(),yes
sigismember(),yes
signal(),
sigpending(),
sigprocmask(),yes
sigsuspend(),
sigwait(),
strsignal(),yes
.. _posix_option_group_single_process:
POSIX_SINGLE_PROCESS
++++++++++++++++++++
The POSIX_SINGLE_PROCESS option group contains services for single
process applications.
Enable this option group with :kconfig:option:`CONFIG_POSIX_SINGLE_PROCESS`.
.. csv-table:: POSIX_SINGLE_PROCESS
:header: API, Supported
:widths: 50,10
confstr(),yes
environ,yes
errno,yes
getenv(),yes
setenv(),yes
sysconf(),yes
uname(),yes
unsetenv(),yes
.. _posix_option_group_spin_locks:
POSIX_SPIN_LOCKS
++++++++++++++++
Enable this option group with :kconfig:option:`CONFIG_POSIX_SPIN_LOCKS`.
.. csv-table:: POSIX_SPIN_LOCKS
:header: API, Supported
:widths: 50,10
pthread_spin_destroy(),yes
pthread_spin_init(),yes
pthread_spin_lock(),yes
pthread_spin_trylock(),yes
pthread_spin_unlock(),yes
.. _posix_option_group_threads_base:
POSIX_THREADS_BASE
++++++++++++++++++
The basic assumption in this profile is that the system
consists of a single (implicit) process with multiple threads. Therefore, the
standard requires all basic thread services, except those related to
multiple processes.
Enable this option group with :kconfig:option:`CONFIG_POSIX_THREADS`.
.. csv-table:: POSIX_THREADS_BASE
:header: API, Supported
:widths: 50,10
pthread_atfork(),yes
pthread_attr_destroy(),yes
pthread_attr_getdetachstate(),yes
pthread_attr_getschedparam(),yes
pthread_attr_init(),yes
pthread_attr_setdetachstate(),yes
pthread_attr_setschedparam(),yes
pthread_barrier_destroy(),yes
pthread_barrier_init(),yes
pthread_barrier_wait(),yes
pthread_barrierattr_destroy(),yes
pthread_barrierattr_getpshared(),yes
pthread_barrierattr_init(),yes
pthread_barrierattr_setpshared(),yes
pthread_cancel(),yes
pthread_cleanup_pop(),yes
pthread_cleanup_push(),yes
pthread_cond_broadcast(),yes
pthread_cond_destroy(),yes
pthread_cond_init(),yes
pthread_cond_signal(),yes
pthread_cond_timedwait(),yes
pthread_cond_wait(),yes
pthread_condattr_destroy(),yes
pthread_condattr_init(),yes
pthread_create(),yes
pthread_detach(),yes
pthread_equal(),yes
pthread_exit(),yes
pthread_getspecific(),yes
pthread_join(),yes
pthread_key_create(),yes
pthread_key_delete(),yes
pthread_kill(),
pthread_mutex_destroy(),yes
pthread_mutex_init(),yes
pthread_mutex_lock(),yes
pthread_mutex_trylock(),yes
pthread_mutex_unlock(),yes
pthread_mutexattr_destroy(),yes
pthread_mutexattr_init(),yes
pthread_once(),yes
pthread_self(),yes
pthread_setcancelstate(),yes
pthread_setcanceltype(),yes
pthread_setspecific(),yes
pthread_sigmask(),yes
pthread_testcancel(),yes
.. _posix_option_group_posix_threads_ext:
POSIX_THREADS_EXT
+++++++++++++++++
Enable this option group with :kconfig:option:`CONFIG_POSIX_THREADS_EXT`.
.. csv-table:: POSIX_THREADS_EXT
:header: API, Supported
:widths: 50,10
pthread_attr_getguardsize(),yes
pthread_attr_setguardsize(),yes
pthread_mutexattr_gettype(),yes
pthread_mutexattr_settype(),yes
.. _posix_option_group_timers:
POSIX_TIMERS
++++++++++++
Enable this option group with :kconfig:option:`CONFIG_POSIX_TIMERS`.
.. csv-table:: POSIX_TIMERS
:header: API, Supported
:widths: 50,10
clock_getres(),yes
clock_gettime(),yes
clock_settime(),yes
nanosleep(),yes
timer_create(),yes
timer_delete(),yes
timer_gettime(),yes
timer_getoverrun(),yes
timer_settime(),yes
.. _posix_option_group_xsi_system_logging:
XSI_SYSTEM_LOGGING
++++++++++++++++++
Enable this option group with :kconfig:option:`CONFIG_XSI_SYSTEM_LOGGING`.
.. csv-table:: XSI_SYSTEM_LOGGING
:header: API, Supported
:widths: 50,10
closelog(),yes
openlog(),yes
setlogmask(),yes
syslog(),yes
.. _posix_option_group_xsi_threads_ext:
XSI_THREADS_EXT
+++++++++++++++
The XSI_THREADS_EXT option group is required because it provides
functions to control a thread's stack. This is considered useful for any
real-time application.
Enable this option group with :kconfig:option:`CONFIG_XSI_THREADS_EXT`.
.. csv-table:: XSI_THREADS_EXT
:header: API, Supported
:widths: 50,10
pthread_attr_getstack(),yes
pthread_attr_setstack(),yes
pthread_getconcurrency(),yes
pthread_setconcurrency(),yes
.. _posix_options:
POSIX Options
=============
.. _posix_option_asynchronous_io:
_POSIX_ASYNCHRONOUS_IO
++++++++++++++++++++++
Functions part of the ``_POSIX_ASYNCHRONOUS_IO`` Option are not implemented in Zephyr but are
provided so that conformant applications can still link. These functions will fail, setting
``errno`` to ``ENOSYS``:ref:`<posix_undefined_behaviour>`.
Enable this option with :kconfig:option:`CONFIG_POSIX_ASYNCHRONOUS_IO`.
.. csv-table:: _POSIX_ASYNCHRONOUS_IO
:header: API, Supported
:widths: 50,10
aio_cancel(),yes :ref:`<posix_undefined_behaviour>`
aio_error(),yes :ref:`<posix_undefined_behaviour>`
aio_fsync(),yes :ref:`<posix_undefined_behaviour>`
aio_read(),yes :ref:`<posix_undefined_behaviour>`
aio_return(),yes :ref:`<posix_undefined_behaviour>`
aio_suspend(),yes :ref:`<posix_undefined_behaviour>`
aio_write(),yes :ref:`<posix_undefined_behaviour>`
lio_listio(),yes :ref:`<posix_undefined_behaviour>`
.. _posix_option_cputime:
_POSIX_CPUTIME
++++++++++++++
Enable this option with :kconfig:option:`CONFIG_POSIX_CPUTIME`.
.. csv-table:: _POSIX_CPUTIME
:header: API, Supported
:widths: 50,10
CLOCK_PROCESS_CPUTIME_ID,yes
.. _posix_option_fsync:
_POSIX_FSYNC
++++++++++++
Enable this option with :kconfig:option:`CONFIG_POSIX_FSYNC`.
.. csv-table:: _POSIX_FSYNC
:header: API, Supported
:widths: 50,10
fsync(),yes
.. _posix_option_ipv6:
_POSIX_IPV6
+++++++++++
Internet Protocol Version 6 is supported.
For more information, please refer to :ref:`Networking <networking>`.
Enable this option with :kconfig:option:`CONFIG_POSIX_IPV6`.
.. _posix_option_memlock:
_POSIX_MEMLOCK
++++++++++++++
Zephyr's :ref:`Demand Paging API <memory_management_api_demand_paging>` does not yet support
pinning or unpinning all virtual memory regions. The functions below are expected to fail and
set ``errno`` to ``ENOSYS`` :ref:`<posix_undefined_behaviour>`.
Enable this option with :kconfig:option:`CONFIG_POSIX_MEMLOCK`.
.. csv-table:: _POSIX_MEMLOCK
:header: API, Supported
:widths: 50,10
mlockall(), yes
munlockall(), yes
.. _posix_option_memlock_range:
_POSIX_MEMLOCK_RANGE
++++++++++++++++++++
Enable this option with :kconfig:option:`CONFIG_POSIX_MEMLOCK_RANGE`.
.. csv-table:: _POSIX_MEMLOCK_RANGE
:header: API, Supported
:widths: 50,10
mlock(), yes
munlock(), yes
.. _posix_option_message_passing:
_POSIX_MESSAGE_PASSING
++++++++++++++++++++++
Enable this option with :kconfig:option:`CONFIG_POSIX_MESSAGE_PASSING`.
.. csv-table:: _POSIX_MESSAGE_PASSING
:header: API, Supported
:widths: 50,10
mq_close(),yes
mq_getattr(),yes
mq_notify(),yes
mq_open(),yes
mq_receive(),yes
mq_send(),yes
mq_setattr(),yes
mq_unlink(),yes
.. _posix_option_monotonic_clock:
_POSIX_MONOTONIC_CLOCK
++++++++++++++++++++++
Enable this option with :kconfig:option:`CONFIG_POSIX_MONOTONIC_CLOCK`.
.. csv-table:: _POSIX_MONOTONIC_CLOCK
:header: API, Supported
:widths: 50,10
CLOCK_MONOTONIC,yes
.. _posix_option_priority_scheduling:
_POSIX_PRIORITY_SCHEDULING
++++++++++++++++++++++++++
As processes are not yet supported in Zephyr, the functions ``sched_rr_get_interval()``,
``sched_setparam()``, and ``sched_setscheduler()`` are expected to fail setting ``errno``
to ``ENOSYS``:ref:`<posix_undefined_behaviour>`.
Enable this option with :kconfig:option:`CONFIG_POSIX_PRIORITY_SCHEDULING`.
.. csv-table:: _POSIX_PRIORITY_SCHEDULING
:header: API, Supported
:widths: 50,10
sched_get_priority_max(),yes
sched_get_priority_min(),yes
sched_getparam(),yes
sched_getscheduler(),yes
sched_rr_get_interval(),yes :ref:`<posix_undefined_behaviour>`
sched_setparam(),yes :ref:`<posix_undefined_behaviour>`
sched_setscheduler(),yes :ref:`<posix_undefined_behaviour>`
sched_yield(),yes
.. _posix_option_raw_sockets:
_POSIX_RAW_SOCKETS
++++++++++++++++++
Raw sockets are supported.
For more information, please refer to :kconfig:option:`CONFIG_NET_SOCKETS_PACKET`.
Enable this option with :kconfig:option:`CONFIG_POSIX_RAW_SOCKETS`.
.. _posix_option_reader_writer_locks:
_POSIX_READER_WRITER_LOCKS
++++++++++++++++++++++++++
Enable this option with :kconfig:option:`CONFIG_POSIX_READER_WRITER_LOCKS`.
.. csv-table:: _POSIX_READER_WRITER_LOCKS
:header: API, Supported
:widths: 50,10
pthread_rwlock_destroy(),yes
pthread_rwlock_init(),yes
pthread_rwlock_rdlock(),yes
pthread_rwlock_tryrdlock(),yes
pthread_rwlock_trywrlock(),yes
pthread_rwlock_unlock(),yes
pthread_rwlock_wrlock(),yes
pthread_rwlockattr_destroy(),yes
pthread_rwlockattr_getpshared(),yes
pthread_rwlockattr_init(),yes
pthread_rwlockattr_setpshared(),yes
.. _posix_shared_memory_objects:
_POSIX_SHARED_MEMORY_OBJECTS
++++++++++++++++++++++++++++
Enable this option with :kconfig:option:`CONFIG_POSIX_SHARED_MEMORY_OBJECTS`.
.. csv-table:: _POSIX_SHARED_MEMORY_OBJECTS
:header: API, Supported
:widths: 50,10
mmap(), yes
munmap(), yes
shm_open(), yes
shm_unlink(), yes
.. _posix_option_synchronized_io:
_POSIX_SYNCHRONIZED_IO
++++++++++++++++++++++
Enable this option with :kconfig:option:`CONFIG_POSIX_SYNCHRONIZED_IO`.
.. csv-table:: _POSIX_SYNCHRONIZED_IO
:header: API, Supported
:widths: 50,10
fdatasync(),yes
fsync(),yes
msync(),yes
.. _posix_option_thread_attr_stackaddr:
_POSIX_THREAD_ATTR_STACKADDR
++++++++++++++++++++++++++++
Enable this option with :kconfig:option:`CONFIG_POSIX_THREAD_ATTR_STACKADDR`.
.. csv-table:: _POSIX_THREAD_ATTR_STACKADDR
:header: API, Supported
:widths: 50,10
pthread_attr_getstackaddr(),yes
pthread_attr_setstackaddr(),yes
.. _posix_option_thread_attr_stacksize:
_POSIX_THREAD_ATTR_STACKSIZE
++++++++++++++++++++++++++++
Enable this option with :kconfig:option:`CONFIG_POSIX_THREAD_ATTR_STACKSIZE`.
.. csv-table:: _POSIX_THREAD_ATTR_STACKSIZE
:header: API, Supported
:widths: 50,10
pthread_attr_getstacksize(),yes
pthread_attr_setstacksize(),yes
.. _posix_option_thread_cputime:
_POSIX_THREAD_CPUTIME
+++++++++++++++++++++
Enable this option with :kconfig:option:`CONFIG_POSIX_THREAD_CPUTIME`.
.. csv-table:: _POSIX_THREAD_CPUTIME
:header: API, Supported
:widths: 50,10
CLOCK_THREAD_CPUTIME_ID,yes
pthread_getcpuclockid(),yes
.. _posix_option_thread_prio_inherit:
_POSIX_THREAD_PRIO_INHERIT
++++++++++++++++++++++++++
Enable this option with :kconfig:option:`CONFIG_POSIX_THREAD_PRIO_INHERIT`.
.. csv-table:: _POSIX_THREAD_PRIO_INHERIT
:header: API, Supported
:widths: 50,10
pthread_mutexattr_getprotocol(),yes
pthread_mutexattr_setprotocol(),yes
.. _posix_option_thread_prio_protect:
_POSIX_THREAD_PRIO_PROTECT
++++++++++++++++++++++++++
Enable this option with :kconfig:option:`CONFIG_POSIX_THREAD_PRIO_PROTECT`.
.. csv-table:: _POSIX_THREAD_PRIO_PROTECT
:header: API, Supported
:widths: 50,10
pthread_mutex_getprioceiling(),yes
pthread_mutex_setprioceiling(),yes
pthread_mutexattr_getprioceiling(),yes
pthread_mutexattr_getprotocol(),yes
pthread_mutexattr_setprioceiling(),yes
pthread_mutexattr_setprotocol(),yes
.. _posix_option_thread_priority_scheduling:
_POSIX_THREAD_PRIORITY_SCHEDULING
+++++++++++++++++++++++++++++++++
Enable this option with :kconfig:option:`CONFIG_POSIX_THREAD_PRIORITY_SCHEDULING`.
.. csv-table:: _POSIX_THREAD_PRIORITY_SCHEDULING
:header: API, Supported
:widths: 50,10
pthread_attr_getinheritsched(),yes
pthread_attr_getschedpolicy(),yes
pthread_attr_getscope(),yes
pthread_attr_setinheritsched(),yes
pthread_attr_setschedpolicy(),yes
pthread_attr_setscope(),yes
pthread_getschedparam(),yes
pthread_setschedparam(),yes
pthread_setschedprio(),yes
.. _posix_thread_safe_functions:
_POSIX_THREAD_SAFE_FUNCTIONS
++++++++++++++++++++++++++++
Enable this option with :kconfig:option:`CONFIG_POSIX_THREAD_SAFE_FUNCTIONS`.
.. csv-table:: _POSIX_THREAD_SAFE_FUNCTIONS
:header: API, Supported
:widths: 50,10
asctime_r(),
ctime_r(),
flockfile(),
ftrylockfile(),
funlockfile(),
getc_unlocked(),
getchar_unlocked(),
getgrgid_r(),yes :ref:`<posix_undefined_behaviour>`
getgrnam_r(),yes :ref:`<posix_undefined_behaviour>`
getpwnam_r(),yes :ref:`<posix_undefined_behaviour>`
getpwuid_r(),yes :ref:`<posix_undefined_behaviour>`
gmtime_r(), yes
localtime_r(),
putc_unlocked(),
putchar_unlocked(),
rand_r(), yes
readdir_r(), yes
strerror_r(), yes
strtok_r(), yes
.. _posix_option_timeouts:
_POSIX_TIMEOUTS
+++++++++++++++
Enable this option with :kconfig:option:`CONFIG_POSIX_TIMEOUTS`.
.. csv-table:: _POSIX_TIMEOUTS
:header: API, Supported
:widths: 50,10
mq_timedreceive(),yes
mq_timedsend(),yes
pthread_mutex_timedlock(),yes
pthread_rwlock_timedrdlock(),yes
pthread_rwlock_timedwrlock(),yes
sem_timedwait(),yes
posix_trace_timedgetnext_event(),
.. _posix_option_xopen_streams:
_XOPEN_STREAMS
++++++++++++++
With the exception of ``ioctl()``, functions in the ``_XOPEN_STREAMS`` option group are not
implemented in Zephyr but are provided so that conformant applications can still link.
Unimplemented functions in this option group will fail, setting ``errno`` to ``ENOSYS``
:ref:`<posix_undefined_behaviour>`.
Enable this option with :kconfig:option:`CONFIG_XOPEN_STREAMS`.
.. csv-table:: _XOPEN_STREAMS
:header: API, Supported
:widths: 50,10
fattach(), yes :ref:`<posix_undefined_behaviour>`
fdetach(), yes :ref:`<posix_undefined_behaviour>`
getmsg(), yes :ref:`<posix_undefined_behaviour>`
getpmsg(), yes :ref:`<posix_undefined_behaviour>`
ioctl(), yes
isastream(), yes :ref:`<posix_undefined_behaviour>`
putmsg(), yes :ref:`<posix_undefined_behaviour>`
putpmsg(), yes :ref:`<posix_undefined_behaviour>`
.. _Subprofiling Considerations:
path_to_url
``` | /content/code_sandbox/doc/services/portability/posix/option_groups/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 6,553 |
```restructuredtext
.. _ipc_service:
IPC service
###########
.. contents::
:local:
:depth: 2
The IPC service API provides an interface to exchange data between two domains
or CPUs.
Overview
========
An IPC service communication channel consists of one instance and one or
several endpoints associated with the instance.
An instance is the external representation of a physical communication channel
between two domains or CPUs. The actual implementation and internal
representation of the instance is peculiar to each backend.
An individual instance is not used to send data between domains/CPUs. To send
and receive the data, the user must create (register) an endpoint in the
instance. This allows for the connection of the two domains of interest.
It is possible to have zero or multiple endpoints for one single instance,
possibly with different priorities, and to use each to exchange data.
Endpoint prioritization and multi-instance ability highly depend on the backend
used.
The endpoint is an entity the user must use to send and receive data between
two domains (connected by the instance). An endpoint is always associated to an
instance.
The creation of the instances is left to the backend, usually at init time.
The registration of the endpoints is left to the user, usually at run time.
The API does not mandate a way for the backend to create instances but it is
strongly recommended to use the devicetree to retrieve the configuration
parameters for an instance. Currently, each backend defines its own
DT-compatible configuration that is used to configure the interface at boot
time.
The following usage scenarios are supported:
* Simple data exchange.
* Data exchange using the no-copy API.
Simple data exchange
====================
To send data between domains or CPUs, an endpoint must be registered onto
an instance.
See the following example:
.. note::
Before registering an endpoint, the instance must be opened using the
:c:func:`ipc_service_open_instance` function.
.. code-block:: c
#include <zephyr/ipc/ipc_service.h>
static void bound_cb(void *priv)
{
/* Endpoint bounded */
}
static void recv_cb(const void *data, size_t len, void *priv)
{
/* Data received */
}
static struct ipc_ept_cfg ept0_cfg = {
.name = "ept0",
.cb = {
.bound = bound_cb,
.received = recv_cb,
},
};
int main(void)
{
const struct device *inst0;
struct ipc_ept ept0;
int ret;
inst0 = DEVICE_DT_GET(DT_NODELABEL(ipc0));
ret = ipc_service_open_instance(inst0);
ret = ipc_service_register_endpoint(inst0, &ept0, &ept0_cfg);
/* Wait for endpoint bound (bound_cb called) */
unsigned char message[] = "hello world";
ret = ipc_service_send(&ept0, &message, sizeof(message));
}
Data exchange using the no-copy API
===================================
If the backend supports the no-copy API you can use it to directly write and
read to and from shared memory regions.
See the following example:
.. code-block:: c
#include <zephyr/ipc/ipc_service.h>
#include <stdint.h>
#include <string.h>
static struct ipc_ept ept0;
static void bound_cb(void *priv)
{
/* Endpoint bounded */
}
static void recv_cb_nocopy(const void *data, size_t len, void *priv)
{
int ret;
ret = ipc_service_hold_rx_buffer(&ept0, (void *)data);
/* Process directly or put the buffer somewhere else and release. */
ret = ipc_service_release_rx_buffer(&ept0, (void *)data);
}
static struct ipc_ept_cfg ept0_cfg = {
.name = "ept0",
.cb = {
.bound = bound_cb,
.received = recv_cb,
},
};
int main(void)
{
const struct device *inst0;
int ret;
inst0 = DEVICE_DT_GET(DT_NODELABEL(ipc0));
ret = ipc_service_open_instance(inst0);
ret = ipc_service_register_endpoint(inst0, &ept0, &ept0_cfg);
/* Wait for endpoint bound (bound_cb called) */
void *data;
unsigned char message[] = "hello world";
uint32_t len = sizeof(message);
ret = ipc_service_get_tx_buffer(&ept0, &data, &len, K_FOREVER);
memcpy(data, message, len);
ret = ipc_service_send_nocopy(&ept0, data, sizeof(message));
}
Backends
********
The requirements needed for implementing backends give flexibility to the IPC
service. These allow for the addition of dedicated backends having only a
subsets of features for specific use cases.
The backend must support at least the following:
* The init-time creation of instances.
* The run-time registration of an endpoint in an instance.
Additionally, the backend can also support the following:
* The run-time deregistration of an endpoint from the instance.
* The run-time closing of an instance.
* The no-copy API.
Each backend can have its own limitations and features that make the backend
unique and dedicated to a specific use case. The IPC service API can be used
with multiple backends simultaneously, combining the pros and cons of each
backend.
.. toctree::
:maxdepth: 1
backends/ipc_service_icmsg.rst
backends/ipc_service_icbmsg.rst
API Reference
*************
IPC service API
===============
.. doxygengroup:: ipc_service_api
IPC service backend API
=======================
.. doxygengroup:: ipc_service_backend
``` | /content/code_sandbox/doc/services/ipc/ipc_service/ipc_service.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,228 |
```restructuredtext
.. _ipc_service_backend_icbmsg:
ICMsg with dynamically allocated buffers backend
################################################
This backend is built on top of the :ref:`ipc_service_backend_icmsg`.
Data transferred over this backend travels in dynamically allocated buffers on shared memory.
The ICMsg just sends references to the buffers.
It also supports multiple endpoints.
This architecture allows for overcoming some common problems with other backends (mostly related to multithread access and zero-copy).
This backend provides an alternative with no significant limitations.
Overview
========
The shared memory is divided into two parts.
One is reserved for the ICMsg and the other contains equal-sized blocks.
The number of blocks is configured in the devicetree.
The data sending process is following:
* The sender allocates one or more blocks.
If there are not enough sequential blocks, it waits using the timeout provided in the parameter that also includes K_FOREVER and K_NO_WAIT.
* The allocated blocks are filled with data.
For the zero-copy case, this is done by the caller, otherwise, it is copied automatically.
During this time other threads are not blocked in any way as long as there are enough free blocks for them.
They can allocate, send data and receive data.
* A message containing the block index is sent over ICMsg to the receiver.
The size of the ICMsg queue is large enough to hold messages for all blocks, so it will never overflow.
* The receiver can hold the data as long as desired.
Again, other threads are not blocked as long as there are enough free blocks for them.
* When data is no longer needed, the backend sends a release message over ICMsg.
* When the backend receives this message, it deallocates all blocks.
It is done internally by the backend and it is invisible to the caller.
Configuration
=============
The backend is configured using Kconfig and devicetree.
When configuring the backend, do the following:
* Define two memory regions and assign them to ``tx-region`` and ``rx-region`` of an instance.
Ensure that the memory regions used for data exchange are unique (not overlapping any other region) and accessible by both domains (or CPUs).
* Define the number of allocable blocks for each region with ``tx-blocks`` and ``rx-blocks``.
* Define MBOX devices for sending a signal that informs the other domain (or CPU) of the written data.
Ensure that the other domain (or CPU) can receive the signal.
See the following configuration example for one of the instances:
.. code-block:: devicetree
reserved-memory {
tx: memory@20070000 {
reg = <0x20070000 0x0800>;
};
rx: memory@20078000 {
reg = <0x20078000 0x0800>;
};
};
ipc {
ipc0: ipc0 {
compatible = "zephyr,ipc-icbmsg";
tx-region = <&tx>;
rx-region = <&rx>;
tx-blocks = <16>;
rx-blocks = <32>;
mboxes = <&mbox 0>, <&mbox 1>;
mbox-names = "tx", "rx";
status = "okay";
};
};
You must provide a similar configuration for the other side of the communication (domain or CPU).
Swap the MBOX channels, memory regions (``tx-region`` and ``rx-region``), and block count (``tx-blocks`` and ``rx-blocks``).
Samples
=======
* :ref:`ipc_multi_endpoint_sample`
``` | /content/code_sandbox/doc/services/ipc/ipc_service/backends/ipc_service_icbmsg.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 747 |
```restructuredtext
.. _ipc_service_backend_icmsg:
ICMsg backend
#############
The inter core messaging backend (ICMsg) is a lighter alternative to the
heavier RPMsg static vrings backend. It offers a minimal feature set in a small
memory footprint. The ICMsg backend is build on top of :ref:`spsc_pbuf`.
Overview
========
The ICMsg backend uses shared memory and MBOX devices for exchanging data.
Shared memory is used to store the data, MBOX devices are used to signal that
the data has been written.
The backend supports the registration of a single endpoint on a single
instance. If the application requires more than one communication channel, you
must define multiple instances, each having its own dedicated endpoint.
Configuration
=============
The backend is configured via Kconfig and devicetree.
When configuring the backend, do the following:
* Define two memory regions and assign them to ``tx-region`` and ``rx-region``
of an instance. Ensure that the memory regions used for data exchange are
unique (not overlapping any other region) and accessible by both domains
(or CPUs).
* Define MBOX devices which are used to send the signal that informs the other
domain (or CPU) that data has been written. Ensure that the other domain
(or CPU) is able to receive the signal.
See the following configuration example for one of the instances:
.. code-block:: devicetree
reserved-memory {
tx: memory@20070000 {
reg = <0x20070000 0x0800>;
};
rx: memory@20078000 {
reg = <0x20078000 0x0800>;
};
};
ipc {
ipc0: ipc0 {
compatible = "zephyr,ipc-icmsg";
tx-region = <&tx>;
rx-region = <&rx>;
mboxes = <&mbox 0>, <&mbox 1>;
mbox-names = "tx", "rx";
status = "okay";
};
};
};
You must provide a similar configuration for the other side of the
communication (domain or CPU) but you must swap the MBOX channels and memory
regions (``tx-region`` and ``rx-region``).
Bonding
=======
When the endpoint is registered, the following happens on each domain (or CPU)
connected through the IPC instance:
1. The domain (or CPU) writes a magic number to its ``tx-region`` of the shared
memory.
#. It then sends a signal to the other domain or CPU, informing that the data
has been written. Sending the signal to the other domain or CPU is repeated
with timeout specified by
:kconfig:option:`CONFIG_IPC_SERVICE_ICMSG_BOND_NOTIFY_REPEAT_TO_MS` option.
#. When the signal from the other domain or CPU is received, the magic number
is read from ``rx-region``. If it is correct, the bonding process is finished
and the backend informs the application by calling
:c:member:`ipc_service_cb.bound` callback.
Samples
=======
- :zephyr:code-sample:`ipc-icmsg`
``` | /content/code_sandbox/doc/services/ipc/ipc_service/backends/ipc_service_icmsg.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 665 |
```restructuredtext
.. _pm-system:
System Power Management
#######################
Introduction
************
The kernel enters the idle state when it has nothing to schedule.
Enabling :kconfig:option:`CONFIG_PM` allows the kernel to call upon the
power management subsystem to put an idle system into one of the supported power states.
The kernel requests an amount of time it would like to suspend, then the PM subsystem decides
the appropriate power state to transition to based on the configured power management policy.
It is the application's responsibility to set up a wake-up event.
A wake-up event will typically be an interrupt triggered by an SoC peripheral module.
Examples include a SysTick, RTC, counter, or GPIO.
Keep in mind that depending on the SoC and the power mode in question,
not all peripherals may be active, and therefore
some wake-up sources may not be usable in all power modes.
The following diagram describes system power management:
.. graphviz::
:caption: System power management
digraph G {
compound=true
node [height=1.2 style=rounded]
lock [label="Lock interruptions"]
config_pm [label="CONFIG_PM" shape=diamond style="rounded,dashed"]
forced_state [label="state forced ?", shape=diamond style="rounded,dashed"]
config_system_managed_device_pm [label="CONFIG_PM_DEVICE" shape=diamond style="rounded,dashed"]
config_system_managed_device_pm2 [label="CONFIG_PM_DEVICE" shape=diamond style="rounded,dashed"]
pm_policy [label="Check policy manager\nfor a power state "]
pm_suspend_devices [label="Suspend\ndevices"]
pm_resume_devices [label="Resume\ndevices"]
pm_state_set [label="Change power state\n(SoC API)" style="rounded,bold"]
pm_system_resume [label="Finish wake-up\n(SoC API)\n(restore interruptions)" style="rounded,bold"]
k_cpu_idle [label="k_cpu_idle()"]
subgraph cluster_0 {
style=invisible;
lock -> config_pm
}
subgraph cluster_1 {
style=dashed
label = "pm_system_suspend()"
forced_state -> config_system_managed_device_pm [label="yes"]
forced_state -> pm_policy [label="no"]
pm_policy -> config_system_managed_device_pm
config_system_managed_device_pm -> pm_state_set:e [label="no"]
config_system_managed_device_pm -> pm_suspend_devices [label="yes"]
pm_suspend_devices -> pm_state_set
pm_state_set -> config_system_managed_device_pm2
config_system_managed_device_pm2 -> pm_resume_devices [label="yes"]
config_system_managed_device_pm2 -> pm_system_resume [label="no"]
pm_resume_devices -> pm_system_resume
}
{rankdir=LR k_cpu_idle; forced_state}
pm_policy -> k_cpu_idle [label="PM_STATE_ACTIVE\n(no power state meet requirements)"]
config_pm -> k_cpu_idle [label="no"]
config_pm -> forced_state [label="yes" lhead="cluster_1"]
pm_system_resume:e -> lock:e [constraint=false lhed="cluster_0"]
}
Power States
============
The power management subsystem defines a set of states described by the
power consumption and context retention associated with each of them.
The set of power states is defined by :c:enum:`pm_state`. In general, lower power states
(higher index in the enum) will offer greater power savings and have higher wake latencies.
Power Management Policies
=========================
The power management subsystem supports the following power management policies:
* Residency based
* Application defined
The policy manager is the component of the power management subsystem responsible
for deciding which power state the system should transition to.
The policy manager can only choose between states that have been defined for the platform.
Other constraints placed upon the decision may include locks disallowing certain power states,
or various kinds of minimum and maximum latency values, depending on the policy.
More details on the states definition can be found in the
:dtcompatible:`zephyr,power-state` binding documentation.
Residency
---------
Under the residency policy, the system will enter the power state which offers the highest
power savings, with the constraint that the sum of the minimum residency value (see
:dtcompatible:`zephyr,power-state`) and the latency to exit the mode must be
less than or equal to the system idle time duration scheduled by the kernel.
Thus the core logic can be summarized with the following expression:
.. code-block:: c
if (time_to_next_scheduled_event >= (state.min_residency_us + state.exit_latency)) {
return state
}
Application
-----------
The application defines the power management policy by implementing the
:c:func:`pm_policy_next_state` function. In this policy, the application is free
to decide which power state the system should transition to based on the
remaining time until the next scheduled timeout.
An example of an application that defines its own policy can be found in
:zephyr_file:`tests/subsys/pm/power_mgmt/`.
.. _pm-policy-power-states:
Policy and Power States
------------------------
The power management subsystem allows different Zephyr components and
applications to configure the policy manager to block the system from transitioning
into certain power states. This can be used by devices when executing tasks in
background to prevent the system from going to a specific state where it would
lose context. See :c:func:`pm_policy_state_lock_get`.
Examples
========
Some helpful examples showing different power management features:
* :zephyr_file:`samples/boards/stm32/power_mgmt/blinky/`
* :zephyr_file:`samples/boards/esp32/deep_sleep/`
* :zephyr_file:`samples/subsys/pm/device_pm/`
* :zephyr_file:`tests/subsys/pm/power_mgmt/`
* :zephyr_file:`tests/subsys/pm/power_mgmt_soc/`
* :zephyr_file:`tests/subsys/pm/power_states_api/`
``` | /content/code_sandbox/doc/services/pm/system.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,268 |
```restructuredtext
Overview
########
The interfaces and APIs provided by the power management subsystem
are designed to be architecture and SOC independent. This enables power
management implementations to be easily adapted to different SOCs and
architectures.
The architecture and SOC independence is achieved by separating the core PM
infrastructure from implementations of the SOC specific components.
Thus a coherent abstraction is presented to the rest of the OS and the application layer.
The power management features are classified into the following categories.
* System Power Management
* Device Power Management
``` | /content/code_sandbox/doc/services/pm/overview.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 106 |
```restructuredtext
.. _pm-guide:
Power Management
################
Zephyr RTOS power management subsystem provides several means for a system
integrator to implement power management support that can take full
advantage of the power saving features of SOCs.
.. toctree::
:maxdepth: 2
overview
system
device
device_runtime
power_domain
api/index.rst
``` | /content/code_sandbox/doc/services/pm/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 85 |
```restructuredtext
.. _pm-device-runtime:
Device Runtime Power Management
###############################
Introduction
************
The device runtime power management (PM) framework is an active power management
mechanism which reduces the overall system power consumption by suspending the
devices which are idle or not used independently of the system state. It can be
enabled by setting :kconfig:option:`CONFIG_PM_DEVICE_RUNTIME`. In this model the device
driver is responsible to indicate when it needs the device and when it does not.
This information is used to determine when to suspend or resume a device based
on usage count.
When device runtime power management is enabled on a device, its state will be
initially set to a :c:enumerator:`PM_DEVICE_STATE_SUSPENDED` indicating it is
not used. On the first device request, it will be resumed and so put into the
:c:enumerator:`PM_DEVICE_STATE_ACTIVE` state. The device will remain in this
state until it is no longer used. At this point, the device will be suspended
until the next device request. If the suspension is performed synchronously the
device will be immediately put into the
:c:enumerator:`PM_DEVICE_STATE_SUSPENDED` state, whereas if it is performed
asynchronously, it will be put into the
:c:enumerator:`PM_DEVICE_STATE_SUSPENDING` state first and then into the
:c:enumerator:`PM_DEVICE_STATE_SUSPENDED` state when the action is run.
For devices on a power domain (via the devicetree 'power-domain' property), device runtime
power management automatically attempts to request and release the dependent domain
in response to :c:func:`pm_device_runtime_get` and :c:func:`pm_device_runtime_put`
calls on the child device.
For the previous to automatically control the power domain state, device runtime PM must be enabled
on the power domain device (either through the `zephyr,pm-device-runtime-auto` devicetree property
or :c:func:`pm_device_runtime_enable`).
.. graphviz::
:caption: Device states and transitions
digraph {
node [shape=box];
init [shape=point];
SUSPENDED [label=PM_DEVICE_STATE_SUSPENDED];
ACTIVE [label=PM_DEVICE_STATE_ACTIVE];
SUSPENDING [label=PM_DEVICE_STATE_SUSPENDING];
init -> SUSPENDED;
SUSPENDED -> ACTIVE;
ACTIVE -> SUSPENDED;
ACTIVE -> SUSPENDING [constraint=false]
SUSPENDING -> SUSPENDED [constraint=false];
SUSPENDED -> SUSPENDING [style=invis];
SUSPENDING -> ACTIVE [style=invis];
}
The device runtime power management framework has been designed to minimize
devices power consumption with minimal application work. Device drivers are
responsible for indicating when they need the device to be operational and
when they do not. Therefore, applications can not manually suspend or resume a
device. An application can, however, decide when to disable or enable runtime
power management for a device. This can be useful, for example, if an
application wants a particular device to be always active.
Design principles
*****************
When runtime PM is enabled on a device it will no longer be resumed or suspended
during system power transitions. Instead, the device is fully responsible to
indicate when it needs a device and when it does not. The device runtime PM API
uses reference counting to keep track of device's usage. This allows the API to
determine when a device needs to be resumed or suspended. The API uses the *get*
and *put* terminology to indicate when a device is needed or not, respectively.
This mechanism plays a key role when we account for device dependencies. For
example, if a bus device is used by multiple sensors, we can keep the bus active
until the last sensor has finished using it.
.. note::
As of today, the device runtime power management API does not manage device
dependencies. This effectively means that, if a device depends on other
devices to operate (e.g. a sensor may depend on a bus device), the bus will
be resumed and suspended on every transaction. In general, it is more
efficient to keep parent devices active when their children are used, since
the children may perform multiple transactions in a short period of time.
Until this feature is added, devices can manually *get* or *put* their
dependencies.
The :c:func:`pm_device_runtime_get` function can be used by a device driver to
indicate it *needs* the device to be active or operational. This function will
increase device usage count and resume the device if necessary. Similarly, the
:c:func:`pm_device_runtime_put` function can be used to indicate that the device
is no longer needed. This function will decrease the device usage count and
suspend the device if necessary. It is worth to note that in both cases, the
operation is carried out synchronously. The sequence diagram shown below
illustrates how a device can use this API and the expected sequence of events.
.. figure:: images/devr-sync-ops.svg
Synchronous operation on a single device
The synchronous model is as simple as it gets. However, it may introduce
unnecessary delays since the application will not get the operation result until
the device is suspended (in case device is no longer used). It will likely not
be a problem if the operation is fast, e.g. a register toggle. However, the
situation will not be the same if suspension involves sending packets through a
slow bus. For this reason the device drivers can also make use of the
:c:func:`pm_device_runtime_put_async` function. This function will schedule
the suspend operation, again, if device is no longer used. The suspension will
then be carried out when the system work queue gets the chance to run. The
sequence diagram shown below illustrates this scenario.
.. figure:: images/devr-async-ops.svg
Asynchronous operation on a single device
Implementation guidelines
*************************
In a first place, a device driver needs to implement the PM action callback used
by the PM subsystem to suspend or resume devices.
.. code-block:: c
static int mydev_pm_action(const struct device *dev,
enum pm_device_action action)
{
switch (action) {
case PM_DEVICE_ACTION_SUSPEND:
/* suspend the device */
...
break;
case PM_DEVICE_ACTION_RESUME:
/* resume the device */
...
break;
default:
return -ENOTSUP;
}
return 0;
}
The PM action callback calls are serialized by the PM subsystem, therefore, no
special synchronization is required.
To enable device runtime power management on a device, the driver needs to call
:c:func:`pm_device_runtime_enable` at initialization time. Note that this
function will suspend the device if its state is
:c:enumerator:`PM_DEVICE_STATE_ACTIVE`. In case the device is physically
suspended, the init function should call
:c:func:`pm_device_init_suspended` before calling
:c:func:`pm_device_runtime_enable`.
.. code-block:: c
/* device driver initialization function */
static int mydev_init(const struct device *dev)
{
int ret;
...
/* OPTIONAL: mark device as suspended if it is physically suspended */
pm_device_init_suspended(dev);
/* enable device runtime power management */
ret = pm_device_runtime_enable(dev);
if ((ret < 0) && (ret != -ENOSYS)) {
return ret;
}
}
Device runtime power management can also be automatically enabled on a device
instance by adding the ``zephyr,pm-device-runtime-auto`` flag onto the corresponding
devicetree node. If enabled, :c:func:`pm_device_runtime_enable` is called immediately
after the ``init`` function of the device runs and returns successfully.
.. code-block:: dts
foo {
/* ... */
zephyr,pm-device-runtime-auto;
};
Assuming an example device driver that implements an ``operation`` API call, the
*get* and *put* operations could be carried out as follows:
.. code-block:: c
static int mydev_operation(const struct device *dev)
{
int ret;
/* "get" device (increases usage count, resumes device if suspended) */
ret = pm_device_runtime_get(dev);
if (ret < 0) {
return ret;
}
/* do something with the device */
...
/* "put" device (decreases usage count, suspends device if no more users) */
return pm_device_runtime_put(dev);
}
In case the suspend operation is *slow*, the device driver can use the
asynchronous API:
.. code-block:: c
static int mydev_operation(const struct device *dev)
{
int ret;
/* "get" device (increases usage count, resumes device if suspended) */
ret = pm_device_runtime_get(dev);
if (ret < 0) {
return ret;
}
/* do something with the device */
...
/* "put" device (decreases usage count, schedule suspend if no more users) */
return pm_device_runtime_put_async(dev, K_NO_WAIT);
}
Examples
********
Some helpful examples showing device runtime power management features:
* :zephyr_file:`tests/subsys/pm/device_runtime_api/`
* :zephyr_file:`tests/subsys/pm/device_power_domains/`
* :zephyr_file:`tests/subsys/pm/power_domain/`
``` | /content/code_sandbox/doc/services/pm/device_runtime.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 2,021 |
```restructuredtext
.. _pm-power-domain:
Power Domain
############
Introduction
************
The Zephyr power domain abstraction is designed to support groupings of devices
powered by a common source to be notified of power source state changes in a
generic fashion. Application code that is using device A does not need to know
that device B is on the same power domain and should also be configured into a
low power state.
Power domains are optional on Zephyr, to enable this feature the
option :kconfig:option:`CONFIG_PM_DEVICE_POWER_DOMAIN` has to be set.
When a power domain turns itself on or off, it is the responsibility of the
power domain to notify all devices using it through their power management
callback called with
:c:enumerator:`PM_DEVICE_ACTION_TURN_ON` or
:c:enumerator:`PM_DEVICE_ACTION_TURN_OFF` respectively. This
work flow is illustrated in the diagram below.
.. _pm-domain-work-flow:
.. graphviz::
:caption: Power domain work flow
digraph {
rankdir="TB";
action [style=invis]
{
rank = same;
rankdir="LR"
devA [label="gpio0"]
devB [label="gpio1"]
}
domain [label="gpio_domain"]
action -> devA [label="pm_device_get()"]
devA:se -> domain:n [label="pm_device_get()"]
domain -> devB [label="action_cb(PM_DEVICE_ACTION_TURN_ON)"]
domain:sw -> devA:sw [label="action_cb(PM_DEVICE_ACTION_TURN_ON)"]
}
Internal Power Domains
----------------------
Most of the devices in an SoC have independent power control that can
be turned on or off to reduce power consumption. But there is a
significant amount of static current leakage that can't be controlled
only using device power management. To solve this problem, SoCs
normally are divided into several regions grouping devices that
are generally used together, so that an unused region can be
completely powered off to eliminate this leakage. These regions are
called "power domains", can be present in a hierarchy and can be
nested.
External Power Domains
----------------------
Devices external to a SoC can be powered from sources other than the main power
source of the SoC. These external sources are typically a switch, a regulator,
or a dedicated power IC. Multiple devices can be powered from the same source,
and this grouping of devices is typically called a "power domain".
Placing devices on power domains can be done for a variety of reasons,
including to enable devices with high power consumption in low power mode to be
completely turned off when not in use.
Implementation guidelines
*************************
In a first place, a device that acts as a power domain needs to
declare compatible with ``power-domain``. Taking
:ref:`pm-domain-work-flow` as example, the following code defines a
domain called ``gpio_domain``.
.. code-block:: devicetree
gpio_domain: gpio_domain@4 {
compatible = "power-domain";
...
};
A power domain needs to implement the PM action callback used by the
PM subsystem to turn devices on and off.
.. code-block:: c
static int mydomain_pm_action(const struct device *dev,
enum pm_device_action *action)
{
switch (action) {
case PM_DEVICE_ACTION_RESUME:
/* resume the domain */
...
/* notify children domain is now powered */
pm_device_children_action_run(dev, PM_DEVICE_ACTION_TURN_ON, NULL);
break;
case PM_DEVICE_ACTION_SUSPEND:
/* notify children domain is going down */
pm_device_children_action_run(dev, PM_DEVICE_ACTION_TURN_OFF, NULL);
/* suspend the domain */
...
break;
case PM_DEVICE_ACTION_TURN_ON:
/* turn on the domain (e.g. setup control pins to disabled) */
...
break;
case PM_DEVICE_ACTION_TURN_OFF:
/* turn off the domain (e.g. reset control pins to default state) */
...
break;
default:
return -ENOTSUP;
}
return 0;
}
Devices belonging to this device can be declared referring it in the
``power-domain`` node's property. The example below declares devices
``gpio0`` and ``gpio1`` belonging to domain ``gpio_domain```.
.. code-block:: devicetree
&gpio0 {
compatible = "zephyr,gpio-emul";
gpio-controller;
power-domain = <&gpio_domain>;
};
&gpio1 {
compatible = "zephyr,gpio-emul";
gpio-controller;
power-domain = <&gpio_domain>;
};
All devices under a domain will be notified when the domain changes
state. These notifications are sent as actions in the device PM action
callback and can be used by them to do any additional work required.
They can safely be ignored though.
.. code-block:: c
static int mydev_pm_action(const struct device *dev,
enum pm_device_action *action)
{
switch (action) {
case PM_DEVICE_ACTION_SUSPEND:
/* suspend the device */
...
break;
case PM_DEVICE_ACTION_RESUME:
/* resume the device */
...
break;
case PM_DEVICE_ACTION_TURN_ON:
/* configure the device into low power mode */
...
break;
case PM_DEVICE_ACTION_TURN_OFF:
/* prepare the device for power down */
...
break;
default:
return -ENOTSUP;
}
return 0;
}
.. note::
It is responsibility of driver or the application to set the domain as
"wakeup" source if a device depending on it is used as "wakeup" source.
Examples
********
Some helpful examples showing power domain features:
* :zephyr_file:`tests/subsys/pm/device_power_domains/`
* :zephyr_file:`tests/subsys/pm/power_domain/`
``` | /content/code_sandbox/doc/services/pm/power_domain.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,256 |
```restructuredtext
.. _pm_api:
Power Management APIs
#####################
System PM APIs
**************
.. doxygengroup:: subsys_pm_sys
States
======
.. doxygengroup:: subsys_pm_states
Policy
======
.. doxygengroup:: subsys_pm_sys_policy
Hooks
=====
.. doxygengroup:: subsys_pm_sys_hooks
Device PM APIs
**************
.. doxygengroup:: subsys_pm_device
.. _device_runtime_apis:
Device Runtime PM APIs
**********************
.. doxygengroup:: subsys_pm_device_runtime
``` | /content/code_sandbox/doc/services/pm/api/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 126 |
```restructuredtext
Test Suites
###########
TF-M includes two sets of test suites:
* tf-m-tests - Standard TF-M specific regression tests
* psa-arch-tests - Test suites for specific PSA APIs (secure storage, etc.)
These test suites can be run from Zephyr via an appropriate sample application
in the samples/tfm_integration folder.
TF-M Regression Tests
*********************
The regression test suite can be run via the :ref:`tfm_regression_test` sample.
This sample tests various services and communication mechanisms across the
NS/S boundary via the PSA APIs. They provide a useful sanity check for proper
integration between the NS RTOS (Zephyr in this case) and the secure
application (TF-M).
PSA Arch Tests
**************
The PSA Arch Test suite, available via :ref:`tfm_psa_test`, contains a number of
test suites that can be used to validate that PSA API specifications are
being followed by the secure application, TF-M being an implementation of
the Platform Security Architecture (PSA).
Only one of these suites can be run at a time, with the available test suites
described via ``CONFIG_TFM_PSA_TEST_*`` KConfig flags:
Purpose
*******
The output of these test suites is required to obtain PSA Certification for
your specific board, RTOS (Zephyr here), and PSA implementation (TF-M in this
case).
They also provide a useful test case to validate any PRs that make meaningful
changes to TF-M, such as enabling a new TF-M board target, or making changes
to the core TF-M module(s). They should generally be run as a coherence check
before publishing a new PR for new board support, etc.
``` | /content/code_sandbox/doc/services/tfm/testsuites.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 352 |
```restructuredtext
Device Power Management
#######################
Introduction
************
Device power management (PM) on Zephyr is a feature that enables devices to
save energy when they are not being used. This feature can be enabled by
setting :kconfig:option:`CONFIG_PM_DEVICE` to ``y``. When this option is
selected, device drivers implementing power management will be able to take
advantage of the device power management subsystem.
Zephyr supports two methods of device power management:
- :ref:`Device Runtime Power Management <pm-device-runtime-pm>`
- :ref:`System-Managed Device Power Management <pm-device-system-pm>`
.. _pm-device-runtime-pm:
Device Runtime Power Management
===============================
Device runtime power management involves coordinated interaction between
device drivers, subsystems, and applications. While device drivers
play a crucial role in directly controlling the power state of
devices, the decision to suspend or resume a device can also be
influenced by higher layers of the software stack.
Each layerdevice drivers, subsystems, and applicationscan operate
independently without needing to know about the specifics of the other
layers because the subsystem uses reference count to check when it needs
to suspend or resume a device.
- **Device drivers** are responsible for managing the
power state of devices. They interact directly with the hardware to
put devices into low-power states (suspend) when they are not in
use, and bring them back (resume) when needed. Drivers should use the
:ref:`device runtime power management APIs <device_runtime_apis>` provided
by Zephyr to control the power state of devices.
- **Subsystems**, such as sensors, file systems,
and network, can also influence device power management.
Subsystems may have better knowledge about the overall system
state and workload, allowing them to make informed decisions about
when to suspend or resume devices. For example, a networking
subsystem may decide to keep a network interface powered on if it
expects network activity in the near future.
- **Applications** running on Zephyr can impact device
power management as well. An application may have specific
requirements regarding device usage and power consumption. For
example, an application that streams data over a network may need
to keep the network interface powered on continuously.
Coordination between device drivers, subsystems, and applications is
key to efficient device power management. For example, a device driver
may not know that a subsystem will perform a series of sequential
operations that require a device to remain powered on. In such cases,
the subsystem can use device runtime power management to ensure that
the device remains in an active state until the operations are
complete.
When using this Device Runtime Power Management, the System Power
Management subsystem is able to change power states quickly because it
does not need to spend time suspending and resuming devices that are
runtime enabled.
For more information, see :ref:`pm-device-runtime`.
.. _pm-device-system-pm:
System-Managed Device Power Management
======================================
The system managed device power management (PM) framework is a method where
devices are suspended along with the system entering a CPU (or SoC) power state.
It can be enabled by setting :kconfig:option:`CONFIG_PM_DEVICE_SYSTEM_MANAGED`.
When using this method, device power management is mostly done inside
:c:func:`pm_system_suspend()`.
If a decision to enter a CPU lower power state is made, the power management
subsystem will check if the selected low power state triggers device power
management and then suspend devices before changing state. The subsystem takes
care of suspending devices following their initialization order, ensuring that
possible dependencies between them are satisfied. As soon as the CPU wakes up
from a sleep state, devices are resumed in the opposite order that they were
suspended.
The decision about suspending devices when entering a low power state is done based on the
state and if it has set the property ``zephyr,pm-device-disabled``. Here is
an example of a target with two low power states with only one triggering device power
management:
.. code-block:: devicetree
/* Node in a DTS file */
cpus {
power-states {
state0: state0 {
compatible = "zephyr,power-state";
power-state-name = "standby";
min-residency-us = <5000>;
exit-latency-us = <240>;
zephyr,pm-device-disabled;
};
state1: state1 {
compatible = "zephyr,power-state";
power-state-name = "suspend-to-ram";
min-residency-us = <8000>;
exit-latency-us = <360>;
};
};
};
.. note::
When using :ref:`pm-system`, device transitions can be run from the idle thread.
As functions in this context cannot block, transitions that intend to use blocking
APIs **must** check whether they can do so with :c:func:`k_can_yield`.
This method of device power management can be useful in the following scenarios:
- Systems with no device requiring any blocking operations when suspending and
resuming. This implementation is reasonably simpler than device runtime
power management.
- For devices that can not make any power management decision and have to be
always active. For example a firmware using Zephyr that is controlled by an
external entity (e.g Host CPU). In this scenario, some devices have to be
always active and should be suspended together with the SoC when requested by
this external entity.
It is important to emphasize that this method has drawbacks (see above) and
:ref:`Device Runtime Power Management <pm-device-runtime-pm>` is the
**preferred** method for implementing device power management.
.. note::
When using this method of device power management, the CPU will not
enter a low-power state if a device cannot be suspended. For example,
if a device returns an error such as ``-EBUSY`` in response to the
``PM_DEVICE_ACTION_SUSPEND`` action, indicating it is in the middle of
a transaction that cannot be interrupted. Another condition that
prevents the CPU from entering a low-power state is if the option
:kconfig:option:`CONFIG_PM_NEED_ALL_DEVICES_IDLE` is set and a device
is marked as busy.
.. note::
Devices are suspended only when the last active core is entering a low power
state and devices are resumed by the first core that becomes active.
Device Power Management States
******************************
The power management subsystem defines device states in
:c:enum:`pm_device_state`. This method is used to track power states of
a particular device. It is important to emphasize that, although the
state is tracked by the subsystem, it is the responsibility of each device driver
to handle device actions(:c:enum:`pm_device_action`) which change device state.
Each :c:enum:`pm_device_action` have a direct an unambiguous relationship with
a :c:enum:`pm_device_state`.
.. graphviz::
:caption: Device actions x states
digraph {
node [shape=circle];
rankdir=LR;
subgraph {
SUSPENDED [label=PM_DEVICE_STATE_SUSPENDED];
SUSPENDING [label=PM_DEVICE_STATE_SUSPENDING];
ACTIVE [label=PM_DEVICE_STATE_ACTIVE];
OFF [label=PM_DEVICE_STATE_OFF];
ACTIVE -> SUSPENDING -> SUSPENDED;
ACTIVE -> SUSPENDED ["label"="PM_DEVICE_ACTION_SUSPEND"];
SUSPENDED -> ACTIVE ["label"="PM_DEVICE_ACTION_RESUME"];
{rank = same; SUSPENDED; SUSPENDING;}
OFF -> SUSPENDED ["label"="PM_DEVICE_ACTION_TURN_ON"];
SUSPENDED -> OFF ["label"="PM_DEVICE_ACTION_TURN_OFF"];
ACTIVE -> OFF ["label"="PM_DEVICE_ACTION_TURN_OFF"];
}
}
As mentioned above, device drivers do not directly change between these states.
This is entirely done by the power management subsystem. Instead, drivers are
responsible for implementing any hardware-specific tasks needed to handle state
changes.
Device Model with Power Management Support
******************************************
Drivers initialize devices using macros. See :ref:`device_model_api` for
details on how these macros are used. A driver which implements device power
management support must provide these macros with arguments that describe its
power management implementation.
Use :c:macro:`PM_DEVICE_DEFINE` or :c:macro:`PM_DEVICE_DT_DEFINE` to define the
power management resources required by a driver. These macros allocate the
driver-specific state which is required by the power management subsystem.
Drivers can use :c:macro:`PM_DEVICE_GET` or
:c:macro:`PM_DEVICE_DT_GET` to get a pointer to this state. These
pointers should be passed to ``DEVICE_DEFINE`` or ``DEVICE_DT_DEFINE``
to initialize the power management field in each :c:struct:`device`.
Here is some example code showing how to implement device power management
support in a device driver.
.. code-block:: c
#define DT_DRV_COMPAT dummy_device
static int dummy_driver_pm_action(const struct device *dev,
enum pm_device_action action)
{
switch (action) {
case PM_DEVICE_ACTION_SUSPEND:
/* suspend the device */
...
break;
case PM_DEVICE_ACTION_RESUME:
/* resume the device */
...
break;
case PM_DEVICE_ACTION_TURN_ON:
/*
* powered on the device, used when the power
* domain this device belongs is resumed.
*/
...
break;
case PM_DEVICE_ACTION_TURN_OFF:
/*
* power off the device, used when the power
* domain this device belongs is suspended.
*/
...
break;
default:
return -ENOTSUP;
}
return 0;
}
PM_DEVICE_DT_INST_DEFINE(0, dummy_driver_pm_action);
DEVICE_DT_INST_DEFINE(0, &dummy_init,
PM_DEVICE_DT_INST_GET(0), NULL, NULL, POST_KERNEL,
CONFIG_KERNEL_INIT_PRIORITY_DEFAULT, NULL);
.. _pm-device-shell:
Shell Commands
**************
Power management actions can be triggered from shell commands for testing
purposes. To do that, enable the :kconfig:option:`CONFIG_PM_DEVICE_SHELL`
option and issue a ``pm`` command on a device from the shell, for example:
.. code-block:: console
uart:~$ device list
- buttons (active)
uart:~$ pm suspend buttons
uart:~$ device list
devices:
- buttons (suspended)
To print the power management state of a device, enable
:kconfig:option:`CONFIG_DEVICE_SHELL` and use the ``device list`` command, for
example:
.. code-block:: console
uart:~$ device list
devices:
- i2c@40003000 (active)
- buttons (active, usage=1)
- leds (READY)
In this case, ``leds`` does not support PM, ``i2c`` supports PM with manual
suspend and resume actions and it's currently active, ``buttons`` supports
runtime PM and it's currently active with one user.
.. _pm-device-busy:
Busy Status Indication
**********************
When the system is idle and the SoC is going to sleep, the power management
subsystem can suspend devices, as described in :ref:`pm-device-system-pm`. This
can cause device hardware to lose some states. Suspending a device which is in
the middle of a hardware transaction, such as writing to a flash memory, may
lead to undefined behavior or inconsistent states. This API guards such
transactions by indicating to the kernel that the device is in the middle of an
operation and should not be suspended.
When :c:func:`pm_device_busy_set` is called, the device is marked as busy and
the system will not do power management on it. After the device is no
longer doing an operation and can be suspended, it should call
:c:func:`pm_device_busy_clear`.
.. _pm-device-constraint:
Device Power Management X System Power Management
*************************************************
When managing power in embedded systems, it's crucial to understand
the interplay between device power state and the overall system power
state. Some devices may have dependencies on the system power
state. For example, certain low-power states of the SoC might not
supply power to peripheral devices, leading to problems if the device
is in the middle of an operation. Proper coordination is essential to
maintain system stability and data integrity.
To avoid this sort of problem, devices must :ref:`get and release lock <pm-policy-power-states>`
power states that cause power loss during an operation.
Zephyr provides a mechanism for devices to declare which power states cause power
loss and an API that automatically get and put lock on them. This feature is
enabled setting :kconfig:option:`CONFIG_PM_POLICY_DEVICE_CONSTRAINTS` to ``y``.
Once this feature is enabled, devices must declare in devicetree which
states cause power loss. In the following example, device ``test_dev``
says that power states ``state1`` and ``state2`` cause power loss.
.. code-block:: devicetree
power-states {
state0: state0 {
compatible = "zephyr,power-state";
power-state-name = "suspend-to-idle";
min-residency-us = <10000>;
exit-latency-us = <100>;
};
state1: state1 {
compatible = "zephyr,power-state";
power-state-name = "standby";
min-residency-us = <20000>;
exit-latency-us = <200>;
};
state2: state2 {
compatible = "zephyr,power-state";
power-state-name = "suspend-to-ram";
min-residency-us = <50000>;
exit-latency-us = <500>;
};
state3: state3 {
compatible = "zephyr,power-state";
power-state-name = "suspend-to-ram";
status = "disabled";
};
};
test_dev: test_dev {
compatible = "test-device-pm";
status = "okay";
zephyr,disabling-power-states = <&state1 &state2>;
};
After that devices can lock these state calling
:c:func:`pm_policy_device_power_lock_get` and release with
:c:func:`pm_policy_device_power_lock_put`. For example:
.. code-block:: C
static void timer_expire_cb(struct k_timer *timer)
{
struct test_driver_data *data = k_timer_user_data_get(timer);
data->ongoing = false;
k_timer_stop(timer);
pm_policy_device_power_lock_put(data->self);
}
void test_driver_async_operation(const struct device *dev)
{
struct test_driver_data *data = dev->data;
data->ongoing = true;
pm_policy_device_power_lock_get(dev);
/** Lets set a timer big enough to ensure that any deep
* sleep state would be suitable but constraints will
* make only state0 (suspend-to-idle) will be used.
*/
k_timer_start(&data->timer, K_MSEC(500), K_NO_WAIT);
}
Wakeup capability
*****************
Some devices are capable of waking the system up from a sleep state.
When a device has such capability, applications can enable or disable
this feature on a device dynamically using
:c:func:`pm_device_wakeup_enable`.
This property can be set on device declaring the property ``wakeup-source`` in
the device node in devicetree. For example, this devicetree fragment sets the
``gpio0`` device as a "wakeup" source:
.. code-block:: devicetree
gpio0: gpio@40022000 {
compatible = "ti,cc13xx-cc26xx-gpio";
reg = <0x40022000 0x400>;
interrupts = <0 0>;
status = "disabled";
label = "GPIO_0";
gpio-controller;
wakeup-source;
#gpio-cells = <2>;
};
By default, "wakeup" capable devices do not have this functionality enabled
during the device initialization. Applications can enable this functionality
later calling :c:func:`pm_device_wakeup_enable`.
.. note::
This property is **only** used by the system power management to identify
devices that should not be suspended.
It is responsibility of driver or the application to do any additional
configuration required by the device to support it.
Examples
********
Some helpful examples showing device power management features:
* :zephyr_file:`samples/subsys/pm/device_pm/`
* :zephyr_file:`tests/subsys/pm/power_mgmt/`
* :zephyr_file:`tests/subsys/pm/device_wakeup_api/`
* :zephyr_file:`tests/subsys/pm/device_driver_init/`
``` | /content/code_sandbox/doc/services/pm/device.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 3,612 |
```restructuredtext
.. _tfm_build_system:
TF-M Build System
#################
When building a valid ``_ns`` board target, TF-M will be built in the
background, and linked with the Zephyr non-secure application. No knowledge
of TF-M's build system is required in most cases, and the following will
build a TF-M and Zephyr image pair, and run it in qemu with no additional
steps required:
.. code-block:: bash
$ west build -p auto -b mps2_an521_ns samples/tfm_integration/psa_protected_storage/ -t run
The outputs and certain key steps in this build process are described here,
however, since you will need to understand and interact with the outputs, and
deal with signing the secure and non-secure images before deploying them.
Images Created by the TF-M Build
********************************
The TF-M build system creates the following executable files:
* tfm_s - TF-M secure firmware
* tfm_ns - TF-M non-secure app (only used by regression tests).
* bl2 - TF-M MCUboot, if enabled
For each of these, it creates .bin, .hex, .elf, and .axf files.
The TF-M build system also creates signed variants of tfm_s and tfm_ns, and a
file which combines them:
* tfm_s_signed
* tfm_ns_signed
* tfm_s_ns_signed
For each of these, only .bin files are created.
The TF-M non-secure app is discarded in favor of Zephyr non-secure app except
when running the TF-M regression test suite.
The Zephyr build system usually signs both tfm_s and the Zephyr non-secure app itself.
See below for details.
The 'tfm' target contains properties for all these paths.
For example, the following will resolve to ``<path>/tfm_s.hex``:
.. code-block::
$<TARGET_PROPERTY:tfm,TFM_S_HEX_FILE>
See the top level CMakeLists.txt file in the tfm module for an overview of all
the properties.
Signing Images
**************
When :kconfig:option:`CONFIG_TFM_BL2` is set to ``y``, TF-M uses a secure bootloader
(BL2) and firmware images must be signed with a private key. The firmware image
is validated by the bootloader during updates using the corresponding public
key, which is stored inside the secure bootloader firmware image.
By default, ``<tfm-dir>/bl2/ext/mcuboot/root-rsa-3072.pem`` is used to sign secure
images, and ``<tfm-dir>/bl2/ext/mcuboot/root-rsa-3072_1.pem`` is used to sign
non-secure images. These default .pem keys can (and **should**) be overridden
using the :kconfig:option:`CONFIG_TFM_KEY_FILE_S` and
:kconfig:option:`CONFIG_TFM_KEY_FILE_NS` config flags.
To satisfy `PSA Certified Level 1`_ requirements, **You MUST replace
the default .pem file with a new key pair!**
To generate a new public/private key pair, run the following commands:
.. code-block:: bash
$ imgtool keygen -k root-rsa-3072_s.pem -t rsa-3072
$ imgtool keygen -k root-rsa-3072_ns.pem -t rsa-3072
You can then place the new .pem files in an alternate location, such as your
Zephyr application folder, and reference them in the ``prj.conf`` file via the
:kconfig:option:`CONFIG_TFM_KEY_FILE_S` and :kconfig:option:`CONFIG_TFM_KEY_FILE_NS` config
flags.
.. warning::
Be sure to keep your private key file in a safe, reliable location! If you
lose this key file, you will be unable to sign any future firmware images,
and it will no longer be possible to update your devices in the field!
After the built-in signing script has run, it creates a ``tfm_merged.hex``
file that contains all three binaries: bl2, tfm_s, and the zephyr app. This
hex file can then be flashed to your development board or run in QEMU.
.. _PSA Certified Level 1:
path_to_url
Custom CMake arguments
======================
When building a Zephyr application with TF-M it might be necessary to control
the CMake arguments passed to the TF-M build.
Zephyr TF-M build offers several Kconfig options for controlling the build, but
doesn't cover every CMake argument supported by the TF-M build system.
The ``TFM_CMAKE_OPTIONS`` property on the ``zephyr_property_target`` can be used
to pass custom CMake arguments to the TF-M build system.
To pass the CMake argument ``-DFOO=bar`` to the TF-M build system, place the
following CMake snippet in your CMakeLists.txt file.
.. code-block:: cmake
set_property(TARGET zephyr_property_target
APPEND PROPERTY TFM_CMAKE_OPTIONS
-DFOO=bar
)
.. note::
The ``TFM_CMAKE_OPTIONS`` is a list so it is possible to append multiple
options. Also CMake generator expressions are supported, such as
``$<1:-DFOO=bar>``
Since ``TFM_CMAKE_OPTIONS`` is a list argument it will be expanded before it is
passed to the TF-M build system.
Options that have list arguments must therefore be properly escaped to avoid
being expanded as a list.
.. code-block:: cmake
set_property(TARGET zephyr_property_target
APPEND PROPERTY TFM_CMAKE_OPTIONS
-DFOO="bar\\\;baz"
)
Footprint and Memory Usage
**************************
The build system offers targets to view and analyse RAM and ROM usage in generated images.
The tools run on the final images and give information about size of symbols and code being used in both RAM and ROM.
For more information on these tools look here: :ref:`footprint_tools`
Use the ``tfm_ram_report`` to get the RAM report for TF-M secure firmware (tfm_s).
.. zephyr-app-commands::
:tool: all
:app: samples/hello_world
:board: mps2_an521_ns
:goals: tfm_ram_report
Use the ``tfm_rom_report`` to get the ROM report for TF-M secure firmware (tfm_s).
.. zephyr-app-commands::
:tool: all
:app: samples/hello_world
:board: mps2_an521_ns
:goals: tfm_rom_report
Use the ``bl2_ram_report`` to get the RAM report for TF-M MCUboot, if enabled.
.. zephyr-app-commands::
:tool: all
:app: samples/hello_world
:board: mps2_an521_ns
:goals: bl2_ram_report
Use the ``bl2_rom_report`` to get the ROM report for TF-M MCUboot, if enabled.
.. zephyr-app-commands::
:tool: all
:app: samples/hello_world
:board: mps2_an521_ns
:goals: bl2_rom_report
``` | /content/code_sandbox/doc/services/tfm/build.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,569 |
```restructuredtext
Trusted Firmware-M Integration
##############################
The Trusted Firmware-M (TF-M) section contains information about the
integration between TF-M and Zephyr RTOS. Use this information to help
understand how to integrate TF-M with Zephyr for Cortex-M platforms and make
use of its secure run-time services in Zephyr applications.
Board Definitions
*****************
TF-M will be built for the secure processing environment along with Zephyr if
the :kconfig:option:`CONFIG_BUILD_WITH_TFM` flag is set to ``y``.
Generally, this value should never be set at the application level, however,
and all config flags required for TF-M should be set in a board variant with
the ``_ns`` suffix.
This board variant must define an appropriate flash, SRAM and peripheral
configuration that takes into account the initialisation process in the secure
processing environment. :kconfig:option:`CONFIG_TFM_BOARD` must also be set via
`modules/trusted-firmware-m/Kconfig.tfm <path_to_url`__
to the board name that TF-M expects for this target, so that it knows which
target to build for the secure processing environment.
Example: ``mps2_an521_ns``
==========================
The ``mps2_an521`` target is a dual-core Arm Cortex-M33 evaluation board that,
when using the default board variant, would generate a secure Zephyr binary.
The optional ``mps2_an521_ns`` target, however, sets these additional
kconfig flags that indicate that Zephyr should be built as a
non-secure image, linked with TF-M as an external project, and optionally the
secure bootloader:
* :kconfig:option:`CONFIG_TRUSTED_EXECUTION_NONSECURE` ``y``
* :kconfig:option:`CONFIG_ARM_TRUSTZONE_M` ``y``
Comparing the ``mps2_an521.dts`` and ``mps2_an521_ns.dts`` files, we can see
that the ``_ns`` version defines offsets in flash and SRAM memory, which leave
the required space for TF-M and the secure bootloader:
::
reserved-memory {
#address-cells = <1>;
#size-cells = <1>;
ranges;
/* The memory regions defined below must match what the TF-M
* project has defined for that board - a single image boot is
* assumed. Please see the memory layout in:
* path_to_url
*/
code: memory@100000 {
reg = <0x00100000 DT_SIZE_K(512)>;
};
ram: memory@28100000 {
reg = <0x28100000 DT_SIZE_M(1)>;
};
};
This reserves 1 MB of code memory and 1 MB of RAM for secure boot and TF-M,
such that our non-secure Zephyr application code will start at 0x10000, with
RAM at 0x28100000. 512 KB code memory is available for the NS zephyr image,
along with 1 MB of RAM.
This matches the flash memory layout we see in ``flash_layout.h`` in TF-M:
::
* 0x0000_0000 BL2 - MCUBoot (0.5 MB)
* 0x0008_0000 Secure image primary slot (0.5 MB)
* 0x0010_0000 Non-secure image primary slot (0.5 MB)
* 0x0018_0000 Secure image secondary slot (0.5 MB)
* 0x0020_0000 Non-secure image secondary slot (0.5 MB)
* 0x0028_0000 Scratch area (0.5 MB)
* 0x0030_0000 Protected Storage Area (20 KB)
* 0x0030_5000 Internal Trusted Storage Area (16 KB)
* 0x0030_9000 NV counters area (4 KB)
* 0x0030_A000 Unused (984 KB)
``mps2/an521`` will be passed in to Tf-M as the board target, specified via
:kconfig:option:`CONFIG_TFM_BOARD`.
``` | /content/code_sandbox/doc/services/tfm/integration.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 892 |
```restructuredtext
TF-M Requirements
#################
The following are some of the boards that can be used with TF-M:
.. list-table::
:header-rows: 1
* - Board
- NSPE board name
* - :ref:`mps2_an521_board`
- ``mps2_an521_ns`` (qemu supported)
* - :ref:`mps3_an547_board`
- ``mps3_an547_ns`` (qemu supported)
* - :ref:`bl5340_dvk`
- ``bl5340_dvk/nrf5340/cpuapp/ns``
* - :ref:`lpcxpresso55s69`
- ``lpcxpresso55s69_ns``
* - :ref:`nrf9160dk_nrf9160`
- ``nrf9160dk/nrf9160/ns``
* - :ref:`nrf5340dk_nrf5340`
- ``nrf5340dk/nrf5340/cpuapp/ns``
* - :ref:`b_u585i_iot02a_board`
- ``b_u585i_iot02a/stm32u585xx/ns``
* - :ref:`nucleo_l552ze_q_board`
- ``nucleo_l552ze_q/stm32l552xx/ns``
* - :ref:`stm32l562e_dk_board`
- ``stm32l562e_dk/stm32l562xx/ns``
* - :ref:`v2m_musca_b1_board`
- ``v2m_musca_b1_ns``
* - :ref:`v2m_musca_s1_board`
- ``v2m_musca_s1_ns``
You can run ``west boards -n _ns$`` to search for non-secure variants
of different board targets. To make sure TF-M is supported for a board
in its output, check that :kconfig:option:`CONFIG_TRUSTED_EXECUTION_NONSECURE`
is set to ``y`` in that board's default configuration.
Software Requirements
*********************
The following Python modules are required when building TF-M binaries:
* cryptography
* pyasn1
* pyyaml
* cbor>=1.0.0
* imgtool>=1.9.0
* jinja2
* click
You can install them via:
.. code-block:: bash
$ pip3 install --user cryptography pyasn1 pyyaml cbor>=1.0.0 imgtool>=1.9.0 jinja2 click
They are used by TF-M's signing utility to prepare firmware images for
validation by the bootloader.
Part of the process of generating binaries for QEMU and merging signed
secure and non-secure binaries on certain platforms also requires the use of
the ``srec_cat`` utility.
This can be installed on Linux via:
.. code-block:: bash
$ sudo apt-get install srecord
And on OS X via:
.. code-block:: bash
$ brew install srecord
For Windows-based systems, please make sure you have a copy of the utility
available on your system path. See, for example:
`SRecord for Windows <path_to_url`_
``` | /content/code_sandbox/doc/services/tfm/requirements.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 689 |
```restructuredtext
.. _tfm:
Trusted Firmware-M
##################
.. toctree::
:maxdepth: 1
overview.rst
requirements.rst
build.rst
integration.rst
testsuites.rst
``` | /content/code_sandbox/doc/services/tfm/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 53 |
```restructuredtext
Trusted Firmware-M Overview
###########################
`Trusted Firmware-M (TF-M) <path_to_url`__
is a reference implementation of the Platform Security Architecture (PSA)
`IoT Security Framework <path_to_url`__.
It defines and implements an architecture and a set of software components
that aim to address some of the main security concerns in IoT products.
Zephyr RTOS has been PSA Certified since Zephyr 2.0.0 with TF-M 1.0, and
is currently integrated with TF-M 2.1.0.
What Does TF-M Offer?
*********************
Through a set of secure services and by design, TF-M provides:
* Isolation of secure and non-secure resources
* Embedded-appropriate crypto
* Management of device secrets (keys, etc.)
* Firmware verification (and encryption)
* Protected off-chip data storage and retrieval
* Proof of device identity (device attestation)
* Audit logging
Build System Integration
************************
When using TF-M with a supported platform, TF-M will be automatically built and
link in the background as part of the standard Zephyr build process. This
build process makes a number of assumptions about how TF-M is being used, and
has certain implications about what the Zephyr application image can and can
not do:
* The secure processing environment (secure boot and TF-M) starts first
* Resource allocation for Zephyr relies on choices made in the secure image.
Architecture Overview
*********************
A TF-M application will, generally, have the following three parts, from most
to least trusted, left-to-right, with code execution happening in the same
order (secure boot > secure image > ns image).
While the secure bootloader is optional, it is enabled by default, and secure
boot is an important part of providing a secure solution:
::
+-------------------------------------+ +--------------+
| Secure Processing Environment (SPE) | | NSPE |
| +----------++---------------------+ | | +----------+ |
| | || | | | | | |
| | bl2.bin || tfm_s_signed.bin | | | |zephyr.bin| |
| | || | | <- PSA -> | | | |
| | Secure || Trusted Firmware-M | | APIs | | Zephyr | |
| | Boot || (Secure Image) | | | |(NS Image)| |
| | || | | | | | |
| +----------++---------------------+ | | +----------+ |
+-------------------------------------+ +--------------+
Communication between the (Zephyr) Non-Secure Processing Environment (NSPE) and
the (TF-M) Secure Processing Environment image happens based on a set of PSA
APIs, and normally makes use of an IPC mechanism that is included as part of
the TF-M build, and implemented in Zephyr
(see :zephyr_file:`modules/trusted-firmware-m/interface`).
Root of Trust (RoT) Architecture
================================
TF-M is based upon a **Root of Trust (RoT)** architecture. This allows for
hierarchies of trust from most, to less, to least trusted, providing a sound
foundation upon which to build or access trusted services and resources.
The benefit of this approach is that less trusted components are prevented from
accessing or compromising more critical parts of the system, and error
conditions in less trusted environments won't corrupt more trusted, isolated
resources.
The following RoT hierarchy is defined for TF-M, from most to least trusted:
* PSA Root of Trust (**PRoT**), which consists of:
* PSA Immutable Root of Trust: secure boot
* PSA Updateable Root of Trust: most trusted secure services
* Application Root of Trust (**ARoT**): isolated secure services
The **PSA Immutable Root of Trust** is the most trusted piece of code in the
system, to which subsequent Roots of Trust are anchored. In TF-M, this is the
secure boot image, which verifies that the secure and non-secure images are
valid, have not been tampered with, and come from a reliable source. The
secure bootloader also verifies new images during the firmware update process,
thanks to the public signing key(s) built into it. As the name implies,
this image is **immutable**.
The **PSA Updateable Root of Trust** implements the most trusted secure
services and components in TF-M, such as the Secure Partition Manager (SPM),
and shared secure services like PSA Crypto, Internal Trusted Storage (ITS),
etc. Services in the PSA Updateable Root of Trust have access to other
resources in the same Root of Trust.
The **Application Root of Trust** is a reduced-privilege area in the secure
processing environment which, depending on the isolation level chosen when
building TF-M, has limited access to the PRoT, or even other ARoT services at
the highest isolation levels. Some standard services exist in the ARoT, such as
Protected Storage (PS), and generally custom secure services that you implement
should be placed in the ARoT, unless a compelling reason is present to place
them in the PRoT.
These divisions are distinct from the **untrusted code**, which runs in the
non-secure environment, and has the least privilege in the system. This is the
Zephyr application image in this case.
Isolation Levels
----------------
At present, there are three distinct **isolation levels** defined in TF-M,
with increasingly rigid boundaries between regions. The isolation level used
will depend on your security requirements, and the system resources available
to you.
* **Isolation Level 1** is the lowest isolation level, and the only major
boundary is between the secure and non-secure processing environment,
usually by means of Arm TrustZone on Armv8-M processors. There is no
distinction here between the PSA Updateable Root of Trust (PRoT) and the
Application Root of Trust (ARoT). They execute at the same privilege level.
This isolation level will lead to the smallest combined application images.
* **Isolation Level 2** builds upon level one by introducing a distinction
between the PSA Updateable Root of Trust and the Application Root of Trust,
where ARoT services have limited access to PRoT services, and can only
communicate with them through public APIs exposed by the PRoT services.
ARoT services, however, are not strictly isolated from one another.
* **Isolation Level 3** is the highest isolation level, and builds upon level
2 by isolating ARoT services from each other, so that each ARoT is
essentially silo'ed from other services. This provides the highest level of
isolation, but also comes at the cost of additional overhead and code
duplication between services.
The current isolation level can be checked via
:kconfig:option:`CONFIG_TFM_ISOLATION_LEVEL`.
Secure Boot
===========
The default secure bootloader in TF-M is based on
`MCUBoot <path_to_url`__, and is referred to as ``BL2`` in TF-M
(for the second-stage bootloader, potentially after a HW-based bootloader on
the secure MCU, etc.).
All images in TF-M are hashed and signed, with the hash and signature verified
by MCUBoot during the firmware update process.
Some key features of MCUBoot as used in TF-M are:
* Public signing key(s) are baked into the bootloader
* S and NS images can be signed using different keys
* Firmware images can optionally be encrypted
* Client software is responsible for writing a new image to the secondary slot
* By default, uses static flash layout of two identically-sized memory regions
* Optional security counter for rollback protection
When dealing with (optionally) encrypted images:
* Only the payload is encrypted (header, TLVs are plain text)
* Hashing and signing are applied over the un-encrypted data
* Uses ``AES-CTR-128`` or ``AES-CTR-256`` for encryption
* Encryption key randomized every encryption cycle (via ``imgtool``)
* The ``AES-CTR`` key is included in the image and can be encrypted using:
* ``RSA-OAEP``
* ``AES-KW`` (128 or 256 bits depending on the ``AES-CTR`` key length)
* ``ECIES-P256``
* ``ECIES-X25519``
Key config properties to control secure boot in Zephyr are:
* :kconfig:option:`CONFIG_TFM_BL2` toggles the bootloader (default = ``y``).
* :kconfig:option:`CONFIG_TFM_KEY_FILE_S` overrides the secure signing key.
* :kconfig:option:`CONFIG_TFM_KEY_FILE_NS` overrides the non-secure signing key.
Secure Processing Environment
=============================
Once the secure bootloader has finished executing, a TF-M based secure image
will begin execution in the **secure processing environment**. This is where
our device will be initially configured, and any secure services will be
initialised.
Note that the starting state of our device is controlled by the secure firmware,
meaning that when the non-secure Zephyr application starts, peripherals may
not be in the HW-default reset state. In case of doubts, be sure to consult
the board support packages in TF-M, available in the ``platform/ext/target/``
folder of the TF-M module (which is in ``modules/tee/tf-m/trusted-firmware-m/``
within a default Zephyr west workspace.)
Secure Services
---------------
As of TF-M 1.8.0, the following secure services are generally available (although vendor support may vary):
* Crypto
* Firmware Update (FWU)
* Initial Attestation
* Platform
* Secure Storage, which has two parts:
* Internal Trusted Storage (ITS)
* Protected Storage (PS)
A template also exists for creating your own custom services.
For full details on these services, and their exposed APIs, please consult the
`TF-M Documentation <path_to_url`__.
Key Management and Derivation
-----------------------------
Key and secret management is a critical part of any secure device. You need to
ensure that key material is available to regions that require it, but not to
anything else, and that it is stored securely in a way that makes it difficult
to tamper with or maliciously access.
The **Internal Trusted Storage** service in TF-M is used by the **PSA Crypto**
service (which itself makes use of mbedtls) to store keys, and ensure that
private keys are only ever accessible to the secure processing environment.
Crypto operations that make use of key material, such as when signing payloads
or when decrypting sensitive data, all take place via key handles. At no point
should the key material ever be exposed to the NS environment.
One exception is that private keys can be provisioned into the secure
processing environment as a one-way operation, such as during a factory
provisioning process, but even this should be avoided where possible, and a
request should be made to the SPE (via the PSA Crypto service) to generate a
new private key itself, and the public key for that can be requested during
provisioning and logged in the factory. This ensures the private key
material is never exposed, or even known during the provisioning phase.
TF-M also makes extensive use of the **Hardware Unique Key (HUK)**, which
every TF-M device must provide. This device-unique key is used by the
**Protected Storage** service, for example, to encrypt information stored in
external memory. For example, this ensures that the contents of flash memory
can't be decrypted if they are removed and placed on a new device, since each
device has its own unique HUK used while encrypting the memory contents
the first time.
HUKs provide an additional advantage for developers, in that they can be used
to derive new keys, and the **derived keys** don't need to be stored since
they can be regenerated from the HUK at startup, using an additional salt/seed
value (depending on the key derivation algorithm used). This removes the
storage issue and a frequent attack vector. The HUK itself it usually highly
protected in secure devices, and inaccessible directly by users.
``TFM_CRYPTO_ALG_HUK_DERIVATION`` identifies the default key derivation
algorithm used if a software implementation is used. The current default
algorithm is ``HKDF`` (RFC 5869) with a SHA-256 hash. Other hardware
implementations may be available on some platforms.
Non-Secure Processing Environment
=================================
Zephyr is used for the NSPE, using a board that is supported by TF-M where the
:kconfig:option:`CONFIG_BUILD_WITH_TFM` flag has been enabled.
Generally, you simply need to select the ``*_ns`` variant of a valid target
(for example ``mps2_an521_ns``), which will configure your Zephyr application
to run in the NSPE, correctly build and link it with the TF-M secure images,
sign the secure and non-secure images, and merge the three binaries into a
single ``tfm_merged.hex`` file. The :ref:`west flash <west-flashing>` command
will flash ``tfm_merged.hex`` by default in this configuration.
At present, Zephyr can not be configured to be used as the secure processing
environment.
``` | /content/code_sandbox/doc/services/tfm/overview.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 2,848 |
```restructuredtext
.. _retention_api:
Retention System
################
The retention system provides an API which allows applications to read and
write data from and to memory areas or devices that retain the data while the
device is powered. This allows for sharing information between different
applications or within a single application without losing state information
when a device reboots. The stored data should not persist in the event of a
power failure (or during some low-power modes on some devices) nor should it be
stored to a non-volatile storage like :ref:`flash_api`, :ref:`eeprom_api`, or
battery-backed RAM.
The retention system builds on top of the retained data driver, and adds
additional software-level features to it for ensuring the validity of data.
Optionally, a magic header can be used to check if the front of
the retained data memory section contains this specific value, and an optional
checksum (1, 2, or 4-bytes in size) of the stored data can be appended to the
end of the data. Additionally, the retention system API allows partitioning of
the retained data sections into multiple distinct areas. For example, a 64-byte
retained data area could be split up into 4 bytes for a boot mode, 16 bytes for
a timestamp, 44 bytes for a last log message. All of these sections can be
accessed or updated independently. The prefix and checksum can be set
per-instance using devicetree.
Devicetree setup
****************
To use the retention system, a retained data driver must be setup for the board
you are using, there is a zephyr driver which can be used which will use some
RAM as non-init for this purpose. The retention system is then initialised as a
child node of this device 1 or more times - note that the memory region will
need to be decremented to account for this reserved portion of RAM. See the
following example (examples in this guide are based on the
:ref:`nrf52840dk_nrf52840` board and memory layout):
.. code-block:: devicetree
/ {
sram@2003FC00 {
compatible = "zephyr,memory-region", "mmio-sram";
reg = <0x2003FC00 DT_SIZE_K(1)>;
zephyr,memory-region = "RetainedMem";
status = "okay";
retainedmem {
compatible = "zephyr,retained-ram";
status = "okay";
#address-cells = <1>;
#size-cells = <1>;
/* This creates a 256-byte partition */
retention0: retention@0 {
compatible = "zephyr,retention";
status = "okay";
/* The total size of this area is 256
* bytes which includes the prefix and
* checksum, this means that the usable
* data storage area is 256 - 3 = 253
* bytes
*/
reg = <0x0 0x100>;
/* This is the prefix which must appear
* at the front of the data
*/
prefix = [08 04];
/* This uses a 1-byte checksum */
checksum = <1>;
};
/* This creates a 768-byte partition */
retention1: retention@100 {
compatible = "zephyr,retention";
status = "okay";
/* Start position must be after the end
* of the previous partition. The total
* size of this area is 768 bytes which
* includes the prefix and checksum,
* this means that the usable data
* storage area is 768 - 6 = 762 bytes
*/
reg = <0x100 0x300>;
/* This is the prefix which must appear
* at the front of the data
*/
prefix = [00 11 55 88 fa bc];
/* If omitted, there will be no
* checksum
*/
};
};
};
};
/* Reduce SRAM0 usage by 1KB to account for non-init area */
&sram0 {
reg = <0x20000000 DT_SIZE_K(255)>;
};
The retention areas can then be accessed using the data retention API (once
enabled with :kconfig:option:`CONFIG_RETENTION`, which requires that
:kconfig:option:`CONFIG_RETAINED_MEM` be enabled) by getting the device by
using:
.. code-block:: C
#include <zephyr/device.h>
#include <zephyr/retention/retention.h>
const struct device *retention1 = DEVICE_DT_GET(DT_NODELABEL(retention1));
const struct device *retention2 = DEVICE_DT_GET(DT_NODELABEL(retention2));
When the write function is called, the magic header and checksum (if enabled)
will be set on the area, and it will be marked as valid from that point
onwards.
Mutex protection
****************
Mutex protection of retention areas is enabled by default when applications are
compiled with multithreading support. This means that different threads can
safely call the retention functions without clashing with other concurrent
thread function usage, but means that retention functions cannot be used from
ISRs. It is possible to disable mutex protection globally on all retention
areas by enabling :kconfig:option:`CONFIG_RETENTION_MUTEX_FORCE_DISABLE` -
users are then responsible for ensuring that the function calls do not conflict
with each other. Note that to use this, retention driver mutex support must
also be disabled by enabling
:kconfig:option:`CONFIG_RETAINED_MEM_MUTEX_FORCE_DISABLE`.
.. _boot_mode_api:
Boot mode
*********
An addition to the retention subsystem is a boot mode interface, this can be
used to dynamically change the state of an application or run a different
application with a minimal set of functions when a device is rebooted (an
example is to have a buttonless way of entering mcuboot's serial recovery
feature from the main application).
To use the boot mode feature, a data retention entry must exist in the device
tree, which is dedicated for use as the boot mode selection (the user area data
size only needs to be a single byte), and this area be assigned to the chosen
node of ``zephyr,boot-mode``. See the following example:
.. code-block:: devicetree
/ {
sram@2003FFFF {
compatible = "zephyr,memory-region", "mmio-sram";
reg = <0x2003FFFF 0x1>;
zephyr,memory-region = "RetainedMem";
status = "okay";
retainedmem {
compatible = "zephyr,retained-ram";
status = "okay";
#address-cells = <1>;
#size-cells = <1>;
retention0: retention@0 {
compatible = "zephyr,retention";
status = "okay";
reg = <0x0 0x1>;
};
};
};
chosen {
zephyr,boot-mode = &retention0;
};
};
/* Reduce SRAM0 usage by 1 byte to account for non-init area */
&sram0 {
reg = <0x20000000 0x3FFFF>;
};
The boot mode interface can be enabled with
:kconfig:option:`CONFIG_RETENTION_BOOT_MODE` and then accessed by using the
boot mode functions. If using mcuboot with serial recovery, it can be built
with ``CONFIG_MCUBOOT_SERIAL`` and ``CONFIG_BOOT_SERIAL_BOOT_MODE`` enabled
which will allow rebooting directly into the serial recovery mode by using:
.. code-block:: C
#include <zephyr/retention/bootmode.h>
#include <zephyr/sys/reboot.h>
bootmode_set(BOOT_MODE_TYPE_BOOTLOADER);
sys_reboot(0);
Retention system modules
************************
Modules can expand the functionality of the retention system by using it as a
transport (e.g. between a bootloader and application).
.. toctree::
:maxdepth: 1
blinfo.rst
API Reference
*************
Retention system API
====================
.. doxygengroup:: retention_api
Boot mode interface
===================
.. doxygengroup:: boot_mode_interface
``` | /content/code_sandbox/doc/services/retention/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,820 |
```restructuredtext
.. _blinfo_api:
Bootloader Information
######################
The bootloader information (abbreviated to blinfo) subsystem is an extension of
the :ref:`retention_api` which allows for reading shared data from a bootloader
and allowing applications to query it. It has an optional feature of organising
the information retrieved from the bootloader and storing it in the
:ref:`settings_api` with the ``blinfo/`` prefix.
Devicetree setup
****************
To use the bootloader information subsystem, a retention area needs to be
created which has a retained data section as its parent, generally non-init RAM
is used for this purpose. See the following example (examples in this guide are
based on the :ref:`nrf52840dk_nrf52840` board and memory layout):
.. code-block:: devicetree
/ {
sram@2003F000 {
compatible = "zephyr,memory-region", "mmio-sram";
reg = <0x2003F000 DT_SIZE_K(1)>;
zephyr,memory-region = "RetainedMem";
status = "okay";
retainedmem {
compatible = "zephyr,retained-ram";
status = "okay";
#address-cells = <1>;
#size-cells = <1>;
boot_info0: boot_info@0 {
compatible = "zephyr,retention";
status = "okay";
reg = <0x0 0x100>;
};
};
};
chosen {
zephyr,bootloader-info = &boot_info0;
};
};
/* Reduce SRAM0 usage by 1KB to account for non-init area */
&sram0 {
reg = <0x20000000 DT_SIZE_K(255)>;
};
Note that this configuration needs to be applied on both the bootloader
(MCUboot) and application to be usable. It can be combined with other retention
system APIs such as the :ref:`boot_mode_api`
MCUboot setup
*************
Once the above devicetree configuration is applied, MCUboot needs to be
configured to store the shared data in this area, the following Kconfigs need
to be set for this:
* :kconfig:option:`CONFIG_RETAINED_MEM` - Enables retained memory driver
* :kconfig:option:`CONFIG_RETENTION` - Enables retention system
* :kconfig:option:`CONFIG_BOOT_SHARE_DATA` - Enables shared data
* :kconfig:option:`CONFIG_BOOT_SHARE_DATA_BOOTINFO` - Enables boot information
shared data type
* :kconfig:option:`CONFIG_BOOT_SHARE_BACKEND_RETENTION` - Stores shared data
using retention/blinfo subsystem
Application setup
*****************
The application must enable the following base Kconfig options for the
bootloader information subsystem to function:
* :kconfig:option:`CONFIG_RETAINED_MEM`
* :kconfig:option:`CONFIG_RETENTION`
* :kconfig:option:`CONFIG_RETENTION_BOOTLOADER_INFO`
* :kconfig:option:`CONFIG_RETENTION_BOOTLOADER_INFO_TYPE_MCUBOOT`
The following include is needed to use the bootloader information subsystem:
.. code-block:: C
#include <zephyr/retention/blinfo.h>
By default, only the lookup function is provided: :c:func:`blinfo_lookup`, the
application can call this to query the information from the bootloader. This
function is enabled by default with
:kconfig:option:`CONFIG_RETENTION_BOOTLOADER_INFO_OUTPUT_FUNCTION`, however,
applications can optionally choose to use the settings storage feature instead.
In this mode, the bootloader information can be queries by using settings keys,
the following Kconfig options need to be enabled for this mode:
* :kconfig:option:`CONFIG_SETTINGS`
* :kconfig:option:`CONFIG_SETTINGS_RUNTIME`
* :kconfig:option:`CONFIG_RETENTION_BOOTLOADER_INFO_OUTPUT_SETTINGS`
This allows the information to be queried via the
:c:func:`settings_runtime_get` function with the following keys:
* ``blinfo/mode`` The mode that MCUboot is configured for
(``enum mcuboot_mode`` value)
* ``blinfo/signature_type`` The signature type MCUboot is configured for
(``enum mcuboot_signature_type`` value)
* ``blinfo/recovery`` The recovery type enabled in MCUboot
(``enum mcuboot_recovery_mode`` value)
* ``blinfo/running_slot`` The running slot, useful for direct-XIP mode to know
which slot to use for an update
* ``blinfo/bootloader_version`` Version of the bootloader
(``struct image_version`` object)
* ``blinfo/max_application_size`` Maximum size of an application (in bytes)
that can be loaded
In addition to the previous include, the following includes are required for
this mode:
.. code-block:: C
#include <bootutil/boot_status.h>
#include <bootutil/image.h>
#include <zephyr/mcuboot_version.h>
#include <zephyr/settings/settings.h>
API Reference
*************
Bootloader information API
==========================
.. doxygengroup:: bootloader_info_interface
``` | /content/code_sandbox/doc/services/retention/blinfo.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,109 |
```html
{% extends "!footer.html" %}
{% block contentinfo %}
<p>
{%- if show_copyright %}
{%- endif %}
{%- if last_updated %}
<span class="lastupdated">
Last generated on {{ last_updated }}.
</span>
{%- endif -%}
</p>
{%- set git_last_updated, sha1 = pagename | git_info | default((None, None), true) %}
{%- if git_last_updated %}
<div class="admonition tip" data-nosnippet>
<p class="admonition-title">
Help us keep our technical documentation accurate and up-to-date!
</p>
<p>
The human-authored contents on this page was last updated on {{ git_last_updated }}.
</p>
<p>
If you find any errors on this page, outdated information, or have any other suggestion for
improving its contents, please consider
<a href="{{ pagename | gh_link_get_open_issue_url(sha1) }}">opening an issue</a>.
</p>
</div>
{%- endif %}
{% endblock %}
``` | /content/code_sandbox/doc/_templates/footer.html | html | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 238 |
```html
{%- extends "!search.html" %}
{%- block scripts %}
{{ super.super() }}
<link rel="stylesheet" href="{{ pathto('_static/css/gcs.css', 1) }}" type="text/css" />
{%- endblock %}
{% block footer %}
{{ super.super() }}
{% endblock %}
{% block body %}
<h2>{{ _('Search Results') }}</h2>
<script async src="path_to_url{{ google_searchengine_id }}">
</script>
<div class="gcse-searchresults-only"></div>
{% endblock %}
``` | /content/code_sandbox/doc/_templates/gsearch.html | html | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 124 |
```html
{# remove from this spot#}
``` | /content/code_sandbox/doc/_templates/versions.html | html | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 9 |
```html
{% extends "!breadcrumbs.html" %}
{% block breadcrumbs %}
<!-- {{ docs_title }} -->
{# parameterize default name "Docs" in breadcrumb via docs_title in conf.py #}
{% if not docs_title %}
{% set docs_title = "Docs" %}
{% endif %}
<li><a href="{{ pathto(master_doc) }}">{{ docs_title }}</a> »</li>
{% for doc in parents %}
<li><a href="{{ doc.link|e }}">{{ doc.title }}</a> »</li>
{% endfor %}
<li>{{ title }}</li>
{% endblock %}
{%- block breadcrumbs_aside %}
<li class="wy-breadcrumbs-aside">
<dark-mode-toggle id="dark-mode-toggle" appearance="toggle" permanent="true"/>
</li>
<li class="wy-breadcrumbs-aside">
{%- if display_gh_links %}
{% set gh_blob_url = pagename | gh_link_get_blob_url %}
{% if gh_blob_url %}
<a href="{{ gh_blob_url }}" class="fa fa-github"> {{ _('Open on GitHub') }}</a>
{% endif %}
{%- set git_last_updated, sha1 = pagename | git_info | default((None, None), true) %}
{%- if sha1 %}
<a href="{{ pagename | gh_link_get_open_issue_url(sha1) }}" class="fa fa-bug">
{{ _('Report an issue with this page')}}
</a>
{% endif %}
{% endif %}
</li>
{%- endblock %}
``` | /content/code_sandbox/doc/_templates/breadcrumbs.html | html | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 334 |
```html
{% extends "!layout.html" %}
{% block document %}
{% if is_release %}
<div class="wy-alert wy-alert-danger" data-nosnippet>
The <a href="/latest/{{ pagename }}.html">latest development version</a>
of this page may be more current than this released {{ version }} version.
</div>
{% else %}
<div class="wy-alert wy-alert-danger" data-nosnippet>
This is the documentation for the latest (main) development branch of
Zephyr. If you are looking for the documentation of previous releases, use
the drop-down list at the bottom of the left panel and select the desired version.
</div>
{% endif %}
{{ super() }}
{% endblock %}
{% block menu %}
<div data-nosnippet>
{% include "zversions.html" %}
{{ super() }}
{% if reference_links %}
<div class="toctree-wrapper compound">
<p class="caption"><span class="caption-text">Reference</span></p>
<ul>
{% for title, url in reference_links.items() %}
<li class="toctree-l1">
<a class="reference internal" href="{{ url }}">{{ title }}</a>
</li>
{% endfor %}
</ul>
</div>
{% endif %}
</div>
{% endblock %}
{% block extrahead %}
<meta name="color-scheme" content="dark light">
{# Light/Dark stylesheets added here due to path_to_url #}
<link rel="stylesheet" href="{{ pathto('_static/css/light.css', 1) }}" type="text/css" media="(prefers-color-scheme: light)"/>
<link rel="stylesheet" href="{{ pathto('_static/css/dark.css', 1) }}" type="text/css" media="(prefers-color-scheme: dark)"/>
{% endblock %}
``` | /content/code_sandbox/doc/_templates/layout.html | html | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 416 |
```html
{#
Override the default searchbox from RTD theme to provide the ability to select a search method
(ex. built-in search, Google Custom Search, ...)
#}
{%- if ('singlehtml' not in builder) %}
<div class="search-container" role="search">
<form id="rtd-search-form" class="wy-form" action="{{ pathto('search') }}" method="get">
<input type="search" name="q" placeholder="{{ _('Search docs') }}"
aria-label="{{ _('Search docs') }}" />
{%- if google_searchengine_id is defined %}
<span id="search-se-settings-icon" class="fa fa-gear" role="button" tabindex="0"
title="Search settings" aria-label="Search settings"
aria-haspopup="true" aria-controls="search-se-menu" aria-expanded="false"
onclick="toggleSearchEngineSettingsMenu()">
</span>
<div id="search-se-menu" role="menu" aria-labelledby="search-se-settings-icon">
<ul>
<li id="search-se-menuitem-sphinx" role="menuitemradio" tabindex="-1"
aria-label="Built-in search" onclick="switchSearchEngine('sphinx')">
Built-in search <span class="fa fa-check">
</li>
<li id="search-se-menuitem-google" role="menuitemradio" tabindex="-1"
aria-label="Google search" onclick="switchSearchEngine('google')">
Google search <span class="fa fa-check">
</li>
</div>
{%- endif %}
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
{%- if google_searchengine_id is defined %}
<script>
(function () {
var form = document.getElementById("rtd-search-form");
var searchMenu = document.getElementById("search-se-menu");
var isBrowsingLatest = window.location.pathname.startsWith("/latest");
var preferenceKey = "search-se-" + (isBrowsingLatest ? "latest" : "default");
var query = new URLSearchParams(window.location.search).get("q");
if (query !== null) {
form.q.value = query;
form.q.focus();
}
// Load the saved search preference. Defaults to Google when browsing "/latest" documentation,
// built-in Sphinx search otherwise.
var engine = localStorage.getItem(preferenceKey);
if (engine === null) {
engine = isBrowsingLatest ? "google" : "sphinx";
}
setActiveSearchEngine(engine);
setSearchEngineSettingsMenuVisibility = function (visible) {
searchMenu.style.display = visible ? "block" : "none";
document
.getElementById("search-se-settings-icon")
.setAttribute("aria-expanded", visible ? "true" : "false");
};
window.toggleSearchEngineSettingsMenu = function () {
isVisible = searchMenu.style.display === "block";
setSearchEngineSettingsMenuVisibility(!isVisible);
};
function setActiveSearchEngine(engine) {
if(engine === "sphinx") {
form.action = "{{ pathto('search') }}";
form.q.placeholder = "Search docs (built-in search)";
} else {
form.action = "{{ pathto('gsearch') }}";
form.q.placeholder = "Search docs (powered by Google)";
}
var selectedElement = document.getElementById("search-se-menuitem-" + engine);
var otherElement = document.getElementById(
"search-se-menuitem-" + (engine === "sphinx" ? "google" : "sphinx")
);
selectedElement.classList.add("selected");
selectedElement.setAttribute("aria-checked", "true");
otherElement.classList.remove("selected");
otherElement.setAttribute("aria-checked", "false");
}
window.switchSearchEngine = function (engine) {
setActiveSearchEngine(engine);
localStorage.setItem(preferenceKey, engine);
setSearchEngineSettingsMenuVisibility(false);
form.q.focus();
if (form.q.value !== "") {
form.submit();
}
};
// Close the dropdown if the user clicks outside of it
window.onclick = function (event) {
if (!event.target.matches("#search-se-settings-icon")) {
if (searchMenu.style.display === "block") {
setSearchEngineSettingsMenuVisibility(false);
}
}
};
document.addEventListener("keydown", function (event) {
if(searchMenu.style.display === "none") return;
let menuItems = document.querySelectorAll('[role="menuitemradio"]');
let currentIndex = Array.from(menuItems).findIndex((item) => item === document.activeElement);
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
let nextIndex = event.key === "ArrowDown" ? currentIndex + 1 : currentIndex - 1;
if (nextIndex >= menuItems.length) nextIndex = 0;
if (nextIndex < 0) nextIndex = menuItems.length - 1;
menuItems[nextIndex].focus();
event.preventDefault();
} else if (event.key === "Enter") {
let activeItem = document.activeElement;
if (activeItem && activeItem.getAttribute("role") === "menuitemradio") {
activeItem.click();
event.preventDefault();
}
}
});
})();
</script>
{%- endif %}
{%- endif %}
``` | /content/code_sandbox/doc/_templates/searchbox.html | html | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,147 |
```html
{# Add rst-badge after rst-versions for small badge style. #}
<div class="rst-versions" data-toggle="rst-versions" role="note" aria-label="versions">
<span class="rst-current-version" data-toggle="rst-current-version">
<span class="fa fa-book"> Zephyr Project</span>
v: latest
<span class="fa fa-caret-down"></span>
</span>
<div class="rst-other-versions">
<dl>
<dt>{{ _('Document Release Versions') }}</dt>
{% for slug, url in versions %}
<dd><a href="{{ url }}">{{ slug }}</a></dd>
{% endfor %}
</dl>
<dl>
<dt>{{ _('Downloads') }}</dt>
{% set prefix = current_version if is_release else "latest" %}
<dd><a href="/{{ prefix }}/zephyr.pdf">PDF</a></dd>
</dl>
<dl>
<dt>{{ _('zephyrproject.org Links') }}</dt>
<dd>
<a href="path_to_url">Project Home</a>
</dd>
<dd>
<a href="path_to_url">SDK</a>
</dd>
<dd>
<a href="path_to_url">Releases</a>
</dd>
</dl>
</div>
</div>
``` | /content/code_sandbox/doc/_templates/zversions.html | html | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 304 |
```restructuredtext
.. _hardware_support:
Hardware Support
################
.. toctree::
:maxdepth: 1
arch/index.rst
barriers/index.rst
cache/index.rst
emulator/index.rst
emulator/bus_emulators.rst
peripherals/index.rst
pinctrl/index.rst
porting/index
``` | /content/code_sandbox/doc/hardware/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 75 |
```restructuredtext
.. _zbus:
Zephyr bus (zbus)
#################
..
Note to documentation authors: the diagrams included in this documentation page were designed
using the following Figma library:
path_to_url
The :dfn:`Zephyr bus - zbus` is a lightweight and flexible software bus enabling a simple way for
threads to talk to one another in a many-to-many way.
.. contents::
:local:
:depth: 2
Concepts
********
Threads can send messages to one or more observers using zbus. It makes the many-to-many
communication possible. The bus implements message-passing and publish/subscribe communication
paradigms that enable threads to communicate synchronously or asynchronously through shared memory.
The communication through zbus is channel-based. Threads (or callbacks) use channels to exchange
messages. Additionally, besides other actions, threads can publish and observe channels. When a
thread publishes a message on a channel, the bus will make the message available to all the
published channel's observers. Based on the observer's type, it can access the message directly,
receive a copy of it, or even receive only a reference of the published channel.
The figure below shows an example of a typical application using zbus in which the application logic
(hardware independent) talks to other threads via software bus. Note that the threads are decoupled
from each other because they only use zbus channels and do not need to know each other to talk.
.. figure:: images/zbus_overview.svg
:alt: zbus usage overview
:width: 75%
A typical zbus application architecture.
The bus comprises:
* Set of channels that consists of the control metadata information, and the message itself;
* :dfn:`Virtual Distributed Event Dispatcher` (VDED), the bus logic responsible for sending
notifications/messages to the observers. The VDED logic runs inside the publishing action in the same
thread context, giving the bus an idea of a distributed execution. When a thread publishes to a
channel, it also propagates the notifications to the observers;
* Threads (subscribers and message subscribers) and callbacks (listeners) publishing, reading, and
receiving notifications from the bus.
.. figure:: images/zbus_anatomy.svg
:alt: ZBus anatomy
:width: 70%
ZBus anatomy.
The bus makes the publish, read, claim, finish, notify, and subscribe actions available over
channels. Publishing, reading, claiming, and finishing are available in all RTOS thread contexts,
including ISRs. The publish and read operations are simple and fast; the procedure is channel
locking followed by a memory copy to and from a shared memory region and then a channel unlocking.
Another essential aspect of zbus is the observers. There are three types of observers:
.. figure:: images/zbus_type_of_observers.svg
:alt: ZBus observers type
:width: 70%
ZBus observers.
* Listeners, a callback that the event dispatcher executes every time an observed channel is
published or notified;
* Subscriber, a thread-based observer that relies internally on a message queue where the event
dispatcher puts a changed channel's reference every time an observed channel is published or
notified. Note this kind of observer does not receive the message itself. It should read the
message from the channel after receiving the notification;
* Message subscribers, a thread-based observer that relies internally on a FIFO where the event
dispatcher puts a copy of the message every time an observed channel is published or notified.
Channel observation structures define the relationship between a channel and its observers. For
every observation, a pair channel/observer. Developers can statically allocate observation using the
:c:macro:`ZBUS_CHAN_DEFINE` or :c:macro:`ZBUS_CHAN_ADD_OBS`. There are also runtime observers,
enabling developers to create runtime observations. It is possible to disable an observer entirely
or observations individually. The event dispatcher will ignore disabled observers and observations.
.. figure:: images/zbus_observation_mask.svg
:alt: ZBus observation mask.
:width: 75%
ZBus observation mask.
The above figure illustrates some states, from (a) to (d), for channels from ``C1`` to ``C5``,
``Subscriber 1``, and the observations. The last two are in orange to indicate they are dynamically
allocated (runtime observation). (a) shows that the observer and all observations are enabled. (b)
shows the observer is disabled, so the event dispatcher will ignore it. (c) shows the observer
enabled. However, there is one static observervation disabled. The event dispatcher will only stop
sending notifications from channel ``C3``. In (d), the event dispatcher will stop sending
notifications from channels ``C3`` and ``C5`` to ``Subscriber 1``.
Suppose a usual sensor-based solution is in the figure below for illustration purposes. When
triggered, the timer publishes to the ``Trigger`` channel. As the sensor thread subscribed to the
``Trigger`` channel, it receives the sensor data. Notice the VDED executes the ``Blink`` because it
also listens to the ``Trigger`` channel. When the sensor data is ready, the sensor thread publishes
it to the ``Sensor data`` channel. The core thread receives the message as a ``Sensor data`` channel
message subscriber, processes the sensor data, and stores it in an internal sample buffer. It
repeats until the sample buffer is full; when it happens, the core thread aggregates the sample
buffer information, prepares a package, and publishes that to the ``Payload`` channel. The Lora
thread receives that because it is a ``Payload`` channel message subscriber and sends the payload to
the cloud. When it completes the transmission, the Lora thread publishes to the ``Transmission
done`` channel. The VDED executes the ``Blink`` again since it listens to the ``Transmission done``
channel.
.. figure:: images/zbus_operations.svg
:alt: ZBus sensor-based application
:width: 85%
ZBus sensor-based application.
This way of implementing the solution makes the application more flexible, enabling us to change
things independently. For example, we want to change the trigger from a timer to a button press. We
can do that, and the change does not affect other parts of the system. Likewise, we would like to
change the communication interface from LoRa to Bluetooth; we only need to change the LoRa thread.
No other change is required in order to make that work. Thus, the developer would do that for every
block of the image. Based on that, there is a sign zbus promotes decoupling in the system
architecture.
Another important aspect of using zbus is the reuse of system modules. If a code portion with
well-defined behaviors (we call that module) only uses zbus channels and not hardware interfaces, it
can easily be reused in other solutions. The new solution must implement the interfaces (set of
channels) the module needs to work. That indicates zbus could improve the module reuse.
The last important note is the zbus solution reach. We can count on many ways of using zbus to
enable the developer to be as free as possible to create what they need. For example, messages can
be dynamic or static allocated; notifications can be synchronous or asynchronous; the developer can
control the channel in so many different ways claiming the channel, developers can add their
metadata information to a channel by using the user-data field, the discretionary use of a validator
enables the systems to be accurate over message format, and so on. Those characteristics increase
the solutions that can be done with zbus and make it a good fit as an open-source community tool.
.. _Virtual Distributed Event Dispatcher:
Virtual Distributed Event Dispatcher
====================================
The VDED execution always happens in the publisher's context. It can be a thread or an ISR. Be
careful with publications inside ISR because the scheduler won't preempt the VDED. Use that wisely.
The basic description of the execution is as follows:
* The channel lock is acquired;
* The channel receives the new message via direct copy (by a raw :c:func:`memcpy`);
* The event dispatcher logic executes the listeners, sends a copy of the message to the message
subscribers, and pushes the channel's reference to the subscribers' notification message queue in
the same sequence they appear on the channel observers' list. The listeners can perform non-copy
quick access to the constant message reference directly (via the :c:func:`zbus_chan_const_msg`
function) since the channel is still locked;
* At last, the publishing function unlocks the channel.
To illustrate the VDED execution, consider the example illustrated below. We have four threads in
ascending priority ``S1``, ``MS2``, ``MS1``, and ``T1`` (the highest priority); two listeners,
``L1`` and ``L2``; and channel A. Supposing ``L1``, ``L2``, ``MS1``, ``MS2``, and ``S1`` observer
channel A.
.. figure:: images/zbus_publishing_process_example_scenario.svg
:alt: ZBus example scenario
:width: 45%
ZBus VDED execution example scenario.
The following code implements channel A. Note the ``struct a_msg`` is illustrative only.
.. code-block:: c
ZBUS_CHAN_DEFINE(a_chan, /* Name */
struct a_msg, /* Message type */
NULL, /* Validator */
NULL, /* User Data */
ZBUS_OBSERVERS(L1, L2, MS1, MS2, S1), /* observers */
ZBUS_MSG_INIT(0) /* Initial value {0} */
);
In the figure below, the letters indicate some action related to the VDED execution. The X-axis
represents the time, and the Y-axis represents the priority of threads. Channel A's message,
represented by a voice balloon, is only one memory portion (shared memory). It appears several times
only as an illustration of the message at that point in time.
.. figure:: images/zbus_publishing_process_example.svg
:alt: ZBus publish processing detail
:width: 85%
ZBus VDED execution detail for priority T1 > MS1 > MS2 > S1.
The figure above illustrates the actions performed during the VDED execution when T1 publishes to
channel A. Thus, the table below describes the activities (represented by a letter) of the VDED
execution. The scenario considers the following priorities: T1 > MS1 > MS2 > S1. T1 has the highest
priority.
.. list-table:: VDED execution steps in detail for priority T1 > MS1 > MS2 > S1.
:widths: 5 65
:header-rows: 1
* - Actions
- Description
* - a
- T1 starts and, at some point, publishes to channel A.
* - b
- The publishing (VDED) process starts. The VDED locks the channel A.
* - c
- The VDED copies the T1 message to the channel A message.
* - d, e
- The VDED executes L1 and L2 in the respective sequence. Inside the listeners, usually, there
is a call to the :c:func:`zbus_chan_const_msg` function, which provides a direct constant
reference to channel A's message. It is quick, and no copy is needed here.
* - f, g
- The VDED copies the message and sends that to MS1 and MS2 sequentially. Notice the threads
get ready to execute right after receiving the notification. However, they go to a pending
state because they have less priority than T1.
* - h
- The VDED pushes the notification message to the queue of S1. Notice the thread gets ready to
execute right after receiving the notification. However, it goes to a pending state because
it cannot access the channel since it is still locked.
* - i
- VDED finishes the publishing by unlocking channel A. The MS1 leaves the pending state and
starts executing.
* - j
- MS1 finishes execution. The MS2 leaves the pending state and starts executing.
* - k
- MS2 finishes execution. The S1 leaves the pending state and starts executing.
* - l, m, n
- The S1 leaves the pending state since channel A is not locked. It gets in the CPU again and
starts executing. As it did receive a notification from channel A, it performed a channel read
(as simple as lock, memory copy, unlock), continues its execution and goes out of the CPU.
* - o
- S1 finishes its workload.
The figure below illustrates the actions performed during the VDED execution when T1 publishes to
channel A. The scenario considers the following priorities: T1 < MS1 < MS2 < S1.
.. figure:: images/zbus_publishing_process_example2.svg
:alt: ZBus publish processing detail
:width: 85%
ZBus VDED execution detail for priority T1 < MS1 < MS2 < S1.
Thus, the table below describes the activities (represented by a letter) of the VDED execution.
.. list-table:: VDED execution steps in detail for priority T1 < MS1 < MS2 < S1.
:widths: 5 65
:header-rows: 1
* - Actions
- Description
* - a
- T1 starts and, at some point, publishes to channel A.
* - b
- The publishing (VDED) process starts. The VDED locks the channel A.
* - c
- The VDED copies the T1 message to the channel A message.
* - d, e
- The VDED executes L1 and L2 in the respective sequence. Inside the listeners, usually, there
is a call to the :c:func:`zbus_chan_const_msg` function, which provides a direct constant
reference to channel A's message. It is quick, and no copy is needed here.
* - f
- The VDED copies the message and sends that to MS1. MS1 preempts T1 and starts working.
After that, the T1 regain MCU.
* - g
- The VDED copies the message and sends that to MS2. MS2 preempts T1 and starts working.
After that, the T1 regain MCU.
* - h
- The VDED pushes the notification message to the queue of S1.
* - i
- VDED finishes the publishing by unlocking channel A.
* - j, k, l
- The S1 leaves the pending state since channel A is not locked. It gets in the CPU again and
starts executing. As it did receive a notification from channel A, it performs a channel read
(as simple as lock, memory copy, unlock), continues its execution, and goes out the CPU.
HLP priority boost
------------------
ZBus implements the Highest Locker Protocol that relies on the observers' thread priority to
determine a temporary publisher priority. The protocol considers the channel's Highest Observer
Priority (HOP); even if the observer is not waiting for a message on the channel, it is considered
in the calculation. The VDED will elevate the publisher's priority based on the HOP to ensure small
latency and as few preemptions as possible.
.. note::
The priority boost is enabled by default. To deactivate it, you must set the
:kconfig:option:`CONFIG_ZBUS_PRIORITY_BOOST` configuration.
.. warning::
ZBus priority boost does not consider runtime observers on the HOP calculations.
The figure below illustrates the actions performed during the VDED execution when T1 publishes to
channel A. The scenario considers the priority boost feature and the following priorities: T1 < MS1
< MS2 < S1.
.. figure:: images/zbus_publishing_process_example_HLP.svg
:alt: ZBus publishing process details using priority boost.
:width: 85%
ZBus VDED execution detail with priority boost enabled and for priority T1 < MS1 < MS2 < S1.
To properly use the priority boost, attaching the observer to a thread is necessary. When the
subscriber is attached to a thread, it assumes its priority, and the priority boost algorithm will
consider the observer's priority. The following code illustrates the thread-attaching function.
.. code-block:: c
:emphasize-lines: 10
ZBUS_SUBSCRIBER_DEFINE(s1, 4);
void s1_thread(void *ptr1, void *ptr2, void *ptr3)
{
ARG_UNUSED(ptr1);
ARG_UNUSED(ptr2);
ARG_UNUSED(ptr3);
const struct zbus_channel *chan;
zbus_obs_attach_to_thread(&s1);
while (1) {
zbus_sub_wait(&s1, &chan, K_FOREVER);
/* Subscriber implementation */
}
}
K_THREAD_DEFINE(s1_id, CONFIG_MAIN_STACK_SIZE, s1_thread, NULL, NULL, NULL, 2, 0, 0);
On the above code, the :c:func:`zbus_obs_attach_to_thread` will set the ``s1`` observer with
priority two as the thread has that priority. It is possible to reverse that by detaching the
observer using the :c:func:`zbus_obs_detach_from_thread`. Only enabled observers and observations
will be considered on the channel HOP calculation. Masking a specific observation of a channel will
affect the channel HOP.
In summary, the benefits of the feature are:
* The HLP is more effective for zbus than the mutexes priority inheritance;
* No bounded priority inversion will happen among the publisher and the observers;
* No other threads (that are not involved in the communication) with priority between T1 and S1 can
preempt T1, avoiding unbounded priority inversion;
* Message subscribers will wait for the VDED to finish the message delivery process. So the VDED
execution will be faster and more consistent;
* The HLP priority is dynamic and can change in execution;
* ZBus operations can be used inside ISRs;
* The priority boosting feature can be turned off, and plain semaphores can be used as the channel
lock mechanism;
* The Highest Locker Protocol's major disadvantage, the Inheritance-related Priority Inversion, is
acceptable in the zbus scenario since it will ensure a small bus latency.
Limitations
===========
Based on the fact that developers can use zbus to solve many different problems, some challenges
arise. ZBus will not solve every problem, so it is necessary to analyze the situation to be sure
zbus is applicable. For instance, based on the zbus benchmark, it would not be well suited to a
high-speed stream of bytes between threads. The `Pipe` kernel object solves this kind of need.
Delivery guarantees
-------------------
ZBus always delivers the messages to the listeners and message subscribers. However, there are no
message delivery guarantees for subscribers because zbus only sends the notification, but the
message reading depends on the subscriber's implementation. It is possible to increase the delivery
rate by following design tips:
* Keep the listeners quick-as-possible (deal with them as ISRs). If some processing is needed,
consider submitting a work item to a work-queue;
* Try to give producers a high priority to avoid losses;
* Leave spare CPU for observers to consume data produced;
* Consider using message queues or pipes for intensive byte transfers.
.. warning::
ZBus uses :zephyr_file:`include/zephyr/net/buf.h` (network buffers) to exchange data with message
subscribers. Thus, choose carefully the configurations
:kconfig:option:`CONFIG_ZBUS_MSG_SUBSCRIBER_NET_BUF_POOL_SIZE` and
:kconfig:option:`CONFIG_HEAP_MEM_POOL_SIZE`. They are crucial to a proper VDED execution
(delivery guarantee) considering message subscribers. If you want to keep an isolated pool for a
specific set of channels, you can use
:kconfig:option:`CONFIG_ZBUS_MSG_SUBSCRIBER_NET_BUF_POOL_ISOLATION` with a dedicated pool. Look
at the :zephyr:code-sample:`zbus-msg-subscriber` to see the isolation in action.
.. warning::
Subscribers will receive only the reference of the changing channel. A data loss may be perceived
if the channel is published twice before the subscriber reads it. The second publication
overwrites the value from the first. Thus, the subscriber will receive two notifications, but
only the last data is there.
.. _zbus delivery sequence:
Message delivery sequence
-------------------------
The message delivery will follow the precedence:
#. Observers defined in a channel using the :c:macro:`ZBUS_CHAN_DEFINE` (following the definition
sequence);
#. Observers defined using the :c:macro:`ZBUS_CHAN_ADD_OBS` based on the sequence priority
(parameter of the macro);
#. The latest is the runtime observers in the addition sequence using the
:c:func:`zbus_chan_add_obs`.
.. note::
The VDED will ignore all disabled observers or observations.
Usage
*****
ZBus operation depends on channels and observers. Therefore, it is necessary to determine its
message and observers list during the channel definition. A message is a regular C struct; the
observer can be a subscriber (asynchronous), a message subscriber (asynchronous), or a listener
(synchronous).
The following code defines and initializes a regular channel and its dependencies. This channel
exchanges accelerometer data, for example.
.. code-block:: c
struct acc_msg {
int x;
int y;
int z;
};
ZBUS_CHAN_DEFINE(acc_chan, /* Name */
struct acc_msg, /* Message type */
NULL, /* Validator */
NULL, /* User Data */
ZBUS_OBSERVERS(my_listener, my_subscriber,
my_msg_subscriber), /* observers */
ZBUS_MSG_INIT(.x = 0, .y = 0, .z = 0) /* Initial value */
);
void listener_callback_example(const struct zbus_channel *chan)
{
const struct acc_msg *acc;
if (&acc_chan == chan) {
acc = zbus_chan_const_msg(chan); // Direct message access
LOG_DBG("From listener -> Acc x=%d, y=%d, z=%d", acc->x, acc->y, acc->z);
}
}
ZBUS_LISTENER_DEFINE(my_listener, listener_callback_example);
ZBUS_LISTENER_DEFINE(my_listener2, listener_callback_example);
ZBUS_CHAN_ADD_OBS(acc_chan, my_listener2, 3);
ZBUS_SUBSCRIBER_DEFINE(my_subscriber, 4);
void subscriber_task(void)
{
const struct zbus_channel *chan;
while (!zbus_sub_wait(&my_subscriber, &chan, K_FOREVER)) {
struct acc_msg acc = {0};
if (&acc_chan == chan) {
// Indirect message access
zbus_chan_read(&acc_chan, &acc, K_NO_WAIT);
LOG_DBG("From subscriber -> Acc x=%d, y=%d, z=%d", acc.x, acc.y, acc.z);
}
}
}
K_THREAD_DEFINE(subscriber_task_id, 512, subscriber_task, NULL, NULL, NULL, 3, 0, 0);
ZBUS_MSG_SUBSCRIBER_DEFINE(my_msg_subscriber);
static void msg_subscriber_task(void *ptr1, void *ptr2, void *ptr3)
{
ARG_UNUSED(ptr1);
ARG_UNUSED(ptr2);
ARG_UNUSED(ptr3);
const struct zbus_channel *chan;
struct acc_msg acc = {0};
while (!zbus_sub_wait_msg(&my_msg_subscriber, &chan, &acc, K_FOREVER)) {
if (&acc_chan == chan) {
LOG_INF("From msg subscriber -> Acc x=%d, y=%d, z=%d", acc.x, acc.y, acc.z);
}
}
}
K_THREAD_DEFINE(msg_subscriber_task_id, 1024, msg_subscriber_task, NULL, NULL, NULL, 3, 0, 0);
It is possible to add static observers to a channel using the :c:macro:`ZBUS_CHAN_ADD_OBS`. We call
that a post-definition static observer. The command enables us to indicate an initialization
priority that affects the observers' initialization order. The sequence priority param only affects
the post-definition static observers. There is no possibility to overwrite the message delivery
sequence of the static observers.
.. note::
It is unnecessary to claim/lock a channel before accessing the message inside the listener since
the event dispatcher calls listeners with the notifying channel already locked. Subscribers,
however, must claim/lock that or use regular read operations to access the message after being
notified.
Channels can have a `validator function` that enables a channel to accept only valid messages.
Publish attempts invalidated by hard channels will return immediately with an error code. This
allows original creators of a channel to exert some authority over other developers/publishers who
may want to piggy-back on their channels. The following code defines and initializes a :dfn:`hard
channel` and its dependencies. Only valid messages can be published to a :dfn:`hard channel`. It is
possible because a `validator function` was passed to the channel's definition. In this example,
only messages with ``move`` equal to 0, -1, and 1 are valid. Publish function will discard all other
values to ``move``.
.. code-block:: c
struct control_msg {
int move;
};
bool control_validator(const void* msg, size_t msg_size) {
const struct control_msg* cm = msg;
bool is_valid = (cm->move == -1) || (cm->move == 0) || (cm->move == 1);
return is_valid;
}
static int message_count = 0;
ZBUS_CHAN_DEFINE(control_chan, /* Name */
struct control_msg, /* Message type */
control_validator, /* Validator */
&message_count, /* User data */
ZBUS_OBSERVERS_EMPTY, /* observers */
ZBUS_MSG_INIT(.move = 0) /* Initial value */
);
The following sections describe in detail how to use zbus features.
.. _publishing to a channel:
Publishing to a channel
=======================
Messages are published to a channel in zbus by calling :c:func:`zbus_chan_pub`. For example, the
following code builds on the examples above and publishes to channel ``acc_chan``. The code is
trying to publish the message ``acc1`` to channel ``acc_chan``, and it will wait up to one second
for the message to be published. Otherwise, the operation fails. As can be inferred from the code
sample, it's OK to use stack allocated messages since VDED copies the data internally.
.. code-block:: c
struct acc_msg acc1 = {.x = 1, .y = 1, .z = 1};
zbus_chan_pub(&acc_chan, &acc1, K_SECONDS(1));
.. warning::
Only use this function inside an ISR with a :c:macro:`K_NO_WAIT` timeout.
.. _reading from a channel:
Reading from a channel
======================
Messages are read from a channel in zbus by calling :c:func:`zbus_chan_read`. So, for example, the
following code tries to read the channel ``acc_chan``, which will wait up to 500 milliseconds to
read the message. Otherwise, the operation fails.
.. code-block:: c
struct acc_msg acc = {0};
zbus_chan_read(&acc_chan, &acc, K_MSEC(500));
.. warning::
Only use this function inside an ISR with a :c:macro:`K_NO_WAIT` timeout.
.. warning::
Choose the timeout of :c:func:`zbus_chan_read` after receiving a notification from
:c:func:`zbus_sub_wait` carefully because the channel will always be unavailable during the VDED
execution. Using ``K_NO_WAIT`` for reading is highly likely to return a timeout error if there
are more than one subscriber. For example, consider the VDED illustration again and notice how
``S1`` read attempts would definitely fail with K_NO_WAIT. For more details, check
the `Virtual Distributed Event Dispatcher`_ section.
Notifying a channel
===================
It is possible to force zbus to notify a channel's observers by calling :c:func:`zbus_chan_notify`.
For example, the following code builds on the examples above and forces a notification for the
channel ``acc_chan``. Note this can send events with no message, which does not require any data
exchange. See the code example under `Claim and finish a channel`_ where this may become useful.
.. code-block:: c
zbus_chan_notify(&acc_chan, K_NO_WAIT);
.. warning::
Only use this function inside an ISR with a :c:macro:`K_NO_WAIT` timeout.
Declaring channels and observers
================================
For accessing channels or observers from files other than its defining files, it is necessary to
declare them by calling :c:macro:`ZBUS_CHAN_DECLARE` and :c:macro:`ZBUS_OBS_DECLARE`. In other
words, zbus channel definitions and declarations with the same channel names in different files
would point to the same (global) channel. Thus, developers should be careful about existing
channels, and naming new channels or linking will fail. It is possible to declare more than one
channel or observer on the same call. The following code builds on the examples above and displays
the defined channels and observers.
.. code-block:: c
ZBUS_OBS_DECLARE(my_listener, my_subscriber);
ZBUS_CHAN_DECLARE(acc_chan, version_chan);
Iterating over channels and observers
=====================================
ZBus subsystem also implements :ref:`Iterable Sections <iterable_sections_api>` for channels and
observers, for which there are supporting APIs like :c:func:`zbus_iterate_over_channels`,
:c:func:`zbus_iterate_over_channels_with_user_data`, :c:func:`zbus_iterate_over_observers` and
:c:func:`zbus_iterate_over_observers_with_user_data`. This feature enables developers to call a
procedure over all declared channels, where the procedure parameter is a :c:struct:`zbus_channel`.
The execution sequence is in the alphabetical name order of the channels (see :ref:`Iterable
Sections <iterable_sections_api>` documentation for details). ZBus also implements this feature for
:c:struct:`zbus_observer`.
.. code-block:: c
static bool print_channel_data_iterator(const struct zbus_channel *chan, void *user_data)
{
int *count = user_data;
LOG_INF("%d - Channel %s:", *count, zbus_chan_name(chan));
LOG_INF(" Message size: %d", zbus_chan_msg_size(chan));
LOG_INF(" Observers:");
++(*count);
struct zbus_channel_observation *observation;
for (int16_t i = *chan->observers_start_idx, limit = *chan->observers_end_idx; i < limit;
++i) {
STRUCT_SECTION_GET(zbus_channel_observation, i, &observation);
LOG_INF(" - %s", observation->obs->name);
}
struct zbus_observer_node *obs_nd, *tmp;
SYS_SLIST_FOR_EACH_CONTAINER_SAFE(chan->observers, obs_nd, tmp, node) {
LOG_INF(" - %s", obs_nd->obs->name);
}
return true;
}
static bool print_observer_data_iterator(const struct zbus_observer *obs, void *user_data)
{
int *count = user_data;
LOG_INF("%d - %s %s", *count, obs->queue ? "Subscriber" : "Listener", zbus_obs_name(obs));
++(*count);
return true;
}
int main(void)
{
int count = 0;
LOG_INF("Channel list:");
zbus_iterate_over_channels_with_user_data(print_channel_data_iterator, &count);
count = 0;
LOG_INF("Observers list:");
zbus_iterate_over_observers_with_user_data(print_observer_data_iterator, &count);
return 0;
}
The code will log the following output:
.. code-block:: console
D: Channel list:
D: 0 - Channel acc_chan:
D: Message size: 12
D: Observers:
D: - my_listener
D: - my_subscriber
D: 1 - Channel version_chan:
D: Message size: 4
D: Observers:
D: Observers list:
D: 0 - Listener my_listener
D: 1 - Subscriber my_subscriber
.. _Claim and finish a channel:
Advanced channel control
========================
ZBus was designed to be as flexible and extensible as possible. Thus, there are some features
designed to provide some control and extensibility to the bus.
Listeners message access
------------------------
For performance purposes, listeners can access the receiving channel message directly since they
already have the channel locked for it. To access the channel's message, the listener should use the
:c:func:`zbus_chan_const_msg` because the channel passed as an argument to the listener function is
a constant pointer to the channel. The const pointer return type tells developers not to modify the
message.
.. code-block:: c
void listener_callback_example(const struct zbus_channel *chan)
{
const struct acc_msg *acc;
if (&acc_chan == chan) {
acc = zbus_chan_const_msg(chan); // Use this
// instead of zbus_chan_read(chan, &acc, K_MSEC(200))
// or zbus_chan_msg(chan)
LOG_DBG("From listener -> Acc x=%d, y=%d, z=%d", acc->x, acc->y, acc->z);
}
}
User Data
---------
It is possible to pass custom data into the channel's ``user_data`` for various purposes, such as
writing channel metadata. That can be achieved by passing a pointer to the channel definition
macro's ``user_data`` field, which will then be accessible by others. Note that ``user_data`` is
individual for each channel. Also, note that ``user_data`` access is not thread-safe. For
thread-safe access to ``user_data``, see the next section.
Claim and finish a channel
--------------------------
To take more control over channels, two functions were added :c:func:`zbus_chan_claim` and
:c:func:`zbus_chan_finish`. With these functions, it is possible to access the channel's metadata
safely. When a channel is claimed, no actions are available to that channel. After finishing the
channel, all the actions are available again.
.. warning::
Never change the fields of the channel struct directly. It may cause zbus behavior
inconsistencies and scheduling issues.
.. warning::
Only use this function inside an ISR with a :c:macro:`K_NO_WAIT` timeout.
The following code builds on the examples above and claims the ``acc_chan`` to set the ``user_data``
to the channel. Suppose we would like to count how many times the channels exchange messages. We
defined the ``user_data`` to have the 32 bits integer. This code could be added to the listener code
described above.
.. code-block:: c
if (!zbus_chan_claim(&acc_chan, K_MSEC(200))) {
int *message_counting = (int *) zbus_chan_user_data(&acc_chan);
*message_counting += 1;
zbus_chan_finish(&acc_chan);
}
The following code has the exact behavior of the code in :ref:`publishing to a channel`.
.. code-block:: c
if (!zbus_chan_claim(&acc_chan, K_MSEC(200))) {
struct acc_msg *acc1 = (struct acc_msg *) zbus_chan_msg(&acc_chan);
acc1.x = 1;
acc1.y = 1;
acc1.z = 1;
zbus_chan_finish(&acc_chan);
zbus_chan_notify(&acc_chan, K_SECONDS(1));
}
The following code has the exact behavior of the code in :ref:`reading from a channel`.
.. code-block:: c
if (!zbus_chan_claim(&acc_chan, K_MSEC(200))) {
const struct acc_msg *acc1 = (const struct acc_msg *) zbus_chan_const_msg(&acc_chan);
// access the acc_msg fields directly.
zbus_chan_finish(&acc_chan);
}
Runtime observer registration
-----------------------------
It is possible to add observers to channels in runtime. This feature uses the heap to allocate the
nodes dynamically. The heap size limits the number of dynamic observers zbus can create. Therefore,
set the :kconfig:option:`CONFIG_ZBUS_RUNTIME_OBSERVERS` to enable the feature. It is possible to
adjust the heap size by changing the configuration :kconfig:option:`CONFIG_HEAP_MEM_POOL_SIZE`. The
following example illustrates the runtime registration usage.
.. code-block:: c
ZBUS_LISTENER_DEFINE(my_listener, callback);
// ...
void thread_entry(void) {
// ...
/* Adding the observer to channel chan1 */
zbus_chan_add_obs(&chan1, &my_listener, K_NO_WAIT);
/* Removing the observer from channel chan1 */
zbus_chan_rm_obs(&chan1, &my_listener, K_NO_WAIT);
Samples
*******
For a complete overview of zbus usage, take a look at the samples. There are the following samples
available:
* :zephyr:code-sample:`zbus-hello-world` illustrates the code used above in action;
* :zephyr:code-sample:`zbus-work-queue` shows how to define and use different kinds of observers.
Note there is an example of using a work queue instead of executing the listener as an execution
option;
* :zephyr:code-sample:`zbus-msg-subscriber` illustrates how to use message subscribers;
* :zephyr:code-sample:`zbus-dyn-channel` demonstrates how to use dynamically allocated exchanging
data in zbus;
* :zephyr:code-sample:`zbus-uart-bridge` shows an example of sending the operation of the channel to
a host via serial;
* :zephyr:code-sample:`zbus-remote-mock` illustrates how to implement an external mock (on the host)
to send and receive messages to and from the bus;
* :zephyr:code-sample:`zbus-priority-boost` illustrates zbus priority boost feature with a priority
inversion scenario;
* :zephyr:code-sample:`zbus-runtime-obs-registration` illustrates a way of using the runtime
observer registration feature;
* :zephyr:code-sample:`zbus-confirmed-channel` implements a way of implement confirmed channel only
with subscribers;
* :zephyr:code-sample:`zbus-benchmark` implements a benchmark with different combinations of inputs.
Suggested Uses
**************
Use zbus to transfer data (messages) between threads in one-to-one, one-to-many, and many-to-many
synchronously or asynchronously. Choosing the proper observer type is crucial. Use subscribers for
scenarios that can tolerate message losses and duplications; when they cannot, use message
subscribers (if you need a thread) or listeners (if you need to be lean and fast). In addition to
the listener, another asynchronous message processing mechanism (like :ref:`message queues
<message_queues_v2>`) may be necessary to retain the pending message until it gets processed.
.. note::
ZBus can be used to transfer streams from the producer to the consumer. However, this can
increase zbus' communication latency. So maybe consider a Pipe a good alternative for this
communication topology.
Configuration Options
*********************
For enabling zbus, it is necessary to enable the :kconfig:option:`CONFIG_ZBUS` option.
Related configuration options:
* :kconfig:option:`CONFIG_ZBUS_PRIORITY_BOOST` zbus Highest Locker Protocol implementation;
* :kconfig:option:`CONFIG_ZBUS_CHANNELS_SYS_INIT_PRIORITY` determine the :c:macro:`SYS_INIT`
priority used by zbus to organize the channels observations by channel;
* :kconfig:option:`CONFIG_ZBUS_CHANNEL_NAME` enables the name of channels to be available inside the
channels metadata. The log uses this information to show the channels' names;
* :kconfig:option:`CONFIG_ZBUS_OBSERVER_NAME` enables the name of observers to be available inside
the channels metadata;
* :kconfig:option:`CONFIG_ZBUS_MSG_SUBSCRIBER` enables the message subscriber observer type;
* :kconfig:option:`CONFIG_ZBUS_MSG_SUBSCRIBER_BUF_ALLOC_DYNAMIC` uses the heap to allocate message
buffers;
* :kconfig:option:`CONFIG_ZBUS_MSG_SUBSCRIBER_BUF_ALLOC_STATIC` uses the stack to allocate message
buffers;
* :kconfig:option:`CONFIG_ZBUS_MSG_SUBSCRIBER_NET_BUF_POOL_SIZE` the available number of message
buffers to be used simultaneously;
* :kconfig:option:`CONFIG_ZBUS_MSG_SUBSCRIBER_NET_BUF_POOL_ISOLATION` enables the developer to isolate
a pool for the message subscriber for a set of channels;
* :kconfig:option:`CONFIG_ZBUS_MSG_SUBSCRIBER_NET_BUF_STATIC_DATA_SIZE` the biggest message of zbus
channels to be transported into a message buffer;
* :kconfig:option:`CONFIG_ZBUS_RUNTIME_OBSERVERS` enables the runtime observer registration.
API Reference
*************
.. doxygengroup:: zbus_apis
``` | /content/code_sandbox/doc/services/zbus/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 9,005 |
```restructuredtext
.. _rtc_api:
Real-Time Clock (RTC)
#####################
Overview
********
.. list-table:: **Glossary**
:widths: 30 80
:header-rows: 1
* - Word
- Definition
* - Real-time clock
- Low power device tracking time using broken-down time
* - Real-time counter
- Low power counter which can be used to track time
* - RTC
- Acronym for real-time clock
An RTC is a low power device which tracks time using broken-down time.
It should not be confused with low-power counters which sometimes share
the same name, acronym, or both.
RTCs are usually optimized for low energy consumption and are usually
kept running even when the system is in a low power state.
RTCs usually contain one or more alarms which can be configured to
trigger at a given time. These alarms are commonly used to wake up the
system from a low power state.
History of RTCs in Zephyr
*************************
RTCs have been supported before this API was created, using the
:ref:`counter_api` API. The unix timestamp was used to convert
between broken-down time and the unix timestamp within the RTC
drivers, which internally used the broken-down time representation.
The disadvantages of this approach were that hardware counters could
not be set to a specific count, requiring all RTCs to use device
specific APIs to set the time, converting from unix time to
broken-down time, unnecessarily in some cases, and some common
features missing, like input clock calibration and the update
callback.
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_RTC`
* :kconfig:option:`CONFIG_RTC_ALARM`
* :kconfig:option:`CONFIG_RTC_UPDATE`
* :kconfig:option:`CONFIG_RTC_CALIBRATION`
API Reference
*************
.. doxygengroup:: rtc_interface
RTC device driver test suite
****************************
The test suite validates the behavior of the RTC device driver. It
is designed to be portable between boards. It uses the device tree
alias ``rtc`` to designate the RTC device to test.
This test suite tests the following:
* Setting and getting the time.
* RTC Time incrementing correctly.
* Alarms if supported by hardware, with and without callback enabled
* Calibration if supported by hardware.
The calibration test tests a range of values which are printed to the
console to be manually compared. The user must review the set and
gotten values to ensure they are valid.
By default, only the mandatory setting and getting of time is enabled
for testing. To test the optional alarms, update event callback
and clock calibration, these must be enabled by selecting
:kconfig:option:`CONFIG_RTC_ALARM`, :kconfig:option:`CONFIG_RTC_UPDATE`
and :kconfig:option:`CONFIG_RTC_CALIBRATION`.
The following examples build the test suite for the ``native_sim``
board. To build the test suite for a different board, replace the
``native_sim`` board with your board.
To build the test application with the default configuration, testing
only the mandatory features, the following command can be used for
reference:
.. zephyr-app-commands::
:tool: west
:host-os: unix
:board: native_sim
:zephyr-app: tests/drivers/rtc/rtc_api
:goals: build
To build the test with additional RTC features enabled, use menuconfig
to enable the additional features by updating the configuration. The
following command can be used for reference:
.. zephyr-app-commands::
:tool: west
:host-os: unix
:board: native_sim
:zephyr-app: tests/drivers/rtc/rtc_api
:goals: menuconfig
Then build the test application using the following command:
.. zephyr-app-commands::
:tool: west
:host-os: unix
:board: native_sim
:zephyr-app: tests/drivers/rtc/rtc_api
:maybe-skip-config:
:goals: build
To run the test suite, flash and run the application on your board, the output will
be printed to the console.
.. note::
The tests take up to 30 seconds each if they are testing real hardware.
.. _rtc_api_emul_dev:
RTC emulated device
*******************
The emulated RTC device fully implements the RTC API, and will behave like a real
RTC device, with the following limitations:
* RTC time is not persistent across application initialization.
* RTC alarms are not persistent across application initialization.
* RTC time will drift over time.
Every time an application is initialized, the RTC's time and alarms are reset. Reading
the time using :c:func:`rtc_get_time` will return ``-ENODATA``, until the time is
set using :c:func:`rtc_set_time`. The RTC will then behave as a real RTC, until the
application is reset.
The emulated RTC device driver is built for the compatible
:dtcompatible:`zephyr,rtc-emul` and will be included if :kconfig:option:`CONFIG_RTC`
is selected.
``` | /content/code_sandbox/doc/hardware/peripherals/rtc.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,094 |
```restructuredtext
.. _pinctrl-guide:
Pin Control
###########
This is a high-level guide to pin control. See :ref:`pinctrl_api` for API
reference material.
Introduction
************
The hardware blocks that control pin multiplexing and pin configuration
parameters such as pin direction, pull-up/down resistors, etc. are named **pin
controllers**. The pin controller's main users are SoC hardware peripherals,
since the controller enables exposing peripheral signals, like for example,
map ``I2C0`` ``SDA`` signal to pin ``PX0``. Not only that, but it usually allows
configuring certain pin settings that are necessary for the correct functioning
of a peripheral, for example, the slew-rate depending on the operating
frequency. The available configuration options are vendor/SoC dependent and can
range from simple pull-up/down options to more advanced settings such as
debouncing, low-power modes, etc.
The way pin control is implemented in hardware is vendor/SoC specific. It is
common to find a *centralized* approach, that is, all pin configuration
parameters are controlled by a single hardware block (typically named pinmux),
including signal mapping. The figure below illustrates this
approach. ``PX0`` can be mapped to ``UART0_TX``, ``I2C0_SCK`` or ``SPI0_MOSI``
depending on the ``AF`` control bits. Other configuration parameters such as
pull-up/down are controlled in the same block via ``CONFIG`` bits. This model is
used by several SoC families, such as many from NXP and STM32.
.. figure:: images/hw-cent-control.svg
Example of pin control centralized into a single per-pin block
Other vendors/SoCs use a *distributed* approach. In such case, the pin mapping
and configuration are controlled by multiple hardware blocks.
The figure below illustrates a distributed approach where pin
mapping is controlled by peripherals, such as in Nordic nRF SoCs.
.. figure:: images/hw-dist-control.svg
Example pin control distributed between peripheral registers and per-pin block
From a user perspective, there is no difference in pin controller usage
regardless of the hardware implementation: a user will always apply a state.
The only difference lies in the driver implementation. In general, implementing
a pin controller driver for a hardware that uses a distributed approach requires
more effort, since the driver needs to gather knowledge of peripheral dependent
registers.
Pin control vs. GPIO
====================
Some functionality covered by a pin controller driver overlaps with GPIO
drivers. For example, pull-up/down resistors can usually be enabled by both the
pin control driver and the GPIO driver. In Zephyr context, the pin control
driver purpose is to perform peripheral signal multiplexing and configuration of
other pin parameters required for the correct operation of that peripheral.
Therefore, the main users of the pin control driver are SoC peripherals. In
contrast, GPIO drivers are for general purpose control of a pin, that is, when
its logic level is read or controlled manually.
State model
***********
For a device driver to operate correctly, a certain pin configuration needs to
be applied. Some device drivers require a static configuration, usually set up
at initialization time. Others need to change the configuration at runtime
depending on the operating conditions, for example, to enable a low-power mode
when suspending the device. Such requirements are modeled using **states**, a
concept that has been adapted from the one in the Linux kernel. Each device
driver owns a set of states. Each state has a unique name and contains a full
pin configuration set (see the figure below). This effectively
means that states are independent of each other, so they do not need to be
applied in any specific order. Another advantage of the state model is that it
isolates device drivers from pin configuration.
.. table:: Example pin configuration encoded using the states model
:align: center
+----+------------------+----+------------------+
| ``UART0`` peripheral |
+====+==================+====+==================+
| ``default`` state | ``sleep`` state |
+----+------------------+----+------------------+
| TX | - Pin: PA0 | TX | - Pin: PA0 |
| | - Pull: NONE | | - Pull: NONE |
| | - Low Power: NO | | - Low Power: YES |
+----+------------------+----+------------------+
| RX | - Pin: PA1 | RX | - Pin: PA1 |
| | - Pull: UP | | - Pull: NONE |
| | - Low Power: NO | | - Low Power: YES |
+----+------------------+----+------------------+
Standard states
===============
The name assigned to pin control states or the number of them is up to the
device driver requirements. In many cases a single state applied at
initialization time will be sufficient, but in some other cases more will be
required. In order to make things consistent, a naming convention has been
established for the most common use cases. The figure below
details the standardized states and its purpose.
.. table:: Standardized state names
:align: center
+-------------+----------------------------------+-------------------------+
| State | Identifier | Purpose |
+-------------+----------------------------------+-------------------------+
| ``default`` | :c:macro:`PINCTRL_STATE_DEFAULT` | State of the pins when |
| | | the device is in |
| | | operational state |
+-------------+----------------------------------+-------------------------+
| ``sleep`` | :c:macro:`PINCTRL_STATE_SLEEP` | State of the pins when |
| | | the device is in low |
| | | power or sleep modes |
+-------------+----------------------------------+-------------------------+
Note that other standard states could be introduced in the future.
Custom states
=============
Some device drivers may require using custom states beyond the standard ones. To
achieve that, the device driver needs to have in its scope definitions for the
custom state identifiers named as ``PINCTRL_STATE_{STATE_NAME}``, where
``{STATE_NAME}`` is the capitalized state name. For example, if ``mystate`` has
to be supported, a definition named ``PINCTRL_STATE_MYSTATE`` needs to be
in the driver's scope.
.. note::
It is important that custom state identifiers start from
:c:macro:`PINCTRL_STATE_PRIV_START`
If custom states need to be accessed from outside the driver, for example to
perform dynamic pin control, custom identifiers should be placed in a header
that is publicly accessible.
Skipping states
===============
In most situations, the states defined in Devicetree will be the ones used in
the compiled firmware. However, there are some cases where certain states will
be conditionally used depending on a compilation flag. A typical case is the
``sleep`` state. This state is only used in practice if
:kconfig:option:`CONFIG_PM` or :kconfig:option:`CONFIG_PM_DEVICE` is enabled.
If a firmware variant without these power management configurations is needed,
one should in theory remove the ``sleep`` state from Devicetree to not waste ROM
space storing such unused state.
States can be skipped by the ``pinctrl`` Devicetree macros if a definition named
``PINCTRL_SKIP_{STATE_NAME}`` expanding to ``1`` is present when pin control
configuration is defined. In case of the ``sleep`` state, the ``pinctrl`` API
already provides such definition conditional to the availability of device power
management:
.. code-block:: c
#if !defined(CONFIG_PM) && !defined(CONFIG_PM_DEVICE)
/** Out of power management configurations, ignore "sleep" state. */
#define PINCTRL_SKIP_SLEEP 1
#endif
Dynamic pin control
*******************
Dynamic pin control refers to the capability of changing pin configuration
at runtime. This feature can be useful in situations where the same firmware
needs to run onto slightly different boards, each having a peripheral routed at
a different set of pins. This feature can be enabled by setting
:kconfig:option:`CONFIG_PINCTRL_DYNAMIC`.
.. note::
Dynamic pin control should only be used on devices that have not been
initialized. Changing pin configurations while a device is operating may
lead to unexpected behavior. Since Zephyr does not support device
de-initialization yet, this functionality should only be used during early
boot stages.
One of the effects of enabling dynamic pin control is that
:c:struct:`pinctrl_dev_config` will be stored in RAM instead of ROM (not states
or pin configurations, though). The user can then use
:c:func:`pinctrl_update_states` to update the states stored in
:c:struct:`pinctrl_dev_config` with a new set. This effectively means that the
device driver will apply the pin configurations stored in the updated states
when it applies a state.
Devicetree representation
*************************
Because Devicetree is meant to describe hardware, it is the natural choice when
it comes to storing pin control configuration. In the following sections you
will find an overview on how states and pin configurations are represented in
Devicetree.
States
======
Given a device, each of its pin control state is represented in Devicetree by
``pinctrl-N`` properties, being ``N`` the state index starting from zero. The
``pinctrl-names`` property is then used to assign a unique identifier for each
state property by index, for example, ``pinctrl-names`` list entry 0 is the name
for ``pinctrl-0``.
.. code-block:: devicetree
periph0: periph@0 {
...
/* state 0 ("default") */
pinctrl-0 = <...>;
...
/* state N ("mystate") */
pinctrl-N = <...>;
/* names for state 0 up to state N */
pinctrl-names = "default", ..., "mystate";
...
};
Pin configuration
=================
There are multiple ways to represent the pin configurations in Devicetree.
However, all end up encoding the same information: the pin multiplexing and the
pin configuration parameters. For example, ``UART_RX`` is mapped to ``PX0`` and
pull-up is enabled. The representation choice largely depends on each
vendor/SoC, so the Devicetree binding files for the pin control drivers are the
best place to look for details.
A popular and versatile option is shown in the example below. One of the
advantages of this choice is the grouping capability based on shared pin
configuration. This allows to reduce the verbosity of the pin control
definitions. Another advantage is that the pin configuration parameters for a
particular state are enclosed in a single Devicetree node.
.. code-block:: devicetree
/* board.dts */
#include "board-pinctrl.dtsi"
&periph0 {
pinctrl-0 = <&periph0_default>;
pinctrl-names = "default";
};
.. code-block:: c
/* vnd-soc-pkgxx.h
* File with valid mappings for a specific package (may be autogenerated).
* This file is optional, but recommended.
*/
...
#define PERIPH0_SIGA_PX0 VNDSOC_PIN(X, 0, MUX0)
#define PERIPH0_SIGB_PY7 VNDSOC_PIN(Y, 7, MUX4)
#define PERIPH0_SIGC_PZ1 VNDSOC_PIN(Z, 1, MUX2)
...
.. code-block:: devicetree
/* board-pinctrl.dtsi */
#include <vnd-soc-pkgxx.h>
&pinctrl {
/* Node with pin configuration for default state */
periph0_default: periph0_default {
group1 {
/* Mappings: PERIPH0_SIGA -> PX0, PERIPH0_SIGC -> PZ1 */
pinmux = <PERIPH0_SIGA_PX0>, <PERIPH0_SIGC_PZ1>;
/* Pins PX0 and PZ1 have pull-up enabled */
bias-pull-up;
};
...
groupN {
/* Mappings: PERIPH0_SIGB -> PY7 */
pinmux = <PERIPH0_SIGB_PY7>;
};
};
};
Another popular model is based on having a node for each pin configuration and
state. While this model may lead to shorter board pin control files, it also
requires to have one node for each pin mapping and state, since in general,
nodes can not be re-used for multiple states. This method is discouraged if
autogeneration is not an option.
.. note::
Because all Devicetree information is parsed into a C header, it is important
to make sure its size is kept to a minimum. For this reason it is important
to prefix pre-generated nodes with ``/omit-if-no-ref/``. This prefix makes
sure that the node is discarded when not used.
.. code-block:: devicetree
/* board.dts */
#include "board-pinctrl.dtsi"
&periph0 {
pinctrl-0 = <&periph0_siga_px0_default &periph0_sigb_py7_default
&periph0_sigc_pz1_default>;
pinctrl-names = "default";
};
.. code-block:: devicetree
/* vnd-soc-pkgxx.dtsi
* File with valid nodes for a specific package (may be autogenerated).
* This file is optional, but recommended.
*/
&pinctrl {
/* Mapping for PERIPH0_SIGA -> PX0, to be used for default state */
/omit-if-no-ref/ periph0_siga_px0_default: periph0_siga_px0_default {
pinmux = <VNDSOC_PIN(X, 0, MUX0)>;
};
/* Mapping for PERIPH0_SIGB -> PY7, to be used for default state */
/omit-if-no-ref/ periph0_sigb_py7_default: periph0_sigb_py7_default {
pinmux = <VNDSOC_PIN(Y, 7, MUX4)>;
};
/* Mapping for PERIPH0_SIGC -> PZ1, to be used for default state */
/omit-if-no-ref/ periph0_sigc_pz1_default: periph0_sigc_pz1_default {
pinmux = <VNDSOC_PIN(Z, 1, MUX2)>;
};
};
.. code-block:: devicetree
/* board-pinctrl.dts */
#include <vnd-soc-pkgxx.dtsi>
/* Enable pull-up for PX0 (default state) */
&periph0_siga_px0_default {
bias-pull-up;
};
/* Enable pull-up for PZ1 (default state) */
&periph0_sigc_pz1_default {
bias-pull-up;
};
.. note::
It is discouraged to add pin configuration defaults in pre-defined nodes.
In general, pin configurations depend on the board design or on the
peripheral working conditions, so the decision should be made by the board.
For example, enabling a pull-up by default may not always be desired because
the board already has one or because its value depends on the operating bus
speed. Another downside of defaults is that user may not be aware of them,
for example:
.. code-block:: devicetree
/* not evident that "periph0_siga_px0_default" also implies "bias-pull-up" */
/omit-if-no-ref/ periph0_siga_px0_default: periph0_siga_px0_default {
pinmux = <VNDSOC_PIN(X, 0, MUX0)>;
bias-pull-up;
};
Implementation guidelines
*************************
Pin control drivers
===================
Pin control drivers need to implement a single function:
:c:func:`pinctrl_configure_pins`. This function receives an array of pin
configurations that need to be applied. Furthermore, if
:kconfig:option:`CONFIG_PINCTRL_STORE_REG` is set, it also receives the associated
device register address for the given pins. This information may be required by
some drivers to perform device specific actions.
The pin configuration is stored in an opaque type that is vendor/SoC dependent:
``pinctrl_soc_pin_t``. This type needs to be defined in a header named
``pinctrl_soc.h`` file that is in the Zephyr's include path. It can range from
a simple integer value to a struct with multiple fields. ``pinctrl_soc.h`` also
needs to define a macro named ``Z_PINCTRL_STATE_PINS_INIT`` that accepts two
arguments: a node identifier and a property name (``pinctrl-N``). With this
information the macro needs to define an initializer for all pin configurations
contained within the ``pinctrl-N`` property of the given node.
Regarding Devicetree pin configuration representation, vendors can decide which
option is better for their devices. However, the following guidelines should be
followed:
- Use ``pinctrl-N`` (N=0, 1, ...) and ``pinctrl-names`` properties to define pin
control states. These properties are defined in
:file:`dts/bindings/pinctrl/pinctrl-device.yaml`.
- Use standard pin configuration properties as defined in
:file:`dts/bindings/pinctrl/pincfg-node.yaml`.
Representations not following these guidelines may be accepted if they are
already used by the same vendor in other operating systems, e.g. Linux.
Device drivers
==============
In this section you will find some tips on how a device driver should use the
``pinctrl`` API to successfully configure the pins it needs.
The device compatible needs to be modified in the corresponding binding so that
the ``pinctrl-device.yaml`` is included. For example:
.. code-block:: yaml
include: [base.yaml, pinctrl-device.yaml]
This file is needed to add ``pinctrl-N`` and ``pinctrl-names`` properties to the
device.
From a device driver perspective there are two steps that need to be performed
to be able to use the ``pinctrl`` API. First, the pin control configuration
needs to be defined. This includes all states and pins.
:c:macro:`PINCTRL_DT_DEFINE` or :c:macro:`PINCTRL_DT_INST_DEFINE` macros
should be used for this purpose. Second, a reference to
the device instance :c:struct:`pinctrl_dev_config` needs to be stored, since it
is required to later use the API. This can be achieved using the
:c:macro:`PINCTRL_DT_DEV_CONFIG_GET` and
:c:macro:`PINCTRL_DT_INST_DEV_CONFIG_GET` macros.
It is worth to note that the only relationship between a device and its
associated pin control configuration is based on variable naming conventions.
The way an instance of :c:struct:`pinctrl_dev_config` is named for a
corresponding device instance allows to later obtain a reference to it given the
device's Devicetree node identifier. This allows to minimize ROM usage, since
only devices requiring pin control will own a reference to a pin control
configuration.
Once the driver has defined the pin control configuration and kept a reference
to it, it is ready to use the API. The most common way to apply a state is by
using :c:func:`pinctrl_apply_state`. It is also possible to use the lower level
function :c:func:`pinctrl_apply_state_direct` to skip state lookup if it is
cached in advance (e.g. at init time). Since state lookup time is expected to be
fast, it is recommended to use :c:func:`pinctrl_apply_state`.
The example below contains a complete example of a device driver that uses the
``pinctrl`` API.
.. code-block:: c
/* A driver for the "mydev" compatible device */
#define DT_DRV_COMPAT mydev
...
#include <zephyr/drivers/pinctrl.h>
...
struct mydev_config {
...
/* Reference to mydev pinctrl configuration */
const struct pinctrl_dev_config *pcfg;
...
};
...
static int mydev_init(const struct device *dev)
{
const struct mydev_config *config = dev->config;
int ret;
...
/* Select "default" state at initialization time */
ret = pinctrl_apply_state(config->pcfg, PINCTRL_STATE_DEFAULT);
if (ret < 0) {
return ret;
}
...
}
#define MYDEV_DEFINE(i) \
/* Define all pinctrl configuration for instance "i" */ \
PINCTRL_DT_INST_DEFINE(i); \
... \
static const struct mydev_config mydev_config_##i = { \
... \
/* Keep a ref. to the pinctrl configuration for instance "i" */ \
.pcfg = PINCTRL_DT_INST_DEV_CONFIG_GET(i), \
... \
}; \
... \
\
DEVICE_DT_INST_DEFINE(i, mydev_init, NULL, &mydev_data##i, \
&mydev_config##i, ...);
DT_INST_FOREACH_STATUS_OKAY(MYDEV_DEFINE)
.. _pinctrl_api:
Pin Control API
****************
.. doxygengroup:: pinctrl_interface
Dynamic pin control
====================
.. doxygengroup:: pinctrl_interface_dynamic
Other reference material
************************
- `Introduction to pin muxing and GPIO control under Linux <path_to_url`_
``` | /content/code_sandbox/doc/hardware/pinctrl/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 4,723 |
```restructuredtext
.. _pcie_api:
Peripheral Component Interconnect express Bus (PCIe)
####################################################
Overview
********
API Reference
*************
.. doxygengroup:: pcie_host_interface
``` | /content/code_sandbox/doc/hardware/peripherals/pcie.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 41 |
```restructuredtext
.. _w1_api:
1-Wire Bus
##########
Overview
********
1-Wire is a low speed half-duplex serial bus using only a single wire plus
ground for both data transmission and device power supply.
Similarly to I2C, 1-Wire uses a bidirectional open-collector data line,
and is a single master multidrop bus. This means one master initiates all data
exchanges with the slave devices.
The 1-Wire bus supports longer bus lines than I2C, while it reaches speeds of up
to 15.4 kbps in standard mode and up to 125 kbps in overdrive mode.
Reliable communication in standard speed configuration is possible with 10 nodes
over a bus length of 100 meters. Using overdrive speed, 3 nodes on a bus of
10 meters length are expected to work solid. Optimized timing parameters and
fewer nodes on the bus may allow to reach larger bus extents.
The implementation details are specified in the `BOOK OF IBUTTON STANDARDS`_.
.. figure:: 1-Wire_bus_topology.drawio.svg
:align: center
:alt: 1-Wire bus topology
A typical 1-Wire bus topology
.. _w1-master-api:
W1 Master API
=================
Zephyr's 1-Wire Master API is used to interact with 1-Wire slave devices like
temperature sensors and serial memories.
In Zephyr this API is split into the following layers.
* The link layer handles basic communication functions such as bus reset,
presence detect and bit transfer operations.
It is the only hardware-dependent layer in Zephyr.
This layer is supported by a driver using the Zephyr :ref:`uart_api` interface,
which should work on most Zephyr platforms.
In the future, a GPIO/Timer based driver and hardware specific drivers might
be added.
* The 1-Wire network layer handles all means for slave identification and bus
arbitration.
This includes ROM commands like Match ROM, or Search ROM.
* All slave devices have a unique 64-bit identification number, which
includes a 8-bit `1-Wire Family Code`_ and a 8-bit CRC.
* In order to find slaves on the bus, the standard specifies an search
algorithm which successively detects all slaves on the bus.
This algorithm is described in detail by `Maxim's Applicationnote 187`_.
* Transport layer and Presentation layer functions are not implemented in the
generic 1-Wire driver and therefore must be handled in individual slave drivers.
The 1-Wire API is considered experimental.
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_W1`
* :kconfig:option:`CONFIG_W1_NET`
API Reference
*************
1-Wire data link layer
======================
.. doxygengroup:: w1_data_link
1-Wire network layer
====================
.. doxygengroup:: w1_network
1-Wire generic functions and helpers
====================================
Functions that are not directly related to any of the networking layers.
.. doxygengroup:: w1_interface
.. _BOOK OF IBUTTON STANDARDS:
path_to_url
.. _1-Wire Family Code:
path_to_url
.. _Maxim's Applicationnote 187:
path_to_url
``` | /content/code_sandbox/doc/hardware/peripherals/w1.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 719 |
```restructuredtext
.. _tcpc_api:
USB Type-C Port Controller (TCPC)
#################################
Overview
********
`TCPC <tcpc-specification_>`_ (USB Type-C Port Controller)
The TCPC is a device used to simplify the implementation of a USB-C system
by providing the following three function:
* VBUS and VCONN control `USB Type-C <usb-type-c-specification_>`_:
The TCPC may provide a Source device, the mechanism to control VBUS sourcing,
and a Sink device, the mechanism to control VBUS sinking. A similar mechanism
is provided for the control of VCONN.
* CC control and sensing:
The TCPC implements logic for controlling the CC pin pull-up and pull-down
resistors. It also provides a way to sense and report what resistors are
present on the CC pin.
* Power Delivery message reception and transmission `USB Power Delivery <usb-pd-specification_>`_:
The TCPC sends and receives messages constructed in the TCPM and places them
on the CC lines.
.. _tcpc-api:
TCPC API
========
The TCPC device driver functions as the liaison between the TCPC device and the
application software; this is accomplished by the Zephyr's API provided by the
device driver that's used to communicate with and control the TCPC device.
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_USBC_TCPC_DRIVER`
API Reference
*************
.. doxygengroup:: usb_type_c
.. doxygengroup:: usb_type_c_port_controller_api
.. doxygengroup:: usb_power_delivery
.. _tcpc-specification:
path_to_url
.. _usb-type-c-specification:
path_to_url
.. _usb-pd-specification:
path_to_url
``` | /content/code_sandbox/doc/hardware/peripherals/tcpc.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 387 |
```restructuredtext
.. _espi_api:
Enhanced Serial Peripheral Interface (eSPI) Bus
###############################################
Overview
********
The eSPI (enhanced serial peripheral interface) is a serial bus that is
based on SPI. It also features a four-wire interface (receive, transmit, clock
and target select) and three configurations: single IO, dual IO and quad IO.
The technical advancements include lower voltage signal levels (1.8V vs. 3.3V),
lower pin count, and the frequency is twice as fast (66MHz vs. 33MHz)
Because of its enhancements, the eSPI is used to replace the LPC
(lower pin count) interface, SPI, SMBus and sideband signals.
See `eSPI interface specification`_ for additional details.
API Reference
*************
.. doxygengroup:: espi_interface
.. _eSPI interface specification:
path_to_url
``` | /content/code_sandbox/doc/hardware/peripherals/espi.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 189 |
```restructuredtext
.. _retained_mem_api:
Retained Memory
###############
Overview
********
The retained memory driver API provides a way of reading from/writing to memory
areas whereby the contents of the memory is retained whilst the device is
powered (data may be lost in low power modes).
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_RETAINED_MEM`
* :kconfig:option:`CONFIG_RETAINED_MEM_INIT_PRIORITY`
* :kconfig:option:`CONFIG_RETAINED_MEM_MUTEX_FORCE_DISABLE`
Mutex protection
****************
Mutex protection of retained memory drivers is enabled by default when
applications are compiled with multithreading support. This means that
different threads can safely call the retained memory functions without
clashing with other concurrent thread function usage, but means that retained
memory functions cannot be used from ISRs. It is possible to disable mutex
protection globally on all retained memory drivers by enabling
:kconfig:option:`CONFIG_RETAINED_MEM_MUTEX_FORCE_DISABLE` - users are then
responsible for ensuring that the function calls do not conflict with each
other.
API Reference
*************
.. doxygengroup:: retained_mem_interface
``` | /content/code_sandbox/doc/hardware/peripherals/retained_mem.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 241 |
```restructuredtext
.. _gnss_api:
GNSS (Global Navigation Satellite System)
#########################################
Overview
********
GNSS is a general term which covers satellite systems used for
navigation, like GPS (Global Positioning System). GNSS services
are usually accessed through GNSS modems which receive and
process GNSS signals to determine their position, or more
specifically, their antennas position. They usually
additionally provide a precise time synchronization mechanism,
commonly named PPS (Pulse-Per-Second).
Subsystem support
*****************
The GNSS subsystem is based on the :ref:`modem`. The GNSS
subsystem covers everything from sending and receiving commands
to and from the modem, to parsing, creating and processing
NMEA0183 messages.
Adding support for additional NMEA0183 based GNSS modems
requires little more than implementing power management
and configuration for the specific GNSS modem.
Adding support for GNSS modems which use other protocols and/or
buses than the usual NMEA0183 over UART is possible, but will
require a bit more work from the driver developer.
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_GNSS`
* :kconfig:option:`CONFIG_GNSS_SATELLITES`
* :kconfig:option:`CONFIG_GNSS_DUMP_TO_LOG`
Navigation Reference
********************
.. doxygengroup:: navigation
GNSS API Reference
******************
.. doxygengroup:: gnss_interface
``` | /content/code_sandbox/doc/hardware/peripherals/gnss.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 309 |
```restructuredtext
.. _led_api:
Light-Emitting Diode (LED)
##########################
Overview
********
The LED API provides access to Light Emitting Diodes, both in individual and
strip form.
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_LED`
* :kconfig:option:`CONFIG_LED_STRIP`
API Reference
*************
LED
===
.. doxygengroup:: led_interface
LED Strip
=========
.. doxygengroup:: led_strip_interface
``` | /content/code_sandbox/doc/hardware/peripherals/led.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 106 |
```restructuredtext
.. _adc_api:
Analog-to-Digital Converter (ADC)
#################################
Overview
********
API Reference
*************
.. doxygengroup:: adc_interface
``` | /content/code_sandbox/doc/hardware/peripherals/adc.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 36 |
```restructuredtext
.. _uart_api:
Universal Asynchronous Receiver-Transmitter (UART)
##################################################
Overview
********
Zephyr provides three different ways to access the UART peripheral. Depending
on the method, different API functions are used according to below sections:
1. :ref:`uart_polling_api`
2. :ref:`uart_interrupt_api`
3. :ref:`uart_async_api` using :ref:`dma_api`
Polling is the most basic method to access the UART peripheral. The reading
function, `uart_poll_in`, is a non-blocking function and returns a character
or `-1` when no valid data is available. The writing function,
`uart_poll_out`, is a blocking function and the thread waits until the given
character is sent.
With the Interrupt-driven API, possibly slow communication can happen in the
background while the thread continues with other tasks. The Kernel's
:ref:`kernel_data_passing_api` features can be used to communicate between
the thread and the UART driver.
The Asynchronous API allows to read and write data in the background using DMA
without interrupting the MCU at all. However, the setup is more complex
than the other methods.
.. warning::
Interrupt-driven API and the Asynchronous API should NOT be used at
the same time for the same hardware peripheral, since both APIs require
hardware interrupts to function properly. Using the callbacks for both
APIs would result in interference between each other.
:kconfig:option:`CONFIG_UART_EXCLUSIVE_API_CALLBACKS` is enabled by default
so that only the callbacks associated with one API is active at a time.
Configuration Options
*********************
Most importantly, the Kconfig options define whether the polling API (default),
the interrupt-driven API or the asynchronous API can be used. Only enable the
features you need in order to minimize memory footprint.
Related configuration options:
* :kconfig:option:`CONFIG_SERIAL`
* :kconfig:option:`CONFIG_UART_INTERRUPT_DRIVEN`
* :kconfig:option:`CONFIG_UART_ASYNC_API`
* :kconfig:option:`CONFIG_UART_WIDE_DATA`
* :kconfig:option:`CONFIG_UART_USE_RUNTIME_CONFIGURE`
* :kconfig:option:`CONFIG_UART_LINE_CTRL`
* :kconfig:option:`CONFIG_UART_DRV_CMD`
API Reference
*************
.. doxygengroup:: uart_interface
.. _uart_polling_api:
Polling API
===========
.. doxygengroup:: uart_polling
.. _uart_interrupt_api:
Interrupt-driven API
====================
.. doxygengroup:: uart_interrupt
.. _uart_async_api:
Asynchronous API
================
.. doxygengroup:: uart_async
``` | /content/code_sandbox/doc/hardware/peripherals/uart.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 556 |
```restructuredtext
.. _ipm_api:
Inter-Processor Mailbox (IPM)
#############################
Overview
********
API Reference
*************
.. doxygengroup:: ipm_interface
``` | /content/code_sandbox/doc/hardware/peripherals/ipm.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 38 |
```restructuredtext
.. _regulator_api:
Regulators
##########
This subsystem provides control of voltage and current regulators. A common
example is a GPIO that controls a transistor that supplies current to a device
that is not always needed. Another example is a PMIC, typically a much more
complex device.
The ``*-supply`` devicetree properties are used to identify the regulator(s)
that a devicetree node directly depends on. Within the driver for the node the
regulator API is used to issue requests for power when the device is to be
active, and release the power request when the device shuts down.
The simplest case where a regulator is needed is one where there is only one
client. For those situations the cost of using the regulator device
infrastructure is not justified, and ``*-gpios`` devicetree properties should be
used. There is no device interface to these regulators as they are entirely
controlled within the driver for the corresponding node, e.g. a sensor.
.. _regulator_api_reference:
API Reference
**************
.. doxygengroup:: regulator_interface
``` | /content/code_sandbox/doc/hardware/peripherals/regulators.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 229 |
```restructuredtext
.. _pwm_api:
Pulse Width Modulation (PWM)
############################
Overview
********
API Reference
*************
.. doxygengroup:: pwm_interface
``` | /content/code_sandbox/doc/hardware/peripherals/pwm.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 36 |
```restructuredtext
.. _usb_bc12_api:
BC1.2 Devices (Experimental)
#######################################
The Battery Charging specification, currently at revision 1.2, is commonly
referred to as just BC1.2. BC1.2 defines limits and detection mechanisms for USB
devices to draw current exceeding the USB 2.0 specification limit of 0.5A, 2.5W.
The BC1.2 specification uses the term Charging Port for the device that supplies
VBUS on the USB connection and the term Portable Device for the device that
sinks current from the USB connection.
Note that the `BC1.2 Specification`_ uses the acronym PD for Portable Device. This
should not be confused with the USB-C Power Delivery, which also uses the
acronym PD.
On many devices, BC1.2 is the fallback mechanism to determine the connected
charger capability on USB type C ports when the attached type-C partner does not
support Power Delivery.
Key parameters from the `BC1.2 Specification`_ include:
============================================================ ======== ===========
Parameter Symbol Range
============================================================ ======== ===========
Allowed PD (portable device) Current Draw from Charging Port IDEV_CHG 1.5 A
Charging Downstream Port Rated Current ICDP 1.5 - 5.0 A
Maximum Configured Current when connected to a SDP ICFG_MAX 500 mA
Dedicated Charging Port Rated Current IDCP 1.5 - 5.0 A
Suspend current ISUSP 2.5 mA
Unit load current IUNIT 100 mA
============================================================ ======== ===========
While the ICDP and IDCP rated currents go up to 5.0 A, the BC1.2 current is
limited by the IDEV_CHG parameter. So the BC1.2 support is capped at 1.5 A in
the Zephyr implementation when using portable-device mode.
.. _BC1.2 Specification: path_to_url
Basic Operation
***************
The BC1.2 device driver provides only two APIs, ``bc12_set_role()`` and
``bc12_set_result_cb()``.
The application calls ``bc12_set_role()`` to transition the BC1.2 device to
either a disconnected, portable-device, or charging port mode.
For the disconnected state, the BC1.2 driver powers down the detection chip.
The power down operation is vendor specific.
The application calls ``bc12_set_role()`` with the type set to
BC12_PORTABLE_DEVICE when both the following conditions are true:
* The application configured the port as an upstream facing port, i.e. a USB
device port.
* The application detects VBUS on the USB connection.
For portable-device mode, the BC1.2 driver powers up the detection chip and
starts charger detection. At completion of the charger detection, the BC1.2
driver notifies the callback registered with ``bc12_set_result_cb()``. By
default, the BC1.2 driver clamps the current to 1.5A to comply with the BC1.2
specification.
To comply with the USB 2.0 specification, when the driver detects a SDP
(Standard Downstream Port) charging partner or if BC1.2 detection fails, the
driver reports the available current as ISUSP (2.5 mA). The application may
increase the current draw to IUNIT (100 mA) when the connected USB host resumes
the USB bus and may increase the current draw to ICFG_MAX (500 mA) when the USB
host configures the USB device.
Charging port mode is used by the application when the USB port is configured as
a downstream facing port, i.e. a USB host port. For charging port mode, the
BC1.2 driver powers up the detection chip and configures the charger type
specified by a devicetree property. If the driver supports detection of plug and
unplug events, the BC1.2 driver notifies the callback registered with
``bc12_set_result_cb()`` to indicate the current connection state of the
portable device partner.
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_USB_BC12`
.. _bc12_api_reference:
API Reference
*************
.. doxygengroup:: b12_interface
.. doxygengroup:: b12_emulator_backend
``` | /content/code_sandbox/doc/hardware/peripherals/bc12.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 942 |
```restructuredtext
.. _video_api:
Video
#####
The video driver API offers a generic interface to video devices.
Basic Operation
***************
Video Device
============
A video device is the abstraction of a hardware or software video function,
which can produce, process, consume or transform video data. The video API is
designed to offer flexible way to create, handle and combine various video
devices.
Endpoint
========
Each video device can have one or more endpoints. Output endpoints configure
video output function and generate data. Input endpoints configure video input
function and consume data.
Video Buffer
============
A video buffer provides the transport mechanism for the data. There is no
particular requirement on the content. The requirement for the content is
defined by the endpoint format. A video buffer can be queued to a device
endpoint for filling (input ep) or consuming (output ep) operation, once
the operation is achieved, buffer can be dequeued for post-processing,
release or reuse.
Controls
========
A video control is accessed and identified by a CID (control identifier). It
represents a video control property. Different devices will have different
controls available which can be generic, related to a device class or vendor
specific. The set/get control functions provide a generic scalable interface
to handle and create controls.
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_VIDEO`
API Reference
*************
.. doxygengroup:: video_interface
.. doxygengroup:: video_controls
``` | /content/code_sandbox/doc/hardware/peripherals/video.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 312 |
```restructuredtext
.. _i3c_api:
Improved Inter-Integrated Circuit (I3C) Bus
###########################################
I3C (Improved Inter-Integrated Circuit) is a two-signal shared
peripheral interface bus. Devices on the bus can operate in
two roles: as a "controller" that initiates transactions and
controls the clock, or as a "target" that responds to transaction
commands.
Currently, the API is based on `I3C Specification`_ version 1.1.1.
.. contents::
:local:
:depth: 2
.. _i3c-controller-api:
I3C Controller API
******************
Zephyr's I3C controller API is used when an I3C controller controls
the bus, in particularly the start and stop conditions and the clock.
This is the most common mode, used to interact with I3C target
devices such as sensors.
Due to the nature of the I3C, there are devices on the bus where
they may not have addresses when powered on. Therefore, an additional
dynamic address assignment needs to be carried out by the I3C
controller. Because of this, the controller needs to maintain
separate structures to keep track of device status. This can be done
at build time, for example, by creating arrays of device descriptors
for both I3C and I\ :sup:`2`\ C devices:
.. code-block:: c
static struct i3c_device_desc i3c_device_array[] = I3C_DEVICE_ARRAY_DT_INST(inst);
static struct i3c_i2c_device_desc i2c_device_array[] = I3C_I2C_DEVICE_ARRAY_DT_INST(inst);
The macros :c:macro:`I3C_DEVICE_ARRAY_DT_INST` and
:c:macro:`I3C_I2C_DEVICE_ARRAY_DT_INST` are helper macros to aid in
create arrays of device descriptors corresponding to the devicetree
nodes under the I3C controller.
Here is a list of generic steps for initializing the I3C
controller and the I3C bus inside the device driver
initialization function:
#. Initialize the data structure of the I3C controller device
driver instance. The usual device defining macros such as
:c:macro:`DEVICE_DT_INST_DEFINE` can be used, and the initialization
function provided as a parameter to the macro.
* The :c:struct:`i3c_addr_slots` and :c:struct:`i3c_dev_list` are
structures to aid in address assignments and device list management.
If this is being used, this struct needs to be initialized by calling
:c:func:`i3c_addr_slots_init`. These two structures can also be used
with various helper functions.
* Initialize the device descriptors if needed by the controller
driver.
#. Initialize the hardware, including but not limited to:
* Setup pin mux and directions.
* Setup the clock for the controller.
* Power on the hardware.
* Configure the hardware (e.g. SCL clock frequency).
#. Perform bus initialization. There is a generic helper function,
:c:func:`i3c_bus_init`, which performs the following steps.
This function can be used if the controller does not require
any special handling during bus initialization.
#. Do ``RSTDAA`` to reset dynamic addresses of connected devices.
If any connected devices have already been assigned an address,
the bookkeeping data structures do not have records of these,
for example, at power-on. So it is a good idea to reset and
assign them new addresses.
#. Do ``DISEC`` to disable any events from devices.
#. Do ``SETDASA`` to use static addresses as dynamic address
if so desired.
* ``SETAASA`` may not be supported for all connected devices
to assign static addresses as dynamic addresses.
* BCR and DCR need to be obtained separately to populate
the relevant fields in the I3C target device descriptor
struct.
#. Do ``ENTDAA`` to start dynamic address assignment, if there are
still devices without addresses.
* If there is a device waiting for address, it will send
its Provisioned ID, BCR, and DCR back. Match the received
Provisioned ID to the list of registered I3C devices.
* If there is a match, assign an address (either from
the stated static address if ``SETDASA`` has not been
done, or use a free address).
* Also, set the BCR and DCR fields in the device descriptor
struct.
* If there is no match, depending on policy, it can be
assigned a free address, or the device driver can stop
the assignment process and errors out.
* Note that the I3C API requires device descriptor to
function. A device without a device descriptor cannot be
accessed through the API.
* This step can be skipped if there is no connected devices
requiring DAA.
#. These are optional but highly recommended:
* Do ``GETMRL`` and ``GETMWL`` to get maximum read/write
length.
* Do ``GETMXDS`` to get maximum read/write speed and maximum
read turnaround time.
* The helper function, :c:func:`i3c_bus_init`, would retrieve
basic device information such as BCR, DCR, MRL and MWL.
#. Do ``ENEC`` to re-enable events from devices.
* The helper function, :c:func:`i3c_bus_init`, only re-enables
hot-join events. IBI event should only be enabled when
enabling IBI of a device.
In-Band Interrupt (IBI)
=======================
If a target device can generate In-Band Interrupt (IBI),
the controller needs to be made aware of it.
* :c:func:`i3c_ibi_enable` to enable IBI of a target device.
* Some controller hardware have IBI slots which need to be
programmed so that the controller can recognize incoming IBIs
from a particular target device.
* If the hardware has IBI slots, :c:func:`i3c_ibi_enable`
needs to program those IBI slots.
* Note that there are usually limited IBI slots on
the controller so this operation may fail.
* The implementation in driver should also send the ``ENEC`` command
to enable interrupt of this target device.
* :c:func:`i3c_ibi_disable` to disable IBI of a target device.
* If controller hardware makes use of IBI slots, this will remove
description of the target device from the slots.
* The implementation in driver should also send the ``DISEC`` command
to disable interrupt of this target device.
Device Tree
===========
Here is an example for defining a I3C controller in device tree:
.. code-block:: devicetree
i3c0: i3c@10000 {
compatible = "vendor,i3c";
#address-cells = < 0x3 >;
#size-cells = < 0x0 >;
reg = < 0x10000 0x1000 >;
interrupts = < 0x1F 0x0 >;
pinctrl-0 = < &pinmux-i3c >;
pinctrl-names = "default";
i2c-scl-hz = < 400000 >;
i3c-scl-hz = < 12000000 >;
status = "okay";
i3c-dev0: i3c-dev0@420000ABCD12345678 {
compatible = "vendor,i3c-dev";
reg = < 0x42 0xABCD 0x12345678 >;
status = "okay";
};
i2c-dev0: i2c-dev0@380000000000000050 {
compatible = "vendor-i2c-dev";
reg = < 0x38 0x0 0x50 >;
status = "okay";
};
};
I3C Devices
-----------
For I3C devices, the ``reg`` property has 3 elements:
* The first one is the static address of the device.
* Can be zero if static address is not used. Address will be
assigned during DAA (Dynamic Address Assignment).
* If non-zero and property ``assigned-address`` is not set,
this will be the address of the device after SETDASA
(Set Dynamic Address from Static Address) is issued.
* Second element is the upper 16-bit of the Provisioned ID (PID)
which contains the manufacturer ID left-shifted by 1. This is
the bits 33-47 (zero-based) of the 48-bit Provisioned ID.
* Third element contains the lower 32-bit of the Provisioned ID
which is a combination of the part ID (left-shifted by 16,
bits 16-31 of the PID) and the instance ID (left-shifted by 12,
bits 12-15 of the PID).
Note that the unit-address (the part after ``@``) must match
the ``reg`` property fully where each element is treated as
32-bit integer, combining to form a 96-bit integer. This is
required for properly generating device tree macros.
I\ :sup:`2`\ C Devices
----------------------
For I\ :sup:`2`\ C devices where the device driver has support for
working under I3C bus, the device node can be described as
a child of the I3C controller. If the device driver is written to
only work with I\ :sup:`2`\ C controllers, define the node under
the I\ :sup:`2`\ C virtual controller as described below.
Otherwise, the ``reg`` property, similar to I3C devices,
has 3 elements:
* The first one is the static address of the device. This must be
a valid address as I\ :sup:`2`\ C devices do not support
dynamic address assignment.
* Second element is always zero.
* This is used by various helper macros to determine whether
the device tree entry corresponds to a I\ :sup:`2`\ C device.
* Third element is the LVR (Legacy Virtual Register):
* bit[31:8] are unused.
* bit[7:5] are the I\ :sup:`2`\ C device index:
* Index ``0``
* I3C device has a 50 ns spike filter where it is not
affected by high frequency on SCL.
* Index ``1``
* I\ :sup:`2`\ C device does not have a 50 ns spike filter but
can work with high frequency on SCL.
* Index ``2``
* I3C device does not have a 50 ns spike filter and
cannot work with high frequency on SCL.
* bit[4] is the I\ :sup:`2`\ C mode indicator:
* ``0`` is FM+ mode.
* ``1`` is FM mode.
Similar to I3C devices, the unit-address must match the ``reg``
property fully where each element is treated as 32-bit integer,
combining to form a 96-bit integer.
Device Drivers for I3C Devices
==============================
All of the transfer functions of I3C controller API require
the use of device descriptors, :c:struct:`i3c_device_desc`.
This struct contains runtime information about a I3C device,
such as, its dynamic address, BCR, DCR, MRL and MWL. Therefore,
the device driver of a I3C device should grab a pointer to
this device descriptor from the controller using
:c:func:`i3c_device_find`. This function takes an ID parameter
of type :c:struct:`i3c_device_id` for matching. The returned
pointer can then be used in subsequent API calls to
the controller.
I\ :sup:`2`\ C Devices under I3C Bus
====================================
Since I3C is backward compatible with I\ :sup:`2`\ C, the I3C controller
API can accommodate I2C API calls without modifications if the controller
device driver implements the I2C API. This has the advantage of using
existing I2C devices without any modifications to their device drivers.
However, since the I3C controller API works on device descriptors,
any calls to I2C API will need to look up the corresponding device
descriptor from the I2C device address. This adds a bit of processing
cost to any I2C API calls.
On the other hand, a device driver can be extended to utilize native
I2C device support via the I3C controller API. During device
initialization, :c:func:`i3c_i2c_device_find` needs to be called to
retrieve the pointer to the device descriptor. This pointer can be used
in subsequent API calls.
Note that, with either methods mentioned above, the devicetree node of
the I2C device must be declared according to I3C standard:
The I\ :sup:`2`\ C virtual controller device driver provides a way to
interface I\ :sup:`2`\ C devices on the I3C bus where the associated
device drivers can be used as-is without modifications. This requires
adding an intermediate node in the device tree:
.. code-block:: devicetree
i3c0: i3c@10000 {
<... I3C controller related properties ...>
<... Nodes of I3C devices, if any ...>
i2c-dev0: i2c-dev0@420000000000000050 {
compatible = "vendor-i2c-dev";
reg = < 0x42 0x0 0x50 >;
status = "okay";
};
};
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_I3C`
* :kconfig:option:`CONFIG_I3C_USE_GROUP_ADDR`
* :kconfig:option:`CONFIG_I3C_USE_IBI`
* :kconfig:option:`CONFIG_I3C_IBI_MAX_PAYLOAD_SIZE`
* :kconfig:option:`CONFIG_I3C_CONTROLLER_INIT_PRIORITY`
API Reference
*************
.. doxygengroup:: i3c_interface
.. doxygengroup:: i3c_ccc
.. doxygengroup:: i3c_addresses
.. doxygengroup:: i3c_target_device
.. _I3C Specification: path_to_url
``` | /content/code_sandbox/doc/hardware/peripherals/i3c.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 3,152 |
```restructuredtext
.. _i2c_api:
Inter-Integrated Circuit (I2C) Bus
##################################
Overview
********
.. note::
The terminology used in Zephyr I2C APIs follows that of the
`NXP I2C Bus Specification Rev 7.0 <i2c-specification_>`_. These changed
from previous revisions as of its release October 1, 2021.
`I2C`_ (Inter-Integrated Circuit, pronounced "eye
squared see") is a commonly-used two-signal shared peripheral interface
bus. Many system-on-chip solutions provide controllers that communicate
on an I2C bus. Devices on the bus can operate in two roles: as a
"controller" that initiates transactions and controls the clock, or as a
"target" that responds to transaction commands. A I2C controller on a
given SoC will generally support the controller role, and some will also
support the target mode. Zephyr has API for both roles.
.. _i2c-controller-api:
I2C Controller API
==================
Zephyr's I2C controller API is used when an I2C peripheral controls the bus,
in particularly the start and stop conditions and the clock. This is
the most common mode, used to interact with I2C devices like sensors and
serial memory.
This API is supported in all in-tree I2C peripheral drivers and is
considered stable.
.. _i2c-target-api:
I2C Target API
==============
Zephyr's I2C target API is used when an I2C peripheral responds to
transactions initiated by a different controller on the bus. It might
be used for a Zephyr application with transducer roles that are
controlled by another device such as a host processor.
This API is supported in very few in-tree I2C peripheral drivers. The
API is considered experimental, as it is not compatible with the
capabilities of all I2C peripherals supported in controller mode.
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_I2C`
API Reference
*************
.. doxygengroup:: i2c_interface
.. _i2c-specification:
path_to_url
.. _I2C: i2c-specification_
``` | /content/code_sandbox/doc/hardware/peripherals/i2c.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 491 |
```restructuredtext
.. _counter_api:
Counter
#######
Overview
********
API Reference
*************
.. doxygengroup:: counter_interface
``` | /content/code_sandbox/doc/hardware/peripherals/counter.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 29 |
```restructuredtext
.. _mipi_dsi_api:
MIPI Display Serial Interface (DSI)
###################################
API Reference
*************
.. doxygengroup:: mipi_dsi_interface
``` | /content/code_sandbox/doc/hardware/peripherals/mipi_dsi.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 38 |
```restructuredtext
.. _smbus_api:
System Management Bus (SMBus)
#############################
.. contents::
:local:
:depth: 2
Overview
********
System Management Bus (SMBus) is derived from I2C for communication
with devices on the motherboard. A system may use SMBus to communicate
with the peripherals on the motherboard without using dedicated control
lines. SMBus peripherals can provide various manufacturer information,
report errors, accept control parameters, etc.
Devices on the bus can operate in three roles: as a Controller that
initiates transactions and controls the clock, a Peripheral that
responds to transaction commands, or a Host, which is a specialized
Controller, that provides the main interface to the system's CPU.
Zephyr has API for the Controller role.
SMBus peripheral devices can initiate communication with Controller
with two methods:
* **Host Notify protocol**: Peripheral device that supports the Host Notify
protocol behaves as a Controller to perform the notification. It writes
a three-bytes message to a special address "SMBus Host (0x08)" with own
address and two bytes of relevant data.
* **SMBALERT# signal**: Peripheral device uses special signal SMBALERT# to
request attention from the Controller. The Controller needs to read one byte
from the special "SMBus Alert Response Address (ARA) (0x0c)". The peripheral
device responds with a data byte containing its own address.
Currently, the API is based on `SMBus Specification`_ version 2.0
.. note::
See :ref:`coding_guideline_inclusive_language` for information about
the terminology used in this API.
.. _smbus-controller-api:
SMBus Controller API
********************
Zephyr's SMBus controller API is used when an SMBus device controls the bus,
particularly the start and stop conditions and the clock. This is
the most common mode used to interact with SMBus peripherals.
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_SMBUS`
API Reference
*************
.. doxygengroup:: smbus_interface
.. _SMBus Specification: path_to_url
``` | /content/code_sandbox/doc/hardware/peripherals/smbus.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 466 |
```restructuredtext
.. _usbc_vbus_api:
USB-C VBUS
##########
Overview
********
USB-C VBUS is the line in a USB Type-C connection that delivers power from a
Source to a Sink device.
.. _usbc-vbus-api:
USB-C VBUS API
==============
The USB-C VBUS device driver presents an API that's used to control and measure
VBUS.
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_USBC_VBUS_DRIVER`
API Reference
*************
.. doxygengroup:: usbc_vbus_api
``` | /content/code_sandbox/doc/hardware/peripherals/usbc_vbus.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 123 |
```restructuredtext
.. _mipi_dbi_api:
MIPI Display Bus Interface (DBI)
###################################
The MIPI DBI driver class implements support for MIPI DBI compliant display
controllers.
MIPI DBI defines 3 interface types:
* Type A: Motorola 6800 parallel bus
* Type B: Intel 8080 parallel bus
* Type C: SPI Type serial bit bus with 3 options:
#. 9 write clocks per byte, final bit is command/data selection bit
#. Same as above, but 16 write clocks per byte
#. 8 write clocks per byte. Command/data selected via GPIO pin
Currently, the API only supports Type C controllers, options 1 and 3.
API Reference
*************
.. doxygengroup:: mipi_dbi_interface
``` | /content/code_sandbox/doc/hardware/peripherals/mipi_dbi.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 170 |
```restructuredtext
.. _hwinfo_api:
Hardware Information
####################
Overview
********
The HW Info API provides access to hardware information such as device
identifiers and reset cause flags.
Reset cause flags can be used to determine why the device was reset; for
example due to a watchdog timeout or due to power cycling. Different devices
support different subset of flags. Use
:c:func:`hwinfo_get_supported_reset_cause` to retrieve the flags that are
supported by that device.
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_HWINFO`
API Reference
*************
.. doxygengroup:: hwinfo_interface
``` | /content/code_sandbox/doc/hardware/peripherals/hwinfo.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 136 |
```restructuredtext
.. _api_peripherals:
Peripherals
###########
..
Please keep the ToC tree sorted based on the titles of the pages included
.. toctree::
:maxdepth: 1
w1.rst
adc.rst
auxdisplay.rst
audio/index.rst
bbram.rst
bc12.rst
clock_control.rst
can/index.rst
charger.rst
coredump.rst
counter.rst
dac.rst
dma.rst
display/index.rst
eeprom/index.rst
espi.rst
entropy.rst
edac/index.rst
flash.rst
fuel_gauge.rst
gnss.rst
gpio.rst
haptics.rst
hwinfo.rst
i2c_eeprom_target.rst
i3c.rst
i2c.rst
ipm.rst
kscan.rst
led.rst
mdio.rst
mipi_dbi.rst
mipi_dsi.rst
mspi.rst
mbox.rst
pcie.rst
peci.rst
ps2.rst
pwm.rst
rtc.rst
regulators.rst
reset.rst
retained_mem.rst
sdhc.rst
sensor/index.rst
spi.rst
smbus.rst
uart.rst
usbc_vbus.rst
tcpc.rst
tgpio.rst
video.rst
watchdog.rst
``` | /content/code_sandbox/doc/hardware/peripherals/index.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 361 |
```restructuredtext
.. _ps2_api:
PS/2
####
Overview
********
The PS/2 connector first hit the market in 1987 on
IBM's desktop PC line of the same name before
becoming an industry-wide standard for mouse and
keyboard connections. Starting around 2007, USB
superseded PS/2 and is the modern peripheral device
connection standard. For legacy support on boards
with a PS/2 connector, Zephyr provides these PS/2 driver APIs.
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_PS2`
API Reference
*************
.. doxygengroup:: ps2_interface
``` | /content/code_sandbox/doc/hardware/peripherals/ps2.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 140 |
```restructuredtext
.. _fuel_gauge_api:
Fuel Gauge
##########
The fuel gauge subsystem exposes an API to uniformly access battery fuel gauge devices. Currently,
only reading data is supported.
Note: This API is currently experimental and this doc will be significantly changed as new features
are added to the API.
Basic Operation
***************
Properties
==========
Fundamentally, a property is a quantity that a fuel gauge device can measure.
Fuel gauges typically support multiple properties, such as temperature readings of the battery-pack
or present-time current/voltage.
Properties are fetched by the client one at a time using :c:func:`fuel_gauge_get_prop`, or fetched
in a batch using :c:func:`fuel_gauge_get_props`.
Properties are set by the client one at a time using :c:func:`fuel_gauge_set_prop`, or set in a
batch using :c:func:`fuel_gauge_set_props`.
Battery Cutoff
==============
Many fuel gauges embedded within battery packs expose a register address that when written to with a
specific payload will do a battery cutoff. This battery cutoff is often referred to as ship, shelf,
or sleep mode due to its utility in reducing battery drain while devices are stored or shipped.
The fuel gauge API exposes battery cutoff with the :c:func:`fuel_gauge_battery_cutoff` function.
Caching
=======
The Fuel Gauge API explicitly provides no caching for its clients.
.. _fuel_gauge_api_reference:
API Reference
*************
.. doxygengroup:: fuel_gauge_interface
.. doxygengroup:: fuel_gauge_emulator_backend
``` | /content/code_sandbox/doc/hardware/peripherals/fuel_gauge.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 331 |
```restructuredtext
.. _flash_api:
Flash
#####
Overview
********
**Flash offset concept**
Offsets used by the user API are expressed in relation to
the flash memory beginning address. This rule shall be applied to
all flash controller regular memory that layout is accessible via
API for retrieving the layout of pages (see :kconfig:option:`CONFIG_FLASH_PAGE_LAYOUT`).
An exception from the rule may be applied to a vendor-specific flash
dedicated-purpose region (such a region obviously can't be covered under
API for retrieving the layout of pages).
User API Reference
******************
.. doxygengroup:: flash_interface
Implementation interface API Reference
**************************************
.. doxygengroup:: flash_internal_interface
``` | /content/code_sandbox/doc/hardware/peripherals/flash.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 147 |
```restructuredtext
.. _kscan_api:
Keyboard Scan
#############
Overview
********
The kscan driver (keyboard scan matrix) is used for detecting a key press in a
connected matrix keyboard or any device with buttons such as joysticks.
Typically, matrix keyboards are implemented using a two-dimensional
configuration in order to sense several keys. This allows interfacing to
many keys through fewer physical pins. Keyboard matrix
drivers read the rows while applying power through the columns one at a time
with the purpose of detecting key events.
There is no correlation between the physical and electrical layout of keys.
For, example, the physical layout may be one array of 16 or fewer keys, which
may be electrically connected to a 4 x 4 array. In addition, key values are
defined by a keymap provided by the keyboard manufacturer.
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_KSCAN`
API Reference
*************
.. doxygengroup:: kscan_interface
``` | /content/code_sandbox/doc/hardware/peripherals/kscan.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 210 |
```restructuredtext
.. _reset_api:
Reset Controller
################
Overview
********
Reset controllers are units that control the reset signals to multiple
peripherals. The reset controller API allows peripheral drivers to request
control over their reset input signals, including the ability to assert,
deassert and toggle those signals. Also, the reset status of the reset input
signal can be checked.
Mainly, the line_assert and line_deassert API functions are optional because
in most cases we want to toggle the reset signals.
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_RESET`
API Reference
*************
.. doxygengroup:: reset_controller_interface
``` | /content/code_sandbox/doc/hardware/peripherals/reset.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 137 |
```restructuredtext
.. _watchdog_api:
Watchdog
########
Overview
********
API Reference
*************
.. doxygengroup:: watchdog_interface
``` | /content/code_sandbox/doc/hardware/peripherals/watchdog.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 31 |
```restructuredtext
.. _entropy_api:
Entropy
#######
Overview
********
The entropy API provides functions to retrieve entropy values from
entropy hardware present on the platform. The entropy APIs are provided
for use by the random subsystem and cryptographic services. They are not
suitable to be used as random number generation functions.
API Reference
*************
.. doxygengroup:: entropy_interface
``` | /content/code_sandbox/doc/hardware/peripherals/entropy.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 78 |
```restructuredtext
.. _mspi_api:
Multi-bit SPI Bus
#################
The MSPI (multi-bit SPI) is provided as a generic API to accommodate
advanced SPI peripherals and devices that typically require command,
address and data phases, and multiple signal lines during these phases.
While the API supports advanced features such as :term:`XIP` and scrambling,
it is also compatible with generic SPI.
.. contents::
:local:
:depth: 2
.. _mspi-controller-api:
MSPI Controller API
*******************
Zephyr's MSPI controller API may be used when a multi-bit SPI controller
is present. E.g. Ambiq MSPI, QSPI, OSPI, Flexspi, etc.
The API supports single to hex SDR/DDR IO with variable latency and advanced
features such as :term:`XIP` and scrambling. Applicable devices include but
not limited to high-speed, high density flash/psram memory devices, displays
and sensors.
The MSPI interface contains controller drivers that are SoC platform specific
and implement the MSPI APIs, and device drivers that reference these APIs.
The relationship between the controller and device drivers is many-to-many to
allow for easy switching between platforms.
Here is a list of generic steps for initializing the MSPI controller and the
MSPI bus inside the device driver initialization function:
#. Initialize the data structure of the MSPI controller driver instance.
The usual device defining macros such as :c:macro:`DEVICE_DT_INST_DEFINE`
can be used, and the initialization function, config and data provided
as a parameter to the macro.
#. Initialize the hardware, including but not limited to:
* Check :c:struct:`mspi_cfg` against hardware's own capabilities to prevent
incorrect usages.
* Setup default pinmux.
* Setup the clock for the controller.
* Power on the hardware.
* Configure the hardware using :c:struct:`mspi_cfg` and possibly more
platform specific settings.
* Usually, the :c:struct:`mspi_cfg` is filled from device tree and contains
static, boot time parameters. However, if needed, one can use :c:func:`mspi_config`
to re-initialize the hardware with new parameters during runtime.
* Release any lock if applicable.
#. Perform device driver initialization. As usually, :c:macro:`DEVICE_DT_INST_DEFINE`
can be used. Inside device driver initialization function, perform the following
required steps.
#. Call :c:func:`mspi_dev_config` with device specific hardware settings obtained
from device datasheets.
* The :c:struct:`mspi_dev_cfg` should be filled by device tree and helper macro
:c:macro:`MSPI_DEVICE_CONFIG_DT` can be used.
* The controller driver should then validate the members of :c:struct:`mspi_dev_cfg`
to prevent incorrect usage.
* The controller driver should implement a mutex to protect from accidental access.
* The controller driver may also switch between different devices based on
:c:struct:`mspi_dev_id`.
#. Call API for additional setups if supported by hardware
* :c:func:`mspi_xip_config` for :term:`XIP` feature
* :c:func:`mspi_scramble_config` for scrambling feature
* :c:func:`mspi_timing_config` for platform specific timing setup.
#. Register any callback with :c:func:`mspi_register_callback` if needed.
#. Release the controller mutex lock.
Transceive
==========
The transceive request is of type :c:struct:`mspi_xfer` which allows dynamic change to
the transfer related settings once the mode of operation is determined and configured
by :c:func:`mspi_dev_config`.
The API also supports bulk transfers with different starting addresses and sizes with
:c:struct:`mspi_xfer_packet`. However, it is up to the controller implementation
whether to support scatter IO and callback management. The controller can determine
which user callback to trigger based on :c:enum:`mspi_bus_event_cb_mask` upon completion
of each async/sync transfer if the callback had been registered using
:c:func:`mspi_register_callback`. Or not to trigger any callback at all with
:c:enum:`MSPI_BUS_NO_CB` even if the callbacks are already registered.
In which case that a controller supports hardware command queue, user could take full
advantage of the hardware performance if scatter IO and callback management are supported
by the driver implementation.
Device Tree
===========
Here is an example for defining an MSPI controller in device tree:
The mspi controller's bindings should reference mspi-controller.yaml as one of the base.
.. code-block:: devicetree
mspi0: mspi@400 {
status = "okay";
compatible = "zephyr,mspi-emul-controller";
reg = < 0x400 0x4 >;
#address-cells = < 0x1 >;
#size-cells = < 0x0 >;
clock-frequency = < 0x17d7840 >;
op-mode = "MSPI_CONTROLLER";
duplex = "MSPI_HALF_DUPLEX";
ce-gpios = < &gpio0 0x5 0x1 >, < &gpio0 0x12 0x1 >;
dqs-support;
pinctrl-0 = < &pinmux-mspi0 >;
pinctrl-names = "default";
};
Here is an example for defining an MSPI device in device tree:
The mspi device's bindings should reference mspi-device.yaml as one of the base.
.. code-block:: devicetree
&mspi0 {
mspi_dev0: mspi_dev0@0 {
status = "okay";
compatible = "zephyr,mspi-emul-device";
reg = < 0x0 >;
size = < 0x10000 >;
mspi-max-frequency = < 0x2dc6c00 >;
mspi-io-mode = "MSPI_IO_MODE_QUAD";
mspi-data-rate = "MSPI_DATA_RATE_SINGLE";
mspi-hardware-ce-num = < 0x0 >;
read-instruction = < 0xb >;
write-instruction = < 0x2 >;
instruction-length = "INSTR_1_BYTE";
address-length = "ADDR_4_BYTE";
rx-dummy = < 0x8 >;
tx-dummy = < 0x0 >;
xip-config = < 0x0 0x0 0x0 0x0 >;
ce-break-config = < 0x0 0x0 >;
};
};
User should specify target operating parameters in the DTS such as ``mspi-max-frequency``,
``mspi-io-mode`` and ``mspi-data-rate`` even though they may subject to change during runtime.
It should represent the typical configuration of the device during normal operations.
Multi Peripheral
================
With :c:struct:`mspi_dev_id` defined as collection of the device index and CE GPIO from
device tree, the API supports multiple devices on the same controller instance.
The controller driver implementation may or may not support device switching,
which can be performed either by software or by hardware. If the switching is handled
by software, it should be performed in :c:func:`mspi_dev_config` call.
The device driver should record the current operating conditions of the device to support
software controlled device switching by saving and updating :c:struct:`mspi_dev_cfg` and
other relevant mspi struct or private data structures. In particular, :c:struct:`mspi_dev_id`
which contains the identity of the device needs to be used for every API call.
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_MSPI`
* :kconfig:option:`CONFIG_MSPI_ASYNC`
* :kconfig:option:`CONFIG_MSPI_PERIPHERAL`
* :kconfig:option:`CONFIG_MSPI_XIP`
* :kconfig:option:`CONFIG_MSPI_SCRAMBLE`
* :kconfig:option:`CONFIG_MSPI_TIMING`
* :kconfig:option:`CONFIG_MSPI_INIT_PRIORITY`
* :kconfig:option:`CONFIG_MSPI_COMPLETION_TIMEOUT_TOLERANCE`
API Reference
*************
.. doxygengroup:: mspi_interface
``` | /content/code_sandbox/doc/hardware/peripherals/mspi.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 1,802 |
```restructuredtext
.. _clock_control_api:
Clock Control
#############
Overview
********
The clock control API provides access to clocks in the system, including the
ability to turn them on and off.
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_CLOCK_CONTROL`
API Reference
*************
.. doxygengroup:: clock_control_interface
``` | /content/code_sandbox/doc/hardware/peripherals/clock_control.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 75 |
```restructuredtext
.. _peci_api:
Platform Environment Control Interface (PECI)
#############################################
Overview
********
The Platform Environment Control Interface, abbreviated as PECI,
is a thermal management standard introduced in 2006
with the Intel Core 2 Duo Microprocessors.
The PECI interface allows external devices to read processor temperature,
perform processor manageability functions, and manage processor interface
tuning and diagnostics.
The PECI bus driver APIs enable the interaction between Embedded
Microcontrollers and CPUs.
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_PECI`
API Reference
*************
.. doxygengroup:: peci_interface
``` | /content/code_sandbox/doc/hardware/peripherals/peci.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 139 |
```restructuredtext
.. _tgpio_api:
Time-aware General-Purpose Input/Output (TGPIO)
###############################################
Overview
********
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_TIMEAWARE_GPIO`
API Reference
*************
.. doxygengroup:: tgpio_interface
``` | /content/code_sandbox/doc/hardware/peripherals/tgpio.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 64 |
```restructuredtext
.. _auxdisplay_api:
Auxiliary Display (auxdisplay)
##############################
Overview
********
Auxiliary Displays are text-based displays that have simple interfaces for
displaying textual, numeric or alphanumeric data, as opposed to the
:ref:`display_api`, auxiliary displays do not support custom
graphical output to displays (and most often monochrome), the most
advanced custom feature supported is generation of custom characters.
These inexpensive displays are commonly found with various configurations
and sizes, a common display size is 16 characters by 2 lines.
This API is unstable and subject to change.
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_AUXDISPLAY`
* :kconfig:option:`CONFIG_AUXDISPLAY_INIT_PRIORITY`
API Reference
*************
.. doxygengroup:: auxdisplay_interface
``` | /content/code_sandbox/doc/hardware/peripherals/auxdisplay.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 169 |
```restructuredtext
.. _gpio_api:
General-Purpose Input/Output (GPIO)
###################################
Overview
********
Configuration Options
*********************
Related configuration options:
* :kconfig:option:`CONFIG_GPIO`
API Reference
*************
.. doxygengroup:: gpio_interface
``` | /content/code_sandbox/doc/hardware/peripherals/gpio.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 55 |
```restructuredtext
.. _charger_api:
Chargers
########
The charger subsystem exposes an API to uniformly access battery charger devices.
A charger device, or charger peripheral, is a device used to take external power provided to the
system as an input and provide power as an output downstream to the battery pack(s) and system.
The charger device can exist as a module, an integrated circuit, or as a functional block in a power
management integrated circuit (PMIC).
The action of charging a battery pack is referred to as a charge cycle. When the charge cycle is
executed the battery pack is charged according to the charge profile configured on the charger
device. The charge profile is defined in the battery pack's specification that is provided by the
manufacturer. On charger devices with a control port, the charge profile can be configured by the
host controller by setting the relevant properties, and can be adjusted at runtime to respond to
environmental changes.
Basic Operation
***************
Initiating a Charge Cycle
=========================
A charge cycle is initiated or terminated using :c:func:`charger_charge_enable`.
Properties
==========
Fundamentally, a property is a configurable setting, state, or quantity that a charger device can
measure.
Chargers typically support multiple properties, such as temperature readings of the battery-pack
or present-time current/voltage.
Properties are fetched by the client one at a time using :c:func:`charger_get_prop`.
Properties are set by the client one at a time using :c:func:`charger_set_prop`.
.. _charger_api_reference:
API Reference
*************
.. doxygengroup:: charger_interface
``` | /content/code_sandbox/doc/hardware/peripherals/charger.rst | restructuredtext | 2016-05-26T17:54:19 | 2024-08-16T18:09:06 | zephyr | zephyrproject-rtos/zephyr | 10,307 | 335 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.