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/sys/device_mmio.h>
16 #include <zephyr/sys/iterable_sections.h>
17 #include <zephyr/sys/util.h>
18 #include <zephyr/toolchain.h>
19 
20 #ifdef __cplusplus
21 extern "C" {
22 #endif
23 
24 /**
25  * @brief Device Model
26  * @defgroup device_model Device Model
27  * @{
28  */
29 
30 /** @cond INTERNAL_HIDDEN */
31 
32 /**
33  * @brief Flag value used in lists of device dependencies to separate distinct
34  * groups.
35  */
36 #define Z_DEVICE_DEPS_SEP INT16_MIN
37 
38 /**
39  * @brief Flag value used in lists of device dependencies to indicate the end of
40  * the list.
41  */
42 #define Z_DEVICE_DEPS_ENDS INT16_MAX
43 
44 /** @endcond */
45 
46 /**
47  * @brief Type used to represent a "handle" for a device.
48  *
49  * Every @ref device has an associated handle. You can get a pointer to a
50  * @ref device from its handle and vice versa, but the handle uses less space
51  * than a pointer. The device.h API mainly uses handles to store lists of
52  * multiple devices in a compact way.
53  *
54  * The extreme values and zero have special significance. Negative values
55  * identify functionality that does not correspond to a Zephyr device, such as
56  * the system clock or a SYS_INIT() function.
57  *
58  * @see device_handle_get()
59  * @see device_from_handle()
60  */
61 typedef int16_t device_handle_t;
62 
63 /** @brief Flag value used to identify an unknown device. */
64 #define DEVICE_HANDLE_NULL 0
65 
66 /**
67  * @brief Expands to the name of a global device object.
68  *
69  * Return the full name of a device object symbol created by DEVICE_DEFINE(),
70  * using the `dev_id` provided to DEVICE_DEFINE(). This is the name of the
71  * global variable storing the device structure, not a pointer to the string in
72  * the @ref device.name field.
73  *
74  * It is meant to be used for declaring extern symbols pointing to device
75  * objects before using the DEVICE_GET macro to get the device object.
76  *
77  * This macro is normally only useful within device driver source code. In other
78  * situations, you are probably looking for device_get_binding().
79  *
80  * @param dev_id Device identifier.
81  *
82  * @return The full name of the device object defined by device definition
83  * macros.
84  */
85 #define DEVICE_NAME_GET(dev_id) _CONCAT(__device_, dev_id)
86 
87 /* Node paths can exceed the maximum size supported by
88  * device_get_binding() in user mode; this macro synthesizes a unique
89  * dev_id from a devicetree node while staying within this maximum
90  * size.
91  *
92  * The ordinal used in this name can be mapped to the path by
93  * examining zephyr/include/generated/devicetree_generated.h.
94  */
95 #define Z_DEVICE_DT_DEV_ID(node_id) _CONCAT(dts_ord_, DT_DEP_ORD(node_id))
96 
97 /**
98  * @brief Create a device object and set it up for boot time initialization.
99  *
100  * This macro defines a @ref device that is automatically configured by the
101  * kernel during system initialization. This macro should only be used when the
102  * device is not being allocated from a devicetree node. If you are allocating a
103  * device from a devicetree node, use DEVICE_DT_DEFINE() or
104  * DEVICE_DT_INST_DEFINE() instead.
105  *
106  * @param dev_id A unique token which is used in the name of the global device
107  * structure as a C identifier.
108  * @param name A string name for the device, which will be stored in
109  * @ref device.name. This name can be used to look up the device with
110  * device_get_binding(). This must be less than Z_DEVICE_MAX_NAME_LEN characters
111  * (including terminating `NULL`) in order to be looked up from user mode.
112  * @param init_fn Pointer to the device's initialization function, which will be
113  * run by the kernel during system initialization. Can be `NULL`.
114  * @param pm Pointer to the device's power management resources, a
115  * @ref pm_device, which will be stored in @ref device.pm field. Use `NULL` if
116  * the device does not use PM.
117  * @param data Pointer to the device's private mutable data, which will be
118  * stored in @ref device.data.
119  * @param config Pointer to the device's private constant data, which will be
120  * stored in @ref device.config.
121  * @param level The device's initialization level (PRE_KERNEL_1, PRE_KERNEL_2 or
122  * POST_KERNEL).
123  * @param prio The device's priority within its initialization level. See
124  * SYS_INIT() for details.
125  * @param api Pointer to the device's API structure. Can be `NULL`.
126  */
127 #define DEVICE_DEFINE(dev_id, name, init_fn, pm, data, config, level, prio,    \
128 		      api)                                                     \
129 	Z_DEVICE_STATE_DEFINE(dev_id);                                         \
130 	Z_DEVICE_DEFINE(DT_INVALID_NODE, dev_id, name, init_fn, pm, data,      \
131 			config, level, prio, api,                              \
132 			&Z_DEVICE_STATE_NAME(dev_id))
133 
134 /**
135  * @brief Return a string name for a devicetree node.
136  *
137  * This macro returns a string literal usable as a device's name from a
138  * devicetree node identifier.
139  *
140  * @param node_id The devicetree node identifier.
141  *
142  * @return The value of the node's `label` property, if it has one.
143  * Otherwise, the node's full name in `node-name@unit-address` form.
144  */
145 #define DEVICE_DT_NAME(node_id)                                                \
146 	DT_PROP_OR(node_id, label, DT_NODE_FULL_NAME(node_id))
147 
148 /**
149  * @brief Create a device object from a devicetree node identifier and set it up
150  * for boot time initialization.
151  *
152  * This macro defines a @ref device that is automatically configured by the
153  * kernel during system initialization. The global device object's name as a C
154  * identifier is derived from the node's dependency ordinal. @ref device.name is
155  * set to `DEVICE_DT_NAME(node_id)`.
156  *
157  * The device is declared with extern visibility, so a pointer to a global
158  * device object can be obtained with `DEVICE_DT_GET(node_id)` from any source
159  * file that includes `<zephyr/device.h>`. Before using the pointer, the
160  * referenced object should be checked using device_is_ready().
161  *
162  * @param node_id The devicetree node identifier.
163  * @param init_fn Pointer to the device's initialization function, which will be
164  * run by the kernel during system initialization. Can be `NULL`.
165  * @param pm Pointer to the device's power management resources, a
166  * @ref pm_device, which will be stored in @ref device.pm. Use `NULL` if the
167  * device does not use PM.
168  * @param data Pointer to the device's private mutable data, which will be
169  * stored in @ref device.data.
170  * @param config Pointer to the device's private constant data, which will be
171  * stored in @ref device.config field.
172  * @param level The device's initialization level (PRE_KERNEL_1, PRE_KERNEL_2 or
173  * POST_KERNEL).
174  * @param prio The device's priority within its initialization level. See
175  * SYS_INIT() for details.
176  * @param api Pointer to the device's API structure. Can be `NULL`.
177  */
178 #define DEVICE_DT_DEFINE(node_id, init_fn, pm, data, config, level, prio, api, \
179 			 ...)                                                  \
180 	Z_DEVICE_STATE_DEFINE(Z_DEVICE_DT_DEV_ID(node_id));                    \
181 	Z_DEVICE_DEFINE(node_id, Z_DEVICE_DT_DEV_ID(node_id),                  \
182 			DEVICE_DT_NAME(node_id), init_fn, pm, data, config,    \
183 			level, prio, api,                                      \
184 			&Z_DEVICE_STATE_NAME(Z_DEVICE_DT_DEV_ID(node_id)),     \
185 			__VA_ARGS__)
186 
187 /**
188  * @brief Like DEVICE_DT_DEFINE(), but uses an instance of a `DT_DRV_COMPAT`
189  * compatible instead of a node identifier.
190  *
191  * @param inst Instance number. The `node_id` argument to DEVICE_DT_DEFINE() is
192  * set to `DT_DRV_INST(inst)`.
193  * @param ... Other parameters as expected by DEVICE_DT_DEFINE().
194  */
195 #define DEVICE_DT_INST_DEFINE(inst, ...)                                       \
196 	DEVICE_DT_DEFINE(DT_DRV_INST(inst), __VA_ARGS__)
197 
198 /**
199  * @brief The name of the global device object for @p node_id
200  *
201  * Returns the name of the global device structure as a C identifier. The device
202  * must be allocated using DEVICE_DT_DEFINE() or DEVICE_DT_INST_DEFINE() for
203  * this to work.
204  *
205  * This macro is normally only useful within device driver source code. In other
206  * situations, you are probably looking for DEVICE_DT_GET().
207  *
208  * @param node_id Devicetree node identifier
209  *
210  * @return The name of the device object as a C identifier
211  */
212 #define DEVICE_DT_NAME_GET(node_id) DEVICE_NAME_GET(Z_DEVICE_DT_DEV_ID(node_id))
213 
214 /**
215  * @brief Get a @ref device reference from a devicetree node identifier.
216  *
217  * Returns a pointer to a device object created from a devicetree node, if any
218  * device was allocated by a driver.
219  *
220  * If no such device was allocated, this will fail at linker time. If you get an
221  * error that looks like `undefined reference to __device_dts_ord_<N>`, that is
222  * what happened. Check to make sure your device driver is being compiled,
223  * usually by enabling the Kconfig options it requires.
224  *
225  * @param node_id A devicetree node identifier
226  *
227  * @return A pointer to the device object created for that node
228  */
229 #define DEVICE_DT_GET(node_id) (&DEVICE_DT_NAME_GET(node_id))
230 
231 /**
232  * @brief Get a @ref device reference for an instance of a `DT_DRV_COMPAT`
233  * compatible.
234  *
235  * This is equivalent to `DEVICE_DT_GET(DT_DRV_INST(inst))`.
236  *
237  * @param inst `DT_DRV_COMPAT` instance number
238  * @return A pointer to the device object created for that instance
239  */
240 #define DEVICE_DT_INST_GET(inst) DEVICE_DT_GET(DT_DRV_INST(inst))
241 
242 /**
243  * @brief Get a @ref device reference from a devicetree compatible.
244  *
245  * If an enabled devicetree node has the given compatible and a device
246  * object was created from it, this returns a pointer to that device.
247  *
248  * If there no such devices, this returns NULL.
249  *
250  * If there are multiple, this returns an arbitrary one.
251  *
252  * If this returns non-NULL, the device must be checked for readiness
253  * before use, e.g. with device_is_ready().
254  *
255  * @param compat lowercase-and-underscores devicetree compatible
256  * @return a pointer to a device, or NULL
257  */
258 #define DEVICE_DT_GET_ANY(compat)                                              \
259 	COND_CODE_1(DT_HAS_COMPAT_STATUS_OKAY(compat),                         \
260 		    (DEVICE_DT_GET(DT_COMPAT_GET_ANY_STATUS_OKAY(compat))),    \
261 		    (NULL))
262 
263 /**
264  * @brief Get a @ref device reference from a devicetree compatible.
265  *
266  * If an enabled devicetree node has the given compatible and a device object
267  * was created from it, this returns a pointer to that device.
268  *
269  * If there are no such devices, this will fail at compile time.
270  *
271  * If there are multiple, this returns an arbitrary one.
272  *
273  * If this returns non-NULL, the device must be checked for readiness before
274  * use, e.g. with device_is_ready().
275  *
276  * @param compat lowercase-and-underscores devicetree compatible
277  * @return a pointer to a device
278  */
279 #define DEVICE_DT_GET_ONE(compat)                                              \
280 	COND_CODE_1(DT_HAS_COMPAT_STATUS_OKAY(compat),                         \
281 		    (DEVICE_DT_GET(DT_COMPAT_GET_ANY_STATUS_OKAY(compat))),    \
282 		    (ZERO_OR_COMPILE_ERROR(0)))
283 
284 /**
285  * @brief Utility macro to obtain an optional reference to a device.
286  *
287  * If the node identifier refers to a node with status `okay`, this returns
288  * `DEVICE_DT_GET(node_id)`. Otherwise, it returns `NULL`.
289  *
290  * @param node_id devicetree node identifier
291  *
292  * @return a @ref device reference for the node identifier, which may be `NULL`.
293  */
294 #define DEVICE_DT_GET_OR_NULL(node_id)                                         \
295 	COND_CODE_1(DT_NODE_HAS_STATUS(node_id, okay),                         \
296 		    (DEVICE_DT_GET(node_id)), (NULL))
297 
298 /**
299  * @brief Obtain a pointer to a device object by name
300  *
301  * @details Return the address of a device object created by
302  * DEVICE_DEFINE(), using the dev_id provided to DEVICE_DEFINE().
303  *
304  * @param dev_id Device identifier.
305  *
306  * @return A pointer to the device object created by DEVICE_DEFINE()
307  */
308 #define DEVICE_GET(dev_id) (&DEVICE_NAME_GET(dev_id))
309 
310 /**
311  * @brief Declare a static device object
312  *
313  * This macro can be used at the top-level to declare a device, such
314  * that DEVICE_GET() may be used before the full declaration in
315  * DEVICE_DEFINE().
316  *
317  * This is often useful when configuring interrupts statically in a
318  * device's init or per-instance config function, as the init function
319  * itself is required by DEVICE_DEFINE() and use of DEVICE_GET()
320  * inside it creates a circular dependency.
321  *
322  * @param dev_id Device identifier.
323  */
324 #define DEVICE_DECLARE(dev_id)                                                 \
325 	static const struct device DEVICE_NAME_GET(dev_id)
326 
327 /**
328  * @brief Get a @ref init_entry reference from a devicetree node.
329  *
330  * @param node_id A devicetree node identifier
331  *
332  * @return A pointer to the @ref init_entry object created for that node
333  */
334 #define DEVICE_INIT_DT_GET(node_id)                                            \
335 	(&Z_INIT_ENTRY_NAME(DEVICE_DT_NAME_GET(node_id)))
336 
337 /**
338  * @brief Get a @ref init_entry reference from a device identifier.
339  *
340  * @param dev_id Device identifier.
341  *
342  * @return A pointer to the init_entry object created for that device
343  */
344 #define DEVICE_INIT_GET(dev_id) (&Z_INIT_ENTRY_NAME(DEVICE_NAME_GET(dev_id)))
345 
346 /**
347  * @brief Runtime device dynamic structure (in RAM) per driver instance
348  *
349  * Fields in this are expected to be default-initialized to zero. The
350  * kernel driver infrastructure and driver access functions are
351  * responsible for ensuring that any non-zero initialization is done
352  * before they are accessed.
353  */
354 struct device_state {
355 	/**
356 	 * Device initialization return code (positive errno value).
357 	 *
358 	 * Device initialization functions return a negative errno code if they
359 	 * fail. In Zephyr, errno values do not exceed 255, so we can store the
360 	 * positive result value in a uint8_t type.
361 	 */
362 	uint8_t init_res;
363 
364 	/** Indicates the device initialization function has been
365 	 * invoked.
366 	 */
367 	bool initialized : 1;
368 };
369 
370 struct pm_device;
371 
372 #ifdef CONFIG_DEVICE_DEPS_DYNAMIC
373 #define Z_DEVICE_DEPS_CONST
374 #else
375 #define Z_DEVICE_DEPS_CONST const
376 #endif
377 
378 /**
379  * @brief Runtime device structure (in ROM) per driver instance
380  */
381 struct device {
382 	/** Name of the device instance */
383 	const char *name;
384 	/** Address of device instance config information */
385 	const void *config;
386 	/** Address of the API structure exposed by the device instance */
387 	const void *api;
388 	/** Address of the common device state */
389 	struct device_state *state;
390 	/** Address of the device instance private data */
391 	void *data;
392 #if defined(CONFIG_DEVICE_DEPS) || defined(__DOXYGEN__)
393 	/**
394 	 * Optional pointer to dependencies associated with the device.
395 	 *
396 	 * This encodes a sequence of sets of device handles that have some
397 	 * relationship to this node. The individual sets are extracted with
398 	 * dedicated API, such as device_required_handles_get(). Only available
399 	 * if @kconfig{CONFIG_DEVICE_DEPS} is enabled.
400 	 */
401 	Z_DEVICE_DEPS_CONST device_handle_t *deps;
402 #endif /* CONFIG_DEVICE_DEPS */
403 #if defined(CONFIG_PM_DEVICE) || defined(__DOXYGEN__)
404 	/**
405 	 * Reference to the device PM resources (only available if
406 	 * @kconfig{CONFIG_PM_DEVICE} is enabled).
407 	 */
408 	struct pm_device *pm;
409 #endif
410 };
411 
412 /**
413  * @brief Get the handle for a given device
414  *
415  * @param dev the device for which a handle is desired.
416  *
417  * @return the handle for the device, or DEVICE_HANDLE_NULL if the device does
418  * not have an associated handle.
419  */
device_handle_get(const struct device * dev)420 static inline device_handle_t device_handle_get(const struct device *dev)
421 {
422 	device_handle_t ret = DEVICE_HANDLE_NULL;
423 	STRUCT_SECTION_START_EXTERN(device);
424 
425 	/* TODO: If/when devices can be constructed that are not part of the
426 	 * fixed sequence we'll need another solution.
427 	 */
428 	if (dev != NULL) {
429 		ret = 1 + (device_handle_t)(dev - STRUCT_SECTION_START(device));
430 	}
431 
432 	return ret;
433 }
434 
435 /**
436  * @brief Get the device corresponding to a handle.
437  *
438  * @param dev_handle the device handle
439  *
440  * @return the device that has that handle, or a null pointer if @p dev_handle
441  * does not identify a device.
442  */
443 static inline const struct device *
device_from_handle(device_handle_t dev_handle)444 device_from_handle(device_handle_t dev_handle)
445 {
446 	STRUCT_SECTION_START_EXTERN(device);
447 	const struct device *dev = NULL;
448 	size_t numdev;
449 
450 	STRUCT_SECTION_COUNT(device, &numdev);
451 
452 	if ((dev_handle > 0) && ((size_t)dev_handle <= numdev)) {
453 		dev = &STRUCT_SECTION_START(device)[dev_handle - 1];
454 	}
455 
456 	return dev;
457 }
458 
459 #if defined(CONFIG_DEVICE_DEPS) || defined(__DOXYGEN__)
460 
461 /**
462  * @brief Prototype for functions used when iterating over a set of devices.
463  *
464  * Such a function may be used in API that identifies a set of devices and
465  * provides a visitor API supporting caller-specific interaction with each
466  * device in the set.
467  *
468  * The visit is said to succeed if the visitor returns a non-negative value.
469  *
470  * @param dev a device in the set being iterated
471  * @param context state used to support the visitor function
472  *
473  * @return A non-negative number to allow walking to continue, and a negative
474  * error code to case the iteration to stop.
475  *
476  * @see device_required_foreach()
477  * @see device_supported_foreach()
478  */
479 typedef int (*device_visitor_callback_t)(const struct device *dev,
480 					 void *context);
481 
482 /**
483  * @brief Get the device handles for devicetree dependencies of this device.
484  *
485  * This function returns a pointer to an array of device handles. The length of
486  * the array is stored in the @p count parameter.
487  *
488  * The array contains a handle for each device that @p dev requires directly, as
489  * determined from the devicetree. This does not include transitive
490  * dependencies; you must recursively determine those.
491  *
492  * @param dev the device for which dependencies are desired.
493  * @param count pointer to where this function should store the length of the
494  * returned array. No value is stored if the call returns a null pointer. The
495  * value may be set to zero if the device has no devicetree dependencies.
496  *
497  * @return a pointer to a sequence of @p count device handles, or a null pointer
498  * if @p dev does not have any dependency data.
499  */
500 static inline const device_handle_t *
device_required_handles_get(const struct device * dev,size_t * count)501 device_required_handles_get(const struct device *dev, size_t *count)
502 {
503 	const device_handle_t *rv = dev->deps;
504 
505 	if (rv != NULL) {
506 		size_t i = 0;
507 
508 		while ((rv[i] != Z_DEVICE_DEPS_ENDS) &&
509 		       (rv[i] != Z_DEVICE_DEPS_SEP)) {
510 			++i;
511 		}
512 		*count = i;
513 	}
514 
515 	return rv;
516 }
517 
518 /**
519  * @brief Get the device handles for injected dependencies of this device.
520  *
521  * This function returns a pointer to an array of device handles. The length of
522  * the array is stored in the @p count parameter.
523  *
524  * The array contains a handle for each device that @p dev manually injected as
525  * a dependency, via providing extra arguments to Z_DEVICE_DEFINE. This does not
526  * include transitive dependencies; you must recursively determine those.
527  *
528  * @param dev the device for which injected dependencies are desired.
529  * @param count pointer to where this function should store the length of the
530  * returned array. No value is stored if the call returns a null pointer. The
531  * value may be set to zero if the device has no devicetree dependencies.
532  *
533  * @return a pointer to a sequence of @p *count device handles, or a null
534  * pointer if @p dev does not have any dependency data.
535  */
536 static inline const device_handle_t *
device_injected_handles_get(const struct device * dev,size_t * count)537 device_injected_handles_get(const struct device *dev, size_t *count)
538 {
539 	const device_handle_t *rv = dev->deps;
540 	size_t region = 0;
541 	size_t i = 0;
542 
543 	if (rv != NULL) {
544 		/* Fast forward to injected devices */
545 		while (region != 1) {
546 			if (*rv == Z_DEVICE_DEPS_SEP) {
547 				region++;
548 			}
549 			rv++;
550 		}
551 		while ((rv[i] != Z_DEVICE_DEPS_ENDS) &&
552 		       (rv[i] != Z_DEVICE_DEPS_SEP)) {
553 			++i;
554 		}
555 		*count = i;
556 	}
557 
558 	return rv;
559 }
560 
561 /**
562  * @brief Get the set of handles that this device supports.
563  *
564  * This function returns a pointer to an array of device handles. The length of
565  * the array is stored in the @p count parameter.
566  *
567  * The array contains a handle for each device that @p dev "supports" -- that
568  * is, devices that require @p dev directly -- as determined from the
569  * devicetree. This does not include transitive dependencies; you must
570  * recursively determine those.
571  *
572  * @param dev the device for which supports are desired.
573  * @param count pointer to where this function should store the length of the
574  * returned array. No value is stored if the call returns a null pointer. The
575  * value may be set to zero if nothing in the devicetree depends on @p dev.
576  *
577  * @return a pointer to a sequence of @p *count device handles, or a null
578  * pointer if @p dev does not have any dependency data.
579  */
580 static inline const device_handle_t *
device_supported_handles_get(const struct device * dev,size_t * count)581 device_supported_handles_get(const struct device *dev, size_t *count)
582 {
583 	const device_handle_t *rv = dev->deps;
584 	size_t region = 0;
585 	size_t i = 0;
586 
587 	if (rv != NULL) {
588 		/* Fast forward to supporting devices */
589 		while (region != 2) {
590 			if (*rv == Z_DEVICE_DEPS_SEP) {
591 				region++;
592 			}
593 			rv++;
594 		}
595 		/* Count supporting devices.
596 		 * Trailing NULL's can be injected by gen_device_deps.py due to
597 		 * CONFIG_PM_DEVICE_POWER_DOMAIN_DYNAMIC_NUM
598 		 */
599 		while ((rv[i] != Z_DEVICE_DEPS_ENDS) &&
600 		       (rv[i] != DEVICE_HANDLE_NULL)) {
601 			++i;
602 		}
603 		*count = i;
604 	}
605 
606 	return rv;
607 }
608 
609 /**
610  * @brief Visit every device that @p dev directly requires.
611  *
612  * Zephyr maintains information about which devices are directly required by
613  * another device; for example an I2C-based sensor driver will require an I2C
614  * controller for communication. Required devices can derive from
615  * statically-defined devicetree relationships or dependencies registered at
616  * runtime.
617  *
618  * This API supports operating on the set of required devices. Example uses
619  * include making sure required devices are ready before the requiring device is
620  * used, and releasing them when the requiring device is no longer needed.
621  *
622  * There is no guarantee on the order in which required devices are visited.
623  *
624  * If the @p visitor_cb function returns a negative value iteration is halted,
625  * and the returned value from the visitor is returned from this function.
626  *
627  * @note This API is not available to unprivileged threads.
628  *
629  * @param dev a device of interest. The devices that this device depends on will
630  * be used as the set of devices to visit. This parameter must not be null.
631  * @param visitor_cb the function that should be invoked on each device in the
632  * dependency set. This parameter must not be null.
633  * @param context state that is passed through to the visitor function. This
634  * parameter may be null if @p visitor_cb tolerates a null @p context.
635  *
636  * @return The number of devices that were visited if all visits succeed, or
637  * the negative value returned from the first visit that did not succeed.
638  */
639 int device_required_foreach(const struct device *dev,
640 			    device_visitor_callback_t visitor_cb,
641 			    void *context);
642 
643 /**
644  * @brief Visit every device that @p dev directly supports.
645  *
646  * Zephyr maintains information about which devices are directly supported by
647  * another device; for example an I2C controller will support an I2C-based
648  * sensor driver. Supported devices can derive from statically-defined
649  * devicetree relationships.
650  *
651  * This API supports operating on the set of supported devices. Example uses
652  * include iterating over the devices connected to a regulator when it is
653  * powered on.
654  *
655  * There is no guarantee on the order in which required devices are visited.
656  *
657  * If the @p visitor_cb function returns a negative value iteration is halted,
658  * and the returned value from the visitor is returned from this function.
659  *
660  * @note This API is not available to unprivileged threads.
661  *
662  * @param dev a device of interest. The devices that this device supports
663  * will be used as the set of devices to visit. This parameter must not be null.
664  * @param visitor_cb the function that should be invoked on each device in the
665  * support set. This parameter must not be null.
666  * @param context state that is passed through to the visitor function. This
667  * parameter may be null if @p visitor_cb tolerates a null @p context.
668  *
669  * @return The number of devices that were visited if all visits succeed, or the
670  * negative value returned from the first visit that did not succeed.
671  */
672 int device_supported_foreach(const struct device *dev,
673 			     device_visitor_callback_t visitor_cb,
674 			     void *context);
675 
676 #endif /* CONFIG_DEVICE_DEPS */
677 
678 /**
679  * @brief Get a @ref device reference from its @ref device.name field.
680  *
681  * This function iterates through the devices on the system. If a device with
682  * the given @p name field is found, and that device initialized successfully at
683  * boot time, this function returns a pointer to the device.
684  *
685  * If no device has the given @p name, this function returns `NULL`.
686  *
687  * This function also returns NULL when a device is found, but it failed to
688  * initialize successfully at boot time. (To troubleshoot this case, set a
689  * breakpoint on your device driver's initialization function.)
690  *
691  * @param name device name to search for. A null pointer, or a pointer to an
692  * empty string, will cause NULL to be returned.
693  *
694  * @return pointer to device structure with the given name; `NULL` if the device
695  * is not found or if the device with that name's initialization function
696  * failed.
697  */
698 __syscall const struct device *device_get_binding(const char *name);
699 
700 /**
701  * @brief Get access to the static array of static devices.
702  *
703  * @param devices where to store the pointer to the array of statically
704  * allocated devices. The array must not be mutated through this pointer.
705  *
706  * @return the number of statically allocated devices.
707  */
708 size_t z_device_get_all_static(const struct device **devices);
709 
710 /**
711  * @brief Verify that a device is ready for use.
712  *
713  * This is the implementation underlying device_is_ready(), without the overhead
714  * of a syscall wrapper.
715  *
716  * @param dev pointer to the device in question.
717  *
718  * @retval true If the device is ready for use.
719  * @retval false If the device is not ready for use or if a NULL device pointer
720  * is passed as argument.
721  *
722  * @see device_is_ready()
723  */
724 bool z_device_is_ready(const struct device *dev);
725 
726 /**
727  * @brief Verify that a device is ready for use.
728  *
729  * Indicates whether the provided device pointer is for a device known to be
730  * in a state where it can be used with its standard API.
731  *
732  * This can be used with device pointers captured from DEVICE_DT_GET(), which
733  * does not include the readiness checks of device_get_binding(). At minimum
734  * this means that the device has been successfully initialized.
735  *
736  * @param dev pointer to the device in question.
737  *
738  * @retval true If the device is ready for use.
739  * @retval false If the device is not ready for use or if a NULL device pointer
740  * is passed as argument.
741  */
742 __syscall bool device_is_ready(const struct device *dev);
743 
z_impl_device_is_ready(const struct device * dev)744 static inline bool z_impl_device_is_ready(const struct device *dev)
745 {
746 	return z_device_is_ready(dev);
747 }
748 
749 /**
750  * @}
751  */
752 
753 /** @cond INTERNAL_HIDDEN */
754 
755 /**
756  * @brief Synthesize a unique name for the device state associated with
757  * @p dev_id.
758  */
759 #define Z_DEVICE_STATE_NAME(dev_id) _CONCAT(__devstate_, dev_id)
760 
761 /**
762  * @brief Utility macro to define and initialize the device state.
763  *
764  * @param dev_id Device identifier.
765  */
766 #define Z_DEVICE_STATE_DEFINE(dev_id)                                          \
767 	static Z_DECL_ALIGN(struct device_state) Z_DEVICE_STATE_NAME(dev_id)   \
768 		__attribute__((__section__(".z_devstate")))
769 
770 #if defined(CONFIG_DEVICE_DEPS) || defined(__DOXYGEN__)
771 
772 /**
773  * @brief Synthesize the name of the object that holds device ordinal and
774  * dependency data.
775  *
776  * @param dev_id Device identifier.
777  */
778 #define Z_DEVICE_DEPS_NAME(dev_id) _CONCAT(__devicedeps_, dev_id)
779 
780 /**
781  * @brief Expand extra dependencies with a comma in between.
782  *
783  * @param ... Extra dependencies.
784  */
785 #define Z_DEVICE_EXTRA_DEPS(...)                                            \
786 	FOR_EACH_NONEMPTY_TERM(IDENTITY, (,), __VA_ARGS__)
787 
788 /** @brief Linker section were device dependencies are placed. */
789 #define Z_DEVICE_DEPS_SECTION                                               \
790 	__attribute__((__section__(".__device_deps_pass1")))
791 
792 #ifdef __cplusplus
793 #define Z_DEVICE_DEPS_EXTERN extern
794 #else
795 #define Z_DEVICE_DEPS_EXTERN
796 #endif
797 
798 /**
799  * @brief Define device dependencies.
800  *
801  * Initial build provides a record that associates the device object with its
802  * devicetree ordinal, and provides the dependency ordinals. These are provided
803  * as weak definitions (to prevent the reference from being captured when the
804  * original object file is compiled), and in a distinct pass1 section (which
805  * will be replaced by postprocessing).
806  *
807  * Before processing in gen_device_deps.py, the array format is:
808  * {
809  *     DEVICE_ORDINAL (or DEVICE_HANDLE_NULL if not a devicetree node),
810  *     List of devicetree dependency ordinals (if any),
811  *     Z_DEVICE_DEPS_SEP,
812  *     List of injected dependency ordinals (if any),
813  *     Z_DEVICE_DEPS_SEP,
814  *     List of devicetree supporting ordinals (if any),
815  * }
816  *
817  * After processing in gen_device_deps.py, the format is updated to:
818  * {
819  *     List of existing devicetree dependency handles (if any),
820  *     Z_DEVICE_DEPS_SEP,
821  *     List of injected devicetree dependency handles (if any),
822  *     Z_DEVICE_DEPS_SEP,
823  *     List of existing devicetree support handles (if any),
824  *     DEVICE_HANDLE_NULL
825  * }
826  *
827  * It is also (experimentally) necessary to provide explicit alignment on each
828  * object. Otherwise x86-64 builds will introduce padding between objects in the
829  * same input section in individual object files, which will be retained in
830  * subsequent links both wasting space and resulting in aggregate size changes
831  * relative to pass2 when all objects will be in the same input section.
832  */
833 #define Z_DEVICE_DEPS_DEFINE(node_id, dev_id, ...)                             \
834 	extern Z_DEVICE_DEPS_CONST device_handle_t Z_DEVICE_DEPS_NAME(         \
835 		dev_id)[];                                                     \
836 	Z_DEVICE_DEPS_CONST Z_DECL_ALIGN(device_handle_t)                      \
837 	Z_DEVICE_DEPS_SECTION Z_DEVICE_DEPS_EXTERN __weak                      \
838 		Z_DEVICE_DEPS_NAME(dev_id)[] = {                               \
839 		COND_CODE_1(                                                   \
840 			DT_NODE_EXISTS(node_id),                               \
841 			(DT_DEP_ORD(node_id), DT_REQUIRES_DEP_ORDS(node_id)),  \
842 			(DEVICE_HANDLE_NULL,)) /**/                            \
843 		Z_DEVICE_DEPS_SEP,                                             \
844 		Z_DEVICE_EXTRA_DEPS(__VA_ARGS__) /**/                          \
845 		Z_DEVICE_DEPS_SEP,                                             \
846 		COND_CODE_1(DT_NODE_EXISTS(node_id),                           \
847 			    (DT_SUPPORTS_DEP_ORDS(node_id)), ()) /**/          \
848 	}
849 
850 #endif /* CONFIG_DEVICE_DEPS */
851 
852 /**
853  * @brief Init sub-priority of the device
854  *
855  * The sub-priority is defined by the devicetree ordinal, which ensures that
856  * multiple drivers running at the same priority level run in an order that
857  * respects the devicetree dependencies.
858  */
859 #define Z_DEVICE_INIT_SUB_PRIO(node_id)                                        \
860 	COND_CODE_1(DT_NODE_EXISTS(node_id),                                   \
861 		    (DT_DEP_ORD_STR_SORTABLE(node_id)), (0))
862 
863 /**
864  * @brief Maximum device name length.
865  *
866  * The maximum length is set so that device_get_binding() can be used from
867  * userspace.
868  */
869 #define Z_DEVICE_MAX_NAME_LEN 48U
870 
871 /**
872  * @brief Compile time check for device name length
873  *
874  * @param name Device name.
875  */
876 #define Z_DEVICE_NAME_CHECK(name)                                              \
877 	BUILD_ASSERT(sizeof(Z_STRINGIFY(name)) <= Z_DEVICE_MAX_NAME_LEN,       \
878 			    Z_STRINGIFY(DEVICE_NAME_GET(name)) " too long")
879 
880 /**
881  * @brief Initializer for @ref device.
882  *
883  * @param name_ Name of the device.
884  * @param pm_ Reference to @ref pm_device (optional).
885  * @param data_ Reference to device data.
886  * @param config_ Reference to device config.
887  * @param api_ Reference to device API ops.
888  * @param state_ Reference to device state.
889  * @param deps_ Reference to device dependencies.
890  */
891 #define Z_DEVICE_INIT(name_, pm_, data_, config_, api_, state_, deps_)         \
892 	{                                                                      \
893 		.name = name_,                                                 \
894 		.config = (config_),                                           \
895 		.api = (api_),                                                 \
896 		.state = (state_),                                             \
897 		.data = (data_),                                               \
898 		IF_ENABLED(CONFIG_DEVICE_DEPS, (.deps = (deps_),)) /**/        \
899 		IF_ENABLED(CONFIG_PM_DEVICE, (.pm = (pm_),)) /**/              \
900 	}
901 
902 /**
903  * @brief Device section name (used for sorting purposes).
904  *
905  * @param level Initialization level
906  * @param prio Initialization priority
907  */
908 #define Z_DEVICE_SECTION_NAME(level, prio)                                     \
909 	_CONCAT(INIT_LEVEL_ORD(level), _##prio)
910 
911 /**
912  * @brief Define a @ref device
913  *
914  * @param node_id Devicetree node id for the device (DT_INVALID_NODE if a
915  * software device).
916  * @param dev_id Device identifier (used to name the defined @ref device).
917  * @param name Name of the device.
918  * @param pm Reference to @ref pm_device associated with the device.
919  * (optional).
920  * @param data Reference to device data.
921  * @param config Reference to device config.
922  * @param level Initialization level.
923  * @param prio Initialization priority.
924  * @param api Reference to device API.
925  * @param ... Optional dependencies, manually specified.
926  */
927 #define Z_DEVICE_BASE_DEFINE(node_id, dev_id, name, pm, data, config, level,   \
928 			     prio, api, state, deps)                           \
929 	COND_CODE_1(DT_NODE_EXISTS(node_id), (), (static))                     \
930 	const STRUCT_SECTION_ITERABLE_NAMED(device,                            \
931 		Z_DEVICE_SECTION_NAME(level, prio),                            \
932 		DEVICE_NAME_GET(dev_id)) =                                     \
933 		Z_DEVICE_INIT(name, pm, data, config, api, state, deps)
934 
935 /* deprecated device initialization levels */
936 #define Z_DEVICE_LEVEL_DEPRECATED_EARLY                                        \
937 	__WARN("EARLY device driver level is deprecated")
938 #define Z_DEVICE_LEVEL_DEPRECATED_PRE_KERNEL_1
939 #define Z_DEVICE_LEVEL_DEPRECATED_PRE_KERNEL_2
940 #define Z_DEVICE_LEVEL_DEPRECATED_POST_KERNEL
941 #define Z_DEVICE_LEVEL_DEPRECATED_APPLICATION                                  \
942 	__WARN("APPLICATION device driver level is deprecated")
943 #define Z_DEVICE_LEVEL_DEPRECATED_SMP                                          \
944 	__WARN("SMP device driver level is deprecated")
945 
946 /**
947  * @brief Issue a warning if the given init level is deprecated.
948  *
949  * @param level Init level
950  */
951 #define Z_DEVICE_LEVEL_CHECK_DEPRECATED_LEVEL(level)                           \
952 	Z_DEVICE_LEVEL_DEPRECATED_##level
953 
954 /**
955  * @brief Define the init entry for a device.
956  *
957  * @param node_id Devicetree node id for the device (DT_INVALID_NODE if a
958  * software device).
959  * @param dev_id Device identifier.
960  * @param init_fn_ Device init function.
961  * @param level Initialization level.
962  * @param prio Initialization priority.
963  */
964 #define Z_DEVICE_INIT_ENTRY_DEFINE(node_id, dev_id, init_fn_, level, prio)     \
965 	Z_DEVICE_LEVEL_CHECK_DEPRECATED_LEVEL(level)                           \
966                                                                                \
967 	static const Z_DECL_ALIGN(struct init_entry) __used __noasan           \
968 		Z_INIT_ENTRY_SECTION(level, prio,                              \
969 				     Z_DEVICE_INIT_SUB_PRIO(node_id))          \
970 		Z_INIT_ENTRY_NAME(DEVICE_NAME_GET(dev_id)) = {                 \
971 			.init_fn = {.dev = (init_fn_)},                        \
972 			.dev = &DEVICE_NAME_GET(dev_id),                       \
973 	}
974 
975 /**
976  * @brief Define a @ref device and all other required objects.
977  *
978  * This is the common macro used to define @ref device objects. It can be used
979  * to define both Devicetree and software devices.
980  *
981  * @param node_id Devicetree node id for the device (DT_INVALID_NODE if a
982  * software device).
983  * @param dev_id Device identifier (used to name the defined @ref device).
984  * @param name Name of the device.
985  * @param init_fn Device init function.
986  * @param pm Reference to @ref pm_device associated with the device.
987  * (optional).
988  * @param data Reference to device data.
989  * @param config Reference to device config.
990  * @param level Initialization level.
991  * @param prio Initialization priority.
992  * @param api Reference to device API.
993  * @param state Reference to device state.
994  * @param ... Optional dependencies, manually specified.
995  */
996 #define Z_DEVICE_DEFINE(node_id, dev_id, name, init_fn, pm, data, config,      \
997 			level, prio, api, state, ...)                          \
998 	Z_DEVICE_NAME_CHECK(name);                                             \
999                                                                                \
1000 	IF_ENABLED(CONFIG_DEVICE_DEPS,                                         \
1001 		   (Z_DEVICE_DEPS_DEFINE(node_id, dev_id, __VA_ARGS__);))      \
1002                                                                                \
1003 	Z_DEVICE_BASE_DEFINE(node_id, dev_id, name, pm, data, config, level,   \
1004 			     prio, api, state, Z_DEVICE_DEPS_NAME(dev_id));    \
1005                                                                                \
1006 	Z_DEVICE_INIT_ENTRY_DEFINE(node_id, dev_id, init_fn, level, prio)
1007 
1008 #if defined(CONFIG_HAS_DTS) || defined(__DOXYGEN__)
1009 /**
1010  * @brief Declare a device for each status "okay" devicetree node.
1011  *
1012  * @note Disabled nodes should not result in devices, so not predeclaring these
1013  * keeps drivers honest.
1014  *
1015  * This is only "maybe" a device because some nodes have status "okay", but
1016  * don't have a corresponding @ref device allocated. There's no way to figure
1017  * that out until after we've built the zephyr image, though.
1018  */
1019 #define Z_MAYBE_DEVICE_DECLARE_INTERNAL(node_id)                               \
1020 	extern const struct device DEVICE_DT_NAME_GET(node_id);
1021 
1022 DT_FOREACH_STATUS_OKAY_NODE(Z_MAYBE_DEVICE_DECLARE_INTERNAL)
1023 #endif /* CONFIG_HAS_DTS */
1024 
1025 /** @endcond */
1026 
1027 #ifdef __cplusplus
1028 }
1029 #endif
1030 
1031 #include <syscalls/device.h>
1032 
1033 #endif /* ZEPHYR_INCLUDE_DEVICE_H_ */
1034