1 /*
2  * Copyright (c) 2015 Intel Corporation.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #ifndef ZEPHYR_INCLUDE_DEVICE_H_
8 #define ZEPHYR_INCLUDE_DEVICE_H_
9 
10 #include <stdint.h>
11 
12 #include <zephyr/devicetree.h>
13 #include <zephyr/init.h>
14 #include <zephyr/linker/sections.h>
15 #include <zephyr/pm/state.h>
16 #include <zephyr/sys/device_mmio.h>
17 #include <zephyr/sys/iterable_sections.h>
18 #include <zephyr/sys/util.h>
19 #include <zephyr/toolchain.h>
20 
21 #ifdef CONFIG_LLEXT
22 #include <zephyr/llext/symbol.h>
23 #endif
24 
25 #ifdef __cplusplus
26 extern "C" {
27 #endif
28 
29 /**
30  * @brief Device Model
31  * @defgroup device_model Device Model
32  * @since 1.0
33  * @version 1.1.0
34  * @{
35  */
36 
37 /** @cond INTERNAL_HIDDEN */
38 
39 /**
40  * @brief Flag value used in lists of device dependencies to separate distinct
41  * groups.
42  */
43 #define Z_DEVICE_DEPS_SEP INT16_MIN
44 
45 /**
46  * @brief Flag value used in lists of device dependencies to indicate the end of
47  * the list.
48  */
49 #define Z_DEVICE_DEPS_ENDS INT16_MAX
50 
51 /** @brief Determine if a DT node is mutable */
52 #define Z_DEVICE_IS_MUTABLE(node_id)                                                               \
53 	COND_CODE_1(IS_ENABLED(CONFIG_DEVICE_MUTABLE), (DT_PROP(node_id, zephyr_mutable)), (0))
54 
55 /** @endcond */
56 
57 /**
58  * @brief Type used to represent a "handle" for a device.
59  *
60  * Every @ref device has an associated handle. You can get a pointer to a
61  * @ref device from its handle and vice versa, but the handle uses less space
62  * than a pointer. The device.h API mainly uses handles to store lists of
63  * multiple devices in a compact way.
64  *
65  * The extreme values and zero have special significance. Negative values
66  * identify functionality that does not correspond to a Zephyr device, such as
67  * the system clock or a SYS_INIT() function.
68  *
69  * @see device_handle_get()
70  * @see device_from_handle()
71  */
72 typedef int16_t device_handle_t;
73 
74 /** @brief Flag value used to identify an unknown device. */
75 #define DEVICE_HANDLE_NULL 0
76 
77 /**
78  * @brief Expands to the name of a global device object.
79  *
80  * Return the full name of a device object symbol created by DEVICE_DEFINE(),
81  * using the `dev_id` provided to DEVICE_DEFINE(). This is the name of the
82  * global variable storing the device structure, not a pointer to the string in
83  * the @ref device.name field.
84  *
85  * It is meant to be used for declaring extern symbols pointing to device
86  * objects before using the DEVICE_GET macro to get the device object.
87  *
88  * This macro is normally only useful within device driver source code. In other
89  * situations, you are probably looking for device_get_binding().
90  *
91  * @param dev_id Device identifier.
92  *
93  * @return The full name of the device object defined by device definition
94  * macros.
95  */
96 #define DEVICE_NAME_GET(dev_id) _CONCAT(__device_, dev_id)
97 
98 /* This macro synthesizes a unique dev_id from a devicetree node by using
99  * the node's dependency ordinal.
100  *
101  * The ordinal used in this name can be mapped to the path by
102  * examining zephyr/include/generated/zephyr/devicetree_generated.h.
103  */
104 #define Z_DEVICE_DT_DEP_ORD(node_id) _CONCAT(dts_ord_, DT_DEP_ORD(node_id))
105 
106 /* Same as above, but uses the hash of the node path instead of the ordinal.
107  *
108  * The hash used in this name can be mapped to the path by
109  * examining zephyr/include/generated/zephyr/devicetree_generated.h.
110  */
111 #define Z_DEVICE_DT_HASH(node_id) _CONCAT(dts_, DT_NODE_HASH(node_id))
112 
113 /* By default, device identifiers are obtained using the dependency ordinal.
114  * When LLEXT_EXPORT_DEV_IDS_BY_HASH is defined, the main Zephyr binary exports
115  * DT identifiers via EXPORT_SYMBOL_NAMED as hashed versions of their paths.
116  * When matching extensions are built, that is what they need to look for.
117  *
118  * The ordinal or hash used in this name can be mapped to the path by
119  * examining zephyr/include/generated/zephyr/devicetree_generated.h.
120  */
121 #if defined(LL_EXTENSION_BUILD) && defined(CONFIG_LLEXT_EXPORT_DEV_IDS_BY_HASH)
122 #define Z_DEVICE_DT_DEV_ID(node_id) Z_DEVICE_DT_HASH(node_id)
123 #else
124 #define Z_DEVICE_DT_DEV_ID(node_id) Z_DEVICE_DT_DEP_ORD(node_id)
125 #endif
126 
127 #if defined(CONFIG_LLEXT_EXPORT_DEV_IDS_BY_HASH)
128 /* Export device identifiers by hash */
129 #define Z_DEVICE_EXPORT(node_id)					       \
130 	EXPORT_SYMBOL_NAMED(DEVICE_DT_NAME_GET(node_id),		       \
131 			    DEVICE_NAME_GET(Z_DEVICE_DT_HASH(node_id)))
132 #elif defined(CONFIG_LLEXT_EXPORT_DEVICES)
133 /* Export device identifiers using the builtin name */
134 #define Z_DEVICE_EXPORT(node_id) EXPORT_SYMBOL(DEVICE_DT_NAME_GET(node_id))
135 #endif
136 
137 /**
138  * @brief Create a device object and set it up for boot time initialization,
139  * with de-init capabilities.
140  *
141  * This macro defines a @ref device that is automatically configured by the
142  * kernel during system initialization. This macro should only be used when the
143  * device is not being allocated from a devicetree node. If you are allocating a
144  * device from a devicetree node, use DEVICE_DT_DEINIT_DEFINE() or
145  * DEVICE_DT_INST_DEINIT_DEFINE() instead.
146  *
147  * @param dev_id A unique token which is used in the name of the global device
148  * structure as a C identifier.
149  * @param name A string name for the device, which will be stored in
150  * @ref device.name. This name can be used to look up the device with
151  * device_get_binding(). This must be less than Z_DEVICE_MAX_NAME_LEN characters
152  * (including terminating `NULL`) in order to be looked up from user mode.
153  * @param init_fn Pointer to the device's initialization function, which will be
154  * run by the kernel during system initialization. Can be `NULL`.
155  * @param deinit_fn Pointer to the device's de-initialization function. Can be
156  * `NULL`. It must release any acquired resources (e.g. pins, bus, clock...) and
157  * leave the device in its reset state.
158  * @param pm Pointer to the device's power management resources, a
159  * @ref pm_device, which will be stored in @ref device.pm field. Use `NULL` if
160  * the device does not use PM.
161  * @param data Pointer to the device's private mutable data, which will be
162  * stored in @ref device.data.
163  * @param config Pointer to the device's private constant data, which will be
164  * stored in @ref device.config.
165  * @param level The device's initialization level (PRE_KERNEL_1, PRE_KERNEL_2 or
166  * POST_KERNEL).
167  * @param prio The device's priority within its initialization level. See
168  * SYS_INIT() for details.
169  * @param api Pointer to the device's API structure. Can be `NULL`.
170  */
171 #define DEVICE_DEINIT_DEFINE(dev_id, name, init_fn, deinit_fn, pm, data,       \
172 			     config, level, prio, api)                         \
173 	Z_DEVICE_STATE_DEFINE(dev_id);                                         \
174 	Z_DEVICE_DEFINE(DT_INVALID_NODE, dev_id, name, init_fn, deinit_fn, 0U, \
175 			pm, data, config, level, prio, api,                    \
176 			&Z_DEVICE_STATE_NAME(dev_id))
177 
178 /**
179  * @brief Create a device object and set it up for boot time initialization.
180  *
181  * @see DEVICE_DEINIT_DEFINE()
182  */
183 #define DEVICE_DEFINE(dev_id, name, init_fn, pm, data, config, level, prio,    \
184 		      api)                                                     \
185 	DEVICE_DEINIT_DEFINE(dev_id, name, init_fn, NULL, pm, data, config,    \
186 			     level, prio, api)
187 
188 /**
189  * @brief Return a string name for a devicetree node.
190  *
191  * This macro returns a string literal usable as a device's name from a
192  * devicetree node identifier.
193  *
194  * @param node_id The devicetree node identifier.
195  *
196  * @return The value of the node's `label` property, if it has one.
197  * Otherwise, the node's full name in `node-name@unit-address` form.
198  */
199 #define DEVICE_DT_NAME(node_id)                                                \
200 	DT_PROP_OR(node_id, label, DT_NODE_FULL_NAME(node_id))
201 
202 /**
203  * @brief Create a device object from a devicetree node identifier and set it up
204  * for boot time initialization.
205  *
206  * This macro defines a @ref device that is automatically configured by the
207  * kernel during system initialization. The global device object's name as a C
208  * identifier is derived from the node's dependency ordinal or hash.
209  * @ref device.name is set to `DEVICE_DT_NAME(node_id)`.
210  *
211  * The device is declared with extern visibility, so a pointer to a global
212  * device object can be obtained with `DEVICE_DT_GET(node_id)` from any source
213  * file that includes `<zephyr/device.h>` (even from extensions, when
214  * @kconfig{CONFIG_LLEXT_EXPORT_DEVICES} is enabled). Before using the
215  * pointer, the referenced object should be checked using device_is_ready().
216  *
217  * @param node_id The devicetree node identifier.
218  * @param init_fn Pointer to the device's initialization function, which will be
219  * run by the kernel during system initialization. Can be `NULL`.
220  * @param deinit_fn Pointer to the device's de-initialization function. Can be
221  * `NULL`. It must release any acquired resources (e.g. pins, bus, clock...) and
222  * leave the device in its reset state.
223  * @param pm Pointer to the device's power management resources, a
224  * @ref pm_device, which will be stored in @ref device.pm. Use `NULL` if the
225  * device does not use PM.
226  * @param data Pointer to the device's private mutable data, which will be
227  * stored in @ref device.data.
228  * @param config Pointer to the device's private constant data, which will be
229  * stored in @ref device.config field.
230  * @param level The device's initialization level (PRE_KERNEL_1, PRE_KERNEL_2 or
231  * POST_KERNEL).
232  * @param prio The device's priority within its initialization level. See
233  * SYS_INIT() for details.
234  * @param api Pointer to the device's API structure. Can be `NULL`.
235  */
236 #define DEVICE_DT_DEINIT_DEFINE(node_id, init_fn, deinit_fn, pm, data, config, \
237 				level, prio, api, ...)                         \
238 	Z_DEVICE_STATE_DEFINE(Z_DEVICE_DT_DEV_ID(node_id));                    \
239 	Z_DEVICE_DEFINE(node_id, Z_DEVICE_DT_DEV_ID(node_id),                  \
240 			DEVICE_DT_NAME(node_id), init_fn, deinit_fn,           \
241 			Z_DEVICE_DT_FLAGS(node_id), pm, data, config, level,   \
242 			prio, api,                                             \
243 			&Z_DEVICE_STATE_NAME(Z_DEVICE_DT_DEV_ID(node_id)),     \
244 			__VA_ARGS__)
245 
246 /**
247  * @brief Create a device object from a devicetree node identifier and set it up
248  * for boot time initialization.
249  *
250  * @see DEVICE_DT_DEINIT_DEFINE()
251  */
252 #define DEVICE_DT_DEFINE(node_id, init_fn, pm, data, config, level, prio, api, \
253 			 ...)                                                  \
254 	DEVICE_DT_DEINIT_DEFINE(node_id, init_fn, NULL, pm, data, config,      \
255 				level, prio, api, __VA_ARGS__)
256 
257 /**
258  * @brief Like DEVICE_DT_DEINIT_DEFINE(), but uses an instance of a
259  * `DT_DRV_COMPAT` compatible instead of a node identifier.
260  *
261  * @param inst Instance number. The `node_id` argument to DEVICE_DT_DEFINE() is
262  * set to `DT_DRV_INST(inst)`.
263  * @param ... Other parameters as expected by DEVICE_DT_DEFINE().
264  */
265 #define DEVICE_DT_INST_DEINIT_DEFINE(inst, ...)                                \
266 	DEVICE_DT_DEINIT_DEFINE(DT_DRV_INST(inst), __VA_ARGS__)
267 
268 /**
269  * @brief Like DEVICE_DT_DEFINE(), but uses an instance of a `DT_DRV_COMPAT`
270  * compatible instead of a node identifier.
271  *
272  * @param inst Instance number. The `node_id` argument to DEVICE_DT_DEFINE() is
273  * set to `DT_DRV_INST(inst)`.
274  * @param ... Other parameters as expected by DEVICE_DT_DEFINE().
275  */
276 #define DEVICE_DT_INST_DEFINE(inst, ...)                                       \
277 	DEVICE_DT_DEFINE(DT_DRV_INST(inst), __VA_ARGS__)
278 
279 /**
280  * @brief The name of the global device object for @p node_id
281  *
282  * Returns the name of the global device structure as a C identifier. The device
283  * must be allocated using DEVICE_DT_DEFINE() or DEVICE_DT_INST_DEFINE() for
284  * this to work.
285  *
286  * This macro is normally only useful within device driver source code. In other
287  * situations, you are probably looking for DEVICE_DT_GET().
288  *
289  * @param node_id Devicetree node identifier
290  *
291  * @return The name of the device object as a C identifier
292  */
293 #define DEVICE_DT_NAME_GET(node_id) DEVICE_NAME_GET(Z_DEVICE_DT_DEV_ID(node_id))
294 
295 /**
296  * @brief Get a @ref device reference from a devicetree node identifier.
297  *
298  * Returns a pointer to a device object created from a devicetree node, if any
299  * device was allocated by a driver.
300  *
301  * If no such device was allocated, this will fail at linker time. If you get an
302  * error that looks like `undefined reference to __device_dts_ord_<N>`, that is
303  * what happened. Check to make sure your device driver is being compiled,
304  * usually by enabling the Kconfig options it requires.
305  *
306  * @param node_id A devicetree node identifier
307  *
308  * @return A pointer to the device object created for that node
309  */
310 #define DEVICE_DT_GET(node_id) (&DEVICE_DT_NAME_GET(node_id))
311 
312 /**
313  * @brief Get a @ref device reference for an instance of a `DT_DRV_COMPAT`
314  * compatible.
315  *
316  * This is equivalent to `DEVICE_DT_GET(DT_DRV_INST(inst))`.
317  *
318  * @param inst `DT_DRV_COMPAT` instance number
319  * @return A pointer to the device object created for that instance
320  */
321 #define DEVICE_DT_INST_GET(inst) DEVICE_DT_GET(DT_DRV_INST(inst))
322 
323 /**
324  * @brief Get a @ref device reference from a devicetree compatible.
325  *
326  * If an enabled devicetree node has the given compatible and a device
327  * object was created from it, this returns a pointer to that device.
328  *
329  * If there no such devices, this returns NULL.
330  *
331  * If there are multiple, this returns an arbitrary one.
332  *
333  * If this returns non-NULL, the device must be checked for readiness
334  * before use, e.g. with device_is_ready().
335  *
336  * @param compat lowercase-and-underscores devicetree compatible
337  * @return a pointer to a device, or NULL
338  */
339 #define DEVICE_DT_GET_ANY(compat)                                              \
340 	COND_CODE_1(DT_HAS_COMPAT_STATUS_OKAY(compat),                         \
341 		    (DEVICE_DT_GET(DT_COMPAT_GET_ANY_STATUS_OKAY(compat))),    \
342 		    (NULL))
343 
344 /**
345  * @brief Get a @ref device reference from a devicetree compatible.
346  *
347  * If an enabled devicetree node has the given compatible and a device object
348  * was created from it, this returns a pointer to that device.
349  *
350  * If there are no such devices, this will fail at compile time.
351  *
352  * If there are multiple, this returns an arbitrary one.
353  *
354  * If this returns non-NULL, the device must be checked for readiness before
355  * use, e.g. with device_is_ready().
356  *
357  * @param compat lowercase-and-underscores devicetree compatible
358  * @return a pointer to a device
359  */
360 #define DEVICE_DT_GET_ONE(compat)                                              \
361 	COND_CODE_1(DT_HAS_COMPAT_STATUS_OKAY(compat),                         \
362 		    (DEVICE_DT_GET(DT_COMPAT_GET_ANY_STATUS_OKAY(compat))),    \
363 		    (ZERO_OR_COMPILE_ERROR(0)))
364 
365 /**
366  * @brief Utility macro to obtain an optional reference to a device.
367  *
368  * If the node identifier refers to a node with status `okay`, this returns
369  * `DEVICE_DT_GET(node_id)`. Otherwise, it returns `NULL`.
370  *
371  * @param node_id devicetree node identifier
372  *
373  * @return a @ref device reference for the node identifier, which may be `NULL`.
374  */
375 #define DEVICE_DT_GET_OR_NULL(node_id)                                         \
376 	COND_CODE_1(DT_NODE_HAS_STATUS_OKAY(node_id),                          \
377 		    (DEVICE_DT_GET(node_id)), (NULL))
378 
379 /**
380  * @brief Get a @ref device reference from a devicetree phandles by idx.
381  *
382  * Returns a pointer to a device object referenced by a phandles property, by idx.
383  *
384  * @param node_id A devicetree node identifier
385  * @param prop lowercase-and-underscores property with type `phandle`,
386  *            `phandles`, or `phandle-array`
387  * @param idx logical index into @p phs, which must be zero if @p phs
388  *            has type `phandle`
389  *
390  * @return A pointer to the device object created for that node
391  */
392 #define DEVICE_DT_GET_BY_IDX(node_id, prop, idx) \
393 	DEVICE_DT_GET(DT_PHANDLE_BY_IDX(node_id, prop, idx))
394 
395 /**
396  * @brief Obtain a pointer to a device object by name
397  *
398  * @details Return the address of a device object created by
399  * DEVICE_DEFINE(), using the dev_id provided to DEVICE_DEFINE().
400  *
401  * @param dev_id Device identifier.
402  *
403  * @return A pointer to the device object created by DEVICE_DEFINE()
404  */
405 #define DEVICE_GET(dev_id) (&DEVICE_NAME_GET(dev_id))
406 
407 /**
408  * @brief Declare a static device object
409  *
410  * This macro can be used at the top-level to declare a device, such
411  * that DEVICE_GET() may be used before the full declaration in
412  * DEVICE_DEFINE().
413  *
414  * This is often useful when configuring interrupts statically in a
415  * device's init or per-instance config function, as the init function
416  * itself is required by DEVICE_DEFINE() and use of DEVICE_GET()
417  * inside it creates a circular dependency.
418  *
419  * @param dev_id Device identifier.
420  */
421 #define DEVICE_DECLARE(dev_id)                                                 \
422 	static const struct device DEVICE_NAME_GET(dev_id)
423 
424 /**
425  * @brief Get a @ref init_entry reference from a devicetree node.
426  *
427  * @param node_id A devicetree node identifier
428  *
429  * @return A pointer to the @ref init_entry object created for that node
430  */
431 #define DEVICE_INIT_DT_GET(node_id)                                            \
432 	(&Z_INIT_ENTRY_NAME(DEVICE_DT_NAME_GET(node_id)))
433 
434 /**
435  * @brief Get a @ref init_entry reference from a device identifier.
436  *
437  * @param dev_id Device identifier.
438  *
439  * @return A pointer to the init_entry object created for that device
440  */
441 #define DEVICE_INIT_GET(dev_id) (&Z_INIT_ENTRY_NAME(DEVICE_NAME_GET(dev_id)))
442 
443 /**
444  * @brief Runtime device dynamic structure (in RAM) per driver instance
445  *
446  * Fields in this are expected to be default-initialized to zero. The
447  * kernel driver infrastructure and driver access functions are
448  * responsible for ensuring that any non-zero initialization is done
449  * before they are accessed.
450  */
451 struct device_state {
452 	/**
453 	 * Device initialization return code (positive errno value).
454 	 *
455 	 * Device initialization functions return a negative errno code if they
456 	 * fail. In Zephyr, errno values do not exceed 255, so we can store the
457 	 * positive result value in a uint8_t type.
458 	 */
459 	uint8_t init_res;
460 
461 	/** Indicates the device initialization function has been
462 	 * invoked.
463 	 */
464 	bool initialized : 1;
465 };
466 
467 struct pm_device_base;
468 struct pm_device;
469 struct pm_device_isr;
470 #if defined(CONFIG_DEVICE_DT_METADATA) || defined(__DOXYGEN__)
471 struct device_dt_metadata;
472 #endif
473 
474 #ifdef CONFIG_DEVICE_DEPS_DYNAMIC
475 #define Z_DEVICE_DEPS_CONST
476 #else
477 #define Z_DEVICE_DEPS_CONST const
478 #endif
479 
480 /** Device flags */
481 typedef uint8_t device_flags_t;
482 
483 /**
484  * @name Device flags
485  * @{
486  */
487 
488 /** Device initialization is deferred */
489 #define DEVICE_FLAG_INIT_DEFERRED BIT(0)
490 
491 /** @} */
492 
493 /** Device operations */
494 struct device_ops {
495 	/** Initialization function */
496 	int (*init)(const struct device *dev);
497 	/** De-initialization function */
498 	int (*deinit)(const struct device *dev);
499 };
500 
501 /**
502  * @brief Runtime device structure (in ROM) per driver instance
503  */
504 struct device {
505 	/** Name of the device instance */
506 	const char *name;
507 	/** Address of device instance config information */
508 	const void *config;
509 	/** Address of the API structure exposed by the device instance */
510 	const void *api;
511 	/** Address of the common device state */
512 	struct device_state *state;
513 	/** Address of the device instance private data */
514 	void *data;
515 	/** Device operations */
516 	struct device_ops ops;
517 	/** Device flags */
518 	device_flags_t flags;
519 #if defined(CONFIG_DEVICE_DEPS) || defined(__DOXYGEN__)
520 	/**
521 	 * Optional pointer to dependencies associated with the device.
522 	 *
523 	 * This encodes a sequence of sets of device handles that have some
524 	 * relationship to this node. The individual sets are extracted with
525 	 * dedicated API, such as device_required_handles_get(). Only available
526 	 * if @kconfig{CONFIG_DEVICE_DEPS} is enabled.
527 	 */
528 	Z_DEVICE_DEPS_CONST device_handle_t *deps;
529 #endif /* CONFIG_DEVICE_DEPS */
530 #if defined(CONFIG_PM_DEVICE) || defined(__DOXYGEN__)
531 	/**
532 	 * Reference to the device PM resources (only available if
533 	 * @kconfig{CONFIG_PM_DEVICE} is enabled).
534 	 */
535 	union {
536 		struct pm_device_base *pm_base;
537 		struct pm_device *pm;
538 		struct pm_device_isr *pm_isr;
539 	};
540 #endif
541 #if defined(CONFIG_DEVICE_DT_METADATA) || defined(__DOXYGEN__)
542 	const struct device_dt_metadata *dt_meta;
543 #endif /* CONFIG_DEVICE_DT_METADATA */
544 };
545 
546 /**
547  * @brief Get the handle for a given device
548  *
549  * @param dev the device for which a handle is desired.
550  *
551  * @return the handle for the device, or DEVICE_HANDLE_NULL if the device does
552  * not have an associated handle.
553  */
device_handle_get(const struct device * dev)554 static inline device_handle_t device_handle_get(const struct device *dev)
555 {
556 	device_handle_t ret = DEVICE_HANDLE_NULL;
557 	STRUCT_SECTION_START_EXTERN(device);
558 
559 	/* TODO: If/when devices can be constructed that are not part of the
560 	 * fixed sequence we'll need another solution.
561 	 */
562 	if (dev != NULL) {
563 		ret = 1 + (device_handle_t)(dev - STRUCT_SECTION_START(device));
564 	}
565 
566 	return ret;
567 }
568 
569 /**
570  * @brief Get the device corresponding to a handle.
571  *
572  * @param dev_handle the device handle
573  *
574  * @return the device that has that handle, or a null pointer if @p dev_handle
575  * does not identify a device.
576  */
577 static inline const struct device *
device_from_handle(device_handle_t dev_handle)578 device_from_handle(device_handle_t dev_handle)
579 {
580 	STRUCT_SECTION_START_EXTERN(device);
581 	const struct device *dev = NULL;
582 	size_t numdev;
583 
584 	STRUCT_SECTION_COUNT(device, &numdev);
585 
586 	if ((dev_handle > 0) && ((size_t)dev_handle <= numdev)) {
587 		dev = &STRUCT_SECTION_START(device)[dev_handle - 1];
588 	}
589 
590 	return dev;
591 }
592 
593 #if defined(CONFIG_DEVICE_DEPS) || defined(__DOXYGEN__)
594 
595 /**
596  * @brief Prototype for functions used when iterating over a set of devices.
597  *
598  * Such a function may be used in API that identifies a set of devices and
599  * provides a visitor API supporting caller-specific interaction with each
600  * device in the set.
601  *
602  * The visit is said to succeed if the visitor returns a non-negative value.
603  *
604  * @param dev a device in the set being iterated
605  * @param context state used to support the visitor function
606  *
607  * @return A non-negative number to allow walking to continue, and a negative
608  * error code to case the iteration to stop.
609  *
610  * @see device_required_foreach()
611  * @see device_supported_foreach()
612  */
613 typedef int (*device_visitor_callback_t)(const struct device *dev,
614 					 void *context);
615 
616 /**
617  * @brief Get the device handles for devicetree dependencies of this device.
618  *
619  * This function returns a pointer to an array of device handles. The length of
620  * the array is stored in the @p count parameter.
621  *
622  * The array contains a handle for each device that @p dev requires directly, as
623  * determined from the devicetree. This does not include transitive
624  * dependencies; you must recursively determine those.
625  *
626  * @param dev the device for which dependencies are desired.
627  * @param count pointer to where this function should store the length of the
628  * returned array. No value is stored if the call returns a null pointer. The
629  * value may be set to zero if the device has no devicetree dependencies.
630  *
631  * @return a pointer to a sequence of @p count device handles, or a null pointer
632  * if @p dev does not have any dependency data.
633  */
634 static inline const device_handle_t *
device_required_handles_get(const struct device * dev,size_t * count)635 device_required_handles_get(const struct device *dev, size_t *count)
636 {
637 	const device_handle_t *rv = dev->deps;
638 
639 	if (rv != NULL) {
640 		size_t i = 0;
641 
642 		while ((rv[i] != Z_DEVICE_DEPS_ENDS) &&
643 		       (rv[i] != Z_DEVICE_DEPS_SEP)) {
644 			++i;
645 		}
646 		*count = i;
647 	}
648 
649 	return rv;
650 }
651 
652 /**
653  * @brief Get the device handles for injected dependencies of this device.
654  *
655  * This function returns a pointer to an array of device handles. The length of
656  * the array is stored in the @p count parameter.
657  *
658  * The array contains a handle for each device that @p dev manually injected as
659  * a dependency, via providing extra arguments to Z_DEVICE_DEFINE. This does not
660  * include transitive dependencies; you must recursively determine those.
661  *
662  * @param dev the device for which injected dependencies are desired.
663  * @param count pointer to where this function should store the length of the
664  * returned array. No value is stored if the call returns a null pointer. The
665  * value may be set to zero if the device has no devicetree dependencies.
666  *
667  * @return a pointer to a sequence of @p *count device handles, or a null
668  * pointer if @p dev does not have any dependency data.
669  */
670 static inline const device_handle_t *
device_injected_handles_get(const struct device * dev,size_t * count)671 device_injected_handles_get(const struct device *dev, size_t *count)
672 {
673 	const device_handle_t *rv = dev->deps;
674 	size_t region = 0;
675 	size_t i = 0;
676 
677 	if (rv != NULL) {
678 		/* Fast forward to injected devices */
679 		while (region != 1) {
680 			if (*rv == Z_DEVICE_DEPS_SEP) {
681 				region++;
682 			}
683 			rv++;
684 		}
685 		while ((rv[i] != Z_DEVICE_DEPS_ENDS) &&
686 		       (rv[i] != Z_DEVICE_DEPS_SEP)) {
687 			++i;
688 		}
689 		*count = i;
690 	}
691 
692 	return rv;
693 }
694 
695 /**
696  * @brief Get the set of handles that this device supports.
697  *
698  * This function returns a pointer to an array of device handles. The length of
699  * the array is stored in the @p count parameter.
700  *
701  * The array contains a handle for each device that @p dev "supports" -- that
702  * is, devices that require @p dev directly -- as determined from the
703  * devicetree. This does not include transitive dependencies; you must
704  * recursively determine those.
705  *
706  * @param dev the device for which supports are desired.
707  * @param count pointer to where this function should store the length of the
708  * returned array. No value is stored if the call returns a null pointer. The
709  * value may be set to zero if nothing in the devicetree depends on @p dev.
710  *
711  * @return a pointer to a sequence of @p *count device handles, or a null
712  * pointer if @p dev does not have any dependency data.
713  */
714 static inline const device_handle_t *
device_supported_handles_get(const struct device * dev,size_t * count)715 device_supported_handles_get(const struct device *dev, size_t *count)
716 {
717 	const device_handle_t *rv = dev->deps;
718 	size_t region = 0;
719 	size_t i = 0;
720 
721 	if (rv != NULL) {
722 		/* Fast forward to supporting devices */
723 		while (region != 2) {
724 			if (*rv == Z_DEVICE_DEPS_SEP) {
725 				region++;
726 			}
727 			rv++;
728 		}
729 		/* Count supporting devices.
730 		 * Trailing NULL's can be injected by gen_device_deps.py due to
731 		 * CONFIG_PM_DEVICE_POWER_DOMAIN_DYNAMIC_NUM
732 		 */
733 		while ((rv[i] != Z_DEVICE_DEPS_ENDS) &&
734 		       (rv[i] != DEVICE_HANDLE_NULL)) {
735 			++i;
736 		}
737 		*count = i;
738 	}
739 
740 	return rv;
741 }
742 
743 /**
744  * @brief Visit every device that @p dev directly requires.
745  *
746  * Zephyr maintains information about which devices are directly required by
747  * another device; for example an I2C-based sensor driver will require an I2C
748  * controller for communication. Required devices can derive from
749  * statically-defined devicetree relationships or dependencies registered at
750  * runtime.
751  *
752  * This API supports operating on the set of required devices. Example uses
753  * include making sure required devices are ready before the requiring device is
754  * used, and releasing them when the requiring device is no longer needed.
755  *
756  * There is no guarantee on the order in which required devices are visited.
757  *
758  * If the @p visitor_cb function returns a negative value iteration is halted,
759  * and the returned value from the visitor is returned from this function.
760  *
761  * @note This API is not available to unprivileged threads.
762  *
763  * @param dev a device of interest. The devices that this device depends on will
764  * be used as the set of devices to visit. This parameter must not be null.
765  * @param visitor_cb the function that should be invoked on each device in the
766  * dependency set. This parameter must not be null.
767  * @param context state that is passed through to the visitor function. This
768  * parameter may be null if @p visitor_cb tolerates a null @p context.
769  *
770  * @return The number of devices that were visited if all visits succeed, or
771  * the negative value returned from the first visit that did not succeed.
772  */
773 int device_required_foreach(const struct device *dev,
774 			    device_visitor_callback_t visitor_cb,
775 			    void *context);
776 
777 /**
778  * @brief Visit every device that @p dev directly supports.
779  *
780  * Zephyr maintains information about which devices are directly supported by
781  * another device; for example an I2C controller will support an I2C-based
782  * sensor driver. Supported devices can derive from statically-defined
783  * devicetree relationships.
784  *
785  * This API supports operating on the set of supported devices. Example uses
786  * include iterating over the devices connected to a regulator when it is
787  * powered on.
788  *
789  * There is no guarantee on the order in which required devices are visited.
790  *
791  * If the @p visitor_cb function returns a negative value iteration is halted,
792  * and the returned value from the visitor is returned from this function.
793  *
794  * @note This API is not available to unprivileged threads.
795  *
796  * @param dev a device of interest. The devices that this device supports
797  * will be used as the set of devices to visit. This parameter must not be null.
798  * @param visitor_cb the function that should be invoked on each device in the
799  * support set. This parameter must not be null.
800  * @param context state that is passed through to the visitor function. This
801  * parameter may be null if @p visitor_cb tolerates a null @p context.
802  *
803  * @return The number of devices that were visited if all visits succeed, or the
804  * negative value returned from the first visit that did not succeed.
805  */
806 int device_supported_foreach(const struct device *dev,
807 			     device_visitor_callback_t visitor_cb,
808 			     void *context);
809 
810 #endif /* CONFIG_DEVICE_DEPS */
811 
812 /**
813  * @brief Get a @ref device reference from its @ref device.name field.
814  *
815  * This function iterates through the devices on the system. If a device with
816  * the given @p name field is found, and that device initialized successfully at
817  * boot time, this function returns a pointer to the device.
818  *
819  * If no device has the given @p name, this function returns `NULL`.
820  *
821  * This function also returns NULL when a device is found, but it failed to
822  * initialize successfully at boot time. (To troubleshoot this case, set a
823  * breakpoint on your device driver's initialization function.)
824  *
825  * @param name device name to search for. A null pointer, or a pointer to an
826  * empty string, will cause NULL to be returned.
827  *
828  * @return pointer to device structure with the given name; `NULL` if the device
829  * is not found or if the device with that name's initialization function
830  * failed.
831  */
832 __syscall const struct device *device_get_binding(const char *name);
833 
834 /**
835  * @brief Get access to the static array of static devices.
836  *
837  * @param devices where to store the pointer to the array of statically
838  * allocated devices. The array must not be mutated through this pointer.
839  *
840  * @return the number of statically allocated devices.
841  */
842 size_t z_device_get_all_static(const struct device **devices);
843 
844 /**
845  * @brief Verify that a device is ready for use.
846  *
847  * Indicates whether the provided device pointer is for a device known to be
848  * in a state where it can be used with its standard API.
849  *
850  * This can be used with device pointers captured from DEVICE_DT_GET(), which
851  * does not include the readiness checks of device_get_binding(). At minimum
852  * this means that the device has been successfully initialized.
853  *
854  * @param dev pointer to the device in question.
855  *
856  * @retval true If the device is ready for use.
857  * @retval false If the device is not ready for use or if a NULL device pointer
858  * is passed as argument.
859  */
860 __syscall bool device_is_ready(const struct device *dev);
861 
862 /**
863  * @brief Initialize a device.
864  *
865  * A device whose initialization was deferred (by marking it as
866  * ``zephyr,deferred-init`` on devicetree) needs to be initialized manually via
867  * this call. De-initialized devices can also be initialized again via this
868  * call.
869  *
870  * @param dev device to be initialized.
871  *
872  * @retval -EALREADY Device is already initialized.
873  * @retval -errno For other errors.
874  */
875 __syscall int device_init(const struct device *dev);
876 
877 /**
878  * @brief De-initialize a device.
879  *
880  * When a device is de-initialized, it will release any resources it has
881  * acquired (e.g. pins, memory, clocks, DMA channels, etc.) and its status will
882  * be left as in its reset state.
883  *
884  * @warning It is the responsability of the caller to ensure that the device is
885  * ready to be de-initialized.
886  *
887  * @param dev device to be de-initialized.
888  *
889  * @retval 0 If successful
890  * @retval -EPERM If device has not been initialized.
891  * @retval -ENOTSUP If device does not support de-initialization.
892  * @retval -errno For any other errors.
893  */
894 __syscall int device_deinit(const struct device *dev);
895 
896 /**
897  * @}
898  */
899 
900 /** @cond INTERNAL_HIDDEN */
901 
902 /**
903  * @brief Synthesize a unique name for the device state associated with
904  * @p dev_id.
905  */
906 #define Z_DEVICE_STATE_NAME(dev_id) _CONCAT(__devstate_, dev_id)
907 
908 /**
909  * @brief Utility macro to define and initialize the device state.
910  *
911  * @param dev_id Device identifier.
912  */
913 #define Z_DEVICE_STATE_DEFINE(dev_id)                                          \
914 	static Z_DECL_ALIGN(struct device_state) Z_DEVICE_STATE_NAME(dev_id)   \
915 		__attribute__((__section__(".z_devstate")))
916 
917 /**
918  * @brief Device flags obtained from DT.
919  *
920  * @param node_id Devicetree node identifier.
921  */
922 #define Z_DEVICE_DT_FLAGS(node_id)                                             \
923 	(DT_PROP_OR(node_id, zephyr_deferred_init, 0U) * DEVICE_FLAG_INIT_DEFERRED)
924 
925 #if defined(CONFIG_DEVICE_DEPS) || defined(__DOXYGEN__)
926 
927 /**
928  * @brief Synthesize the name of the object that holds device ordinal and
929  * dependency data.
930  *
931  * @param dev_id Device identifier.
932  */
933 #define Z_DEVICE_DEPS_NAME(dev_id) _CONCAT(__devicedeps_, dev_id)
934 
935 /**
936  * @brief Expand extra dependencies with a comma in between.
937  *
938  * @param ... Extra dependencies.
939  */
940 #define Z_DEVICE_EXTRA_DEPS(...)                                            \
941 	FOR_EACH_NONEMPTY_TERM(IDENTITY, (,), __VA_ARGS__)
942 
943 /** @brief Linker section were device dependencies are placed. */
944 #define Z_DEVICE_DEPS_SECTION                                               \
945 	__attribute__((__section__(".__device_deps_pass1")))
946 
947 #ifdef __cplusplus
948 #define Z_DEVICE_DEPS_EXTERN extern
949 #else
950 #define Z_DEVICE_DEPS_EXTERN
951 #endif
952 
953 /**
954  * @brief Define device dependencies.
955  *
956  * Initial build provides a record that associates the device object with its
957  * devicetree ordinal, and provides the dependency ordinals. These are provided
958  * as weak definitions (to prevent the reference from being captured when the
959  * original object file is compiled), and in a distinct pass1 section (which
960  * will be replaced by postprocessing).
961  *
962  * Before processing in gen_device_deps.py, the array format is:
963  * {
964  *     DEVICE_ORDINAL (or DEVICE_HANDLE_NULL if not a devicetree node),
965  *     List of devicetree dependency ordinals (if any),
966  *     Z_DEVICE_DEPS_SEP,
967  *     List of injected dependency ordinals (if any),
968  *     Z_DEVICE_DEPS_SEP,
969  *     List of devicetree supporting ordinals (if any),
970  * }
971  *
972  * After processing in gen_device_deps.py, the format is updated to:
973  * {
974  *     List of existing devicetree dependency handles (if any),
975  *     Z_DEVICE_DEPS_SEP,
976  *     List of injected devicetree dependency handles (if any),
977  *     Z_DEVICE_DEPS_SEP,
978  *     List of existing devicetree support handles (if any),
979  *     DEVICE_HANDLE_NULL
980  * }
981  *
982  * It is also (experimentally) necessary to provide explicit alignment on each
983  * object. Otherwise x86-64 builds will introduce padding between objects in the
984  * same input section in individual object files, which will be retained in
985  * subsequent links both wasting space and resulting in aggregate size changes
986  * relative to pass2 when all objects will be in the same input section.
987  */
988 #define Z_DEVICE_DEPS_DEFINE(node_id, dev_id, ...)                             \
989 	extern Z_DEVICE_DEPS_CONST device_handle_t Z_DEVICE_DEPS_NAME(         \
990 		dev_id)[];                                                     \
991 	Z_DEVICE_DEPS_CONST Z_DECL_ALIGN(device_handle_t)                      \
992 	Z_DEVICE_DEPS_SECTION Z_DEVICE_DEPS_EXTERN __weak                      \
993 		Z_DEVICE_DEPS_NAME(dev_id)[] = {                               \
994 		COND_CODE_1(                                                   \
995 			DT_NODE_EXISTS(node_id),                               \
996 			(DT_DEP_ORD(node_id), DT_REQUIRES_DEP_ORDS(node_id)),  \
997 			(DEVICE_HANDLE_NULL,)) /**/                            \
998 		Z_DEVICE_DEPS_SEP,                                             \
999 		Z_DEVICE_EXTRA_DEPS(__VA_ARGS__) /**/                          \
1000 		Z_DEVICE_DEPS_SEP,                                             \
1001 		COND_CODE_1(DT_NODE_EXISTS(node_id),                           \
1002 			    (DT_SUPPORTS_DEP_ORDS(node_id)), ()) /**/          \
1003 	}
1004 
1005 #endif /* CONFIG_DEVICE_DEPS */
1006 #if defined(CONFIG_DEVICE_DT_METADATA) || defined(__DOXYGEN__)
1007 /**
1008  * @brief Devicetree node labels associated with a device
1009  */
1010 struct device_dt_nodelabels {
1011 	/* @brief number of elements in the nodelabels array */
1012 	size_t num_nodelabels;
1013 	/* @brief array of node labels as strings, exactly as they
1014 	 *        appear in the final devicetree
1015 	 */
1016 	const char *nodelabels[];
1017 };
1018 
1019 /**
1020  * @brief Devicetree metadata associated with a device
1021  *
1022  * This is currently limited to node labels, but the structure is
1023  * generic enough to be extended later without requiring breaking
1024  * changes.
1025  */
1026 struct device_dt_metadata {
1027 	/**
1028 	 * @brief Node labels associated with the device
1029 	 * @see device_get_dt_nodelabels()
1030 	 */
1031 	const struct device_dt_nodelabels *nl;
1032 };
1033 
1034 /**
1035  * @brief Get a @ref device reference from a devicetree node label.
1036  *
1037  * If:
1038  *
1039  * 1. a device was defined from a devicetree node, for example
1040  *    with DEVICE_DT_DEFINE() or another similar macro, and
1041  * 2. that devicetree node has @p nodelabel as one of its node labels, and
1042  * 3. the device initialized successfully at boot time,
1043  *
1044  * then this function returns a pointer to the device. Otherwise, it
1045  * returns NULL.
1046  *
1047  * @param nodelabel a devicetree node label
1048  * @return a device reference for a device created from a node with that
1049  *         node label, or NULL if either no such device exists or the device
1050  *         failed to initialize
1051  */
1052 __syscall const struct device *device_get_by_dt_nodelabel(const char *nodelabel);
1053 
1054 /**
1055  * @brief Get the devicetree node labels associated with a device
1056  * @param dev device whose metadata to look up
1057  * @return information about the devicetree node labels or NULL if not available
1058  */
1059 static inline const struct device_dt_nodelabels *
device_get_dt_nodelabels(const struct device * dev)1060 device_get_dt_nodelabels(const struct device *dev)
1061 {
1062 	if (dev->dt_meta == NULL) {
1063 		return NULL;
1064 	}
1065 	return dev->dt_meta->nl;
1066 }
1067 
1068 /**
1069  * @brief Maximum devicetree node label length.
1070  *
1071  * The maximum length is set so that device_get_by_dt_nodelabel() can
1072  * be used from userspace.
1073  */
1074 #define Z_DEVICE_MAX_NODELABEL_LEN Z_DEVICE_MAX_NAME_LEN
1075 
1076 /**
1077  * @brief Name of the identifier for a device's DT metadata structure
1078  * @param dev_id device identifier
1079  */
1080 #define Z_DEVICE_DT_METADATA_NAME_GET(dev_id) UTIL_CAT(__dev_dt_meta_, dev_id)
1081 
1082 /**
1083  * @brief Name of the identifier for the array of node label strings
1084  *        saved for a device.
1085  */
1086 #define Z_DEVICE_DT_NODELABELS_NAME_GET(dev_id) UTIL_CAT(__dev_dt_nodelabels_, dev_id)
1087 
1088 /**
1089  * @brief Initialize an entry in the device DT node label lookup table
1090  *
1091  * Allocates and initializes a struct device_dt_metadata in the
1092  * appropriate iterable section for use finding devices.
1093  */
1094 #define Z_DEVICE_DT_METADATA_DEFINE(node_id, dev_id)			\
1095 	static const struct device_dt_nodelabels			\
1096 	Z_DEVICE_DT_NODELABELS_NAME_GET(dev_id) = {			\
1097 		.num_nodelabels = DT_NUM_NODELABELS(node_id),		\
1098 		.nodelabels = DT_NODELABEL_STRING_ARRAY(node_id),	\
1099 	};								\
1100 									\
1101 	static const struct device_dt_metadata				\
1102 	Z_DEVICE_DT_METADATA_NAME_GET(dev_id) = {			\
1103 		.nl = &Z_DEVICE_DT_NODELABELS_NAME_GET(dev_id),			\
1104 	};
1105 #endif  /* CONFIG_DEVICE_DT_METADATA */
1106 
1107 /**
1108  * @brief Init sub-priority of the device
1109  *
1110  * The sub-priority is defined by the devicetree ordinal, which ensures that
1111  * multiple drivers running at the same priority level run in an order that
1112  * respects the devicetree dependencies.
1113  */
1114 #define Z_DEVICE_INIT_SUB_PRIO(node_id)                                        \
1115 	COND_CODE_1(DT_NODE_EXISTS(node_id),                                   \
1116 		    (DT_DEP_ORD_STR_SORTABLE(node_id)), (0))
1117 
1118 /**
1119  * @brief Maximum device name length.
1120  *
1121  * The maximum length is set so that device_get_binding() can be used from
1122  * userspace.
1123  */
1124 #define Z_DEVICE_MAX_NAME_LEN 48U
1125 
1126 /**
1127  * @brief Compile time check for device name length
1128  *
1129  * @param name Device name.
1130  */
1131 #define Z_DEVICE_NAME_CHECK(name)                                              \
1132 	BUILD_ASSERT(sizeof(Z_STRINGIFY(name)) <= Z_DEVICE_MAX_NAME_LEN,       \
1133 			    Z_STRINGIFY(name) " too long")
1134 
1135 /**
1136  * @brief Initializer for @ref device.
1137  *
1138  * @param name_ Name of the device.
1139  * @param init_fn_ Init function (optional).
1140  * @param deinit_fn_ De-init function (optional).
1141  * @param flags_ Device flags.
1142  * @param pm_ Reference to @ref pm_device_base (optional).
1143  * @param data_ Reference to device data.
1144  * @param config_ Reference to device config.
1145  * @param api_ Reference to device API ops.
1146  * @param state_ Reference to device state.
1147  * @param deps_ Reference to device dependencies.
1148  * @param node_id_ Devicetree node identifier
1149  * @param dev_id_ Device identifier token, as passed to Z_DEVICE_BASE_DEFINE
1150  */
1151 #define Z_DEVICE_INIT(name_, init_fn_, deinit_fn_, flags_, pm_, data_, config_, api_,   \
1152 		      state_, deps_, node_id_, dev_id_)					\
1153 	{										\
1154 		.name = name_,								\
1155 		.config = (config_),							\
1156 		.api = (api_),								\
1157 		.state = (state_),							\
1158 		.data = (data_),							\
1159 		.ops = { .init = (init_fn_), .deinit = (deinit_fn_) },			\
1160 		.flags = (flags_),							\
1161 		IF_ENABLED(CONFIG_DEVICE_DEPS, (.deps = (deps_),)) /**/			\
1162 		IF_ENABLED(CONFIG_PM_DEVICE, Z_DEVICE_INIT_PM_BASE(pm_)) /**/		\
1163 		IF_ENABLED(CONFIG_DEVICE_DT_METADATA,					\
1164 			   (IF_ENABLED(DT_NODE_EXISTS(node_id_),			\
1165 				       (.dt_meta = &Z_DEVICE_DT_METADATA_NAME_GET(	\
1166 						dev_id_),))))				\
1167 	}
1168 
1169 /*
1170  * Anonymous unions require C11. Some pre-C11 gcc versions have early support for anonymous
1171  * unions but they require these braces when combined with C99 designated initializers. For
1172  * more details see https://docs.zephyrproject.org/latest/develop/languages/cpp/
1173  */
1174 #if defined(__STDC_VERSION__) && (__STDC_VERSION__) < 201100
1175 #  define Z_DEVICE_INIT_PM_BASE(pm_) ({ .pm_base = (pm_),},)
1176 #else
1177 #  define Z_DEVICE_INIT_PM_BASE(pm_)   (.pm_base = (pm_),)
1178 #endif
1179 
1180 /**
1181  * @brief Device section name (used for sorting purposes).
1182  *
1183  * @param level Initialization level
1184  * @param prio Initialization priority
1185  */
1186 #define Z_DEVICE_SECTION_NAME(level, prio)                                     \
1187 	_CONCAT(INIT_LEVEL_ORD(level), _##prio)
1188 
1189 /**
1190  * @brief Define a @ref device
1191  *
1192  * @param node_id Devicetree node id for the device (DT_INVALID_NODE if a
1193  * software device).
1194  * @param dev_id Device identifier (used to name the defined @ref device).
1195  * @param name Name of the device.
1196  * @param init_fn Init function.
1197  * @param deinit_fn De-init function.
1198  * @param flags Device flags.
1199  * @param pm Reference to @ref pm_device_base associated with the device.
1200  * (optional).
1201  * @param data Reference to device data.
1202  * @param config Reference to device config.
1203  * @param level Initialization level.
1204  * @param prio Initialization priority.
1205  * @param api Reference to device API.
1206  * @param ... Optional dependencies, manually specified.
1207  */
1208 #define Z_DEVICE_BASE_DEFINE(node_id, dev_id, name, init_fn, deinit_fn, flags, pm, data, config,   \
1209 			     level, prio, api, state, deps)                                        \
1210 	COND_CODE_1(DT_NODE_EXISTS(node_id), (), (static))                                         \
1211 	COND_CODE_1(Z_DEVICE_IS_MUTABLE(node_id), (), (const))                                     \
1212 	STRUCT_SECTION_ITERABLE_NAMED_ALTERNATE(                                                   \
1213 		device, COND_CODE_1(Z_DEVICE_IS_MUTABLE(node_id), (device_mutable), (device)),     \
1214 		Z_DEVICE_SECTION_NAME(level, prio), DEVICE_NAME_GET(dev_id)) =                     \
1215 		Z_DEVICE_INIT(name, init_fn, deinit_fn, flags, pm, data, config, api, state, deps, \
1216 			      node_id, dev_id)
1217 
1218 /**
1219  * @brief Issue an error if the given init level is not supported.
1220  *
1221  * @param level Init level
1222  */
1223 #define Z_DEVICE_CHECK_INIT_LEVEL(level)                                       \
1224 	COND_CODE_1(Z_INIT_PRE_KERNEL_1_##level, (),                           \
1225 	(COND_CODE_1(Z_INIT_PRE_KERNEL_2_##level, (),                          \
1226 	(COND_CODE_1(Z_INIT_POST_KERNEL_##level, (),                           \
1227 	(ZERO_OR_COMPILE_ERROR(0)))))))
1228 
1229 /**
1230  * @brief Define the init entry for a device.
1231  *
1232  * @param node_id Devicetree node id for the device (DT_INVALID_NODE if a
1233  * software device).
1234  * @param dev_id Device identifier.
1235  * @param level Initialization level.
1236  * @param prio Initialization priority.
1237  */
1238 #define Z_DEVICE_INIT_ENTRY_DEFINE(node_id, dev_id, level, prio)                                   \
1239 	Z_DEVICE_CHECK_INIT_LEVEL(level)                                                           \
1240                                                                                                    \
1241 	static const Z_DECL_ALIGN(struct init_entry) __used __noasan Z_INIT_ENTRY_SECTION(         \
1242 		level, prio, Z_DEVICE_INIT_SUB_PRIO(node_id))                                      \
1243 		Z_INIT_ENTRY_NAME(DEVICE_NAME_GET(dev_id)) = {                                     \
1244 			.init_fn = NULL,                                                           \
1245 			.dev = (const struct device *)&DEVICE_NAME_GET(dev_id),                    \
1246 		}
1247 
1248 /**
1249  * @brief Define a @ref device and all other required objects.
1250  *
1251  * This is the common macro used to define @ref device objects. It can be used
1252  * to define both Devicetree and software devices.
1253  *
1254  * @param node_id Devicetree node id for the device (DT_INVALID_NODE if a
1255  * software device).
1256  * @param dev_id Device identifier (used to name the defined @ref device).
1257  * @param name Name of the device.
1258  * @param init_fn Device init function.
1259  * @param flags Device flags.
1260  * @param pm Reference to @ref pm_device_base associated with the device.
1261  * (optional).
1262  * @param data Reference to device data.
1263  * @param config Reference to device config.
1264  * @param level Initialization level.
1265  * @param prio Initialization priority.
1266  * @param api Reference to device API.
1267  * @param state Reference to device state.
1268  * @param ... Optional dependencies, manually specified.
1269  */
1270 #define Z_DEVICE_DEFINE(node_id, dev_id, name, init_fn, deinit_fn, flags, pm,   \
1271 			data, config, level, prio, api, state, ...)             \
1272 	Z_DEVICE_NAME_CHECK(name);                                              \
1273                                                                                 \
1274 	IF_ENABLED(CONFIG_DEVICE_DEPS,                                          \
1275 		   (Z_DEVICE_DEPS_DEFINE(node_id, dev_id, __VA_ARGS__);))       \
1276                                                                                 \
1277 	IF_ENABLED(CONFIG_DEVICE_DT_METADATA,                                   \
1278 		   (IF_ENABLED(DT_NODE_EXISTS(node_id),                         \
1279 			      (Z_DEVICE_DT_METADATA_DEFINE(node_id, dev_id);))))\
1280                                                                                 \
1281 	Z_DEVICE_BASE_DEFINE(node_id, dev_id, name, init_fn, deinit_fn, flags,  \
1282 			     pm, data, config, level, prio, api, state,         \
1283 			     Z_DEVICE_DEPS_NAME(dev_id));                       \
1284                                                                                 \
1285 	Z_DEVICE_INIT_ENTRY_DEFINE(node_id, dev_id, level, prio);               \
1286                                                                                 \
1287 	IF_ENABLED(CONFIG_LLEXT_EXPORT_DEVICES,                                 \
1288 		(IF_ENABLED(DT_NODE_EXISTS(node_id),                            \
1289 				(Z_DEVICE_EXPORT(node_id);))))
1290 
1291 /**
1292  * @brief Declare a device for each status "okay" devicetree node.
1293  *
1294  * @note Disabled nodes should not result in devices, so not predeclaring these
1295  * keeps drivers honest.
1296  *
1297  * This is only "maybe" a device because some nodes have status "okay", but
1298  * don't have a corresponding @ref device allocated. There's no way to figure
1299  * that out until after we've built the zephyr image, though.
1300  */
1301 #define Z_MAYBE_DEVICE_DECLARE_INTERNAL(node_id)                                                   \
1302 	extern COND_CODE_1(Z_DEVICE_IS_MUTABLE(node_id), (),                                       \
1303 			   (const)) struct device DEVICE_DT_NAME_GET(node_id);
1304 
1305 DT_FOREACH_STATUS_OKAY_NODE(Z_MAYBE_DEVICE_DECLARE_INTERNAL)
1306 
1307 /** @brief Expands to the full type. */
1308 #define Z_DEVICE_API_TYPE(_class) _CONCAT(_class, _driver_api)
1309 
1310 /** @endcond */
1311 
1312 /**
1313  * @brief Wrapper macro for declaring device API structs inside iterable sections.
1314  *
1315  * @param _class The device API class.
1316  * @param _name The API instance name.
1317  */
1318 #define DEVICE_API(_class, _name) const STRUCT_SECTION_ITERABLE(Z_DEVICE_API_TYPE(_class), _name)
1319 
1320 /**
1321  * @brief Expands to the pointer of a device's API for a given class.
1322  *
1323  * @param _class The device API class.
1324  * @param _dev The device instance pointer.
1325  *
1326  * @return the pointer to the device API.
1327  */
1328 #define DEVICE_API_GET(_class, _dev) ((const struct Z_DEVICE_API_TYPE(_class) *)_dev->api)
1329 
1330 /**
1331  * @brief Macro that evaluates to a boolean that can be used to check if
1332  *        a device is of a particular class.
1333  *
1334  * @param _class The device API class.
1335  * @param _dev The device instance pointer.
1336  *
1337  * @retval true If the device is of the given class
1338  * @retval false If the device is not of the given class
1339  */
1340 #define DEVICE_API_IS(_class, _dev)                                                                \
1341 	({                                                                                         \
1342 		STRUCT_SECTION_START_EXTERN(Z_DEVICE_API_TYPE(_class));                            \
1343 		STRUCT_SECTION_END_EXTERN(Z_DEVICE_API_TYPE(_class));                              \
1344 		(DEVICE_API_GET(_class, _dev) < STRUCT_SECTION_END(Z_DEVICE_API_TYPE(_class)) &&   \
1345 		 DEVICE_API_GET(_class, _dev) >= STRUCT_SECTION_START(Z_DEVICE_API_TYPE(_class))); \
1346 	})
1347 
1348 #ifdef __cplusplus
1349 }
1350 #endif
1351 
1352 #include <zephyr/syscalls/device.h>
1353 
1354 #endif /* ZEPHYR_INCLUDE_DEVICE_H_ */
1355