1.. _device_model_api: 2 3Device Driver Model 4################### 5 6Introduction 7************ 8The Zephyr kernel supports a variety of device drivers. Whether a 9driver is available depends on the board and the driver. 10 11The Zephyr device model provides a consistent device model for configuring the 12drivers that are part of a system. The device model is responsible 13for initializing all the drivers configured into the system. 14 15Each type of driver (e.g. UART, SPI, I2C) is supported by a generic type API. 16 17In this model the driver fills in the pointer to the structure containing the 18function pointers to its API functions during driver initialization. These 19structures are placed into the RAM section in initialization level order. 20 21.. image:: device_driver_model.svg 22 :width: 40% 23 :align: center 24 :alt: Device Driver Model 25 26Standard Drivers 27**************** 28 29Device drivers which are present on all supported board configurations 30are listed below. 31 32* **Interrupt controller**: This device driver is used by the kernel's 33 interrupt management subsystem. 34 35* **Timer**: This device driver is used by the kernel's system clock and 36 hardware clock subsystem. 37 38* **Serial communication**: This device driver is used by the kernel's 39 system console subsystem. 40 41* **Entropy**: This device driver provides a source of entropy numbers 42 for the random number generator subsystem. 43 44 .. important:: 45 46 Use the :ref:`random API functions <random_api>` for random 47 values. :ref:`Entropy functions <entropy_api>` should not be 48 directly used as a random number generator source as some hardware 49 implementations are designed to be an entropy seed source for random 50 number generators and will not provide cryptographically secure 51 random number streams. 52 53Synchronous Calls 54***************** 55 56Zephyr provides a set of device drivers for multiple boards. Each driver 57should support an interrupt-based implementation, rather than polling, unless 58the specific hardware does not provide any interrupt. 59 60High-level calls accessed through device-specific APIs, such as 61:file:`i2c.h` or :file:`spi.h`, are usually intended as synchronous. Thus, 62these calls should be blocking. 63 64Driver APIs 65*********** 66 67The following APIs for device drivers are provided by :file:`device.h`. The APIs 68are intended for use in device drivers only and should not be used in 69applications. 70 71:c:func:`DEVICE_DEFINE()` 72 Create device object and related data structures including setting it 73 up for boot-time initialization. 74 75:c:func:`DEVICE_NAME_GET()` 76 Converts a device identifier to the global identifier for a device 77 object. 78 79:c:func:`DEVICE_GET()` 80 Obtain a pointer to a device object by name. 81 82:c:func:`DEVICE_DECLARE()` 83 Declare a device object. Use this when you need a forward reference 84 to a device that has not yet been defined. 85 86.. _device_struct: 87 88Driver Data Structures 89********************** 90 91The device initialization macros populate some data structures at build time 92which are 93split into read-only and runtime-mutable parts. At a high level we have: 94 95.. code-block:: C 96 97 struct device { 98 const char *name; 99 const void *config; 100 const void *api; 101 void * const data; 102 }; 103 104The ``config`` member is for read-only configuration data set at build time. For 105example, base memory mapped IO addresses, IRQ line numbers, or other fixed 106physical characteristics of the device. This is the ``config`` pointer 107passed to ``DEVICE_DEFINE()`` and related macros. 108 109The ``data`` struct is kept in RAM, and is used by the driver for 110per-instance runtime housekeeping. For example, it may contain reference counts, 111semaphores, scratch buffers, etc. 112 113The ``api`` struct maps generic subsystem APIs to the device-specific 114implementations in the driver. It is typically read-only and populated at 115build time. The next section describes this in more detail. 116 117 118Subsystems and API Structures 119***************************** 120 121Most drivers will be implementing a device-independent subsystem API. 122Applications can simply program to that generic API, and application 123code is not specific to any particular driver implementation. 124 125A subsystem API definition typically looks like this: 126 127.. code-block:: C 128 129 typedef int (*subsystem_do_this_t)(const struct device *dev, int foo, int bar); 130 typedef void (*subsystem_do_that_t)(const struct device *dev, void *baz); 131 132 struct subsystem_api { 133 subsystem_do_this_t do_this; 134 subsystem_do_that_t do_that; 135 }; 136 137 static inline int subsystem_do_this(const struct device *dev, int foo, int bar) 138 { 139 struct subsystem_api *api; 140 141 api = (struct subsystem_api *)dev->api; 142 return api->do_this(dev, foo, bar); 143 } 144 145 static inline void subsystem_do_that(const struct device *dev, void *baz) 146 { 147 struct subsystem_api *api; 148 149 api = (struct subsystem_api *)dev->api; 150 api->do_that(dev, baz); 151 } 152 153A driver implementing a particular subsystem will define the real implementation 154of these APIs, and populate an instance of subsystem_api structure: 155 156.. code-block:: C 157 158 static int my_driver_do_this(const struct device *dev, int foo, int bar) 159 { 160 ... 161 } 162 163 static void my_driver_do_that(const struct device *dev, void *baz) 164 { 165 ... 166 } 167 168 static struct subsystem_api my_driver_api_funcs = { 169 .do_this = my_driver_do_this, 170 .do_that = my_driver_do_that 171 }; 172 173The driver would then pass ``my_driver_api_funcs`` as the ``api`` argument to 174``DEVICE_DEFINE()``. 175 176.. note:: 177 178 Since pointers to the API functions are referenced in the ``api`` 179 struct, they will always be included in the binary even if unused; 180 ``gc-sections`` linker option will always see at least one reference to 181 them. Providing for link-time size optimizations with driver APIs in 182 most cases requires that the optional feature be controlled by a 183 Kconfig option. 184 185Device-Specific API Extensions 186****************************** 187 188Some devices can be cast as an instance of a driver subsystem such as GPIO, 189but provide additional functionality that cannot be exposed through the 190standard API. These devices combine subsystem operations with 191device-specific APIs, described in a device-specific header. 192 193A device-specific API definition typically looks like this: 194 195.. code-block:: C 196 197 #include <zephyr/drivers/subsystem.h> 198 199 /* When extensions need not be invoked from user mode threads */ 200 int specific_do_that(const struct device *dev, int foo); 201 202 /* When extensions must be invokable from user mode threads */ 203 __syscall int specific_from_user(const struct device *dev, int bar); 204 205 /* Only needed when extensions include syscalls */ 206 #include <zephyr/syscalls/specific.h> 207 208A driver implementing extensions to the subsystem will define the real 209implementation of both the subsystem API and the specific APIs: 210 211.. code-block:: C 212 213 static int generic_do_this(const struct device *dev, void *arg) 214 { 215 ... 216 } 217 218 static struct generic_api api { 219 ... 220 .do_this = generic_do_this, 221 ... 222 }; 223 224 /* supervisor-only API is globally visible */ 225 int specific_do_that(const struct device *dev, int foo) 226 { 227 ... 228 } 229 230 /* syscall API passes through a translation */ 231 int z_impl_specific_from_user(const struct device *dev, int bar) 232 { 233 ... 234 } 235 236 #ifdef CONFIG_USERSPACE 237 238 #include <zephyr/internal/syscall_handler.h> 239 240 int z_vrfy_specific_from_user(const struct device *dev, int bar) 241 { 242 K_OOPS(K_SYSCALL_SPECIFIC_DRIVER(dev, K_OBJ_DRIVER_GENERIC, &api)); 243 return z_impl_specific_do_that(dev, bar) 244 } 245 246 #include <zephyr/syscalls/specific_from_user_mrsh.c> 247 248 #endif /* CONFIG_USERSPACE */ 249 250Applications use the device through both the subsystem and specific 251APIs. 252 253.. note:: 254 Public API for device-specific extensions should be prefixed with the 255 compatible for the device to which it applies. For example, if 256 adding special functions to support the Maxim DS3231 the identifier 257 fragment ``specific`` in the examples above would be ``maxim_ds3231``. 258 259Single Driver, Multiple Instances 260********************************* 261 262Some drivers may be instantiated multiple times in a given system. For example 263there can be multiple GPIO banks, or multiple UARTS. Each instance of the driver 264will have a different ``config`` struct and ``data`` struct. 265 266Configuring interrupts for multiple drivers instances is a special case. If each 267instance needs to configure a different interrupt line, this can be accomplished 268through the use of per-instance configuration functions, since the parameters 269to ``IRQ_CONNECT()`` need to be resolvable at build time. 270 271For example, let's say we need to configure two instances of ``my_driver``, each 272with a different interrupt line. In ``drivers/subsystem/subsystem_my_driver.h``: 273 274.. code-block:: C 275 276 typedef void (*my_driver_config_irq_t)(const struct device *dev); 277 278 struct my_driver_config { 279 DEVICE_MMIO_ROM; 280 my_driver_config_irq_t config_func; 281 }; 282 283In the implementation of the common init function: 284 285.. code-block:: C 286 287 void my_driver_isr(const struct device *dev) 288 { 289 /* Handle interrupt */ 290 ... 291 } 292 293 int my_driver_init(const struct device *dev) 294 { 295 const struct my_driver_config *config = dev->config; 296 297 DEVICE_MMIO_MAP(dev, K_MEM_CACHE_NONE); 298 299 /* Do other initialization stuff */ 300 ... 301 302 config->config_func(dev); 303 304 return 0; 305 } 306 307Then when the particular instance is declared: 308 309.. code-block:: C 310 311 #if CONFIG_MY_DRIVER_0 312 313 DEVICE_DECLARE(my_driver_0); 314 315 static void my_driver_config_irq_0(const struct device *dev) 316 { 317 IRQ_CONNECT(MY_DRIVER_0_IRQ, MY_DRIVER_0_PRI, my_driver_isr, 318 DEVICE_GET(my_driver_0), MY_DRIVER_0_FLAGS); 319 } 320 321 const static struct my_driver_config my_driver_config_0 = { 322 DEVICE_MMIO_ROM_INIT(DT_DRV_INST(0)), 323 .config_func = my_driver_config_irq_0 324 } 325 326 static struct my_data_0; 327 328 DEVICE_DEFINE(my_driver_0, MY_DRIVER_0_NAME, my_driver_init, 329 NULL, &my_data_0, &my_driver_config_0, 330 POST_KERNEL, MY_DRIVER_0_PRIORITY, &my_api_funcs); 331 332 #endif /* CONFIG_MY_DRIVER_0 */ 333 334Note the use of ``DEVICE_DECLARE()`` to avoid a circular dependency on providing 335the IRQ handler argument and the definition of the device itself. 336 337Initialization Levels 338********************* 339 340Drivers may depend on other drivers being initialized first, or require 341the use of kernel services. :c:func:`DEVICE_DEFINE()` and related APIs 342allow the user to specify at what time during the boot sequence the init 343function will be executed. Any driver will specify one of four 344initialization levels: 345 346``PRE_KERNEL_1`` 347 Used for devices that have no dependencies, such as those that rely 348 solely on hardware present in the processor/SOC. These devices cannot 349 use any kernel services during configuration, since the kernel services are 350 not yet available. The interrupt subsystem will be configured however 351 so it's OK to set up interrupts. Init functions at this level run on the 352 interrupt stack. 353 354``PRE_KERNEL_2`` 355 Used for devices that rely on the initialization of devices initialized 356 as part of the ``PRE_KERNEL_1`` level. These devices cannot use any kernel 357 services during configuration, since the kernel services are not yet 358 available. Init functions at this level run on the interrupt stack. 359 360``POST_KERNEL`` 361 Used for devices that require kernel services during configuration. 362 Init functions at this level run in context of the kernel main task. 363 364Within each initialization level you may specify a priority level, relative to 365other devices in the same initialization level. The priority level is specified 366as an integer value in the range 0 to 99; lower values indicate earlier 367initialization. The priority level must be a decimal integer literal without 368leading zeroes or sign (e.g. 32), or an equivalent symbolic name (e.g. 369``\#define MY_INIT_PRIO 32``); symbolic expressions are *not* permitted (e.g. 370``CONFIG_KERNEL_INIT_PRIORITY_DEFAULT + 5``). 371 372Drivers and other system utilities can determine whether startup is 373still in pre-kernel states by using the :c:func:`k_is_pre_kernel` 374function. 375 376Deferred initialization 377*********************** 378 379Initialization of devices can also be deferred to a later time. In this case, 380the device is not automatically initialized by Zephyr at boot time. Instead, 381the device is initialized when the application calls :c:func:`device_init`. 382To defer a device driver initialization, add the property ``zephyr,deferred-init`` 383to the associated device node in the DTS file. For example: 384 385.. code-block:: devicetree 386 387 / { 388 a-driver@40000000 { 389 reg = <0x40000000 0x1000>; 390 zephyr,deferred-init; 391 }; 392 }; 393 394System Drivers 395************** 396 397In some cases you may just need to run a function at boot. For such cases, the 398:c:macro:`SYS_INIT` can be used. This macro does not take any config or runtime 399data structures and there isn't a way to later get a device pointer by name. The 400same device policies for initialization level and priority apply. 401 402Inspecting the initialization sequence 403************************************** 404 405Device drivers declared with :c:macro:`DEVICE_DEFINE` (or any variations of it) 406and :c:macro:`SYS_INIT` are processed at boot time and the corresponding 407initialization functions are called sequentially according to their specified 408level and priority. 409 410Sometimes it's useful to inspect the final sequence of initialization function 411call as produced by the linker. To do that, use the ``initlevels`` CMake 412target, for example ``west build -t initlevels``. 413 414Error handling 415************** 416 417In general, it's best to use ``__ASSERT()`` macros instead of 418propagating return values unless the failure is expected to occur 419during the normal course of operation (such as a storage device 420full). Bad parameters, programming errors, consistency checks, 421pathological/unrecoverable failures, etc., should be handled by 422assertions. 423 424When it is appropriate to return error conditions for the caller to 425check, 0 should be returned on success and a POSIX :file:`errno.h` code 426returned on failure. See 427https://github.com/zephyrproject-rtos/zephyr/wiki/Naming-Conventions#return-codes 428for details about this. 429 430Memory Mapping 431************** 432 433On some systems, the linear address of peripheral memory-mapped I/O (MMIO) 434regions cannot be known at build time: 435 436- The I/O ranges must be probed at runtime from the bus, such as with 437 PCI express 438- A memory management unit (MMU) is active, and the physical address of 439 the MMIO range must be mapped into the page tables at some virtual 440 memory location determined by the kernel. 441 442These systems must maintain storage for the MMIO range within RAM and 443establish the mapping within the driver's init function. Other systems 444do not care about this and can use MMIO physical addresses directly from 445DTS and do not need any RAM-based storage for it. 446 447For drivers that may need to deal with this situation, a set of 448APIs under the DEVICE_MMIO scope are defined, along with a mapping function 449:c:func:`device_map`. 450 451Device Model Drivers with one MMIO region 452========================================= 453 454The simplest case is for drivers which need to maintain one MMIO region. 455These drivers will need to use the ``DEVICE_MMIO_ROM`` and 456``DEVICE_MMIO_RAM`` macros in the definitions for their ``config_info`` 457and ``driver_data`` structures, with initialization of the ``config_info`` 458from DTS using ``DEVICE_MMIO_ROM_INIT``. A call to ``DEVICE_MMIO_MAP()`` 459is made within the init function: 460 461.. code-block:: C 462 463 struct my_driver_config { 464 DEVICE_MMIO_ROM; /* Must be first */ 465 ... 466 } 467 468 struct my_driver_dev_data { 469 DEVICE_MMIO_RAM; /* Must be first */ 470 ... 471 } 472 473 const static struct my_driver_config my_driver_config_0 = { 474 DEVICE_MMIO_ROM_INIT(DT_DRV_INST(...)), 475 ... 476 } 477 478 int my_driver_init(const struct device *dev) 479 { 480 ... 481 DEVICE_MMIO_MAP(dev, K_MEM_CACHE_NONE); 482 ... 483 } 484 485 int my_driver_some_function(const struct device *dev) 486 { 487 ... 488 /* Write some data to the MMIO region */ 489 sys_write32(0xDEADBEEF, DEVICE_MMIO_GET(dev)); 490 ... 491 } 492 493The particular expansion of these macros depends on configuration. On 494a device with no MMU or PCI-e, ``DEVICE_MMIO_MAP`` and 495``DEVICE_MMIO_RAM`` expand to nothing. 496 497Device Model Drivers with multiple MMIO regions 498=============================================== 499 500Some drivers may have multiple MMIO regions. In addition, some drivers 501may already be implementing a form of inheritance which requires some other 502data to be placed first in the ``config_info`` and ``driver_data`` 503structures. 504 505This can be managed with the ``DEVICE_MMIO_NAMED`` variant macros. These 506require that ``DEV_CFG()`` and ``DEV_DATA()`` macros be defined to obtain 507a properly typed pointer to the driver's config_info or dev_data structs. 508For example: 509 510.. code-block:: C 511 512 struct my_driver_config { 513 ... 514 DEVICE_MMIO_NAMED_ROM(corge); 515 DEVICE_MMIO_NAMED_ROM(grault); 516 ... 517 } 518 519 struct my_driver_dev_data { 520 ... 521 DEVICE_MMIO_NAMED_RAM(corge); 522 DEVICE_MMIO_NAMED_RAM(grault); 523 ... 524 } 525 526 #define DEV_CFG(_dev) \ 527 ((const struct my_driver_config *)((_dev)->config)) 528 529 #define DEV_DATA(_dev) \ 530 ((struct my_driver_dev_data *)((_dev)->data)) 531 532 const static struct my_driver_config my_driver_config_0 = { 533 ... 534 DEVICE_MMIO_NAMED_ROM_INIT(corge, DT_DRV_INST(...)), 535 DEVICE_MMIO_NAMED_ROM_INIT(grault, DT_DRV_INST(...)), 536 ... 537 } 538 539 int my_driver_init(const struct device *dev) 540 { 541 ... 542 DEVICE_MMIO_NAMED_MAP(dev, corge, K_MEM_CACHE_NONE); 543 DEVICE_MMIO_NAMED_MAP(dev, grault, K_MEM_CACHE_NONE); 544 ... 545 } 546 547 int my_driver_some_function(const struct device *dev) 548 { 549 ... 550 /* Write some data to the MMIO regions */ 551 sys_write32(0xDEADBEEF, DEVICE_MMIO_GET(dev, grault)); 552 sys_write32(0xF0CCAC1A, DEVICE_MMIO_GET(dev, corge)); 553 ... 554 } 555 556Device Model Drivers with multiple MMIO regions in the same DT node 557=================================================================== 558 559Some drivers may have multiple MMIO regions defined into the same DT device 560node using the ``reg-names`` property to differentiate them, for example: 561 562.. code-block:: devicetree 563 564 /dts-v1/; 565 566 / { 567 a-driver@40000000 { 568 reg = <0x40000000 0x1000>, 569 <0x40001000 0x1000>; 570 reg-names = "corge", "grault"; 571 }; 572 }; 573 574This can be managed as seen in the previous section but this time using the 575``DEVICE_MMIO_NAMED_ROM_INIT_BY_NAME`` macro instead. So the only difference 576would be in the driver config struct: 577 578.. code-block:: C 579 580 const static struct my_driver_config my_driver_config_0 = { 581 ... 582 DEVICE_MMIO_NAMED_ROM_INIT_BY_NAME(corge, DT_DRV_INST(...)), 583 DEVICE_MMIO_NAMED_ROM_INIT_BY_NAME(grault, DT_DRV_INST(...)), 584 ... 585 } 586 587Drivers that do not use Zephyr Device Model 588=========================================== 589 590Some drivers or driver-like code may not user Zephyr's device model, 591and alternative storage must be arranged for the MMIO data. An 592example of this are timer drivers, or interrupt controller code. 593 594This can be managed with the ``DEVICE_MMIO_TOPLEVEL`` set of macros, 595for example: 596 597.. code-block:: C 598 599 DEVICE_MMIO_TOPLEVEL_STATIC(my_regs, DT_DRV_INST(..)); 600 601 void some_init_code(...) 602 { 603 ... 604 DEVICE_MMIO_TOPLEVEL_MAP(my_regs, K_MEM_CACHE_NONE); 605 ... 606 } 607 608 void some_function(...) 609 ... 610 sys_write32(DEVICE_MMIO_TOPLEVEL_GET(my_regs), 0xDEADBEEF); 611 ... 612 } 613 614Drivers that do not use DTS 615=========================== 616 617Some drivers may not obtain the MMIO physical address from DTS, such as 618is the case with PCI-E. In this case the :c:func:`device_map` function 619may be used directly: 620 621.. code-block:: C 622 623 void some_init_code(...) 624 { 625 ... 626 struct pcie_bar mbar; 627 bool bar_found = pcie_get_mbar(bdf, index, &mbar); 628 629 device_map(DEVICE_MMIO_RAM_PTR(dev), mbar.phys_addr, mbar.size, K_MEM_CACHE_NONE); 630 ... 631 } 632 633For these cases, DEVICE_MMIO_ROM directives may be omitted. 634 635API Reference 636************** 637 638.. doxygengroup:: device_model 639