a7f11765303342f873162fe5bf951d3d6b09a28e
[cascardo/linux.git] / Documentation / gpu / drm-internals.rst
1 =============
2 DRM Internals
3 =============
4
5 This chapter documents DRM internals relevant to driver authors and
6 developers working to add support for the latest features to existing
7 drivers.
8
9 First, we go over some typical driver initialization requirements, like
10 setting up command buffers, creating an initial output configuration,
11 and initializing core services. Subsequent sections cover core internals
12 in more detail, providing implementation notes and examples.
13
14 The DRM layer provides several services to graphics drivers, many of
15 them driven by the application interfaces it provides through libdrm,
16 the library that wraps most of the DRM ioctls. These include vblank
17 event handling, memory management, output management, framebuffer
18 management, command submission & fencing, suspend/resume support, and
19 DMA services.
20
21 Driver Initialization
22 =====================
23
24 At the core of every DRM driver is a :c:type:`struct drm_driver
25 <drm_driver>` structure. Drivers typically statically initialize
26 a drm_driver structure, and then pass it to
27 :c:func:`drm_dev_alloc()` to allocate a device instance. After the
28 device instance is fully initialized it can be registered (which makes
29 it accessible from userspace) using :c:func:`drm_dev_register()`.
30
31 The :c:type:`struct drm_driver <drm_driver>` structure
32 contains static information that describes the driver and features it
33 supports, and pointers to methods that the DRM core will call to
34 implement the DRM API. We will first go through the :c:type:`struct
35 drm_driver <drm_driver>` static information fields, and will
36 then describe individual operations in details as they get used in later
37 sections.
38
39 Driver Information
40 ------------------
41
42 Driver Features
43 ^^^^^^^^^^^^^^^
44
45 Drivers inform the DRM core about their requirements and supported
46 features by setting appropriate flags in the driver_features field.
47 Since those flags influence the DRM core behaviour since registration
48 time, most of them must be set to registering the :c:type:`struct
49 drm_driver <drm_driver>` instance.
50
51 u32 driver_features;
52
53 DRIVER_USE_AGP
54     Driver uses AGP interface, the DRM core will manage AGP resources.
55
56 DRIVER_REQUIRE_AGP
57     Driver needs AGP interface to function. AGP initialization failure
58     will become a fatal error.
59
60 DRIVER_PCI_DMA
61     Driver is capable of PCI DMA, mapping of PCI DMA buffers to
62     userspace will be enabled. Deprecated.
63
64 DRIVER_SG
65     Driver can perform scatter/gather DMA, allocation and mapping of
66     scatter/gather buffers will be enabled. Deprecated.
67
68 DRIVER_HAVE_DMA
69     Driver supports DMA, the userspace DMA API will be supported.
70     Deprecated.
71
72 DRIVER_HAVE_IRQ; DRIVER_IRQ_SHARED
73     DRIVER_HAVE_IRQ indicates whether the driver has an IRQ handler
74     managed by the DRM Core. The core will support simple IRQ handler
75     installation when the flag is set. The installation process is
76     described in ?.
77
78     DRIVER_IRQ_SHARED indicates whether the device & handler support
79     shared IRQs (note that this is required of PCI drivers).
80
81 DRIVER_GEM
82     Driver use the GEM memory manager.
83
84 DRIVER_MODESET
85     Driver supports mode setting interfaces (KMS).
86
87 DRIVER_PRIME
88     Driver implements DRM PRIME buffer sharing.
89
90 DRIVER_RENDER
91     Driver supports dedicated render nodes.
92
93 DRIVER_ATOMIC
94     Driver supports atomic properties. In this case the driver must
95     implement appropriate obj->atomic_get_property() vfuncs for any
96     modeset objects with driver specific properties.
97
98 Major, Minor and Patchlevel
99 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
100
101 int major; int minor; int patchlevel;
102 The DRM core identifies driver versions by a major, minor and patch
103 level triplet. The information is printed to the kernel log at
104 initialization time and passed to userspace through the
105 DRM_IOCTL_VERSION ioctl.
106
107 The major and minor numbers are also used to verify the requested driver
108 API version passed to DRM_IOCTL_SET_VERSION. When the driver API
109 changes between minor versions, applications can call
110 DRM_IOCTL_SET_VERSION to select a specific version of the API. If the
111 requested major isn't equal to the driver major, or the requested minor
112 is larger than the driver minor, the DRM_IOCTL_SET_VERSION call will
113 return an error. Otherwise the driver's set_version() method will be
114 called with the requested version.
115
116 Name, Description and Date
117 ^^^^^^^^^^^^^^^^^^^^^^^^^^
118
119 char \*name; char \*desc; char \*date;
120 The driver name is printed to the kernel log at initialization time,
121 used for IRQ registration and passed to userspace through
122 DRM_IOCTL_VERSION.
123
124 The driver description is a purely informative string passed to
125 userspace through the DRM_IOCTL_VERSION ioctl and otherwise unused by
126 the kernel.
127
128 The driver date, formatted as YYYYMMDD, is meant to identify the date of
129 the latest modification to the driver. However, as most drivers fail to
130 update it, its value is mostly useless. The DRM core prints it to the
131 kernel log at initialization time and passes it to userspace through the
132 DRM_IOCTL_VERSION ioctl.
133
134 Device Instance and Driver Handling
135 -----------------------------------
136
137 .. kernel-doc:: drivers/gpu/drm/drm_drv.c
138    :doc: driver instance overview
139
140 .. kernel-doc:: drivers/gpu/drm/drm_drv.c
141    :export:
142
143 Driver Load
144 -----------
145
146 IRQ Registration
147 ^^^^^^^^^^^^^^^^
148
149 The DRM core tries to facilitate IRQ handler registration and
150 unregistration by providing :c:func:`drm_irq_install()` and
151 :c:func:`drm_irq_uninstall()` functions. Those functions only
152 support a single interrupt per device, devices that use more than one
153 IRQs need to be handled manually.
154
155 Managed IRQ Registration
156 ''''''''''''''''''''''''
157
158 :c:func:`drm_irq_install()` starts by calling the irq_preinstall
159 driver operation. The operation is optional and must make sure that the
160 interrupt will not get fired by clearing all pending interrupt flags or
161 disabling the interrupt.
162
163 The passed-in IRQ will then be requested by a call to
164 :c:func:`request_irq()`. If the DRIVER_IRQ_SHARED driver feature
165 flag is set, a shared (IRQF_SHARED) IRQ handler will be requested.
166
167 The IRQ handler function must be provided as the mandatory irq_handler
168 driver operation. It will get passed directly to
169 :c:func:`request_irq()` and thus has the same prototype as all IRQ
170 handlers. It will get called with a pointer to the DRM device as the
171 second argument.
172
173 Finally the function calls the optional irq_postinstall driver
174 operation. The operation usually enables interrupts (excluding the
175 vblank interrupt, which is enabled separately), but drivers may choose
176 to enable/disable interrupts at a different time.
177
178 :c:func:`drm_irq_uninstall()` is similarly used to uninstall an
179 IRQ handler. It starts by waking up all processes waiting on a vblank
180 interrupt to make sure they don't hang, and then calls the optional
181 irq_uninstall driver operation. The operation must disable all hardware
182 interrupts. Finally the function frees the IRQ by calling
183 :c:func:`free_irq()`.
184
185 Manual IRQ Registration
186 '''''''''''''''''''''''
187
188 Drivers that require multiple interrupt handlers can't use the managed
189 IRQ registration functions. In that case IRQs must be registered and
190 unregistered manually (usually with the :c:func:`request_irq()` and
191 :c:func:`free_irq()` functions, or their devm_\* equivalent).
192
193 When manually registering IRQs, drivers must not set the
194 DRIVER_HAVE_IRQ driver feature flag, and must not provide the
195 irq_handler driver operation. They must set the :c:type:`struct
196 drm_device <drm_device>` irq_enabled field to 1 upon
197 registration of the IRQs, and clear it to 0 after unregistering the
198 IRQs.
199
200 Memory Manager Initialization
201 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
202
203 Every DRM driver requires a memory manager which must be initialized at
204 load time. DRM currently contains two memory managers, the Translation
205 Table Manager (TTM) and the Graphics Execution Manager (GEM). This
206 document describes the use of the GEM memory manager only. See ? for
207 details.
208
209 Miscellaneous Device Configuration
210 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
211
212 Another task that may be necessary for PCI devices during configuration
213 is mapping the video BIOS. On many devices, the VBIOS describes device
214 configuration, LCD panel timings (if any), and contains flags indicating
215 device state. Mapping the BIOS can be done using the pci_map_rom()
216 call, a convenience function that takes care of mapping the actual ROM,
217 whether it has been shadowed into memory (typically at address 0xc0000)
218 or exists on the PCI device in the ROM BAR. Note that after the ROM has
219 been mapped and any necessary information has been extracted, it should
220 be unmapped; on many devices, the ROM address decoder is shared with
221 other BARs, so leaving it mapped could cause undesired behaviour like
222 hangs or memory corruption.
223
224 Bus-specific Device Registration and PCI Support
225 ------------------------------------------------
226
227 A number of functions are provided to help with device registration. The
228 functions deal with PCI and platform devices respectively and are only
229 provided for historical reasons. These are all deprecated and shouldn't
230 be used in new drivers. Besides that there's a few helpers for pci
231 drivers.
232
233 .. kernel-doc:: drivers/gpu/drm/drm_pci.c
234    :export:
235
236 .. kernel-doc:: drivers/gpu/drm/drm_platform.c
237    :export:
238
239 Memory management
240 =================
241
242 Modern Linux systems require large amount of graphics memory to store
243 frame buffers, textures, vertices and other graphics-related data. Given
244 the very dynamic nature of many of that data, managing graphics memory
245 efficiently is thus crucial for the graphics stack and plays a central
246 role in the DRM infrastructure.
247
248 The DRM core includes two memory managers, namely Translation Table Maps
249 (TTM) and Graphics Execution Manager (GEM). TTM was the first DRM memory
250 manager to be developed and tried to be a one-size-fits-them all
251 solution. It provides a single userspace API to accommodate the need of
252 all hardware, supporting both Unified Memory Architecture (UMA) devices
253 and devices with dedicated video RAM (i.e. most discrete video cards).
254 This resulted in a large, complex piece of code that turned out to be
255 hard to use for driver development.
256
257 GEM started as an Intel-sponsored project in reaction to TTM's
258 complexity. Its design philosophy is completely different: instead of
259 providing a solution to every graphics memory-related problems, GEM
260 identified common code between drivers and created a support library to
261 share it. GEM has simpler initialization and execution requirements than
262 TTM, but has no video RAM management capabilities and is thus limited to
263 UMA devices.
264
265 The Translation Table Manager (TTM)
266 -----------------------------------
267
268 TTM design background and information belongs here.
269
270 TTM initialization
271 ^^^^^^^^^^^^^^^^^^
272
273     **Warning**
274
275     This section is outdated.
276
277 Drivers wishing to support TTM must fill out a drm_bo_driver
278 structure. The structure contains several fields with function pointers
279 for initializing the TTM, allocating and freeing memory, waiting for
280 command completion and fence synchronization, and memory migration. See
281 the radeon_ttm.c file for an example of usage.
282
283 The ttm_global_reference structure is made up of several fields:
284
285 ::
286
287               struct ttm_global_reference {
288                       enum ttm_global_types global_type;
289                       size_t size;
290                       void *object;
291                       int (*init) (struct ttm_global_reference *);
292                       void (*release) (struct ttm_global_reference *);
293               };
294
295
296 There should be one global reference structure for your memory manager
297 as a whole, and there will be others for each object created by the
298 memory manager at runtime. Your global TTM should have a type of
299 TTM_GLOBAL_TTM_MEM. The size field for the global object should be
300 sizeof(struct ttm_mem_global), and the init and release hooks should
301 point at your driver-specific init and release routines, which probably
302 eventually call ttm_mem_global_init and ttm_mem_global_release,
303 respectively.
304
305 Once your global TTM accounting structure is set up and initialized by
306 calling ttm_global_item_ref() on it, you need to create a buffer
307 object TTM to provide a pool for buffer object allocation by clients and
308 the kernel itself. The type of this object should be
309 TTM_GLOBAL_TTM_BO, and its size should be sizeof(struct
310 ttm_bo_global). Again, driver-specific init and release functions may
311 be provided, likely eventually calling ttm_bo_global_init() and
312 ttm_bo_global_release(), respectively. Also, like the previous
313 object, ttm_global_item_ref() is used to create an initial reference
314 count for the TTM, which will call your initialization function.
315
316 The Graphics Execution Manager (GEM)
317 ------------------------------------
318
319 The GEM design approach has resulted in a memory manager that doesn't
320 provide full coverage of all (or even all common) use cases in its
321 userspace or kernel API. GEM exposes a set of standard memory-related
322 operations to userspace and a set of helper functions to drivers, and
323 let drivers implement hardware-specific operations with their own
324 private API.
325
326 The GEM userspace API is described in the `GEM - the Graphics Execution
327 Manager <http://lwn.net/Articles/283798/>`__ article on LWN. While
328 slightly outdated, the document provides a good overview of the GEM API
329 principles. Buffer allocation and read and write operations, described
330 as part of the common GEM API, are currently implemented using
331 driver-specific ioctls.
332
333 GEM is data-agnostic. It manages abstract buffer objects without knowing
334 what individual buffers contain. APIs that require knowledge of buffer
335 contents or purpose, such as buffer allocation or synchronization
336 primitives, are thus outside of the scope of GEM and must be implemented
337 using driver-specific ioctls.
338
339 On a fundamental level, GEM involves several operations:
340
341 -  Memory allocation and freeing
342 -  Command execution
343 -  Aperture management at command execution time
344
345 Buffer object allocation is relatively straightforward and largely
346 provided by Linux's shmem layer, which provides memory to back each
347 object.
348
349 Device-specific operations, such as command execution, pinning, buffer
350 read & write, mapping, and domain ownership transfers are left to
351 driver-specific ioctls.
352
353 GEM Initialization
354 ^^^^^^^^^^^^^^^^^^
355
356 Drivers that use GEM must set the DRIVER_GEM bit in the struct
357 :c:type:`struct drm_driver <drm_driver>` driver_features
358 field. The DRM core will then automatically initialize the GEM core
359 before calling the load operation. Behind the scene, this will create a
360 DRM Memory Manager object which provides an address space pool for
361 object allocation.
362
363 In a KMS configuration, drivers need to allocate and initialize a
364 command ring buffer following core GEM initialization if required by the
365 hardware. UMA devices usually have what is called a "stolen" memory
366 region, which provides space for the initial framebuffer and large,
367 contiguous memory regions required by the device. This space is
368 typically not managed by GEM, and must be initialized separately into
369 its own DRM MM object.
370
371 GEM Objects Creation
372 ^^^^^^^^^^^^^^^^^^^^
373
374 GEM splits creation of GEM objects and allocation of the memory that
375 backs them in two distinct operations.
376
377 GEM objects are represented by an instance of struct :c:type:`struct
378 drm_gem_object <drm_gem_object>`. Drivers usually need to
379 extend GEM objects with private information and thus create a
380 driver-specific GEM object structure type that embeds an instance of
381 struct :c:type:`struct drm_gem_object <drm_gem_object>`.
382
383 To create a GEM object, a driver allocates memory for an instance of its
384 specific GEM object type and initializes the embedded struct
385 :c:type:`struct drm_gem_object <drm_gem_object>` with a call
386 to :c:func:`drm_gem_object_init()`. The function takes a pointer
387 to the DRM device, a pointer to the GEM object and the buffer object
388 size in bytes.
389
390 GEM uses shmem to allocate anonymous pageable memory.
391 :c:func:`drm_gem_object_init()` will create an shmfs file of the
392 requested size and store it into the struct :c:type:`struct
393 drm_gem_object <drm_gem_object>` filp field. The memory is
394 used as either main storage for the object when the graphics hardware
395 uses system memory directly or as a backing store otherwise.
396
397 Drivers are responsible for the actual physical pages allocation by
398 calling :c:func:`shmem_read_mapping_page_gfp()` for each page.
399 Note that they can decide to allocate pages when initializing the GEM
400 object, or to delay allocation until the memory is needed (for instance
401 when a page fault occurs as a result of a userspace memory access or
402 when the driver needs to start a DMA transfer involving the memory).
403
404 Anonymous pageable memory allocation is not always desired, for instance
405 when the hardware requires physically contiguous system memory as is
406 often the case in embedded devices. Drivers can create GEM objects with
407 no shmfs backing (called private GEM objects) by initializing them with
408 a call to :c:func:`drm_gem_private_object_init()` instead of
409 :c:func:`drm_gem_object_init()`. Storage for private GEM objects
410 must be managed by drivers.
411
412 GEM Objects Lifetime
413 ^^^^^^^^^^^^^^^^^^^^
414
415 All GEM objects are reference-counted by the GEM core. References can be
416 acquired and release by :c:func:`calling
417 drm_gem_object_reference()` and
418 :c:func:`drm_gem_object_unreference()` respectively. The caller
419 must hold the :c:type:`struct drm_device <drm_device>`
420 struct_mutex lock when calling
421 :c:func:`drm_gem_object_reference()`. As a convenience, GEM
422 provides :c:func:`drm_gem_object_unreference_unlocked()`
423 functions that can be called without holding the lock.
424
425 When the last reference to a GEM object is released the GEM core calls
426 the :c:type:`struct drm_driver <drm_driver>` gem_free_object
427 operation. That operation is mandatory for GEM-enabled drivers and must
428 free the GEM object and all associated resources.
429
430 void (\*gem_free_object) (struct drm_gem_object \*obj); Drivers are
431 responsible for freeing all GEM object resources. This includes the
432 resources created by the GEM core, which need to be released with
433 :c:func:`drm_gem_object_release()`.
434
435 GEM Objects Naming
436 ^^^^^^^^^^^^^^^^^^
437
438 Communication between userspace and the kernel refers to GEM objects
439 using local handles, global names or, more recently, file descriptors.
440 All of those are 32-bit integer values; the usual Linux kernel limits
441 apply to the file descriptors.
442
443 GEM handles are local to a DRM file. Applications get a handle to a GEM
444 object through a driver-specific ioctl, and can use that handle to refer
445 to the GEM object in other standard or driver-specific ioctls. Closing a
446 DRM file handle frees all its GEM handles and dereferences the
447 associated GEM objects.
448
449 To create a handle for a GEM object drivers call
450 :c:func:`drm_gem_handle_create()`. The function takes a pointer
451 to the DRM file and the GEM object and returns a locally unique handle.
452 When the handle is no longer needed drivers delete it with a call to
453 :c:func:`drm_gem_handle_delete()`. Finally the GEM object
454 associated with a handle can be retrieved by a call to
455 :c:func:`drm_gem_object_lookup()`.
456
457 Handles don't take ownership of GEM objects, they only take a reference
458 to the object that will be dropped when the handle is destroyed. To
459 avoid leaking GEM objects, drivers must make sure they drop the
460 reference(s) they own (such as the initial reference taken at object
461 creation time) as appropriate, without any special consideration for the
462 handle. For example, in the particular case of combined GEM object and
463 handle creation in the implementation of the dumb_create operation,
464 drivers must drop the initial reference to the GEM object before
465 returning the handle.
466
467 GEM names are similar in purpose to handles but are not local to DRM
468 files. They can be passed between processes to reference a GEM object
469 globally. Names can't be used directly to refer to objects in the DRM
470 API, applications must convert handles to names and names to handles
471 using the DRM_IOCTL_GEM_FLINK and DRM_IOCTL_GEM_OPEN ioctls
472 respectively. The conversion is handled by the DRM core without any
473 driver-specific support.
474
475 GEM also supports buffer sharing with dma-buf file descriptors through
476 PRIME. GEM-based drivers must use the provided helpers functions to
477 implement the exporting and importing correctly. See ?. Since sharing
478 file descriptors is inherently more secure than the easily guessable and
479 global GEM names it is the preferred buffer sharing mechanism. Sharing
480 buffers through GEM names is only supported for legacy userspace.
481 Furthermore PRIME also allows cross-device buffer sharing since it is
482 based on dma-bufs.
483
484 GEM Objects Mapping
485 ^^^^^^^^^^^^^^^^^^^
486
487 Because mapping operations are fairly heavyweight GEM favours
488 read/write-like access to buffers, implemented through driver-specific
489 ioctls, over mapping buffers to userspace. However, when random access
490 to the buffer is needed (to perform software rendering for instance),
491 direct access to the object can be more efficient.
492
493 The mmap system call can't be used directly to map GEM objects, as they
494 don't have their own file handle. Two alternative methods currently
495 co-exist to map GEM objects to userspace. The first method uses a
496 driver-specific ioctl to perform the mapping operation, calling
497 :c:func:`do_mmap()` under the hood. This is often considered
498 dubious, seems to be discouraged for new GEM-enabled drivers, and will
499 thus not be described here.
500
501 The second method uses the mmap system call on the DRM file handle. void
502 \*mmap(void \*addr, size_t length, int prot, int flags, int fd, off_t
503 offset); DRM identifies the GEM object to be mapped by a fake offset
504 passed through the mmap offset argument. Prior to being mapped, a GEM
505 object must thus be associated with a fake offset. To do so, drivers
506 must call :c:func:`drm_gem_create_mmap_offset()` on the object.
507
508 Once allocated, the fake offset value must be passed to the application
509 in a driver-specific way and can then be used as the mmap offset
510 argument.
511
512 The GEM core provides a helper method :c:func:`drm_gem_mmap()` to
513 handle object mapping. The method can be set directly as the mmap file
514 operation handler. It will look up the GEM object based on the offset
515 value and set the VMA operations to the :c:type:`struct drm_driver
516 <drm_driver>` gem_vm_ops field. Note that
517 :c:func:`drm_gem_mmap()` doesn't map memory to userspace, but
518 relies on the driver-provided fault handler to map pages individually.
519
520 To use :c:func:`drm_gem_mmap()`, drivers must fill the struct
521 :c:type:`struct drm_driver <drm_driver>` gem_vm_ops field
522 with a pointer to VM operations.
523
524 struct vm_operations_struct \*gem_vm_ops struct
525 vm_operations_struct { void (\*open)(struct vm_area_struct \* area);
526 void (\*close)(struct vm_area_struct \* area); int (\*fault)(struct
527 vm_area_struct \*vma, struct vm_fault \*vmf); };
528
529 The open and close operations must update the GEM object reference
530 count. Drivers can use the :c:func:`drm_gem_vm_open()` and
531 :c:func:`drm_gem_vm_close()` helper functions directly as open
532 and close handlers.
533
534 The fault operation handler is responsible for mapping individual pages
535 to userspace when a page fault occurs. Depending on the memory
536 allocation scheme, drivers can allocate pages at fault time, or can
537 decide to allocate memory for the GEM object at the time the object is
538 created.
539
540 Drivers that want to map the GEM object upfront instead of handling page
541 faults can implement their own mmap file operation handler.
542
543 Memory Coherency
544 ^^^^^^^^^^^^^^^^
545
546 When mapped to the device or used in a command buffer, backing pages for
547 an object are flushed to memory and marked write combined so as to be
548 coherent with the GPU. Likewise, if the CPU accesses an object after the
549 GPU has finished rendering to the object, then the object must be made
550 coherent with the CPU's view of memory, usually involving GPU cache
551 flushing of various kinds. This core CPU<->GPU coherency management is
552 provided by a device-specific ioctl, which evaluates an object's current
553 domain and performs any necessary flushing or synchronization to put the
554 object into the desired coherency domain (note that the object may be
555 busy, i.e. an active render target; in that case, setting the domain
556 blocks the client and waits for rendering to complete before performing
557 any necessary flushing operations).
558
559 Command Execution
560 ^^^^^^^^^^^^^^^^^
561
562 Perhaps the most important GEM function for GPU devices is providing a
563 command execution interface to clients. Client programs construct
564 command buffers containing references to previously allocated memory
565 objects, and then submit them to GEM. At that point, GEM takes care to
566 bind all the objects into the GTT, execute the buffer, and provide
567 necessary synchronization between clients accessing the same buffers.
568 This often involves evicting some objects from the GTT and re-binding
569 others (a fairly expensive operation), and providing relocation support
570 which hides fixed GTT offsets from clients. Clients must take care not
571 to submit command buffers that reference more objects than can fit in
572 the GTT; otherwise, GEM will reject them and no rendering will occur.
573 Similarly, if several objects in the buffer require fence registers to
574 be allocated for correct rendering (e.g. 2D blits on pre-965 chips),
575 care must be taken not to require more fence registers than are
576 available to the client. Such resource management should be abstracted
577 from the client in libdrm.
578
579 GEM Function Reference
580 ----------------------
581
582 .. kernel-doc:: drivers/gpu/drm/drm_gem.c
583    :export:
584
585 .. kernel-doc:: include/drm/drm_gem.h
586    :internal:
587
588 VMA Offset Manager
589 ------------------
590
591 .. kernel-doc:: drivers/gpu/drm/drm_vma_manager.c
592    :doc: vma offset manager
593
594 .. kernel-doc:: drivers/gpu/drm/drm_vma_manager.c
595    :export:
596
597 .. kernel-doc:: include/drm/drm_vma_manager.h
598    :internal:
599
600 PRIME Buffer Sharing
601 --------------------
602
603 PRIME is the cross device buffer sharing framework in drm, originally
604 created for the OPTIMUS range of multi-gpu platforms. To userspace PRIME
605 buffers are dma-buf based file descriptors.
606
607 Overview and Driver Interface
608 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
609
610 Similar to GEM global names, PRIME file descriptors are also used to
611 share buffer objects across processes. They offer additional security:
612 as file descriptors must be explicitly sent over UNIX domain sockets to
613 be shared between applications, they can't be guessed like the globally
614 unique GEM names.
615
616 Drivers that support the PRIME API must set the DRIVER_PRIME bit in the
617 struct :c:type:`struct drm_driver <drm_driver>`
618 driver_features field, and implement the prime_handle_to_fd and
619 prime_fd_to_handle operations.
620
621 int (\*prime_handle_to_fd)(struct drm_device \*dev, struct drm_file
622 \*file_priv, uint32_t handle, uint32_t flags, int \*prime_fd); int
623 (\*prime_fd_to_handle)(struct drm_device \*dev, struct drm_file
624 \*file_priv, int prime_fd, uint32_t \*handle); Those two operations
625 convert a handle to a PRIME file descriptor and vice versa. Drivers must
626 use the kernel dma-buf buffer sharing framework to manage the PRIME file
627 descriptors. Similar to the mode setting API PRIME is agnostic to the
628 underlying buffer object manager, as long as handles are 32bit unsigned
629 integers.
630
631 While non-GEM drivers must implement the operations themselves, GEM
632 drivers must use the :c:func:`drm_gem_prime_handle_to_fd()` and
633 :c:func:`drm_gem_prime_fd_to_handle()` helper functions. Those
634 helpers rely on the driver gem_prime_export and gem_prime_import
635 operations to create a dma-buf instance from a GEM object (dma-buf
636 exporter role) and to create a GEM object from a dma-buf instance
637 (dma-buf importer role).
638
639 struct dma_buf \* (\*gem_prime_export)(struct drm_device \*dev,
640 struct drm_gem_object \*obj, int flags); struct drm_gem_object \*
641 (\*gem_prime_import)(struct drm_device \*dev, struct dma_buf
642 \*dma_buf); These two operations are mandatory for GEM drivers that
643 support PRIME.
644
645 PRIME Helper Functions
646 ^^^^^^^^^^^^^^^^^^^^^^
647
648 .. kernel-doc:: drivers/gpu/drm/drm_prime.c
649    :doc: PRIME Helpers
650
651 PRIME Function References
652 -------------------------
653
654 .. kernel-doc:: drivers/gpu/drm/drm_prime.c
655    :export:
656
657 DRM MM Range Allocator
658 ----------------------
659
660 Overview
661 ^^^^^^^^
662
663 .. kernel-doc:: drivers/gpu/drm/drm_mm.c
664    :doc: Overview
665
666 LRU Scan/Eviction Support
667 ^^^^^^^^^^^^^^^^^^^^^^^^^
668
669 .. kernel-doc:: drivers/gpu/drm/drm_mm.c
670    :doc: lru scan roaster
671
672 DRM MM Range Allocator Function References
673 ------------------------------------------
674
675 .. kernel-doc:: drivers/gpu/drm/drm_mm.c
676    :export:
677
678 .. kernel-doc:: include/drm/drm_mm.h
679    :internal:
680
681 CMA Helper Functions Reference
682 ------------------------------
683
684 .. kernel-doc:: drivers/gpu/drm/drm_gem_cma_helper.c
685    :doc: cma helpers
686
687 .. kernel-doc:: drivers/gpu/drm/drm_gem_cma_helper.c
688    :export:
689
690 .. kernel-doc:: include/drm/drm_gem_cma_helper.h
691    :internal:
692
693 Mode Setting
694 ============
695
696 Drivers must initialize the mode setting core by calling
697 :c:func:`drm_mode_config_init()` on the DRM device. The function
698 initializes the :c:type:`struct drm_device <drm_device>`
699 mode_config field and never fails. Once done, mode configuration must
700 be setup by initializing the following fields.
701
702 -  int min_width, min_height; int max_width, max_height;
703    Minimum and maximum width and height of the frame buffers in pixel
704    units.
705
706 -  struct drm_mode_config_funcs \*funcs;
707    Mode setting functions.
708
709 Display Modes Function Reference
710 --------------------------------
711
712 .. kernel-doc:: include/drm/drm_modes.h
713    :internal:
714
715 .. kernel-doc:: drivers/gpu/drm/drm_modes.c
716    :export:
717
718 Atomic Mode Setting Function Reference
719 --------------------------------------
720
721 .. kernel-doc:: drivers/gpu/drm/drm_atomic.c
722    :export:
723
724 .. kernel-doc:: drivers/gpu/drm/drm_atomic.c
725    :internal:
726
727 Frame Buffer Abstraction
728 ------------------------
729
730 Frame buffers are abstract memory objects that provide a source of
731 pixels to scanout to a CRTC. Applications explicitly request the
732 creation of frame buffers through the DRM_IOCTL_MODE_ADDFB(2) ioctls
733 and receive an opaque handle that can be passed to the KMS CRTC control,
734 plane configuration and page flip functions.
735
736 Frame buffers rely on the underneath memory manager for low-level memory
737 operations. When creating a frame buffer applications pass a memory
738 handle (or a list of memory handles for multi-planar formats) through
739 the ``drm_mode_fb_cmd2`` argument. For drivers using GEM as their
740 userspace buffer management interface this would be a GEM handle.
741 Drivers are however free to use their own backing storage object
742 handles, e.g. vmwgfx directly exposes special TTM handles to userspace
743 and so expects TTM handles in the create ioctl and not GEM handles.
744
745 The lifetime of a drm framebuffer is controlled with a reference count,
746 drivers can grab additional references with
747 :c:func:`drm_framebuffer_reference()`and drop them again with
748 :c:func:`drm_framebuffer_unreference()`. For driver-private
749 framebuffers for which the last reference is never dropped (e.g. for the
750 fbdev framebuffer when the struct :c:type:`struct drm_framebuffer
751 <drm_framebuffer>` is embedded into the fbdev helper struct)
752 drivers can manually clean up a framebuffer at module unload time with
753 :c:func:`drm_framebuffer_unregister_private()`.
754
755 DRM Format Handling
756 -------------------
757
758 .. kernel-doc:: include/drm/drm_fourcc.h
759    :internal:
760
761 .. kernel-doc:: drivers/gpu/drm/drm_fourcc.c
762    :export:
763
764 Dumb Buffer Objects
765 -------------------
766
767 The KMS API doesn't standardize backing storage object creation and
768 leaves it to driver-specific ioctls. Furthermore actually creating a
769 buffer object even for GEM-based drivers is done through a
770 driver-specific ioctl - GEM only has a common userspace interface for
771 sharing and destroying objects. While not an issue for full-fledged
772 graphics stacks that include device-specific userspace components (in
773 libdrm for instance), this limit makes DRM-based early boot graphics
774 unnecessarily complex.
775
776 Dumb objects partly alleviate the problem by providing a standard API to
777 create dumb buffers suitable for scanout, which can then be used to
778 create KMS frame buffers.
779
780 To support dumb objects drivers must implement the dumb_create,
781 dumb_destroy and dumb_map_offset operations.
782
783 -  int (\*dumb_create)(struct drm_file \*file_priv, struct
784    drm_device \*dev, struct drm_mode_create_dumb \*args);
785    The dumb_create operation creates a driver object (GEM or TTM
786    handle) suitable for scanout based on the width, height and depth
787    from the struct :c:type:`struct drm_mode_create_dumb
788    <drm_mode_create_dumb>` argument. It fills the argument's
789    handle, pitch and size fields with a handle for the newly created
790    object and its line pitch and size in bytes.
791
792 -  int (\*dumb_destroy)(struct drm_file \*file_priv, struct
793    drm_device \*dev, uint32_t handle);
794    The dumb_destroy operation destroys a dumb object created by
795    dumb_create.
796
797 -  int (\*dumb_map_offset)(struct drm_file \*file_priv, struct
798    drm_device \*dev, uint32_t handle, uint64_t \*offset);
799    The dumb_map_offset operation associates an mmap fake offset with
800    the object given by the handle and returns it. Drivers must use the
801    :c:func:`drm_gem_create_mmap_offset()` function to associate
802    the fake offset as described in ?.
803
804 Note that dumb objects may not be used for gpu acceleration, as has been
805 attempted on some ARM embedded platforms. Such drivers really must have
806 a hardware-specific ioctl to allocate suitable buffer objects.
807
808 Output Polling
809 --------------
810
811 void (\*output_poll_changed)(struct drm_device \*dev);
812 This operation notifies the driver that the status of one or more
813 connectors has changed. Drivers that use the fb helper can just call the
814 :c:func:`drm_fb_helper_hotplug_event()` function to handle this
815 operation.
816
817 KMS Initialization and Cleanup
818 ==============================
819
820 A KMS device is abstracted and exposed as a set of planes, CRTCs,
821 encoders and connectors. KMS drivers must thus create and initialize all
822 those objects at load time after initializing mode setting.
823
824 CRTCs (:c:type:`struct drm_crtc <drm_crtc>`)
825 --------------------------------------------
826
827 A CRTC is an abstraction representing a part of the chip that contains a
828 pointer to a scanout buffer. Therefore, the number of CRTCs available
829 determines how many independent scanout buffers can be active at any
830 given time. The CRTC structure contains several fields to support this:
831 a pointer to some video memory (abstracted as a frame buffer object), a
832 display mode, and an (x, y) offset into the video memory to support
833 panning or configurations where one piece of video memory spans multiple
834 CRTCs.
835
836 CRTC Initialization
837 ^^^^^^^^^^^^^^^^^^^
838
839 A KMS device must create and register at least one struct
840 :c:type:`struct drm_crtc <drm_crtc>` instance. The instance is
841 allocated and zeroed by the driver, possibly as part of a larger
842 structure, and registered with a call to :c:func:`drm_crtc_init()`
843 with a pointer to CRTC functions.
844
845 Planes (:c:type:`struct drm_plane <drm_plane>`)
846 -----------------------------------------------
847
848 A plane represents an image source that can be blended with or overlayed
849 on top of a CRTC during the scanout process. Planes are associated with
850 a frame buffer to crop a portion of the image memory (source) and
851 optionally scale it to a destination size. The result is then blended
852 with or overlayed on top of a CRTC.
853
854 The DRM core recognizes three types of planes:
855
856 -  DRM_PLANE_TYPE_PRIMARY represents a "main" plane for a CRTC.
857    Primary planes are the planes operated upon by CRTC modesetting and
858    flipping operations described in the page_flip hook in
859    :c:type:`struct drm_crtc_funcs <drm_crtc_funcs>`.
860 -  DRM_PLANE_TYPE_CURSOR represents a "cursor" plane for a CRTC.
861    Cursor planes are the planes operated upon by the
862    DRM_IOCTL_MODE_CURSOR and DRM_IOCTL_MODE_CURSOR2 ioctls.
863 -  DRM_PLANE_TYPE_OVERLAY represents all non-primary, non-cursor
864    planes. Some drivers refer to these types of planes as "sprites"
865    internally.
866
867 For compatibility with legacy userspace, only overlay planes are made
868 available to userspace by default. Userspace clients may set the
869 DRM_CLIENT_CAP_UNIVERSAL_PLANES client capability bit to indicate
870 that they wish to receive a universal plane list containing all plane
871 types.
872
873 Plane Initialization
874 ^^^^^^^^^^^^^^^^^^^^
875
876 To create a plane, a KMS drivers allocates and zeroes an instances of
877 :c:type:`struct drm_plane <drm_plane>` (possibly as part of a
878 larger structure) and registers it with a call to
879 :c:func:`drm_universal_plane_init()`. The function takes a
880 bitmask of the CRTCs that can be associated with the plane, a pointer to
881 the plane functions, a list of format supported formats, and the type of
882 plane (primary, cursor, or overlay) being initialized.
883
884 Cursor and overlay planes are optional. All drivers should provide one
885 primary plane per CRTC (although this requirement may change in the
886 future); drivers that do not wish to provide special handling for
887 primary planes may make use of the helper functions described in ? to
888 create and register a primary plane with standard capabilities.
889
890 Encoders (:c:type:`struct drm_encoder <drm_encoder>`)
891 -----------------------------------------------------
892
893 An encoder takes pixel data from a CRTC and converts it to a format
894 suitable for any attached connectors. On some devices, it may be
895 possible to have a CRTC send data to more than one encoder. In that
896 case, both encoders would receive data from the same scanout buffer,
897 resulting in a "cloned" display configuration across the connectors
898 attached to each encoder.
899
900 Encoder Initialization
901 ^^^^^^^^^^^^^^^^^^^^^^
902
903 As for CRTCs, a KMS driver must create, initialize and register at least
904 one :c:type:`struct drm_encoder <drm_encoder>` instance. The
905 instance is allocated and zeroed by the driver, possibly as part of a
906 larger structure.
907
908 Drivers must initialize the :c:type:`struct drm_encoder
909 <drm_encoder>` possible_crtcs and possible_clones fields before
910 registering the encoder. Both fields are bitmasks of respectively the
911 CRTCs that the encoder can be connected to, and sibling encoders
912 candidate for cloning.
913
914 After being initialized, the encoder must be registered with a call to
915 :c:func:`drm_encoder_init()`. The function takes a pointer to the
916 encoder functions and an encoder type. Supported types are
917
918 -  DRM_MODE_ENCODER_DAC for VGA and analog on DVI-I/DVI-A
919 -  DRM_MODE_ENCODER_TMDS for DVI, HDMI and (embedded) DisplayPort
920 -  DRM_MODE_ENCODER_LVDS for display panels
921 -  DRM_MODE_ENCODER_TVDAC for TV output (Composite, S-Video,
922    Component, SCART)
923 -  DRM_MODE_ENCODER_VIRTUAL for virtual machine displays
924
925 Encoders must be attached to a CRTC to be used. DRM drivers leave
926 encoders unattached at initialization time. Applications (or the fbdev
927 compatibility layer when implemented) are responsible for attaching the
928 encoders they want to use to a CRTC.
929
930 Connectors (:c:type:`struct drm_connector <drm_connector>`)
931 -----------------------------------------------------------
932
933 A connector is the final destination for pixel data on a device, and
934 usually connects directly to an external display device like a monitor
935 or laptop panel. A connector can only be attached to one encoder at a
936 time. The connector is also the structure where information about the
937 attached display is kept, so it contains fields for display data, EDID
938 data, DPMS & connection status, and information about modes supported on
939 the attached displays.
940
941 Connector Initialization
942 ^^^^^^^^^^^^^^^^^^^^^^^^
943
944 Finally a KMS driver must create, initialize, register and attach at
945 least one :c:type:`struct drm_connector <drm_connector>`
946 instance. The instance is created as other KMS objects and initialized
947 by setting the following fields.
948
949 interlace_allowed
950     Whether the connector can handle interlaced modes.
951
952 doublescan_allowed
953     Whether the connector can handle doublescan.
954
955 display_info
956     Display information is filled from EDID information when a display
957     is detected. For non hot-pluggable displays such as flat panels in
958     embedded systems, the driver should initialize the
959     display_info.width_mm and display_info.height_mm fields with the
960     physical size of the display.
961
962 polled
963     Connector polling mode, a combination of
964
965     DRM_CONNECTOR_POLL_HPD
966         The connector generates hotplug events and doesn't need to be
967         periodically polled. The CONNECT and DISCONNECT flags must not
968         be set together with the HPD flag.
969
970     DRM_CONNECTOR_POLL_CONNECT
971         Periodically poll the connector for connection.
972
973     DRM_CONNECTOR_POLL_DISCONNECT
974         Periodically poll the connector for disconnection.
975
976     Set to 0 for connectors that don't support connection status
977     discovery.
978
979 The connector is then registered with a call to
980 :c:func:`drm_connector_init()` with a pointer to the connector
981 functions and a connector type, and exposed through sysfs with a call to
982 :c:func:`drm_connector_register()`.
983
984 Supported connector types are
985
986 -  DRM_MODE_CONNECTOR_VGA
987 -  DRM_MODE_CONNECTOR_DVII
988 -  DRM_MODE_CONNECTOR_DVID
989 -  DRM_MODE_CONNECTOR_DVIA
990 -  DRM_MODE_CONNECTOR_Composite
991 -  DRM_MODE_CONNECTOR_SVIDEO
992 -  DRM_MODE_CONNECTOR_LVDS
993 -  DRM_MODE_CONNECTOR_Component
994 -  DRM_MODE_CONNECTOR_9PinDIN
995 -  DRM_MODE_CONNECTOR_DisplayPort
996 -  DRM_MODE_CONNECTOR_HDMIA
997 -  DRM_MODE_CONNECTOR_HDMIB
998 -  DRM_MODE_CONNECTOR_TV
999 -  DRM_MODE_CONNECTOR_eDP
1000 -  DRM_MODE_CONNECTOR_VIRTUAL
1001
1002 Connectors must be attached to an encoder to be used. For devices that
1003 map connectors to encoders 1:1, the connector should be attached at
1004 initialization time with a call to
1005 :c:func:`drm_mode_connector_attach_encoder()`. The driver must
1006 also set the :c:type:`struct drm_connector <drm_connector>`
1007 encoder field to point to the attached encoder.
1008
1009 Finally, drivers must initialize the connectors state change detection
1010 with a call to :c:func:`drm_kms_helper_poll_init()`. If at least
1011 one connector is pollable but can't generate hotplug interrupts
1012 (indicated by the DRM_CONNECTOR_POLL_CONNECT and
1013 DRM_CONNECTOR_POLL_DISCONNECT connector flags), a delayed work will
1014 automatically be queued to periodically poll for changes. Connectors
1015 that can generate hotplug interrupts must be marked with the
1016 DRM_CONNECTOR_POLL_HPD flag instead, and their interrupt handler must
1017 call :c:func:`drm_helper_hpd_irq_event()`. The function will
1018 queue a delayed work to check the state of all connectors, but no
1019 periodic polling will be done.
1020
1021 Connector Operations
1022 ^^^^^^^^^^^^^^^^^^^^
1023
1024     **Note**
1025
1026     Unless otherwise state, all operations are mandatory.
1027
1028 DPMS
1029 ''''
1030
1031 void (\*dpms)(struct drm_connector \*connector, int mode);
1032 The DPMS operation sets the power state of a connector. The mode
1033 argument is one of
1034
1035 -  DRM_MODE_DPMS_ON
1036
1037 -  DRM_MODE_DPMS_STANDBY
1038
1039 -  DRM_MODE_DPMS_SUSPEND
1040
1041 -  DRM_MODE_DPMS_OFF
1042
1043 In all but DPMS_ON mode the encoder to which the connector is attached
1044 should put the display in low-power mode by driving its signals
1045 appropriately. If more than one connector is attached to the encoder
1046 care should be taken not to change the power state of other displays as
1047 a side effect. Low-power mode should be propagated to the encoders and
1048 CRTCs when all related connectors are put in low-power mode.
1049
1050 Modes
1051 '''''
1052
1053 int (\*fill_modes)(struct drm_connector \*connector, uint32_t
1054 max_width, uint32_t max_height);
1055 Fill the mode list with all supported modes for the connector. If the
1056 ``max_width`` and ``max_height`` arguments are non-zero, the
1057 implementation must ignore all modes wider than ``max_width`` or higher
1058 than ``max_height``.
1059
1060 The connector must also fill in this operation its display_info
1061 width_mm and height_mm fields with the connected display physical size
1062 in millimeters. The fields should be set to 0 if the value isn't known
1063 or is not applicable (for instance for projector devices).
1064
1065 Connection Status
1066 '''''''''''''''''
1067
1068 The connection status is updated through polling or hotplug events when
1069 supported (see ?). The status value is reported to userspace through
1070 ioctls and must not be used inside the driver, as it only gets
1071 initialized by a call to :c:func:`drm_mode_getconnector()` from
1072 userspace.
1073
1074 enum drm_connector_status (\*detect)(struct drm_connector
1075 \*connector, bool force);
1076 Check to see if anything is attached to the connector. The ``force``
1077 parameter is set to false whilst polling or to true when checking the
1078 connector due to user request. ``force`` can be used by the driver to
1079 avoid expensive, destructive operations during automated probing.
1080
1081 Return connector_status_connected if something is connected to the
1082 connector, connector_status_disconnected if nothing is connected and
1083 connector_status_unknown if the connection state isn't known.
1084
1085 Drivers should only return connector_status_connected if the
1086 connection status has really been probed as connected. Connectors that
1087 can't detect the connection status, or failed connection status probes,
1088 should return connector_status_unknown.
1089
1090 Cleanup
1091 -------
1092
1093 The DRM core manages its objects' lifetime. When an object is not needed
1094 anymore the core calls its destroy function, which must clean up and
1095 free every resource allocated for the object. Every
1096 :c:func:`drm_\*_init()` call must be matched with a corresponding
1097 :c:func:`drm_\*_cleanup()` call to cleanup CRTCs
1098 (:c:func:`drm_crtc_cleanup()`), planes
1099 (:c:func:`drm_plane_cleanup()`), encoders
1100 (:c:func:`drm_encoder_cleanup()`) and connectors
1101 (:c:func:`drm_connector_cleanup()`). Furthermore, connectors that
1102 have been added to sysfs must be removed by a call to
1103 :c:func:`drm_connector_unregister()` before calling
1104 :c:func:`drm_connector_cleanup()`.
1105
1106 Connectors state change detection must be cleanup up with a call to
1107 :c:func:`drm_kms_helper_poll_fini()`.
1108
1109 Output discovery and initialization example
1110 -------------------------------------------
1111
1112 ::
1113
1114     void intel_crt_init(struct drm_device *dev)
1115     {
1116         struct drm_connector *connector;
1117         struct intel_output *intel_output;
1118
1119         intel_output = kzalloc(sizeof(struct intel_output), GFP_KERNEL);
1120         if (!intel_output)
1121             return;
1122
1123         connector = &intel_output->base;
1124         drm_connector_init(dev, &intel_output->base,
1125                    &intel_crt_connector_funcs, DRM_MODE_CONNECTOR_VGA);
1126
1127         drm_encoder_init(dev, &intel_output->enc, &intel_crt_enc_funcs,
1128                  DRM_MODE_ENCODER_DAC);
1129
1130         drm_mode_connector_attach_encoder(&intel_output->base,
1131                           &intel_output->enc);
1132
1133         /* Set up the DDC bus. */
1134         intel_output->ddc_bus = intel_i2c_create(dev, GPIOA, "CRTDDC_A");
1135         if (!intel_output->ddc_bus) {
1136             dev_printk(KERN_ERR, &dev->pdev->dev, "DDC bus registration "
1137                    "failed.\n");
1138             return;
1139         }
1140
1141         intel_output->type = INTEL_OUTPUT_ANALOG;
1142         connector->interlace_allowed = 0;
1143         connector->doublescan_allowed = 0;
1144
1145         drm_encoder_helper_add(&intel_output->enc, &intel_crt_helper_funcs);
1146         drm_connector_helper_add(connector, &intel_crt_connector_helper_funcs);
1147
1148         drm_connector_register(connector);
1149     }
1150
1151 In the example above (taken from the i915 driver), a CRTC, connector and
1152 encoder combination is created. A device-specific i2c bus is also
1153 created for fetching EDID data and performing monitor detection. Once
1154 the process is complete, the new connector is registered with sysfs to
1155 make its properties available to applications.
1156
1157 KMS API Functions
1158 -----------------
1159
1160 .. kernel-doc:: drivers/gpu/drm/drm_crtc.c
1161    :export:
1162
1163 KMS Data Structures
1164 -------------------
1165
1166 .. kernel-doc:: include/drm/drm_crtc.h
1167    :internal:
1168
1169 KMS Locking
1170 -----------
1171
1172 .. kernel-doc:: drivers/gpu/drm/drm_modeset_lock.c
1173    :doc: kms locking
1174
1175 .. kernel-doc:: include/drm/drm_modeset_lock.h
1176    :internal:
1177
1178 .. kernel-doc:: drivers/gpu/drm/drm_modeset_lock.c
1179    :export:
1180
1181 Mode Setting Helper Functions
1182 =============================
1183
1184 The plane, CRTC, encoder and connector functions provided by the drivers
1185 implement the DRM API. They're called by the DRM core and ioctl handlers
1186 to handle device state changes and configuration request. As
1187 implementing those functions often requires logic not specific to
1188 drivers, mid-layer helper functions are available to avoid duplicating
1189 boilerplate code.
1190
1191 The DRM core contains one mid-layer implementation. The mid-layer
1192 provides implementations of several plane, CRTC, encoder and connector
1193 functions (called from the top of the mid-layer) that pre-process
1194 requests and call lower-level functions provided by the driver (at the
1195 bottom of the mid-layer). For instance, the
1196 :c:func:`drm_crtc_helper_set_config()` function can be used to
1197 fill the :c:type:`struct drm_crtc_funcs <drm_crtc_funcs>`
1198 set_config field. When called, it will split the set_config operation
1199 in smaller, simpler operations and call the driver to handle them.
1200
1201 To use the mid-layer, drivers call
1202 :c:func:`drm_crtc_helper_add()`,
1203 :c:func:`drm_encoder_helper_add()` and
1204 :c:func:`drm_connector_helper_add()` functions to install their
1205 mid-layer bottom operations handlers, and fill the :c:type:`struct
1206 drm_crtc_funcs <drm_crtc_funcs>`, :c:type:`struct
1207 drm_encoder_funcs <drm_encoder_funcs>` and :c:type:`struct
1208 drm_connector_funcs <drm_connector_funcs>` structures with
1209 pointers to the mid-layer top API functions. Installing the mid-layer
1210 bottom operation handlers is best done right after registering the
1211 corresponding KMS object.
1212
1213 The mid-layer is not split between CRTC, encoder and connector
1214 operations. To use it, a driver must provide bottom functions for all of
1215 the three KMS entities.
1216
1217 Atomic Modeset Helper Functions Reference
1218 -----------------------------------------
1219
1220 Overview
1221 ^^^^^^^^
1222
1223 .. kernel-doc:: drivers/gpu/drm/drm_atomic_helper.c
1224    :doc: overview
1225
1226 Implementing Asynchronous Atomic Commit
1227 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1228
1229 .. kernel-doc:: drivers/gpu/drm/drm_atomic_helper.c
1230    :doc: implementing nonblocking commit
1231
1232 Atomic State Reset and Initialization
1233 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1234
1235 .. kernel-doc:: drivers/gpu/drm/drm_atomic_helper.c
1236    :doc: atomic state reset and initialization
1237
1238 .. kernel-doc:: include/drm/drm_atomic_helper.h
1239    :internal:
1240
1241 .. kernel-doc:: drivers/gpu/drm/drm_atomic_helper.c
1242    :export:
1243
1244 Modeset Helper Reference for Common Vtables
1245 -------------------------------------------
1246
1247 .. kernel-doc:: include/drm/drm_modeset_helper_vtables.h
1248    :internal:
1249
1250 .. kernel-doc:: include/drm/drm_modeset_helper_vtables.h
1251    :doc: overview
1252
1253 Legacy CRTC/Modeset Helper Functions Reference
1254 ----------------------------------------------
1255
1256 .. kernel-doc:: drivers/gpu/drm/drm_crtc_helper.c
1257    :export:
1258
1259 .. kernel-doc:: drivers/gpu/drm/drm_crtc_helper.c
1260    :doc: overview
1261
1262 Output Probing Helper Functions Reference
1263 -----------------------------------------
1264
1265 .. kernel-doc:: drivers/gpu/drm/drm_probe_helper.c
1266    :doc: output probing helper overview
1267
1268 .. kernel-doc:: drivers/gpu/drm/drm_probe_helper.c
1269    :export:
1270
1271 fbdev Helper Functions Reference
1272 --------------------------------
1273
1274 .. kernel-doc:: drivers/gpu/drm/drm_fb_helper.c
1275    :doc: fbdev helpers
1276
1277 .. kernel-doc:: drivers/gpu/drm/drm_fb_helper.c
1278    :export:
1279
1280 .. kernel-doc:: include/drm/drm_fb_helper.h
1281    :internal:
1282
1283 Framebuffer CMA Helper Functions Reference
1284 ------------------------------------------
1285
1286 .. kernel-doc:: drivers/gpu/drm/drm_fb_cma_helper.c
1287    :doc: framebuffer cma helper functions
1288
1289 .. kernel-doc:: drivers/gpu/drm/drm_fb_cma_helper.c
1290    :export:
1291
1292 Display Port Helper Functions Reference
1293 ---------------------------------------
1294
1295 .. kernel-doc:: drivers/gpu/drm/drm_dp_helper.c
1296    :doc: dp helpers
1297
1298 .. kernel-doc:: include/drm/drm_dp_helper.h
1299    :internal:
1300
1301 .. kernel-doc:: drivers/gpu/drm/drm_dp_helper.c
1302    :export:
1303
1304 Display Port Dual Mode Adaptor Helper Functions Reference
1305 ---------------------------------------------------------
1306
1307 .. kernel-doc:: drivers/gpu/drm/drm_dp_dual_mode_helper.c
1308    :doc: dp dual mode helpers
1309
1310 .. kernel-doc:: include/drm/drm_dp_dual_mode_helper.h
1311    :internal:
1312
1313 .. kernel-doc:: drivers/gpu/drm/drm_dp_dual_mode_helper.c
1314    :export:
1315
1316 Display Port MST Helper Functions Reference
1317 -------------------------------------------
1318
1319 .. kernel-doc:: drivers/gpu/drm/drm_dp_mst_topology.c
1320    :doc: dp mst helper
1321
1322 .. kernel-doc:: include/drm/drm_dp_mst_helper.h
1323    :internal:
1324
1325 .. kernel-doc:: drivers/gpu/drm/drm_dp_mst_topology.c
1326    :export:
1327
1328 MIPI DSI Helper Functions Reference
1329 -----------------------------------
1330
1331 .. kernel-doc:: drivers/gpu/drm/drm_mipi_dsi.c
1332    :doc: dsi helpers
1333
1334 .. kernel-doc:: include/drm/drm_mipi_dsi.h
1335    :internal:
1336
1337 .. kernel-doc:: drivers/gpu/drm/drm_mipi_dsi.c
1338    :export:
1339
1340 EDID Helper Functions Reference
1341 -------------------------------
1342
1343 .. kernel-doc:: drivers/gpu/drm/drm_edid.c
1344    :export:
1345
1346 Rectangle Utilities Reference
1347 -----------------------------
1348
1349 .. kernel-doc:: include/drm/drm_rect.h
1350    :doc: rect utils
1351
1352 .. kernel-doc:: include/drm/drm_rect.h
1353    :internal:
1354
1355 .. kernel-doc:: drivers/gpu/drm/drm_rect.c
1356    :export:
1357
1358 Flip-work Helper Reference
1359 --------------------------
1360
1361 .. kernel-doc:: include/drm/drm_flip_work.h
1362    :doc: flip utils
1363
1364 .. kernel-doc:: include/drm/drm_flip_work.h
1365    :internal:
1366
1367 .. kernel-doc:: drivers/gpu/drm/drm_flip_work.c
1368    :export:
1369
1370 HDMI Infoframes Helper Reference
1371 --------------------------------
1372
1373 Strictly speaking this is not a DRM helper library but generally useable
1374 by any driver interfacing with HDMI outputs like v4l or alsa drivers.
1375 But it nicely fits into the overall topic of mode setting helper
1376 libraries and hence is also included here.
1377
1378 .. kernel-doc:: include/linux/hdmi.h
1379    :internal:
1380
1381 .. kernel-doc:: drivers/video/hdmi.c
1382    :export:
1383
1384 Plane Helper Reference
1385 ----------------------
1386
1387 .. kernel-doc:: drivers/gpu/drm/drm_plane_helper.c
1388    :export:
1389
1390 .. kernel-doc:: drivers/gpu/drm/drm_plane_helper.c
1391    :doc: overview
1392
1393 Tile group
1394 ----------
1395
1396 .. kernel-doc:: drivers/gpu/drm/drm_crtc.c
1397    :doc: Tile group
1398
1399 Bridges
1400 -------
1401
1402 Overview
1403 ^^^^^^^^
1404
1405 .. kernel-doc:: drivers/gpu/drm/drm_bridge.c
1406    :doc: overview
1407
1408 Default bridge callback sequence
1409 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1410
1411 .. kernel-doc:: drivers/gpu/drm/drm_bridge.c
1412    :doc: bridge callbacks
1413
1414 .. kernel-doc:: drivers/gpu/drm/drm_bridge.c
1415    :export:
1416
1417 Panel Helper Reference
1418 ----------------------
1419
1420 .. kernel-doc:: include/drm/drm_panel.h
1421    :internal:
1422
1423 .. kernel-doc:: drivers/gpu/drm/drm_panel.c
1424    :export:
1425
1426 .. kernel-doc:: drivers/gpu/drm/drm_panel.c
1427    :doc: drm panel
1428
1429 Simple KMS Helper Reference
1430 ---------------------------
1431
1432 .. kernel-doc:: include/drm/drm_simple_kms_helper.h
1433    :internal:
1434
1435 .. kernel-doc:: drivers/gpu/drm/drm_simple_kms_helper.c
1436    :export:
1437
1438 .. kernel-doc:: drivers/gpu/drm/drm_simple_kms_helper.c
1439    :doc: overview
1440
1441 KMS Properties
1442 ==============
1443
1444 Drivers may need to expose additional parameters to applications than
1445 those described in the previous sections. KMS supports attaching
1446 properties to CRTCs, connectors and planes and offers a userspace API to
1447 list, get and set the property values.
1448
1449 Properties are identified by a name that uniquely defines the property
1450 purpose, and store an associated value. For all property types except
1451 blob properties the value is a 64-bit unsigned integer.
1452
1453 KMS differentiates between properties and property instances. Drivers
1454 first create properties and then create and associate individual
1455 instances of those properties to objects. A property can be instantiated
1456 multiple times and associated with different objects. Values are stored
1457 in property instances, and all other property information are stored in
1458 the property and shared between all instances of the property.
1459
1460 Every property is created with a type that influences how the KMS core
1461 handles the property. Supported property types are
1462
1463 DRM_MODE_PROP_RANGE
1464     Range properties report their minimum and maximum admissible values.
1465     The KMS core verifies that values set by application fit in that
1466     range.
1467
1468 DRM_MODE_PROP_ENUM
1469     Enumerated properties take a numerical value that ranges from 0 to
1470     the number of enumerated values defined by the property minus one,
1471     and associate a free-formed string name to each value. Applications
1472     can retrieve the list of defined value-name pairs and use the
1473     numerical value to get and set property instance values.
1474
1475 DRM_MODE_PROP_BITMASK
1476     Bitmask properties are enumeration properties that additionally
1477     restrict all enumerated values to the 0..63 range. Bitmask property
1478     instance values combine one or more of the enumerated bits defined
1479     by the property.
1480
1481 DRM_MODE_PROP_BLOB
1482     Blob properties store a binary blob without any format restriction.
1483     The binary blobs are created as KMS standalone objects, and blob
1484     property instance values store the ID of their associated blob
1485     object.
1486
1487     Blob properties are only used for the connector EDID property and
1488     cannot be created by drivers.
1489
1490 To create a property drivers call one of the following functions
1491 depending on the property type. All property creation functions take
1492 property flags and name, as well as type-specific arguments.
1493
1494 -  struct drm_property \*drm_property_create_range(struct
1495    drm_device \*dev, int flags, const char \*name, uint64_t min,
1496    uint64_t max);
1497    Create a range property with the given minimum and maximum values.
1498
1499 -  struct drm_property \*drm_property_create_enum(struct drm_device
1500    \*dev, int flags, const char \*name, const struct
1501    drm_prop_enum_list \*props, int num_values);
1502    Create an enumerated property. The ``props`` argument points to an
1503    array of ``num_values`` value-name pairs.
1504
1505 -  struct drm_property \*drm_property_create_bitmask(struct
1506    drm_device \*dev, int flags, const char \*name, const struct
1507    drm_prop_enum_list \*props, int num_values);
1508    Create a bitmask property. The ``props`` argument points to an array
1509    of ``num_values`` value-name pairs.
1510
1511 Properties can additionally be created as immutable, in which case they
1512 will be read-only for applications but can be modified by the driver. To
1513 create an immutable property drivers must set the
1514 DRM_MODE_PROP_IMMUTABLE flag at property creation time.
1515
1516 When no array of value-name pairs is readily available at property
1517 creation time for enumerated or range properties, drivers can create the
1518 property using the :c:func:`drm_property_create()` function and
1519 manually add enumeration value-name pairs by calling the
1520 :c:func:`drm_property_add_enum()` function. Care must be taken to
1521 properly specify the property type through the ``flags`` argument.
1522
1523 After creating properties drivers can attach property instances to CRTC,
1524 connector and plane objects by calling the
1525 :c:func:`drm_object_attach_property()`. The function takes a
1526 pointer to the target object, a pointer to the previously created
1527 property and an initial instance value.
1528
1529 Existing KMS Properties
1530 -----------------------
1531
1532 The following table gives description of drm properties exposed by
1533 various modules/drivers.
1534
1535 .. csv-table::
1536    :header-rows: 1
1537    :file: kms-properties.csv
1538
1539 Vertical Blanking
1540 =================
1541
1542 Vertical blanking plays a major role in graphics rendering. To achieve
1543 tear-free display, users must synchronize page flips and/or rendering to
1544 vertical blanking. The DRM API offers ioctls to perform page flips
1545 synchronized to vertical blanking and wait for vertical blanking.
1546
1547 The DRM core handles most of the vertical blanking management logic,
1548 which involves filtering out spurious interrupts, keeping race-free
1549 blanking counters, coping with counter wrap-around and resets and
1550 keeping use counts. It relies on the driver to generate vertical
1551 blanking interrupts and optionally provide a hardware vertical blanking
1552 counter. Drivers must implement the following operations.
1553
1554 -  int (\*enable_vblank) (struct drm_device \*dev, int crtc); void
1555    (\*disable_vblank) (struct drm_device \*dev, int crtc);
1556    Enable or disable vertical blanking interrupts for the given CRTC.
1557
1558 -  u32 (\*get_vblank_counter) (struct drm_device \*dev, int crtc);
1559    Retrieve the value of the vertical blanking counter for the given
1560    CRTC. If the hardware maintains a vertical blanking counter its value
1561    should be returned. Otherwise drivers can use the
1562    :c:func:`drm_vblank_count()` helper function to handle this
1563    operation.
1564
1565 Drivers must initialize the vertical blanking handling core with a call
1566 to :c:func:`drm_vblank_init()` in their load operation.
1567
1568 Vertical blanking interrupts can be enabled by the DRM core or by
1569 drivers themselves (for instance to handle page flipping operations).
1570 The DRM core maintains a vertical blanking use count to ensure that the
1571 interrupts are not disabled while a user still needs them. To increment
1572 the use count, drivers call :c:func:`drm_vblank_get()`. Upon
1573 return vertical blanking interrupts are guaranteed to be enabled.
1574
1575 To decrement the use count drivers call
1576 :c:func:`drm_vblank_put()`. Only when the use count drops to zero
1577 will the DRM core disable the vertical blanking interrupts after a delay
1578 by scheduling a timer. The delay is accessible through the
1579 vblankoffdelay module parameter or the ``drm_vblank_offdelay`` global
1580 variable and expressed in milliseconds. Its default value is 5000 ms.
1581 Zero means never disable, and a negative value means disable
1582 immediately. Drivers may override the behaviour by setting the
1583 :c:type:`struct drm_device <drm_device>`
1584 vblank_disable_immediate flag, which when set causes vblank interrupts
1585 to be disabled immediately regardless of the drm_vblank_offdelay
1586 value. The flag should only be set if there's a properly working
1587 hardware vblank counter present.
1588
1589 When a vertical blanking interrupt occurs drivers only need to call the
1590 :c:func:`drm_handle_vblank()` function to account for the
1591 interrupt.
1592
1593 Resources allocated by :c:func:`drm_vblank_init()` must be freed
1594 with a call to :c:func:`drm_vblank_cleanup()` in the driver unload
1595 operation handler.
1596
1597 Vertical Blanking and Interrupt Handling Functions Reference
1598 ------------------------------------------------------------
1599
1600 .. kernel-doc:: drivers/gpu/drm/drm_irq.c
1601    :export:
1602
1603 .. kernel-doc:: include/drm/drmP.h
1604    :functions: drm_crtc_vblank_waitqueue
1605
1606 Open/Close, File Operations and IOCTLs
1607 ======================================
1608
1609 Open and Close
1610 --------------
1611
1612 int (\*firstopen) (struct drm_device \*); void (\*lastclose) (struct
1613 drm_device \*); int (\*open) (struct drm_device \*, struct drm_file
1614 \*); void (\*preclose) (struct drm_device \*, struct drm_file \*);
1615 void (\*postclose) (struct drm_device \*, struct drm_file \*);
1616     Open and close handlers. None of those methods are mandatory.
1617
1618 The firstopen method is called by the DRM core for legacy UMS (User Mode
1619 Setting) drivers only when an application opens a device that has no
1620 other opened file handle. UMS drivers can implement it to acquire device
1621 resources. KMS drivers can't use the method and must acquire resources
1622 in the load method instead.
1623
1624 Similarly the lastclose method is called when the last application
1625 holding a file handle opened on the device closes it, for both UMS and
1626 KMS drivers. Additionally, the method is also called at module unload
1627 time or, for hot-pluggable devices, when the device is unplugged. The
1628 firstopen and lastclose calls can thus be unbalanced.
1629
1630 The open method is called every time the device is opened by an
1631 application. Drivers can allocate per-file private data in this method
1632 and store them in the struct :c:type:`struct drm_file
1633 <drm_file>` driver_priv field. Note that the open method is
1634 called before firstopen.
1635
1636 The close operation is split into preclose and postclose methods.
1637 Drivers must stop and cleanup all per-file operations in the preclose
1638 method. For instance pending vertical blanking and page flip events must
1639 be cancelled. No per-file operation is allowed on the file handle after
1640 returning from the preclose method.
1641
1642 Finally the postclose method is called as the last step of the close
1643 operation, right before calling the lastclose method if no other open
1644 file handle exists for the device. Drivers that have allocated per-file
1645 private data in the open method should free it here.
1646
1647 The lastclose method should restore CRTC and plane properties to default
1648 value, so that a subsequent open of the device will not inherit state
1649 from the previous user. It can also be used to execute delayed power
1650 switching state changes, e.g. in conjunction with the vga_switcheroo
1651 infrastructure (see ?). Beyond that KMS drivers should not do any
1652 further cleanup. Only legacy UMS drivers might need to clean up device
1653 state so that the vga console or an independent fbdev driver could take
1654 over.
1655
1656 File Operations
1657 ---------------
1658
1659 .. kernel-doc:: drivers/gpu/drm/drm_fops.c
1660    :doc: file operations
1661
1662 .. kernel-doc:: drivers/gpu/drm/drm_fops.c
1663    :export:
1664
1665 IOCTLs
1666 ------
1667
1668 struct drm_ioctl_desc \*ioctls; int num_ioctls;
1669     Driver-specific ioctls descriptors table.
1670
1671 Driver-specific ioctls numbers start at DRM_COMMAND_BASE. The ioctls
1672 descriptors table is indexed by the ioctl number offset from the base
1673 value. Drivers can use the DRM_IOCTL_DEF_DRV() macro to initialize
1674 the table entries.
1675
1676 ::
1677
1678     DRM_IOCTL_DEF_DRV(ioctl, func, flags)
1679
1680 ``ioctl`` is the ioctl name. Drivers must define the DRM_##ioctl and
1681 DRM_IOCTL_##ioctl macros to the ioctl number offset from
1682 DRM_COMMAND_BASE and the ioctl number respectively. The first macro is
1683 private to the device while the second must be exposed to userspace in a
1684 public header.
1685
1686 ``func`` is a pointer to the ioctl handler function compatible with the
1687 ``drm_ioctl_t`` type.
1688
1689 ::
1690
1691     typedef int drm_ioctl_t(struct drm_device *dev, void *data,
1692             struct drm_file *file_priv);
1693
1694 ``flags`` is a bitmask combination of the following values. It restricts
1695 how the ioctl is allowed to be called.
1696
1697 -  DRM_AUTH - Only authenticated callers allowed
1698
1699 -  DRM_MASTER - The ioctl can only be called on the master file handle
1700
1701 -  DRM_ROOT_ONLY - Only callers with the SYSADMIN capability allowed
1702
1703 -  DRM_CONTROL_ALLOW - The ioctl can only be called on a control
1704    device
1705
1706 -  DRM_UNLOCKED - The ioctl handler will be called without locking the
1707    DRM global mutex. This is the enforced default for kms drivers (i.e.
1708    using the DRIVER_MODESET flag) and hence shouldn't be used any more
1709    for new drivers.
1710
1711 .. kernel-doc:: drivers/gpu/drm/drm_ioctl.c
1712    :export:
1713
1714 Legacy Support Code
1715 ===================
1716
1717 The section very briefly covers some of the old legacy support code
1718 which is only used by old DRM drivers which have done a so-called
1719 shadow-attach to the underlying device instead of registering as a real
1720 driver. This also includes some of the old generic buffer management and
1721 command submission code. Do not use any of this in new and modern
1722 drivers.
1723
1724 Legacy Suspend/Resume
1725 ---------------------
1726
1727 The DRM core provides some suspend/resume code, but drivers wanting full
1728 suspend/resume support should provide save() and restore() functions.
1729 These are called at suspend, hibernate, or resume time, and should
1730 perform any state save or restore required by your device across suspend
1731 or hibernate states.
1732
1733 int (\*suspend) (struct drm_device \*, pm_message_t state); int
1734 (\*resume) (struct drm_device \*);
1735 Those are legacy suspend and resume methods which *only* work with the
1736 legacy shadow-attach driver registration functions. New driver should
1737 use the power management interface provided by their bus type (usually
1738 through the :c:type:`struct device_driver <device_driver>`
1739 dev_pm_ops) and set these methods to NULL.
1740
1741 Legacy DMA Services
1742 -------------------
1743
1744 This should cover how DMA mapping etc. is supported by the core. These
1745 functions are deprecated and should not be used.