Linux Audio

Check our new training course

Loading...
v6.13.7
  1.. Copyright 2020 DisplayLink (UK) Ltd.
  2
  3===================
  4Userland interfaces
  5===================
  6
  7The DRM core exports several interfaces to applications, generally
  8intended to be used through corresponding libdrm wrapper functions. In
  9addition, drivers export device-specific interfaces for use by userspace
 10drivers & device-aware applications through ioctls and sysfs files.
 11
 12External interfaces include: memory mapping, context management, DMA
 13operations, AGP management, vblank control, fence management, memory
 14management, and output management.
 15
 16Cover generic ioctls and sysfs layout here. We only need high-level
 17info, since man pages should cover the rest.
 18
 19libdrm Device Lookup
 20====================
 21
 22.. kernel-doc:: drivers/gpu/drm/drm_ioctl.c
 23   :doc: getunique and setversion story
 24
 25
 26.. _drm_primary_node:
 27
 28Primary Nodes, DRM Master and Authentication
 29============================================
 30
 31.. kernel-doc:: drivers/gpu/drm/drm_auth.c
 32   :doc: master and authentication
 33
 34.. kernel-doc:: drivers/gpu/drm/drm_auth.c
 35   :export:
 36
 37.. kernel-doc:: include/drm/drm_auth.h
 38   :internal:
 39
 40
 41.. _drm_leasing:
 42
 43DRM Display Resource Leasing
 44============================
 45
 46.. kernel-doc:: drivers/gpu/drm/drm_lease.c
 47   :doc: drm leasing
 48
 49Open-Source Userspace Requirements
 50==================================
 51
 52The DRM subsystem has stricter requirements than most other kernel subsystems on
 53what the userspace side for new uAPI needs to look like. This section here
 54explains what exactly those requirements are, and why they exist.
 55
 56The short summary is that any addition of DRM uAPI requires corresponding
 57open-sourced userspace patches, and those patches must be reviewed and ready for
 58merging into a suitable and canonical upstream project.
 59
 60GFX devices (both display and render/GPU side) are really complex bits of
 61hardware, with userspace and kernel by necessity having to work together really
 62closely.  The interfaces, for rendering and modesetting, must be extremely wide
 63and flexible, and therefore it is almost always impossible to precisely define
 64them for every possible corner case. This in turn makes it really practically
 65infeasible to differentiate between behaviour that's required by userspace, and
 66which must not be changed to avoid regressions, and behaviour which is only an
 67accidental artifact of the current implementation.
 68
 69Without access to the full source code of all userspace users that means it
 70becomes impossible to change the implementation details, since userspace could
 71depend upon the accidental behaviour of the current implementation in minute
 72details. And debugging such regressions without access to source code is pretty
 73much impossible. As a consequence this means:
 74
 75- The Linux kernel's "no regression" policy holds in practice only for
 76  open-source userspace of the DRM subsystem. DRM developers are perfectly fine
 77  if closed-source blob drivers in userspace use the same uAPI as the open
 78  drivers, but they must do so in the exact same way as the open drivers.
 79  Creative (ab)use of the interfaces will, and in the past routinely has, lead
 80  to breakage.
 81
 82- Any new userspace interface must have an open-source implementation as
 83  demonstration vehicle.
 84
 85The other reason for requiring open-source userspace is uAPI review. Since the
 86kernel and userspace parts of a GFX stack must work together so closely, code
 87review can only assess whether a new interface achieves its goals by looking at
 88both sides. Making sure that the interface indeed covers the use-case fully
 89leads to a few additional requirements:
 90
 91- The open-source userspace must not be a toy/test application, but the real
 92  thing. Specifically it needs to handle all the usual error and corner cases.
 93  These are often the places where new uAPI falls apart and hence essential to
 94  assess the fitness of a proposed interface.
 95
 96- The userspace side must be fully reviewed and tested to the standards of that
 97  userspace project. For e.g. mesa this means piglit testcases and review on the
 98  mailing list. This is again to ensure that the new interface actually gets the
 99  job done.  The userspace-side reviewer should also provide an Acked-by on the
100  kernel uAPI patch indicating that they believe the proposed uAPI is sound and
101  sufficiently documented and validated for userspace's consumption.
102
103- The userspace patches must be against the canonical upstream, not some vendor
104  fork. This is to make sure that no one cheats on the review and testing
105  requirements by doing a quick fork.
106
107- The kernel patch can only be merged after all the above requirements are met,
108  but it **must** be merged to either drm-next or drm-misc-next **before** the
109  userspace patches land. uAPI always flows from the kernel, doing things the
110  other way round risks divergence of the uAPI definitions and header files.
111
112These are fairly steep requirements, but have grown out from years of shared
113pain and experience with uAPI added hastily, and almost always regretted about
114just as fast. GFX devices change really fast, requiring a paradigm shift and
115entire new set of uAPI interfaces every few years at least. Together with the
116Linux kernel's guarantee to keep existing userspace running for 10+ years this
117is already rather painful for the DRM subsystem, with multiple different uAPIs
118for the same thing co-existing. If we add a few more complete mistakes into the
119mix every year it would be entirely unmanageable.
120
121.. _drm_render_node:
122
123Render nodes
124============
125
126DRM core provides multiple character-devices for user-space to use.
127Depending on which device is opened, user-space can perform a different
128set of operations (mainly ioctls). The primary node is always created
129and called card<num>. Additionally, a currently unused control node,
130called controlD<num> is also created. The primary node provides all
131legacy operations and historically was the only interface used by
132userspace. With KMS, the control node was introduced. However, the
133planned KMS control interface has never been written and so the control
134node stays unused to date.
135
136With the increased use of offscreen renderers and GPGPU applications,
137clients no longer require running compositors or graphics servers to
138make use of a GPU. But the DRM API required unprivileged clients to
139authenticate to a DRM-Master prior to getting GPU access. To avoid this
140step and to grant clients GPU access without authenticating, render
141nodes were introduced. Render nodes solely serve render clients, that
142is, no modesetting or privileged ioctls can be issued on render nodes.
143Only non-global rendering commands are allowed. If a driver supports
144render nodes, it must advertise it via the DRIVER_RENDER DRM driver
145capability. If not supported, the primary node must be used for render
146clients together with the legacy drmAuth authentication procedure.
147
148If a driver advertises render node support, DRM core will create a
149separate render node called renderD<num>. There will be one render node
150per device. No ioctls except PRIME-related ioctls will be allowed on
151this node. Especially GEM_OPEN will be explicitly prohibited. For a
152complete list of driver-independent ioctls that can be used on render
153nodes, see the ioctls marked DRM_RENDER_ALLOW in drm_ioctl.c  Render
154nodes are designed to avoid the buffer-leaks, which occur if clients
155guess the flink names or mmap offsets on the legacy interface.
156Additionally to this basic interface, drivers must mark their
157driver-dependent render-only ioctls as DRM_RENDER_ALLOW so render
158clients can use them. Driver authors must be careful not to allow any
159privileged ioctls on render nodes.
160
161With render nodes, user-space can now control access to the render node
162via basic file-system access-modes. A running graphics server which
163authenticates clients on the privileged primary/legacy node is no longer
164required. Instead, a client can open the render node and is immediately
165granted GPU access. Communication between clients (or servers) is done
166via PRIME. FLINK from render node to legacy node is not supported. New
167clients must not use the insecure FLINK interface.
168
169Besides dropping all modeset/global ioctls, render nodes also drop the
170DRM-Master concept. There is no reason to associate render clients with
171a DRM-Master as they are independent of any graphics server. Besides,
172they must work without any running master, anyway. Drivers must be able
173to run without a master object if they support render nodes. If, on the
174other hand, a driver requires shared state between clients which is
175visible to user-space and accessible beyond open-file boundaries, they
176cannot support render nodes.
177
178Device Hot-Unplug
179=================
180
181.. note::
182   The following is the plan. Implementation is not there yet
183   (2020 May).
184
185Graphics devices (display and/or render) may be connected via USB (e.g.
186display adapters or docking stations) or Thunderbolt (e.g. eGPU). An end
187user is able to hot-unplug this kind of devices while they are being
188used, and expects that the very least the machine does not crash. Any
189damage from hot-unplugging a DRM device needs to be limited as much as
190possible and userspace must be given the chance to handle it if it wants
191to. Ideally, unplugging a DRM device still lets a desktop continue to
192run, but that is going to need explicit support throughout the whole
193graphics stack: from kernel and userspace drivers, through display
194servers, via window system protocols, and in applications and libraries.
195
196Other scenarios that should lead to the same are: unrecoverable GPU
197crash, PCI device disappearing off the bus, or forced unbind of a driver
198from the physical device.
199
200In other words, from userspace perspective everything needs to keep on
201working more or less, until userspace stops using the disappeared DRM
202device and closes it completely. Userspace will learn of the device
203disappearance from the device removed uevent, ioctls returning ENODEV
204(or driver-specific ioctls returning driver-specific things), or open()
205returning ENXIO.
206
207Only after userspace has closed all relevant DRM device and dmabuf file
208descriptors and removed all mmaps, the DRM driver can tear down its
209instance for the device that no longer exists. If the same physical
210device somehow comes back in the mean time, it shall be a new DRM
211device.
212
213Similar to PIDs, chardev minor numbers are not recycled immediately. A
214new DRM device always picks the next free minor number compared to the
215previous one allocated, and wraps around when minor numbers are
216exhausted.
217
218The goal raises at least the following requirements for the kernel and
219drivers.
220
221Requirements for KMS UAPI
222-------------------------
223
224- KMS connectors must change their status to disconnected.
225
226- Legacy modesets and pageflips, and atomic commits, both real and
227  TEST_ONLY, and any other ioctls either fail with ENODEV or fake
228  success.
229
230- Pending non-blocking KMS operations deliver the DRM events userspace
231  is expecting. This applies also to ioctls that faked success.
232
233- open() on a device node whose underlying device has disappeared will
234  fail with ENXIO.
235
236- Attempting to create a DRM lease on a disappeared DRM device will
237  fail with ENODEV. Existing DRM leases remain and work as listed
238  above.
239
240Requirements for Render and Cross-Device UAPI
241---------------------------------------------
242
243- All GPU jobs that can no longer run must have their fences
244  force-signalled to avoid inflicting hangs on userspace.
245  The associated error code is ENODEV.
246
247- Some userspace APIs already define what should happen when the device
248  disappears (OpenGL, GL ES: `GL_KHR_robustness`_; `Vulkan`_:
249  VK_ERROR_DEVICE_LOST; etc.). DRM drivers are free to implement this
250  behaviour the way they see best, e.g. returning failures in
251  driver-specific ioctls and handling those in userspace drivers, or
252  rely on uevents, and so on.
253
254- dmabuf which point to memory that has disappeared will either fail to
255  import with ENODEV or continue to be successfully imported if it would
256  have succeeded before the disappearance. See also about memory maps
257  below for already imported dmabufs.
258
259- Attempting to import a dmabuf to a disappeared device will either fail
260  with ENODEV or succeed if it would have succeeded without the
261  disappearance.
262
263- open() on a device node whose underlying device has disappeared will
264  fail with ENXIO.
265
266.. _GL_KHR_robustness: https://www.khronos.org/registry/OpenGL/extensions/KHR/KHR_robustness.txt
267.. _Vulkan: https://www.khronos.org/vulkan/
268
269Requirements for Memory Maps
270----------------------------
271
272Memory maps have further requirements that apply to both existing maps
273and maps created after the device has disappeared. If the underlying
274memory disappears, the map is created or modified such that reads and
275writes will still complete successfully but the result is undefined.
276This applies to both userspace mmap()'d memory and memory pointed to by
277dmabuf which might be mapped to other devices (cross-device dmabuf
278imports).
279
280Raising SIGBUS is not an option, because userspace cannot realistically
281handle it. Signal handlers are global, which makes them extremely
282difficult to use correctly from libraries like those that Mesa produces.
283Signal handlers are not composable, you can't have different handlers
284for GPU1 and GPU2 from different vendors, and a third handler for
285mmapped regular files. Threads cause additional pain with signal
286handling as well.
287
288Device reset
289============
290
291The GPU stack is really complex and is prone to errors, from hardware bugs,
292faulty applications and everything in between the many layers. Some errors
293require resetting the device in order to make the device usable again. This
294section describes the expectations for DRM and usermode drivers when a
295device resets and how to propagate the reset status.
296
297Device resets can not be disabled without tainting the kernel, which can lead to
298hanging the entire kernel through shrinkers/mmu_notifiers. Userspace role in
299device resets is to propagate the message to the application and apply any
300special policy for blocking guilty applications, if any. Corollary is that
301debugging a hung GPU context require hardware support to be able to preempt such
302a GPU context while it's stopped.
303
304Kernel Mode Driver
305------------------
306
307The KMD is responsible for checking if the device needs a reset, and to perform
308it as needed. Usually a hang is detected when a job gets stuck executing.
309
310Propagation of errors to userspace has proven to be tricky since it goes in
311the opposite direction of the usual flow of commands. Because of this vendor
312independent error handling was added to the &dma_fence object, this way drivers
313can add an error code to their fences before signaling them. See function
314dma_fence_set_error() on how to do this and for examples of error codes to use.
315
316The DRM scheduler also allows setting error codes on all pending fences when
317hardware submissions are restarted after an reset. Error codes are also
318forwarded from the hardware fence to the scheduler fence to bubble up errors
319to the higher levels of the stack and eventually userspace.
320
321Fence errors can be queried by userspace through the generic SYNC_IOC_FILE_INFO
322IOCTL as well as through driver specific interfaces.
323
324Additional to setting fence errors drivers should also keep track of resets per
325context, the DRM scheduler provides the drm_sched_entity_error() function as
326helper for this use case. After a reset, KMD should reject new command
327submissions for affected contexts.
328
329User Mode Driver
330----------------
331
332After command submission, UMD should check if the submission was accepted or
333rejected. After a reset, KMD should reject submissions, and UMD can issue an
334ioctl to the KMD to check the reset status, and this can be checked more often
335if the UMD requires it. After detecting a reset, UMD will then proceed to report
336it to the application using the appropriate API error code, as explained in the
337section below about robustness.
338
339Robustness
340----------
341
342The only way to try to keep a graphical API context working after a reset is if
343it complies with the robustness aspects of the graphical API that it is using.
344
345Graphical APIs provide ways to applications to deal with device resets. However,
346there is no guarantee that the app will use such features correctly, and a
347userspace that doesn't support robust interfaces (like a non-robust
348OpenGL context or API without any robustness support like libva) leave the
349robustness handling entirely to the userspace driver. There is no strong
350community consensus on what the userspace driver should do in that case,
351since all reasonable approaches have some clear downsides.
352
353OpenGL
354~~~~~~
355
356Apps using OpenGL should use the available robust interfaces, like the
357extension ``GL_ARB_robustness`` (or ``GL_EXT_robustness`` for OpenGL ES). This
358interface tells if a reset has happened, and if so, all the context state is
359considered lost and the app proceeds by creating new ones. There's no consensus
360on what to do to if robustness is not in use.
361
362Vulkan
363~~~~~~
364
365Apps using Vulkan should check for ``VK_ERROR_DEVICE_LOST`` for submissions.
366This error code means, among other things, that a device reset has happened and
367it needs to recreate the contexts to keep going.
368
369Reporting causes of resets
370--------------------------
371
372Apart from propagating the reset through the stack so apps can recover, it's
373really useful for driver developers to learn more about what caused the reset in
374the first place. DRM devices should make use of devcoredump to store relevant
375information about the reset, so this information can be added to user bug
376reports.
377
378.. _drm_driver_ioctl:
379
380IOCTL Support on Device Nodes
381=============================
382
383.. kernel-doc:: drivers/gpu/drm/drm_ioctl.c
384   :doc: driver specific ioctls
385
386Recommended IOCTL Return Values
387-------------------------------
388
389In theory a driver's IOCTL callback is only allowed to return very few error
390codes. In practice it's good to abuse a few more. This section documents common
391practice within the DRM subsystem:
392
393ENOENT:
394        Strictly this should only be used when a file doesn't exist e.g. when
395        calling the open() syscall. We reuse that to signal any kind of object
396        lookup failure, e.g. for unknown GEM buffer object handles, unknown KMS
397        object handles and similar cases.
398
399ENOSPC:
400        Some drivers use this to differentiate "out of kernel memory" from "out
401        of VRAM". Sometimes also applies to other limited gpu resources used for
402        rendering (e.g. when you have a special limited compression buffer).
403        Sometimes resource allocation/reservation issues in command submission
404        IOCTLs are also signalled through EDEADLK.
405
406        Simply running out of kernel/system memory is signalled through ENOMEM.
407
408EPERM/EACCES:
409        Returned for an operation that is valid, but needs more privileges.
410        E.g. root-only or much more common, DRM master-only operations return
411        this when called by unpriviledged clients. There's no clear
412        difference between EACCES and EPERM.
413
414ENODEV:
415        The device is not present anymore or is not yet fully initialized.
416
417EOPNOTSUPP:
418        Feature (like PRIME, modesetting, GEM) is not supported by the driver.
419
420ENXIO:
421        Remote failure, either a hardware transaction (like i2c), but also used
422        when the exporting driver of a shared dma-buf or fence doesn't support a
423        feature needed.
424
425EINTR:
426        DRM drivers assume that userspace restarts all IOCTLs. Any DRM IOCTL can
427        return EINTR and in such a case should be restarted with the IOCTL
428        parameters left unchanged.
429
430EIO:
431        The GPU died and couldn't be resurrected through a reset. Modesetting
432        hardware failures are signalled through the "link status" connector
433        property.
434
435EINVAL:
436        Catch-all for anything that is an invalid argument combination which
437        cannot work.
438
439IOCTL also use other error codes like ETIME, EFAULT, EBUSY, ENOTTY but their
440usage is in line with the common meanings. The above list tries to just document
441DRM specific patterns. Note that ENOTTY has the slightly unintuitive meaning of
442"this IOCTL does not exist", and is used exactly as such in DRM.
443
444.. kernel-doc:: include/drm/drm_ioctl.h
445   :internal:
446
447.. kernel-doc:: drivers/gpu/drm/drm_ioctl.c
448   :export:
449
450.. kernel-doc:: drivers/gpu/drm/drm_ioc32.c
451   :export:
452
453Testing and validation
454======================
455
456Testing Requirements for userspace API
457--------------------------------------
458
459New cross-driver userspace interface extensions, like new IOCTL, new KMS
460properties, new files in sysfs or anything else that constitutes an API change
461should have driver-agnostic testcases in IGT for that feature, if such a test
462can be reasonably made using IGT for the target hardware.
463
464Validating changes with IGT
465---------------------------
466
467There's a collection of tests that aims to cover the whole functionality of
468DRM drivers and that can be used to check that changes to DRM drivers or the
469core don't regress existing functionality. This test suite is called IGT and
470its code and instructions to build and run can be found in
471https://gitlab.freedesktop.org/drm/igt-gpu-tools/.
472
473Using VKMS to test DRM API
474--------------------------
475
476VKMS is a software-only model of a KMS driver that is useful for testing
477and for running compositors. VKMS aims to enable a virtual display without
478the need for a hardware display capability. These characteristics made VKMS
479a perfect tool for validating the DRM core behavior and also support the
480compositor developer. VKMS makes it possible to test DRM functions in a
481virtual machine without display, simplifying the validation of some of the
482core changes.
483
484To Validate changes in DRM API with VKMS, start setting the kernel: make
485sure to enable VKMS module; compile the kernel with the VKMS enabled and
486install it in the target machine. VKMS can be run in a Virtual Machine
487(QEMU, virtme or similar). It's recommended the use of KVM with the minimum
488of 1GB of RAM and four cores.
489
490It's possible to run the IGT-tests in a VM in two ways:
491
492	1. Use IGT inside a VM
493	2. Use IGT from the host machine and write the results in a shared directory.
494
495Following is an example of using a VM with a shared directory with
496the host machine to run igt-tests. This example uses virtme::
497
498	$ virtme-run --rwdir /path/for/shared_dir --kdir=path/for/kernel/directory --mods=auto
499
500Run the igt-tests in the guest machine. This example runs the 'kms_flip'
501tests::
502
503	$ /path/for/igt-gpu-tools/scripts/run-tests.sh -p -s -t "kms_flip.*" -v
504
505In this example, instead of building the igt_runner, Piglit is used
506(-p option). It creates an HTML summary of the test results and saves
507them in the folder "igt-gpu-tools/results". It executes only the igt-tests
508matching the -t option.
509
510Display CRC Support
511-------------------
512
513.. kernel-doc:: drivers/gpu/drm/drm_debugfs_crc.c
514   :doc: CRC ABI
515
516.. kernel-doc:: drivers/gpu/drm/drm_debugfs_crc.c
517   :export:
518
519Debugfs Support
520---------------
521
522.. kernel-doc:: include/drm/drm_debugfs.h
523   :internal:
524
525.. kernel-doc:: drivers/gpu/drm/drm_debugfs.c
526   :export:
527
528Sysfs Support
529=============
530
531.. kernel-doc:: drivers/gpu/drm/drm_sysfs.c
532   :doc: overview
533
534.. kernel-doc:: drivers/gpu/drm/drm_sysfs.c
535   :export:
536
537
538VBlank event handling
539=====================
540
541The DRM core exposes two vertical blank related ioctls:
542
543:c:macro:`DRM_IOCTL_WAIT_VBLANK`
544    This takes a struct drm_wait_vblank structure as its argument, and
545    it is used to block or request a signal when a specified vblank
546    event occurs.
547
548:c:macro:`DRM_IOCTL_MODESET_CTL`
549    This was only used for user-mode-settind drivers around modesetting
550    changes to allow the kernel to update the vblank interrupt after
551    mode setting, since on many devices the vertical blank counter is
552    reset to 0 at some point during modeset. Modern drivers should not
553    call this any more since with kernel mode setting it is a no-op.
554
555Userspace API Structures
556========================
557
558.. kernel-doc:: include/uapi/drm/drm_mode.h
559   :doc: overview
560
561.. _crtc_index:
562
563CRTC index
564----------
565
566CRTC's have both an object ID and an index, and they are not the same thing.
567The index is used in cases where a densely packed identifier for a CRTC is
568needed, for instance a bitmask of CRTC's. The member possible_crtcs of struct
569drm_mode_get_plane is an example.
570
571:c:macro:`DRM_IOCTL_MODE_GETRESOURCES` populates a structure with an array of
572CRTC ID's, and the CRTC index is its position in this array.
573
574.. kernel-doc:: include/uapi/drm/drm.h
575   :internal:
576
577.. kernel-doc:: include/uapi/drm/drm_mode.h
578   :internal:
579
580
581dma-buf interoperability
582========================
583
584Please see Documentation/userspace-api/dma-buf-alloc-exchange.rst for
585information on how dma-buf is integrated and exposed within DRM.
v5.14.15
  1.. Copyright 2020 DisplayLink (UK) Ltd.
  2
  3===================
  4Userland interfaces
  5===================
  6
  7The DRM core exports several interfaces to applications, generally
  8intended to be used through corresponding libdrm wrapper functions. In
  9addition, drivers export device-specific interfaces for use by userspace
 10drivers & device-aware applications through ioctls and sysfs files.
 11
 12External interfaces include: memory mapping, context management, DMA
 13operations, AGP management, vblank control, fence management, memory
 14management, and output management.
 15
 16Cover generic ioctls and sysfs layout here. We only need high-level
 17info, since man pages should cover the rest.
 18
 19libdrm Device Lookup
 20====================
 21
 22.. kernel-doc:: drivers/gpu/drm/drm_ioctl.c
 23   :doc: getunique and setversion story
 24
 25
 26.. _drm_primary_node:
 27
 28Primary Nodes, DRM Master and Authentication
 29============================================
 30
 31.. kernel-doc:: drivers/gpu/drm/drm_auth.c
 32   :doc: master and authentication
 33
 34.. kernel-doc:: drivers/gpu/drm/drm_auth.c
 35   :export:
 36
 37.. kernel-doc:: include/drm/drm_auth.h
 38   :internal:
 39
 
 
 
 
 
 
 
 
 
 40Open-Source Userspace Requirements
 41==================================
 42
 43The DRM subsystem has stricter requirements than most other kernel subsystems on
 44what the userspace side for new uAPI needs to look like. This section here
 45explains what exactly those requirements are, and why they exist.
 46
 47The short summary is that any addition of DRM uAPI requires corresponding
 48open-sourced userspace patches, and those patches must be reviewed and ready for
 49merging into a suitable and canonical upstream project.
 50
 51GFX devices (both display and render/GPU side) are really complex bits of
 52hardware, with userspace and kernel by necessity having to work together really
 53closely.  The interfaces, for rendering and modesetting, must be extremely wide
 54and flexible, and therefore it is almost always impossible to precisely define
 55them for every possible corner case. This in turn makes it really practically
 56infeasible to differentiate between behaviour that's required by userspace, and
 57which must not be changed to avoid regressions, and behaviour which is only an
 58accidental artifact of the current implementation.
 59
 60Without access to the full source code of all userspace users that means it
 61becomes impossible to change the implementation details, since userspace could
 62depend upon the accidental behaviour of the current implementation in minute
 63details. And debugging such regressions without access to source code is pretty
 64much impossible. As a consequence this means:
 65
 66- The Linux kernel's "no regression" policy holds in practice only for
 67  open-source userspace of the DRM subsystem. DRM developers are perfectly fine
 68  if closed-source blob drivers in userspace use the same uAPI as the open
 69  drivers, but they must do so in the exact same way as the open drivers.
 70  Creative (ab)use of the interfaces will, and in the past routinely has, lead
 71  to breakage.
 72
 73- Any new userspace interface must have an open-source implementation as
 74  demonstration vehicle.
 75
 76The other reason for requiring open-source userspace is uAPI review. Since the
 77kernel and userspace parts of a GFX stack must work together so closely, code
 78review can only assess whether a new interface achieves its goals by looking at
 79both sides. Making sure that the interface indeed covers the use-case fully
 80leads to a few additional requirements:
 81
 82- The open-source userspace must not be a toy/test application, but the real
 83  thing. Specifically it needs to handle all the usual error and corner cases.
 84  These are often the places where new uAPI falls apart and hence essential to
 85  assess the fitness of a proposed interface.
 86
 87- The userspace side must be fully reviewed and tested to the standards of that
 88  userspace project. For e.g. mesa this means piglit testcases and review on the
 89  mailing list. This is again to ensure that the new interface actually gets the
 90  job done.  The userspace-side reviewer should also provide an Acked-by on the
 91  kernel uAPI patch indicating that they believe the proposed uAPI is sound and
 92  sufficiently documented and validated for userspace's consumption.
 93
 94- The userspace patches must be against the canonical upstream, not some vendor
 95  fork. This is to make sure that no one cheats on the review and testing
 96  requirements by doing a quick fork.
 97
 98- The kernel patch can only be merged after all the above requirements are met,
 99  but it **must** be merged to either drm-next or drm-misc-next **before** the
100  userspace patches land. uAPI always flows from the kernel, doing things the
101  other way round risks divergence of the uAPI definitions and header files.
102
103These are fairly steep requirements, but have grown out from years of shared
104pain and experience with uAPI added hastily, and almost always regretted about
105just as fast. GFX devices change really fast, requiring a paradigm shift and
106entire new set of uAPI interfaces every few years at least. Together with the
107Linux kernel's guarantee to keep existing userspace running for 10+ years this
108is already rather painful for the DRM subsystem, with multiple different uAPIs
109for the same thing co-existing. If we add a few more complete mistakes into the
110mix every year it would be entirely unmanageable.
111
112.. _drm_render_node:
113
114Render nodes
115============
116
117DRM core provides multiple character-devices for user-space to use.
118Depending on which device is opened, user-space can perform a different
119set of operations (mainly ioctls). The primary node is always created
120and called card<num>. Additionally, a currently unused control node,
121called controlD<num> is also created. The primary node provides all
122legacy operations and historically was the only interface used by
123userspace. With KMS, the control node was introduced. However, the
124planned KMS control interface has never been written and so the control
125node stays unused to date.
126
127With the increased use of offscreen renderers and GPGPU applications,
128clients no longer require running compositors or graphics servers to
129make use of a GPU. But the DRM API required unprivileged clients to
130authenticate to a DRM-Master prior to getting GPU access. To avoid this
131step and to grant clients GPU access without authenticating, render
132nodes were introduced. Render nodes solely serve render clients, that
133is, no modesetting or privileged ioctls can be issued on render nodes.
134Only non-global rendering commands are allowed. If a driver supports
135render nodes, it must advertise it via the DRIVER_RENDER DRM driver
136capability. If not supported, the primary node must be used for render
137clients together with the legacy drmAuth authentication procedure.
138
139If a driver advertises render node support, DRM core will create a
140separate render node called renderD<num>. There will be one render node
141per device. No ioctls except PRIME-related ioctls will be allowed on
142this node. Especially GEM_OPEN will be explicitly prohibited. Render
 
 
143nodes are designed to avoid the buffer-leaks, which occur if clients
144guess the flink names or mmap offsets on the legacy interface.
145Additionally to this basic interface, drivers must mark their
146driver-dependent render-only ioctls as DRM_RENDER_ALLOW so render
147clients can use them. Driver authors must be careful not to allow any
148privileged ioctls on render nodes.
149
150With render nodes, user-space can now control access to the render node
151via basic file-system access-modes. A running graphics server which
152authenticates clients on the privileged primary/legacy node is no longer
153required. Instead, a client can open the render node and is immediately
154granted GPU access. Communication between clients (or servers) is done
155via PRIME. FLINK from render node to legacy node is not supported. New
156clients must not use the insecure FLINK interface.
157
158Besides dropping all modeset/global ioctls, render nodes also drop the
159DRM-Master concept. There is no reason to associate render clients with
160a DRM-Master as they are independent of any graphics server. Besides,
161they must work without any running master, anyway. Drivers must be able
162to run without a master object if they support render nodes. If, on the
163other hand, a driver requires shared state between clients which is
164visible to user-space and accessible beyond open-file boundaries, they
165cannot support render nodes.
166
167Device Hot-Unplug
168=================
169
170.. note::
171   The following is the plan. Implementation is not there yet
172   (2020 May).
173
174Graphics devices (display and/or render) may be connected via USB (e.g.
175display adapters or docking stations) or Thunderbolt (e.g. eGPU). An end
176user is able to hot-unplug this kind of devices while they are being
177used, and expects that the very least the machine does not crash. Any
178damage from hot-unplugging a DRM device needs to be limited as much as
179possible and userspace must be given the chance to handle it if it wants
180to. Ideally, unplugging a DRM device still lets a desktop continue to
181run, but that is going to need explicit support throughout the whole
182graphics stack: from kernel and userspace drivers, through display
183servers, via window system protocols, and in applications and libraries.
184
185Other scenarios that should lead to the same are: unrecoverable GPU
186crash, PCI device disappearing off the bus, or forced unbind of a driver
187from the physical device.
188
189In other words, from userspace perspective everything needs to keep on
190working more or less, until userspace stops using the disappeared DRM
191device and closes it completely. Userspace will learn of the device
192disappearance from the device removed uevent, ioctls returning ENODEV
193(or driver-specific ioctls returning driver-specific things), or open()
194returning ENXIO.
195
196Only after userspace has closed all relevant DRM device and dmabuf file
197descriptors and removed all mmaps, the DRM driver can tear down its
198instance for the device that no longer exists. If the same physical
199device somehow comes back in the mean time, it shall be a new DRM
200device.
201
202Similar to PIDs, chardev minor numbers are not recycled immediately. A
203new DRM device always picks the next free minor number compared to the
204previous one allocated, and wraps around when minor numbers are
205exhausted.
206
207The goal raises at least the following requirements for the kernel and
208drivers.
209
210Requirements for KMS UAPI
211-------------------------
212
213- KMS connectors must change their status to disconnected.
214
215- Legacy modesets and pageflips, and atomic commits, both real and
216  TEST_ONLY, and any other ioctls either fail with ENODEV or fake
217  success.
218
219- Pending non-blocking KMS operations deliver the DRM events userspace
220  is expecting. This applies also to ioctls that faked success.
221
222- open() on a device node whose underlying device has disappeared will
223  fail with ENXIO.
224
225- Attempting to create a DRM lease on a disappeared DRM device will
226  fail with ENODEV. Existing DRM leases remain and work as listed
227  above.
228
229Requirements for Render and Cross-Device UAPI
230---------------------------------------------
231
232- All GPU jobs that can no longer run must have their fences
233  force-signalled to avoid inflicting hangs on userspace.
234  The associated error code is ENODEV.
235
236- Some userspace APIs already define what should happen when the device
237  disappears (OpenGL, GL ES: `GL_KHR_robustness`_; `Vulkan`_:
238  VK_ERROR_DEVICE_LOST; etc.). DRM drivers are free to implement this
239  behaviour the way they see best, e.g. returning failures in
240  driver-specific ioctls and handling those in userspace drivers, or
241  rely on uevents, and so on.
242
243- dmabuf which point to memory that has disappeared will either fail to
244  import with ENODEV or continue to be successfully imported if it would
245  have succeeded before the disappearance. See also about memory maps
246  below for already imported dmabufs.
247
248- Attempting to import a dmabuf to a disappeared device will either fail
249  with ENODEV or succeed if it would have succeeded without the
250  disappearance.
251
252- open() on a device node whose underlying device has disappeared will
253  fail with ENXIO.
254
255.. _GL_KHR_robustness: https://www.khronos.org/registry/OpenGL/extensions/KHR/KHR_robustness.txt
256.. _Vulkan: https://www.khronos.org/vulkan/
257
258Requirements for Memory Maps
259----------------------------
260
261Memory maps have further requirements that apply to both existing maps
262and maps created after the device has disappeared. If the underlying
263memory disappears, the map is created or modified such that reads and
264writes will still complete successfully but the result is undefined.
265This applies to both userspace mmap()'d memory and memory pointed to by
266dmabuf which might be mapped to other devices (cross-device dmabuf
267imports).
268
269Raising SIGBUS is not an option, because userspace cannot realistically
270handle it. Signal handlers are global, which makes them extremely
271difficult to use correctly from libraries like those that Mesa produces.
272Signal handlers are not composable, you can't have different handlers
273for GPU1 and GPU2 from different vendors, and a third handler for
274mmapped regular files. Threads cause additional pain with signal
275handling as well.
276
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277.. _drm_driver_ioctl:
278
279IOCTL Support on Device Nodes
280=============================
281
282.. kernel-doc:: drivers/gpu/drm/drm_ioctl.c
283   :doc: driver specific ioctls
284
285Recommended IOCTL Return Values
286-------------------------------
287
288In theory a driver's IOCTL callback is only allowed to return very few error
289codes. In practice it's good to abuse a few more. This section documents common
290practice within the DRM subsystem:
291
292ENOENT:
293        Strictly this should only be used when a file doesn't exist e.g. when
294        calling the open() syscall. We reuse that to signal any kind of object
295        lookup failure, e.g. for unknown GEM buffer object handles, unknown KMS
296        object handles and similar cases.
297
298ENOSPC:
299        Some drivers use this to differentiate "out of kernel memory" from "out
300        of VRAM". Sometimes also applies to other limited gpu resources used for
301        rendering (e.g. when you have a special limited compression buffer).
302        Sometimes resource allocation/reservation issues in command submission
303        IOCTLs are also signalled through EDEADLK.
304
305        Simply running out of kernel/system memory is signalled through ENOMEM.
306
307EPERM/EACCES:
308        Returned for an operation that is valid, but needs more privileges.
309        E.g. root-only or much more common, DRM master-only operations return
310        this when called by unpriviledged clients. There's no clear
311        difference between EACCES and EPERM.
312
313ENODEV:
314        The device is not present anymore or is not yet fully initialized.
315
316EOPNOTSUPP:
317        Feature (like PRIME, modesetting, GEM) is not supported by the driver.
318
319ENXIO:
320        Remote failure, either a hardware transaction (like i2c), but also used
321        when the exporting driver of a shared dma-buf or fence doesn't support a
322        feature needed.
323
324EINTR:
325        DRM drivers assume that userspace restarts all IOCTLs. Any DRM IOCTL can
326        return EINTR and in such a case should be restarted with the IOCTL
327        parameters left unchanged.
328
329EIO:
330        The GPU died and couldn't be resurrected through a reset. Modesetting
331        hardware failures are signalled through the "link status" connector
332        property.
333
334EINVAL:
335        Catch-all for anything that is an invalid argument combination which
336        cannot work.
337
338IOCTL also use other error codes like ETIME, EFAULT, EBUSY, ENOTTY but their
339usage is in line with the common meanings. The above list tries to just document
340DRM specific patterns. Note that ENOTTY has the slightly unintuitive meaning of
341"this IOCTL does not exist", and is used exactly as such in DRM.
342
343.. kernel-doc:: include/drm/drm_ioctl.h
344   :internal:
345
346.. kernel-doc:: drivers/gpu/drm/drm_ioctl.c
347   :export:
348
349.. kernel-doc:: drivers/gpu/drm/drm_ioc32.c
350   :export:
351
352Testing and validation
353======================
354
355Testing Requirements for userspace API
356--------------------------------------
357
358New cross-driver userspace interface extensions, like new IOCTL, new KMS
359properties, new files in sysfs or anything else that constitutes an API change
360should have driver-agnostic testcases in IGT for that feature, if such a test
361can be reasonably made using IGT for the target hardware.
362
363Validating changes with IGT
364---------------------------
365
366There's a collection of tests that aims to cover the whole functionality of
367DRM drivers and that can be used to check that changes to DRM drivers or the
368core don't regress existing functionality. This test suite is called IGT and
369its code and instructions to build and run can be found in
370https://gitlab.freedesktop.org/drm/igt-gpu-tools/.
371
372Using VKMS to test DRM API
373--------------------------
374
375VKMS is a software-only model of a KMS driver that is useful for testing
376and for running compositors. VKMS aims to enable a virtual display without
377the need for a hardware display capability. These characteristics made VKMS
378a perfect tool for validating the DRM core behavior and also support the
379compositor developer. VKMS makes it possible to test DRM functions in a
380virtual machine without display, simplifying the validation of some of the
381core changes.
382
383To Validate changes in DRM API with VKMS, start setting the kernel: make
384sure to enable VKMS module; compile the kernel with the VKMS enabled and
385install it in the target machine. VKMS can be run in a Virtual Machine
386(QEMU, virtme or similar). It's recommended the use of KVM with the minimum
387of 1GB of RAM and four cores.
388
389It's possible to run the IGT-tests in a VM in two ways:
390
391	1. Use IGT inside a VM
392	2. Use IGT from the host machine and write the results in a shared directory.
393
394As follow, there is an example of using a VM with a shared directory with
395the host machine to run igt-tests. As an example it's used virtme::
396
397	$ virtme-run --rwdir /path/for/shared_dir --kdir=path/for/kernel/directory --mods=auto
398
399Run the igt-tests in the guest machine, as example it's ran the 'kms_flip'
400tests::
401
402	$ /path/for/igt-gpu-tools/scripts/run-tests.sh -p -s -t "kms_flip.*" -v
403
404In this example, instead of build the igt_runner, Piglit is used
405(-p option); it's created html summary of the tests results and it's saved
406in the folder "igt-gpu-tools/results"; it's executed only the igt-tests
407matching the -t option.
408
409Display CRC Support
410-------------------
411
412.. kernel-doc:: drivers/gpu/drm/drm_debugfs_crc.c
413   :doc: CRC ABI
414
415.. kernel-doc:: drivers/gpu/drm/drm_debugfs_crc.c
416   :export:
417
418Debugfs Support
419---------------
420
421.. kernel-doc:: include/drm/drm_debugfs.h
422   :internal:
423
424.. kernel-doc:: drivers/gpu/drm/drm_debugfs.c
425   :export:
426
427Sysfs Support
428=============
429
430.. kernel-doc:: drivers/gpu/drm/drm_sysfs.c
431   :doc: overview
432
433.. kernel-doc:: drivers/gpu/drm/drm_sysfs.c
434   :export:
435
436
437VBlank event handling
438=====================
439
440The DRM core exposes two vertical blank related ioctls:
441
442DRM_IOCTL_WAIT_VBLANK
443    This takes a struct drm_wait_vblank structure as its argument, and
444    it is used to block or request a signal when a specified vblank
445    event occurs.
446
447DRM_IOCTL_MODESET_CTL
448    This was only used for user-mode-settind drivers around modesetting
449    changes to allow the kernel to update the vblank interrupt after
450    mode setting, since on many devices the vertical blank counter is
451    reset to 0 at some point during modeset. Modern drivers should not
452    call this any more since with kernel mode setting it is a no-op.
453
454Userspace API Structures
455========================
456
457.. kernel-doc:: include/uapi/drm/drm_mode.h
458   :doc: overview
459
 
 
 
 
 
 
 
 
 
 
 
 
 
460.. kernel-doc:: include/uapi/drm/drm.h
461   :internal:
462
463.. kernel-doc:: include/uapi/drm/drm_mode.h
464   :internal: