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