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 /**
11  * @brief Device Driver APIs
12  * @defgroup io_interfaces Device Driver APIs
13  * @{
14  * @}
15  */
16 /**
17  * @brief Miscellaneous Drivers APIs
18  * @defgroup misc_interfaces Miscellaneous Drivers APIs
19  * @ingroup io_interfaces
20  * @{
21  * @}
22  */
23 /**
24  * @brief Device Model APIs
25  * @defgroup device_model Device Model APIs
26  * @{
27  */
28 
29 #include <init.h>
30 #include <linker/sections.h>
31 #include <pm/device.h>
32 #include <sys/device_mmio.h>
33 #include <sys/util.h>
34 
35 #ifdef __cplusplus
36 extern "C" {
37 #endif
38 
39 /** @brief Type used to represent devices and functions.
40  *
41  * The extreme values and zero have special significance. Negative
42  * values identify functionality that does not correspond to a Zephyr
43  * device, such as the system clock or a SYS_INIT() function.
44  */
45 typedef int16_t device_handle_t;
46 
47 /** @brief Flag value used in lists of device handles to separate
48  * distinct groups.
49  *
50  * This is the minimum value for the device_handle_t type.
51  */
52 #define DEVICE_HANDLE_SEP INT16_MIN
53 
54 /** @brief Flag value used in lists of device handles to indicate the
55  * end of the list.
56  *
57  * This is the maximum value for the device_handle_t type.
58  */
59 #define DEVICE_HANDLE_ENDS INT16_MAX
60 
61 /** @brief Flag value used to identify an unknown device. */
62 #define DEVICE_HANDLE_NULL 0
63 
64 #define Z_DEVICE_MAX_NAME_LEN	48
65 
66 /**
67  * @def DEVICE_NAME_GET
68  *
69  * @brief Expands to the full name of a global device object
70  *
71  * @details Return the full name of a device object symbol created by
72  * DEVICE_DEFINE(), using the dev_name provided to DEVICE_DEFINE().
73  *
74  * It is meant to be used for declaring extern symbols pointing on device
75  * objects before using the DEVICE_GET macro to get the device object.
76  *
77  * @param name The same as dev_name provided to DEVICE_DEFINE()
78  *
79  * @return The expanded name of the device object created by DEVICE_DEFINE()
80  */
81 #define DEVICE_NAME_GET(name) _CONCAT(__device_, name)
82 
83 /**
84  * @def SYS_DEVICE_DEFINE
85  *
86  * @brief Run an initialization function at boot at specified priority,
87  * and define device PM control function.
88  *
89  * @details Invokes DEVICE_DEFINE() with no power management support
90  * (@p pm_control_fn), no API (@p api_ptr), and a device name derived from
91  * the @p init_fn name (@p dev_name).
92  */
93 #define SYS_DEVICE_DEFINE(drv_name, init_fn, pm_control_fn, level, prio) \
94 	DEVICE_DEFINE(Z_SYS_NAME(init_fn), drv_name, init_fn,		\
95 		      pm_control_fn,					\
96 		      NULL, NULL, level, prio, NULL)
97 
98 /**
99  * @def DEVICE_DEFINE
100  *
101  * @brief Create device object and set it up for boot time initialization,
102  * with the option to pm_control. In case of Device Idle Power
103  * Management is enabled, make sure the device is in suspended state after
104  * initialization.
105  *
106  * @details This macro defines a device object that is automatically
107  * configured by the kernel during system initialization. Note that
108  * devices set up with this macro will not be accessible from user mode
109  * since the API is not specified;
110  *
111  * @param dev_name Device name. This must be less than Z_DEVICE_MAX_NAME_LEN
112  * characters (including terminating NUL) in order to be looked up from user
113  * mode with device_get_binding().
114  *
115  * @param drv_name The name this instance of the driver exposes to
116  * the system.
117  *
118  * @param init_fn Address to the init function of the driver.
119  *
120  * @param pm_control_fn Pointer to pm_control function.
121  * Can be NULL if not implemented.
122  *
123  * @param data_ptr Pointer to the device's private data.
124  *
125  * @param cfg_ptr The address to the structure containing the
126  * configuration information for this instance of the driver.
127  *
128  * @param level The initialization level. See SYS_INIT() for
129  * details.
130  *
131  * @param prio Priority within the selected initialization level. See
132  * SYS_INIT() for details.
133  *
134  * @param api_ptr Provides an initial pointer to the API function struct
135  * used by the driver. Can be NULL.
136  */
137 #define DEVICE_DEFINE(dev_name, drv_name, init_fn, pm_control_fn,	\
138 		      data_ptr, cfg_ptr, level, prio, api_ptr)		\
139 	Z_DEVICE_DEFINE(DT_INVALID_NODE, dev_name, drv_name, init_fn,	\
140 			pm_control_fn,					\
141 			data_ptr, cfg_ptr, level, prio, api_ptr)
142 
143 /**
144  * @def DEVICE_DT_NAME
145  *
146  * @brief Return a string name for a devicetree node.
147  *
148  * @details This macro returns a string literal usable as a device name
149  * from a devicetree node. If the node has a "label" property, its value is
150  * returned. Otherwise, the node's full "node-name@@unit-address" name is
151  * returned.
152  *
153  * @param node_id The devicetree node identifier.
154  */
155 #define DEVICE_DT_NAME(node_id) \
156 	DT_PROP_OR(node_id, label, DT_NODE_FULL_NAME(node_id))
157 
158 /**
159  * @def DEVICE_DT_DEFINE
160  *
161  * @brief Like DEVICE_DEFINE but taking metadata from a devicetree node.
162  *
163  * @details This macro defines a device object that is automatically
164  * configured by the kernel during system initialization. The device
165  * object name is derived from the node identifier (encoding the
166  * devicetree path to the node), and the driver name is from the @p
167  * label property of the devicetree node.
168  *
169  * The device is declared with extern visibility, so device objects
170  * defined through this API can be obtained directly through
171  * DEVICE_DT_GET() using @p node_id. Before using the pointer the
172  * referenced object should be checked using device_is_ready().
173  *
174  * @param node_id The devicetree node identifier.
175  *
176  * @param init_fn Address to the init function of the driver.
177  *
178  * @param pm_control_fn Pointer to pm_control function.
179  * Can be NULL if not implemented.
180  *
181  * @param data_ptr Pointer to the device's private data.
182  *
183  * @param cfg_ptr The address to the structure containing the
184  * configuration information for this instance of the driver.
185  *
186  * @param level The initialization level. See SYS_INIT() for
187  * details.
188  *
189  * @param prio Priority within the selected initialization level. See
190  * SYS_INIT() for details.
191  *
192  * @param api_ptr Provides an initial pointer to the API function struct
193  * used by the driver. Can be NULL.
194  */
195 #define DEVICE_DT_DEFINE(node_id, init_fn, pm_control_fn,		\
196 			 data_ptr, cfg_ptr, level, prio,		\
197 			 api_ptr, ...)					\
198 	Z_DEVICE_DEFINE(node_id, Z_DEVICE_DT_DEV_NAME(node_id),		\
199 			DEVICE_DT_NAME(node_id), init_fn,		\
200 			pm_control_fn,					\
201 			data_ptr, cfg_ptr, level, prio,			\
202 			api_ptr, __VA_ARGS__)
203 
204 /**
205  * @def DEVICE_DT_INST_DEFINE
206  *
207  * @brief Like DEVICE_DT_DEFINE for an instance of a DT_DRV_COMPAT compatible
208  *
209  * @param inst instance number. This is replaced by
210  * <tt>DT_DRV_COMPAT(inst)</tt> in the call to DEVICE_DT_DEFINE.
211  *
212  * @param ... other parameters as expected by DEVICE_DT_DEFINE.
213  */
214 #define DEVICE_DT_INST_DEFINE(inst, ...) \
215 	DEVICE_DT_DEFINE(DT_DRV_INST(inst), __VA_ARGS__)
216 
217 /**
218  * @def DEVICE_DT_NAME_GET
219  *
220  * @brief The name of the struct device object for @p node_id
221  *
222  * @details Return the full name of a device object symbol created by
223  * DEVICE_DT_DEFINE(), using the dev_name derived from @p node_id
224  *
225  * It is meant to be used for declaring extern symbols pointing on device
226  * objects before using the DEVICE_DT_GET macro to get the device object.
227  *
228  * @param node_id The same as node_id provided to DEVICE_DT_DEFINE()
229  *
230  * @return The expanded name of the device object created by
231  * DEVICE_DT_DEFINE()
232  */
233 #define DEVICE_DT_NAME_GET(node_id) DEVICE_NAME_GET(Z_DEVICE_DT_DEV_NAME(node_id))
234 
235 /**
236  * @def DEVICE_DT_GET
237  *
238  * @brief Obtain a pointer to a device object by @p node_id
239  *
240  * @details Return the address of a device object created by
241  * DEVICE_DT_INIT(), using the dev_name derived from @p node_id
242  *
243  * @param node_id The same as node_id provided to DEVICE_DT_DEFINE()
244  *
245  * @return A pointer to the device object created by DEVICE_DT_DEFINE()
246  */
247 #define DEVICE_DT_GET(node_id) (&DEVICE_DT_NAME_GET(node_id))
248 
249 /** @def DEVICE_DT_INST_GET
250  *
251  * @brief Obtain a pointer to a device object for an instance of a
252  *        DT_DRV_COMPAT compatible
253  *
254  * @param inst instance number
255  */
256 #define DEVICE_DT_INST_GET(inst) DEVICE_DT_GET(DT_DRV_INST(inst))
257 
258 /**
259  * @def DEVICE_DT_GET_ANY
260  *
261  * @brief Obtain a pointer to a device object by devicetree compatible
262  *
263  * If any enabled devicetree node has the given compatible and a
264  * device object was created from it, this returns that device.
265  *
266  * If there no such devices, this returns NULL.
267  *
268  * If there are multiple, this returns an arbitrary one.
269  *
270  * If this returns non-NULL, the device must be checked for readiness
271  * before use, e.g. with device_is_ready().
272  *
273  * @param compat lowercase-and-underscores devicetree compatible
274  * @return a pointer to a device, or NULL
275  */
276 #define DEVICE_DT_GET_ANY(compat)					    \
277 	COND_CODE_1(DT_HAS_COMPAT_STATUS_OKAY(compat),			    \
278 		    (DEVICE_DT_GET(DT_COMPAT_GET_ANY_STATUS_OKAY(compat))), \
279 		    (NULL))
280 
281 /**
282  * @def DEVICE_DT_GET_ONE
283  *
284  * @brief Obtain a pointer to a device object by devicetree compatible
285  *
286  * If any enabled devicetree node has the given compatible and a
287  * device object was created from it, this returns that device.
288  *
289  * If there no such devices, this throws a compilation error.
290  *
291  * If there are multiple, this returns an arbitrary one.
292  *
293  * If this returns non-NULL, the device must be checked for readiness
294  * before use, e.g. with device_is_ready().
295  *
296  * @param compat lowercase-and-underscores devicetree compatible
297  * @return a pointer to a device
298  */
299 #define DEVICE_DT_GET_ONE(compat)					    \
300 	COND_CODE_1(DT_HAS_COMPAT_STATUS_OKAY(compat),			    \
301 		    (DEVICE_DT_GET(DT_COMPAT_GET_ANY_STATUS_OKAY(compat))), \
302 		    (ZERO_OR_COMPILE_ERROR(0)))
303 
304 /**
305  * @def DEVICE_GET
306  *
307  * @brief Obtain a pointer to a device object by name
308  *
309  * @details Return the address of a device object created by
310  * DEVICE_DEFINE(), using the dev_name provided to DEVICE_DEFINE().
311  *
312  * @param name The same as dev_name provided to DEVICE_DEFINE()
313  *
314  * @return A pointer to the device object created by DEVICE_DEFINE()
315  */
316 #define DEVICE_GET(name) (&DEVICE_NAME_GET(name))
317 
318 /** @def DEVICE_DECLARE
319  *
320  * @brief Declare a static device object
321  *
322  * This macro can be used at the top-level to declare a device, such
323  * that DEVICE_GET() may be used before the full declaration in
324  * DEVICE_DEFINE().
325  *
326  * This is often useful when configuring interrupts statically in a
327  * device's init or per-instance config function, as the init function
328  * itself is required by DEVICE_DEFINE() and use of DEVICE_GET()
329  * inside it creates a circular dependency.
330  *
331  * @param name Device name
332  */
333 #define DEVICE_DECLARE(name) static const struct device DEVICE_NAME_GET(name)
334 
335 /**
336  * @brief Runtime device dynamic structure (in RAM) per driver instance
337  *
338  * Fields in this are expected to be default-initialized to zero. The
339  * kernel driver infrastructure and driver access functions are
340  * responsible for ensuring that any non-zero initialization is done
341  * before they are accessed.
342  */
343 struct device_state {
344 	/** Non-negative result of initializing the device.
345 	 *
346 	 * The absolute value returned when the device initialization
347 	 * function was invoked, or `UINT8_MAX` if the value exceeds
348 	 * an 8-bit integer. If initialized is also set, a zero value
349 	 * indicates initialization succeeded.
350 	 */
351 	unsigned int init_res : 8;
352 
353 	/** Indicates the device initialization function has been
354 	 * invoked.
355 	 */
356 	bool initialized : 1;
357 
358 #ifdef CONFIG_PM_DEVICE
359 	/* Power management data */
360 	struct pm_device pm;
361 #endif /* CONFIG_PM_DEVICE */
362 };
363 
364 /**
365  * @brief Runtime device structure (in ROM) per driver instance
366  */
367 struct device {
368 	/** Name of the device instance */
369 	const char *name;
370 	/** Address of device instance config information */
371 	const void *config;
372 	/** Address of the API structure exposed by the device instance */
373 	const void *api;
374 	/** Address of the common device state */
375 	struct device_state * const state;
376 	/** Address of the device instance private data */
377 	void * const data;
378 	/** optional pointer to handles associated with the device.
379 	 *
380 	 * This encodes a sequence of sets of device handles that have
381 	 * some relationship to this node. The individual sets are
382 	 * extracted with dedicated API, such as
383 	 * device_required_handles_get().
384 	 */
385 	const device_handle_t *const handles;
386 #ifdef CONFIG_PM_DEVICE
387 	/** Power Management function */
388 	pm_device_control_callback_t pm_control;
389 	/** Pointer to device instance power management data */
390 	struct pm_device * const pm;
391 #endif
392 };
393 
394 /**
395  * @brief Get the handle for a given device
396  *
397  * @param dev the device for which a handle is desired.
398  *
399  * @return the handle for the device, or DEVICE_HANDLE_NULL if the
400  * device does not have an associated handle.
401  */
402 static inline device_handle_t
device_handle_get(const struct device * dev)403 device_handle_get(const struct device *dev)
404 {
405 	device_handle_t ret = DEVICE_HANDLE_NULL;
406 	extern const struct device __device_start[];
407 
408 	/* TODO: If/when devices can be constructed that are not part of the
409 	 * fixed sequence we'll need another solution.
410 	 */
411 	if (dev != NULL) {
412 		ret = 1 + (device_handle_t)(dev - __device_start);
413 	}
414 
415 	return ret;
416 }
417 
418 /**
419  * @brief Get the device corresponding to a handle.
420  *
421  * @param dev_handle the device handle
422  *
423  * @return the device that has that handle, or a null pointer if @p
424  * dev_handle does not identify a device.
425  */
426 static inline const struct device *
device_from_handle(device_handle_t dev_handle)427 device_from_handle(device_handle_t dev_handle)
428 {
429 	extern const struct device __device_start[];
430 	extern const struct device __device_end[];
431 	const struct device *dev = NULL;
432 	size_t numdev = __device_end - __device_start;
433 
434 	if ((dev_handle > 0) && ((size_t)dev_handle <= numdev)) {
435 		dev = &__device_start[dev_handle - 1];
436 	}
437 
438 	return dev;
439 }
440 
441 /**
442  * @brief Prototype for functions used when iterating over a set of devices.
443  *
444  * Such a function may be used in API that identifies a set of devices and
445  * provides a visitor API supporting caller-specific interaction with each
446  * device in the set.
447  *
448  * The visit is said to succeed if the visitor returns a non-negative value.
449  *
450  * @param dev a device in the set being iterated
451  *
452  * @param context state used to support the visitor function
453  *
454  * @return A non-negative number to allow walking to continue, and a negative
455  * error code to case the iteration to stop.
456  */
457 typedef int (*device_visitor_callback_t)(const struct device *dev, void *context);
458 
459 /**
460  * @brief Get the set of handles for devicetree dependencies of this device.
461  *
462  * These are the device dependencies inferred from devicetree.
463  *
464  * @param dev the device for which dependencies are desired.
465  *
466  * @param count pointer to a place to store the number of devices provided at
467  * the returned pointer. The value is not set if the call returns a null
468  * pointer. The value may be set to zero.
469  *
470  * @return a pointer to a sequence of @p *count device handles, or a null
471  * pointer if @p dh does not provide dependency information.
472  */
473 static inline const device_handle_t *
device_required_handles_get(const struct device * dev,size_t * count)474 device_required_handles_get(const struct device *dev,
475 			    size_t *count)
476 {
477 	const device_handle_t *rv = dev->handles;
478 
479 	if (rv != NULL) {
480 		size_t i = 0;
481 
482 		while ((rv[i] != DEVICE_HANDLE_ENDS)
483 		       && (rv[i] != DEVICE_HANDLE_SEP)) {
484 			++i;
485 		}
486 		*count = i;
487 	}
488 
489 	return rv;
490 }
491 
492 /**
493  * @brief Visit every device that @p dev directly requires.
494  *
495  * Zephyr maintains information about which devices are directly required by
496  * another device; for example an I2C-based sensor driver will require an I2C
497  * controller for communication. Required devices can derive from
498  * statically-defined devicetree relationships or dependencies registered
499  * at runtime.
500  *
501  * This API supports operating on the set of required devices. Example uses
502  * include making sure required devices are ready before the requiring device
503  * is used, and releasing them when the requiring device is no longer needed.
504  *
505  * There is no guarantee on the order in which required devices are visited.
506  *
507  * If the @p visitor function returns a negative value iteration is halted,
508  * and the returned value from the visitor is returned from this function.
509  *
510  * @note This API is not available to unprivileged threads.
511  *
512  * @param dev a device of interest. The devices that this device depends on
513  * will be used as the set of devices to visit. This parameter must not be
514  * null.
515  *
516  * @param visitor_cb the function that should be invoked on each device in the
517  * dependency set. This parameter must not be null.
518  *
519  * @param context state that is passed through to the visitor function. This
520  * parameter may be null if @p visitor tolerates a null @p context.
521  *
522  * @return The number of devices that were visited if all visits succeed, or
523  * the negative value returned from the first visit that did not succeed.
524  */
525 int device_required_foreach(const struct device *dev,
526 			  device_visitor_callback_t visitor_cb,
527 			  void *context);
528 
529 /**
530  * @brief Retrieve the device structure for a driver by name
531  *
532  * @details Device objects are created via the DEVICE_DEFINE() macro and
533  * placed in memory by the linker. If a driver needs to bind to another driver
534  * it can use this function to retrieve the device structure of the lower level
535  * driver by the name the driver exposes to the system.
536  *
537  * @param name device name to search for. A null pointer, or a pointer to an
538  * empty string, will cause NULL to be returned.
539  *
540  * @return pointer to device structure; NULL if not found or cannot be used.
541  */
542 __syscall const struct device *device_get_binding(const char *name);
543 
544 /** @brief Get access to the static array of static devices.
545  *
546  * @param devices where to store the pointer to the array of
547  * statically allocated devices. The array must not be mutated
548  * through this pointer.
549  *
550  * @return the number of statically allocated devices.
551  */
552 size_t z_device_get_all_static(const struct device * *devices);
553 
554 /** @brief Determine whether a device has been successfully initialized.
555  *
556  * @param dev pointer to the device in question.
557  *
558  * @return true if and only if the device is available for use.
559  */
560 bool z_device_ready(const struct device *dev);
561 
562 /** @brief Determine whether a device is ready for use
563  *
564  * This is the implementation underlying `device_usable_check()`, without the
565  * overhead of a syscall wrapper.
566  *
567  * @param dev pointer to the device in question.
568  *
569  * @return a non-positive integer as documented in device_usable_check().
570  */
z_device_usable_check(const struct device * dev)571 static inline int z_device_usable_check(const struct device *dev)
572 {
573 	return z_device_ready(dev) ? 0 : -ENODEV;
574 }
575 
576 /** @brief Determine whether a device is ready for use.
577  *
578  * This checks whether a device can be used, returning 0 if it can, and
579  * distinct error values that identify the reason if it cannot.
580  *
581  * @retval 0 if the device is usable.
582  * @retval -ENODEV if the device has not been initialized, the device pointer
583  * is NULL or the initialization failed.
584  * @retval other negative error codes to indicate additional conditions that
585  * make the device unusable.
586  */
587 __syscall int device_usable_check(const struct device *dev);
588 
z_impl_device_usable_check(const struct device * dev)589 static inline int z_impl_device_usable_check(const struct device *dev)
590 {
591 	return z_device_usable_check(dev);
592 }
593 
594 /** @brief Verify that a device is ready for use.
595  *
596  * Indicates whether the provided device pointer is for a device known to be
597  * in a state where it can be used with its standard API.
598  *
599  * This can be used with device pointers captured from DEVICE_DT_GET(), which
600  * does not include the readiness checks of device_get_binding(). At minimum
601  * this means that the device has been successfully initialized, but it may
602  * take on further conditions (e.g. is not powered down).
603  *
604  * @param dev pointer to the device in question.
605  *
606  * @retval true if the device is ready for use.
607  * @retval false if the device is not ready for use or if a NULL device pointer
608  * is passed as argument.
609  */
device_is_ready(const struct device * dev)610 static inline bool device_is_ready(const struct device *dev)
611 {
612 	return device_usable_check(dev) == 0;
613 }
614 
615 /**
616  * @}
617  */
618 
619 /* Node paths can exceed the maximum size supported by device_get_binding() in user mode,
620  * so synthesize a unique dev_name from the devicetree node.
621  *
622  * The ordinal used in this name can be mapped to the path by
623  * examining zephyr/include/generated/device_extern.h header. If the
624  * format of this conversion changes, gen_defines should be updated to
625  * match it.
626  */
627 #define Z_DEVICE_DT_DEV_NAME(node_id) _CONCAT(dts_ord_, DT_DEP_ORD(node_id))
628 
629 /* Synthesize a unique name for the device state associated with
630  * dev_name.
631  */
632 #define Z_DEVICE_STATE_NAME(dev_name) _CONCAT(__devstate_, dev_name)
633 
634 /** Synthesize the name of the object that holds device ordinal and
635  * dependency data. If the object doesn't come from a devicetree
636  * node, use dev_name.
637  */
638 #define Z_DEVICE_HANDLE_NAME(node_id, dev_name)				\
639 	_CONCAT(__devicehdl_,						\
640 		COND_CODE_1(DT_NODE_EXISTS(node_id),			\
641 			    (node_id),					\
642 			    (dev_name)))
643 
644 #define Z_DEVICE_EXTRA_HANDLES(...)				\
645 	FOR_EACH_NONEMPTY_TERM(IDENTITY, (,), __VA_ARGS__)
646 
647 #ifdef CONFIG_PM_DEVICE
648 #define Z_DEVICE_STATE_PM_INIT(node_id, dev_name)			\
649 	.pm = Z_PM_DEVICE_INIT(Z_DEVICE_STATE_NAME(dev_name).pm, node_id),
650 #else
651 #define Z_DEVICE_STATE_PM_INIT(node_id, dev_name)
652 #endif
653 
654 /**
655  * @brief Utility macro to define and initialize the device state.
656 
657  * @param node_id Devicetree node id of the device.
658  * @param dev_name Device name.
659  */
660 #define Z_DEVICE_STATE_DEFINE(node_id, dev_name)			\
661 	static struct device_state Z_DEVICE_STATE_NAME(dev_name)	\
662 	__attribute__((__section__(".z_devstate"))) = {			\
663 		Z_DEVICE_STATE_PM_INIT(node_id, dev_name)		\
664 	};
665 
666 /* If device power management is enabled, this macro defines a pointer to a
667  * device in the z_pm_device_slots region. When invoked for each device, this
668  * will effectively result in a device pointer array with the same size of the
669  * actual devices list. This is used internally by the device PM subsystem to
670  * keep track of suspended devices during system power transitions.
671  */
672 #if CONFIG_PM_DEVICE
673 #define Z_DEVICE_DEFINE_PM_SLOT(dev_name)				\
674 	static const Z_DECL_ALIGN(struct device *)			\
675 	_CONCAT(__pm_device_slot_, DEVICE_NAME_GET(dev_name)) __used	\
676 	__attribute__((__section__(".z_pm_device_slots")));
677 #else
678 #define Z_DEVICE_DEFINE_PM_SLOT(dev_name)
679 #endif
680 
681 /* Construct objects that are referenced from struct device. These
682  * include power management and dependency handles.
683  */
684 #define Z_DEVICE_DEFINE_PRE(node_id, dev_name, ...)			\
685 	Z_DEVICE_DEFINE_HANDLES(node_id, dev_name, __VA_ARGS__)		\
686 	Z_DEVICE_STATE_DEFINE(node_id, dev_name)			\
687 	Z_DEVICE_DEFINE_PM_SLOT(dev_name)
688 
689 /* Helper macros needed for CONFIG_DEVICE_HANDLE_PADDING. These should
690  * be deleted when that option is removed.
691  *
692  * This is implemented "by hand" -- rather than using a helper macro
693  * like UTIL_LISTIFY() -- because we need to allow users to wrap
694  * DEVICE_DT_DEFINE with UTIL_LISTIFY, like this:
695  *
696  *     #define DEFINE_FOO_DEVICE(...) DEVICE_DT_DEFINE(...)
697  *     UTIL_LISTIFY(N, DEFINE_FOO_DEVICE)
698  *
699  * If Z_DEVICE_HANDLE_PADDING uses UTIL_LISTIFY, this type of code
700  * would fail, because the UTIL_LISTIFY token within the
701  * Z_DEVICE_DEFINE_HANDLES expansion would not be expanded again,
702  * since it appears in a context where UTIL_LISTIFY is already being
703  * expanded. Standard C does not reexpand macros appearing in their
704  * own expansion; this would lead to infinite recursions in general.
705  */
706 #define Z_DEVICE_HANDLE_PADDING \
707 	Z_DEVICE_HANDLE_PADDING_(CONFIG_DEVICE_HANDLE_PADDING)
708 #define Z_DEVICE_HANDLE_PADDING_(count) \
709 	Z_DEVICE_HANDLE_PADDING__(count)
710 #define Z_DEVICE_HANDLE_PADDING__(count) \
711 	Z_DEVICE_HANDLE_PADDING_ ## count
712 #define Z_DEVICE_HANDLE_PADDING_10 \
713 	DEVICE_HANDLE_ENDS, Z_DEVICE_HANDLE_PADDING_9
714 #define Z_DEVICE_HANDLE_PADDING_9 \
715 	DEVICE_HANDLE_ENDS, Z_DEVICE_HANDLE_PADDING_8
716 #define Z_DEVICE_HANDLE_PADDING_8 \
717 	DEVICE_HANDLE_ENDS, Z_DEVICE_HANDLE_PADDING_7
718 #define Z_DEVICE_HANDLE_PADDING_7 \
719 	DEVICE_HANDLE_ENDS, Z_DEVICE_HANDLE_PADDING_6
720 #define Z_DEVICE_HANDLE_PADDING_6 \
721 	DEVICE_HANDLE_ENDS, Z_DEVICE_HANDLE_PADDING_5
722 #define Z_DEVICE_HANDLE_PADDING_5 \
723 	DEVICE_HANDLE_ENDS, Z_DEVICE_HANDLE_PADDING_4
724 #define Z_DEVICE_HANDLE_PADDING_4 \
725 	DEVICE_HANDLE_ENDS, Z_DEVICE_HANDLE_PADDING_3
726 #define Z_DEVICE_HANDLE_PADDING_3 \
727 	DEVICE_HANDLE_ENDS, Z_DEVICE_HANDLE_PADDING_2
728 #define Z_DEVICE_HANDLE_PADDING_2 \
729 	DEVICE_HANDLE_ENDS, Z_DEVICE_HANDLE_PADDING_1
730 #define Z_DEVICE_HANDLE_PADDING_1 \
731 	DEVICE_HANDLE_ENDS, Z_DEVICE_HANDLE_PADDING_0
732 #define Z_DEVICE_HANDLE_PADDING_0 EMPTY
733 
734 /* Initial build provides a record that associates the device object
735  * with its devicetree ordinal, and provides the dependency ordinals.
736  * These are provided as weak definitions (to prevent the reference
737  * from being captured when the original object file is compiled), and
738  * in a distinct pass1 section (which will be replaced by
739  * postprocessing).
740  *
741  * It is also (experimentally) necessary to provide explicit alignment
742  * on each object. Otherwise x86-64 builds will introduce padding
743  * between objects in the same input section in individual object
744  * files, which will be retained in subsequent links both wasting
745  * space and resulting in aggregate size changes relative to pass2
746  * when all objects will be in the same input section.
747  *
748  * The build assert will fail if device_handle_t changes size, which
749  * means the alignment directives in the linker scripts and in
750  * `gen_handles.py` must be updated.
751  */
752 BUILD_ASSERT(sizeof(device_handle_t) == 2, "fix the linker scripts");
753 #define Z_DEVICE_DEFINE_HANDLES(node_id, dev_name, ...)			\
754 	extern const device_handle_t					\
755 		Z_DEVICE_HANDLE_NAME(node_id, dev_name)[];		\
756 	const device_handle_t						\
757 	__aligned(sizeof(device_handle_t))				\
758 	__attribute__((__weak__,					\
759 		       __section__(".__device_handles_pass1")))		\
760 	Z_DEVICE_HANDLE_NAME(node_id, dev_name)[] = {			\
761 	COND_CODE_1(DT_NODE_EXISTS(node_id), (				\
762 			DT_DEP_ORD(node_id),				\
763 			DT_REQUIRES_DEP_ORDS(node_id)			\
764 		), (							\
765 			DEVICE_HANDLE_NULL,				\
766 		))							\
767 			DEVICE_HANDLE_SEP,				\
768 			Z_DEVICE_EXTRA_HANDLES(__VA_ARGS__)		\
769 			Z_DEVICE_HANDLE_PADDING				\
770 		};
771 
772 #ifdef CONFIG_PM_DEVICE
773 #define Z_DEVICE_DEFINE_PM_INIT(dev_name, pm_control_fn)		\
774 	.pm_control = (pm_control_fn),					\
775 	.pm = &Z_DEVICE_STATE_NAME(dev_name).pm,
776 #else
777 #define Z_DEVICE_DEFINE_PM_INIT(dev_name, pm_control_fn)
778 #endif
779 
780 #define Z_DEVICE_DEFINE_INIT(node_id, dev_name, pm_control_fn)		\
781 		.handles = Z_DEVICE_HANDLE_NAME(node_id, dev_name),	\
782 		Z_DEVICE_DEFINE_PM_INIT(dev_name, pm_control_fn)
783 
784 /* Like DEVICE_DEFINE but takes a node_id AND a dev_name, and trailing
785  * dependency handles that come from outside devicetree.
786  */
787 #define Z_DEVICE_DEFINE(node_id, dev_name, drv_name, init_fn, pm_control_fn, \
788 			data_ptr, cfg_ptr, level, prio, api_ptr, ...)	\
789 	Z_DEVICE_DEFINE_PRE(node_id, dev_name, __VA_ARGS__)		\
790 	COND_CODE_1(DT_NODE_EXISTS(node_id), (), (static))		\
791 		const Z_DECL_ALIGN(struct device)			\
792 		DEVICE_NAME_GET(dev_name) __used			\
793 	__attribute__((__section__(".z_device_" #level STRINGIFY(prio)"_"))) = { \
794 		.name = drv_name,					\
795 		.config = (cfg_ptr),					\
796 		.api = (api_ptr),					\
797 		.state = &Z_DEVICE_STATE_NAME(dev_name),		\
798 		.data = (data_ptr),					\
799 		Z_DEVICE_DEFINE_INIT(node_id, dev_name, pm_control_fn)	\
800 	};								\
801 	BUILD_ASSERT(sizeof(Z_STRINGIFY(drv_name)) <= Z_DEVICE_MAX_NAME_LEN, \
802 		     Z_STRINGIFY(DEVICE_NAME_GET(drv_name)) " too long"); \
803 	Z_INIT_ENTRY_DEFINE(DEVICE_NAME_GET(dev_name), init_fn,		\
804 		(&DEVICE_NAME_GET(dev_name)), level, prio)
805 
806 #ifdef __cplusplus
807 }
808 #endif
809 
810 /* device_extern is generated based on devicetree nodes */
811 #include <device_extern.h>
812 
813 #include <syscalls/device.h>
814 
815 #endif /* ZEPHYR_INCLUDE_DEVICE_H_ */
816