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