9fc8ed4ac0f49b1759ed00d4f5ce731bd35e7a55
[platform/adaptation/renesas_rcar/renesas_kernel.git] / Documentation / DocBook / drm.tmpl
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
3         "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" []>
4
5 <book id="drmDevelopersGuide">
6   <bookinfo>
7     <title>Linux DRM Developer's Guide</title>
8
9     <authorgroup>
10       <author>
11         <firstname>Jesse</firstname>
12         <surname>Barnes</surname>
13         <contrib>Initial version</contrib>
14         <affiliation>
15           <orgname>Intel Corporation</orgname>
16           <address>
17             <email>jesse.barnes@intel.com</email>
18           </address>
19         </affiliation>
20       </author>
21       <author>
22         <firstname>Laurent</firstname>
23         <surname>Pinchart</surname>
24         <contrib>Driver internals</contrib>
25         <affiliation>
26           <orgname>Ideas on board SPRL</orgname>
27           <address>
28             <email>laurent.pinchart@ideasonboard.com</email>
29           </address>
30         </affiliation>
31       </author>
32     </authorgroup>
33
34     <copyright>
35       <year>2008-2009</year>
36       <year>2012</year>
37       <holder>Intel Corporation</holder>
38       <holder>Laurent Pinchart</holder>
39     </copyright>
40
41     <legalnotice>
42       <para>
43         The contents of this file may be used under the terms of the GNU
44         General Public License version 2 (the "GPL") as distributed in
45         the kernel source COPYING file.
46       </para>
47     </legalnotice>
48
49     <revhistory>
50       <!-- Put document revisions here, newest first. -->
51       <revision>
52         <revnumber>1.0</revnumber>
53         <date>2012-07-13</date>
54         <authorinitials>LP</authorinitials>
55         <revremark>Added extensive documentation about driver internals.
56         </revremark>
57       </revision>
58     </revhistory>
59   </bookinfo>
60
61 <toc></toc>
62
63   <!-- Introduction -->
64
65   <chapter id="drmIntroduction">
66     <title>Introduction</title>
67     <para>
68       The Linux DRM layer contains code intended to support the needs
69       of complex graphics devices, usually containing programmable
70       pipelines well suited to 3D graphics acceleration.  Graphics
71       drivers in the kernel may make use of DRM functions to make
72       tasks like memory management, interrupt handling and DMA easier,
73       and provide a uniform interface to applications.
74     </para>
75     <para>
76       A note on versions: this guide covers features found in the DRM
77       tree, including the TTM memory manager, output configuration and
78       mode setting, and the new vblank internals, in addition to all
79       the regular features found in current kernels.
80     </para>
81     <para>
82       [Insert diagram of typical DRM stack here]
83     </para>
84   </chapter>
85
86   <!-- Internals -->
87
88   <chapter id="drmInternals">
89     <title>DRM Internals</title>
90     <para>
91       This chapter documents DRM internals relevant to driver authors
92       and developers working to add support for the latest features to
93       existing drivers.
94     </para>
95     <para>
96       First, we go over some typical driver initialization
97       requirements, like setting up command buffers, creating an
98       initial output configuration, and initializing core services.
99       Subsequent sections cover core internals in more detail,
100       providing implementation notes and examples.
101     </para>
102     <para>
103       The DRM layer provides several services to graphics drivers,
104       many of them driven by the application interfaces it provides
105       through libdrm, the library that wraps most of the DRM ioctls.
106       These include vblank event handling, memory
107       management, output management, framebuffer management, command
108       submission &amp; fencing, suspend/resume support, and DMA
109       services.
110     </para>
111
112   <!-- Internals: driver init -->
113
114   <sect1>
115     <title>Driver Initialization</title>
116     <para>
117       At the core of every DRM driver is a <structname>drm_driver</structname>
118       structure. Drivers typically statically initialize a drm_driver structure,
119       and then pass it to one of the <function>drm_*_init()</function> functions
120       to register it with the DRM subsystem.
121     </para>
122     <para>
123       The <structname>drm_driver</structname> structure contains static
124       information that describes the driver and features it supports, and
125       pointers to methods that the DRM core will call to implement the DRM API.
126       We will first go through the <structname>drm_driver</structname> static
127       information fields, and will then describe individual operations in
128       details as they get used in later sections.
129     </para>
130     <sect2>
131       <title>Driver Information</title>
132       <sect3>
133         <title>Driver Features</title>
134         <para>
135           Drivers inform the DRM core about their requirements and supported
136           features by setting appropriate flags in the
137           <structfield>driver_features</structfield> field. Since those flags
138           influence the DRM core behaviour since registration time, most of them
139           must be set to registering the <structname>drm_driver</structname>
140           instance.
141         </para>
142         <synopsis>u32 driver_features;</synopsis>
143         <variablelist>
144           <title>Driver Feature Flags</title>
145           <varlistentry>
146             <term>DRIVER_USE_AGP</term>
147             <listitem><para>
148               Driver uses AGP interface, the DRM core will manage AGP resources.
149             </para></listitem>
150           </varlistentry>
151           <varlistentry>
152             <term>DRIVER_REQUIRE_AGP</term>
153             <listitem><para>
154               Driver needs AGP interface to function. AGP initialization failure
155               will become a fatal error.
156             </para></listitem>
157           </varlistentry>
158           <varlistentry>
159             <term>DRIVER_PCI_DMA</term>
160             <listitem><para>
161               Driver is capable of PCI DMA, mapping of PCI DMA buffers to
162               userspace will be enabled. Deprecated.
163             </para></listitem>
164           </varlistentry>
165           <varlistentry>
166             <term>DRIVER_SG</term>
167             <listitem><para>
168               Driver can perform scatter/gather DMA, allocation and mapping of
169               scatter/gather buffers will be enabled. Deprecated.
170             </para></listitem>
171           </varlistentry>
172           <varlistentry>
173             <term>DRIVER_HAVE_DMA</term>
174             <listitem><para>
175               Driver supports DMA, the userspace DMA API will be supported.
176               Deprecated.
177             </para></listitem>
178           </varlistentry>
179           <varlistentry>
180             <term>DRIVER_HAVE_IRQ</term><term>DRIVER_IRQ_SHARED</term>
181             <listitem><para>
182               DRIVER_HAVE_IRQ indicates whether the driver has an IRQ handler
183               managed by the DRM Core. The core will support simple IRQ handler
184               installation when the flag is set. The installation process is
185               described in <xref linkend="drm-irq-registration"/>.</para>
186               <para>DRIVER_IRQ_SHARED indicates whether the device &amp; handler
187               support shared IRQs (note that this is required of PCI  drivers).
188             </para></listitem>
189           </varlistentry>
190           <varlistentry>
191             <term>DRIVER_GEM</term>
192             <listitem><para>
193               Driver use the GEM memory manager.
194             </para></listitem>
195           </varlistentry>
196           <varlistentry>
197             <term>DRIVER_MODESET</term>
198             <listitem><para>
199               Driver supports mode setting interfaces (KMS).
200             </para></listitem>
201           </varlistentry>
202           <varlistentry>
203             <term>DRIVER_PRIME</term>
204             <listitem><para>
205               Driver implements DRM PRIME buffer sharing.
206             </para></listitem>
207           </varlistentry>
208         </variablelist>
209       </sect3>
210       <sect3>
211         <title>Major, Minor and Patchlevel</title>
212         <synopsis>int major;
213 int minor;
214 int patchlevel;</synopsis>
215         <para>
216           The DRM core identifies driver versions by a major, minor and patch
217           level triplet. The information is printed to the kernel log at
218           initialization time and passed to userspace through the
219           DRM_IOCTL_VERSION ioctl.
220         </para>
221         <para>
222           The major and minor numbers are also used to verify the requested driver
223           API version passed to DRM_IOCTL_SET_VERSION. When the driver API changes
224           between minor versions, applications can call DRM_IOCTL_SET_VERSION to
225           select a specific version of the API. If the requested major isn't equal
226           to the driver major, or the requested minor is larger than the driver
227           minor, the DRM_IOCTL_SET_VERSION call will return an error. Otherwise
228           the driver's set_version() method will be called with the requested
229           version.
230         </para>
231       </sect3>
232       <sect3>
233         <title>Name, Description and Date</title>
234         <synopsis>char *name;
235 char *desc;
236 char *date;</synopsis>
237         <para>
238           The driver name is printed to the kernel log at initialization time,
239           used for IRQ registration and passed to userspace through
240           DRM_IOCTL_VERSION.
241         </para>
242         <para>
243           The driver description is a purely informative string passed to
244           userspace through the DRM_IOCTL_VERSION ioctl and otherwise unused by
245           the kernel.
246         </para>
247         <para>
248           The driver date, formatted as YYYYMMDD, is meant to identify the date of
249           the latest modification to the driver. However, as most drivers fail to
250           update it, its value is mostly useless. The DRM core prints it to the
251           kernel log at initialization time and passes it to userspace through the
252           DRM_IOCTL_VERSION ioctl.
253         </para>
254       </sect3>
255     </sect2>
256     <sect2>
257       <title>Driver Load</title>
258       <para>
259         The <methodname>load</methodname> method is the driver and device
260         initialization entry point. The method is responsible for allocating and
261         initializing driver private data, specifying supported performance
262         counters, performing resource allocation and mapping (e.g. acquiring
263         clocks, mapping registers or allocating command buffers), initializing
264         the memory manager (<xref linkend="drm-memory-management"/>), installing
265         the IRQ handler (<xref linkend="drm-irq-registration"/>), setting up
266         vertical blanking handling (<xref linkend="drm-vertical-blank"/>), mode
267         setting (<xref linkend="drm-mode-setting"/>) and initial output
268         configuration (<xref linkend="drm-kms-init"/>).
269       </para>
270       <note><para>
271         If compatibility is a concern (e.g. with drivers converted over from
272         User Mode Setting to Kernel Mode Setting), care must be taken to prevent
273         device initialization and control that is incompatible with currently
274         active userspace drivers. For instance, if user level mode setting
275         drivers are in use, it would be problematic to perform output discovery
276         &amp; configuration at load time. Likewise, if user-level drivers
277         unaware of memory management are in use, memory management and command
278         buffer setup may need to be omitted. These requirements are
279         driver-specific, and care needs to be taken to keep both old and new
280         applications and libraries working.
281       </para></note>
282       <synopsis>int (*load) (struct drm_device *, unsigned long flags);</synopsis>
283       <para>
284         The method takes two arguments, a pointer to the newly created
285         <structname>drm_device</structname> and flags. The flags are used to
286         pass the <structfield>driver_data</structfield> field of the device id
287         corresponding to the device passed to <function>drm_*_init()</function>.
288         Only PCI devices currently use this, USB and platform DRM drivers have
289         their <methodname>load</methodname> method called with flags to 0.
290       </para>
291       <sect3>
292         <title>Driver Private &amp; Performance Counters</title>
293         <para>
294           The driver private hangs off the main
295           <structname>drm_device</structname> structure and can be used for
296           tracking various device-specific bits of information, like register
297           offsets, command buffer status, register state for suspend/resume, etc.
298           At load time, a driver may simply allocate one and set
299           <structname>drm_device</structname>.<structfield>dev_priv</structfield>
300           appropriately; it should be freed and
301           <structname>drm_device</structname>.<structfield>dev_priv</structfield>
302           set to NULL when the driver is unloaded.
303         </para>
304         <para>
305           DRM supports several counters which were used for rough performance
306           characterization. This stat counter system is deprecated and should not
307           be used. If performance monitoring is desired, the developer should
308           investigate and potentially enhance the kernel perf and tracing
309           infrastructure to export GPU related performance information for
310           consumption by performance monitoring tools and applications.
311         </para>
312       </sect3>
313       <sect3 id="drm-irq-registration">
314         <title>IRQ Registration</title>
315         <para>
316           The DRM core tries to facilitate IRQ handler registration and
317           unregistration by providing <function>drm_irq_install</function> and
318           <function>drm_irq_uninstall</function> functions. Those functions only
319           support a single interrupt per device, devices that use more than one
320           IRQs need to be handled manually.
321         </para>
322         <sect4>
323           <title>Managed IRQ Registration</title>
324           <para>
325             Both the <function>drm_irq_install</function> and
326             <function>drm_irq_uninstall</function> functions get the device IRQ by
327             calling <function>drm_dev_to_irq</function>. This inline function will
328             call a bus-specific operation to retrieve the IRQ number. For platform
329             devices, <function>platform_get_irq</function>(..., 0) is used to
330             retrieve the IRQ number.
331           </para>
332           <para>
333             <function>drm_irq_install</function> starts by calling the
334             <methodname>irq_preinstall</methodname> driver operation. The operation
335             is optional and must make sure that the interrupt will not get fired by
336             clearing all pending interrupt flags or disabling the interrupt.
337           </para>
338           <para>
339             The IRQ will then be requested by a call to
340             <function>request_irq</function>. If the DRIVER_IRQ_SHARED driver
341             feature flag is set, a shared (IRQF_SHARED) IRQ handler will be
342             requested.
343           </para>
344           <para>
345             The IRQ handler function must be provided as the mandatory irq_handler
346             driver operation. It will get passed directly to
347             <function>request_irq</function> and thus has the same prototype as all
348             IRQ handlers. It will get called with a pointer to the DRM device as the
349             second argument.
350           </para>
351           <para>
352             Finally the function calls the optional
353             <methodname>irq_postinstall</methodname> driver operation. The operation
354             usually enables interrupts (excluding the vblank interrupt, which is
355             enabled separately), but drivers may choose to enable/disable interrupts
356             at a different time.
357           </para>
358           <para>
359             <function>drm_irq_uninstall</function> is similarly used to uninstall an
360             IRQ handler. It starts by waking up all processes waiting on a vblank
361             interrupt to make sure they don't hang, and then calls the optional
362             <methodname>irq_uninstall</methodname> driver operation. The operation
363             must disable all hardware interrupts. Finally the function frees the IRQ
364             by calling <function>free_irq</function>.
365           </para>
366         </sect4>
367         <sect4>
368           <title>Manual IRQ Registration</title>
369           <para>
370             Drivers that require multiple interrupt handlers can't use the managed
371             IRQ registration functions. In that case IRQs must be registered and
372             unregistered manually (usually with the <function>request_irq</function>
373             and <function>free_irq</function> functions, or their devm_* equivalent).
374           </para>
375           <para>
376             When manually registering IRQs, drivers must not set the DRIVER_HAVE_IRQ
377             driver feature flag, and must not provide the
378             <methodname>irq_handler</methodname> driver operation. They must set the
379             <structname>drm_device</structname> <structfield>irq_enabled</structfield>
380             field to 1 upon registration of the IRQs, and clear it to 0 after
381             unregistering the IRQs.
382           </para>
383         </sect4>
384       </sect3>
385       <sect3>
386         <title>Memory Manager Initialization</title>
387         <para>
388           Every DRM driver requires a memory manager which must be initialized at
389           load time. DRM currently contains two memory managers, the Translation
390           Table Manager (TTM) and the Graphics Execution Manager (GEM).
391           This document describes the use of the GEM memory manager only. See
392           <xref linkend="drm-memory-management"/> for details.
393         </para>
394       </sect3>
395       <sect3>
396         <title>Miscellaneous Device Configuration</title>
397         <para>
398           Another task that may be necessary for PCI devices during configuration
399           is mapping the video BIOS. On many devices, the VBIOS describes device
400           configuration, LCD panel timings (if any), and contains flags indicating
401           device state. Mapping the BIOS can be done using the pci_map_rom() call,
402           a convenience function that takes care of mapping the actual ROM,
403           whether it has been shadowed into memory (typically at address 0xc0000)
404           or exists on the PCI device in the ROM BAR. Note that after the ROM has
405           been mapped and any necessary information has been extracted, it should
406           be unmapped; on many devices, the ROM address decoder is shared with
407           other BARs, so leaving it mapped could cause undesired behaviour like
408           hangs or memory corruption.
409   <!--!Fdrivers/pci/rom.c pci_map_rom-->
410         </para>
411       </sect3>
412     </sect2>
413   </sect1>
414
415   <!-- Internals: memory management -->
416
417   <sect1 id="drm-memory-management">
418     <title>Memory management</title>
419     <para>
420       Modern Linux systems require large amount of graphics memory to store
421       frame buffers, textures, vertices and other graphics-related data. Given
422       the very dynamic nature of many of that data, managing graphics memory
423       efficiently is thus crucial for the graphics stack and plays a central
424       role in the DRM infrastructure.
425     </para>
426     <para>
427       The DRM core includes two memory managers, namely Translation Table Maps
428       (TTM) and Graphics Execution Manager (GEM). TTM was the first DRM memory
429       manager to be developed and tried to be a one-size-fits-them all
430       solution. It provides a single userspace API to accommodate the need of
431       all hardware, supporting both Unified Memory Architecture (UMA) devices
432       and devices with dedicated video RAM (i.e. most discrete video cards).
433       This resulted in a large, complex piece of code that turned out to be
434       hard to use for driver development.
435     </para>
436     <para>
437       GEM started as an Intel-sponsored project in reaction to TTM's
438       complexity. Its design philosophy is completely different: instead of
439       providing a solution to every graphics memory-related problems, GEM
440       identified common code between drivers and created a support library to
441       share it. GEM has simpler initialization and execution requirements than
442       TTM, but has no video RAM management capabitilies and is thus limited to
443       UMA devices.
444     </para>
445     <sect2>
446       <title>The Translation Table Manager (TTM)</title>
447       <para>
448         TTM design background and information belongs here.
449       </para>
450       <sect3>
451         <title>TTM initialization</title>
452         <warning><para>This section is outdated.</para></warning>
453         <para>
454           Drivers wishing to support TTM must fill out a drm_bo_driver
455           structure. The structure contains several fields with function
456           pointers for initializing the TTM, allocating and freeing memory,
457           waiting for command completion and fence synchronization, and memory
458           migration. See the radeon_ttm.c file for an example of usage.
459         </para>
460         <para>
461           The ttm_global_reference structure is made up of several fields:
462         </para>
463         <programlisting>
464           struct ttm_global_reference {
465                 enum ttm_global_types global_type;
466                 size_t size;
467                 void *object;
468                 int (*init) (struct ttm_global_reference *);
469                 void (*release) (struct ttm_global_reference *);
470           };
471         </programlisting>
472         <para>
473           There should be one global reference structure for your memory
474           manager as a whole, and there will be others for each object
475           created by the memory manager at runtime.  Your global TTM should
476           have a type of TTM_GLOBAL_TTM_MEM.  The size field for the global
477           object should be sizeof(struct ttm_mem_global), and the init and
478           release hooks should point at your driver-specific init and
479           release routines, which probably eventually call
480           ttm_mem_global_init and ttm_mem_global_release, respectively.
481         </para>
482         <para>
483           Once your global TTM accounting structure is set up and initialized
484           by calling ttm_global_item_ref() on it,
485           you need to create a buffer object TTM to
486           provide a pool for buffer object allocation by clients and the
487           kernel itself.  The type of this object should be TTM_GLOBAL_TTM_BO,
488           and its size should be sizeof(struct ttm_bo_global).  Again,
489           driver-specific init and release functions may be provided,
490           likely eventually calling ttm_bo_global_init() and
491           ttm_bo_global_release(), respectively.  Also, like the previous
492           object, ttm_global_item_ref() is used to create an initial reference
493           count for the TTM, which will call your initialization function.
494         </para>
495       </sect3>
496     </sect2>
497     <sect2 id="drm-gem">
498       <title>The Graphics Execution Manager (GEM)</title>
499       <para>
500         The GEM design approach has resulted in a memory manager that doesn't
501         provide full coverage of all (or even all common) use cases in its
502         userspace or kernel API. GEM exposes a set of standard memory-related
503         operations to userspace and a set of helper functions to drivers, and let
504         drivers implement hardware-specific operations with their own private API.
505       </para>
506       <para>
507         The GEM userspace API is described in the
508         <ulink url="http://lwn.net/Articles/283798/"><citetitle>GEM - the Graphics
509         Execution Manager</citetitle></ulink> article on LWN. While slightly
510         outdated, the document provides a good overview of the GEM API principles.
511         Buffer allocation and read and write operations, described as part of the
512         common GEM API, are currently implemented using driver-specific ioctls.
513       </para>
514       <para>
515         GEM is data-agnostic. It manages abstract buffer objects without knowing
516         what individual buffers contain. APIs that require knowledge of buffer
517         contents or purpose, such as buffer allocation or synchronization
518         primitives, are thus outside of the scope of GEM and must be implemented
519         using driver-specific ioctls.
520       </para>
521       <para>
522         On a fundamental level, GEM involves several operations:
523         <itemizedlist>
524           <listitem>Memory allocation and freeing</listitem>
525           <listitem>Command execution</listitem>
526           <listitem>Aperture management at command execution time</listitem>
527         </itemizedlist>
528         Buffer object allocation is relatively straightforward and largely
529         provided by Linux's shmem layer, which provides memory to back each
530         object.
531       </para>
532       <para>
533         Device-specific operations, such as command execution, pinning, buffer
534         read &amp; write, mapping, and domain ownership transfers are left to
535         driver-specific ioctls.
536       </para>
537       <sect3>
538         <title>GEM Initialization</title>
539         <para>
540           Drivers that use GEM must set the DRIVER_GEM bit in the struct
541           <structname>drm_driver</structname>
542           <structfield>driver_features</structfield> field. The DRM core will
543           then automatically initialize the GEM core before calling the
544           <methodname>load</methodname> operation. Behind the scene, this will
545           create a DRM Memory Manager object which provides an address space
546           pool for object allocation.
547         </para>
548         <para>
549           In a KMS configuration, drivers need to allocate and initialize a
550           command ring buffer following core GEM initialization if required by
551           the hardware. UMA devices usually have what is called a "stolen"
552           memory region, which provides space for the initial framebuffer and
553           large, contiguous memory regions required by the device. This space is
554           typically not managed by GEM, and must be initialized separately into
555           its own DRM MM object.
556         </para>
557       </sect3>
558       <sect3>
559         <title>GEM Objects Creation</title>
560         <para>
561           GEM splits creation of GEM objects and allocation of the memory that
562           backs them in two distinct operations.
563         </para>
564         <para>
565           GEM objects are represented by an instance of struct
566           <structname>drm_gem_object</structname>. Drivers usually need to extend
567           GEM objects with private information and thus create a driver-specific
568           GEM object structure type that embeds an instance of struct
569           <structname>drm_gem_object</structname>.
570         </para>
571         <para>
572           To create a GEM object, a driver allocates memory for an instance of its
573           specific GEM object type and initializes the embedded struct
574           <structname>drm_gem_object</structname> with a call to
575           <function>drm_gem_object_init</function>. The function takes a pointer to
576           the DRM device, a pointer to the GEM object and the buffer object size
577           in bytes.
578         </para>
579         <para>
580           GEM uses shmem to allocate anonymous pageable memory.
581           <function>drm_gem_object_init</function> will create an shmfs file of
582           the requested size and store it into the struct
583           <structname>drm_gem_object</structname> <structfield>filp</structfield>
584           field. The memory is used as either main storage for the object when the
585           graphics hardware uses system memory directly or as a backing store
586           otherwise.
587         </para>
588         <para>
589           Drivers are responsible for the actual physical pages allocation by
590           calling <function>shmem_read_mapping_page_gfp</function> for each page.
591           Note that they can decide to allocate pages when initializing the GEM
592           object, or to delay allocation until the memory is needed (for instance
593           when a page fault occurs as a result of a userspace memory access or
594           when the driver needs to start a DMA transfer involving the memory).
595         </para>
596         <para>
597           Anonymous pageable memory allocation is not always desired, for instance
598           when the hardware requires physically contiguous system memory as is
599           often the case in embedded devices. Drivers can create GEM objects with
600           no shmfs backing (called private GEM objects) by initializing them with
601           a call to <function>drm_gem_private_object_init</function> instead of
602           <function>drm_gem_object_init</function>. Storage for private GEM
603           objects must be managed by drivers.
604         </para>
605         <para>
606           Drivers that do not need to extend GEM objects with private information
607           can call the <function>drm_gem_object_alloc</function> function to
608           allocate and initialize a struct <structname>drm_gem_object</structname>
609           instance. The GEM core will call the optional driver
610           <methodname>gem_init_object</methodname> operation after initializing
611           the GEM object with <function>drm_gem_object_init</function>.
612           <synopsis>int (*gem_init_object) (struct drm_gem_object *obj);</synopsis>
613         </para>
614         <para>
615           No alloc-and-init function exists for private GEM objects.
616         </para>
617       </sect3>
618       <sect3>
619         <title>GEM Objects Lifetime</title>
620         <para>
621           All GEM objects are reference-counted by the GEM core. References can be
622           acquired and release by <function>calling drm_gem_object_reference</function>
623           and <function>drm_gem_object_unreference</function> respectively. The
624           caller must hold the <structname>drm_device</structname>
625           <structfield>struct_mutex</structfield> lock. As a convenience, GEM
626           provides the <function>drm_gem_object_reference_unlocked</function> and
627           <function>drm_gem_object_unreference_unlocked</function> functions that
628           can be called without holding the lock.
629         </para>
630         <para>
631           When the last reference to a GEM object is released the GEM core calls
632           the <structname>drm_driver</structname>
633           <methodname>gem_free_object</methodname> operation. That operation is
634           mandatory for GEM-enabled drivers and must free the GEM object and all
635           associated resources.
636         </para>
637         <para>
638           <synopsis>void (*gem_free_object) (struct drm_gem_object *obj);</synopsis>
639           Drivers are responsible for freeing all GEM object resources, including
640           the resources created by the GEM core. If an mmap offset has been
641           created for the object (in which case
642           <structname>drm_gem_object</structname>::<structfield>map_list</structfield>::<structfield>map</structfield>
643           is not NULL) it must be freed by a call to
644           <function>drm_gem_free_mmap_offset</function>. The shmfs backing store
645           must be released by calling <function>drm_gem_object_release</function>
646           (that function can safely be called if no shmfs backing store has been
647           created).
648         </para>
649       </sect3>
650       <sect3>
651         <title>GEM Objects Naming</title>
652         <para>
653           Communication between userspace and the kernel refers to GEM objects
654           using local handles, global names or, more recently, file descriptors.
655           All of those are 32-bit integer values; the usual Linux kernel limits
656           apply to the file descriptors.
657         </para>
658         <para>
659           GEM handles are local to a DRM file. Applications get a handle to a GEM
660           object through a driver-specific ioctl, and can use that handle to refer
661           to the GEM object in other standard or driver-specific ioctls. Closing a
662           DRM file handle frees all its GEM handles and dereferences the
663           associated GEM objects.
664         </para>
665         <para>
666           To create a handle for a GEM object drivers call
667           <function>drm_gem_handle_create</function>. The function takes a pointer
668           to the DRM file and the GEM object and returns a locally unique handle.
669           When the handle is no longer needed drivers delete it with a call to
670           <function>drm_gem_handle_delete</function>. Finally the GEM object
671           associated with a handle can be retrieved by a call to
672           <function>drm_gem_object_lookup</function>.
673         </para>
674         <para>
675           Handles don't take ownership of GEM objects, they only take a reference
676           to the object that will be dropped when the handle is destroyed. To
677           avoid leaking GEM objects, drivers must make sure they drop the
678           reference(s) they own (such as the initial reference taken at object
679           creation time) as appropriate, without any special consideration for the
680           handle. For example, in the particular case of combined GEM object and
681           handle creation in the implementation of the
682           <methodname>dumb_create</methodname> operation, drivers must drop the
683           initial reference to the GEM object before returning the handle.
684         </para>
685         <para>
686           GEM names are similar in purpose to handles but are not local to DRM
687           files. They can be passed between processes to reference a GEM object
688           globally. Names can't be used directly to refer to objects in the DRM
689           API, applications must convert handles to names and names to handles
690           using the DRM_IOCTL_GEM_FLINK and DRM_IOCTL_GEM_OPEN ioctls
691           respectively. The conversion is handled by the DRM core without any
692           driver-specific support.
693         </para>
694         <para>
695           Similar to global names, GEM file descriptors are also used to share GEM
696           objects across processes. They offer additional security: as file
697           descriptors must be explicitly sent over UNIX domain sockets to be shared
698           between applications, they can't be guessed like the globally unique GEM
699           names.
700         </para>
701         <para>
702           Drivers that support GEM file descriptors, also known as the DRM PRIME
703           API, must set the DRIVER_PRIME bit in the struct
704           <structname>drm_driver</structname>
705           <structfield>driver_features</structfield> field, and implement the
706           <methodname>prime_handle_to_fd</methodname> and
707           <methodname>prime_fd_to_handle</methodname> operations.
708         </para>
709         <para>
710           <synopsis>int (*prime_handle_to_fd)(struct drm_device *dev,
711                             struct drm_file *file_priv, uint32_t handle,
712                             uint32_t flags, int *prime_fd);
713   int (*prime_fd_to_handle)(struct drm_device *dev,
714                             struct drm_file *file_priv, int prime_fd,
715                             uint32_t *handle);</synopsis>
716           Those two operations convert a handle to a PRIME file descriptor and
717           vice versa. Drivers must use the kernel dma-buf buffer sharing framework
718           to manage the PRIME file descriptors.
719         </para>
720         <para>
721           While non-GEM drivers must implement the operations themselves, GEM
722           drivers must use the <function>drm_gem_prime_handle_to_fd</function>
723           and <function>drm_gem_prime_fd_to_handle</function> helper functions.
724           Those helpers rely on the driver
725           <methodname>gem_prime_export</methodname> and
726           <methodname>gem_prime_import</methodname> operations to create a dma-buf
727           instance from a GEM object (dma-buf exporter role) and to create a GEM
728           object from a dma-buf instance (dma-buf importer role).
729         </para>
730         <para>
731           <synopsis>struct dma_buf * (*gem_prime_export)(struct drm_device *dev,
732                                        struct drm_gem_object *obj,
733                                        int flags);
734   struct drm_gem_object * (*gem_prime_import)(struct drm_device *dev,
735                                               struct dma_buf *dma_buf);</synopsis>
736           These two operations are mandatory for GEM drivers that support DRM
737           PRIME.
738         </para>
739         <sect4>
740           <title>DRM PRIME Helper Functions Reference</title>
741 !Pdrivers/gpu/drm/drm_prime.c PRIME Helpers
742         </sect4>
743       </sect3>
744       <sect3 id="drm-gem-objects-mapping">
745         <title>GEM Objects Mapping</title>
746         <para>
747           Because mapping operations are fairly heavyweight GEM favours
748           read/write-like access to buffers, implemented through driver-specific
749           ioctls, over mapping buffers to userspace. However, when random access
750           to the buffer is needed (to perform software rendering for instance),
751           direct access to the object can be more efficient.
752         </para>
753         <para>
754           The mmap system call can't be used directly to map GEM objects, as they
755           don't have their own file handle. Two alternative methods currently
756           co-exist to map GEM objects to userspace. The first method uses a
757           driver-specific ioctl to perform the mapping operation, calling
758           <function>do_mmap</function> under the hood. This is often considered
759           dubious, seems to be discouraged for new GEM-enabled drivers, and will
760           thus not be described here.
761         </para>
762         <para>
763           The second method uses the mmap system call on the DRM file handle.
764           <synopsis>void *mmap(void *addr, size_t length, int prot, int flags, int fd,
765              off_t offset);</synopsis>
766           DRM identifies the GEM object to be mapped by a fake offset passed
767           through the mmap offset argument. Prior to being mapped, a GEM object
768           must thus be associated with a fake offset. To do so, drivers must call
769           <function>drm_gem_create_mmap_offset</function> on the object. The
770           function allocates a fake offset range from a pool and stores the
771           offset divided by PAGE_SIZE in
772           <literal>obj-&gt;map_list.hash.key</literal>. Care must be taken not to
773           call <function>drm_gem_create_mmap_offset</function> if a fake offset
774           has already been allocated for the object. This can be tested by
775           <literal>obj-&gt;map_list.map</literal> being non-NULL.
776         </para>
777         <para>
778           Once allocated, the fake offset value
779           (<literal>obj-&gt;map_list.hash.key &lt;&lt; PAGE_SHIFT</literal>)
780           must be passed to the application in a driver-specific way and can then
781           be used as the mmap offset argument.
782         </para>
783         <para>
784           The GEM core provides a helper method <function>drm_gem_mmap</function>
785           to handle object mapping. The method can be set directly as the mmap
786           file operation handler. It will look up the GEM object based on the
787           offset value and set the VMA operations to the
788           <structname>drm_driver</structname> <structfield>gem_vm_ops</structfield>
789           field. Note that <function>drm_gem_mmap</function> doesn't map memory to
790           userspace, but relies on the driver-provided fault handler to map pages
791           individually.
792         </para>
793         <para>
794           To use <function>drm_gem_mmap</function>, drivers must fill the struct
795           <structname>drm_driver</structname> <structfield>gem_vm_ops</structfield>
796           field with a pointer to VM operations.
797         </para>
798         <para>
799           <synopsis>struct vm_operations_struct *gem_vm_ops
800
801   struct vm_operations_struct {
802           void (*open)(struct vm_area_struct * area);
803           void (*close)(struct vm_area_struct * area);
804           int (*fault)(struct vm_area_struct *vma, struct vm_fault *vmf);
805   };</synopsis>
806         </para>
807         <para>
808           The <methodname>open</methodname> and <methodname>close</methodname>
809           operations must update the GEM object reference count. Drivers can use
810           the <function>drm_gem_vm_open</function> and
811           <function>drm_gem_vm_close</function> helper functions directly as open
812           and close handlers.
813         </para>
814         <para>
815           The fault operation handler is responsible for mapping individual pages
816           to userspace when a page fault occurs. Depending on the memory
817           allocation scheme, drivers can allocate pages at fault time, or can
818           decide to allocate memory for the GEM object at the time the object is
819           created.
820         </para>
821         <para>
822           Drivers that want to map the GEM object upfront instead of handling page
823           faults can implement their own mmap file operation handler.
824         </para>
825       </sect3>
826       <sect3>
827         <title>Dumb GEM Objects</title>
828         <para>
829           The GEM API doesn't standardize GEM objects creation and leaves it to
830           driver-specific ioctls. While not an issue for full-fledged graphics
831           stacks that include device-specific userspace components (in libdrm for
832           instance), this limit makes DRM-based early boot graphics unnecessarily
833           complex.
834         </para>
835         <para>
836           Dumb GEM objects partly alleviate the problem by providing a standard
837           API to create dumb buffers suitable for scanout, which can then be used
838           to create KMS frame buffers.
839         </para>
840         <para>
841           To support dumb GEM objects drivers must implement the
842           <methodname>dumb_create</methodname>,
843           <methodname>dumb_destroy</methodname> and
844           <methodname>dumb_map_offset</methodname> operations.
845         </para>
846         <itemizedlist>
847           <listitem>
848             <synopsis>int (*dumb_create)(struct drm_file *file_priv, struct drm_device *dev,
849                      struct drm_mode_create_dumb *args);</synopsis>
850             <para>
851               The <methodname>dumb_create</methodname> operation creates a GEM
852               object suitable for scanout based on the width, height and depth
853               from the struct <structname>drm_mode_create_dumb</structname>
854               argument. It fills the argument's <structfield>handle</structfield>,
855               <structfield>pitch</structfield> and <structfield>size</structfield>
856               fields with a handle for the newly created GEM object and its line
857               pitch and size in bytes.
858             </para>
859           </listitem>
860           <listitem>
861             <synopsis>int (*dumb_destroy)(struct drm_file *file_priv, struct drm_device *dev,
862                       uint32_t handle);</synopsis>
863             <para>
864               The <methodname>dumb_destroy</methodname> operation destroys a dumb
865               GEM object created by <methodname>dumb_create</methodname>.
866             </para>
867           </listitem>
868           <listitem>
869             <synopsis>int (*dumb_map_offset)(struct drm_file *file_priv, struct drm_device *dev,
870                          uint32_t handle, uint64_t *offset);</synopsis>
871             <para>
872               The <methodname>dumb_map_offset</methodname> operation associates an
873               mmap fake offset with the GEM object given by the handle and returns
874               it. Drivers must use the
875               <function>drm_gem_create_mmap_offset</function> function to
876               associate the fake offset as described in
877               <xref linkend="drm-gem-objects-mapping"/>.
878             </para>
879           </listitem>
880         </itemizedlist>
881       </sect3>
882       <sect3>
883         <title>Memory Coherency</title>
884         <para>
885           When mapped to the device or used in a command buffer, backing pages
886           for an object are flushed to memory and marked write combined so as to
887           be coherent with the GPU. Likewise, if the CPU accesses an object
888           after the GPU has finished rendering to the object, then the object
889           must be made coherent with the CPU's view of memory, usually involving
890           GPU cache flushing of various kinds. This core CPU&lt;-&gt;GPU
891           coherency management is provided by a device-specific ioctl, which
892           evaluates an object's current domain and performs any necessary
893           flushing or synchronization to put the object into the desired
894           coherency domain (note that the object may be busy, i.e. an active
895           render target; in that case, setting the domain blocks the client and
896           waits for rendering to complete before performing any necessary
897           flushing operations).
898         </para>
899       </sect3>
900       <sect3>
901         <title>Command Execution</title>
902         <para>
903           Perhaps the most important GEM function for GPU devices is providing a
904           command execution interface to clients. Client programs construct
905           command buffers containing references to previously allocated memory
906           objects, and then submit them to GEM. At that point, GEM takes care to
907           bind all the objects into the GTT, execute the buffer, and provide
908           necessary synchronization between clients accessing the same buffers.
909           This often involves evicting some objects from the GTT and re-binding
910           others (a fairly expensive operation), and providing relocation
911           support which hides fixed GTT offsets from clients. Clients must take
912           care not to submit command buffers that reference more objects than
913           can fit in the GTT; otherwise, GEM will reject them and no rendering
914           will occur. Similarly, if several objects in the buffer require fence
915           registers to be allocated for correct rendering (e.g. 2D blits on
916           pre-965 chips), care must be taken not to require more fence registers
917           than are available to the client. Such resource management should be
918           abstracted from the client in libdrm.
919         </para>
920       </sect3>
921     </sect2>
922   </sect1>
923
924   <!-- Internals: mode setting -->
925
926   <sect1 id="drm-mode-setting">
927     <title>Mode Setting</title>
928     <para>
929       Drivers must initialize the mode setting core by calling
930       <function>drm_mode_config_init</function> on the DRM device. The function
931       initializes the <structname>drm_device</structname>
932       <structfield>mode_config</structfield> field and never fails. Once done,
933       mode configuration must be setup by initializing the following fields.
934     </para>
935     <itemizedlist>
936       <listitem>
937         <synopsis>int min_width, min_height;
938 int max_width, max_height;</synopsis>
939         <para>
940           Minimum and maximum width and height of the frame buffers in pixel
941           units.
942         </para>
943       </listitem>
944       <listitem>
945         <synopsis>struct drm_mode_config_funcs *funcs;</synopsis>
946         <para>Mode setting functions.</para>
947       </listitem>
948     </itemizedlist>
949     <sect2>
950       <title>Frame Buffer Creation</title>
951       <synopsis>struct drm_framebuffer *(*fb_create)(struct drm_device *dev,
952                                      struct drm_file *file_priv,
953                                      struct drm_mode_fb_cmd2 *mode_cmd);</synopsis>
954       <para>
955         Frame buffers are abstract memory objects that provide a source of
956         pixels to scanout to a CRTC. Applications explicitly request the
957         creation of frame buffers through the DRM_IOCTL_MODE_ADDFB(2) ioctls and
958         receive an opaque handle that can be passed to the KMS CRTC control,
959         plane configuration and page flip functions.
960       </para>
961       <para>
962         Frame buffers rely on the underneath memory manager for low-level memory
963         operations. When creating a frame buffer applications pass a memory
964         handle (or a list of memory handles for multi-planar formats) through
965         the <parameter>drm_mode_fb_cmd2</parameter> argument. This document
966         assumes that the driver uses GEM, those handles thus reference GEM
967         objects.
968       </para>
969       <para>
970         Drivers must first validate the requested frame buffer parameters passed
971         through the mode_cmd argument. In particular this is where invalid
972         sizes, pixel formats or pitches can be caught.
973       </para>
974       <para>
975         If the parameters are deemed valid, drivers then create, initialize and
976         return an instance of struct <structname>drm_framebuffer</structname>.
977         If desired the instance can be embedded in a larger driver-specific
978         structure. Drivers must fill its <structfield>width</structfield>,
979         <structfield>height</structfield>, <structfield>pitches</structfield>,
980         <structfield>offsets</structfield>, <structfield>depth</structfield>,
981         <structfield>bits_per_pixel</structfield> and
982         <structfield>pixel_format</structfield> fields from the values passed
983         through the <parameter>drm_mode_fb_cmd2</parameter> argument. They
984         should call the <function>drm_helper_mode_fill_fb_struct</function>
985         helper function to do so.
986       </para>
987
988       <para>
989         The initailization of the new framebuffer instance is finalized with a
990         call to <function>drm_framebuffer_init</function> which takes a pointer
991         to DRM frame buffer operations (struct
992         <structname>drm_framebuffer_funcs</structname>). Note that this function
993         publishes the framebuffer and so from this point on it can be accessed
994         concurrently from other threads. Hence it must be the last step in the
995         driver's framebuffer initialization sequence. Frame buffer operations
996         are
997         <itemizedlist>
998           <listitem>
999             <synopsis>int (*create_handle)(struct drm_framebuffer *fb,
1000                      struct drm_file *file_priv, unsigned int *handle);</synopsis>
1001             <para>
1002               Create a handle to the frame buffer underlying memory object. If
1003               the frame buffer uses a multi-plane format, the handle will
1004               reference the memory object associated with the first plane.
1005             </para>
1006             <para>
1007               Drivers call <function>drm_gem_handle_create</function> to create
1008               the handle.
1009             </para>
1010           </listitem>
1011           <listitem>
1012             <synopsis>void (*destroy)(struct drm_framebuffer *framebuffer);</synopsis>
1013             <para>
1014               Destroy the frame buffer object and frees all associated
1015               resources. Drivers must call
1016               <function>drm_framebuffer_cleanup</function> to free resources
1017               allocated by the DRM core for the frame buffer object, and must
1018               make sure to unreference all memory objects associated with the
1019               frame buffer. Handles created by the
1020               <methodname>create_handle</methodname> operation are released by
1021               the DRM core.
1022             </para>
1023           </listitem>
1024           <listitem>
1025             <synopsis>int (*dirty)(struct drm_framebuffer *framebuffer,
1026              struct drm_file *file_priv, unsigned flags, unsigned color,
1027              struct drm_clip_rect *clips, unsigned num_clips);</synopsis>
1028             <para>
1029               This optional operation notifies the driver that a region of the
1030               frame buffer has changed in response to a DRM_IOCTL_MODE_DIRTYFB
1031               ioctl call.
1032             </para>
1033           </listitem>
1034         </itemizedlist>
1035       </para>
1036       <para>
1037         The lifetime of a drm framebuffer is controlled with a reference count,
1038         drivers can grab additional references with
1039         <function>drm_framebuffer_reference</function> </para> and drop them
1040         again with <function>drm_framebuffer_unreference</function>. For
1041         driver-private framebuffers for which the last reference is never
1042         dropped (e.g. for the fbdev framebuffer when the struct
1043         <structname>drm_framebuffer</structname> is embedded into the fbdev
1044         helper struct) drivers can manually clean up a framebuffer at module
1045         unload time with
1046         <function>drm_framebuffer_unregister_private</function>.
1047     </sect2>
1048     <sect2>
1049       <title>Output Polling</title>
1050       <synopsis>void (*output_poll_changed)(struct drm_device *dev);</synopsis>
1051       <para>
1052         This operation notifies the driver that the status of one or more
1053         connectors has changed. Drivers that use the fb helper can just call the
1054         <function>drm_fb_helper_hotplug_event</function> function to handle this
1055         operation.
1056       </para>
1057     </sect2>
1058     <sect2>
1059       <title>Locking</title>
1060       <para>
1061         Beside some lookup structures with their own locking (which is hidden
1062         behind the interface functions) most of the modeset state is protected
1063         by the <code>dev-&lt;mode_config.lock</code> mutex and additionally
1064         per-crtc locks to allow cursor updates, pageflips and similar operations
1065         to occur concurrently with background tasks like output detection.
1066         Operations which cross domains like a full modeset always grab all
1067         locks. Drivers there need to protect resources shared between crtcs with
1068         additional locking. They also need to be careful to always grab the
1069         relevant crtc locks if a modset functions touches crtc state, e.g. for
1070         load detection (which does only grab the <code>mode_config.lock</code>
1071         to allow concurrent screen updates on live crtcs).
1072       </para>
1073     </sect2>
1074   </sect1>
1075
1076   <!-- Internals: kms initialization and cleanup -->
1077
1078   <sect1 id="drm-kms-init">
1079     <title>KMS Initialization and Cleanup</title>
1080     <para>
1081       A KMS device is abstracted and exposed as a set of planes, CRTCs, encoders
1082       and connectors. KMS drivers must thus create and initialize all those
1083       objects at load time after initializing mode setting.
1084     </para>
1085     <sect2>
1086       <title>CRTCs (struct <structname>drm_crtc</structname>)</title>
1087       <para>
1088         A CRTC is an abstraction representing a part of the chip that contains a
1089         pointer to a scanout buffer. Therefore, the number of CRTCs available
1090         determines how many independent scanout buffers can be active at any
1091         given time. The CRTC structure contains several fields to support this:
1092         a pointer to some video memory (abstracted as a frame buffer object), a
1093         display mode, and an (x, y) offset into the video memory to support
1094         panning or configurations where one piece of video memory spans multiple
1095         CRTCs.
1096       </para>
1097       <sect3>
1098         <title>CRTC Initialization</title>
1099         <para>
1100           A KMS device must create and register at least one struct
1101           <structname>drm_crtc</structname> instance. The instance is allocated
1102           and zeroed by the driver, possibly as part of a larger structure, and
1103           registered with a call to <function>drm_crtc_init</function> with a
1104           pointer to CRTC functions.
1105         </para>
1106       </sect3>
1107       <sect3>
1108         <title>CRTC Operations</title>
1109         <sect4>
1110           <title>Set Configuration</title>
1111           <synopsis>int (*set_config)(struct drm_mode_set *set);</synopsis>
1112           <para>
1113             Apply a new CRTC configuration to the device. The configuration
1114             specifies a CRTC, a frame buffer to scan out from, a (x,y) position in
1115             the frame buffer, a display mode and an array of connectors to drive
1116             with the CRTC if possible.
1117           </para>
1118           <para>
1119             If the frame buffer specified in the configuration is NULL, the driver
1120             must detach all encoders connected to the CRTC and all connectors
1121             attached to those encoders and disable them.
1122           </para>
1123           <para>
1124             This operation is called with the mode config lock held.
1125           </para>
1126           <note><para>
1127             FIXME: How should set_config interact with DPMS? If the CRTC is
1128             suspended, should it be resumed?
1129           </para></note>
1130         </sect4>
1131         <sect4>
1132           <title>Page Flipping</title>
1133           <synopsis>int (*page_flip)(struct drm_crtc *crtc, struct drm_framebuffer *fb,
1134                    struct drm_pending_vblank_event *event);</synopsis>
1135           <para>
1136             Schedule a page flip to the given frame buffer for the CRTC. This
1137             operation is called with the mode config mutex held.
1138           </para>
1139           <para>
1140             Page flipping is a synchronization mechanism that replaces the frame
1141             buffer being scanned out by the CRTC with a new frame buffer during
1142             vertical blanking, avoiding tearing. When an application requests a page
1143             flip the DRM core verifies that the new frame buffer is large enough to
1144             be scanned out by  the CRTC in the currently configured mode and then
1145             calls the CRTC <methodname>page_flip</methodname> operation with a
1146             pointer to the new frame buffer.
1147           </para>
1148           <para>
1149             The <methodname>page_flip</methodname> operation schedules a page flip.
1150             Once any pending rendering targeting the new frame buffer has
1151             completed, the CRTC will be reprogrammed to display that frame buffer
1152             after the next vertical refresh. The operation must return immediately
1153             without waiting for rendering or page flip to complete and must block
1154             any new rendering to the frame buffer until the page flip completes.
1155           </para>
1156           <para>
1157             If a page flip can be successfully scheduled the driver must set the
1158             <code>drm_crtc-&lt;fb</code> field to the new framebuffer pointed to
1159             by <code>fb</code>. This is important so that the reference counting
1160             on framebuffers stays balanced.
1161           </para>
1162           <para>
1163             If a page flip is already pending, the
1164             <methodname>page_flip</methodname> operation must return
1165             -<errorname>EBUSY</errorname>.
1166           </para>
1167           <para>
1168             To synchronize page flip to vertical blanking the driver will likely
1169             need to enable vertical blanking interrupts. It should call
1170             <function>drm_vblank_get</function> for that purpose, and call
1171             <function>drm_vblank_put</function> after the page flip completes.
1172           </para>
1173           <para>
1174             If the application has requested to be notified when page flip completes
1175             the <methodname>page_flip</methodname> operation will be called with a
1176             non-NULL <parameter>event</parameter> argument pointing to a
1177             <structname>drm_pending_vblank_event</structname> instance. Upon page
1178             flip completion the driver must call <methodname>drm_send_vblank_event</methodname>
1179             to fill in the event and send to wake up any waiting processes.
1180             This can be performed with
1181             <programlisting><![CDATA[
1182             spin_lock_irqsave(&dev->event_lock, flags);
1183             ...
1184             drm_send_vblank_event(dev, pipe, event);
1185             spin_unlock_irqrestore(&dev->event_lock, flags);
1186             ]]></programlisting>
1187           </para>
1188           <note><para>
1189             FIXME: Could drivers that don't need to wait for rendering to complete
1190             just add the event to <literal>dev-&gt;vblank_event_list</literal> and
1191             let the DRM core handle everything, as for "normal" vertical blanking
1192             events?
1193           </para></note>
1194           <para>
1195             While waiting for the page flip to complete, the
1196             <literal>event-&gt;base.link</literal> list head can be used freely by
1197             the driver to store the pending event in a driver-specific list.
1198           </para>
1199           <para>
1200             If the file handle is closed before the event is signaled, drivers must
1201             take care to destroy the event in their
1202             <methodname>preclose</methodname> operation (and, if needed, call
1203             <function>drm_vblank_put</function>).
1204           </para>
1205         </sect4>
1206         <sect4>
1207           <title>Miscellaneous</title>
1208           <itemizedlist>
1209             <listitem>
1210               <synopsis>void (*set_property)(struct drm_crtc *crtc,
1211                      struct drm_property *property, uint64_t value);</synopsis>
1212               <para>
1213                 Set the value of the given CRTC property to
1214                 <parameter>value</parameter>. See <xref linkend="drm-kms-properties"/>
1215                 for more information about properties.
1216               </para>
1217             </listitem>
1218             <listitem>
1219               <synopsis>void (*gamma_set)(struct drm_crtc *crtc, u16 *r, u16 *g, u16 *b,
1220                         uint32_t start, uint32_t size);</synopsis>
1221               <para>
1222                 Apply a gamma table to the device. The operation is optional.
1223               </para>
1224             </listitem>
1225             <listitem>
1226               <synopsis>void (*destroy)(struct drm_crtc *crtc);</synopsis>
1227               <para>
1228                 Destroy the CRTC when not needed anymore. See
1229                 <xref linkend="drm-kms-init"/>.
1230               </para>
1231             </listitem>
1232           </itemizedlist>
1233         </sect4>
1234       </sect3>
1235     </sect2>
1236     <sect2>
1237       <title>Planes (struct <structname>drm_plane</structname>)</title>
1238       <para>
1239         A plane represents an image source that can be blended with or overlayed
1240         on top of a CRTC during the scanout process. Planes are associated with
1241         a frame buffer to crop a portion of the image memory (source) and
1242         optionally scale it to a destination size. The result is then blended
1243         with or overlayed on top of a CRTC.
1244       </para>
1245       <sect3>
1246         <title>Plane Initialization</title>
1247         <para>
1248           Planes are optional. To create a plane, a KMS drivers allocates and
1249           zeroes an instances of struct <structname>drm_plane</structname>
1250           (possibly as part of a larger structure) and registers it with a call
1251           to <function>drm_plane_init</function>. The function takes a bitmask
1252           of the CRTCs that can be associated with the plane, a pointer to the
1253           plane functions and a list of format supported formats.
1254         </para>
1255       </sect3>
1256       <sect3>
1257         <title>Plane Operations</title>
1258         <itemizedlist>
1259           <listitem>
1260             <synopsis>int (*update_plane)(struct drm_plane *plane, struct drm_crtc *crtc,
1261                         struct drm_framebuffer *fb, int crtc_x, int crtc_y,
1262                         unsigned int crtc_w, unsigned int crtc_h,
1263                         uint32_t src_x, uint32_t src_y,
1264                         uint32_t src_w, uint32_t src_h);</synopsis>
1265             <para>
1266               Enable and configure the plane to use the given CRTC and frame buffer.
1267             </para>
1268             <para>
1269               The source rectangle in frame buffer memory coordinates is given by
1270               the <parameter>src_x</parameter>, <parameter>src_y</parameter>,
1271               <parameter>src_w</parameter> and <parameter>src_h</parameter>
1272               parameters (as 16.16 fixed point values). Devices that don't support
1273               subpixel plane coordinates can ignore the fractional part.
1274             </para>
1275             <para>
1276               The destination rectangle in CRTC coordinates is given by the
1277               <parameter>crtc_x</parameter>, <parameter>crtc_y</parameter>,
1278               <parameter>crtc_w</parameter> and <parameter>crtc_h</parameter>
1279               parameters (as integer values). Devices scale the source rectangle to
1280               the destination rectangle. If scaling is not supported, and the source
1281               rectangle size doesn't match the destination rectangle size, the
1282               driver must return a -<errorname>EINVAL</errorname> error.
1283             </para>
1284           </listitem>
1285           <listitem>
1286             <synopsis>int (*disable_plane)(struct drm_plane *plane);</synopsis>
1287             <para>
1288               Disable the plane. The DRM core calls this method in response to a
1289               DRM_IOCTL_MODE_SETPLANE ioctl call with the frame buffer ID set to 0.
1290               Disabled planes must not be processed by the CRTC.
1291             </para>
1292           </listitem>
1293           <listitem>
1294             <synopsis>void (*destroy)(struct drm_plane *plane);</synopsis>
1295             <para>
1296               Destroy the plane when not needed anymore. See
1297               <xref linkend="drm-kms-init"/>.
1298             </para>
1299           </listitem>
1300         </itemizedlist>
1301       </sect3>
1302     </sect2>
1303     <sect2>
1304       <title>Encoders (struct <structname>drm_encoder</structname>)</title>
1305       <para>
1306         An encoder takes pixel data from a CRTC and converts it to a format
1307         suitable for any attached connectors. On some devices, it may be
1308         possible to have a CRTC send data to more than one encoder. In that
1309         case, both encoders would receive data from the same scanout buffer,
1310         resulting in a "cloned" display configuration across the connectors
1311         attached to each encoder.
1312       </para>
1313       <sect3>
1314         <title>Encoder Initialization</title>
1315         <para>
1316           As for CRTCs, a KMS driver must create, initialize and register at
1317           least one struct <structname>drm_encoder</structname> instance. The
1318           instance is allocated and zeroed by the driver, possibly as part of a
1319           larger structure.
1320         </para>
1321         <para>
1322           Drivers must initialize the struct <structname>drm_encoder</structname>
1323           <structfield>possible_crtcs</structfield> and
1324           <structfield>possible_clones</structfield> fields before registering the
1325           encoder. Both fields are bitmasks of respectively the CRTCs that the
1326           encoder can be connected to, and sibling encoders candidate for cloning.
1327         </para>
1328         <para>
1329           After being initialized, the encoder must be registered with a call to
1330           <function>drm_encoder_init</function>. The function takes a pointer to
1331           the encoder functions and an encoder type. Supported types are
1332           <itemizedlist>
1333             <listitem>
1334               DRM_MODE_ENCODER_DAC for VGA and analog on DVI-I/DVI-A
1335               </listitem>
1336             <listitem>
1337               DRM_MODE_ENCODER_TMDS for DVI, HDMI and (embedded) DisplayPort
1338             </listitem>
1339             <listitem>
1340               DRM_MODE_ENCODER_LVDS for display panels
1341             </listitem>
1342             <listitem>
1343               DRM_MODE_ENCODER_TVDAC for TV output (Composite, S-Video, Component,
1344               SCART)
1345             </listitem>
1346             <listitem>
1347               DRM_MODE_ENCODER_VIRTUAL for virtual machine displays
1348             </listitem>
1349           </itemizedlist>
1350         </para>
1351         <para>
1352           Encoders must be attached to a CRTC to be used. DRM drivers leave
1353           encoders unattached at initialization time. Applications (or the fbdev
1354           compatibility layer when implemented) are responsible for attaching the
1355           encoders they want to use to a CRTC.
1356         </para>
1357       </sect3>
1358       <sect3>
1359         <title>Encoder Operations</title>
1360         <itemizedlist>
1361           <listitem>
1362             <synopsis>void (*destroy)(struct drm_encoder *encoder);</synopsis>
1363             <para>
1364               Called to destroy the encoder when not needed anymore. See
1365               <xref linkend="drm-kms-init"/>.
1366             </para>
1367           </listitem>
1368           <listitem>
1369             <synopsis>void (*set_property)(struct drm_plane *plane,
1370                      struct drm_property *property, uint64_t value);</synopsis>
1371             <para>
1372               Set the value of the given plane property to
1373               <parameter>value</parameter>. See <xref linkend="drm-kms-properties"/>
1374               for more information about properties.
1375             </para>
1376           </listitem>
1377         </itemizedlist>
1378       </sect3>
1379     </sect2>
1380     <sect2>
1381       <title>Connectors (struct <structname>drm_connector</structname>)</title>
1382       <para>
1383         A connector is the final destination for pixel data on a device, and
1384         usually connects directly to an external display device like a monitor
1385         or laptop panel. A connector can only be attached to one encoder at a
1386         time. The connector is also the structure where information about the
1387         attached display is kept, so it contains fields for display data, EDID
1388         data, DPMS &amp; connection status, and information about modes
1389         supported on the attached displays.
1390       </para>
1391       <sect3>
1392         <title>Connector Initialization</title>
1393         <para>
1394           Finally a KMS driver must create, initialize, register and attach at
1395           least one struct <structname>drm_connector</structname> instance. The
1396           instance is created as other KMS objects and initialized by setting the
1397           following fields.
1398         </para>
1399         <variablelist>
1400           <varlistentry>
1401             <term><structfield>interlace_allowed</structfield></term>
1402             <listitem><para>
1403               Whether the connector can handle interlaced modes.
1404             </para></listitem>
1405           </varlistentry>
1406           <varlistentry>
1407             <term><structfield>doublescan_allowed</structfield></term>
1408             <listitem><para>
1409               Whether the connector can handle doublescan.
1410             </para></listitem>
1411           </varlistentry>
1412           <varlistentry>
1413             <term><structfield>display_info
1414             </structfield></term>
1415             <listitem><para>
1416               Display information is filled from EDID information when a display
1417               is detected. For non hot-pluggable displays such as flat panels in
1418               embedded systems, the driver should initialize the
1419               <structfield>display_info</structfield>.<structfield>width_mm</structfield>
1420               and
1421               <structfield>display_info</structfield>.<structfield>height_mm</structfield>
1422               fields with the physical size of the display.
1423             </para></listitem>
1424           </varlistentry>
1425           <varlistentry>
1426             <term id="drm-kms-connector-polled"><structfield>polled</structfield></term>
1427             <listitem><para>
1428               Connector polling mode, a combination of
1429               <variablelist>
1430                 <varlistentry>
1431                   <term>DRM_CONNECTOR_POLL_HPD</term>
1432                   <listitem><para>
1433                     The connector generates hotplug events and doesn't need to be
1434                     periodically polled. The CONNECT and DISCONNECT flags must not
1435                     be set together with the HPD flag.
1436                   </para></listitem>
1437                 </varlistentry>
1438                 <varlistentry>
1439                   <term>DRM_CONNECTOR_POLL_CONNECT</term>
1440                   <listitem><para>
1441                     Periodically poll the connector for connection.
1442                   </para></listitem>
1443                 </varlistentry>
1444                 <varlistentry>
1445                   <term>DRM_CONNECTOR_POLL_DISCONNECT</term>
1446                   <listitem><para>
1447                     Periodically poll the connector for disconnection.
1448                   </para></listitem>
1449                 </varlistentry>
1450               </variablelist>
1451               Set to 0 for connectors that don't support connection status
1452               discovery.
1453             </para></listitem>
1454           </varlistentry>
1455         </variablelist>
1456         <para>
1457           The connector is then registered with a call to
1458           <function>drm_connector_init</function> with a pointer to the connector
1459           functions and a connector type, and exposed through sysfs with a call to
1460           <function>drm_sysfs_connector_add</function>.
1461         </para>
1462         <para>
1463           Supported connector types are
1464           <itemizedlist>
1465             <listitem>DRM_MODE_CONNECTOR_VGA</listitem>
1466             <listitem>DRM_MODE_CONNECTOR_DVII</listitem>
1467             <listitem>DRM_MODE_CONNECTOR_DVID</listitem>
1468             <listitem>DRM_MODE_CONNECTOR_DVIA</listitem>
1469             <listitem>DRM_MODE_CONNECTOR_Composite</listitem>
1470             <listitem>DRM_MODE_CONNECTOR_SVIDEO</listitem>
1471             <listitem>DRM_MODE_CONNECTOR_LVDS</listitem>
1472             <listitem>DRM_MODE_CONNECTOR_Component</listitem>
1473             <listitem>DRM_MODE_CONNECTOR_9PinDIN</listitem>
1474             <listitem>DRM_MODE_CONNECTOR_DisplayPort</listitem>
1475             <listitem>DRM_MODE_CONNECTOR_HDMIA</listitem>
1476             <listitem>DRM_MODE_CONNECTOR_HDMIB</listitem>
1477             <listitem>DRM_MODE_CONNECTOR_TV</listitem>
1478             <listitem>DRM_MODE_CONNECTOR_eDP</listitem>
1479             <listitem>DRM_MODE_CONNECTOR_VIRTUAL</listitem>
1480           </itemizedlist>
1481         </para>
1482         <para>
1483           Connectors must be attached to an encoder to be used. For devices that
1484           map connectors to encoders 1:1, the connector should be attached at
1485           initialization time with a call to
1486           <function>drm_mode_connector_attach_encoder</function>. The driver must
1487           also set the <structname>drm_connector</structname>
1488           <structfield>encoder</structfield> field to point to the attached
1489           encoder.
1490         </para>
1491         <para>
1492           Finally, drivers must initialize the connectors state change detection
1493           with a call to <function>drm_kms_helper_poll_init</function>. If at
1494           least one connector is pollable but can't generate hotplug interrupts
1495           (indicated by the DRM_CONNECTOR_POLL_CONNECT and
1496           DRM_CONNECTOR_POLL_DISCONNECT connector flags), a delayed work will
1497           automatically be queued to periodically poll for changes. Connectors
1498           that can generate hotplug interrupts must be marked with the
1499           DRM_CONNECTOR_POLL_HPD flag instead, and their interrupt handler must
1500           call <function>drm_helper_hpd_irq_event</function>. The function will
1501           queue a delayed work to check the state of all connectors, but no
1502           periodic polling will be done.
1503         </para>
1504       </sect3>
1505       <sect3>
1506         <title>Connector Operations</title>
1507         <note><para>
1508           Unless otherwise state, all operations are mandatory.
1509         </para></note>
1510         <sect4>
1511           <title>DPMS</title>
1512           <synopsis>void (*dpms)(struct drm_connector *connector, int mode);</synopsis>
1513           <para>
1514             The DPMS operation sets the power state of a connector. The mode
1515             argument is one of
1516             <itemizedlist>
1517               <listitem><para>DRM_MODE_DPMS_ON</para></listitem>
1518               <listitem><para>DRM_MODE_DPMS_STANDBY</para></listitem>
1519               <listitem><para>DRM_MODE_DPMS_SUSPEND</para></listitem>
1520               <listitem><para>DRM_MODE_DPMS_OFF</para></listitem>
1521             </itemizedlist>
1522           </para>
1523           <para>
1524             In all but DPMS_ON mode the encoder to which the connector is attached
1525             should put the display in low-power mode by driving its signals
1526             appropriately. If more than one connector is attached to the encoder
1527             care should be taken not to change the power state of other displays as
1528             a side effect. Low-power mode should be propagated to the encoders and
1529             CRTCs when all related connectors are put in low-power mode.
1530           </para>
1531         </sect4>
1532         <sect4>
1533           <title>Modes</title>
1534           <synopsis>int (*fill_modes)(struct drm_connector *connector, uint32_t max_width,
1535                       uint32_t max_height);</synopsis>
1536           <para>
1537             Fill the mode list with all supported modes for the connector. If the
1538             <parameter>max_width</parameter> and <parameter>max_height</parameter>
1539             arguments are non-zero, the implementation must ignore all modes wider
1540             than <parameter>max_width</parameter> or higher than
1541             <parameter>max_height</parameter>.
1542           </para>
1543           <para>
1544             The connector must also fill in this operation its
1545             <structfield>display_info</structfield>
1546             <structfield>width_mm</structfield> and
1547             <structfield>height_mm</structfield> fields with the connected display
1548             physical size in millimeters. The fields should be set to 0 if the value
1549             isn't known or is not applicable (for instance for projector devices).
1550           </para>
1551         </sect4>
1552         <sect4>
1553           <title>Connection Status</title>
1554           <para>
1555             The connection status is updated through polling or hotplug events when
1556             supported (see <xref linkend="drm-kms-connector-polled"/>). The status
1557             value is reported to userspace through ioctls and must not be used
1558             inside the driver, as it only gets initialized by a call to
1559             <function>drm_mode_getconnector</function> from userspace.
1560           </para>
1561           <synopsis>enum drm_connector_status (*detect)(struct drm_connector *connector,
1562                                         bool force);</synopsis>
1563           <para>
1564             Check to see if anything is attached to the connector. The
1565             <parameter>force</parameter> parameter is set to false whilst polling or
1566             to true when checking the connector due to user request.
1567             <parameter>force</parameter> can be used by the driver to avoid
1568             expensive, destructive operations during automated probing.
1569           </para>
1570           <para>
1571             Return connector_status_connected if something is connected to the
1572             connector, connector_status_disconnected if nothing is connected and
1573             connector_status_unknown if the connection state isn't known.
1574           </para>
1575           <para>
1576             Drivers should only return connector_status_connected if the connection
1577             status has really been probed as connected. Connectors that can't detect
1578             the connection status, or failed connection status probes, should return
1579             connector_status_unknown.
1580           </para>
1581         </sect4>
1582         <sect4>
1583           <title>Miscellaneous</title>
1584           <itemizedlist>
1585             <listitem>
1586               <synopsis>void (*set_property)(struct drm_connector *connector,
1587                      struct drm_property *property, uint64_t value);</synopsis>
1588               <para>
1589                 Set the value of the given connector property to
1590                 <parameter>value</parameter>. See <xref linkend="drm-kms-properties"/>
1591                 for more information about properties.
1592               </para>
1593             </listitem>
1594             <listitem>
1595               <synopsis>void (*destroy)(struct drm_connector *connector);</synopsis>
1596               <para>
1597                 Destroy the connector when not needed anymore. See
1598                 <xref linkend="drm-kms-init"/>.
1599               </para>
1600             </listitem>
1601           </itemizedlist>
1602         </sect4>
1603       </sect3>
1604     </sect2>
1605     <sect2>
1606       <title>Cleanup</title>
1607       <para>
1608         The DRM core manages its objects' lifetime. When an object is not needed
1609         anymore the core calls its destroy function, which must clean up and
1610         free every resource allocated for the object. Every
1611         <function>drm_*_init</function> call must be matched with a
1612         corresponding <function>drm_*_cleanup</function> call to cleanup CRTCs
1613         (<function>drm_crtc_cleanup</function>), planes
1614         (<function>drm_plane_cleanup</function>), encoders
1615         (<function>drm_encoder_cleanup</function>) and connectors
1616         (<function>drm_connector_cleanup</function>). Furthermore, connectors
1617         that have been added to sysfs must be removed by a call to
1618         <function>drm_sysfs_connector_remove</function> before calling
1619         <function>drm_connector_cleanup</function>.
1620       </para>
1621       <para>
1622         Connectors state change detection must be cleanup up with a call to
1623         <function>drm_kms_helper_poll_fini</function>.
1624       </para>
1625     </sect2>
1626     <sect2>
1627       <title>Output discovery and initialization example</title>
1628       <programlisting><![CDATA[
1629 void intel_crt_init(struct drm_device *dev)
1630 {
1631         struct drm_connector *connector;
1632         struct intel_output *intel_output;
1633
1634         intel_output = kzalloc(sizeof(struct intel_output), GFP_KERNEL);
1635         if (!intel_output)
1636                 return;
1637
1638         connector = &intel_output->base;
1639         drm_connector_init(dev, &intel_output->base,
1640                            &intel_crt_connector_funcs, DRM_MODE_CONNECTOR_VGA);
1641
1642         drm_encoder_init(dev, &intel_output->enc, &intel_crt_enc_funcs,
1643                          DRM_MODE_ENCODER_DAC);
1644
1645         drm_mode_connector_attach_encoder(&intel_output->base,
1646                                           &intel_output->enc);
1647
1648         /* Set up the DDC bus. */
1649         intel_output->ddc_bus = intel_i2c_create(dev, GPIOA, "CRTDDC_A");
1650         if (!intel_output->ddc_bus) {
1651                 dev_printk(KERN_ERR, &dev->pdev->dev, "DDC bus registration "
1652                            "failed.\n");
1653                 return;
1654         }
1655
1656         intel_output->type = INTEL_OUTPUT_ANALOG;
1657         connector->interlace_allowed = 0;
1658         connector->doublescan_allowed = 0;
1659
1660         drm_encoder_helper_add(&intel_output->enc, &intel_crt_helper_funcs);
1661         drm_connector_helper_add(connector, &intel_crt_connector_helper_funcs);
1662
1663         drm_sysfs_connector_add(connector);
1664 }]]></programlisting>
1665       <para>
1666         In the example above (taken from the i915 driver), a CRTC, connector and
1667         encoder combination is created. A device-specific i2c bus is also
1668         created for fetching EDID data and performing monitor detection. Once
1669         the process is complete, the new connector is registered with sysfs to
1670         make its properties available to applications.
1671       </para>
1672     </sect2>
1673     <sect2>
1674       <title>KMS API Functions</title>
1675 !Edrivers/gpu/drm/drm_crtc.c
1676     </sect2>
1677   </sect1>
1678
1679   <!-- Internals: kms helper functions -->
1680
1681   <sect1>
1682     <title>Mode Setting Helper Functions</title>
1683     <para>
1684       The CRTC, encoder and connector functions provided by the drivers
1685       implement the DRM API. They're called by the DRM core and ioctl handlers
1686       to handle device state changes and configuration request. As implementing
1687       those functions often requires logic not specific to drivers, mid-layer
1688       helper functions are available to avoid duplicating boilerplate code.
1689     </para>
1690     <para>
1691       The DRM core contains one mid-layer implementation. The mid-layer provides
1692       implementations of several CRTC, encoder and connector functions (called
1693       from the top of the mid-layer) that pre-process requests and call
1694       lower-level functions provided by the driver (at the bottom of the
1695       mid-layer). For instance, the
1696       <function>drm_crtc_helper_set_config</function> function can be used to
1697       fill the struct <structname>drm_crtc_funcs</structname>
1698       <structfield>set_config</structfield> field. When called, it will split
1699       the <methodname>set_config</methodname> operation in smaller, simpler
1700       operations and call the driver to handle them.
1701     </para>
1702     <para>
1703       To use the mid-layer, drivers call <function>drm_crtc_helper_add</function>,
1704       <function>drm_encoder_helper_add</function> and
1705       <function>drm_connector_helper_add</function> functions to install their
1706       mid-layer bottom operations handlers, and fill the
1707       <structname>drm_crtc_funcs</structname>,
1708       <structname>drm_encoder_funcs</structname> and
1709       <structname>drm_connector_funcs</structname> structures with pointers to
1710       the mid-layer top API functions. Installing the mid-layer bottom operation
1711       handlers is best done right after registering the corresponding KMS object.
1712     </para>
1713     <para>
1714       The mid-layer is not split between CRTC, encoder and connector operations.
1715       To use it, a driver must provide bottom functions for all of the three KMS
1716       entities.
1717     </para>
1718     <sect2>
1719       <title>Helper Functions</title>
1720       <itemizedlist>
1721         <listitem>
1722           <synopsis>int drm_crtc_helper_set_config(struct drm_mode_set *set);</synopsis>
1723           <para>
1724             The <function>drm_crtc_helper_set_config</function> helper function
1725             is a CRTC <methodname>set_config</methodname> implementation. It
1726             first tries to locate the best encoder for each connector by calling
1727             the connector <methodname>best_encoder</methodname> helper
1728             operation.
1729           </para>
1730           <para>
1731             After locating the appropriate encoders, the helper function will
1732             call the <methodname>mode_fixup</methodname> encoder and CRTC helper
1733             operations to adjust the requested mode, or reject it completely in
1734             which case an error will be returned to the application. If the new
1735             configuration after mode adjustment is identical to the current
1736             configuration the helper function will return without performing any
1737             other operation.
1738           </para>
1739           <para>
1740             If the adjusted mode is identical to the current mode but changes to
1741             the frame buffer need to be applied, the
1742             <function>drm_crtc_helper_set_config</function> function will call
1743             the CRTC <methodname>mode_set_base</methodname> helper operation. If
1744             the adjusted mode differs from the current mode, or if the
1745             <methodname>mode_set_base</methodname> helper operation is not
1746             provided, the helper function performs a full mode set sequence by
1747             calling the <methodname>prepare</methodname>,
1748             <methodname>mode_set</methodname> and
1749             <methodname>commit</methodname> CRTC and encoder helper operations,
1750             in that order.
1751           </para>
1752         </listitem>
1753         <listitem>
1754           <synopsis>void drm_helper_connector_dpms(struct drm_connector *connector, int mode);</synopsis>
1755           <para>
1756             The <function>drm_helper_connector_dpms</function> helper function
1757             is a connector <methodname>dpms</methodname> implementation that
1758             tracks power state of connectors. To use the function, drivers must
1759             provide <methodname>dpms</methodname> helper operations for CRTCs
1760             and encoders to apply the DPMS state to the device.
1761           </para>
1762           <para>
1763             The mid-layer doesn't track the power state of CRTCs and encoders.
1764             The <methodname>dpms</methodname> helper operations can thus be
1765             called with a mode identical to the currently active mode.
1766           </para>
1767         </listitem>
1768         <listitem>
1769           <synopsis>int drm_helper_probe_single_connector_modes(struct drm_connector *connector,
1770                                             uint32_t maxX, uint32_t maxY);</synopsis>
1771           <para>
1772             The <function>drm_helper_probe_single_connector_modes</function> helper
1773             function is a connector <methodname>fill_modes</methodname>
1774             implementation that updates the connection status for the connector
1775             and then retrieves a list of modes by calling the connector
1776             <methodname>get_modes</methodname> helper operation.
1777           </para>
1778           <para>
1779             The function filters out modes larger than
1780             <parameter>max_width</parameter> and <parameter>max_height</parameter>
1781             if specified. It then calls the connector
1782             <methodname>mode_valid</methodname> helper operation for  each mode in
1783             the probed list to check whether the mode is valid for the connector.
1784           </para>
1785         </listitem>
1786       </itemizedlist>
1787     </sect2>
1788     <sect2>
1789       <title>CRTC Helper Operations</title>
1790       <itemizedlist>
1791         <listitem id="drm-helper-crtc-mode-fixup">
1792           <synopsis>bool (*mode_fixup)(struct drm_crtc *crtc,
1793                        const struct drm_display_mode *mode,
1794                        struct drm_display_mode *adjusted_mode);</synopsis>
1795           <para>
1796             Let CRTCs adjust the requested mode or reject it completely. This
1797             operation returns true if the mode is accepted (possibly after being
1798             adjusted) or false if it is rejected.
1799           </para>
1800           <para>
1801             The <methodname>mode_fixup</methodname> operation should reject the
1802             mode if it can't reasonably use it. The definition of "reasonable"
1803             is currently fuzzy in this context. One possible behaviour would be
1804             to set the adjusted mode to the panel timings when a fixed-mode
1805             panel is used with hardware capable of scaling. Another behaviour
1806             would be to accept any input mode and adjust it to the closest mode
1807             supported by the hardware (FIXME: This needs to be clarified).
1808           </para>
1809         </listitem>
1810         <listitem>
1811           <synopsis>int (*mode_set_base)(struct drm_crtc *crtc, int x, int y,
1812                      struct drm_framebuffer *old_fb)</synopsis>
1813           <para>
1814             Move the CRTC on the current frame buffer (stored in
1815             <literal>crtc-&gt;fb</literal>) to position (x,y). Any of the frame
1816             buffer, x position or y position may have been modified.
1817           </para>
1818           <para>
1819             This helper operation is optional. If not provided, the
1820             <function>drm_crtc_helper_set_config</function> function will fall
1821             back to the <methodname>mode_set</methodname> helper operation.
1822           </para>
1823           <note><para>
1824             FIXME: Why are x and y passed as arguments, as they can be accessed
1825             through <literal>crtc-&gt;x</literal> and
1826             <literal>crtc-&gt;y</literal>?
1827           </para></note>
1828         </listitem>
1829         <listitem>
1830           <synopsis>void (*prepare)(struct drm_crtc *crtc);</synopsis>
1831           <para>
1832             Prepare the CRTC for mode setting. This operation is called after
1833             validating the requested mode. Drivers use it to perform
1834             device-specific operations required before setting the new mode.
1835           </para>
1836         </listitem>
1837         <listitem>
1838           <synopsis>int (*mode_set)(struct drm_crtc *crtc, struct drm_display_mode *mode,
1839                 struct drm_display_mode *adjusted_mode, int x, int y,
1840                 struct drm_framebuffer *old_fb);</synopsis>
1841           <para>
1842             Set a new mode, position and frame buffer. Depending on the device
1843             requirements, the mode can be stored internally by the driver and
1844             applied in the <methodname>commit</methodname> operation, or
1845             programmed to the hardware immediately.
1846           </para>
1847           <para>
1848             The <methodname>mode_set</methodname> operation returns 0 on success
1849             or a negative error code if an error occurs.
1850           </para>
1851         </listitem>
1852         <listitem>
1853           <synopsis>void (*commit)(struct drm_crtc *crtc);</synopsis>
1854           <para>
1855             Commit a mode. This operation is called after setting the new mode.
1856             Upon return the device must use the new mode and be fully
1857             operational.
1858           </para>
1859         </listitem>
1860       </itemizedlist>
1861     </sect2>
1862     <sect2>
1863       <title>Encoder Helper Operations</title>
1864       <itemizedlist>
1865         <listitem>
1866           <synopsis>bool (*mode_fixup)(struct drm_encoder *encoder,
1867                        const struct drm_display_mode *mode,
1868                        struct drm_display_mode *adjusted_mode);</synopsis>
1869           <para>
1870             Let encoders adjust the requested mode or reject it completely. This
1871             operation returns true if the mode is accepted (possibly after being
1872             adjusted) or false if it is rejected. See the
1873             <link linkend="drm-helper-crtc-mode-fixup">mode_fixup CRTC helper
1874             operation</link> for an explanation of the allowed adjustments.
1875           </para>
1876         </listitem>
1877         <listitem>
1878           <synopsis>void (*prepare)(struct drm_encoder *encoder);</synopsis>
1879           <para>
1880             Prepare the encoder for mode setting. This operation is called after
1881             validating the requested mode. Drivers use it to perform
1882             device-specific operations required before setting the new mode.
1883           </para>
1884         </listitem>
1885         <listitem>
1886           <synopsis>void (*mode_set)(struct drm_encoder *encoder,
1887                  struct drm_display_mode *mode,
1888                  struct drm_display_mode *adjusted_mode);</synopsis>
1889           <para>
1890             Set a new mode. Depending on the device requirements, the mode can
1891             be stored internally by the driver and applied in the
1892             <methodname>commit</methodname> operation, or programmed to the
1893             hardware immediately.
1894           </para>
1895         </listitem>
1896         <listitem>
1897           <synopsis>void (*commit)(struct drm_encoder *encoder);</synopsis>
1898           <para>
1899             Commit a mode. This operation is called after setting the new mode.
1900             Upon return the device must use the new mode and be fully
1901             operational.
1902           </para>
1903         </listitem>
1904       </itemizedlist>
1905     </sect2>
1906     <sect2>
1907       <title>Connector Helper Operations</title>
1908       <itemizedlist>
1909         <listitem>
1910           <synopsis>struct drm_encoder *(*best_encoder)(struct drm_connector *connector);</synopsis>
1911           <para>
1912             Return a pointer to the best encoder for the connecter. Device that
1913             map connectors to encoders 1:1 simply return the pointer to the
1914             associated encoder. This operation is mandatory.
1915           </para>
1916         </listitem>
1917         <listitem>
1918           <synopsis>int (*get_modes)(struct drm_connector *connector);</synopsis>
1919           <para>
1920             Fill the connector's <structfield>probed_modes</structfield> list
1921             by parsing EDID data with <function>drm_add_edid_modes</function> or
1922             calling <function>drm_mode_probed_add</function> directly for every
1923             supported mode and return the number of modes it has detected. This
1924             operation is mandatory.
1925           </para>
1926           <para>
1927             When adding modes manually the driver creates each mode with a call to
1928             <function>drm_mode_create</function> and must fill the following fields.
1929             <itemizedlist>
1930               <listitem>
1931                 <synopsis>__u32 type;</synopsis>
1932                 <para>
1933                   Mode type bitmask, a combination of
1934                   <variablelist>
1935                     <varlistentry>
1936                       <term>DRM_MODE_TYPE_BUILTIN</term>
1937                       <listitem><para>not used?</para></listitem>
1938                     </varlistentry>
1939                     <varlistentry>
1940                       <term>DRM_MODE_TYPE_CLOCK_C</term>
1941                       <listitem><para>not used?</para></listitem>
1942                     </varlistentry>
1943                     <varlistentry>
1944                       <term>DRM_MODE_TYPE_CRTC_C</term>
1945                       <listitem><para>not used?</para></listitem>
1946                     </varlistentry>
1947                     <varlistentry>
1948                       <term>
1949         DRM_MODE_TYPE_PREFERRED - The preferred mode for the connector
1950                       </term>
1951                       <listitem>
1952                         <para>not used?</para>
1953                       </listitem>
1954                     </varlistentry>
1955                     <varlistentry>
1956                       <term>DRM_MODE_TYPE_DEFAULT</term>
1957                       <listitem><para>not used?</para></listitem>
1958                     </varlistentry>
1959                     <varlistentry>
1960                       <term>DRM_MODE_TYPE_USERDEF</term>
1961                       <listitem><para>not used?</para></listitem>
1962                     </varlistentry>
1963                     <varlistentry>
1964                       <term>DRM_MODE_TYPE_DRIVER</term>
1965                       <listitem>
1966                         <para>
1967                           The mode has been created by the driver (as opposed to
1968                           to user-created modes).
1969                         </para>
1970                       </listitem>
1971                     </varlistentry>
1972                   </variablelist>
1973                   Drivers must set the DRM_MODE_TYPE_DRIVER bit for all modes they
1974                   create, and set the DRM_MODE_TYPE_PREFERRED bit for the preferred
1975                   mode.
1976                 </para>
1977               </listitem>
1978               <listitem>
1979                 <synopsis>__u32 clock;</synopsis>
1980                 <para>Pixel clock frequency in kHz unit</para>
1981               </listitem>
1982               <listitem>
1983                 <synopsis>__u16 hdisplay, hsync_start, hsync_end, htotal;
1984     __u16 vdisplay, vsync_start, vsync_end, vtotal;</synopsis>
1985                 <para>Horizontal and vertical timing information</para>
1986                 <screen><![CDATA[
1987              Active                 Front           Sync           Back
1988              Region                 Porch                          Porch
1989     <-----------------------><----------------><-------------><-------------->
1990
1991       //////////////////////|
1992      ////////////////////// |
1993     //////////////////////  |..................               ................
1994                                                _______________
1995
1996     <----- [hv]display ----->
1997     <------------- [hv]sync_start ------------>
1998     <--------------------- [hv]sync_end --------------------->
1999     <-------------------------------- [hv]total ----------------------------->
2000 ]]></screen>
2001               </listitem>
2002               <listitem>
2003                 <synopsis>__u16 hskew;
2004     __u16 vscan;</synopsis>
2005                 <para>Unknown</para>
2006               </listitem>
2007               <listitem>
2008                 <synopsis>__u32 flags;</synopsis>
2009                 <para>
2010                   Mode flags, a combination of
2011                   <variablelist>
2012                     <varlistentry>
2013                       <term>DRM_MODE_FLAG_PHSYNC</term>
2014                       <listitem><para>
2015                         Horizontal sync is active high
2016                       </para></listitem>
2017                     </varlistentry>
2018                     <varlistentry>
2019                       <term>DRM_MODE_FLAG_NHSYNC</term>
2020                       <listitem><para>
2021                         Horizontal sync is active low
2022                       </para></listitem>
2023                     </varlistentry>
2024                     <varlistentry>
2025                       <term>DRM_MODE_FLAG_PVSYNC</term>
2026                       <listitem><para>
2027                         Vertical sync is active high
2028                       </para></listitem>
2029                     </varlistentry>
2030                     <varlistentry>
2031                       <term>DRM_MODE_FLAG_NVSYNC</term>
2032                       <listitem><para>
2033                         Vertical sync is active low
2034                       </para></listitem>
2035                     </varlistentry>
2036                     <varlistentry>
2037                       <term>DRM_MODE_FLAG_INTERLACE</term>
2038                       <listitem><para>
2039                         Mode is interlaced
2040                       </para></listitem>
2041                     </varlistentry>
2042                     <varlistentry>
2043                       <term>DRM_MODE_FLAG_DBLSCAN</term>
2044                       <listitem><para>
2045                         Mode uses doublescan
2046                       </para></listitem>
2047                     </varlistentry>
2048                     <varlistentry>
2049                       <term>DRM_MODE_FLAG_CSYNC</term>
2050                       <listitem><para>
2051                         Mode uses composite sync
2052                       </para></listitem>
2053                     </varlistentry>
2054                     <varlistentry>
2055                       <term>DRM_MODE_FLAG_PCSYNC</term>
2056                       <listitem><para>
2057                         Composite sync is active high
2058                       </para></listitem>
2059                     </varlistentry>
2060                     <varlistentry>
2061                       <term>DRM_MODE_FLAG_NCSYNC</term>
2062                       <listitem><para>
2063                         Composite sync is active low
2064                       </para></listitem>
2065                     </varlistentry>
2066                     <varlistentry>
2067                       <term>DRM_MODE_FLAG_HSKEW</term>
2068                       <listitem><para>
2069                         hskew provided (not used?)
2070                       </para></listitem>
2071                     </varlistentry>
2072                     <varlistentry>
2073                       <term>DRM_MODE_FLAG_BCAST</term>
2074                       <listitem><para>
2075                         not used?
2076                       </para></listitem>
2077                     </varlistentry>
2078                     <varlistentry>
2079                       <term>DRM_MODE_FLAG_PIXMUX</term>
2080                       <listitem><para>
2081                         not used?
2082                       </para></listitem>
2083                     </varlistentry>
2084                     <varlistentry>
2085                       <term>DRM_MODE_FLAG_DBLCLK</term>
2086                       <listitem><para>
2087                         not used?
2088                       </para></listitem>
2089                     </varlistentry>
2090                     <varlistentry>
2091                       <term>DRM_MODE_FLAG_CLKDIV2</term>
2092                       <listitem><para>
2093                         ?
2094                       </para></listitem>
2095                     </varlistentry>
2096                   </variablelist>
2097                 </para>
2098                 <para>
2099                   Note that modes marked with the INTERLACE or DBLSCAN flags will be
2100                   filtered out by
2101                   <function>drm_helper_probe_single_connector_modes</function> if
2102                   the connector's <structfield>interlace_allowed</structfield> or
2103                   <structfield>doublescan_allowed</structfield> field is set to 0.
2104                 </para>
2105               </listitem>
2106               <listitem>
2107                 <synopsis>char name[DRM_DISPLAY_MODE_LEN];</synopsis>
2108                 <para>
2109                   Mode name. The driver must call
2110                   <function>drm_mode_set_name</function> to fill the mode name from
2111                   <structfield>hdisplay</structfield>,
2112                   <structfield>vdisplay</structfield> and interlace flag after
2113                   filling the corresponding fields.
2114                 </para>
2115               </listitem>
2116             </itemizedlist>
2117           </para>
2118           <para>
2119             The <structfield>vrefresh</structfield> value is computed by
2120             <function>drm_helper_probe_single_connector_modes</function>.
2121           </para>
2122           <para>
2123             When parsing EDID data, <function>drm_add_edid_modes</function> fill the
2124             connector <structfield>display_info</structfield>
2125             <structfield>width_mm</structfield> and
2126             <structfield>height_mm</structfield> fields. When creating modes
2127             manually the <methodname>get_modes</methodname> helper operation must
2128             set the <structfield>display_info</structfield>
2129             <structfield>width_mm</structfield> and
2130             <structfield>height_mm</structfield> fields if they haven't been set
2131             already (for instance at initilization time when a fixed-size panel is
2132             attached to the connector). The mode <structfield>width_mm</structfield>
2133             and <structfield>height_mm</structfield> fields are only used internally
2134             during EDID parsing and should not be set when creating modes manually.
2135           </para>
2136         </listitem>
2137         <listitem>
2138           <synopsis>int (*mode_valid)(struct drm_connector *connector,
2139                   struct drm_display_mode *mode);</synopsis>
2140           <para>
2141             Verify whether a mode is valid for the connector. Return MODE_OK for
2142             supported modes and one of the enum drm_mode_status values (MODE_*)
2143             for unsupported modes. This operation is mandatory.
2144           </para>
2145           <para>
2146             As the mode rejection reason is currently not used beside for
2147             immediately removing the unsupported mode, an implementation can
2148             return MODE_BAD regardless of the exact reason why the mode is not
2149             valid.
2150           </para>
2151           <note><para>
2152             Note that the <methodname>mode_valid</methodname> helper operation is
2153             only called for modes detected by the device, and
2154             <emphasis>not</emphasis> for modes set by the user through the CRTC
2155             <methodname>set_config</methodname> operation.
2156           </para></note>
2157         </listitem>
2158       </itemizedlist>
2159     </sect2>
2160     <sect2>
2161       <title>Modeset Helper Functions Reference</title>
2162 !Edrivers/gpu/drm/drm_crtc_helper.c
2163     </sect2>
2164     <sect2>
2165       <title>fbdev Helper Functions Reference</title>
2166 !Pdrivers/gpu/drm/drm_fb_helper.c fbdev helpers
2167 !Edrivers/gpu/drm/drm_fb_helper.c
2168 !Iinclude/drm/drm_fb_helper.h
2169     </sect2>
2170     <sect2>
2171       <title>Display Port Helper Functions Reference</title>
2172 !Pdrivers/gpu/drm/drm_dp_helper.c dp helpers
2173 !Iinclude/drm/drm_dp_helper.h
2174 !Edrivers/gpu/drm/drm_dp_helper.c
2175     </sect2>
2176     <sect2>
2177       <title>EDID Helper Functions Reference</title>
2178 !Edrivers/gpu/drm/drm_edid.c
2179     </sect2>
2180     <sect2>
2181       <title>Rectangle Utilities Reference</title>
2182 !Pinclude/drm/drm_rect.h rect utils
2183 !Iinclude/drm/drm_rect.h
2184 !Edrivers/gpu/drm/drm_rect.c
2185     </sect2>
2186     <sect2>
2187       <title>Flip-work Helper Reference</title>
2188 !Pinclude/drm/drm_flip_work.h flip utils
2189 !Iinclude/drm/drm_flip_work.h
2190 !Edrivers/gpu/drm/drm_flip_work.c
2191     </sect2>
2192     <sect2>
2193       <title>VMA Offset Manager</title>
2194 !Pdrivers/gpu/drm/drm_vma_manager.c vma offset manager
2195 !Edrivers/gpu/drm/drm_vma_manager.c
2196 !Iinclude/drm/drm_vma_manager.h
2197     </sect2>
2198   </sect1>
2199
2200   <!-- Internals: kms properties -->
2201
2202   <sect1 id="drm-kms-properties">
2203     <title>KMS Properties</title>
2204     <para>
2205       Drivers may need to expose additional parameters to applications than
2206       those described in the previous sections. KMS supports attaching
2207       properties to CRTCs, connectors and planes and offers a userspace API to
2208       list, get and set the property values.
2209     </para>
2210     <para>
2211       Properties are identified by a name that uniquely defines the property
2212       purpose, and store an associated value. For all property types except blob
2213       properties the value is a 64-bit unsigned integer.
2214     </para>
2215     <para>
2216       KMS differentiates between properties and property instances. Drivers
2217       first create properties and then create and associate individual instances
2218       of those properties to objects. A property can be instantiated multiple
2219       times and associated with different objects. Values are stored in property
2220       instances, and all other property information are stored in the propery
2221       and shared between all instances of the property.
2222     </para>
2223     <para>
2224       Every property is created with a type that influences how the KMS core
2225       handles the property. Supported property types are
2226       <variablelist>
2227         <varlistentry>
2228           <term>DRM_MODE_PROP_RANGE</term>
2229           <listitem><para>Range properties report their minimum and maximum
2230             admissible values. The KMS core verifies that values set by
2231             application fit in that range.</para></listitem>
2232         </varlistentry>
2233         <varlistentry>
2234           <term>DRM_MODE_PROP_ENUM</term>
2235           <listitem><para>Enumerated properties take a numerical value that
2236             ranges from 0 to the number of enumerated values defined by the
2237             property minus one, and associate a free-formed string name to each
2238             value. Applications can retrieve the list of defined value-name pairs
2239             and use the numerical value to get and set property instance values.
2240             </para></listitem>
2241         </varlistentry>
2242         <varlistentry>
2243           <term>DRM_MODE_PROP_BITMASK</term>
2244           <listitem><para>Bitmask properties are enumeration properties that
2245             additionally restrict all enumerated values to the 0..63 range.
2246             Bitmask property instance values combine one or more of the
2247             enumerated bits defined by the property.</para></listitem>
2248         </varlistentry>
2249         <varlistentry>
2250           <term>DRM_MODE_PROP_BLOB</term>
2251           <listitem><para>Blob properties store a binary blob without any format
2252             restriction. The binary blobs are created as KMS standalone objects,
2253             and blob property instance values store the ID of their associated
2254             blob object.</para>
2255             <para>Blob properties are only used for the connector EDID property
2256             and cannot be created by drivers.</para></listitem>
2257         </varlistentry>
2258       </variablelist>
2259     </para>
2260     <para>
2261       To create a property drivers call one of the following functions depending
2262       on the property type. All property creation functions take property flags
2263       and name, as well as type-specific arguments.
2264       <itemizedlist>
2265         <listitem>
2266           <synopsis>struct drm_property *drm_property_create_range(struct drm_device *dev, int flags,
2267                                                const char *name,
2268                                                uint64_t min, uint64_t max);</synopsis>
2269           <para>Create a range property with the given minimum and maximum
2270             values.</para>
2271         </listitem>
2272         <listitem>
2273           <synopsis>struct drm_property *drm_property_create_enum(struct drm_device *dev, int flags,
2274                                               const char *name,
2275                                               const struct drm_prop_enum_list *props,
2276                                               int num_values);</synopsis>
2277           <para>Create an enumerated property. The <parameter>props</parameter>
2278             argument points to an array of <parameter>num_values</parameter>
2279             value-name pairs.</para>
2280         </listitem>
2281         <listitem>
2282           <synopsis>struct drm_property *drm_property_create_bitmask(struct drm_device *dev,
2283                                                  int flags, const char *name,
2284                                                  const struct drm_prop_enum_list *props,
2285                                                  int num_values);</synopsis>
2286           <para>Create a bitmask property. The <parameter>props</parameter>
2287             argument points to an array of <parameter>num_values</parameter>
2288             value-name pairs.</para>
2289         </listitem>
2290       </itemizedlist>
2291     </para>
2292     <para>
2293       Properties can additionally be created as immutable, in which case they
2294       will be read-only for applications but can be modified by the driver. To
2295       create an immutable property drivers must set the DRM_MODE_PROP_IMMUTABLE
2296       flag at property creation time.
2297     </para>
2298     <para>
2299       When no array of value-name pairs is readily available at property
2300       creation time for enumerated or range properties, drivers can create
2301       the property using the <function>drm_property_create</function> function
2302       and manually add enumeration value-name pairs by calling the
2303       <function>drm_property_add_enum</function> function. Care must be taken to
2304       properly specify the property type through the <parameter>flags</parameter>
2305       argument.
2306     </para>
2307     <para>
2308       After creating properties drivers can attach property instances to CRTC,
2309       connector and plane objects by calling the
2310       <function>drm_object_attach_property</function>. The function takes a
2311       pointer to the target object, a pointer to the previously created property
2312       and an initial instance value.
2313     </para>
2314   </sect1>
2315
2316   <!-- Internals: vertical blanking -->
2317
2318   <sect1 id="drm-vertical-blank">
2319     <title>Vertical Blanking</title>
2320     <para>
2321       Vertical blanking plays a major role in graphics rendering. To achieve
2322       tear-free display, users must synchronize page flips and/or rendering to
2323       vertical blanking. The DRM API offers ioctls to perform page flips
2324       synchronized to vertical blanking and wait for vertical blanking.
2325     </para>
2326     <para>
2327       The DRM core handles most of the vertical blanking management logic, which
2328       involves filtering out spurious interrupts, keeping race-free blanking
2329       counters, coping with counter wrap-around and resets and keeping use
2330       counts. It relies on the driver to generate vertical blanking interrupts
2331       and optionally provide a hardware vertical blanking counter. Drivers must
2332       implement the following operations.
2333     </para>
2334     <itemizedlist>
2335       <listitem>
2336         <synopsis>int (*enable_vblank) (struct drm_device *dev, int crtc);
2337 void (*disable_vblank) (struct drm_device *dev, int crtc);</synopsis>
2338         <para>
2339           Enable or disable vertical blanking interrupts for the given CRTC.
2340         </para>
2341       </listitem>
2342       <listitem>
2343         <synopsis>u32 (*get_vblank_counter) (struct drm_device *dev, int crtc);</synopsis>
2344         <para>
2345           Retrieve the value of the vertical blanking counter for the given
2346           CRTC. If the hardware maintains a vertical blanking counter its value
2347           should be returned. Otherwise drivers can use the
2348           <function>drm_vblank_count</function> helper function to handle this
2349           operation.
2350         </para>
2351       </listitem>
2352     </itemizedlist>
2353     <para>
2354       Drivers must initialize the vertical blanking handling core with a call to
2355       <function>drm_vblank_init</function> in their
2356       <methodname>load</methodname> operation. The function will set the struct
2357       <structname>drm_device</structname>
2358       <structfield>vblank_disable_allowed</structfield> field to 0. This will
2359       keep vertical blanking interrupts enabled permanently until the first mode
2360       set operation, where <structfield>vblank_disable_allowed</structfield> is
2361       set to 1. The reason behind this is not clear. Drivers can set the field
2362       to 1 after <function>calling drm_vblank_init</function> to make vertical
2363       blanking interrupts dynamically managed from the beginning.
2364     </para>
2365     <para>
2366       Vertical blanking interrupts can be enabled by the DRM core or by drivers
2367       themselves (for instance to handle page flipping operations). The DRM core
2368       maintains a vertical blanking use count to ensure that the interrupts are
2369       not disabled while a user still needs them. To increment the use count,
2370       drivers call <function>drm_vblank_get</function>. Upon return vertical
2371       blanking interrupts are guaranteed to be enabled.
2372     </para>
2373     <para>
2374       To decrement the use count drivers call
2375       <function>drm_vblank_put</function>. Only when the use count drops to zero
2376       will the DRM core disable the vertical blanking interrupts after a delay
2377       by scheduling a timer. The delay is accessible through the vblankoffdelay
2378       module parameter or the <varname>drm_vblank_offdelay</varname> global
2379       variable and expressed in milliseconds. Its default value is 5000 ms.
2380     </para>
2381     <para>
2382       When a vertical blanking interrupt occurs drivers only need to call the
2383       <function>drm_handle_vblank</function> function to account for the
2384       interrupt.
2385     </para>
2386     <para>
2387       Resources allocated by <function>drm_vblank_init</function> must be freed
2388       with a call to <function>drm_vblank_cleanup</function> in the driver
2389       <methodname>unload</methodname> operation handler.
2390     </para>
2391   </sect1>
2392
2393   <!-- Internals: open/close, file operations and ioctls -->
2394
2395   <sect1>
2396     <title>Open/Close, File Operations and IOCTLs</title>
2397     <sect2>
2398       <title>Open and Close</title>
2399       <synopsis>int (*firstopen) (struct drm_device *);
2400 void (*lastclose) (struct drm_device *);
2401 int (*open) (struct drm_device *, struct drm_file *);
2402 void (*preclose) (struct drm_device *, struct drm_file *);
2403 void (*postclose) (struct drm_device *, struct drm_file *);</synopsis>
2404       <abstract>Open and close handlers. None of those methods are mandatory.
2405       </abstract>
2406       <para>
2407         The <methodname>firstopen</methodname> method is called by the DRM core
2408         for legacy UMS (User Mode Setting) drivers only when an application
2409         opens a device that has no other opened file handle. UMS drivers can
2410         implement it to acquire device resources. KMS drivers can't use the
2411         method and must acquire resources in the <methodname>load</methodname>
2412         method instead.
2413       </para>
2414       <para>
2415         Similarly the <methodname>lastclose</methodname> method is called when
2416         the last application holding a file handle opened on the device closes
2417         it, for both UMS and KMS drivers. Additionally, the method is also
2418         called at module unload time or, for hot-pluggable devices, when the
2419         device is unplugged. The <methodname>firstopen</methodname> and
2420         <methodname>lastclose</methodname> calls can thus be unbalanced.
2421       </para>
2422       <para>
2423         The <methodname>open</methodname> method is called every time the device
2424         is opened by an application. Drivers can allocate per-file private data
2425         in this method and store them in the struct
2426         <structname>drm_file</structname> <structfield>driver_priv</structfield>
2427         field. Note that the <methodname>open</methodname> method is called
2428         before <methodname>firstopen</methodname>.
2429       </para>
2430       <para>
2431         The close operation is split into <methodname>preclose</methodname> and
2432         <methodname>postclose</methodname> methods. Drivers must stop and
2433         cleanup all per-file operations in the <methodname>preclose</methodname>
2434         method. For instance pending vertical blanking and page flip events must
2435         be cancelled. No per-file operation is allowed on the file handle after
2436         returning from the <methodname>preclose</methodname> method.
2437       </para>
2438       <para>
2439         Finally the <methodname>postclose</methodname> method is called as the
2440         last step of the close operation, right before calling the
2441         <methodname>lastclose</methodname> method if no other open file handle
2442         exists for the device. Drivers that have allocated per-file private data
2443         in the <methodname>open</methodname> method should free it here.
2444       </para>
2445       <para>
2446         The <methodname>lastclose</methodname> method should restore CRTC and
2447         plane properties to default value, so that a subsequent open of the
2448         device will not inherit state from the previous user. It can also be
2449         used to execute delayed power switching state changes, e.g. in
2450         conjunction with the vga-switcheroo infrastructure. Beyond that KMS
2451         drivers should not do any further cleanup. Only legacy UMS drivers might
2452         need to clean up device state so that the vga console or an independent
2453         fbdev driver could take over.
2454       </para>
2455     </sect2>
2456     <sect2>
2457       <title>File Operations</title>
2458       <synopsis>const struct file_operations *fops</synopsis>
2459       <abstract>File operations for the DRM device node.</abstract>
2460       <para>
2461         Drivers must define the file operations structure that forms the DRM
2462         userspace API entry point, even though most of those operations are
2463         implemented in the DRM core. The <methodname>open</methodname>,
2464         <methodname>release</methodname> and <methodname>ioctl</methodname>
2465         operations are handled by
2466         <programlisting>
2467         .owner = THIS_MODULE,
2468         .open = drm_open,
2469         .release = drm_release,
2470         .unlocked_ioctl = drm_ioctl,
2471   #ifdef CONFIG_COMPAT
2472         .compat_ioctl = drm_compat_ioctl,
2473   #endif
2474         </programlisting>
2475       </para>
2476       <para>
2477         Drivers that implement private ioctls that requires 32/64bit
2478         compatibility support must provide their own
2479         <methodname>compat_ioctl</methodname> handler that processes private
2480         ioctls and calls <function>drm_compat_ioctl</function> for core ioctls.
2481       </para>
2482       <para>
2483         The <methodname>read</methodname> and <methodname>poll</methodname>
2484         operations provide support for reading DRM events and polling them. They
2485         are implemented by
2486         <programlisting>
2487         .poll = drm_poll,
2488         .read = drm_read,
2489         .llseek = no_llseek,
2490         </programlisting>
2491       </para>
2492       <para>
2493         The memory mapping implementation varies depending on how the driver
2494         manages memory. Pre-GEM drivers will use <function>drm_mmap</function>,
2495         while GEM-aware drivers will use <function>drm_gem_mmap</function>. See
2496         <xref linkend="drm-gem"/>.
2497         <programlisting>
2498         .mmap = drm_gem_mmap,
2499         </programlisting>
2500       </para>
2501       <para>
2502         No other file operation is supported by the DRM API.
2503       </para>
2504     </sect2>
2505     <sect2>
2506       <title>IOCTLs</title>
2507       <synopsis>struct drm_ioctl_desc *ioctls;
2508 int num_ioctls;</synopsis>
2509       <abstract>Driver-specific ioctls descriptors table.</abstract>
2510       <para>
2511         Driver-specific ioctls numbers start at DRM_COMMAND_BASE. The ioctls
2512         descriptors table is indexed by the ioctl number offset from the base
2513         value. Drivers can use the DRM_IOCTL_DEF_DRV() macro to initialize the
2514         table entries.
2515       </para>
2516       <para>
2517         <programlisting>DRM_IOCTL_DEF_DRV(ioctl, func, flags)</programlisting>
2518         <para>
2519           <parameter>ioctl</parameter> is the ioctl name. Drivers must define
2520           the DRM_##ioctl and DRM_IOCTL_##ioctl macros to the ioctl number
2521           offset from DRM_COMMAND_BASE and the ioctl number respectively. The
2522           first macro is private to the device while the second must be exposed
2523           to userspace in a public header.
2524         </para>
2525         <para>
2526           <parameter>func</parameter> is a pointer to the ioctl handler function
2527           compatible with the <type>drm_ioctl_t</type> type.
2528           <programlisting>typedef int drm_ioctl_t(struct drm_device *dev, void *data,
2529                 struct drm_file *file_priv);</programlisting>
2530         </para>
2531         <para>
2532           <parameter>flags</parameter> is a bitmask combination of the following
2533           values. It restricts how the ioctl is allowed to be called.
2534           <itemizedlist>
2535             <listitem><para>
2536               DRM_AUTH - Only authenticated callers allowed
2537             </para></listitem>
2538             <listitem><para>
2539               DRM_MASTER - The ioctl can only be called on the master file
2540               handle
2541             </para></listitem>
2542             <listitem><para>
2543               DRM_ROOT_ONLY - Only callers with the SYSADMIN capability allowed
2544             </para></listitem>
2545             <listitem><para>
2546               DRM_CONTROL_ALLOW - The ioctl can only be called on a control
2547               device
2548             </para></listitem>
2549             <listitem><para>
2550               DRM_UNLOCKED - The ioctl handler will be called without locking
2551               the DRM global mutex
2552             </para></listitem>
2553           </itemizedlist>
2554         </para>
2555       </para>
2556     </sect2>
2557   </sect1>
2558
2559   <sect1>
2560     <title>Command submission &amp; fencing</title>
2561     <para>
2562       This should cover a few device-specific command submission
2563       implementations.
2564     </para>
2565   </sect1>
2566
2567   <!-- Internals: suspend/resume -->
2568
2569   <sect1>
2570     <title>Suspend/Resume</title>
2571     <para>
2572       The DRM core provides some suspend/resume code, but drivers wanting full
2573       suspend/resume support should provide save() and restore() functions.
2574       These are called at suspend, hibernate, or resume time, and should perform
2575       any state save or restore required by your device across suspend or
2576       hibernate states.
2577     </para>
2578     <synopsis>int (*suspend) (struct drm_device *, pm_message_t state);
2579 int (*resume) (struct drm_device *);</synopsis>
2580     <para>
2581       Those are legacy suspend and resume methods. New driver should use the
2582       power management interface provided by their bus type (usually through
2583       the struct <structname>device_driver</structname> dev_pm_ops) and set
2584       these methods to NULL.
2585     </para>
2586   </sect1>
2587
2588   <sect1>
2589     <title>DMA services</title>
2590     <para>
2591       This should cover how DMA mapping etc. is supported by the core.
2592       These functions are deprecated and should not be used.
2593     </para>
2594   </sect1>
2595   </chapter>
2596
2597 <!-- TODO
2598
2599 - Add a glossary
2600 - Document the struct_mutex catch-all lock
2601 - Document connector properties
2602
2603 - Why is the load method optional?
2604 - What are drivers supposed to set the initial display state to, and how?
2605   Connector's DPMS states are not initialized and are thus equal to
2606   DRM_MODE_DPMS_ON. The fbcon compatibility layer calls
2607   drm_helper_disable_unused_functions(), which disables unused encoders and
2608   CRTCs, but doesn't touch the connectors' DPMS state, and
2609   drm_helper_connector_dpms() in reaction to fbdev blanking events. Do drivers
2610   that don't implement (or just don't use) fbcon compatibility need to call
2611   those functions themselves?
2612 - KMS drivers must call drm_vblank_pre_modeset() and drm_vblank_post_modeset()
2613   around mode setting. Should this be done in the DRM core?
2614 - vblank_disable_allowed is set to 1 in the first drm_vblank_post_modeset()
2615   call and never set back to 0. It seems to be safe to permanently set it to 1
2616   in drm_vblank_init() for KMS driver, and it might be safe for UMS drivers as
2617   well. This should be investigated.
2618 - crtc and connector .save and .restore operations are only used internally in
2619   drivers, should they be removed from the core?
2620 - encoder mid-layer .save and .restore operations are only used internally in
2621   drivers, should they be removed from the core?
2622 - encoder mid-layer .detect operation is only used internally in drivers,
2623   should it be removed from the core?
2624 -->
2625
2626   <!-- External interfaces -->
2627
2628   <chapter id="drmExternals">
2629     <title>Userland interfaces</title>
2630     <para>
2631       The DRM core exports several interfaces to applications,
2632       generally intended to be used through corresponding libdrm
2633       wrapper functions.  In addition, drivers export device-specific
2634       interfaces for use by userspace drivers &amp; device-aware
2635       applications through ioctls and sysfs files.
2636     </para>
2637     <para>
2638       External interfaces include: memory mapping, context management,
2639       DMA operations, AGP management, vblank control, fence
2640       management, memory management, and output management.
2641     </para>
2642     <para>
2643       Cover generic ioctls and sysfs layout here.  We only need high-level
2644       info, since man pages should cover the rest.
2645     </para>
2646
2647   <!-- External: vblank handling -->
2648
2649     <sect1>
2650       <title>VBlank event handling</title>
2651       <para>
2652         The DRM core exposes two vertical blank related ioctls:
2653         <variablelist>
2654           <varlistentry>
2655             <term>DRM_IOCTL_WAIT_VBLANK</term>
2656             <listitem>
2657               <para>
2658                 This takes a struct drm_wait_vblank structure as its argument,
2659                 and it is used to block or request a signal when a specified
2660                 vblank event occurs.
2661               </para>
2662             </listitem>
2663           </varlistentry>
2664           <varlistentry>
2665             <term>DRM_IOCTL_MODESET_CTL</term>
2666             <listitem>
2667               <para>
2668                 This should be called by application level drivers before and
2669                 after mode setting, since on many devices the vertical blank
2670                 counter is reset at that time.  Internally, the DRM snapshots
2671                 the last vblank count when the ioctl is called with the
2672                 _DRM_PRE_MODESET command, so that the counter won't go backwards
2673                 (which is dealt with when _DRM_POST_MODESET is used).
2674               </para>
2675             </listitem>
2676           </varlistentry>
2677         </variablelist>
2678 <!--!Edrivers/char/drm/drm_irq.c-->
2679       </para>
2680     </sect1>
2681
2682   </chapter>
2683
2684   <!-- API reference -->
2685
2686   <appendix id="drmDriverApi">
2687     <title>DRM Driver API</title>
2688     <para>
2689       Include auto-generated API reference here (need to reference it
2690       from paragraphs above too).
2691     </para>
2692   </appendix>
2693
2694 </book>