573 lines · plain
1.. Copyright 2020 DisplayLink (UK) Ltd.2 3===================4Userland interfaces5===================6 7The DRM core exports several interfaces to applications, generally8intended to be used through corresponding libdrm wrapper functions. In9addition, drivers export device-specific interfaces for use by userspace10drivers & device-aware applications through ioctls and sysfs files.11 12External interfaces include: memory mapping, context management, DMA13operations, AGP management, vblank control, fence management, memory14management, and output management.15 16Cover generic ioctls and sysfs layout here. We only need high-level17info, since man pages should cover the rest.18 19libdrm Device Lookup20====================21 22.. kernel-doc:: drivers/gpu/drm/drm_ioctl.c23 :doc: getunique and setversion story24 25 26.. _drm_primary_node:27 28Primary Nodes, DRM Master and Authentication29============================================30 31.. kernel-doc:: drivers/gpu/drm/drm_auth.c32 :doc: master and authentication33 34.. kernel-doc:: drivers/gpu/drm/drm_auth.c35 :export:36 37.. kernel-doc:: include/drm/drm_auth.h38 :internal:39 40 41.. _drm_leasing:42 43DRM Display Resource Leasing44============================45 46.. kernel-doc:: drivers/gpu/drm/drm_lease.c47 :doc: drm leasing48 49Open-Source Userspace Requirements50==================================51 52The DRM subsystem has stricter requirements than most other kernel subsystems on53what the userspace side for new uAPI needs to look like. This section here54explains what exactly those requirements are, and why they exist.55 56The short summary is that any addition of DRM uAPI requires corresponding57open-sourced userspace patches, and those patches must be reviewed and ready for58merging into a suitable and canonical upstream project.59 60GFX devices (both display and render/GPU side) are really complex bits of61hardware, with userspace and kernel by necessity having to work together really62closely. The interfaces, for rendering and modesetting, must be extremely wide63and flexible, and therefore it is almost always impossible to precisely define64them for every possible corner case. This in turn makes it really practically65infeasible to differentiate between behaviour that's required by userspace, and66which must not be changed to avoid regressions, and behaviour which is only an67accidental artifact of the current implementation.68 69Without access to the full source code of all userspace users that means it70becomes impossible to change the implementation details, since userspace could71depend upon the accidental behaviour of the current implementation in minute72details. And debugging such regressions without access to source code is pretty73much impossible. As a consequence this means:74 75- The Linux kernel's "no regression" policy holds in practice only for76 open-source userspace of the DRM subsystem. DRM developers are perfectly fine77 if closed-source blob drivers in userspace use the same uAPI as the open78 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, lead80 to breakage.81 82- Any new userspace interface must have an open-source implementation as83 demonstration vehicle.84 85The other reason for requiring open-source userspace is uAPI review. Since the86kernel and userspace parts of a GFX stack must work together so closely, code87review can only assess whether a new interface achieves its goals by looking at88both sides. Making sure that the interface indeed covers the use-case fully89leads to a few additional requirements:90 91- The open-source userspace must not be a toy/test application, but the real92 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 to94 assess the fitness of a proposed interface.95 96- The userspace side must be fully reviewed and tested to the standards of that97 userspace project. For e.g. mesa this means piglit testcases and review on the98 mailing list. This is again to ensure that the new interface actually gets the99 job done. The userspace-side reviewer should also provide an Acked-by on the100 kernel uAPI patch indicating that they believe the proposed uAPI is sound and101 sufficiently documented and validated for userspace's consumption.102 103- The userspace patches must be against the canonical upstream, not some vendor104 fork. This is to make sure that no one cheats on the review and testing105 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** the109 userspace patches land. uAPI always flows from the kernel, doing things the110 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 shared113pain and experience with uAPI added hastily, and almost always regretted about114just as fast. GFX devices change really fast, requiring a paradigm shift and115entire new set of uAPI interfaces every few years at least. Together with the116Linux kernel's guarantee to keep existing userspace running for 10+ years this117is already rather painful for the DRM subsystem, with multiple different uAPIs118for the same thing co-existing. If we add a few more complete mistakes into the119mix every year it would be entirely unmanageable.120 121.. _drm_render_node:122 123Render nodes124============125 126DRM core provides multiple character-devices for user-space to use.127Depending on which device is opened, user-space can perform a different128set of operations (mainly ioctls). The primary node is always created129and called card<num>. Additionally, a currently unused control node,130called controlD<num> is also created. The primary node provides all131legacy operations and historically was the only interface used by132userspace. With KMS, the control node was introduced. However, the133planned KMS control interface has never been written and so the control134node stays unused to date.135 136With the increased use of offscreen renderers and GPGPU applications,137clients no longer require running compositors or graphics servers to138make use of a GPU. But the DRM API required unprivileged clients to139authenticate to a DRM-Master prior to getting GPU access. To avoid this140step and to grant clients GPU access without authenticating, render141nodes were introduced. Render nodes solely serve render clients, that142is, no modesetting or privileged ioctls can be issued on render nodes.143Only non-global rendering commands are allowed. If a driver supports144render nodes, it must advertise it via the DRIVER_RENDER DRM driver145capability. If not supported, the primary node must be used for render146clients together with the legacy drmAuth authentication procedure.147 148If a driver advertises render node support, DRM core will create a149separate render node called renderD<num>. There will be one render node150per device. No ioctls except PRIME-related ioctls will be allowed on151this node. Especially GEM_OPEN will be explicitly prohibited. For a152complete list of driver-independent ioctls that can be used on render153nodes, see the ioctls marked DRM_RENDER_ALLOW in drm_ioctl.c Render154nodes are designed to avoid the buffer-leaks, which occur if clients155guess the flink names or mmap offsets on the legacy interface.156Additionally to this basic interface, drivers must mark their157driver-dependent render-only ioctls as DRM_RENDER_ALLOW so render158clients can use them. Driver authors must be careful not to allow any159privileged ioctls on render nodes.160 161With render nodes, user-space can now control access to the render node162via basic file-system access-modes. A running graphics server which163authenticates clients on the privileged primary/legacy node is no longer164required. Instead, a client can open the render node and is immediately165granted GPU access. Communication between clients (or servers) is done166via PRIME. FLINK from render node to legacy node is not supported. New167clients must not use the insecure FLINK interface.168 169Besides dropping all modeset/global ioctls, render nodes also drop the170DRM-Master concept. There is no reason to associate render clients with171a DRM-Master as they are independent of any graphics server. Besides,172they must work without any running master, anyway. Drivers must be able173to run without a master object if they support render nodes. If, on the174other hand, a driver requires shared state between clients which is175visible to user-space and accessible beyond open-file boundaries, they176cannot support render nodes.177 178Device Hot-Unplug179=================180 181.. note::182 The following is the plan. Implementation is not there yet183 (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 end187user is able to hot-unplug this kind of devices while they are being188used, and expects that the very least the machine does not crash. Any189damage from hot-unplugging a DRM device needs to be limited as much as190possible and userspace must be given the chance to handle it if it wants191to. Ideally, unplugging a DRM device still lets a desktop continue to192run, but that is going to need explicit support throughout the whole193graphics stack: from kernel and userspace drivers, through display194servers, via window system protocols, and in applications and libraries.195 196Other scenarios that should lead to the same are: unrecoverable GPU197crash, PCI device disappearing off the bus, or forced unbind of a driver198from the physical device.199 200In other words, from userspace perspective everything needs to keep on201working more or less, until userspace stops using the disappeared DRM202device and closes it completely. Userspace will learn of the device203disappearance from the device removed uevent, ioctls returning ENODEV204(or driver-specific ioctls returning driver-specific things), or open()205returning ENXIO.206 207Only after userspace has closed all relevant DRM device and dmabuf file208descriptors and removed all mmaps, the DRM driver can tear down its209instance for the device that no longer exists. If the same physical210device somehow comes back in the mean time, it shall be a new DRM211device.212 213Similar to PIDs, chardev minor numbers are not recycled immediately. A214new DRM device always picks the next free minor number compared to the215previous one allocated, and wraps around when minor numbers are216exhausted.217 218The goal raises at least the following requirements for the kernel and219drivers.220 221Requirements for KMS UAPI222-------------------------223 224- KMS connectors must change their status to disconnected.225 226- Legacy modesets and pageflips, and atomic commits, both real and227 TEST_ONLY, and any other ioctls either fail with ENODEV or fake228 success.229 230- Pending non-blocking KMS operations deliver the DRM events userspace231 is expecting. This applies also to ioctls that faked success.232 233- open() on a device node whose underlying device has disappeared will234 fail with ENXIO.235 236- Attempting to create a DRM lease on a disappeared DRM device will237 fail with ENODEV. Existing DRM leases remain and work as listed238 above.239 240Requirements for Render and Cross-Device UAPI241---------------------------------------------242 243- All GPU jobs that can no longer run must have their fences244 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 device248 disappears (OpenGL, GL ES: `GL_KHR_robustness`_; `Vulkan`_:249 VK_ERROR_DEVICE_LOST; etc.). DRM drivers are free to implement this250 behaviour the way they see best, e.g. returning failures in251 driver-specific ioctls and handling those in userspace drivers, or252 rely on uevents, and so on.253 254- dmabuf which point to memory that has disappeared will either fail to255 import with ENODEV or continue to be successfully imported if it would256 have succeeded before the disappearance. See also about memory maps257 below for already imported dmabufs.258 259- Attempting to import a dmabuf to a disappeared device will either fail260 with ENODEV or succeed if it would have succeeded without the261 disappearance.262 263- open() on a device node whose underlying device has disappeared will264 fail with ENXIO.265 266.. _GL_KHR_robustness: https://www.khronos.org/registry/OpenGL/extensions/KHR/KHR_robustness.txt267.. _Vulkan: https://www.khronos.org/vulkan/268 269Requirements for Memory Maps270----------------------------271 272Memory maps have further requirements that apply to both existing maps273and maps created after the device has disappeared. If the underlying274memory disappears, the map is created or modified such that reads and275writes will still complete successfully but the result is undefined.276This applies to both userspace mmap()'d memory and memory pointed to by277dmabuf which might be mapped to other devices (cross-device dmabuf278imports).279 280Raising SIGBUS is not an option, because userspace cannot realistically281handle it. Signal handlers are global, which makes them extremely282difficult to use correctly from libraries like those that Mesa produces.283Signal handlers are not composable, you can't have different handlers284for GPU1 and GPU2 from different vendors, and a third handler for285mmapped regular files. Threads cause additional pain with signal286handling as well.287 288Device reset289============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 errors293require resetting the device in order to make the device usable again. This294section describes the expectations for DRM and usermode drivers when a295device resets and how to propagate the reset status.296 297Device resets can not be disabled without tainting the kernel, which can lead to298hanging the entire kernel through shrinkers/mmu_notifiers. Userspace role in299device resets is to propagate the message to the application and apply any300special policy for blocking guilty applications, if any. Corollary is that301debugging a hung GPU context require hardware support to be able to preempt such302a GPU context while it's stopped.303 304Kernel Mode Driver305------------------306 307The KMD is responsible for checking if the device needs a reset, and to perform308it as needed. Usually a hang is detected when a job gets stuck executing. KMD309should keep track of resets, because userspace can query any time about the310reset status for a specific context. This is needed to propagate to the rest of311the stack that a reset has happened. Currently, this is implemented by each312driver separately, with no common DRM interface. Ideally this should be properly313integrated at DRM scheduler to provide a common ground for all drivers. After a314reset, KMD should reject new command submissions for affected contexts.315 316User Mode Driver317----------------318 319After command submission, UMD should check if the submission was accepted or320rejected. After a reset, KMD should reject submissions, and UMD can issue an321ioctl to the KMD to check the reset status, and this can be checked more often322if the UMD requires it. After detecting a reset, UMD will then proceed to report323it to the application using the appropriate API error code, as explained in the324section below about robustness.325 326Robustness327----------328 329The only way to try to keep a graphical API context working after a reset is if330it complies with the robustness aspects of the graphical API that it is using.331 332Graphical APIs provide ways to applications to deal with device resets. However,333there is no guarantee that the app will use such features correctly, and a334userspace that doesn't support robust interfaces (like a non-robust335OpenGL context or API without any robustness support like libva) leave the336robustness handling entirely to the userspace driver. There is no strong337community consensus on what the userspace driver should do in that case,338since all reasonable approaches have some clear downsides.339 340OpenGL341~~~~~~342 343Apps using OpenGL should use the available robust interfaces, like the344extension ``GL_ARB_robustness`` (or ``GL_EXT_robustness`` for OpenGL ES). This345interface tells if a reset has happened, and if so, all the context state is346considered lost and the app proceeds by creating new ones. There's no consensus347on what to do to if robustness is not in use.348 349Vulkan350~~~~~~351 352Apps using Vulkan should check for ``VK_ERROR_DEVICE_LOST`` for submissions.353This error code means, among other things, that a device reset has happened and354it needs to recreate the contexts to keep going.355 356Reporting causes of resets357--------------------------358 359Apart from propagating the reset through the stack so apps can recover, it's360really useful for driver developers to learn more about what caused the reset in361the first place. DRM devices should make use of devcoredump to store relevant362information about the reset, so this information can be added to user bug363reports.364 365.. _drm_driver_ioctl:366 367IOCTL Support on Device Nodes368=============================369 370.. kernel-doc:: drivers/gpu/drm/drm_ioctl.c371 :doc: driver specific ioctls372 373Recommended IOCTL Return Values374-------------------------------375 376In theory a driver's IOCTL callback is only allowed to return very few error377codes. In practice it's good to abuse a few more. This section documents common378practice within the DRM subsystem:379 380ENOENT:381 Strictly this should only be used when a file doesn't exist e.g. when382 calling the open() syscall. We reuse that to signal any kind of object383 lookup failure, e.g. for unknown GEM buffer object handles, unknown KMS384 object handles and similar cases.385 386ENOSPC:387 Some drivers use this to differentiate "out of kernel memory" from "out388 of VRAM". Sometimes also applies to other limited gpu resources used for389 rendering (e.g. when you have a special limited compression buffer).390 Sometimes resource allocation/reservation issues in command submission391 IOCTLs are also signalled through EDEADLK.392 393 Simply running out of kernel/system memory is signalled through ENOMEM.394 395EPERM/EACCES:396 Returned for an operation that is valid, but needs more privileges.397 E.g. root-only or much more common, DRM master-only operations return398 this when called by unpriviledged clients. There's no clear399 difference between EACCES and EPERM.400 401ENODEV:402 The device is not present anymore or is not yet fully initialized.403 404EOPNOTSUPP:405 Feature (like PRIME, modesetting, GEM) is not supported by the driver.406 407ENXIO:408 Remote failure, either a hardware transaction (like i2c), but also used409 when the exporting driver of a shared dma-buf or fence doesn't support a410 feature needed.411 412EINTR:413 DRM drivers assume that userspace restarts all IOCTLs. Any DRM IOCTL can414 return EINTR and in such a case should be restarted with the IOCTL415 parameters left unchanged.416 417EIO:418 The GPU died and couldn't be resurrected through a reset. Modesetting419 hardware failures are signalled through the "link status" connector420 property.421 422EINVAL:423 Catch-all for anything that is an invalid argument combination which424 cannot work.425 426IOCTL also use other error codes like ETIME, EFAULT, EBUSY, ENOTTY but their427usage is in line with the common meanings. The above list tries to just document428DRM specific patterns. Note that ENOTTY has the slightly unintuitive meaning of429"this IOCTL does not exist", and is used exactly as such in DRM.430 431.. kernel-doc:: include/drm/drm_ioctl.h432 :internal:433 434.. kernel-doc:: drivers/gpu/drm/drm_ioctl.c435 :export:436 437.. kernel-doc:: drivers/gpu/drm/drm_ioc32.c438 :export:439 440Testing and validation441======================442 443Testing Requirements for userspace API444--------------------------------------445 446New cross-driver userspace interface extensions, like new IOCTL, new KMS447properties, new files in sysfs or anything else that constitutes an API change448should have driver-agnostic testcases in IGT for that feature, if such a test449can be reasonably made using IGT for the target hardware.450 451Validating changes with IGT452---------------------------453 454There's a collection of tests that aims to cover the whole functionality of455DRM drivers and that can be used to check that changes to DRM drivers or the456core don't regress existing functionality. This test suite is called IGT and457its code and instructions to build and run can be found in458https://gitlab.freedesktop.org/drm/igt-gpu-tools/.459 460Using VKMS to test DRM API461--------------------------462 463VKMS is a software-only model of a KMS driver that is useful for testing464and for running compositors. VKMS aims to enable a virtual display without465the need for a hardware display capability. These characteristics made VKMS466a perfect tool for validating the DRM core behavior and also support the467compositor developer. VKMS makes it possible to test DRM functions in a468virtual machine without display, simplifying the validation of some of the469core changes.470 471To Validate changes in DRM API with VKMS, start setting the kernel: make472sure to enable VKMS module; compile the kernel with the VKMS enabled and473install it in the target machine. VKMS can be run in a Virtual Machine474(QEMU, virtme or similar). It's recommended the use of KVM with the minimum475of 1GB of RAM and four cores.476 477It's possible to run the IGT-tests in a VM in two ways:478 479 1. Use IGT inside a VM480 2. Use IGT from the host machine and write the results in a shared directory.481 482Following is an example of using a VM with a shared directory with483the host machine to run igt-tests. This example uses virtme::484 485 $ virtme-run --rwdir /path/for/shared_dir --kdir=path/for/kernel/directory --mods=auto486 487Run the igt-tests in the guest machine. This example runs the 'kms_flip'488tests::489 490 $ /path/for/igt-gpu-tools/scripts/run-tests.sh -p -s -t "kms_flip.*" -v491 492In this example, instead of building the igt_runner, Piglit is used493(-p option). It creates an HTML summary of the test results and saves494them in the folder "igt-gpu-tools/results". It executes only the igt-tests495matching the -t option.496 497Display CRC Support498-------------------499 500.. kernel-doc:: drivers/gpu/drm/drm_debugfs_crc.c501 :doc: CRC ABI502 503.. kernel-doc:: drivers/gpu/drm/drm_debugfs_crc.c504 :export:505 506Debugfs Support507---------------508 509.. kernel-doc:: include/drm/drm_debugfs.h510 :internal:511 512.. kernel-doc:: drivers/gpu/drm/drm_debugfs.c513 :export:514 515Sysfs Support516=============517 518.. kernel-doc:: drivers/gpu/drm/drm_sysfs.c519 :doc: overview520 521.. kernel-doc:: drivers/gpu/drm/drm_sysfs.c522 :export:523 524 525VBlank event handling526=====================527 528The DRM core exposes two vertical blank related ioctls:529 530:c:macro:`DRM_IOCTL_WAIT_VBLANK`531 This takes a struct drm_wait_vblank structure as its argument, and532 it is used to block or request a signal when a specified vblank533 event occurs.534 535:c:macro:`DRM_IOCTL_MODESET_CTL`536 This was only used for user-mode-settind drivers around modesetting537 changes to allow the kernel to update the vblank interrupt after538 mode setting, since on many devices the vertical blank counter is539 reset to 0 at some point during modeset. Modern drivers should not540 call this any more since with kernel mode setting it is a no-op.541 542Userspace API Structures543========================544 545.. kernel-doc:: include/uapi/drm/drm_mode.h546 :doc: overview547 548.. _crtc_index:549 550CRTC index551----------552 553CRTC's have both an object ID and an index, and they are not the same thing.554The index is used in cases where a densely packed identifier for a CRTC is555needed, for instance a bitmask of CRTC's. The member possible_crtcs of struct556drm_mode_get_plane is an example.557 558:c:macro:`DRM_IOCTL_MODE_GETRESOURCES` populates a structure with an array of559CRTC ID's, and the CRTC index is its position in this array.560 561.. kernel-doc:: include/uapi/drm/drm.h562 :internal:563 564.. kernel-doc:: include/uapi/drm/drm_mode.h565 :internal:566 567 568dma-buf interoperability569========================570 571Please see Documentation/userspace-api/dma-buf-alloc-exchange.rst for572information on how dma-buf is integrated and exposed within DRM.573