1.. _dt-from-c:
2
3Devicetree access from C/C++
4############################
5
6This guide describes Zephyr's ``<zephyr/devicetree.h>`` API for reading the
7devicetree from C source files. It assumes you're familiar with the concepts in
8:ref:`devicetree-intro` and :ref:`dt-bindings`. See :ref:`dt-reference` for
9reference material.
10
11A note for Linux developers
12***************************
13
14Linux developers familiar with devicetree should be warned that the API
15described here differs significantly from how devicetree is used on Linux.
16
17Instead of generating a C header with all the devicetree data which is then
18abstracted behind a macro API, the Linux kernel would instead read the
19devicetree data structure in its binary form. The binary representation is
20parsed at runtime, for example to load and initialize device drivers.
21
22Zephyr does not work this way because the size of the devicetree binary and
23associated handling code would be too large to fit comfortably on the
24relatively constrained devices Zephyr supports.
25
26.. _dt-node-identifiers:
27
28Node identifiers
29****************
30
31To get information about a particular devicetree node, you need a *node
32identifier* for it. This is a just a C macro that refers to the node.
33
34These are the main ways to get a node identifier:
35
36By path
37   Use :c:func:`DT_PATH()` along with the node's full path in the devicetree,
38   starting from the root node. This is mostly useful if you happen to know the
39   exact node you're looking for.
40
41By node label
42   Use :c:func:`DT_NODELABEL()` to get a node identifier from a :ref:`node
43   label <dt-node-labels>`. Node labels are often provided by SoC :file:`.dtsi`
44   files to give nodes names that match the SoC datasheet, like ``i2c1``,
45   ``spi2``, etc.
46
47By alias
48   Use :c:func:`DT_ALIAS()` to get a node identifier for a property of the
49   special ``/aliases`` node. This is sometimes done by applications (like
50   :zephyr:code-sample:`blinky`, which uses the ``led0`` alias) that need to
51   refer to *some* device of a particular type ("the board's user LED") but
52   don't care which one is used.
53
54By instance number
55   This is done primarily by device drivers, as instance numbers are a way to
56   refer to individual nodes based on a matching compatible. Get these with
57   :c:func:`DT_INST()`, but be careful doing so. See below.
58
59By chosen node
60   Use :c:func:`DT_CHOSEN()` to get a node identifier for ``/chosen`` node
61   properties.
62
63By parent/child
64   Use :c:func:`DT_PARENT()` and :c:func:`DT_CHILD()` to get a node identifier
65   for a parent or child node, starting from a node identifier you already have.
66
67Two node identifiers which refer to the same node are identical and can be used
68interchangeably.
69
70.. _dt-node-main-ex:
71
72Here's a DTS fragment for some imaginary hardware we'll return to throughout
73this file for examples:
74
75.. literalinclude:: main-example.dts
76   :language: devicetree
77   :start-after: start-after-here
78
79Here are a few ways to get node identifiers for the ``i2c@40002000`` node:
80
81- ``DT_PATH(soc, i2c_40002000)``
82- ``DT_NODELABEL(i2c1)``
83- ``DT_ALIAS(sensor_controller)``
84- ``DT_INST(x, vnd_soc_i2c)`` for some unknown number ``x``. See the
85  :c:func:`DT_INST()` documentation for details.
86
87.. important::
88
89   Non-alphanumeric characters like dash (``-``) and the at sign (``@``) in
90   devicetree names are converted to underscores (``_``). The names in a DTS
91   are also converted to lowercase.
92
93.. _node-ids-are-not-values:
94
95Node identifiers are not values
96*******************************
97
98There is no way to store one in a variable. You cannot write:
99
100.. code-block:: c
101
102   /* These will give you compiler errors: */
103
104   void *i2c_0 = DT_INST(0, vnd_soc_i2c);
105   unsigned int i2c_1 = DT_INST(1, vnd_soc_i2c);
106   long my_i2c = DT_NODELABEL(i2c1);
107
108If you want something short to save typing, use C macros:
109
110.. code-block:: c
111
112   /* Use something like this instead: */
113
114   #define MY_I2C DT_NODELABEL(i2c1)
115
116   #define INST(i) DT_INST(i, vnd_soc_i2c)
117   #define I2C_0 INST(0)
118   #define I2C_1 INST(1)
119
120Property access
121***************
122
123The right API to use to read property values depends on the node and property.
124
125- :ref:`dt-checking-property-exists`
126- :ref:`simple-properties`
127- :ref:`reg-properties`
128- :ref:`interrupts-properties`
129- :ref:`phandle-properties`
130
131.. _dt-checking-property-exists:
132
133Checking properties and values
134==============================
135
136You can use :c:func:`DT_NODE_HAS_PROP()` to check if a node has a property. For
137the :ref:`example devicetree <dt-node-main-ex>` above:
138
139.. code-block:: c
140
141   DT_NODE_HAS_PROP(DT_NODELABEL(i2c1), clock_frequency)  /* expands to 1 */
142   DT_NODE_HAS_PROP(DT_NODELABEL(i2c1), not_a_property)   /* expands to 0 */
143
144.. _simple-properties:
145
146Simple properties
147=================
148
149Use ``DT_PROP(node_id, property)`` to read basic integer, boolean, string,
150numeric array, and string array properties.
151
152For example, to read the ``clock-frequency`` property's value in the
153:ref:`above example <dt-node-main-ex>`:
154
155.. code-block:: c
156
157   DT_PROP(DT_PATH(soc, i2c_40002000), clock_frequency)  /* This is 100000, */
158   DT_PROP(DT_NODELABEL(i2c1), clock_frequency)          /* and so is this, */
159   DT_PROP(DT_ALIAS(sensor_controller), clock_frequency) /* and this. */
160
161.. important::
162
163   The DTS property ``clock-frequency`` is spelled ``clock_frequency`` in C.
164   That is, properties also need special characters converted to underscores.
165   Their names are also forced to lowercase.
166
167Properties with ``string`` and ``boolean`` types work the exact same way. The
168``DT_PROP()`` macro expands to a string literal in the case of strings, and the
169number 0 or 1 in the case of booleans. For example:
170
171.. code-block:: c
172
173   #define I2C1 DT_NODELABEL(i2c1)
174
175   DT_PROP(I2C1, status)  /* expands to the string literal "okay" */
176
177.. note::
178
179   Don't use DT_NODE_HAS_PROP() for boolean properties. Use DT_PROP() instead
180   as shown above. It will expand to either 0 or 1 depending on if the property
181   is present or absent.
182
183Properties with type ``array``, ``uint8-array``, and ``string-array`` work
184similarly, except ``DT_PROP()`` expands to an array initializer in these cases.
185Here is an example devicetree fragment:
186
187.. code-block:: devicetree
188
189   foo: foo@1234 {
190           a = <1000 2000 3000>; /* array */
191           b = [aa bb cc dd];    /* uint8-array */
192           c = "bar", "baz";     /* string-array */
193   };
194
195Its properties can be accessed like this:
196
197.. code-block:: c
198
199   #define FOO DT_NODELABEL(foo)
200
201   int a[] = DT_PROP(FOO, a);           /* {1000, 2000, 3000} */
202   unsigned char b[] = DT_PROP(FOO, b); /* {0xaa, 0xbb, 0xcc, 0xdd} */
203   char* c[] = DT_PROP(FOO, c);         /* {"foo", "bar"} */
204
205You can use :c:func:`DT_PROP_LEN()` to get logical array lengths in number of
206elements.
207
208.. code-block:: c
209
210   size_t a_len = DT_PROP_LEN(FOO, a); /* 3 */
211   size_t b_len = DT_PROP_LEN(FOO, b); /* 4 */
212   size_t c_len = DT_PROP_LEN(FOO, c); /* 2 */
213
214``DT_PROP_LEN()`` cannot be used with the special ``reg`` or ``interrupts``
215properties. These have alternative macros which are described next.
216
217.. _reg-properties:
218
219reg properties
220==============
221
222See :ref:`dt-important-props` for an introduction to ``reg``.
223
224Given a node identifier ``node_id``, ``DT_NUM_REGS(node_id)`` is the
225total number of register blocks in the node's ``reg`` property.
226
227You **cannot** read register block addresses and lengths with ``DT_PROP(node,
228reg)``. Instead, if a node only has one register block, use
229:c:func:`DT_REG_ADDR` or :c:func:`DT_REG_SIZE`:
230
231- ``DT_REG_ADDR(node_id)``: the given node's register block address
232- ``DT_REG_SIZE(node_id)``: its size
233
234Use :c:func:`DT_REG_ADDR_BY_IDX` or :c:func:`DT_REG_SIZE_BY_IDX` instead if the
235node has multiple register blocks:
236
237- ``DT_REG_ADDR_BY_IDX(node_id, idx)``: address of register block at index
238  ``idx``
239- ``DT_REG_SIZE_BY_IDX(node_id, idx)``: size of block at index ``idx``
240
241The ``idx`` argument to these must be an integer literal or a macro that
242expands to one without requiring any arithmetic. In particular, ``idx`` cannot
243be a variable. This won't work:
244
245.. code-block:: c
246
247   /* This will cause a compiler error. */
248
249   for (size_t i = 0; i < DT_NUM_REGS(node_id); i++) {
250           size_t addr = DT_REG_ADDR_BY_IDX(node_id, i);
251   }
252
253.. _interrupts-properties:
254
255interrupts properties
256=====================
257
258See :ref:`dt-important-props` for a brief introduction to ``interrupts``.
259
260Given a node identifier ``node_id``, ``DT_NUM_IRQS(node_id)`` is the total
261number of interrupt specifiers in the node's ``interrupts`` property.
262
263The most general purpose API macro for accessing these is
264:c:func:`DT_IRQ_BY_IDX`:
265
266.. code-block:: c
267
268   DT_IRQ_BY_IDX(node_id, idx, val)
269
270Here, ``idx`` is the logical index into the ``interrupts`` array, i.e. it is
271the index of an individual interrupt specifier in the property. The ``val``
272argument is the name of a cell within the interrupt specifier. To use this
273macro, check the bindings file for the node you are interested in to find the
274``val`` names.
275
276Most Zephyr devicetree bindings have a cell named ``irq``, which is the
277interrupt number. You can use :c:func:`DT_IRQN` as a convenient way to get a
278processed view of this value.
279
280.. warning::
281
282   Here, "processed" reflects Zephyr's devicetree :ref:`dt-scripts`, which
283   change the ``irq`` number in :ref:`zephyr.dts <devicetree-in-out-files>` to
284   handle hardware constraints on some SoCs and in accordance with Zephyr's
285   multilevel interrupt numbering.
286
287   This is currently not very well documented, and you'll need to read the
288   scripts' source code and existing drivers for more details if you are writing
289   a device driver.
290
291.. _phandle-properties:
292
293phandle properties
294==================
295
296.. note::
297
298   See :ref:`dt-phandles` for a detailed guide to phandles.
299
300Property values can refer to other nodes using the ``&another-node`` phandle
301syntax introduced in :ref:`dt-writing-property-values`. Properties which
302contain phandles have type ``phandle``, ``phandles``, or ``phandle-array`` in
303their bindings. We'll call these "phandle properties" for short.
304
305You can convert a phandle to a node identifier using :c:func:`DT_PHANDLE`,
306:c:func:`DT_PHANDLE_BY_IDX`, or :c:func:`DT_PHANDLE_BY_NAME`, depending on the
307type of property you are working with.
308
309One common use case for phandle properties is referring to other hardware in
310the tree. In this case, you usually want to convert the devicetree-level
311phandle to a Zephyr driver-level :ref:`struct device <device_model_api>`.
312See :ref:`dt-get-device` for ways to do that.
313
314Another common use case is accessing specifier values in a phandle array. The
315general purpose APIs for this are :c:func:`DT_PHA_BY_IDX` and :c:func:`DT_PHA`.
316There are also hardware-specific shorthands like :c:func:`DT_GPIO_CTLR_BY_IDX`,
317:c:func:`DT_GPIO_CTLR`,
318:c:func:`DT_GPIO_PIN_BY_IDX`, :c:func:`DT_GPIO_PIN`,
319:c:func:`DT_GPIO_FLAGS_BY_IDX`, and :c:func:`DT_GPIO_FLAGS`.
320
321See :c:func:`DT_PHA_HAS_CELL_AT_IDX` and :c:func:`DT_PROP_HAS_IDX` for ways to
322check if a specifier value is present in a phandle property.
323
324.. _other-devicetree-apis:
325
326Other APIs
327**********
328
329Here are pointers to some other available APIs.
330
331- :c:func:`DT_CHOSEN`, :c:func:`DT_HAS_CHOSEN`: for properties
332  of the special ``/chosen`` node
333- :c:func:`DT_HAS_COMPAT_STATUS_OKAY`, :c:func:`DT_NODE_HAS_COMPAT`: global-
334  and node-specific tests related to the ``compatible`` property
335- :c:func:`DT_BUS`: get a node's bus controller, if there is one
336- :c:func:`DT_ENUM_IDX`: for properties whose values are among a fixed list of
337  choices
338- :ref:`devicetree-flash-api`: APIs for managing fixed flash partitions.
339  Also see :ref:`flash_map_api`, which wraps this in a more user-friendly API.
340
341Device driver conveniences
342**************************
343
344Special purpose macros are available for writing device drivers, which usually
345rely on :ref:`instance identifiers <dt-node-identifiers>`.
346
347To use these, you must define ``DT_DRV_COMPAT`` to the ``compat`` value your
348driver implements support for. This ``compat`` value is what you would pass to
349:c:func:`DT_INST`.
350
351If you do that, you can access the properties of individual instances of your
352compatible with less typing, like this:
353
354.. code-block:: c
355
356   #include <zephyr/devicetree.h>
357
358   #define DT_DRV_COMPAT my_driver_compat
359
360   /* This is same thing as DT_INST(0, my_driver_compat): */
361   DT_DRV_INST(0)
362
363   /*
364    * This is the same thing as
365    * DT_PROP(DT_INST(0, my_driver_compat), clock_frequency)
366    */
367   DT_INST_PROP(0, clock_frequency)
368
369See :ref:`devicetree-inst-apis` for a generic API reference.
370
371Hardware specific APIs
372**********************
373
374Convenience macros built on top of the above APIs are also defined to help
375readability for hardware specific code. See :ref:`devicetree-hw-api` for
376details.
377
378Generated macros
379****************
380
381While the :file:`zephyr/devicetree.h` API is not generated, it does rely on a
382generated C header which is put into every application build directory:
383:ref:`devicetree_generated.h <dt-outputs>`. This file contains macros with
384devicetree data.
385
386These macros have tricky naming conventions which the :ref:`devicetree_api` API
387abstracts away. They should be considered an implementation detail, but it's
388useful to understand them since they will frequently be seen in compiler error
389messages.
390
391This section contains an Augmented Backus-Naur Form grammar for these
392generated macros, with examples and more details in comments. See `RFC 7405`_
393(which extends `RFC 5234`_) for a syntax specification.
394
395.. literalinclude:: macros.bnf
396   :language: abnf
397
398.. _RFC 7405: https://tools.ietf.org/html/rfc7405
399.. _RFC 5234: https://tools.ietf.org/html/rfc5234
400