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