compositor-drm: move mode list to set_mode()
[platform/upstream/weston.git] / libweston / compositor-drm.c
1 /*
2  * Copyright © 2008-2011 Kristian Høgsberg
3  * Copyright © 2011 Intel Corporation
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining
6  * a copy of this software and associated documentation files (the
7  * "Software"), to deal in the Software without restriction, including
8  * without limitation the rights to use, copy, modify, merge, publish,
9  * distribute, sublicense, and/or sell copies of the Software, and to
10  * permit persons to whom the Software is furnished to do so, subject to
11  * the following conditions:
12  *
13  * The above copyright notice and this permission notice (including the
14  * next paragraph) shall be included in all copies or substantial
15  * portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
21  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
22  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24  * SOFTWARE.
25  */
26
27 #include "config.h"
28
29 #include <errno.h>
30 #include <stdint.h>
31 #include <stdlib.h>
32 #include <ctype.h>
33 #include <string.h>
34 #include <fcntl.h>
35 #include <unistd.h>
36 #include <linux/input.h>
37 #include <linux/vt.h>
38 #include <assert.h>
39 #include <sys/mman.h>
40 #include <dlfcn.h>
41 #include <time.h>
42
43 #include <xf86drm.h>
44 #include <xf86drmMode.h>
45 #include <drm_fourcc.h>
46
47 #include <gbm.h>
48 #include <libudev.h>
49
50 #include "compositor.h"
51 #include "compositor-drm.h"
52 #include "shared/helpers.h"
53 #include "shared/timespec-util.h"
54 #include "gl-renderer.h"
55 #include "weston-egl-ext.h"
56 #include "pixman-renderer.h"
57 #include "pixel-formats.h"
58 #include "libbacklight.h"
59 #include "libinput-seat.h"
60 #include "launcher-util.h"
61 #include "vaapi-recorder.h"
62 #include "presentation-time-server-protocol.h"
63 #include "linux-dmabuf.h"
64 #include "linux-dmabuf-unstable-v1-server-protocol.h"
65
66 #ifndef DRM_CAP_TIMESTAMP_MONOTONIC
67 #define DRM_CAP_TIMESTAMP_MONOTONIC 0x6
68 #endif
69
70 #ifndef DRM_CLIENT_CAP_UNIVERSAL_PLANES
71 #define DRM_CLIENT_CAP_UNIVERSAL_PLANES 2
72 #endif
73
74 #ifndef DRM_CAP_CURSOR_WIDTH
75 #define DRM_CAP_CURSOR_WIDTH 0x8
76 #endif
77
78 #ifndef DRM_CAP_CURSOR_HEIGHT
79 #define DRM_CAP_CURSOR_HEIGHT 0x9
80 #endif
81
82 #ifndef GBM_BO_USE_CURSOR
83 #define GBM_BO_USE_CURSOR GBM_BO_USE_CURSOR_64X64
84 #endif
85
86 #define MAX_CLONED_CONNECTORS 1
87
88 /**
89  * Represents the values of an enum-type KMS property
90  */
91 struct drm_property_enum_info {
92         const char *name; /**< name as string (static, not freed) */
93         bool valid; /**< true if value is supported; ignore if false */
94         uint64_t value; /**< raw value */
95 };
96
97 /**
98  * Holds information on a DRM property, including its ID and the enum
99  * values it holds.
100  *
101  * DRM properties are allocated dynamically, and maintained as DRM objects
102  * within the normal object ID space; they thus do not have a stable ID
103  * to refer to. This includes enum values, which must be referred to by
104  * integer values, but these are not stable.
105  *
106  * drm_property_info allows a cache to be maintained where Weston can use
107  * enum values internally to refer to properties, with the mapping to DRM
108  * ID values being maintained internally.
109  */
110 struct drm_property_info {
111         const char *name; /**< name as string (static, not freed) */
112         uint32_t prop_id; /**< KMS property object ID */
113         unsigned int num_enum_values; /**< number of enum values */
114         struct drm_property_enum_info *enum_values; /**< array of enum values */
115 };
116
117 /**
118  * List of properties attached to DRM planes
119  */
120 enum wdrm_plane_property {
121         WDRM_PLANE_TYPE = 0,
122         WDRM_PLANE_SRC_X,
123         WDRM_PLANE_SRC_Y,
124         WDRM_PLANE_SRC_W,
125         WDRM_PLANE_SRC_H,
126         WDRM_PLANE_CRTC_X,
127         WDRM_PLANE_CRTC_Y,
128         WDRM_PLANE_CRTC_W,
129         WDRM_PLANE_CRTC_H,
130         WDRM_PLANE_FB_ID,
131         WDRM_PLANE_CRTC_ID,
132         WDRM_PLANE__COUNT
133 };
134
135 /**
136  * Possible values for the WDRM_PLANE_TYPE property.
137  */
138 enum wdrm_plane_type {
139         WDRM_PLANE_TYPE_PRIMARY = 0,
140         WDRM_PLANE_TYPE_CURSOR,
141         WDRM_PLANE_TYPE_OVERLAY,
142         WDRM_PLANE_TYPE__COUNT
143 };
144
145 static struct drm_property_enum_info plane_type_enums[] = {
146         [WDRM_PLANE_TYPE_PRIMARY] = {
147                 .name = "Primary",
148         },
149         [WDRM_PLANE_TYPE_OVERLAY] = {
150                 .name = "Overlay",
151         },
152         [WDRM_PLANE_TYPE_CURSOR] = {
153                 .name = "Cursor",
154         },
155 };
156
157 static const struct drm_property_info plane_props[] = {
158         [WDRM_PLANE_TYPE] = {
159                 .name = "type",
160                 .enum_values = plane_type_enums,
161                 .num_enum_values = WDRM_PLANE_TYPE__COUNT,
162         },
163         [WDRM_PLANE_SRC_X] = { .name = "SRC_X", },
164         [WDRM_PLANE_SRC_Y] = { .name = "SRC_Y", },
165         [WDRM_PLANE_SRC_W] = { .name = "SRC_W", },
166         [WDRM_PLANE_SRC_H] = { .name = "SRC_H", },
167         [WDRM_PLANE_CRTC_X] = { .name = "CRTC_X", },
168         [WDRM_PLANE_CRTC_Y] = { .name = "CRTC_Y", },
169         [WDRM_PLANE_CRTC_W] = { .name = "CRTC_W", },
170         [WDRM_PLANE_CRTC_H] = { .name = "CRTC_H", },
171         [WDRM_PLANE_FB_ID] = { .name = "FB_ID", },
172         [WDRM_PLANE_CRTC_ID] = { .name = "CRTC_ID", },
173 };
174
175 /**
176  * List of properties attached to a DRM connector
177  */
178 enum wdrm_connector_property {
179         WDRM_CONNECTOR_EDID = 0,
180         WDRM_CONNECTOR_DPMS,
181         WDRM_CONNECTOR_CRTC_ID,
182         WDRM_CONNECTOR__COUNT
183 };
184
185 static const struct drm_property_info connector_props[] = {
186         [WDRM_CONNECTOR_EDID] = { .name = "EDID" },
187         [WDRM_CONNECTOR_DPMS] = { .name = "DPMS" },
188         [WDRM_CONNECTOR_CRTC_ID] = { .name = "CRTC_ID", },
189 };
190
191 /**
192  * List of properties attached to DRM CRTCs
193  */
194 enum wdrm_crtc_property {
195         WDRM_CRTC_MODE_ID = 0,
196         WDRM_CRTC_ACTIVE,
197         WDRM_CRTC__COUNT
198 };
199
200 static const struct drm_property_info crtc_props[] = {
201         [WDRM_CRTC_MODE_ID] = { .name = "MODE_ID", },
202         [WDRM_CRTC_ACTIVE] = { .name = "ACTIVE", },
203 };
204
205 /**
206  * Mode for drm_output_state_duplicate.
207  */
208 enum drm_output_state_duplicate_mode {
209         DRM_OUTPUT_STATE_CLEAR_PLANES, /**< reset all planes to off */
210         DRM_OUTPUT_STATE_PRESERVE_PLANES, /**< preserve plane state */
211 };
212
213 /**
214  * Mode for drm_pending_state_apply and co.
215  */
216 enum drm_state_apply_mode {
217         DRM_STATE_APPLY_SYNC, /**< state fully processed */
218         DRM_STATE_APPLY_ASYNC, /**< state pending event delivery */
219 };
220
221 struct drm_backend {
222         struct weston_backend base;
223         struct weston_compositor *compositor;
224
225         struct udev *udev;
226         struct wl_event_source *drm_source;
227
228         struct udev_monitor *udev_monitor;
229         struct wl_event_source *udev_drm_source;
230
231         struct {
232                 int id;
233                 int fd;
234                 char *filename;
235         } drm;
236         struct gbm_device *gbm;
237         struct wl_listener session_listener;
238         uint32_t gbm_format;
239
240         /* we need these parameters in order to not fail drmModeAddFB2()
241          * due to out of bounds dimensions, and then mistakenly set
242          * sprites_are_broken:
243          */
244         int min_width, max_width;
245         int min_height, max_height;
246
247         struct wl_list plane_list;
248         int sprites_are_broken;
249         int sprites_hidden;
250
251         void *repaint_data;
252
253         bool state_invalid;
254
255         /* Connector and CRTC IDs not used by any enabled output. */
256         struct wl_array unused_connectors;
257         struct wl_array unused_crtcs;
258
259         int cursors_are_broken;
260
261         bool universal_planes;
262         bool atomic_modeset;
263
264         int use_pixman;
265
266         struct udev_input input;
267
268         int32_t cursor_width;
269         int32_t cursor_height;
270
271         uint32_t pageflip_timeout;
272
273         bool shutting_down;
274 };
275
276 struct drm_mode {
277         struct weston_mode base;
278         drmModeModeInfo mode_info;
279         uint32_t blob_id;
280 };
281
282 enum drm_fb_type {
283         BUFFER_INVALID = 0, /**< never used */
284         BUFFER_CLIENT, /**< directly sourced from client */
285         BUFFER_PIXMAN_DUMB, /**< internal Pixman rendering */
286         BUFFER_GBM_SURFACE, /**< internal EGL rendering */
287         BUFFER_CURSOR, /**< internal cursor buffer */
288 };
289
290 struct drm_fb {
291         enum drm_fb_type type;
292
293         int refcnt;
294
295         uint32_t fb_id, stride, handle, size;
296         const struct pixel_format_info *format;
297         int width, height;
298         int fd;
299         struct weston_buffer_reference buffer_ref;
300
301         /* Used by gbm fbs */
302         struct gbm_bo *bo;
303         struct gbm_surface *gbm_surface;
304
305         /* Used by dumb fbs */
306         void *map;
307 };
308
309 struct drm_edid {
310         char eisa_id[13];
311         char monitor_name[13];
312         char pnp_id[5];
313         char serial_number[13];
314 };
315
316 /**
317  * Pending state holds one or more drm_output_state structures, collected from
318  * performing repaint. This pending state is transient, and only lives between
319  * beginning a repaint group and flushing the results: after flush, each
320  * output state will complete and be retired separately.
321  */
322 struct drm_pending_state {
323         struct drm_backend *backend;
324         struct wl_list output_list;
325 };
326
327 /*
328  * Output state holds the dynamic state for one Weston output, i.e. a KMS CRTC,
329  * plus >= 1 each of encoder/connector/plane. Since everything but the planes
330  * is currently statically assigned per-output, we mainly use this to track
331  * plane state.
332  *
333  * pending_state is set when the output state is owned by a pending_state,
334  * i.e. when it is being constructed and has not yet been applied. When the
335  * output state has been applied, the owning pending_state is freed.
336  */
337 struct drm_output_state {
338         struct drm_pending_state *pending_state;
339         struct drm_output *output;
340         struct wl_list link;
341         enum dpms_enum dpms;
342         struct wl_list plane_list;
343 };
344
345 /**
346  * Plane state holds the dynamic state for a plane: where it is positioned,
347  * and which buffer it is currently displaying.
348  *
349  * The plane state is owned by an output state, except when setting an initial
350  * state. See drm_output_state for notes on state object lifetime.
351  */
352 struct drm_plane_state {
353         struct drm_plane *plane;
354         struct drm_output *output;
355         struct drm_output_state *output_state;
356
357         struct drm_fb *fb;
358
359         int32_t src_x, src_y;
360         uint32_t src_w, src_h;
361         int32_t dest_x, dest_y;
362         uint32_t dest_w, dest_h;
363
364         bool complete;
365
366         struct wl_list link; /* drm_output_state::plane_list */
367 };
368
369 /**
370  * A plane represents one buffer, positioned within a CRTC, and stacked
371  * relative to other planes on the same CRTC.
372  *
373  * Each CRTC has a 'primary plane', which use used to display the classic
374  * framebuffer contents, as accessed through the legacy drmModeSetCrtc
375  * call (which combines setting the CRTC's actual physical mode, and the
376  * properties of the primary plane).
377  *
378  * The cursor plane also has its own alternate legacy API.
379  *
380  * Other planes are used opportunistically to display content we do not
381  * wish to blit into the primary plane. These non-primary/cursor planes
382  * are referred to as 'sprites'.
383  */
384 struct drm_plane {
385         struct weston_plane base;
386
387         struct drm_backend *backend;
388
389         enum wdrm_plane_type type;
390
391         uint32_t possible_crtcs;
392         uint32_t plane_id;
393         uint32_t count_formats;
394
395         struct drm_property_info props[WDRM_PLANE__COUNT];
396
397         /* The last state submitted to the kernel for this plane. */
398         struct drm_plane_state *state_cur;
399
400         struct wl_list link;
401
402         uint32_t formats[];
403 };
404
405 struct drm_head {
406         struct weston_head base;
407         struct drm_backend *backend;
408
409         struct drm_output *output; /* XXX: temporary */
410
411         drmModeConnector *connector;
412         uint32_t connector_id;
413         struct drm_edid edid;
414
415         /* Holds the properties for the connector */
416         struct drm_property_info props_conn[WDRM_CONNECTOR__COUNT];
417
418         struct backlight *backlight;
419
420         drmModeModeInfo inherited_mode; /**< Original mode on the connector */
421 };
422
423 struct drm_output {
424         struct weston_output base;
425
426         uint32_t crtc_id; /* object ID to pass to DRM functions */
427         int pipe; /* index of CRTC in resource array / bitmasks */
428
429         /* Holds the properties for the CRTC */
430         struct drm_property_info props_crtc[WDRM_CRTC__COUNT];
431
432         int vblank_pending;
433         int page_flip_pending;
434         int atomic_complete_pending;
435         int destroy_pending;
436         int disable_pending;
437         int dpms_off_pending;
438
439         struct drm_fb *gbm_cursor_fb[2];
440         struct drm_plane *cursor_plane;
441         struct weston_view *cursor_view;
442         int current_cursor;
443
444         struct gbm_surface *gbm_surface;
445         uint32_t gbm_format;
446
447         /* Plane being displayed directly on the CRTC */
448         struct drm_plane *scanout_plane;
449
450         /* The last state submitted to the kernel for this CRTC. */
451         struct drm_output_state *state_cur;
452         /* The previously-submitted state, where the hardware has not
453          * yet acknowledged completion of state_cur. */
454         struct drm_output_state *state_last;
455
456         struct drm_fb *dumb[2];
457         pixman_image_t *image[2];
458         int current_image;
459         pixman_region32_t previous_damage;
460
461         struct vaapi_recorder *recorder;
462         struct wl_listener recorder_frame_listener;
463
464         struct wl_event_source *pageflip_timer;
465 };
466
467 static struct gl_renderer_interface *gl_renderer;
468
469 static const char default_seat[] = "seat0";
470
471 static void
472 wl_array_remove_uint32(struct wl_array *array, uint32_t elm)
473 {
474         uint32_t *pos, *end;
475
476         end = (uint32_t *) ((char *) array->data + array->size);
477
478         wl_array_for_each(pos, array) {
479                 if (*pos != elm)
480                         continue;
481
482                 array->size -= sizeof(*pos);
483                 if (pos + 1 == end)
484                         break;
485
486                 memmove(pos, pos + 1, (char *) end -  (char *) (pos + 1));
487                 break;
488         }
489 }
490
491 static inline struct drm_head *
492 to_drm_head(struct weston_head *base)
493 {
494         return container_of(base, struct drm_head, base);
495 }
496
497 static inline struct drm_output *
498 to_drm_output(struct weston_output *base)
499 {
500         return container_of(base, struct drm_output, base);
501 }
502
503 static inline struct drm_backend *
504 to_drm_backend(struct weston_compositor *base)
505 {
506         return container_of(base->backend, struct drm_backend, base);
507 }
508
509 static int
510 pageflip_timeout(void *data) {
511         /*
512          * Our timer just went off, that means we're not receiving drm
513          * page flip events anymore for that output. Let's gracefully exit
514          * weston with a return value so devs can debug what's going on.
515          */
516         struct drm_output *output = data;
517         struct weston_compositor *compositor = output->base.compositor;
518
519         weston_log("Pageflip timeout reached on output %s, your "
520                    "driver is probably buggy!  Exiting.\n",
521                    output->base.name);
522         weston_compositor_exit_with_code(compositor, EXIT_FAILURE);
523
524         return 0;
525 }
526
527 /* Creates the pageflip timer. Note that it isn't armed by default */
528 static int
529 drm_output_pageflip_timer_create(struct drm_output *output)
530 {
531         struct wl_event_loop *loop = NULL;
532         struct weston_compositor *ec = output->base.compositor;
533
534         loop = wl_display_get_event_loop(ec->wl_display);
535         assert(loop);
536         output->pageflip_timer = wl_event_loop_add_timer(loop,
537                                                          pageflip_timeout,
538                                                          output);
539
540         if (output->pageflip_timer == NULL) {
541                 weston_log("creating drm pageflip timer failed: %m\n");
542                 return -1;
543         }
544
545         return 0;
546 }
547
548 static inline struct drm_mode *
549 to_drm_mode(struct weston_mode *base)
550 {
551         return container_of(base, struct drm_mode, base);
552 }
553
554 /**
555  * Get the current value of a KMS property
556  *
557  * Given a drmModeObjectGetProperties return, as well as the drm_property_info
558  * for the target property, return the current value of that property,
559  * with an optional default. If the property is a KMS enum type, the return
560  * value will be translated into the appropriate internal enum.
561  *
562  * If the property is not present, the default value will be returned.
563  *
564  * @param info Internal structure for property to look up
565  * @param props Raw KMS properties for the target object
566  * @param def Value to return if property is not found
567  */
568 static uint64_t
569 drm_property_get_value(struct drm_property_info *info,
570                        drmModeObjectPropertiesPtr props,
571                        uint64_t def)
572 {
573         unsigned int i;
574
575         if (info->prop_id == 0)
576                 return def;
577
578         for (i = 0; i < props->count_props; i++) {
579                 unsigned int j;
580
581                 if (props->props[i] != info->prop_id)
582                         continue;
583
584                 /* Simple (non-enum) types can return the value directly */
585                 if (info->num_enum_values == 0)
586                         return props->prop_values[i];
587
588                 /* Map from raw value to enum value */
589                 for (j = 0; j < info->num_enum_values; j++) {
590                         if (!info->enum_values[j].valid)
591                                 continue;
592                         if (info->enum_values[j].value != props->prop_values[i])
593                                 continue;
594
595                         return j;
596                 }
597
598                 /* We don't have a mapping for this enum; return default. */
599                 break;
600         }
601
602         return def;
603 }
604
605 /**
606  * Cache DRM property values
607  *
608  * Update a per-object array of drm_property_info structures, given the
609  * DRM properties of the object.
610  *
611  * Call this every time an object newly appears (note that only connectors
612  * can be hotplugged), the first time it is seen, or when its status changes
613  * in a way which invalidates the potential property values (currently, the
614  * only case for this is connector hotplug).
615  *
616  * This updates the property IDs and enum values within the drm_property_info
617  * array.
618  *
619  * DRM property enum values are dynamic at runtime; the user must query the
620  * property to find out the desired runtime value for a requested string
621  * name. Using the 'type' field on planes as an example, there is no single
622  * hardcoded constant for primary plane types; instead, the property must be
623  * queried at runtime to find the value associated with the string "Primary".
624  *
625  * This helper queries and caches the enum values, to allow us to use a set
626  * of compile-time-constant enums portably across various implementations.
627  * The values given in enum_names are searched for, and stored in the
628  * same-indexed field of the map array.
629  *
630  * @param b DRM backend object
631  * @param src DRM property info array to source from
632  * @param info DRM property info array to copy into
633  * @param num_infos Number of entries in the source array
634  * @param props DRM object properties for the object
635  */
636 static void
637 drm_property_info_populate(struct drm_backend *b,
638                            const struct drm_property_info *src,
639                            struct drm_property_info *info,
640                            unsigned int num_infos,
641                            drmModeObjectProperties *props)
642 {
643         drmModePropertyRes *prop;
644         unsigned i, j;
645
646         for (i = 0; i < num_infos; i++) {
647                 unsigned int j;
648
649                 info[i].name = src[i].name;
650                 info[i].prop_id = 0;
651                 info[i].num_enum_values = src[i].num_enum_values;
652
653                 if (src[i].num_enum_values == 0)
654                         continue;
655
656                 info[i].enum_values =
657                         malloc(src[i].num_enum_values *
658                                sizeof(*info[i].enum_values));
659                 assert(info[i].enum_values);
660                 for (j = 0; j < info[i].num_enum_values; j++) {
661                         info[i].enum_values[j].name = src[i].enum_values[j].name;
662                         info[i].enum_values[j].valid = false;
663                 }
664         }
665
666         for (i = 0; i < props->count_props; i++) {
667                 unsigned int k;
668
669                 prop = drmModeGetProperty(b->drm.fd, props->props[i]);
670                 if (!prop)
671                         continue;
672
673                 for (j = 0; j < num_infos; j++) {
674                         if (!strcmp(prop->name, info[j].name))
675                                 break;
676                 }
677
678                 /* We don't know/care about this property. */
679                 if (j == num_infos) {
680 #ifdef DEBUG
681                         weston_log("DRM debug: unrecognized property %u '%s'\n",
682                                    prop->prop_id, prop->name);
683 #endif
684                         drmModeFreeProperty(prop);
685                         continue;
686                 }
687
688                 if (info[j].num_enum_values == 0 &&
689                     (prop->flags & DRM_MODE_PROP_ENUM)) {
690                         weston_log("DRM: expected property %s to not be an"
691                                    " enum, but it is; ignoring\n", prop->name);
692                         drmModeFreeProperty(prop);
693                         continue;
694                 }
695
696                 info[j].prop_id = props->props[i];
697
698                 if (info[j].num_enum_values == 0) {
699                         drmModeFreeProperty(prop);
700                         continue;
701                 }
702
703                 if (!(prop->flags & DRM_MODE_PROP_ENUM)) {
704                         weston_log("DRM: expected property %s to be an enum,"
705                                    " but it is not; ignoring\n", prop->name);
706                         drmModeFreeProperty(prop);
707                         info[j].prop_id = 0;
708                         continue;
709                 }
710
711                 for (k = 0; k < info[j].num_enum_values; k++) {
712                         int l;
713
714                         for (l = 0; l < prop->count_enums; l++) {
715                                 if (!strcmp(prop->enums[l].name,
716                                             info[j].enum_values[k].name))
717                                         break;
718                         }
719
720                         if (l == prop->count_enums)
721                                 continue;
722
723                         info[j].enum_values[k].valid = true;
724                         info[j].enum_values[k].value = prop->enums[l].value;
725                 }
726
727                 drmModeFreeProperty(prop);
728         }
729
730 #ifdef DEBUG
731         for (i = 0; i < num_infos; i++) {
732                 if (info[i].prop_id == 0)
733                         weston_log("DRM warning: property '%s' missing\n",
734                                    info[i].name);
735         }
736 #endif
737 }
738
739 /**
740  * Free DRM property information
741  *
742  * Frees all memory associated with a DRM property info array and zeroes
743  * it out, leaving it usable for a further drm_property_info_update() or
744  * drm_property_info_free().
745  *
746  * @param info DRM property info array
747  * @param num_props Number of entries in array to free
748  */
749 static void
750 drm_property_info_free(struct drm_property_info *info, int num_props)
751 {
752         int i;
753
754         for (i = 0; i < num_props; i++)
755                 free(info[i].enum_values);
756
757         memset(info, 0, sizeof(*info) * num_props);
758 }
759
760 static void
761 drm_output_set_cursor(struct drm_output_state *output_state);
762
763 static void
764 drm_output_update_msc(struct drm_output *output, unsigned int seq);
765
766 static void
767 drm_output_destroy(struct weston_output *output_base);
768
769 /**
770  * Returns true if the plane can be used on the given output for its current
771  * repaint cycle.
772  */
773 static bool
774 drm_plane_is_available(struct drm_plane *plane, struct drm_output *output)
775 {
776         assert(plane->state_cur);
777
778         /* The plane still has a request not yet completed by the kernel. */
779         if (!plane->state_cur->complete)
780                 return false;
781
782         /* The plane is still active on another output. */
783         if (plane->state_cur->output && plane->state_cur->output != output)
784                 return false;
785
786         /* Check whether the plane can be used with this CRTC; possible_crtcs
787          * is a bitmask of CRTC indices (pipe), rather than CRTC object ID. */
788         return !!(plane->possible_crtcs & (1 << output->pipe));
789 }
790
791 static struct drm_output *
792 drm_output_find_by_crtc(struct drm_backend *b, uint32_t crtc_id)
793 {
794         struct drm_output *output;
795
796         wl_list_for_each(output, &b->compositor->output_list, base.link) {
797                 if (output->crtc_id == crtc_id)
798                         return output;
799         }
800
801         return NULL;
802 }
803
804 static struct drm_head *
805 drm_head_find_by_connector(struct drm_backend *backend, uint32_t connector_id)
806 {
807         struct weston_head *base;
808         struct drm_head *head;
809
810         wl_list_for_each(base,
811                          &backend->compositor->head_list, compositor_link) {
812                 head = to_drm_head(base);
813                 if (head->connector_id == connector_id)
814                         return head;
815         }
816
817         return NULL;
818 }
819
820 static struct drm_output *
821 drm_output_find_by_connector(struct drm_backend *b, uint32_t connector_id)
822 {
823         struct drm_head *head;
824
825         /* XXX: like the old version, this counts both enabled and disabled outputs */
826         head = drm_head_find_by_connector(b, connector_id);
827         if (head && head->output)
828                 return head->output;
829
830         return NULL;
831 }
832
833 static void
834 drm_fb_destroy(struct drm_fb *fb)
835 {
836         if (fb->fb_id != 0)
837                 drmModeRmFB(fb->fd, fb->fb_id);
838         weston_buffer_reference(&fb->buffer_ref, NULL);
839         free(fb);
840 }
841
842 static void
843 drm_fb_destroy_dumb(struct drm_fb *fb)
844 {
845         struct drm_mode_destroy_dumb destroy_arg;
846
847         assert(fb->type == BUFFER_PIXMAN_DUMB);
848
849         if (fb->map && fb->size > 0)
850                 munmap(fb->map, fb->size);
851
852         memset(&destroy_arg, 0, sizeof(destroy_arg));
853         destroy_arg.handle = fb->handle;
854         drmIoctl(fb->fd, DRM_IOCTL_MODE_DESTROY_DUMB, &destroy_arg);
855
856         drm_fb_destroy(fb);
857 }
858
859 static void
860 drm_fb_destroy_gbm(struct gbm_bo *bo, void *data)
861 {
862         struct drm_fb *fb = data;
863
864         assert(fb->type == BUFFER_GBM_SURFACE || fb->type == BUFFER_CLIENT ||
865                fb->type == BUFFER_CURSOR);
866         drm_fb_destroy(fb);
867 }
868
869 static struct drm_fb *
870 drm_fb_create_dumb(struct drm_backend *b, int width, int height,
871                    uint32_t format)
872 {
873         struct drm_fb *fb;
874         int ret;
875
876         struct drm_mode_create_dumb create_arg;
877         struct drm_mode_destroy_dumb destroy_arg;
878         struct drm_mode_map_dumb map_arg;
879         uint32_t handles[4] = { 0 }, pitches[4] = { 0 }, offsets[4] = { 0 };
880
881         fb = zalloc(sizeof *fb);
882         if (!fb)
883                 return NULL;
884
885         fb->refcnt = 1;
886
887         fb->format = pixel_format_get_info(format);
888         if (!fb->format) {
889                 weston_log("failed to look up format 0x%lx\n",
890                            (unsigned long) format);
891                 goto err_fb;
892         }
893
894         if (!fb->format->depth || !fb->format->bpp) {
895                 weston_log("format 0x%lx is not compatible with dumb buffers\n",
896                            (unsigned long) format);
897                 goto err_fb;
898         }
899
900         memset(&create_arg, 0, sizeof create_arg);
901         create_arg.bpp = fb->format->bpp;
902         create_arg.width = width;
903         create_arg.height = height;
904
905         ret = drmIoctl(b->drm.fd, DRM_IOCTL_MODE_CREATE_DUMB, &create_arg);
906         if (ret)
907                 goto err_fb;
908
909         fb->type = BUFFER_PIXMAN_DUMB;
910         fb->handle = create_arg.handle;
911         fb->stride = create_arg.pitch;
912         fb->size = create_arg.size;
913         fb->width = width;
914         fb->height = height;
915         fb->fd = b->drm.fd;
916
917         handles[0] = fb->handle;
918         pitches[0] = fb->stride;
919         offsets[0] = 0;
920
921         ret = drmModeAddFB2(b->drm.fd, width, height, fb->format->format,
922                             handles, pitches, offsets, &fb->fb_id, 0);
923         if (ret) {
924                 ret = drmModeAddFB(b->drm.fd, width, height,
925                                    fb->format->depth, fb->format->bpp,
926                                    fb->stride, fb->handle, &fb->fb_id);
927         }
928
929         if (ret)
930                 goto err_bo;
931
932         memset(&map_arg, 0, sizeof map_arg);
933         map_arg.handle = fb->handle;
934         ret = drmIoctl(fb->fd, DRM_IOCTL_MODE_MAP_DUMB, &map_arg);
935         if (ret)
936                 goto err_add_fb;
937
938         fb->map = mmap(NULL, fb->size, PROT_WRITE,
939                        MAP_SHARED, b->drm.fd, map_arg.offset);
940         if (fb->map == MAP_FAILED)
941                 goto err_add_fb;
942
943         return fb;
944
945 err_add_fb:
946         drmModeRmFB(b->drm.fd, fb->fb_id);
947 err_bo:
948         memset(&destroy_arg, 0, sizeof(destroy_arg));
949         destroy_arg.handle = create_arg.handle;
950         drmIoctl(b->drm.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &destroy_arg);
951 err_fb:
952         free(fb);
953         return NULL;
954 }
955
956 static struct drm_fb *
957 drm_fb_ref(struct drm_fb *fb)
958 {
959         fb->refcnt++;
960         return fb;
961 }
962
963 static struct drm_fb *
964 drm_fb_get_from_bo(struct gbm_bo *bo, struct drm_backend *backend,
965                    uint32_t format, enum drm_fb_type type)
966 {
967         struct drm_fb *fb = gbm_bo_get_user_data(bo);
968         uint32_t handles[4] = { 0 }, pitches[4] = { 0 }, offsets[4] = { 0 };
969         int ret;
970
971         if (fb) {
972                 assert(fb->type == type);
973                 return drm_fb_ref(fb);
974         }
975
976         assert(format != 0);
977
978         fb = zalloc(sizeof *fb);
979         if (fb == NULL)
980                 return NULL;
981
982         fb->type = type;
983         fb->refcnt = 1;
984         fb->bo = bo;
985
986         fb->width = gbm_bo_get_width(bo);
987         fb->height = gbm_bo_get_height(bo);
988         fb->stride = gbm_bo_get_stride(bo);
989         fb->handle = gbm_bo_get_handle(bo).u32;
990         fb->format = pixel_format_get_info(format);
991         fb->size = fb->stride * fb->height;
992         fb->fd = backend->drm.fd;
993
994         if (!fb->format) {
995                 weston_log("couldn't look up format 0x%lx\n",
996                            (unsigned long) format);
997                 goto err_free;
998         }
999
1000         if (backend->min_width > fb->width ||
1001             fb->width > backend->max_width ||
1002             backend->min_height > fb->height ||
1003             fb->height > backend->max_height) {
1004                 weston_log("bo geometry out of bounds\n");
1005                 goto err_free;
1006         }
1007
1008         handles[0] = fb->handle;
1009         pitches[0] = fb->stride;
1010         offsets[0] = 0;
1011
1012         ret = drmModeAddFB2(backend->drm.fd, fb->width, fb->height,
1013                             fb->format->format, handles, pitches, offsets,
1014                             &fb->fb_id, 0);
1015         if (ret && fb->format->depth && fb->format->bpp)
1016                 ret = drmModeAddFB(backend->drm.fd, fb->width, fb->height,
1017                                    fb->format->depth, fb->format->bpp,
1018                                    fb->stride, fb->handle, &fb->fb_id);
1019
1020         if (ret) {
1021                 weston_log("failed to create kms fb: %m\n");
1022                 goto err_free;
1023         }
1024
1025         gbm_bo_set_user_data(bo, fb, drm_fb_destroy_gbm);
1026
1027         return fb;
1028
1029 err_free:
1030         free(fb);
1031         return NULL;
1032 }
1033
1034 static void
1035 drm_fb_set_buffer(struct drm_fb *fb, struct weston_buffer *buffer)
1036 {
1037         assert(fb->buffer_ref.buffer == NULL);
1038         assert(fb->type == BUFFER_CLIENT);
1039         weston_buffer_reference(&fb->buffer_ref, buffer);
1040 }
1041
1042 static void
1043 drm_fb_unref(struct drm_fb *fb)
1044 {
1045         if (!fb)
1046                 return;
1047
1048         assert(fb->refcnt > 0);
1049         if (--fb->refcnt > 0)
1050                 return;
1051
1052         switch (fb->type) {
1053         case BUFFER_PIXMAN_DUMB:
1054                 drm_fb_destroy_dumb(fb);
1055                 break;
1056         case BUFFER_CURSOR:
1057         case BUFFER_CLIENT:
1058                 gbm_bo_destroy(fb->bo);
1059                 break;
1060         case BUFFER_GBM_SURFACE:
1061                 gbm_surface_release_buffer(fb->gbm_surface, fb->bo);
1062                 break;
1063         default:
1064                 assert(NULL);
1065                 break;
1066         }
1067 }
1068
1069 /**
1070  * Allocate a new, empty, plane state.
1071  */
1072 static struct drm_plane_state *
1073 drm_plane_state_alloc(struct drm_output_state *state_output,
1074                       struct drm_plane *plane)
1075 {
1076         struct drm_plane_state *state = zalloc(sizeof(*state));
1077
1078         assert(state);
1079         state->output_state = state_output;
1080         state->plane = plane;
1081
1082         /* Here we only add the plane state to the desired link, and not
1083          * set the member. Having an output pointer set means that the
1084          * plane will be displayed on the output; this won't be the case
1085          * when we go to disable a plane. In this case, it must be part of
1086          * the commit (and thus the output state), but the member must be
1087          * NULL, as it will not be on any output when the state takes
1088          * effect.
1089          */
1090         if (state_output)
1091                 wl_list_insert(&state_output->plane_list, &state->link);
1092         else
1093                 wl_list_init(&state->link);
1094
1095         return state;
1096 }
1097
1098 /**
1099  * Free an existing plane state. As a special case, the state will not
1100  * normally be freed if it is the current state; see drm_plane_set_state.
1101  */
1102 static void
1103 drm_plane_state_free(struct drm_plane_state *state, bool force)
1104 {
1105         if (!state)
1106                 return;
1107
1108         wl_list_remove(&state->link);
1109         wl_list_init(&state->link);
1110         state->output_state = NULL;
1111
1112         if (force || state != state->plane->state_cur) {
1113                 drm_fb_unref(state->fb);
1114                 free(state);
1115         }
1116 }
1117
1118 /**
1119  * Duplicate an existing plane state into a new plane state, storing it within
1120  * the given output state. If the output state already contains a plane state
1121  * for the drm_plane referenced by 'src', that plane state is freed first.
1122  */
1123 static struct drm_plane_state *
1124 drm_plane_state_duplicate(struct drm_output_state *state_output,
1125                           struct drm_plane_state *src)
1126 {
1127         struct drm_plane_state *dst = malloc(sizeof(*dst));
1128         struct drm_plane_state *old, *tmp;
1129
1130         assert(src);
1131         assert(dst);
1132         *dst = *src;
1133         wl_list_init(&dst->link);
1134
1135         wl_list_for_each_safe(old, tmp, &state_output->plane_list, link) {
1136                 /* Duplicating a plane state into the same output state, so
1137                  * it can replace itself with an identical copy of itself,
1138                  * makes no sense. */
1139                 assert(old != src);
1140                 if (old->plane == dst->plane)
1141                         drm_plane_state_free(old, false);
1142         }
1143
1144         wl_list_insert(&state_output->plane_list, &dst->link);
1145         if (src->fb)
1146                 dst->fb = drm_fb_ref(src->fb);
1147         dst->output_state = state_output;
1148         dst->complete = false;
1149
1150         return dst;
1151 }
1152
1153 /**
1154  * Remove a plane state from an output state; if the plane was previously
1155  * enabled, then replace it with a disabling state. This ensures that the
1156  * output state was untouched from it was before the plane state was
1157  * modified by the caller of this function.
1158  *
1159  * This is required as drm_output_state_get_plane may either allocate a
1160  * new plane state, in which case this function will just perform a matching
1161  * drm_plane_state_free, or it may instead repurpose an existing disabling
1162  * state (if the plane was previously active), in which case this function
1163  * will reset it.
1164  */
1165 static void
1166 drm_plane_state_put_back(struct drm_plane_state *state)
1167 {
1168         struct drm_output_state *state_output;
1169         struct drm_plane *plane;
1170
1171         if (!state)
1172                 return;
1173
1174         state_output = state->output_state;
1175         plane = state->plane;
1176         drm_plane_state_free(state, false);
1177
1178         /* Plane was previously disabled; no need to keep this temporary
1179          * state around. */
1180         if (!plane->state_cur->fb)
1181                 return;
1182
1183         (void) drm_plane_state_alloc(state_output, plane);
1184 }
1185
1186 /**
1187  * Return a plane state from a drm_output_state.
1188  */
1189 static struct drm_plane_state *
1190 drm_output_state_get_existing_plane(struct drm_output_state *state_output,
1191                                     struct drm_plane *plane)
1192 {
1193         struct drm_plane_state *ps;
1194
1195         wl_list_for_each(ps, &state_output->plane_list, link) {
1196                 if (ps->plane == plane)
1197                         return ps;
1198         }
1199
1200         return NULL;
1201 }
1202
1203 /**
1204  * Return a plane state from a drm_output_state, either existing or
1205  * freshly allocated.
1206  */
1207 static struct drm_plane_state *
1208 drm_output_state_get_plane(struct drm_output_state *state_output,
1209                            struct drm_plane *plane)
1210 {
1211         struct drm_plane_state *ps;
1212
1213         ps = drm_output_state_get_existing_plane(state_output, plane);
1214         if (ps)
1215                 return ps;
1216
1217         return drm_plane_state_alloc(state_output, plane);
1218 }
1219
1220 /**
1221  * Allocate a new, empty drm_output_state. This should not generally be used
1222  * in the repaint cycle; see drm_output_state_duplicate.
1223  */
1224 static struct drm_output_state *
1225 drm_output_state_alloc(struct drm_output *output,
1226                        struct drm_pending_state *pending_state)
1227 {
1228         struct drm_output_state *state = zalloc(sizeof(*state));
1229
1230         assert(state);
1231         state->output = output;
1232         state->dpms = WESTON_DPMS_OFF;
1233         state->pending_state = pending_state;
1234         if (pending_state)
1235                 wl_list_insert(&pending_state->output_list, &state->link);
1236         else
1237                 wl_list_init(&state->link);
1238
1239         wl_list_init(&state->plane_list);
1240
1241         return state;
1242 }
1243
1244 /**
1245  * Duplicate an existing drm_output_state into a new one. This is generally
1246  * used during the repaint cycle, to capture the existing state of an output
1247  * and modify it to create a new state to be used.
1248  *
1249  * The mode determines whether the output will be reset to an a blank state,
1250  * or an exact mirror of the current state.
1251  */
1252 static struct drm_output_state *
1253 drm_output_state_duplicate(struct drm_output_state *src,
1254                            struct drm_pending_state *pending_state,
1255                            enum drm_output_state_duplicate_mode plane_mode)
1256 {
1257         struct drm_output_state *dst = malloc(sizeof(*dst));
1258         struct drm_plane_state *ps;
1259
1260         assert(dst);
1261
1262         /* Copy the whole structure, then individually modify the
1263          * pending_state, as well as the list link into our pending
1264          * state. */
1265         *dst = *src;
1266
1267         dst->pending_state = pending_state;
1268         if (pending_state)
1269                 wl_list_insert(&pending_state->output_list, &dst->link);
1270         else
1271                 wl_list_init(&dst->link);
1272
1273         wl_list_init(&dst->plane_list);
1274
1275         wl_list_for_each(ps, &src->plane_list, link) {
1276                 /* Don't carry planes which are now disabled; these should be
1277                  * free for other outputs to reuse. */
1278                 if (!ps->output)
1279                         continue;
1280
1281                 if (plane_mode == DRM_OUTPUT_STATE_CLEAR_PLANES)
1282                         (void) drm_plane_state_alloc(dst, ps->plane);
1283                 else
1284                         (void) drm_plane_state_duplicate(dst, ps);
1285         }
1286
1287         return dst;
1288 }
1289
1290 /**
1291  * Free an unused drm_output_state.
1292  */
1293 static void
1294 drm_output_state_free(struct drm_output_state *state)
1295 {
1296         struct drm_plane_state *ps, *next;
1297
1298         if (!state)
1299                 return;
1300
1301         wl_list_for_each_safe(ps, next, &state->plane_list, link)
1302                 drm_plane_state_free(ps, false);
1303
1304         wl_list_remove(&state->link);
1305
1306         free(state);
1307 }
1308
1309 /**
1310  * Get output state to disable output
1311  *
1312  * Returns a pointer to an output_state object which can be used to disable
1313  * an output (e.g. DPMS off).
1314  *
1315  * @param pending_state The pending state object owning this update
1316  * @param output The output to disable
1317  * @returns A drm_output_state to disable the output
1318  */
1319 static struct drm_output_state *
1320 drm_output_get_disable_state(struct drm_pending_state *pending_state,
1321                              struct drm_output *output)
1322 {
1323         struct drm_output_state *output_state;
1324
1325         output_state = drm_output_state_duplicate(output->state_cur,
1326                                                   pending_state,
1327                                                   DRM_OUTPUT_STATE_CLEAR_PLANES);
1328         output_state->dpms = WESTON_DPMS_OFF;
1329
1330         return output_state;
1331 }
1332
1333 /**
1334  * Allocate a new drm_pending_state
1335  *
1336  * Allocate a new, empty, 'pending state' structure to be used across a
1337  * repaint cycle or similar.
1338  *
1339  * @param backend DRM backend
1340  * @returns Newly-allocated pending state structure
1341  */
1342 static struct drm_pending_state *
1343 drm_pending_state_alloc(struct drm_backend *backend)
1344 {
1345         struct drm_pending_state *ret;
1346
1347         ret = calloc(1, sizeof(*ret));
1348         if (!ret)
1349                 return NULL;
1350
1351         ret->backend = backend;
1352         wl_list_init(&ret->output_list);
1353
1354         return ret;
1355 }
1356
1357 /**
1358  * Free a drm_pending_state structure
1359  *
1360  * Frees a pending_state structure, as well as any output_states connected
1361  * to this pending state.
1362  *
1363  * @param pending_state Pending state structure to free
1364  */
1365 static void
1366 drm_pending_state_free(struct drm_pending_state *pending_state)
1367 {
1368         struct drm_output_state *output_state, *tmp;
1369
1370         if (!pending_state)
1371                 return;
1372
1373         wl_list_for_each_safe(output_state, tmp, &pending_state->output_list,
1374                               link) {
1375                 drm_output_state_free(output_state);
1376         }
1377
1378         free(pending_state);
1379 }
1380
1381 /**
1382  * Find an output state in a pending state
1383  *
1384  * Given a pending_state structure, find the output_state for a particular
1385  * output.
1386  *
1387  * @param pending_state Pending state structure to search
1388  * @param output Output to find state for
1389  * @returns Output state if present, or NULL if not
1390  */
1391 static struct drm_output_state *
1392 drm_pending_state_get_output(struct drm_pending_state *pending_state,
1393                              struct drm_output *output)
1394 {
1395         struct drm_output_state *output_state;
1396
1397         wl_list_for_each(output_state, &pending_state->output_list, link) {
1398                 if (output_state->output == output)
1399                         return output_state;
1400         }
1401
1402         return NULL;
1403 }
1404
1405 static int drm_pending_state_apply_sync(struct drm_pending_state *state);
1406
1407 /**
1408  * Mark a drm_output_state (the output's last state) as complete. This handles
1409  * any post-completion actions such as updating the repaint timer, disabling the
1410  * output, and finally freeing the state.
1411  */
1412 static void
1413 drm_output_update_complete(struct drm_output *output, uint32_t flags,
1414                            unsigned int sec, unsigned int usec)
1415 {
1416         struct drm_backend *b = to_drm_backend(output->base.compositor);
1417         struct drm_plane_state *ps;
1418         struct timespec ts;
1419
1420         /* Stop the pageflip timer instead of rearming it here */
1421         if (output->pageflip_timer)
1422                 wl_event_source_timer_update(output->pageflip_timer, 0);
1423
1424         wl_list_for_each(ps, &output->state_cur->plane_list, link)
1425                 ps->complete = true;
1426
1427         drm_output_state_free(output->state_last);
1428         output->state_last = NULL;
1429
1430         if (output->destroy_pending) {
1431                 output->destroy_pending = 0;
1432                 output->disable_pending = 0;
1433                 output->dpms_off_pending = 0;
1434                 drm_output_destroy(&output->base);
1435                 return;
1436         } else if (output->disable_pending) {
1437                 output->disable_pending = 0;
1438                 output->dpms_off_pending = 0;
1439                 weston_output_disable(&output->base);
1440                 return;
1441         } else if (output->dpms_off_pending) {
1442                 struct drm_pending_state *pending = drm_pending_state_alloc(b);
1443                 output->dpms_off_pending = 0;
1444                 drm_output_get_disable_state(pending, output);
1445                 drm_pending_state_apply_sync(pending);
1446                 return;
1447         } else if (output->state_cur->dpms == WESTON_DPMS_OFF &&
1448                    output->base.repaint_status != REPAINT_AWAITING_COMPLETION) {
1449                 /* DPMS can happen to us either in the middle of a repaint
1450                  * cycle (when we have painted fresh content, only to throw it
1451                  * away for DPMS off), or at any other random point. If the
1452                  * latter is true, then we cannot go through finish_frame,
1453                  * because the repaint machinery does not expect this. */
1454                 return;
1455         }
1456
1457         ts.tv_sec = sec;
1458         ts.tv_nsec = usec * 1000;
1459         weston_output_finish_frame(&output->base, &ts, flags);
1460
1461         /* We can't call this from frame_notify, because the output's
1462          * repaint needed flag is cleared just after that */
1463         if (output->recorder)
1464                 weston_output_schedule_repaint(&output->base);
1465 }
1466
1467 /**
1468  * Mark an output state as current on the output, i.e. it has been
1469  * submitted to the kernel. The mode argument determines whether this
1470  * update will be applied synchronously (e.g. when calling drmModeSetCrtc),
1471  * or asynchronously (in which case we wait for events to complete).
1472  */
1473 static void
1474 drm_output_assign_state(struct drm_output_state *state,
1475                         enum drm_state_apply_mode mode)
1476 {
1477         struct drm_output *output = state->output;
1478         struct drm_backend *b = to_drm_backend(output->base.compositor);
1479         struct drm_plane_state *plane_state;
1480
1481         assert(!output->state_last);
1482
1483         if (mode == DRM_STATE_APPLY_ASYNC)
1484                 output->state_last = output->state_cur;
1485         else
1486                 drm_output_state_free(output->state_cur);
1487
1488         wl_list_remove(&state->link);
1489         wl_list_init(&state->link);
1490         state->pending_state = NULL;
1491
1492         output->state_cur = state;
1493
1494         if (b->atomic_modeset && mode == DRM_STATE_APPLY_ASYNC)
1495                 output->atomic_complete_pending = 1;
1496
1497         /* Replace state_cur on each affected plane with the new state, being
1498          * careful to dispose of orphaned (but only orphaned) previous state.
1499          * If the previous state is not orphaned (still has an output_state
1500          * attached), it will be disposed of by freeing the output_state. */
1501         wl_list_for_each(plane_state, &state->plane_list, link) {
1502                 struct drm_plane *plane = plane_state->plane;
1503
1504                 if (plane->state_cur && !plane->state_cur->output_state)
1505                         drm_plane_state_free(plane->state_cur, true);
1506                 plane->state_cur = plane_state;
1507
1508                 if (mode != DRM_STATE_APPLY_ASYNC) {
1509                         plane_state->complete = true;
1510                         continue;
1511                 }
1512
1513                 if (b->atomic_modeset)
1514                         continue;
1515
1516                 if (plane->type == WDRM_PLANE_TYPE_OVERLAY)
1517                         output->vblank_pending++;
1518                 else if (plane->type == WDRM_PLANE_TYPE_PRIMARY)
1519                         output->page_flip_pending = 1;
1520         }
1521 }
1522
1523 static int
1524 drm_view_transform_supported(struct weston_view *ev)
1525 {
1526         return !ev->transform.enabled ||
1527                 (ev->transform.matrix.type < WESTON_MATRIX_TRANSFORM_ROTATE);
1528 }
1529
1530 static uint32_t
1531 drm_output_check_scanout_format(struct drm_output *output,
1532                                 struct weston_surface *es, struct gbm_bo *bo)
1533 {
1534         uint32_t format;
1535         pixman_region32_t r;
1536
1537         format = gbm_bo_get_format(bo);
1538
1539         if (format == GBM_FORMAT_ARGB8888) {
1540                 /* We can scanout an ARGB buffer if the surface's
1541                  * opaque region covers the whole output, but we have
1542                  * to use XRGB as the KMS format code. */
1543                 pixman_region32_init_rect(&r, 0, 0,
1544                                           output->base.width,
1545                                           output->base.height);
1546                 pixman_region32_subtract(&r, &r, &es->opaque);
1547
1548                 if (!pixman_region32_not_empty(&r))
1549                         format = GBM_FORMAT_XRGB8888;
1550
1551                 pixman_region32_fini(&r);
1552         }
1553
1554         if (output->gbm_format == format)
1555                 return format;
1556
1557         return 0;
1558 }
1559
1560 static struct weston_plane *
1561 drm_output_prepare_scanout_view(struct drm_output_state *output_state,
1562                                 struct weston_view *ev)
1563 {
1564         struct drm_output *output = output_state->output;
1565         struct drm_backend *b = to_drm_backend(output->base.compositor);
1566         struct drm_plane *scanout_plane = output->scanout_plane;
1567         struct drm_plane_state *state;
1568         struct weston_buffer *buffer = ev->surface->buffer_ref.buffer;
1569         struct weston_buffer_viewport *viewport = &ev->surface->buffer_viewport;
1570         struct gbm_bo *bo;
1571         uint32_t format;
1572
1573         /* Don't import buffers which span multiple outputs. */
1574         if (ev->output_mask != (1u << output->base.id))
1575                 return NULL;
1576
1577         /* We use GBM to import buffers. */
1578         if (b->gbm == NULL)
1579                 return NULL;
1580
1581         if (buffer == NULL)
1582                 return NULL;
1583         if (wl_shm_buffer_get(buffer->resource))
1584                 return NULL;
1585
1586         /* Make sure our view is exactly compatible with the output. */
1587         if (ev->geometry.x != output->base.x ||
1588             ev->geometry.y != output->base.y)
1589                 return NULL;
1590         if (buffer->width != output->base.current_mode->width ||
1591             buffer->height != output->base.current_mode->height)
1592                 return NULL;
1593
1594         if (ev->transform.enabled)
1595                 return NULL;
1596         if (ev->geometry.scissor_enabled)
1597                 return NULL;
1598         if (viewport->buffer.transform != output->base.transform)
1599                 return NULL;
1600         if (viewport->buffer.scale != output->base.current_scale)
1601                 return NULL;
1602         if (!drm_view_transform_supported(ev))
1603                 return NULL;
1604
1605         if (ev->alpha != 1.0f)
1606                 return NULL;
1607
1608         state = drm_output_state_get_plane(output_state, scanout_plane);
1609         if (state->fb) {
1610                 /* If there is already a framebuffer on the scanout plane,
1611                  * a client view has already been placed on the scanout
1612                  * view. In that case, do not free or put back the state,
1613                  * but just leave it in place and quietly exit. */
1614                 return NULL;
1615         }
1616
1617         bo = gbm_bo_import(b->gbm, GBM_BO_IMPORT_WL_BUFFER,
1618                            buffer->resource, GBM_BO_USE_SCANOUT);
1619
1620         /* Unable to use the buffer for scanout */
1621         if (!bo)
1622                 return NULL;
1623
1624         format = drm_output_check_scanout_format(output, ev->surface, bo);
1625         if (format == 0) {
1626                 drm_plane_state_put_back(state);
1627                 gbm_bo_destroy(bo);
1628                 return NULL;
1629         }
1630
1631         state->fb = drm_fb_get_from_bo(bo, b, format, BUFFER_CLIENT);
1632         if (!state->fb) {
1633                 drm_plane_state_put_back(state);
1634                 gbm_bo_destroy(bo);
1635                 return NULL;
1636         }
1637
1638         drm_fb_set_buffer(state->fb, buffer);
1639
1640         state->output = output;
1641
1642         state->src_x = 0;
1643         state->src_y = 0;
1644         state->src_w = state->fb->width << 16;
1645         state->src_h = state->fb->height << 16;
1646
1647         state->dest_x = 0;
1648         state->dest_y = 0;
1649         state->dest_w = output->base.current_mode->width;
1650         state->dest_h = output->base.current_mode->height;
1651
1652         return &scanout_plane->base;
1653 }
1654
1655 static struct drm_fb *
1656 drm_output_render_gl(struct drm_output_state *state, pixman_region32_t *damage)
1657 {
1658         struct drm_output *output = state->output;
1659         struct drm_backend *b = to_drm_backend(output->base.compositor);
1660         struct gbm_bo *bo;
1661         struct drm_fb *ret;
1662
1663         output->base.compositor->renderer->repaint_output(&output->base,
1664                                                           damage);
1665
1666         bo = gbm_surface_lock_front_buffer(output->gbm_surface);
1667         if (!bo) {
1668                 weston_log("failed to lock front buffer: %m\n");
1669                 return NULL;
1670         }
1671
1672         ret = drm_fb_get_from_bo(bo, b, output->gbm_format, BUFFER_GBM_SURFACE);
1673         if (!ret) {
1674                 weston_log("failed to get drm_fb for bo\n");
1675                 gbm_surface_release_buffer(output->gbm_surface, bo);
1676                 return NULL;
1677         }
1678         ret->gbm_surface = output->gbm_surface;
1679
1680         return ret;
1681 }
1682
1683 static struct drm_fb *
1684 drm_output_render_pixman(struct drm_output_state *state,
1685                          pixman_region32_t *damage)
1686 {
1687         struct drm_output *output = state->output;
1688         struct weston_compositor *ec = output->base.compositor;
1689         pixman_region32_t total_damage, previous_damage;
1690
1691         pixman_region32_init(&total_damage);
1692         pixman_region32_init(&previous_damage);
1693
1694         pixman_region32_copy(&previous_damage, damage);
1695
1696         pixman_region32_union(&total_damage, damage, &output->previous_damage);
1697         pixman_region32_copy(&output->previous_damage, &previous_damage);
1698
1699         output->current_image ^= 1;
1700
1701         pixman_renderer_output_set_buffer(&output->base,
1702                                           output->image[output->current_image]);
1703
1704         ec->renderer->repaint_output(&output->base, &total_damage);
1705
1706         pixman_region32_fini(&total_damage);
1707         pixman_region32_fini(&previous_damage);
1708
1709         return drm_fb_ref(output->dumb[output->current_image]);
1710 }
1711
1712 static void
1713 drm_output_render(struct drm_output_state *state, pixman_region32_t *damage)
1714 {
1715         struct drm_output *output = state->output;
1716         struct weston_compositor *c = output->base.compositor;
1717         struct drm_plane_state *scanout_state;
1718         struct drm_plane *scanout_plane = output->scanout_plane;
1719         struct drm_backend *b = to_drm_backend(c);
1720         struct drm_fb *fb;
1721
1722         /* If we already have a client buffer promoted to scanout, then we don't
1723          * want to render. */
1724         scanout_state = drm_output_state_get_plane(state,
1725                                                    output->scanout_plane);
1726         if (scanout_state->fb)
1727                 return;
1728
1729         if (!pixman_region32_not_empty(damage) &&
1730             scanout_plane->state_cur->fb &&
1731             (scanout_plane->state_cur->fb->type == BUFFER_GBM_SURFACE ||
1732              scanout_plane->state_cur->fb->type == BUFFER_PIXMAN_DUMB) &&
1733             scanout_plane->state_cur->fb->width ==
1734                 output->base.current_mode->width &&
1735             scanout_plane->state_cur->fb->height ==
1736                 output->base.current_mode->height) {
1737                 fb = drm_fb_ref(scanout_plane->state_cur->fb);
1738         } else if (b->use_pixman) {
1739                 fb = drm_output_render_pixman(state, damage);
1740         } else {
1741                 fb = drm_output_render_gl(state, damage);
1742         }
1743
1744         if (!fb) {
1745                 drm_plane_state_put_back(scanout_state);
1746                 return;
1747         }
1748
1749         scanout_state->fb = fb;
1750         scanout_state->output = output;
1751
1752         scanout_state->src_x = 0;
1753         scanout_state->src_y = 0;
1754         scanout_state->src_w = output->base.current_mode->width << 16;
1755         scanout_state->src_h = output->base.current_mode->height << 16;
1756
1757         scanout_state->dest_x = 0;
1758         scanout_state->dest_y = 0;
1759         scanout_state->dest_w = scanout_state->src_w >> 16;
1760         scanout_state->dest_h = scanout_state->src_h >> 16;
1761
1762
1763         pixman_region32_subtract(&c->primary_plane.damage,
1764                                  &c->primary_plane.damage, damage);
1765 }
1766
1767 static void
1768 drm_output_set_gamma(struct weston_output *output_base,
1769                      uint16_t size, uint16_t *r, uint16_t *g, uint16_t *b)
1770 {
1771         int rc;
1772         struct drm_output *output = to_drm_output(output_base);
1773         struct drm_backend *backend =
1774                 to_drm_backend(output->base.compositor);
1775
1776         /* check */
1777         if (output_base->gamma_size != size)
1778                 return;
1779
1780         rc = drmModeCrtcSetGamma(backend->drm.fd,
1781                                  output->crtc_id,
1782                                  size, r, g, b);
1783         if (rc)
1784                 weston_log("set gamma failed: %m\n");
1785 }
1786
1787 /* Determine the type of vblank synchronization to use for the output.
1788  *
1789  * The pipe parameter indicates which CRTC is in use.  Knowing this, we
1790  * can determine which vblank sequence type to use for it.  Traditional
1791  * cards had only two CRTCs, with CRTC 0 using no special flags, and
1792  * CRTC 1 using DRM_VBLANK_SECONDARY.  The first bit of the pipe
1793  * parameter indicates this.
1794  *
1795  * Bits 1-5 of the pipe parameter are 5 bit wide pipe number between
1796  * 0-31.  If this is non-zero it indicates we're dealing with a
1797  * multi-gpu situation and we need to calculate the vblank sync
1798  * using DRM_BLANK_HIGH_CRTC_MASK.
1799  */
1800 static unsigned int
1801 drm_waitvblank_pipe(struct drm_output *output)
1802 {
1803         if (output->pipe > 1)
1804                 return (output->pipe << DRM_VBLANK_HIGH_CRTC_SHIFT) &
1805                                 DRM_VBLANK_HIGH_CRTC_MASK;
1806         else if (output->pipe > 0)
1807                 return DRM_VBLANK_SECONDARY;
1808         else
1809                 return 0;
1810 }
1811
1812 static int
1813 drm_output_apply_state_legacy(struct drm_output_state *state)
1814 {
1815         struct drm_output *output = state->output;
1816         struct drm_head *head = to_drm_head(weston_output_get_first_head(&output->base));
1817         struct drm_backend *backend = to_drm_backend(output->base.compositor);
1818         struct drm_plane *scanout_plane = output->scanout_plane;
1819         struct drm_property_info *dpms_prop =
1820                 &head->props_conn[WDRM_CONNECTOR_DPMS];
1821         struct drm_plane_state *scanout_state;
1822         struct drm_plane_state *ps;
1823         struct drm_plane *p;
1824         struct drm_mode *mode;
1825         struct timespec now;
1826         int ret = 0;
1827
1828         /* If disable_planes is set then assign_planes() wasn't
1829          * called for this render, so we could still have a stale
1830          * cursor plane set up.
1831          */
1832         if (output->base.disable_planes) {
1833                 output->cursor_view = NULL;
1834                 if (output->cursor_plane) {
1835                         output->cursor_plane->base.x = INT32_MIN;
1836                         output->cursor_plane->base.y = INT32_MIN;
1837                 }
1838         }
1839
1840         if (state->dpms != WESTON_DPMS_ON) {
1841                 wl_list_for_each(ps, &state->plane_list, link) {
1842                         p = ps->plane;
1843                         assert(ps->fb == NULL);
1844                         assert(ps->output == NULL);
1845
1846                         if (p->type != WDRM_PLANE_TYPE_OVERLAY)
1847                                 continue;
1848
1849                         ret = drmModeSetPlane(backend->drm.fd, p->plane_id,
1850                                               0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1851                         if (ret)
1852                                 weston_log("drmModeSetPlane failed disable: %m\n");
1853                 }
1854
1855                 if (output->cursor_plane) {
1856                         ret = drmModeSetCursor(backend->drm.fd, output->crtc_id,
1857                                                0, 0, 0);
1858                         if (ret)
1859                                 weston_log("drmModeSetCursor failed disable: %m\n");
1860                 }
1861
1862                 ret = drmModeSetCrtc(backend->drm.fd, output->crtc_id, 0, 0, 0,
1863                                      &head->connector_id, 0, NULL);
1864                 if (ret)
1865                         weston_log("drmModeSetCrtc failed disabling: %m\n");
1866
1867                 drm_output_assign_state(state, DRM_STATE_APPLY_SYNC);
1868                 weston_compositor_read_presentation_clock(output->base.compositor, &now);
1869                 drm_output_update_complete(output,
1870                                            WP_PRESENTATION_FEEDBACK_KIND_HW_COMPLETION,
1871                                            now.tv_sec, now.tv_nsec / 1000);
1872
1873                 return 0;
1874         }
1875
1876         scanout_state =
1877                 drm_output_state_get_existing_plane(state, scanout_plane);
1878
1879         /* The legacy SetCrtc API doesn't allow us to do scaling, and the
1880          * legacy PageFlip API doesn't allow us to do clipping either. */
1881         assert(scanout_state->src_x == 0);
1882         assert(scanout_state->src_y == 0);
1883         assert(scanout_state->src_w ==
1884                 (unsigned) (output->base.current_mode->width << 16));
1885         assert(scanout_state->src_h ==
1886                 (unsigned) (output->base.current_mode->height << 16));
1887         assert(scanout_state->dest_x == 0);
1888         assert(scanout_state->dest_y == 0);
1889         assert(scanout_state->dest_w == scanout_state->src_w >> 16);
1890         assert(scanout_state->dest_h == scanout_state->src_h >> 16);
1891
1892         mode = to_drm_mode(output->base.current_mode);
1893         if (backend->state_invalid || !scanout_plane->state_cur->fb ||
1894             scanout_plane->state_cur->fb->stride != scanout_state->fb->stride) {
1895                 ret = drmModeSetCrtc(backend->drm.fd, output->crtc_id,
1896                                      scanout_state->fb->fb_id,
1897                                      0, 0,
1898                                      &head->connector_id, 1,
1899                                      &mode->mode_info);
1900                 if (ret) {
1901                         weston_log("set mode failed: %m\n");
1902                         goto err;
1903                 }
1904         }
1905
1906         if (drmModePageFlip(backend->drm.fd, output->crtc_id,
1907                             scanout_state->fb->fb_id,
1908                             DRM_MODE_PAGE_FLIP_EVENT, output) < 0) {
1909                 weston_log("queueing pageflip failed: %m\n");
1910                 goto err;
1911         }
1912
1913         assert(!output->page_flip_pending);
1914
1915         if (output->pageflip_timer)
1916                 wl_event_source_timer_update(output->pageflip_timer,
1917                                              backend->pageflip_timeout);
1918
1919         drm_output_set_cursor(state);
1920
1921         /*
1922          * Now, update all the sprite surfaces
1923          */
1924         wl_list_for_each(ps, &state->plane_list, link) {
1925                 uint32_t flags = 0, fb_id = 0;
1926                 drmVBlank vbl = {
1927                         .request.type = DRM_VBLANK_RELATIVE | DRM_VBLANK_EVENT,
1928                         .request.sequence = 1,
1929                 };
1930
1931                 p = ps->plane;
1932                 if (p->type != WDRM_PLANE_TYPE_OVERLAY)
1933                         continue;
1934
1935                 assert(p->state_cur->complete);
1936                 assert(!!p->state_cur->output == !!p->state_cur->fb);
1937                 assert(!p->state_cur->output || p->state_cur->output == output);
1938                 assert(!ps->complete);
1939                 assert(!ps->output || ps->output == output);
1940                 assert(!!ps->output == !!ps->fb);
1941
1942                 if (ps->fb && !backend->sprites_hidden)
1943                         fb_id = ps->fb->fb_id;
1944
1945                 ret = drmModeSetPlane(backend->drm.fd, p->plane_id,
1946                                       output->crtc_id, fb_id, flags,
1947                                       ps->dest_x, ps->dest_y,
1948                                       ps->dest_w, ps->dest_h,
1949                                       ps->src_x, ps->src_y,
1950                                       ps->src_w, ps->src_h);
1951                 if (ret)
1952                         weston_log("setplane failed: %d: %s\n",
1953                                 ret, strerror(errno));
1954
1955                 vbl.request.type |= drm_waitvblank_pipe(output);
1956
1957                 /*
1958                  * Queue a vblank signal so we know when the surface
1959                  * becomes active on the display or has been replaced.
1960                  */
1961                 vbl.request.signal = (unsigned long) ps;
1962                 ret = drmWaitVBlank(backend->drm.fd, &vbl);
1963                 if (ret) {
1964                         weston_log("vblank event request failed: %d: %s\n",
1965                                 ret, strerror(errno));
1966                 }
1967         }
1968
1969         if (dpms_prop->prop_id && state->dpms != output->state_cur->dpms) {
1970                 ret = drmModeConnectorSetProperty(backend->drm.fd,
1971                                                   head->connector_id,
1972                                                   dpms_prop->prop_id,
1973                                                   state->dpms);
1974                 if (ret) {
1975                         weston_log("DRM: DPMS: failed property set for %s\n",
1976                                    output->base.name);
1977                 }
1978         }
1979
1980         drm_output_assign_state(state, DRM_STATE_APPLY_ASYNC);
1981
1982         return 0;
1983
1984 err:
1985         output->cursor_view = NULL;
1986         drm_output_state_free(state);
1987         return -1;
1988 }
1989
1990 #ifdef HAVE_DRM_ATOMIC
1991 static int
1992 crtc_add_prop(drmModeAtomicReq *req, struct drm_output *output,
1993               enum wdrm_crtc_property prop, uint64_t val)
1994 {
1995         struct drm_property_info *info = &output->props_crtc[prop];
1996         int ret;
1997
1998         if (info->prop_id == 0)
1999                 return -1;
2000
2001         ret = drmModeAtomicAddProperty(req, output->crtc_id, info->prop_id,
2002                                        val);
2003         return (ret <= 0) ? -1 : 0;
2004 }
2005
2006 static int
2007 connector_add_prop(drmModeAtomicReq *req, struct drm_head *head,
2008                    enum wdrm_connector_property prop, uint64_t val)
2009 {
2010         struct drm_property_info *info = &head->props_conn[prop];
2011         int ret;
2012
2013         if (info->prop_id == 0)
2014                 return -1;
2015
2016         ret = drmModeAtomicAddProperty(req, head->connector_id,
2017                                        info->prop_id, val);
2018         return (ret <= 0) ? -1 : 0;
2019 }
2020
2021 static int
2022 plane_add_prop(drmModeAtomicReq *req, struct drm_plane *plane,
2023                enum wdrm_plane_property prop, uint64_t val)
2024 {
2025         struct drm_property_info *info = &plane->props[prop];
2026         int ret;
2027
2028         if (info->prop_id == 0)
2029                 return -1;
2030
2031         ret = drmModeAtomicAddProperty(req, plane->plane_id, info->prop_id,
2032                                        val);
2033         return (ret <= 0) ? -1 : 0;
2034 }
2035
2036 static int
2037 drm_mode_ensure_blob(struct drm_backend *backend, struct drm_mode *mode)
2038 {
2039         int ret;
2040
2041         if (mode->blob_id)
2042                 return 0;
2043
2044         ret = drmModeCreatePropertyBlob(backend->drm.fd,
2045                                         &mode->mode_info,
2046                                         sizeof(mode->mode_info),
2047                                         &mode->blob_id);
2048         if (ret != 0)
2049                 weston_log("failed to create mode property blob: %m\n");
2050
2051         return ret;
2052 }
2053
2054 static int
2055 drm_output_apply_state_atomic(struct drm_output_state *state,
2056                               drmModeAtomicReq *req,
2057                               uint32_t *flags)
2058 {
2059         struct drm_output *output = state->output;
2060         struct drm_head *head = to_drm_head(weston_output_get_first_head(&output->base));
2061         struct drm_backend *backend = to_drm_backend(output->base.compositor);
2062         struct drm_plane_state *plane_state;
2063         struct drm_mode *current_mode = to_drm_mode(output->base.current_mode);
2064         int ret = 0;
2065
2066         if (state->dpms != output->state_cur->dpms)
2067                 *flags |= DRM_MODE_ATOMIC_ALLOW_MODESET;
2068
2069         if (state->dpms == WESTON_DPMS_ON) {
2070                 ret = drm_mode_ensure_blob(backend, current_mode);
2071                 if (ret != 0)
2072                         return ret;
2073
2074                 ret |= crtc_add_prop(req, output, WDRM_CRTC_MODE_ID,
2075                                      current_mode->blob_id);
2076                 ret |= crtc_add_prop(req, output, WDRM_CRTC_ACTIVE, 1);
2077                 ret |= connector_add_prop(req, head, WDRM_CONNECTOR_CRTC_ID,
2078                                           output->crtc_id);
2079         } else {
2080                 ret |= crtc_add_prop(req, output, WDRM_CRTC_MODE_ID, 0);
2081                 ret |= crtc_add_prop(req, output, WDRM_CRTC_ACTIVE, 0);
2082                 ret |= connector_add_prop(req, head, WDRM_CONNECTOR_CRTC_ID, 0);
2083         }
2084
2085         if (ret != 0) {
2086                 weston_log("couldn't set atomic CRTC/connector state\n");
2087                 return ret;
2088         }
2089
2090         wl_list_for_each(plane_state, &state->plane_list, link) {
2091                 struct drm_plane *plane = plane_state->plane;
2092
2093                 ret |= plane_add_prop(req, plane, WDRM_PLANE_FB_ID,
2094                                       plane_state->fb ? plane_state->fb->fb_id : 0);
2095                 ret |= plane_add_prop(req, plane, WDRM_PLANE_CRTC_ID,
2096                                       plane_state->fb ? output->crtc_id : 0);
2097                 ret |= plane_add_prop(req, plane, WDRM_PLANE_SRC_X,
2098                                       plane_state->src_x);
2099                 ret |= plane_add_prop(req, plane, WDRM_PLANE_SRC_Y,
2100                                       plane_state->src_y);
2101                 ret |= plane_add_prop(req, plane, WDRM_PLANE_SRC_W,
2102                                       plane_state->src_w);
2103                 ret |= plane_add_prop(req, plane, WDRM_PLANE_SRC_H,
2104                                       plane_state->src_h);
2105                 ret |= plane_add_prop(req, plane, WDRM_PLANE_CRTC_X,
2106                                       plane_state->dest_x);
2107                 ret |= plane_add_prop(req, plane, WDRM_PLANE_CRTC_Y,
2108                                       plane_state->dest_y);
2109                 ret |= plane_add_prop(req, plane, WDRM_PLANE_CRTC_W,
2110                                       plane_state->dest_w);
2111                 ret |= plane_add_prop(req, plane, WDRM_PLANE_CRTC_H,
2112                                       plane_state->dest_h);
2113
2114                 if (ret != 0) {
2115                         weston_log("couldn't set plane state\n");
2116                         return ret;
2117                 }
2118         }
2119
2120         return 0;
2121 }
2122
2123 /**
2124  * Helper function used only by drm_pending_state_apply, with the same
2125  * guarantees and constraints as that function.
2126  */
2127 static int
2128 drm_pending_state_apply_atomic(struct drm_pending_state *pending_state,
2129                                enum drm_state_apply_mode mode)
2130 {
2131         struct drm_backend *b = pending_state->backend;
2132         struct drm_output_state *output_state, *tmp;
2133         struct drm_plane *plane;
2134         drmModeAtomicReq *req = drmModeAtomicAlloc();
2135         uint32_t flags = 0;
2136         int ret = 0;
2137
2138         if (!req)
2139                 return -1;
2140
2141         if (b->state_invalid) {
2142                 uint32_t *unused;
2143                 int err;
2144
2145                 /* If we need to reset all our state (e.g. because we've
2146                  * just started, or just been VT-switched in), explicitly
2147                  * disable all the CRTCs and connectors we aren't using. */
2148                 wl_array_for_each(unused, &b->unused_connectors) {
2149                         struct drm_property_info infos[WDRM_CONNECTOR__COUNT];
2150                         struct drm_property_info *info;
2151                         drmModeObjectProperties *props;
2152
2153                         memset(infos, 0, sizeof(infos));
2154
2155                         props = drmModeObjectGetProperties(b->drm.fd,
2156                                                            *unused,
2157                                                            DRM_MODE_OBJECT_CONNECTOR);
2158                         if (!props) {
2159                                 ret = -1;
2160                                 continue;
2161                         }
2162
2163                         drm_property_info_populate(b, connector_props, infos,
2164                                                    WDRM_CONNECTOR__COUNT,
2165                                                    props);
2166                         drmModeFreeObjectProperties(props);
2167
2168                         info = &infos[WDRM_CONNECTOR_CRTC_ID];
2169                         err = drmModeAtomicAddProperty(req, *unused,
2170                                                        info->prop_id, 0);
2171                         if (err <= 0)
2172                                 ret = -1;
2173
2174                         info = &infos[WDRM_CONNECTOR_DPMS];
2175                         if (info->prop_id > 0)
2176                                 err = drmModeAtomicAddProperty(req, *unused,
2177                                                                info->prop_id,
2178                                                                DRM_MODE_DPMS_OFF);
2179                         if (err <= 0)
2180                                 ret = -1;
2181
2182                         drm_property_info_free(infos, WDRM_CONNECTOR__COUNT);
2183                 }
2184
2185                 wl_array_for_each(unused, &b->unused_crtcs) {
2186                         struct drm_property_info infos[WDRM_CRTC__COUNT];
2187                         struct drm_property_info *info;
2188                         drmModeObjectProperties *props;
2189                         uint64_t active;
2190
2191                         memset(infos, 0, sizeof(infos));
2192
2193                         /* We can't emit a disable on a CRTC that's already
2194                          * off, as the kernel will refuse to generate an event
2195                          * for an off->off state and fail the commit.
2196                          */
2197                         props = drmModeObjectGetProperties(b->drm.fd,
2198                                                            *unused,
2199                                                            DRM_MODE_OBJECT_CRTC);
2200                         if (!props) {
2201                                 ret = -1;
2202                                 continue;
2203                         }
2204
2205                         drm_property_info_populate(b, crtc_props, infos,
2206                                                    WDRM_CRTC__COUNT,
2207                                                    props);
2208
2209                         info = &infos[WDRM_CRTC_ACTIVE];
2210                         active = drm_property_get_value(info, props, 0);
2211                         drmModeFreeObjectProperties(props);
2212                         if (active == 0) {
2213                                 drm_property_info_free(infos, WDRM_CRTC__COUNT);
2214                                 continue;
2215                         }
2216
2217                         err = drmModeAtomicAddProperty(req, *unused,
2218                                                        info->prop_id, 0);
2219                         if (err <= 0)
2220                                 ret = -1;
2221
2222                         info = &infos[WDRM_CRTC_MODE_ID];
2223                         err = drmModeAtomicAddProperty(req, *unused,
2224                                                        info->prop_id, 0);
2225                         if (err <= 0)
2226                                 ret = -1;
2227
2228                         drm_property_info_free(infos, WDRM_CRTC__COUNT);
2229                 }
2230
2231                 /* Disable all the planes; planes which are being used will
2232                  * override this state in the output-state application. */
2233                 wl_list_for_each(plane, &b->plane_list, link) {
2234                         plane_add_prop(req, plane, WDRM_PLANE_CRTC_ID, 0);
2235                         plane_add_prop(req, plane, WDRM_PLANE_FB_ID, 0);
2236                 }
2237
2238                 flags |= DRM_MODE_ATOMIC_ALLOW_MODESET;
2239         }
2240
2241         wl_list_for_each(output_state, &pending_state->output_list, link) {
2242                 if (mode == DRM_STATE_APPLY_SYNC)
2243                         assert(output_state->dpms == WESTON_DPMS_OFF);
2244                 ret |= drm_output_apply_state_atomic(output_state, req, &flags);
2245         }
2246
2247         if (ret != 0) {
2248                 weston_log("atomic: couldn't compile atomic state\n");
2249                 goto out;
2250         }
2251
2252         switch (mode) {
2253         case DRM_STATE_APPLY_SYNC:
2254                 break;
2255         case DRM_STATE_APPLY_ASYNC:
2256                 flags |= DRM_MODE_PAGE_FLIP_EVENT | DRM_MODE_ATOMIC_NONBLOCK;
2257                 break;
2258         }
2259
2260         ret = drmModeAtomicCommit(b->drm.fd, req, flags, b);
2261         if (ret != 0) {
2262                 weston_log("atomic: couldn't commit new state: %m\n");
2263                 goto out;
2264         }
2265
2266         wl_list_for_each_safe(output_state, tmp, &pending_state->output_list,
2267                               link)
2268                 drm_output_assign_state(output_state, mode);
2269
2270         b->state_invalid = false;
2271
2272         assert(wl_list_empty(&pending_state->output_list));
2273
2274 out:
2275         drmModeAtomicFree(req);
2276         drm_pending_state_free(pending_state);
2277         return ret;
2278 }
2279 #endif
2280
2281 /**
2282  * Applies all of a pending_state asynchronously: the primary entry point for
2283  * applying KMS state to a device. Updates the state for all outputs in the
2284  * pending_state, as well as disabling any unclaimed outputs.
2285  *
2286  * Unconditionally takes ownership of pending_state, and clears state_invalid.
2287  */
2288 static int
2289 drm_pending_state_apply(struct drm_pending_state *pending_state)
2290 {
2291         struct drm_backend *b = pending_state->backend;
2292         struct drm_output_state *output_state, *tmp;
2293         uint32_t *unused;
2294
2295 #ifdef HAVE_DRM_ATOMIC
2296         if (b->atomic_modeset)
2297                 return drm_pending_state_apply_atomic(pending_state,
2298                                                       DRM_STATE_APPLY_ASYNC);
2299 #endif
2300
2301         if (b->state_invalid) {
2302                 /* If we need to reset all our state (e.g. because we've
2303                  * just started, or just been VT-switched in), explicitly
2304                  * disable all the CRTCs we aren't using. This also disables
2305                  * all connectors on these CRTCs, so we don't need to do that
2306                  * separately with the pre-atomic API. */
2307                 wl_array_for_each(unused, &b->unused_crtcs)
2308                         drmModeSetCrtc(b->drm.fd, *unused, 0, 0, 0, NULL, 0,
2309                                        NULL);
2310         }
2311
2312         wl_list_for_each_safe(output_state, tmp, &pending_state->output_list,
2313                               link) {
2314                 struct drm_output *output = output_state->output;
2315                 int ret;
2316
2317                 ret = drm_output_apply_state_legacy(output_state);
2318                 if (ret != 0) {
2319                         weston_log("Couldn't apply state for output %s\n",
2320                                    output->base.name);
2321                 }
2322         }
2323
2324         b->state_invalid = false;
2325
2326         assert(wl_list_empty(&pending_state->output_list));
2327
2328         drm_pending_state_free(pending_state);
2329
2330         return 0;
2331 }
2332
2333 /**
2334  * The synchronous version of drm_pending_state_apply. May only be used to
2335  * disable outputs. Does so synchronously: the request is guaranteed to have
2336  * completed on return, and the output will not be touched afterwards.
2337  *
2338  * Unconditionally takes ownership of pending_state, and clears state_invalid.
2339  */
2340 static int
2341 drm_pending_state_apply_sync(struct drm_pending_state *pending_state)
2342 {
2343         struct drm_backend *b = pending_state->backend;
2344         struct drm_output_state *output_state, *tmp;
2345         uint32_t *unused;
2346
2347 #ifdef HAVE_DRM_ATOMIC
2348         if (b->atomic_modeset)
2349                 return drm_pending_state_apply_atomic(pending_state,
2350                                                       DRM_STATE_APPLY_SYNC);
2351 #endif
2352
2353         if (b->state_invalid) {
2354                 /* If we need to reset all our state (e.g. because we've
2355                  * just started, or just been VT-switched in), explicitly
2356                  * disable all the CRTCs we aren't using. This also disables
2357                  * all connectors on these CRTCs, so we don't need to do that
2358                  * separately with the pre-atomic API. */
2359                 wl_array_for_each(unused, &b->unused_crtcs)
2360                         drmModeSetCrtc(b->drm.fd, *unused, 0, 0, 0, NULL, 0,
2361                                        NULL);
2362         }
2363
2364         wl_list_for_each_safe(output_state, tmp, &pending_state->output_list,
2365                               link) {
2366                 int ret;
2367
2368                 assert(output_state->dpms == WESTON_DPMS_OFF);
2369                 ret = drm_output_apply_state_legacy(output_state);
2370                 if (ret != 0) {
2371                         weston_log("Couldn't apply state for output %s\n",
2372                                    output_state->output->base.name);
2373                 }
2374         }
2375
2376         b->state_invalid = false;
2377
2378         assert(wl_list_empty(&pending_state->output_list));
2379
2380         drm_pending_state_free(pending_state);
2381
2382         return 0;
2383 }
2384
2385 static int
2386 drm_output_repaint(struct weston_output *output_base,
2387                    pixman_region32_t *damage,
2388                    void *repaint_data)
2389 {
2390         struct drm_pending_state *pending_state = repaint_data;
2391         struct drm_output *output = to_drm_output(output_base);
2392         struct drm_output_state *state = NULL;
2393         struct drm_plane_state *scanout_state;
2394
2395         if (output->disable_pending || output->destroy_pending)
2396                 goto err;
2397
2398         assert(!output->state_last);
2399
2400         /* If planes have been disabled in the core, we might not have
2401          * hit assign_planes at all, so might not have valid output state
2402          * here. */
2403         state = drm_pending_state_get_output(pending_state, output);
2404         if (!state)
2405                 state = drm_output_state_duplicate(output->state_cur,
2406                                                    pending_state,
2407                                                    DRM_OUTPUT_STATE_CLEAR_PLANES);
2408         state->dpms = WESTON_DPMS_ON;
2409
2410         drm_output_render(state, damage);
2411         scanout_state = drm_output_state_get_plane(state,
2412                                                    output->scanout_plane);
2413         if (!scanout_state || !scanout_state->fb)
2414                 goto err;
2415
2416         return 0;
2417
2418 err:
2419         drm_output_state_free(state);
2420         return -1;
2421 }
2422
2423 static void
2424 drm_output_start_repaint_loop(struct weston_output *output_base)
2425 {
2426         struct drm_output *output = to_drm_output(output_base);
2427         struct drm_pending_state *pending_state;
2428         struct drm_plane *scanout_plane = output->scanout_plane;
2429         struct drm_backend *backend =
2430                 to_drm_backend(output_base->compositor);
2431         struct timespec ts, tnow;
2432         struct timespec vbl2now;
2433         int64_t refresh_nsec;
2434         int ret;
2435         drmVBlank vbl = {
2436                 .request.type = DRM_VBLANK_RELATIVE,
2437                 .request.sequence = 0,
2438                 .request.signal = 0,
2439         };
2440
2441         if (output->disable_pending || output->destroy_pending)
2442                 return;
2443
2444         if (!output->scanout_plane->state_cur->fb) {
2445                 /* We can't page flip if there's no mode set */
2446                 goto finish_frame;
2447         }
2448
2449         /* Need to smash all state in from scratch; current timings might not
2450          * be what we want, page flip might not work, etc.
2451          */
2452         if (backend->state_invalid)
2453                 goto finish_frame;
2454
2455         assert(scanout_plane->state_cur->output == output);
2456
2457         /* Try to get current msc and timestamp via instant query */
2458         vbl.request.type |= drm_waitvblank_pipe(output);
2459         ret = drmWaitVBlank(backend->drm.fd, &vbl);
2460
2461         /* Error ret or zero timestamp means failure to get valid timestamp */
2462         if ((ret == 0) && (vbl.reply.tval_sec > 0 || vbl.reply.tval_usec > 0)) {
2463                 ts.tv_sec = vbl.reply.tval_sec;
2464                 ts.tv_nsec = vbl.reply.tval_usec * 1000;
2465
2466                 /* Valid timestamp for most recent vblank - not stale?
2467                  * Stale ts could happen on Linux 3.17+, so make sure it
2468                  * is not older than 1 refresh duration since now.
2469                  */
2470                 weston_compositor_read_presentation_clock(backend->compositor,
2471                                                           &tnow);
2472                 timespec_sub(&vbl2now, &tnow, &ts);
2473                 refresh_nsec =
2474                         millihz_to_nsec(output->base.current_mode->refresh);
2475                 if (timespec_to_nsec(&vbl2now) < refresh_nsec) {
2476                         drm_output_update_msc(output, vbl.reply.sequence);
2477                         weston_output_finish_frame(output_base, &ts,
2478                                                 WP_PRESENTATION_FEEDBACK_INVALID);
2479                         return;
2480                 }
2481         }
2482
2483         /* Immediate query didn't provide valid timestamp.
2484          * Use pageflip fallback.
2485          */
2486
2487         assert(!output->page_flip_pending);
2488         assert(!output->state_last);
2489
2490         pending_state = drm_pending_state_alloc(backend);
2491         drm_output_state_duplicate(output->state_cur, pending_state,
2492                                    DRM_OUTPUT_STATE_PRESERVE_PLANES);
2493
2494         ret = drm_pending_state_apply(pending_state);
2495         if (ret != 0) {
2496                 weston_log("applying repaint-start state failed: %m\n");
2497                 goto finish_frame;
2498         }
2499
2500         return;
2501
2502 finish_frame:
2503         /* if we cannot page-flip, immediately finish frame */
2504         weston_output_finish_frame(output_base, NULL,
2505                                    WP_PRESENTATION_FEEDBACK_INVALID);
2506 }
2507
2508 static void
2509 drm_output_update_msc(struct drm_output *output, unsigned int seq)
2510 {
2511         uint64_t msc_hi = output->base.msc >> 32;
2512
2513         if (seq < (output->base.msc & 0xffffffff))
2514                 msc_hi++;
2515
2516         output->base.msc = (msc_hi << 32) + seq;
2517 }
2518
2519 static void
2520 vblank_handler(int fd, unsigned int frame, unsigned int sec, unsigned int usec,
2521                void *data)
2522 {
2523         struct drm_plane_state *ps = (struct drm_plane_state *) data;
2524         struct drm_output_state *os = ps->output_state;
2525         struct drm_output *output = os->output;
2526         struct drm_backend *b = to_drm_backend(output->base.compositor);
2527         uint32_t flags = WP_PRESENTATION_FEEDBACK_KIND_HW_COMPLETION |
2528                          WP_PRESENTATION_FEEDBACK_KIND_HW_CLOCK;
2529
2530         assert(!b->atomic_modeset);
2531
2532         drm_output_update_msc(output, frame);
2533         output->vblank_pending--;
2534         assert(output->vblank_pending >= 0);
2535
2536         assert(ps->fb);
2537
2538         if (output->page_flip_pending || output->vblank_pending)
2539                 return;
2540
2541         drm_output_update_complete(output, flags, sec, usec);
2542 }
2543
2544 static void
2545 page_flip_handler(int fd, unsigned int frame,
2546                   unsigned int sec, unsigned int usec, void *data)
2547 {
2548         struct drm_output *output = data;
2549         struct drm_backend *b = to_drm_backend(output->base.compositor);
2550         uint32_t flags = WP_PRESENTATION_FEEDBACK_KIND_VSYNC |
2551                          WP_PRESENTATION_FEEDBACK_KIND_HW_COMPLETION |
2552                          WP_PRESENTATION_FEEDBACK_KIND_HW_CLOCK;
2553
2554         drm_output_update_msc(output, frame);
2555
2556         assert(!b->atomic_modeset);
2557         assert(output->page_flip_pending);
2558         output->page_flip_pending = 0;
2559
2560         if (output->vblank_pending)
2561                 return;
2562
2563         drm_output_update_complete(output, flags, sec, usec);
2564 }
2565
2566 /**
2567  * Begin a new repaint cycle
2568  *
2569  * Called by the core compositor at the beginning of a repaint cycle. Creates
2570  * a new pending_state structure to own any output state created by individual
2571  * output repaint functions until the repaint is flushed or cancelled.
2572  */
2573 static void *
2574 drm_repaint_begin(struct weston_compositor *compositor)
2575 {
2576         struct drm_backend *b = to_drm_backend(compositor);
2577         struct drm_pending_state *ret;
2578
2579         ret = drm_pending_state_alloc(b);
2580         b->repaint_data = ret;
2581
2582         return ret;
2583 }
2584
2585 /**
2586  * Flush a repaint set
2587  *
2588  * Called by the core compositor when a repaint cycle has been completed
2589  * and should be flushed. Frees the pending state, transitioning ownership
2590  * of the output state from the pending state, to the update itself. When
2591  * the update completes (see drm_output_update_complete), the output
2592  * state will be freed.
2593  */
2594 static void
2595 drm_repaint_flush(struct weston_compositor *compositor, void *repaint_data)
2596 {
2597         struct drm_backend *b = to_drm_backend(compositor);
2598         struct drm_pending_state *pending_state = repaint_data;
2599
2600         drm_pending_state_apply(pending_state);
2601         b->repaint_data = NULL;
2602 }
2603
2604 /**
2605  * Cancel a repaint set
2606  *
2607  * Called by the core compositor when a repaint has finished, so the data
2608  * held across the repaint cycle should be discarded.
2609  */
2610 static void
2611 drm_repaint_cancel(struct weston_compositor *compositor, void *repaint_data)
2612 {
2613         struct drm_backend *b = to_drm_backend(compositor);
2614         struct drm_pending_state *pending_state = repaint_data;
2615
2616         drm_pending_state_free(pending_state);
2617         b->repaint_data = NULL;
2618 }
2619
2620 #ifdef HAVE_DRM_ATOMIC
2621 static void
2622 atomic_flip_handler(int fd, unsigned int frame, unsigned int sec,
2623                     unsigned int usec, unsigned int crtc_id, void *data)
2624 {
2625         struct drm_backend *b = data;
2626         struct drm_output *output = drm_output_find_by_crtc(b, crtc_id);
2627         uint32_t flags = WP_PRESENTATION_FEEDBACK_KIND_VSYNC |
2628                          WP_PRESENTATION_FEEDBACK_KIND_HW_COMPLETION |
2629                          WP_PRESENTATION_FEEDBACK_KIND_HW_CLOCK;
2630
2631         /* During the initial modeset, we can disable CRTCs which we don't
2632          * actually handle during normal operation; this will give us events
2633          * for unknown outputs. Ignore them. */
2634         if (!output || !output->base.enabled)
2635                 return;
2636
2637         drm_output_update_msc(output, frame);
2638
2639         assert(b->atomic_modeset);
2640         assert(output->atomic_complete_pending);
2641         output->atomic_complete_pending = 0;
2642
2643         drm_output_update_complete(output, flags, sec, usec);
2644 }
2645 #endif
2646
2647 static uint32_t
2648 drm_output_check_plane_format(struct drm_plane *p,
2649                                struct weston_view *ev, struct gbm_bo *bo)
2650 {
2651         uint32_t i, format;
2652
2653         format = gbm_bo_get_format(bo);
2654
2655         if (format == GBM_FORMAT_ARGB8888) {
2656                 pixman_region32_t r;
2657
2658                 pixman_region32_init_rect(&r, 0, 0,
2659                                           ev->surface->width,
2660                                           ev->surface->height);
2661                 pixman_region32_subtract(&r, &r, &ev->surface->opaque);
2662
2663                 if (!pixman_region32_not_empty(&r))
2664                         format = GBM_FORMAT_XRGB8888;
2665
2666                 pixman_region32_fini(&r);
2667         }
2668
2669         for (i = 0; i < p->count_formats; i++)
2670                 if (p->formats[i] == format)
2671                         return format;
2672
2673         return 0;
2674 }
2675
2676 static struct weston_plane *
2677 drm_output_prepare_overlay_view(struct drm_output_state *output_state,
2678                                 struct weston_view *ev)
2679 {
2680         struct drm_output *output = output_state->output;
2681         struct weston_compositor *ec = output->base.compositor;
2682         struct drm_backend *b = to_drm_backend(ec);
2683         struct weston_buffer_viewport *viewport = &ev->surface->buffer_viewport;
2684         struct wl_resource *buffer_resource;
2685         struct drm_plane *p;
2686         struct drm_plane_state *state = NULL;
2687         struct linux_dmabuf_buffer *dmabuf;
2688         struct gbm_bo *bo;
2689         pixman_region32_t dest_rect, src_rect;
2690         pixman_box32_t *box, tbox;
2691         uint32_t format;
2692         wl_fixed_t sx1, sy1, sx2, sy2;
2693
2694         if (b->sprites_are_broken)
2695                 return NULL;
2696
2697         /* Don't import buffers which span multiple outputs. */
2698         if (ev->output_mask != (1u << output->base.id))
2699                 return NULL;
2700
2701         /* We can only import GBM buffers. */
2702         if (b->gbm == NULL)
2703                 return NULL;
2704
2705         if (ev->surface->buffer_ref.buffer == NULL)
2706                 return NULL;
2707         buffer_resource = ev->surface->buffer_ref.buffer->resource;
2708         if (wl_shm_buffer_get(buffer_resource))
2709                 return NULL;
2710
2711         if (viewport->buffer.transform != output->base.transform)
2712                 return NULL;
2713         if (viewport->buffer.scale != output->base.current_scale)
2714                 return NULL;
2715         if (!drm_view_transform_supported(ev))
2716                 return NULL;
2717
2718         if (ev->alpha != 1.0f)
2719                 return NULL;
2720
2721         wl_list_for_each(p, &b->plane_list, link) {
2722                 if (p->type != WDRM_PLANE_TYPE_OVERLAY)
2723                         continue;
2724
2725                 if (!drm_plane_is_available(p, output))
2726                         continue;
2727
2728                 state = drm_output_state_get_plane(output_state, p);
2729                 if (state->fb) {
2730                         state = NULL;
2731                         continue;
2732                 }
2733
2734                 break;
2735         }
2736
2737         /* No sprites available */
2738         if (!state)
2739                 return NULL;
2740
2741         if ((dmabuf = linux_dmabuf_buffer_get(buffer_resource))) {
2742 #ifdef HAVE_GBM_FD_IMPORT
2743                 /* XXX: TODO:
2744                  *
2745                  * Use AddFB2 directly, do not go via GBM.
2746                  * Add support for multiplanar formats.
2747                  * Both require refactoring in the DRM-backend to
2748                  * support a mix of gbm_bos and drmfbs.
2749                  */
2750                 struct gbm_import_fd_data gbm_dmabuf = {
2751                         .fd     = dmabuf->attributes.fd[0],
2752                         .width  = dmabuf->attributes.width,
2753                         .height = dmabuf->attributes.height,
2754                         .stride = dmabuf->attributes.stride[0],
2755                         .format = dmabuf->attributes.format
2756                 };
2757
2758                 /* XXX: TODO:
2759                  *
2760                  * Currently the buffer is rejected if any dmabuf attribute
2761                  * flag is set.  This keeps us from passing an inverted /
2762                  * interlaced / bottom-first buffer (or any other type that may
2763                  * be added in the future) through to an overlay.  Ultimately,
2764                  * these types of buffers should be handled through buffer
2765                  * transforms and not as spot-checks requiring specific
2766                  * knowledge. */
2767                 if (dmabuf->attributes.n_planes != 1 ||
2768                     dmabuf->attributes.offset[0] != 0 ||
2769                     dmabuf->attributes.flags)
2770                         return NULL;
2771
2772                 bo = gbm_bo_import(b->gbm, GBM_BO_IMPORT_FD, &gbm_dmabuf,
2773                                    GBM_BO_USE_SCANOUT);
2774 #else
2775                 goto err;
2776 #endif
2777         } else {
2778                 bo = gbm_bo_import(b->gbm, GBM_BO_IMPORT_WL_BUFFER,
2779                                    buffer_resource, GBM_BO_USE_SCANOUT);
2780         }
2781         if (!bo)
2782                 goto err;
2783
2784         format = drm_output_check_plane_format(p, ev, bo);
2785         if (format == 0)
2786                 goto err;
2787
2788         state->fb = drm_fb_get_from_bo(bo, b, format, BUFFER_CLIENT);
2789         if (!state->fb)
2790                 goto err;
2791
2792         drm_fb_set_buffer(state->fb, ev->surface->buffer_ref.buffer);
2793
2794         state->output = output;
2795
2796         box = pixman_region32_extents(&ev->transform.boundingbox);
2797         p->base.x = box->x1;
2798         p->base.y = box->y1;
2799
2800         /*
2801          * Calculate the source & dest rects properly based on actual
2802          * position (note the caller has called weston_view_update_transform()
2803          * for us already).
2804          */
2805         pixman_region32_init(&dest_rect);
2806         pixman_region32_intersect(&dest_rect, &ev->transform.boundingbox,
2807                                   &output->base.region);
2808         pixman_region32_translate(&dest_rect, -output->base.x, -output->base.y);
2809         box = pixman_region32_extents(&dest_rect);
2810         tbox = weston_transformed_rect(output->base.width,
2811                                        output->base.height,
2812                                        output->base.transform,
2813                                        output->base.current_scale,
2814                                        *box);
2815         state->dest_x = tbox.x1;
2816         state->dest_y = tbox.y1;
2817         state->dest_w = tbox.x2 - tbox.x1;
2818         state->dest_h = tbox.y2 - tbox.y1;
2819         pixman_region32_fini(&dest_rect);
2820
2821         pixman_region32_init(&src_rect);
2822         pixman_region32_intersect(&src_rect, &ev->transform.boundingbox,
2823                                   &output->base.region);
2824         box = pixman_region32_extents(&src_rect);
2825
2826         weston_view_from_global_fixed(ev,
2827                                       wl_fixed_from_int(box->x1),
2828                                       wl_fixed_from_int(box->y1),
2829                                       &sx1, &sy1);
2830         weston_view_from_global_fixed(ev,
2831                                       wl_fixed_from_int(box->x2),
2832                                       wl_fixed_from_int(box->y2),
2833                                       &sx2, &sy2);
2834
2835         if (sx1 < 0)
2836                 sx1 = 0;
2837         if (sy1 < 0)
2838                 sy1 = 0;
2839         if (sx2 > wl_fixed_from_int(ev->surface->width))
2840                 sx2 = wl_fixed_from_int(ev->surface->width);
2841         if (sy2 > wl_fixed_from_int(ev->surface->height))
2842                 sy2 = wl_fixed_from_int(ev->surface->height);
2843
2844         tbox.x1 = sx1;
2845         tbox.y1 = sy1;
2846         tbox.x2 = sx2;
2847         tbox.y2 = sy2;
2848
2849         tbox = weston_transformed_rect(wl_fixed_from_int(ev->surface->width),
2850                                        wl_fixed_from_int(ev->surface->height),
2851                                        viewport->buffer.transform,
2852                                        viewport->buffer.scale,
2853                                        tbox);
2854
2855         state->src_x = tbox.x1 << 8;
2856         state->src_y = tbox.y1 << 8;
2857         state->src_w = (tbox.x2 - tbox.x1) << 8;
2858         state->src_h = (tbox.y2 - tbox.y1) << 8;
2859         pixman_region32_fini(&src_rect);
2860
2861         return &p->base;
2862
2863 err:
2864         drm_plane_state_put_back(state);
2865         if (bo)
2866                 gbm_bo_destroy(bo);
2867         return NULL;
2868 }
2869
2870 /**
2871  * Update the image for the current cursor surface
2872  *
2873  * @param b DRM backend structure
2874  * @param bo GBM buffer object to write into
2875  * @param ev View to use for cursor image
2876  */
2877 static void
2878 cursor_bo_update(struct drm_backend *b, struct gbm_bo *bo,
2879                  struct weston_view *ev)
2880 {
2881         struct weston_buffer *buffer = ev->surface->buffer_ref.buffer;
2882         uint32_t buf[b->cursor_width * b->cursor_height];
2883         int32_t stride;
2884         uint8_t *s;
2885         int i;
2886
2887         assert(buffer && buffer->shm_buffer);
2888         assert(buffer->shm_buffer == wl_shm_buffer_get(buffer->resource));
2889         assert(ev->surface->width <= b->cursor_width);
2890         assert(ev->surface->height <= b->cursor_height);
2891
2892         memset(buf, 0, sizeof buf);
2893         stride = wl_shm_buffer_get_stride(buffer->shm_buffer);
2894         s = wl_shm_buffer_get_data(buffer->shm_buffer);
2895
2896         wl_shm_buffer_begin_access(buffer->shm_buffer);
2897         for (i = 0; i < ev->surface->height; i++)
2898                 memcpy(buf + i * b->cursor_width,
2899                        s + i * stride,
2900                        ev->surface->width * 4);
2901         wl_shm_buffer_end_access(buffer->shm_buffer);
2902
2903         if (gbm_bo_write(bo, buf, sizeof buf) < 0)
2904                 weston_log("failed update cursor: %m\n");
2905 }
2906
2907 static struct weston_plane *
2908 drm_output_prepare_cursor_view(struct drm_output_state *output_state,
2909                                struct weston_view *ev)
2910 {
2911         struct drm_output *output = output_state->output;
2912         struct drm_backend *b = to_drm_backend(output->base.compositor);
2913         struct drm_plane *plane = output->cursor_plane;
2914         struct drm_plane_state *plane_state;
2915         struct weston_buffer_viewport *viewport = &ev->surface->buffer_viewport;
2916         struct wl_shm_buffer *shmbuf;
2917         bool needs_update = false;
2918         float x, y;
2919
2920         if (!plane)
2921                 return NULL;
2922
2923         if (b->cursors_are_broken)
2924                 return NULL;
2925
2926         if (!plane->state_cur->complete)
2927                 return NULL;
2928
2929         if (plane->state_cur->output && plane->state_cur->output != output)
2930                 return NULL;
2931
2932         /* Don't import buffers which span multiple outputs. */
2933         if (ev->output_mask != (1u << output->base.id))
2934                 return NULL;
2935
2936         /* We use GBM to import SHM buffers. */
2937         if (b->gbm == NULL)
2938                 return NULL;
2939
2940         if (ev->surface->buffer_ref.buffer == NULL)
2941                 return NULL;
2942         shmbuf = wl_shm_buffer_get(ev->surface->buffer_ref.buffer->resource);
2943         if (!shmbuf)
2944                 return NULL;
2945         if (wl_shm_buffer_get_format(shmbuf) != WL_SHM_FORMAT_ARGB8888)
2946                 return NULL;
2947
2948         if (output->base.transform != WL_OUTPUT_TRANSFORM_NORMAL)
2949                 return NULL;
2950         if (ev->transform.enabled &&
2951             (ev->transform.matrix.type > WESTON_MATRIX_TRANSFORM_TRANSLATE))
2952                 return NULL;
2953         if (viewport->buffer.scale != output->base.current_scale)
2954                 return NULL;
2955         if (ev->geometry.scissor_enabled)
2956                 return NULL;
2957
2958         if (ev->surface->width > b->cursor_width ||
2959             ev->surface->height > b->cursor_height)
2960                 return NULL;
2961
2962         plane_state =
2963                 drm_output_state_get_plane(output_state, output->cursor_plane);
2964
2965         if (plane_state && plane_state->fb)
2966                 return NULL;
2967
2968         /* Since we're setting plane state up front, we need to work out
2969          * whether or not we need to upload a new cursor. We can't use the
2970          * plane damage, since the planes haven't actually been calculated
2971          * yet: instead try to figure it out directly. KMS cursor planes are
2972          * pretty unique here, in that they lie partway between a Weston plane
2973          * (direct scanout) and a renderer. */
2974         if (ev != output->cursor_view ||
2975             pixman_region32_not_empty(&ev->surface->damage)) {
2976                 output->current_cursor++;
2977                 output->current_cursor =
2978                         output->current_cursor %
2979                                 ARRAY_LENGTH(output->gbm_cursor_fb);
2980                 needs_update = true;
2981         }
2982
2983         output->cursor_view = ev;
2984         weston_view_to_global_float(ev, 0, 0, &x, &y);
2985         plane->base.x = x;
2986         plane->base.y = y;
2987
2988         plane_state->fb =
2989                 drm_fb_ref(output->gbm_cursor_fb[output->current_cursor]);
2990         plane_state->output = output;
2991         plane_state->src_x = 0;
2992         plane_state->src_y = 0;
2993         plane_state->src_w = b->cursor_width << 16;
2994         plane_state->src_h = b->cursor_height << 16;
2995         plane_state->dest_x = (x - output->base.x) * output->base.current_scale;
2996         plane_state->dest_y = (y - output->base.y) * output->base.current_scale;
2997         plane_state->dest_w = b->cursor_width;
2998         plane_state->dest_h = b->cursor_height;
2999
3000         if (needs_update)
3001                 cursor_bo_update(b, plane_state->fb->bo, ev);
3002
3003         return &plane->base;
3004 }
3005
3006 static void
3007 drm_output_set_cursor(struct drm_output_state *output_state)
3008 {
3009         struct drm_output *output = output_state->output;
3010         struct drm_backend *b = to_drm_backend(output->base.compositor);
3011         struct drm_plane *plane = output->cursor_plane;
3012         struct drm_plane_state *state;
3013         EGLint handle;
3014         struct gbm_bo *bo;
3015
3016         if (!plane)
3017                 return;
3018
3019         state = drm_output_state_get_existing_plane(output_state, plane);
3020         if (!state)
3021                 return;
3022
3023         if (!state->fb) {
3024                 pixman_region32_fini(&plane->base.damage);
3025                 pixman_region32_init(&plane->base.damage);
3026                 drmModeSetCursor(b->drm.fd, output->crtc_id, 0, 0, 0);
3027                 return;
3028         }
3029
3030         assert(state->fb == output->gbm_cursor_fb[output->current_cursor]);
3031         assert(!plane->state_cur->output || plane->state_cur->output == output);
3032
3033         if (plane->state_cur->fb != state->fb) {
3034                 bo = state->fb->bo;
3035                 handle = gbm_bo_get_handle(bo).s32;
3036                 if (drmModeSetCursor(b->drm.fd, output->crtc_id, handle,
3037                                      b->cursor_width, b->cursor_height)) {
3038                         weston_log("failed to set cursor: %m\n");
3039                         goto err;
3040                 }
3041         }
3042
3043         pixman_region32_fini(&plane->base.damage);
3044         pixman_region32_init(&plane->base.damage);
3045
3046         if (drmModeMoveCursor(b->drm.fd, output->crtc_id,
3047                               state->dest_x, state->dest_y)) {
3048                 weston_log("failed to move cursor: %m\n");
3049                 goto err;
3050         }
3051
3052         return;
3053
3054 err:
3055         b->cursors_are_broken = 1;
3056         drmModeSetCursor(b->drm.fd, output->crtc_id, 0, 0, 0);
3057 }
3058
3059 static void
3060 drm_assign_planes(struct weston_output *output_base, void *repaint_data)
3061 {
3062         struct drm_backend *b = to_drm_backend(output_base->compositor);
3063         struct drm_pending_state *pending_state = repaint_data;
3064         struct drm_output *output = to_drm_output(output_base);
3065         struct drm_output_state *state;
3066         struct drm_plane_state *plane_state;
3067         struct weston_view *ev;
3068         pixman_region32_t surface_overlap, renderer_region;
3069         struct weston_plane *primary, *next_plane;
3070         bool picked_scanout = false;
3071
3072         assert(!output->state_last);
3073         state = drm_output_state_duplicate(output->state_cur,
3074                                            pending_state,
3075                                            DRM_OUTPUT_STATE_CLEAR_PLANES);
3076
3077         /*
3078          * Find a surface for each sprite in the output using some heuristics:
3079          * 1) size
3080          * 2) frequency of update
3081          * 3) opacity (though some hw might support alpha blending)
3082          * 4) clipping (this can be fixed with color keys)
3083          *
3084          * The idea is to save on blitting since this should save power.
3085          * If we can get a large video surface on the sprite for example,
3086          * the main display surface may not need to update at all, and
3087          * the client buffer can be used directly for the sprite surface
3088          * as we do for flipping full screen surfaces.
3089          */
3090         pixman_region32_init(&renderer_region);
3091         primary = &output_base->compositor->primary_plane;
3092
3093         wl_list_for_each(ev, &output_base->compositor->view_list, link) {
3094                 struct weston_surface *es = ev->surface;
3095
3096                 /* Test whether this buffer can ever go into a plane:
3097                  * non-shm, or small enough to be a cursor.
3098                  *
3099                  * Also, keep a reference when using the pixman renderer.
3100                  * That makes it possible to do a seamless switch to the GL
3101                  * renderer and since the pixman renderer keeps a reference
3102                  * to the buffer anyway, there is no side effects.
3103                  */
3104                 if (b->use_pixman ||
3105                     (es->buffer_ref.buffer &&
3106                     (!wl_shm_buffer_get(es->buffer_ref.buffer->resource) ||
3107                      (ev->surface->width <= b->cursor_width &&
3108                       ev->surface->height <= b->cursor_height))))
3109                         es->keep_buffer = true;
3110                 else
3111                         es->keep_buffer = false;
3112
3113                 pixman_region32_init(&surface_overlap);
3114                 pixman_region32_intersect(&surface_overlap, &renderer_region,
3115                                           &ev->transform.boundingbox);
3116
3117                 next_plane = NULL;
3118                 if (pixman_region32_not_empty(&surface_overlap) || picked_scanout)
3119                         next_plane = primary;
3120                 if (next_plane == NULL)
3121                         next_plane = drm_output_prepare_cursor_view(state, ev);
3122
3123                 /* If a higher-stacked view already got assigned to scanout, it's incorrect to
3124                  * assign a subsequent (lower-stacked) view to scanout.
3125                  */
3126                 if (next_plane == NULL) {
3127                         next_plane = drm_output_prepare_scanout_view(state, ev);
3128                         if (next_plane)
3129                                 picked_scanout = true;
3130                 }
3131
3132                 if (next_plane == NULL)
3133                         next_plane = drm_output_prepare_overlay_view(state, ev);
3134
3135                 if (next_plane == NULL)
3136                         next_plane = primary;
3137
3138                 weston_view_move_to_plane(ev, next_plane);
3139
3140                 if (next_plane == primary)
3141                         pixman_region32_union(&renderer_region,
3142                                               &renderer_region,
3143                                               &ev->transform.boundingbox);
3144
3145                 if (next_plane == primary ||
3146                     (output->cursor_plane &&
3147                      next_plane == &output->cursor_plane->base)) {
3148                         /* cursor plane involves a copy */
3149                         ev->psf_flags = 0;
3150                 } else {
3151                         /* All other planes are a direct scanout of a
3152                          * single client buffer.
3153                          */
3154                         ev->psf_flags = WP_PRESENTATION_FEEDBACK_KIND_ZERO_COPY;
3155                 }
3156
3157                 pixman_region32_fini(&surface_overlap);
3158         }
3159         pixman_region32_fini(&renderer_region);
3160
3161         /* We rely on output->cursor_view being both an accurate reflection of
3162          * the cursor plane's state, but also being maintained across repaints
3163          * to avoid unnecessary damage uploads, per the comment in
3164          * drm_output_prepare_cursor_view. In the event that we go from having
3165          * a cursor view to not having a cursor view, we need to clear it. */
3166         if (output->cursor_view) {
3167                 plane_state =
3168                         drm_output_state_get_existing_plane(state,
3169                                                             output->cursor_plane);
3170                 if (!plane_state || !plane_state->fb)
3171                         output->cursor_view = NULL;
3172         }
3173 }
3174
3175 /**
3176  * Find the closest-matching mode for a given target
3177  *
3178  * Given a target mode, find the most suitable mode amongst the output's
3179  * current mode list to use, preferring the current mode if possible, to
3180  * avoid an expensive mode switch.
3181  *
3182  * @param output DRM output
3183  * @param target_mode Mode to attempt to match
3184  * @returns Pointer to a mode from the output's mode list
3185  */
3186 static struct drm_mode *
3187 choose_mode (struct drm_output *output, struct weston_mode *target_mode)
3188 {
3189         struct drm_mode *tmp_mode = NULL, *mode;
3190
3191         if (output->base.current_mode->width == target_mode->width &&
3192             output->base.current_mode->height == target_mode->height &&
3193             (output->base.current_mode->refresh == target_mode->refresh ||
3194              target_mode->refresh == 0))
3195                 return to_drm_mode(output->base.current_mode);
3196
3197         wl_list_for_each(mode, &output->base.mode_list, base.link) {
3198                 if (mode->mode_info.hdisplay == target_mode->width &&
3199                     mode->mode_info.vdisplay == target_mode->height) {
3200                         if (mode->base.refresh == target_mode->refresh ||
3201                             target_mode->refresh == 0) {
3202                                 return mode;
3203                         } else if (!tmp_mode)
3204                                 tmp_mode = mode;
3205                 }
3206         }
3207
3208         return tmp_mode;
3209 }
3210
3211 static int
3212 drm_output_init_egl(struct drm_output *output, struct drm_backend *b);
3213 static void
3214 drm_output_fini_egl(struct drm_output *output);
3215 static int
3216 drm_output_init_pixman(struct drm_output *output, struct drm_backend *b);
3217 static void
3218 drm_output_fini_pixman(struct drm_output *output);
3219
3220 static int
3221 drm_output_switch_mode(struct weston_output *output_base, struct weston_mode *mode)
3222 {
3223         struct drm_output *output = to_drm_output(output_base);
3224         struct drm_backend *b = to_drm_backend(output_base->compositor);
3225         struct drm_mode *drm_mode = choose_mode(output, mode);
3226
3227         if (!drm_mode) {
3228                 weston_log("%s: invalid resolution %dx%d\n",
3229                            output_base->name, mode->width, mode->height);
3230                 return -1;
3231         }
3232
3233         if (&drm_mode->base == output->base.current_mode)
3234                 return 0;
3235
3236         output->base.current_mode->flags = 0;
3237
3238         output->base.current_mode = &drm_mode->base;
3239         output->base.current_mode->flags =
3240                 WL_OUTPUT_MODE_CURRENT | WL_OUTPUT_MODE_PREFERRED;
3241
3242         /* XXX: This drops our current buffer too early, before we've started
3243          *      displaying it. Ideally this should be much more atomic and
3244          *      integrated with a full repaint cycle, rather than doing a
3245          *      sledgehammer modeswitch first, and only later showing new
3246          *      content.
3247          */
3248         b->state_invalid = true;
3249
3250         if (b->use_pixman) {
3251                 drm_output_fini_pixman(output);
3252                 if (drm_output_init_pixman(output, b) < 0) {
3253                         weston_log("failed to init output pixman state with "
3254                                    "new mode\n");
3255                         return -1;
3256                 }
3257         } else {
3258                 drm_output_fini_egl(output);
3259                 if (drm_output_init_egl(output, b) < 0) {
3260                         weston_log("failed to init output egl state with "
3261                                    "new mode");
3262                         return -1;
3263                 }
3264         }
3265
3266         return 0;
3267 }
3268
3269 static int
3270 on_drm_input(int fd, uint32_t mask, void *data)
3271 {
3272 #ifdef HAVE_DRM_ATOMIC
3273         struct drm_backend *b = data;
3274 #endif
3275         drmEventContext evctx;
3276
3277         memset(&evctx, 0, sizeof evctx);
3278 #ifndef HAVE_DRM_ATOMIC
3279         evctx.version = 2;
3280 #else
3281         evctx.version = 3;
3282         if (b->atomic_modeset)
3283                 evctx.page_flip_handler2 = atomic_flip_handler;
3284         else
3285 #endif
3286                 evctx.page_flip_handler = page_flip_handler;
3287         evctx.vblank_handler = vblank_handler;
3288         drmHandleEvent(fd, &evctx);
3289
3290         return 1;
3291 }
3292
3293 static int
3294 init_kms_caps(struct drm_backend *b)
3295 {
3296         uint64_t cap;
3297         int ret;
3298         clockid_t clk_id;
3299
3300         weston_log("using %s\n", b->drm.filename);
3301
3302         ret = drmGetCap(b->drm.fd, DRM_CAP_TIMESTAMP_MONOTONIC, &cap);
3303         if (ret == 0 && cap == 1)
3304                 clk_id = CLOCK_MONOTONIC;
3305         else
3306                 clk_id = CLOCK_REALTIME;
3307
3308         if (weston_compositor_set_presentation_clock(b->compositor, clk_id) < 0) {
3309                 weston_log("Error: failed to set presentation clock %d.\n",
3310                            clk_id);
3311                 return -1;
3312         }
3313
3314         ret = drmGetCap(b->drm.fd, DRM_CAP_CURSOR_WIDTH, &cap);
3315         if (ret == 0)
3316                 b->cursor_width = cap;
3317         else
3318                 b->cursor_width = 64;
3319
3320         ret = drmGetCap(b->drm.fd, DRM_CAP_CURSOR_HEIGHT, &cap);
3321         if (ret == 0)
3322                 b->cursor_height = cap;
3323         else
3324                 b->cursor_height = 64;
3325
3326         if (!getenv("WESTON_DISABLE_UNIVERSAL_PLANES")) {
3327                 ret = drmSetClientCap(b->drm.fd, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1);
3328                 b->universal_planes = (ret == 0);
3329         }
3330         weston_log("DRM: %s universal planes\n",
3331                    b->universal_planes ? "supports" : "does not support");
3332
3333 #ifdef HAVE_DRM_ATOMIC
3334         if (b->universal_planes && !getenv("WESTON_DISABLE_ATOMIC")) {
3335                 ret = drmGetCap(b->drm.fd, DRM_CAP_CRTC_IN_VBLANK_EVENT, &cap);
3336                 if (ret != 0)
3337                         cap = 0;
3338                 ret = drmSetClientCap(b->drm.fd, DRM_CLIENT_CAP_ATOMIC, 1);
3339                 b->atomic_modeset = ((ret == 0) && (cap == 1));
3340         }
3341 #endif
3342         weston_log("DRM: %s atomic modesetting\n",
3343                    b->atomic_modeset ? "supports" : "does not support");
3344
3345         return 0;
3346 }
3347
3348 static struct gbm_device *
3349 create_gbm_device(int fd)
3350 {
3351         struct gbm_device *gbm;
3352
3353         gl_renderer = weston_load_module("gl-renderer.so",
3354                                          "gl_renderer_interface");
3355         if (!gl_renderer)
3356                 return NULL;
3357
3358         /* GBM will load a dri driver, but even though they need symbols from
3359          * libglapi, in some version of Mesa they are not linked to it. Since
3360          * only the gl-renderer module links to it, the call above won't make
3361          * these symbols globally available, and loading the DRI driver fails.
3362          * Workaround this by dlopen()'ing libglapi with RTLD_GLOBAL. */
3363         dlopen("libglapi.so.0", RTLD_LAZY | RTLD_GLOBAL);
3364
3365         gbm = gbm_create_device(fd);
3366
3367         return gbm;
3368 }
3369
3370 /* When initializing EGL, if the preferred buffer format isn't available
3371  * we may be able to substitute an ARGB format for an XRGB one.
3372  *
3373  * This returns 0 if substitution isn't possible, but 0 might be a
3374  * legitimate format for other EGL platforms, so the caller is
3375  * responsible for checking for 0 before calling gl_renderer->create().
3376  *
3377  * This works around https://bugs.freedesktop.org/show_bug.cgi?id=89689
3378  * but it's entirely possible we'll see this again on other implementations.
3379  */
3380 static int
3381 fallback_format_for(uint32_t format)
3382 {
3383         switch (format) {
3384         case GBM_FORMAT_XRGB8888:
3385                 return GBM_FORMAT_ARGB8888;
3386         case GBM_FORMAT_XRGB2101010:
3387                 return GBM_FORMAT_ARGB2101010;
3388         default:
3389                 return 0;
3390         }
3391 }
3392
3393 static int
3394 drm_backend_create_gl_renderer(struct drm_backend *b)
3395 {
3396         EGLint format[3] = {
3397                 b->gbm_format,
3398                 fallback_format_for(b->gbm_format),
3399                 0,
3400         };
3401         int n_formats = 2;
3402
3403         if (format[1])
3404                 n_formats = 3;
3405         if (gl_renderer->display_create(b->compositor,
3406                                         EGL_PLATFORM_GBM_KHR,
3407                                         (void *)b->gbm,
3408                                         NULL,
3409                                         gl_renderer->opaque_attribs,
3410                                         format,
3411                                         n_formats) < 0) {
3412                 return -1;
3413         }
3414
3415         return 0;
3416 }
3417
3418 static int
3419 init_egl(struct drm_backend *b)
3420 {
3421         b->gbm = create_gbm_device(b->drm.fd);
3422
3423         if (!b->gbm)
3424                 return -1;
3425
3426         if (drm_backend_create_gl_renderer(b) < 0) {
3427                 gbm_device_destroy(b->gbm);
3428                 return -1;
3429         }
3430
3431         return 0;
3432 }
3433
3434 static int
3435 init_pixman(struct drm_backend *b)
3436 {
3437         return pixman_renderer_init(b->compositor);
3438 }
3439
3440 /**
3441  * Create a drm_plane for a hardware plane
3442  *
3443  * Creates one drm_plane structure for a hardware plane, and initialises its
3444  * properties and formats.
3445  *
3446  * In the absence of universal plane support, where KMS does not explicitly
3447  * expose the primary and cursor planes to userspace, this may also create
3448  * an 'internal' plane for internal management.
3449  *
3450  * This function does not add the plane to the list of usable planes in Weston
3451  * itself; the caller is responsible for this.
3452  *
3453  * Call drm_plane_destroy to clean up the plane.
3454  *
3455  * @sa drm_output_find_special_plane
3456  * @param b DRM compositor backend
3457  * @param kplane DRM plane to create, or NULL if creating internal plane
3458  * @param output Output to create internal plane for, or NULL
3459  * @param type Type to use when creating internal plane, or invalid
3460  * @param format Format to use for internal planes, or 0
3461  */
3462 static struct drm_plane *
3463 drm_plane_create(struct drm_backend *b, const drmModePlane *kplane,
3464                  struct drm_output *output, enum wdrm_plane_type type,
3465                  uint32_t format)
3466 {
3467         struct drm_plane *plane;
3468         drmModeObjectProperties *props;
3469         int num_formats = (kplane) ? kplane->count_formats : 1;
3470
3471         plane = zalloc(sizeof(*plane) +
3472                        (sizeof(uint32_t) * num_formats));
3473         if (!plane) {
3474                 weston_log("%s: out of memory\n", __func__);
3475                 return NULL;
3476         }
3477
3478         plane->backend = b;
3479         plane->state_cur = drm_plane_state_alloc(NULL, plane);
3480         plane->state_cur->complete = true;
3481
3482         if (kplane) {
3483                 plane->possible_crtcs = kplane->possible_crtcs;
3484                 plane->plane_id = kplane->plane_id;
3485                 plane->count_formats = kplane->count_formats;
3486                 memcpy(plane->formats, kplane->formats,
3487                        kplane->count_formats * sizeof(kplane->formats[0]));
3488
3489                 props = drmModeObjectGetProperties(b->drm.fd, kplane->plane_id,
3490                                                    DRM_MODE_OBJECT_PLANE);
3491                 if (!props) {
3492                         weston_log("couldn't get plane properties\n");
3493                         goto err;
3494                 }
3495                 drm_property_info_populate(b, plane_props, plane->props,
3496                                            WDRM_PLANE__COUNT, props);
3497                 plane->type =
3498                         drm_property_get_value(&plane->props[WDRM_PLANE_TYPE],
3499                                                props,
3500                                                WDRM_PLANE_TYPE__COUNT);
3501                 drmModeFreeObjectProperties(props);
3502         }
3503         else {
3504                 plane->possible_crtcs = (1 << output->pipe);
3505                 plane->plane_id = 0;
3506                 plane->count_formats = 1;
3507                 plane->formats[0] = format;
3508                 plane->type = type;
3509         }
3510
3511         if (plane->type == WDRM_PLANE_TYPE__COUNT)
3512                 goto err_props;
3513
3514         /* With universal planes, everything is a DRM plane; without
3515          * universal planes, the only DRM planes are overlay planes.
3516          * Everything else is a fake plane. */
3517         if (b->universal_planes) {
3518                 assert(kplane);
3519         } else {
3520                 if (kplane)
3521                         assert(plane->type == WDRM_PLANE_TYPE_OVERLAY);
3522                 else
3523                         assert(plane->type != WDRM_PLANE_TYPE_OVERLAY &&
3524                                output);
3525         }
3526
3527         weston_plane_init(&plane->base, b->compositor, 0, 0);
3528         wl_list_insert(&b->plane_list, &plane->link);
3529
3530         return plane;
3531
3532 err_props:
3533         drm_property_info_free(plane->props, WDRM_PLANE__COUNT);
3534 err:
3535         drm_plane_state_free(plane->state_cur, true);
3536         free(plane);
3537         return NULL;
3538 }
3539
3540 /**
3541  * Find, or create, a special-purpose plane
3542  *
3543  * Primary and cursor planes are a special case, in that before universal
3544  * planes, they are driven by non-plane API calls. Without universal plane
3545  * support, the only way to configure a primary plane is via drmModeSetCrtc,
3546  * and the only way to configure a cursor plane is drmModeSetCursor2.
3547  *
3548  * Although they may actually be regular planes in the hardware, without
3549  * universal plane support, these planes are not actually exposed to
3550  * userspace in the regular plane list.
3551  *
3552  * However, for ease of internal tracking, we want to manage all planes
3553  * through the same drm_plane structures. Therefore, when we are running
3554  * without universal plane support, we create fake drm_plane structures
3555  * to track these planes.
3556  *
3557  * @param b DRM backend
3558  * @param output Output to use for plane
3559  * @param type Type of plane
3560  */
3561 static struct drm_plane *
3562 drm_output_find_special_plane(struct drm_backend *b, struct drm_output *output,
3563                               enum wdrm_plane_type type)
3564 {
3565         struct drm_plane *plane;
3566
3567         if (!b->universal_planes) {
3568                 uint32_t format;
3569
3570                 switch (type) {
3571                 case WDRM_PLANE_TYPE_CURSOR:
3572                         format = GBM_FORMAT_ARGB8888;
3573                         break;
3574                 case WDRM_PLANE_TYPE_PRIMARY:
3575                         /* We don't know what formats the primary plane supports
3576                          * before universal planes, so we just assume that the
3577                          * GBM format works; however, this isn't set until after
3578                          * the output is created. */
3579                         format = 0;
3580                         break;
3581                 default:
3582                         assert(!"invalid type in drm_output_find_special_plane");
3583                         break;
3584                 }
3585
3586                 return drm_plane_create(b, NULL, output, type, format);
3587         }
3588
3589         wl_list_for_each(plane, &b->plane_list, link) {
3590                 struct drm_output *tmp;
3591                 bool found_elsewhere = false;
3592
3593                 if (plane->type != type)
3594                         continue;
3595                 if (!drm_plane_is_available(plane, output))
3596                         continue;
3597
3598                 /* On some platforms, primary/cursor planes can roam
3599                  * between different CRTCs, so make sure we don't claim the
3600                  * same plane for two outputs. */
3601                 wl_list_for_each(tmp, &b->compositor->output_list,
3602                                  base.link) {
3603                         if (tmp->cursor_plane == plane ||
3604                             tmp->scanout_plane == plane) {
3605                                 found_elsewhere = true;
3606                                 break;
3607                         }
3608                 }
3609
3610                 if (found_elsewhere)
3611                         continue;
3612
3613                 plane->possible_crtcs = (1 << output->pipe);
3614                 return plane;
3615         }
3616
3617         return NULL;
3618 }
3619
3620 /**
3621  * Destroy one DRM plane
3622  *
3623  * Destroy a DRM plane, removing it from screen and releasing its retained
3624  * buffers in the process. The counterpart to drm_plane_create.
3625  *
3626  * @param plane Plane to deallocate (will be freed)
3627  */
3628 static void
3629 drm_plane_destroy(struct drm_plane *plane)
3630 {
3631         if (plane->type == WDRM_PLANE_TYPE_OVERLAY)
3632                 drmModeSetPlane(plane->backend->drm.fd, plane->plane_id,
3633                                 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
3634         drm_plane_state_free(plane->state_cur, true);
3635         drm_property_info_free(plane->props, WDRM_PLANE__COUNT);
3636         weston_plane_release(&plane->base);
3637         wl_list_remove(&plane->link);
3638         free(plane);
3639 }
3640
3641 /**
3642  * Initialise sprites (overlay planes)
3643  *
3644  * Walk the list of provided DRM planes, and add overlay planes.
3645  *
3646  * Call destroy_sprites to free these planes.
3647  *
3648  * @param b DRM compositor backend
3649  */
3650 static void
3651 create_sprites(struct drm_backend *b)
3652 {
3653         drmModePlaneRes *kplane_res;
3654         drmModePlane *kplane;
3655         struct drm_plane *drm_plane;
3656         uint32_t i;
3657         kplane_res = drmModeGetPlaneResources(b->drm.fd);
3658         if (!kplane_res) {
3659                 weston_log("failed to get plane resources: %s\n",
3660                         strerror(errno));
3661                 return;
3662         }
3663
3664         for (i = 0; i < kplane_res->count_planes; i++) {
3665                 kplane = drmModeGetPlane(b->drm.fd, kplane_res->planes[i]);
3666                 if (!kplane)
3667                         continue;
3668
3669                 drm_plane = drm_plane_create(b, kplane, NULL,
3670                                              WDRM_PLANE_TYPE__COUNT, 0);
3671                 drmModeFreePlane(kplane);
3672                 if (!drm_plane)
3673                         continue;
3674
3675                 if (drm_plane->type == WDRM_PLANE_TYPE_OVERLAY)
3676                         weston_compositor_stack_plane(b->compositor,
3677                                                       &drm_plane->base,
3678                                                       &b->compositor->primary_plane);
3679         }
3680
3681         drmModeFreePlaneResources(kplane_res);
3682 }
3683
3684 /**
3685  * Clean up sprites (overlay planes)
3686  *
3687  * The counterpart to create_sprites.
3688  *
3689  * @param b DRM compositor backend
3690  */
3691 static void
3692 destroy_sprites(struct drm_backend *b)
3693 {
3694         struct drm_plane *plane, *next;
3695
3696         wl_list_for_each_safe(plane, next, &b->plane_list, link)
3697                 drm_plane_destroy(plane);
3698 }
3699
3700 static uint32_t
3701 drm_refresh_rate_mHz(const drmModeModeInfo *info)
3702 {
3703         uint64_t refresh;
3704
3705         /* Calculate higher precision (mHz) refresh rate */
3706         refresh = (info->clock * 1000000LL / info->htotal +
3707                    info->vtotal / 2) / info->vtotal;
3708
3709         if (info->flags & DRM_MODE_FLAG_INTERLACE)
3710                 refresh *= 2;
3711         if (info->flags & DRM_MODE_FLAG_DBLSCAN)
3712                 refresh /= 2;
3713         if (info->vscan > 1)
3714             refresh /= info->vscan;
3715
3716         return refresh;
3717 }
3718
3719 /**
3720  * Add a mode to output's mode list
3721  *
3722  * Copy the supplied DRM mode into a Weston mode structure, and add it to the
3723  * output's mode list.
3724  *
3725  * @param output DRM output to add mode to
3726  * @param info DRM mode structure to add
3727  * @returns Newly-allocated Weston/DRM mode structure
3728  */
3729 static struct drm_mode *
3730 drm_output_add_mode(struct drm_output *output, const drmModeModeInfo *info)
3731 {
3732         struct drm_mode *mode;
3733
3734         mode = malloc(sizeof *mode);
3735         if (mode == NULL)
3736                 return NULL;
3737
3738         mode->base.flags = 0;
3739         mode->base.width = info->hdisplay;
3740         mode->base.height = info->vdisplay;
3741
3742         mode->base.refresh = drm_refresh_rate_mHz(info);
3743         mode->mode_info = *info;
3744         mode->blob_id = 0;
3745
3746         if (info->type & DRM_MODE_TYPE_PREFERRED)
3747                 mode->base.flags |= WL_OUTPUT_MODE_PREFERRED;
3748
3749         wl_list_insert(output->base.mode_list.prev, &mode->base.link);
3750
3751         return mode;
3752 }
3753
3754 /**
3755  * Destroys a mode, and removes it from the list.
3756  */
3757 static void
3758 drm_output_destroy_mode(struct drm_backend *backend, struct drm_mode *mode)
3759 {
3760         if (mode->blob_id)
3761                 drmModeDestroyPropertyBlob(backend->drm.fd, mode->blob_id);
3762         wl_list_remove(&mode->base.link);
3763         free(mode);
3764 }
3765
3766 /** Destroy a list of drm_modes
3767  *
3768  * @param backend The backend for releasing mode property blobs.
3769  * @param mode_list The list linked by drm_mode::base.link.
3770  */
3771 static void
3772 drm_mode_list_destroy(struct drm_backend *backend, struct wl_list *mode_list)
3773 {
3774         struct drm_mode *mode, *next;
3775
3776         wl_list_for_each_safe(mode, next, mode_list, base.link)
3777                 drm_output_destroy_mode(backend, mode);
3778 }
3779
3780 static int
3781 drm_subpixel_to_wayland(int drm_value)
3782 {
3783         switch (drm_value) {
3784         default:
3785         case DRM_MODE_SUBPIXEL_UNKNOWN:
3786                 return WL_OUTPUT_SUBPIXEL_UNKNOWN;
3787         case DRM_MODE_SUBPIXEL_NONE:
3788                 return WL_OUTPUT_SUBPIXEL_NONE;
3789         case DRM_MODE_SUBPIXEL_HORIZONTAL_RGB:
3790                 return WL_OUTPUT_SUBPIXEL_HORIZONTAL_RGB;
3791         case DRM_MODE_SUBPIXEL_HORIZONTAL_BGR:
3792                 return WL_OUTPUT_SUBPIXEL_HORIZONTAL_BGR;
3793         case DRM_MODE_SUBPIXEL_VERTICAL_RGB:
3794                 return WL_OUTPUT_SUBPIXEL_VERTICAL_RGB;
3795         case DRM_MODE_SUBPIXEL_VERTICAL_BGR:
3796                 return WL_OUTPUT_SUBPIXEL_VERTICAL_BGR;
3797         }
3798 }
3799
3800 /* returns a value between 0-255 range, where higher is brighter */
3801 static uint32_t
3802 drm_get_backlight(struct drm_head *head)
3803 {
3804         long brightness, max_brightness, norm;
3805
3806         brightness = backlight_get_brightness(head->backlight);
3807         max_brightness = backlight_get_max_brightness(head->backlight);
3808
3809         /* convert it on a scale of 0 to 255 */
3810         norm = (brightness * 255)/(max_brightness);
3811
3812         return (uint32_t) norm;
3813 }
3814
3815 /* values accepted are between 0-255 range */
3816 static void
3817 drm_set_backlight(struct weston_output *output_base, uint32_t value)
3818 {
3819         struct drm_head *head = to_drm_head(weston_output_get_first_head(output_base));
3820         long max_brightness, new_brightness;
3821
3822         if (!head->backlight)
3823                 return;
3824
3825         if (value > 255)
3826                 return;
3827
3828         max_brightness = backlight_get_max_brightness(head->backlight);
3829
3830         /* get denormalized value */
3831         new_brightness = (value * max_brightness) / 255;
3832
3833         backlight_set_brightness(head->backlight, new_brightness);
3834 }
3835
3836 /**
3837  * Power output on or off
3838  *
3839  * The DPMS/power level of an output is used to switch it on or off. This
3840  * is DRM's hook for doing so, which can called either as part of repaint,
3841  * or independently of the repaint loop.
3842  *
3843  * If we are called as part of repaint, we simply set the relevant bit in
3844  * state and return.
3845  */
3846 static void
3847 drm_set_dpms(struct weston_output *output_base, enum dpms_enum level)
3848 {
3849         struct drm_output *output = to_drm_output(output_base);
3850         struct drm_backend *b = to_drm_backend(output_base->compositor);
3851         struct drm_pending_state *pending_state = b->repaint_data;
3852         struct drm_output_state *state;
3853         int ret;
3854
3855         if (output->state_cur->dpms == level)
3856                 return;
3857
3858         /* If we're being called during the repaint loop, then this is
3859          * simple: discard any previously-generated state, and create a new
3860          * state where we disable everything. When we come to flush, this
3861          * will be applied.
3862          *
3863          * However, we need to be careful: we can be called whilst another
3864          * output is in its repaint cycle (pending_state exists), but our
3865          * output still has an incomplete state application outstanding.
3866          * In that case, we need to wait until that completes. */
3867         if (pending_state && !output->state_last) {
3868                 /* The repaint loop already sets DPMS on; we don't need to
3869                  * explicitly set it on here, as it will already happen
3870                  * whilst applying the repaint state. */
3871                 if (level == WESTON_DPMS_ON)
3872                         return;
3873
3874                 state = drm_pending_state_get_output(pending_state, output);
3875                 if (state)
3876                         drm_output_state_free(state);
3877                 state = drm_output_get_disable_state(pending_state, output);
3878                 return;
3879         }
3880
3881         /* As we throw everything away when disabling, just send us back through
3882          * a repaint cycle. */
3883         if (level == WESTON_DPMS_ON) {
3884                 if (output->dpms_off_pending)
3885                         output->dpms_off_pending = 0;
3886                 weston_output_schedule_repaint(output_base);
3887                 return;
3888         }
3889
3890         /* If we've already got a request in the pipeline, then we need to
3891          * park our DPMS request until that request has quiesced. */
3892         if (output->state_last) {
3893                 output->dpms_off_pending = 1;
3894                 return;
3895         }
3896
3897         pending_state = drm_pending_state_alloc(b);
3898         drm_output_get_disable_state(pending_state, output);
3899         ret = drm_pending_state_apply_sync(pending_state);
3900         if (ret != 0)
3901                 weston_log("drm_set_dpms: couldn't disable output?\n");
3902 }
3903
3904 static const char * const connector_type_names[] = {
3905         [DRM_MODE_CONNECTOR_Unknown]     = "Unknown",
3906         [DRM_MODE_CONNECTOR_VGA]         = "VGA",
3907         [DRM_MODE_CONNECTOR_DVII]        = "DVI-I",
3908         [DRM_MODE_CONNECTOR_DVID]        = "DVI-D",
3909         [DRM_MODE_CONNECTOR_DVIA]        = "DVI-A",
3910         [DRM_MODE_CONNECTOR_Composite]   = "Composite",
3911         [DRM_MODE_CONNECTOR_SVIDEO]      = "SVIDEO",
3912         [DRM_MODE_CONNECTOR_LVDS]        = "LVDS",
3913         [DRM_MODE_CONNECTOR_Component]   = "Component",
3914         [DRM_MODE_CONNECTOR_9PinDIN]     = "DIN",
3915         [DRM_MODE_CONNECTOR_DisplayPort] = "DP",
3916         [DRM_MODE_CONNECTOR_HDMIA]       = "HDMI-A",
3917         [DRM_MODE_CONNECTOR_HDMIB]       = "HDMI-B",
3918         [DRM_MODE_CONNECTOR_TV]          = "TV",
3919         [DRM_MODE_CONNECTOR_eDP]         = "eDP",
3920 #ifdef DRM_MODE_CONNECTOR_DSI
3921         [DRM_MODE_CONNECTOR_VIRTUAL]     = "Virtual",
3922         [DRM_MODE_CONNECTOR_DSI]         = "DSI",
3923 #endif
3924 };
3925
3926 /** Create a name given a DRM connector
3927  *
3928  * \param con The DRM connector whose type and id form the name.
3929  * \return A newly allocate string, or NULL on error. Must be free()'d
3930  * after use.
3931  *
3932  * The name does not identify the DRM display device.
3933  */
3934 static char *
3935 make_connector_name(const drmModeConnector *con)
3936 {
3937         char *name;
3938         const char *type_name = NULL;
3939         int ret;
3940
3941         if (con->connector_type < ARRAY_LENGTH(connector_type_names))
3942                 type_name = connector_type_names[con->connector_type];
3943
3944         if (!type_name)
3945                 type_name = "UNNAMED";
3946
3947         ret = asprintf(&name, "%s-%d", type_name, con->connector_type_id);
3948         if (ret < 0)
3949                 return NULL;
3950
3951         return name;
3952 }
3953
3954 static int
3955 find_crtc_for_connector(struct drm_backend *b,
3956                         drmModeRes *resources, drmModeConnector *connector)
3957 {
3958         drmModeEncoder *encoder;
3959         int i, j;
3960         int ret = -1;
3961
3962         for (j = 0; j < connector->count_encoders; j++) {
3963                 uint32_t possible_crtcs, encoder_id, crtc_id;
3964
3965                 encoder = drmModeGetEncoder(b->drm.fd, connector->encoders[j]);
3966                 if (encoder == NULL) {
3967                         weston_log("Failed to get encoder.\n");
3968                         continue;
3969                 }
3970                 encoder_id = encoder->encoder_id;
3971                 possible_crtcs = encoder->possible_crtcs;
3972                 crtc_id = encoder->crtc_id;
3973                 drmModeFreeEncoder(encoder);
3974
3975                 for (i = 0; i < resources->count_crtcs; i++) {
3976                         if (!(possible_crtcs & (1 << i)))
3977                                 continue;
3978
3979                         if (drm_output_find_by_crtc(b, resources->crtcs[i]))
3980                                 continue;
3981
3982                         /* Try to preserve the existing
3983                          * CRTC -> encoder -> connector routing; it makes
3984                          * initialisation faster, and also since we have a
3985                          * very dumb picking algorithm, may preserve a better
3986                          * choice. */
3987                         if (!connector->encoder_id ||
3988                             (encoder_id == connector->encoder_id &&
3989                              crtc_id == resources->crtcs[i]))
3990                                 return i;
3991
3992                         ret = i;
3993                 }
3994         }
3995
3996         return ret;
3997 }
3998
3999 static void drm_output_fini_cursor_egl(struct drm_output *output)
4000 {
4001         unsigned int i;
4002
4003         for (i = 0; i < ARRAY_LENGTH(output->gbm_cursor_fb); i++) {
4004                 drm_fb_unref(output->gbm_cursor_fb[i]);
4005                 output->gbm_cursor_fb[i] = NULL;
4006         }
4007 }
4008
4009 static int
4010 drm_output_init_cursor_egl(struct drm_output *output, struct drm_backend *b)
4011 {
4012         unsigned int i;
4013
4014         /* No point creating cursors if we don't have a plane for them. */
4015         if (!output->cursor_plane)
4016                 return 0;
4017
4018         for (i = 0; i < ARRAY_LENGTH(output->gbm_cursor_fb); i++) {
4019                 struct gbm_bo *bo;
4020
4021                 bo = gbm_bo_create(b->gbm, b->cursor_width, b->cursor_height,
4022                                    GBM_FORMAT_ARGB8888,
4023                                    GBM_BO_USE_CURSOR | GBM_BO_USE_WRITE);
4024                 if (!bo)
4025                         goto err;
4026
4027                 output->gbm_cursor_fb[i] =
4028                         drm_fb_get_from_bo(bo, b, GBM_FORMAT_ARGB8888,
4029                                            BUFFER_CURSOR);
4030                 if (!output->gbm_cursor_fb[i]) {
4031                         gbm_bo_destroy(bo);
4032                         goto err;
4033                 }
4034         }
4035
4036         return 0;
4037
4038 err:
4039         weston_log("cursor buffers unavailable, using gl cursors\n");
4040         b->cursors_are_broken = 1;
4041         drm_output_fini_cursor_egl(output);
4042         return -1;
4043 }
4044
4045 /* Init output state that depends on gl or gbm */
4046 static int
4047 drm_output_init_egl(struct drm_output *output, struct drm_backend *b)
4048 {
4049         EGLint format[2] = {
4050                 output->gbm_format,
4051                 fallback_format_for(output->gbm_format),
4052         };
4053         int n_formats = 1;
4054
4055         output->gbm_surface = gbm_surface_create(b->gbm,
4056                                              output->base.current_mode->width,
4057                                              output->base.current_mode->height,
4058                                              format[0],
4059                                              GBM_BO_USE_SCANOUT |
4060                                              GBM_BO_USE_RENDERING);
4061         if (!output->gbm_surface) {
4062                 weston_log("failed to create gbm surface\n");
4063                 return -1;
4064         }
4065
4066         if (format[1])
4067                 n_formats = 2;
4068         if (gl_renderer->output_window_create(&output->base,
4069                                               (EGLNativeWindowType)output->gbm_surface,
4070                                               output->gbm_surface,
4071                                               gl_renderer->opaque_attribs,
4072                                               format,
4073                                               n_formats) < 0) {
4074                 weston_log("failed to create gl renderer output state\n");
4075                 gbm_surface_destroy(output->gbm_surface);
4076                 return -1;
4077         }
4078
4079         drm_output_init_cursor_egl(output, b);
4080
4081         return 0;
4082 }
4083
4084 static void
4085 drm_output_fini_egl(struct drm_output *output)
4086 {
4087         struct drm_backend *b = to_drm_backend(output->base.compositor);
4088
4089         /* Destroying the GBM surface will destroy all our GBM buffers,
4090          * regardless of refcount. Ensure we destroy them here. */
4091         if (!b->shutting_down &&
4092             output->scanout_plane->state_cur->fb &&
4093             output->scanout_plane->state_cur->fb->type == BUFFER_GBM_SURFACE) {
4094                 drm_plane_state_free(output->scanout_plane->state_cur, true);
4095                 output->scanout_plane->state_cur =
4096                         drm_plane_state_alloc(NULL, output->scanout_plane);
4097                 output->scanout_plane->state_cur->complete = true;
4098         }
4099
4100         gl_renderer->output_destroy(&output->base);
4101         gbm_surface_destroy(output->gbm_surface);
4102         drm_output_fini_cursor_egl(output);
4103 }
4104
4105 static int
4106 drm_output_init_pixman(struct drm_output *output, struct drm_backend *b)
4107 {
4108         int w = output->base.current_mode->width;
4109         int h = output->base.current_mode->height;
4110         uint32_t format = output->gbm_format;
4111         uint32_t pixman_format;
4112         unsigned int i;
4113
4114         switch (format) {
4115                 case GBM_FORMAT_XRGB8888:
4116                         pixman_format = PIXMAN_x8r8g8b8;
4117                         break;
4118                 case GBM_FORMAT_RGB565:
4119                         pixman_format = PIXMAN_r5g6b5;
4120                         break;
4121                 default:
4122                         weston_log("Unsupported pixman format 0x%x\n", format);
4123                         return -1;
4124         }
4125
4126         /* FIXME error checking */
4127         for (i = 0; i < ARRAY_LENGTH(output->dumb); i++) {
4128                 output->dumb[i] = drm_fb_create_dumb(b, w, h, format);
4129                 if (!output->dumb[i])
4130                         goto err;
4131
4132                 output->image[i] =
4133                         pixman_image_create_bits(pixman_format, w, h,
4134                                                  output->dumb[i]->map,
4135                                                  output->dumb[i]->stride);
4136                 if (!output->image[i])
4137                         goto err;
4138         }
4139
4140         if (pixman_renderer_output_create(&output->base) < 0)
4141                 goto err;
4142
4143         pixman_region32_init_rect(&output->previous_damage,
4144                                   output->base.x, output->base.y, output->base.width, output->base.height);
4145
4146         return 0;
4147
4148 err:
4149         for (i = 0; i < ARRAY_LENGTH(output->dumb); i++) {
4150                 if (output->dumb[i])
4151                         drm_fb_unref(output->dumb[i]);
4152                 if (output->image[i])
4153                         pixman_image_unref(output->image[i]);
4154
4155                 output->dumb[i] = NULL;
4156                 output->image[i] = NULL;
4157         }
4158
4159         return -1;
4160 }
4161
4162 static void
4163 drm_output_fini_pixman(struct drm_output *output)
4164 {
4165         struct drm_backend *b = to_drm_backend(output->base.compositor);
4166         unsigned int i;
4167
4168         /* Destroying the Pixman surface will destroy all our buffers,
4169          * regardless of refcount. Ensure we destroy them here. */
4170         if (!b->shutting_down &&
4171             output->scanout_plane->state_cur->fb &&
4172             output->scanout_plane->state_cur->fb->type == BUFFER_PIXMAN_DUMB) {
4173                 drm_plane_state_free(output->scanout_plane->state_cur, true);
4174                 output->scanout_plane->state_cur =
4175                         drm_plane_state_alloc(NULL, output->scanout_plane);
4176                 output->scanout_plane->state_cur->complete = true;
4177         }
4178
4179         pixman_renderer_output_destroy(&output->base);
4180         pixman_region32_fini(&output->previous_damage);
4181
4182         for (i = 0; i < ARRAY_LENGTH(output->dumb); i++) {
4183                 pixman_image_unref(output->image[i]);
4184                 drm_fb_unref(output->dumb[i]);
4185                 output->dumb[i] = NULL;
4186                 output->image[i] = NULL;
4187         }
4188 }
4189
4190 static void
4191 edid_parse_string(const uint8_t *data, char text[])
4192 {
4193         int i;
4194         int replaced = 0;
4195
4196         /* this is always 12 bytes, but we can't guarantee it's null
4197          * terminated or not junk. */
4198         strncpy(text, (const char *) data, 12);
4199
4200         /* guarantee our new string is null-terminated */
4201         text[12] = '\0';
4202
4203         /* remove insane chars */
4204         for (i = 0; text[i] != '\0'; i++) {
4205                 if (text[i] == '\n' ||
4206                     text[i] == '\r') {
4207                         text[i] = '\0';
4208                         break;
4209                 }
4210         }
4211
4212         /* ensure string is printable */
4213         for (i = 0; text[i] != '\0'; i++) {
4214                 if (!isprint(text[i])) {
4215                         text[i] = '-';
4216                         replaced++;
4217                 }
4218         }
4219
4220         /* if the string is random junk, ignore the string */
4221         if (replaced > 4)
4222                 text[0] = '\0';
4223 }
4224
4225 #define EDID_DESCRIPTOR_ALPHANUMERIC_DATA_STRING        0xfe
4226 #define EDID_DESCRIPTOR_DISPLAY_PRODUCT_NAME            0xfc
4227 #define EDID_DESCRIPTOR_DISPLAY_PRODUCT_SERIAL_NUMBER   0xff
4228 #define EDID_OFFSET_DATA_BLOCKS                         0x36
4229 #define EDID_OFFSET_LAST_BLOCK                          0x6c
4230 #define EDID_OFFSET_PNPID                               0x08
4231 #define EDID_OFFSET_SERIAL                              0x0c
4232
4233 static int
4234 edid_parse(struct drm_edid *edid, const uint8_t *data, size_t length)
4235 {
4236         int i;
4237         uint32_t serial_number;
4238
4239         /* check header */
4240         if (length < 128)
4241                 return -1;
4242         if (data[0] != 0x00 || data[1] != 0xff)
4243                 return -1;
4244
4245         /* decode the PNP ID from three 5 bit words packed into 2 bytes
4246          * /--08--\/--09--\
4247          * 7654321076543210
4248          * |\---/\---/\---/
4249          * R  C1   C2   C3 */
4250         edid->pnp_id[0] = 'A' + ((data[EDID_OFFSET_PNPID + 0] & 0x7c) / 4) - 1;
4251         edid->pnp_id[1] = 'A' + ((data[EDID_OFFSET_PNPID + 0] & 0x3) * 8) + ((data[EDID_OFFSET_PNPID + 1] & 0xe0) / 32) - 1;
4252         edid->pnp_id[2] = 'A' + (data[EDID_OFFSET_PNPID + 1] & 0x1f) - 1;
4253         edid->pnp_id[3] = '\0';
4254
4255         /* maybe there isn't a ASCII serial number descriptor, so use this instead */
4256         serial_number = (uint32_t) data[EDID_OFFSET_SERIAL + 0];
4257         serial_number += (uint32_t) data[EDID_OFFSET_SERIAL + 1] * 0x100;
4258         serial_number += (uint32_t) data[EDID_OFFSET_SERIAL + 2] * 0x10000;
4259         serial_number += (uint32_t) data[EDID_OFFSET_SERIAL + 3] * 0x1000000;
4260         if (serial_number > 0)
4261                 sprintf(edid->serial_number, "%lu", (unsigned long) serial_number);
4262
4263         /* parse EDID data */
4264         for (i = EDID_OFFSET_DATA_BLOCKS;
4265              i <= EDID_OFFSET_LAST_BLOCK;
4266              i += 18) {
4267                 /* ignore pixel clock data */
4268                 if (data[i] != 0)
4269                         continue;
4270                 if (data[i+2] != 0)
4271                         continue;
4272
4273                 /* any useful blocks? */
4274                 if (data[i+3] == EDID_DESCRIPTOR_DISPLAY_PRODUCT_NAME) {
4275                         edid_parse_string(&data[i+5],
4276                                           edid->monitor_name);
4277                 } else if (data[i+3] == EDID_DESCRIPTOR_DISPLAY_PRODUCT_SERIAL_NUMBER) {
4278                         edid_parse_string(&data[i+5],
4279                                           edid->serial_number);
4280                 } else if (data[i+3] == EDID_DESCRIPTOR_ALPHANUMERIC_DATA_STRING) {
4281                         edid_parse_string(&data[i+5],
4282                                           edid->eisa_id);
4283                 }
4284         }
4285         return 0;
4286 }
4287
4288 /** Parse monitor make, model and serial from EDID
4289  *
4290  * \param head The head whose \c drm_edid to fill in.
4291  * \param props The DRM connector properties to get the EDID from.
4292  * \param make[out] The monitor make (PNP ID).
4293  * \param model[out] The monitor model (name).
4294  * \param serial_number[out] The monitor serial number.
4295  *
4296  * Each of \c *make, \c *model and \c *serial_number are set only if the
4297  * information is found in the EDID. The pointers they are set to must not
4298  * be free()'d explicitly, instead they get implicitly freed when the
4299  * \c drm_head is destroyed.
4300  */
4301 static void
4302 find_and_parse_output_edid(struct drm_head *head,
4303                            drmModeObjectPropertiesPtr props,
4304                            const char **make,
4305                            const char **model,
4306                            const char **serial_number)
4307 {
4308         drmModePropertyBlobPtr edid_blob = NULL;
4309         uint32_t blob_id;
4310         int rc;
4311
4312         blob_id =
4313                 drm_property_get_value(&head->props_conn[WDRM_CONNECTOR_EDID],
4314                                        props, 0);
4315         if (!blob_id)
4316                 return;
4317
4318         edid_blob = drmModeGetPropertyBlob(head->backend->drm.fd, blob_id);
4319         if (!edid_blob)
4320                 return;
4321
4322         rc = edid_parse(&head->edid,
4323                         edid_blob->data,
4324                         edid_blob->length);
4325         if (!rc) {
4326                 weston_log("EDID data '%s', '%s', '%s'\n",
4327                            head->edid.pnp_id,
4328                            head->edid.monitor_name,
4329                            head->edid.serial_number);
4330                 if (head->edid.pnp_id[0] != '\0')
4331                         *make = head->edid.pnp_id;
4332                 if (head->edid.monitor_name[0] != '\0')
4333                         *model = head->edid.monitor_name;
4334                 if (head->edid.serial_number[0] != '\0')
4335                         *serial_number = head->edid.serial_number;
4336         }
4337         drmModeFreePropertyBlob(edid_blob);
4338 }
4339
4340 static int
4341 parse_modeline(const char *s, drmModeModeInfo *mode)
4342 {
4343         char hsync[16];
4344         char vsync[16];
4345         float fclock;
4346
4347         memset(mode, 0, sizeof *mode);
4348
4349         mode->type = DRM_MODE_TYPE_USERDEF;
4350         mode->hskew = 0;
4351         mode->vscan = 0;
4352         mode->vrefresh = 0;
4353         mode->flags = 0;
4354
4355         if (sscanf(s, "%f %hd %hd %hd %hd %hd %hd %hd %hd %15s %15s",
4356                    &fclock,
4357                    &mode->hdisplay,
4358                    &mode->hsync_start,
4359                    &mode->hsync_end,
4360                    &mode->htotal,
4361                    &mode->vdisplay,
4362                    &mode->vsync_start,
4363                    &mode->vsync_end,
4364                    &mode->vtotal, hsync, vsync) != 11)
4365                 return -1;
4366
4367         mode->clock = fclock * 1000;
4368         if (strcmp(hsync, "+hsync") == 0)
4369                 mode->flags |= DRM_MODE_FLAG_PHSYNC;
4370         else if (strcmp(hsync, "-hsync") == 0)
4371                 mode->flags |= DRM_MODE_FLAG_NHSYNC;
4372         else
4373                 return -1;
4374
4375         if (strcmp(vsync, "+vsync") == 0)
4376                 mode->flags |= DRM_MODE_FLAG_PVSYNC;
4377         else if (strcmp(vsync, "-vsync") == 0)
4378                 mode->flags |= DRM_MODE_FLAG_NVSYNC;
4379         else
4380                 return -1;
4381
4382         snprintf(mode->name, sizeof mode->name, "%dx%d@%.3f",
4383                  mode->hdisplay, mode->vdisplay, fclock);
4384
4385         return 0;
4386 }
4387
4388 static void
4389 setup_output_seat_constraint(struct drm_backend *b,
4390                              struct weston_output *output,
4391                              const char *s)
4392 {
4393         if (strcmp(s, "") != 0) {
4394                 struct weston_pointer *pointer;
4395                 struct udev_seat *seat;
4396
4397                 seat = udev_seat_get_named(&b->input, s);
4398                 if (!seat)
4399                         return;
4400
4401                 seat->base.output = output;
4402
4403                 pointer = weston_seat_get_pointer(&seat->base);
4404                 if (pointer)
4405                         weston_pointer_clamp(pointer,
4406                                              &pointer->x,
4407                                              &pointer->y);
4408         }
4409 }
4410
4411 static int
4412 drm_output_attach_head(struct weston_output *output_base,
4413                        struct weston_head *head_base)
4414 {
4415         if (wl_list_length(&output_base->head_list) >= MAX_CLONED_CONNECTORS)
4416                 return -1;
4417
4418         return 0;
4419 }
4420
4421 static int
4422 parse_gbm_format(const char *s, uint32_t default_value, uint32_t *gbm_format)
4423 {
4424         int ret = 0;
4425
4426         if (s == NULL)
4427                 *gbm_format = default_value;
4428         else if (strcmp(s, "xrgb8888") == 0)
4429                 *gbm_format = GBM_FORMAT_XRGB8888;
4430         else if (strcmp(s, "rgb565") == 0)
4431                 *gbm_format = GBM_FORMAT_RGB565;
4432         else if (strcmp(s, "xrgb2101010") == 0)
4433                 *gbm_format = GBM_FORMAT_XRGB2101010;
4434         else {
4435                 weston_log("fatal: unrecognized pixel format: %s\n", s);
4436                 ret = -1;
4437         }
4438
4439         return ret;
4440 }
4441
4442 /** Rewrite the output's mode list
4443  *
4444  * @param output The output.
4445  * @return 0 on success, -1 on failure.
4446  *
4447  * Destroy all existing modes in the list, and reconstruct a new list from
4448  * scratch, based on the currently attached heads.
4449  *
4450  * On failure the output's mode list may contain some modes.
4451  */
4452 static int
4453 drm_output_update_modelist_from_heads(struct drm_output *output)
4454 {
4455         struct drm_backend *backend = to_drm_backend(output->base.compositor);
4456         struct weston_head *head_base;
4457         struct drm_head *head;
4458         struct drm_mode *mode;
4459         int i;
4460
4461         assert(!output->base.enabled);
4462
4463         drm_mode_list_destroy(backend, &output->base.mode_list);
4464
4465         /* XXX: needs a strategy for combining mode lists from multiple heads */
4466         head_base = weston_output_get_first_head(&output->base);
4467         assert(head_base);
4468         head = to_drm_head(head_base);
4469
4470         for (i = 0; i < head->connector->count_modes; i++) {
4471                 mode = drm_output_add_mode(output, &head->connector->modes[i]);
4472                 if (!mode)
4473                         return -1;
4474         }
4475
4476         return 0;
4477 }
4478
4479 /**
4480  * Choose suitable mode for an output
4481  *
4482  * Find the most suitable mode to use for initial setup (or reconfiguration on
4483  * hotplug etc) for a DRM output.
4484  *
4485  * @param output DRM output to choose mode for
4486  * @param kind Strategy and preference to use when choosing mode
4487  * @param width Desired width for this output
4488  * @param height Desired height for this output
4489  * @param current_mode Mode currently being displayed on this output
4490  * @param modeline Manually-entered mode (may be NULL)
4491  * @returns A mode from the output's mode list, or NULL if none available
4492  */
4493 static struct drm_mode *
4494 drm_output_choose_initial_mode(struct drm_backend *backend,
4495                                struct drm_output *output,
4496                                enum weston_drm_backend_output_mode mode,
4497                                const char *modeline,
4498                                const drmModeModeInfo *current_mode)
4499 {
4500         struct drm_mode *preferred = NULL;
4501         struct drm_mode *current = NULL;
4502         struct drm_mode *configured = NULL;
4503         struct drm_mode *best = NULL;
4504         struct drm_mode *drm_mode;
4505         drmModeModeInfo drm_modeline;
4506         int32_t width = 0;
4507         int32_t height = 0;
4508         uint32_t refresh = 0;
4509         int n;
4510
4511         if (mode == WESTON_DRM_BACKEND_OUTPUT_PREFERRED && modeline) {
4512                 n = sscanf(modeline, "%dx%d@%d", &width, &height, &refresh);
4513                 if (n != 2 && n != 3) {
4514                         width = -1;
4515
4516                         if (parse_modeline(modeline, &drm_modeline) == 0) {
4517                                 configured = drm_output_add_mode(output, &drm_modeline);
4518                                 if (!configured)
4519                                         return NULL;
4520                         } else {
4521                                 weston_log("Invalid modeline \"%s\" for output %s\n",
4522                                            modeline, output->base.name);
4523                         }
4524                 }
4525         }
4526
4527         wl_list_for_each_reverse(drm_mode, &output->base.mode_list, base.link) {
4528                 if (width == drm_mode->base.width &&
4529                     height == drm_mode->base.height &&
4530                     (refresh == 0 || refresh == drm_mode->mode_info.vrefresh))
4531                         configured = drm_mode;
4532
4533                 if (memcmp(current_mode, &drm_mode->mode_info,
4534                            sizeof *current_mode) == 0)
4535                         current = drm_mode;
4536
4537                 if (drm_mode->base.flags & WL_OUTPUT_MODE_PREFERRED)
4538                         preferred = drm_mode;
4539
4540                 best = drm_mode;
4541         }
4542
4543         if (current == NULL && current_mode->clock != 0) {
4544                 current = drm_output_add_mode(output, current_mode);
4545                 if (!current)
4546                         return NULL;
4547         }
4548
4549         if (mode == WESTON_DRM_BACKEND_OUTPUT_CURRENT)
4550                 configured = current;
4551
4552         if (configured)
4553                 return configured;
4554
4555         if (preferred)
4556                 return preferred;
4557
4558         if (current)
4559                 return current;
4560
4561         if (best)
4562                 return best;
4563
4564         weston_log("no available modes for %s\n", output->base.name);
4565         return NULL;
4566 }
4567
4568 static int
4569 connector_get_current_mode(drmModeConnector *connector, int drm_fd,
4570                            drmModeModeInfo *mode)
4571 {
4572         drmModeEncoder *encoder;
4573         drmModeCrtc *crtc;
4574
4575         /* Get the current mode on the crtc that's currently driving
4576          * this connector. */
4577         encoder = drmModeGetEncoder(drm_fd, connector->encoder_id);
4578         memset(mode, 0, sizeof *mode);
4579         if (encoder != NULL) {
4580                 crtc = drmModeGetCrtc(drm_fd, encoder->crtc_id);
4581                 drmModeFreeEncoder(encoder);
4582                 if (crtc == NULL)
4583                         return -1;
4584                 if (crtc->mode_valid)
4585                         *mode = crtc->mode;
4586                 drmModeFreeCrtc(crtc);
4587         }
4588
4589         return 0;
4590 }
4591
4592 static int
4593 drm_output_set_mode(struct weston_output *base,
4594                     enum weston_drm_backend_output_mode mode,
4595                     const char *modeline)
4596 {
4597         struct drm_output *output = to_drm_output(base);
4598         struct drm_backend *b = to_drm_backend(base->compositor);
4599         struct drm_head *head = to_drm_head(weston_output_get_first_head(base));
4600
4601         struct drm_mode *current;
4602
4603         if (drm_output_update_modelist_from_heads(output) < 0)
4604                 return -1;
4605
4606         current = drm_output_choose_initial_mode(b, output, mode, modeline,
4607                                                  &head->inherited_mode);
4608         if (!current)
4609                 return -1;
4610
4611         output->base.current_mode = &current->base;
4612         output->base.current_mode->flags |= WL_OUTPUT_MODE_CURRENT;
4613
4614         /* Set native_ fields, so weston_output_mode_switch_to_native() works */
4615         output->base.native_mode = output->base.current_mode;
4616         output->base.native_scale = output->base.current_scale;
4617
4618         return 0;
4619 }
4620
4621 static void
4622 drm_output_set_gbm_format(struct weston_output *base,
4623                           const char *gbm_format)
4624 {
4625         struct drm_output *output = to_drm_output(base);
4626         struct drm_backend *b = to_drm_backend(base->compositor);
4627
4628         if (parse_gbm_format(gbm_format, b->gbm_format, &output->gbm_format) == -1)
4629                 output->gbm_format = b->gbm_format;
4630
4631         /* Without universal planes, we can't discover which formats are
4632          * supported by the primary plane; we just hope that the GBM format
4633          * works. */
4634         if (!b->universal_planes)
4635                 output->scanout_plane->formats[0] = output->gbm_format;
4636 }
4637
4638 static void
4639 drm_output_set_seat(struct weston_output *base,
4640                     const char *seat)
4641 {
4642         struct drm_output *output = to_drm_output(base);
4643         struct drm_backend *b = to_drm_backend(base->compositor);
4644
4645         setup_output_seat_constraint(b, &output->base,
4646                                      seat ? seat : "");
4647 }
4648
4649 static int
4650 drm_output_init_gamma_size(struct drm_output *output)
4651 {
4652         struct drm_backend *backend = to_drm_backend(output->base.compositor);
4653         drmModeCrtc *crtc;
4654
4655         assert(output->base.compositor);
4656         assert(output->crtc_id != 0);
4657         crtc = drmModeGetCrtc(backend->drm.fd, output->crtc_id);
4658         if (!crtc)
4659                 return -1;
4660
4661         output->base.gamma_size = crtc->gamma_size;
4662
4663         drmModeFreeCrtc(crtc);
4664
4665         return 0;
4666 }
4667
4668 /** Allocate a CRTC for the output
4669  *
4670  * @param output The output with no allocated CRTC.
4671  * @param resources DRM KMS resources.
4672  * @param connector The DRM KMS connector data.
4673  * @return 0 on success, -1 on failure.
4674  *
4675  * Finds a free CRTC that can drive the given connector, reserves the CRTC
4676  * for the output, and loads the CRTC properties.
4677  *
4678  * Populates the cursor and scanout planes.
4679  *
4680  * On failure, the output remains without a CRTC.
4681  */
4682 static int
4683 drm_output_init_crtc(struct drm_output *output,
4684                      drmModeRes *resources, drmModeConnector *connector)
4685 {
4686         struct drm_backend *b = to_drm_backend(output->base.compositor);
4687         drmModeObjectPropertiesPtr props;
4688         int i;
4689
4690         assert(output->crtc_id == 0);
4691
4692         i = find_crtc_for_connector(b, resources, connector);
4693         if (i < 0) {
4694                 weston_log("No usable crtc/encoder pair for connector.\n");
4695                 return -1;
4696         }
4697
4698         output->crtc_id = resources->crtcs[i];
4699         output->pipe = i;
4700
4701         props = drmModeObjectGetProperties(b->drm.fd, output->crtc_id,
4702                                            DRM_MODE_OBJECT_CRTC);
4703         if (!props) {
4704                 weston_log("failed to get CRTC properties\n");
4705                 goto err_crtc;
4706         }
4707         drm_property_info_populate(b, crtc_props, output->props_crtc,
4708                                    WDRM_CRTC__COUNT, props);
4709         drmModeFreeObjectProperties(props);
4710
4711         output->scanout_plane =
4712                 drm_output_find_special_plane(b, output,
4713                                               WDRM_PLANE_TYPE_PRIMARY);
4714         if (!output->scanout_plane) {
4715                 weston_log("Failed to find primary plane for output %s\n",
4716                            output->base.name);
4717                 goto err_crtc;
4718         }
4719
4720         /* Failing to find a cursor plane is not fatal, as we'll fall back
4721          * to software cursor. */
4722         output->cursor_plane =
4723                 drm_output_find_special_plane(b, output,
4724                                               WDRM_PLANE_TYPE_CURSOR);
4725
4726         wl_array_remove_uint32(&b->unused_crtcs, output->crtc_id);
4727
4728         return 0;
4729
4730 err_crtc:
4731         output->crtc_id = 0;
4732         output->pipe = 0;
4733
4734         return -1;
4735 }
4736
4737 /** Free the CRTC from the output
4738  *
4739  * @param output The output whose CRTC to deallocate.
4740  *
4741  * The CRTC reserved for the given output becomes free to use again.
4742  */
4743 static void
4744 drm_output_fini_crtc(struct drm_output *output)
4745 {
4746         struct drm_backend *b = to_drm_backend(output->base.compositor);
4747         uint32_t *unused;
4748
4749         if (!b->universal_planes && !b->shutting_down) {
4750                 /* With universal planes, the 'special' planes are allocated at
4751                  * startup, freed at shutdown, and live on the plane list in
4752                  * between. We want the planes to continue to exist and be freed
4753                  * up for other outputs.
4754                  *
4755                  * Without universal planes, our special planes are
4756                  * pseudo-planes allocated at output creation, freed at output
4757                  * destruction, and not usable by other outputs.
4758                  *
4759                  * On the other hand, if the compositor is already shutting down,
4760                  * the plane has already been destroyed.
4761                  */
4762                 if (output->cursor_plane)
4763                         drm_plane_destroy(output->cursor_plane);
4764                 if (output->scanout_plane)
4765                         drm_plane_destroy(output->scanout_plane);
4766         }
4767
4768         drm_property_info_free(output->props_crtc, WDRM_CRTC__COUNT);
4769
4770         assert(output->crtc_id != 0);
4771
4772         unused = wl_array_add(&b->unused_crtcs, sizeof(*unused));
4773         *unused = output->crtc_id;
4774
4775         /* Force resetting unused CRTCs */
4776         b->state_invalid = true;
4777
4778         output->crtc_id = 0;
4779         output->cursor_plane = NULL;
4780         output->scanout_plane = NULL;
4781 }
4782
4783 static int
4784 drm_output_enable(struct weston_output *base)
4785 {
4786         struct drm_output *output = to_drm_output(base);
4787         struct drm_backend *b = to_drm_backend(base->compositor);
4788         struct drm_head *head = to_drm_head(weston_output_get_first_head(base));
4789         struct weston_mode *m;
4790         drmModeRes *resources;
4791         int ret;
4792
4793         resources = drmModeGetResources(b->drm.fd);
4794         if (!resources) {
4795                 weston_log("drmModeGetResources failed\n");
4796                 return -1;
4797         }
4798         ret = drm_output_init_crtc(output, resources, head->connector);
4799         drmModeFreeResources(resources);
4800         if (ret < 0)
4801                 return -1;
4802
4803         if (drm_output_init_gamma_size(output) < 0)
4804                 goto err;
4805
4806         if (b->pageflip_timeout)
4807                 drm_output_pageflip_timer_create(output);
4808
4809         if (b->use_pixman) {
4810                 if (drm_output_init_pixman(output, b) < 0) {
4811                         weston_log("Failed to init output pixman state\n");
4812                         goto err;
4813                 }
4814         } else if (drm_output_init_egl(output, b) < 0) {
4815                 weston_log("Failed to init output gl state\n");
4816                 goto err;
4817         }
4818
4819         if (head->backlight) {
4820                 weston_log("Initialized backlight, device %s\n",
4821                            head->backlight->path);
4822                 output->base.set_backlight = drm_set_backlight;
4823                 output->base.backlight_current = drm_get_backlight(head);
4824         } else {
4825                 weston_log("Failed to initialize backlight\n");
4826         }
4827
4828         output->base.start_repaint_loop = drm_output_start_repaint_loop;
4829         output->base.repaint = drm_output_repaint;
4830         output->base.assign_planes = drm_assign_planes;
4831         output->base.set_dpms = drm_set_dpms;
4832         output->base.switch_mode = drm_output_switch_mode;
4833         output->base.set_gamma = drm_output_set_gamma;
4834
4835         if (output->cursor_plane)
4836                 weston_compositor_stack_plane(b->compositor,
4837                                               &output->cursor_plane->base,
4838                                               NULL);
4839         else
4840                 b->cursors_are_broken = 1;
4841
4842         weston_compositor_stack_plane(b->compositor,
4843                                       &output->scanout_plane->base,
4844                                       &b->compositor->primary_plane);
4845
4846         wl_array_remove_uint32(&b->unused_connectors, head->connector_id);
4847
4848         weston_log("Output %s, (connector %d, crtc %d)\n",
4849                    output->base.name, head->connector_id, output->crtc_id);
4850         wl_list_for_each(m, &output->base.mode_list, link)
4851                 weston_log_continue(STAMP_SPACE "mode %dx%d@%.1f%s%s%s\n",
4852                                     m->width, m->height, m->refresh / 1000.0,
4853                                     m->flags & WL_OUTPUT_MODE_PREFERRED ?
4854                                     ", preferred" : "",
4855                                     m->flags & WL_OUTPUT_MODE_CURRENT ?
4856                                     ", current" : "",
4857                                     head->connector->count_modes == 0 ?
4858                                     ", built-in" : "");
4859
4860         return 0;
4861
4862 err:
4863         drm_output_fini_crtc(output);
4864
4865         return -1;
4866 }
4867
4868 static void
4869 drm_output_deinit(struct weston_output *base)
4870 {
4871         struct drm_output *output = to_drm_output(base);
4872         struct drm_head *head = to_drm_head(weston_output_get_first_head(base));
4873         struct drm_backend *b = to_drm_backend(base->compositor);
4874         uint32_t *unused;
4875
4876         if (b->use_pixman)
4877                 drm_output_fini_pixman(output);
4878         else
4879                 drm_output_fini_egl(output);
4880
4881         /* Since our planes are no longer in use anywhere, remove their base
4882          * weston_plane's link from the plane stacking list, unless we're
4883          * shutting down, in which case the plane has already been
4884          * destroyed. */
4885         if (!b->shutting_down) {
4886                 wl_list_remove(&output->scanout_plane->base.link);
4887                 wl_list_init(&output->scanout_plane->base.link);
4888
4889                 if (output->cursor_plane) {
4890                         wl_list_remove(&output->cursor_plane->base.link);
4891                         wl_list_init(&output->cursor_plane->base.link);
4892                         /* Turn off hardware cursor */
4893                         drmModeSetCursor(b->drm.fd, output->crtc_id, 0, 0, 0);
4894                 }
4895         }
4896
4897         unused = wl_array_add(&b->unused_connectors, sizeof(*unused));
4898         *unused = head->connector_id;
4899
4900         drm_output_fini_crtc(output);
4901 }
4902
4903 static void
4904 drm_head_destroy(struct drm_head *head);
4905
4906 static void
4907 drm_output_destroy(struct weston_output *base)
4908 {
4909         struct drm_output *output = to_drm_output(base);
4910         struct drm_backend *b = to_drm_backend(base->compositor);
4911         struct weston_head *head = weston_output_get_first_head(base);
4912
4913         if (output->page_flip_pending || output->vblank_pending ||
4914             output->atomic_complete_pending) {
4915                 output->destroy_pending = 1;
4916                 weston_log("destroy output while page flip pending\n");
4917                 return;
4918         }
4919
4920         if (output->base.enabled)
4921                 drm_output_deinit(&output->base);
4922
4923         drm_mode_list_destroy(b, &output->base.mode_list);
4924
4925         if (output->pageflip_timer)
4926                 wl_event_source_remove(output->pageflip_timer);
4927
4928         weston_output_release(&output->base);
4929
4930         assert(!output->state_last);
4931         drm_output_state_free(output->state_cur);
4932
4933         free(output);
4934
4935         /* XXX: temporary */
4936         if (head)
4937                 drm_head_destroy(to_drm_head(head));
4938 }
4939
4940 static int
4941 drm_output_disable(struct weston_output *base)
4942 {
4943         struct drm_output *output = to_drm_output(base);
4944
4945         if (output->page_flip_pending || output->vblank_pending ||
4946             output->atomic_complete_pending) {
4947                 output->disable_pending = 1;
4948                 return -1;
4949         }
4950
4951         weston_log("Disabling output %s\n", output->base.name);
4952
4953         if (output->base.enabled)
4954                 drm_output_deinit(&output->base);
4955
4956         output->disable_pending = 0;
4957
4958         return 0;
4959 }
4960
4961 static struct weston_output *
4962 drm_output_create(struct weston_compositor *compositor, const char *name)
4963 {
4964         struct drm_head *head;
4965
4966         /* XXX: Temporary until we can have heads without an output */
4967         wl_list_for_each(head, &compositor->head_list, base.compositor_link)
4968                 if (strcmp(name, head->base.name) == 0)
4969                         return &head->output->base;
4970
4971         return NULL;
4972 }
4973
4974 /**
4975  * Update the list of unused connectors and CRTCs
4976  *
4977  * This keeps the unused_connectors and unused_crtcs arrays up to date.
4978  *
4979  * @param b Weston backend structure
4980  * @param resources DRM resources for this device
4981  */
4982 static void
4983 drm_backend_update_unused_outputs(struct drm_backend *b, drmModeRes *resources)
4984 {
4985         int i;
4986
4987         wl_array_release(&b->unused_connectors);
4988         wl_array_init(&b->unused_connectors);
4989
4990         for (i = 0; i < resources->count_connectors; i++) {
4991                 struct drm_head *head;
4992                 uint32_t *connector_id;
4993
4994                 head = drm_head_find_by_connector(b, resources->connectors[i]);
4995                 if (head && weston_head_is_enabled(&head->base))
4996                         continue;
4997
4998                 connector_id = wl_array_add(&b->unused_connectors,
4999                                             sizeof(*connector_id));
5000                 *connector_id = resources->connectors[i];
5001         }
5002
5003         wl_array_release(&b->unused_crtcs);
5004         wl_array_init(&b->unused_crtcs);
5005
5006         for (i = 0; i < resources->count_crtcs; i++) {
5007                 struct drm_output *output;
5008                 uint32_t *crtc_id;
5009
5010                 output = drm_output_find_by_crtc(b, resources->crtcs[i]);
5011                 if (output && output->base.enabled)
5012                         continue;
5013
5014                 crtc_id = wl_array_add(&b->unused_crtcs, sizeof(*crtc_id));
5015                 *crtc_id = resources->crtcs[i];
5016         }
5017 }
5018
5019 /** Replace connector data and monitor information
5020  *
5021  * @param head The head to update.
5022  * @param connector The connector data to be owned by the head, must match
5023  * the head's connector ID.
5024  * @return 0 on success, -1 on failure.
5025  *
5026  * Takes ownership of @c connector on success, not on failure.
5027  *
5028  * May schedule a heads changed call.
5029  */
5030 static int
5031 drm_head_assign_connector_info(struct drm_head *head,
5032                                drmModeConnector *connector)
5033 {
5034         drmModeObjectProperties *props;
5035         const char *make = "unknown";
5036         const char *model = "unknown";
5037         const char *serial_number = "unknown";
5038
5039         assert(connector);
5040         assert(head->connector_id == connector->connector_id);
5041
5042         props = drmModeObjectGetProperties(head->backend->drm.fd,
5043                                            head->connector_id,
5044                                            DRM_MODE_OBJECT_CONNECTOR);
5045         if (!props) {
5046                 weston_log("Error: failed to get connector '%s' properties\n",
5047                            head->base.name);
5048                 return -1;
5049         }
5050
5051         if (head->connector)
5052                 drmModeFreeConnector(head->connector);
5053         head->connector = connector;
5054
5055         drm_property_info_populate(head->backend, connector_props,
5056                                    head->props_conn,
5057                                    WDRM_CONNECTOR__COUNT, props);
5058         find_and_parse_output_edid(head, props, &make, &model, &serial_number);
5059         weston_head_set_monitor_strings(&head->base, make, model, serial_number);
5060         weston_head_set_subpixel(&head->base,
5061                 drm_subpixel_to_wayland(head->connector->subpixel));
5062
5063         weston_head_set_physical_size(&head->base, head->connector->mmWidth,
5064                                       head->connector->mmHeight);
5065
5066         drmModeFreeObjectProperties(props);
5067
5068         /* Unknown connection status is assumed disconnected. */
5069         weston_head_set_connection_status(&head->base,
5070                         head->connector->connection == DRM_MODE_CONNECTED);
5071
5072         return 0;
5073 }
5074
5075 /**
5076  * Create a Weston head for a connector
5077  *
5078  * Given a DRM connector, create a matching drm_head structure and add it
5079  * to Weston's head list.
5080  *
5081  * @param b Weston backend structure
5082  * @param connector_id DRM connector ID for the head
5083  * @param drm_device udev device pointer
5084  * @returns The new head, or NULL on failure.
5085  */
5086 static struct drm_head *
5087 drm_head_create(struct drm_backend *backend, uint32_t connector_id,
5088                 struct udev_device *drm_device)
5089 {
5090         struct drm_head *head;
5091         drmModeConnector *connector;
5092         char *name;
5093
5094         head = zalloc(sizeof *head);
5095         if (!head)
5096                 return NULL;
5097
5098         connector = drmModeGetConnector(backend->drm.fd, connector_id);
5099         if (!connector)
5100                 goto err_alloc;
5101
5102         name = make_connector_name(connector);
5103         if (!name)
5104                 goto err_alloc;
5105
5106         weston_head_init(&head->base, name);
5107         free(name);
5108
5109         head->connector_id = connector_id;
5110         head->backend = backend;
5111
5112         head->backlight = backlight_init(drm_device, connector->connector_type);
5113
5114         if (drm_head_assign_connector_info(head, connector) < 0)
5115                 goto err_init;
5116
5117         if (head->connector->connector_type == DRM_MODE_CONNECTOR_LVDS ||
5118             head->connector->connector_type == DRM_MODE_CONNECTOR_eDP)
5119                 weston_head_set_internal(&head->base);
5120
5121         if (connector_get_current_mode(head->connector, backend->drm.fd,
5122                                        &head->inherited_mode) < 0) {
5123                 weston_log("Failed to retrieve current mode from connector %d.\n",
5124                            head->connector_id);
5125                 /* Continue, inherited_mode was memset to zero. */
5126         }
5127
5128         weston_compositor_add_head(backend->compositor, &head->base);
5129
5130         weston_log("DRM: found head '%s', connector %d %s.\n",
5131                    head->base.name, head->connector_id,
5132                    head->base.connected ? "connected" : "disconnected");
5133
5134         return head;
5135
5136 err_init:
5137         weston_head_release(&head->base);
5138
5139 err_alloc:
5140         if (connector)
5141                 drmModeFreeConnector(connector);
5142
5143         free(head);
5144
5145         return NULL;
5146 }
5147
5148 static void
5149 drm_head_destroy(struct drm_head *head)
5150 {
5151         weston_head_release(&head->base);
5152
5153         drm_property_info_free(head->props_conn, WDRM_CONNECTOR__COUNT);
5154         drmModeFreeConnector(head->connector);
5155
5156         if (head->backlight)
5157                 backlight_destroy(head->backlight);
5158
5159         free(head);
5160 }
5161
5162 /**
5163  * Create a Weston output structure
5164  *
5165  * Given a DRM connector, create a matching drm_output structure and add it
5166  * to Weston's output list. It also takes ownership of the connector, which
5167  * is released when output is destroyed.
5168  *
5169  * @param b Weston backend structure
5170  * @param resources DRM resources for this device
5171  * @param connector DRM connector to use for this new output
5172  * @param drm_device udev device pointer
5173  * @returns 0 on success, or -1 on failure
5174  */
5175 static int
5176 create_output_for_connector(struct drm_backend *b,
5177                             drmModeRes *resources,
5178                             drmModeConnector *connector,
5179                             struct udev_device *drm_device)
5180 {
5181         struct drm_output *output;
5182         struct drm_head *head;
5183
5184         output = zalloc(sizeof *output);
5185         if (output == NULL)
5186                 goto err_init;
5187
5188         /* XXX: temporary */
5189         head = drm_head_create(b, connector->connector_id, drm_device);
5190         if (!head)
5191                 abort();
5192         head->output = output;
5193
5194         weston_output_init(&output->base, b->compositor, head->base.name);
5195
5196         output->base.enable = drm_output_enable;
5197         output->base.destroy = drm_output_destroy;
5198         output->base.disable = drm_output_disable;
5199         output->base.attach_head = drm_output_attach_head;
5200
5201         output->destroy_pending = 0;
5202         output->disable_pending = 0;
5203
5204         output->state_cur = drm_output_state_alloc(output, NULL);
5205
5206         weston_compositor_add_pending_output(&output->base, b->compositor);
5207
5208         /* drm_head_create() made its own connector */
5209         drmModeFreeConnector(connector);
5210
5211         return 0;
5212
5213 err_init:
5214         drmModeFreeConnector(connector);
5215         return -1;
5216 }
5217
5218 static int
5219 create_outputs(struct drm_backend *b, struct udev_device *drm_device)
5220 {
5221         drmModeConnector *connector;
5222         drmModeRes *resources;
5223         int i;
5224
5225         resources = drmModeGetResources(b->drm.fd);
5226         if (!resources) {
5227                 weston_log("drmModeGetResources failed\n");
5228                 return -1;
5229         }
5230
5231         b->min_width  = resources->min_width;
5232         b->max_width  = resources->max_width;
5233         b->min_height = resources->min_height;
5234         b->max_height = resources->max_height;
5235
5236         for (i = 0; i < resources->count_connectors; i++) {
5237                 int ret;
5238
5239                 connector = drmModeGetConnector(b->drm.fd,
5240                                                 resources->connectors[i]);
5241                 if (connector == NULL)
5242                         continue;
5243
5244                 if (connector->connection == DRM_MODE_CONNECTED) {
5245                         ret = create_output_for_connector(b, resources,
5246                                                           connector, drm_device);
5247                         if (ret < 0)
5248                                 weston_log("failed to create new connector\n");
5249                 } else {
5250                         drmModeFreeConnector(connector);
5251                 }
5252         }
5253
5254         drm_backend_update_unused_outputs(b, resources);
5255
5256         if (wl_list_empty(&b->compositor->output_list) &&
5257             wl_list_empty(&b->compositor->pending_output_list))
5258                 weston_log("No currently active connector found.\n");
5259
5260         drmModeFreeResources(resources);
5261
5262         return 0;
5263 }
5264
5265 static void
5266 update_outputs(struct drm_backend *b, struct udev_device *drm_device)
5267 {
5268         drmModeConnector *connector;
5269         drmModeRes *resources;
5270         struct weston_head *base, *next;
5271         struct drm_head *head;
5272         uint32_t *connected;
5273         int i;
5274
5275         resources = drmModeGetResources(b->drm.fd);
5276         if (!resources) {
5277                 weston_log("drmModeGetResources failed\n");
5278                 return;
5279         }
5280
5281         connected = calloc(resources->count_connectors, sizeof(uint32_t));
5282         if (!connected) {
5283                 drmModeFreeResources(resources);
5284                 return;
5285         }
5286
5287         /* collect new connects */
5288         for (i = 0; i < resources->count_connectors; i++) {
5289                 uint32_t connector_id = resources->connectors[i];
5290
5291                 connector = drmModeGetConnector(b->drm.fd, connector_id);
5292                 if (connector == NULL)
5293                         continue;
5294
5295                 if (connector->connection != DRM_MODE_CONNECTED) {
5296                         drmModeFreeConnector(connector);
5297                         continue;
5298                 }
5299
5300                 connected[i] = connector_id;
5301
5302                 if (drm_output_find_by_connector(b, connector_id)) {
5303                         drmModeFreeConnector(connector);
5304                         continue;
5305                 }
5306
5307                 create_output_for_connector(b, resources,
5308                                             connector, drm_device);
5309                 weston_log("connector %d connected\n", connector_id);
5310         }
5311
5312         wl_list_for_each_safe(base, next,
5313                               &b->compositor->head_list, compositor_link) {
5314                 bool disconnected = true;
5315
5316                 head = to_drm_head(base);
5317
5318                 if (!head->output)
5319                         continue;
5320
5321                 for (i = 0; i < resources->count_connectors; i++) {
5322                         if (connected[i] == head->connector_id) {
5323                                 disconnected = false;
5324                                 break;
5325                         }
5326                 }
5327
5328                 if (!disconnected)
5329                         continue;
5330
5331                 weston_log("connector %d disconnected\n", head->connector_id);
5332                 drm_output_destroy(&head->output->base);
5333         }
5334
5335         drm_backend_update_unused_outputs(b, resources);
5336
5337         free(connected);
5338         drmModeFreeResources(resources);
5339 }
5340
5341 static int
5342 udev_event_is_hotplug(struct drm_backend *b, struct udev_device *device)
5343 {
5344         const char *sysnum;
5345         const char *val;
5346
5347         sysnum = udev_device_get_sysnum(device);
5348         if (!sysnum || atoi(sysnum) != b->drm.id)
5349                 return 0;
5350
5351         val = udev_device_get_property_value(device, "HOTPLUG");
5352         if (!val)
5353                 return 0;
5354
5355         return strcmp(val, "1") == 0;
5356 }
5357
5358 static int
5359 udev_drm_event(int fd, uint32_t mask, void *data)
5360 {
5361         struct drm_backend *b = data;
5362         struct udev_device *event;
5363
5364         event = udev_monitor_receive_device(b->udev_monitor);
5365
5366         if (udev_event_is_hotplug(b, event))
5367                 update_outputs(b, event);
5368
5369         udev_device_unref(event);
5370
5371         return 1;
5372 }
5373
5374 static void
5375 drm_destroy(struct weston_compositor *ec)
5376 {
5377         struct drm_backend *b = to_drm_backend(ec);
5378         struct weston_head *base, *next;
5379
5380         udev_input_destroy(&b->input);
5381
5382         wl_event_source_remove(b->udev_drm_source);
5383         wl_event_source_remove(b->drm_source);
5384
5385         b->shutting_down = true;
5386
5387         destroy_sprites(b);
5388
5389         weston_compositor_shutdown(ec);
5390
5391         wl_list_for_each_safe(base, next, &ec->head_list, compositor_link)
5392                 drm_head_destroy(to_drm_head(base));
5393
5394         if (b->gbm)
5395                 gbm_device_destroy(b->gbm);
5396
5397         udev_monitor_unref(b->udev_monitor);
5398         udev_unref(b->udev);
5399
5400         weston_launcher_destroy(ec->launcher);
5401
5402         wl_array_release(&b->unused_crtcs);
5403         wl_array_release(&b->unused_connectors);
5404
5405         close(b->drm.fd);
5406         free(b->drm.filename);
5407         free(b);
5408 }
5409
5410 static void
5411 session_notify(struct wl_listener *listener, void *data)
5412 {
5413         struct weston_compositor *compositor = data;
5414         struct drm_backend *b = to_drm_backend(compositor);
5415         struct drm_plane *plane;
5416         struct drm_output *output;
5417
5418         if (compositor->session_active) {
5419                 weston_log("activating session\n");
5420                 weston_compositor_wake(compositor);
5421                 weston_compositor_damage_all(compositor);
5422                 b->state_invalid = true;
5423                 udev_input_enable(&b->input);
5424         } else {
5425                 weston_log("deactivating session\n");
5426                 udev_input_disable(&b->input);
5427
5428                 weston_compositor_offscreen(compositor);
5429
5430                 /* If we have a repaint scheduled (either from a
5431                  * pending pageflip or the idle handler), make sure we
5432                  * cancel that so we don't try to pageflip when we're
5433                  * vt switched away.  The OFFSCREEN state will prevent
5434                  * further attempts at repainting.  When we switch
5435                  * back, we schedule a repaint, which will process
5436                  * pending frame callbacks. */
5437
5438                 wl_list_for_each(output, &compositor->output_list, base.link) {
5439                         output->base.repaint_needed = false;
5440                         if (output->cursor_plane)
5441                                 drmModeSetCursor(b->drm.fd, output->crtc_id,
5442                                                  0, 0, 0);
5443                 }
5444
5445                 output = container_of(compositor->output_list.next,
5446                                       struct drm_output, base.link);
5447
5448                 wl_list_for_each(plane, &b->plane_list, link) {
5449                         if (plane->type != WDRM_PLANE_TYPE_OVERLAY)
5450                                 continue;
5451
5452                         drmModeSetPlane(b->drm.fd,
5453                                         plane->plane_id,
5454                                         output->crtc_id, 0, 0,
5455                                         0, 0, 0, 0, 0, 0, 0, 0);
5456                 }
5457         }
5458 }
5459
5460 /**
5461  * Determines whether or not a device is capable of modesetting. If successful,
5462  * sets b->drm.fd and b->drm.filename to the opened device.
5463  */
5464 static bool
5465 drm_device_is_kms(struct drm_backend *b, struct udev_device *device)
5466 {
5467         const char *filename = udev_device_get_devnode(device);
5468         const char *sysnum = udev_device_get_sysnum(device);
5469         drmModeRes *res;
5470         int id, fd;
5471
5472         if (!filename)
5473                 return false;
5474
5475         fd = weston_launcher_open(b->compositor->launcher, filename, O_RDWR);
5476         if (fd < 0)
5477                 return false;
5478
5479         res = drmModeGetResources(fd);
5480         if (!res)
5481                 goto out_fd;
5482
5483         if (res->count_crtcs <= 0 || res->count_connectors <= 0 ||
5484             res->count_encoders <= 0)
5485                 goto out_res;
5486
5487         if (sysnum)
5488                 id = atoi(sysnum);
5489         if (!sysnum || id < 0) {
5490                 weston_log("couldn't get sysnum for device %s\n", filename);
5491                 goto out_res;
5492         }
5493
5494         /* We can be called successfully on multiple devices; if we have,
5495          * clean up old entries. */
5496         if (b->drm.fd >= 0)
5497                 weston_launcher_close(b->compositor->launcher, b->drm.fd);
5498         free(b->drm.filename);
5499
5500         b->drm.fd = fd;
5501         b->drm.id = id;
5502         b->drm.filename = strdup(filename);
5503
5504         drmModeFreeResources(res);
5505
5506         return true;
5507
5508 out_res:
5509         drmModeFreeResources(res);
5510 out_fd:
5511         weston_launcher_close(b->compositor->launcher, fd);
5512         return false;
5513 }
5514
5515 /*
5516  * Find primary GPU
5517  * Some systems may have multiple DRM devices attached to a single seat. This
5518  * function loops over all devices and tries to find a PCI device with the
5519  * boot_vga sysfs attribute set to 1.
5520  * If no such device is found, the first DRM device reported by udev is used.
5521  * Devices are also vetted to make sure they are are capable of modesetting,
5522  * rather than pure render nodes (GPU with no display), or pure
5523  * memory-allocation devices (VGEM).
5524  */
5525 static struct udev_device*
5526 find_primary_gpu(struct drm_backend *b, const char *seat)
5527 {
5528         struct udev_enumerate *e;
5529         struct udev_list_entry *entry;
5530         const char *path, *device_seat, *id;
5531         struct udev_device *device, *drm_device, *pci;
5532
5533         e = udev_enumerate_new(b->udev);
5534         udev_enumerate_add_match_subsystem(e, "drm");
5535         udev_enumerate_add_match_sysname(e, "card[0-9]*");
5536
5537         udev_enumerate_scan_devices(e);
5538         drm_device = NULL;
5539         udev_list_entry_foreach(entry, udev_enumerate_get_list_entry(e)) {
5540                 bool is_boot_vga = false;
5541
5542                 path = udev_list_entry_get_name(entry);
5543                 device = udev_device_new_from_syspath(b->udev, path);
5544                 if (!device)
5545                         continue;
5546                 device_seat = udev_device_get_property_value(device, "ID_SEAT");
5547                 if (!device_seat)
5548                         device_seat = default_seat;
5549                 if (strcmp(device_seat, seat)) {
5550                         udev_device_unref(device);
5551                         continue;
5552                 }
5553
5554                 pci = udev_device_get_parent_with_subsystem_devtype(device,
5555                                                                 "pci", NULL);
5556                 if (pci) {
5557                         id = udev_device_get_sysattr_value(pci, "boot_vga");
5558                         if (id && !strcmp(id, "1"))
5559                                 is_boot_vga = true;
5560                 }
5561
5562                 /* If we already have a modesetting-capable device, and this
5563                  * device isn't our boot-VGA device, we aren't going to use
5564                  * it. */
5565                 if (!is_boot_vga && drm_device) {
5566                         udev_device_unref(device);
5567                         continue;
5568                 }
5569
5570                 /* Make sure this device is actually capable of modesetting;
5571                  * if this call succeeds, b->drm.{fd,filename} will be set,
5572                  * and any old values freed. */
5573                 if (!drm_device_is_kms(b, device)) {
5574                         udev_device_unref(device);
5575                         continue;
5576                 }
5577
5578                 /* There can only be one boot_vga device, and we try to use it
5579                  * at all costs. */
5580                 if (is_boot_vga) {
5581                         if (drm_device)
5582                                 udev_device_unref(drm_device);
5583                         drm_device = device;
5584                         break;
5585                 }
5586
5587                 /* Per the (!is_boot_vga && drm_device) test above, we only
5588                  * trump existing saved devices with boot-VGA devices, so if
5589                  * we end up here, this must be the first device we've seen. */
5590                 assert(!drm_device);
5591                 drm_device = device;
5592         }
5593
5594         /* If we're returning a device to use, we must have an open FD for
5595          * it. */
5596         assert(!!drm_device == (b->drm.fd >= 0));
5597
5598         udev_enumerate_unref(e);
5599         return drm_device;
5600 }
5601
5602 static struct udev_device *
5603 open_specific_drm_device(struct drm_backend *b, const char *name)
5604 {
5605         struct udev_device *device;
5606
5607         device = udev_device_new_from_subsystem_sysname(b->udev, "drm", name);
5608         if (!device) {
5609                 weston_log("ERROR: could not open DRM device '%s'\n", name);
5610                 return NULL;
5611         }
5612
5613         if (!drm_device_is_kms(b, device)) {
5614                 udev_device_unref(device);
5615                 weston_log("ERROR: DRM device '%s' is not a KMS device.\n", name);
5616                 return NULL;
5617         }
5618
5619         /* If we're returning a device to use, we must have an open FD for
5620          * it. */
5621         assert(b->drm.fd >= 0);
5622
5623         return device;
5624 }
5625
5626 static void
5627 planes_binding(struct weston_keyboard *keyboard, const struct timespec *time,
5628                uint32_t key, void *data)
5629 {
5630         struct drm_backend *b = data;
5631
5632         switch (key) {
5633         case KEY_C:
5634                 b->cursors_are_broken ^= 1;
5635                 break;
5636         case KEY_V:
5637                 b->sprites_are_broken ^= 1;
5638                 break;
5639         case KEY_O:
5640                 b->sprites_hidden ^= 1;
5641                 break;
5642         default:
5643                 break;
5644         }
5645 }
5646
5647 #ifdef BUILD_VAAPI_RECORDER
5648 static void
5649 recorder_destroy(struct drm_output *output)
5650 {
5651         vaapi_recorder_destroy(output->recorder);
5652         output->recorder = NULL;
5653
5654         output->base.disable_planes--;
5655
5656         wl_list_remove(&output->recorder_frame_listener.link);
5657         weston_log("[libva recorder] done\n");
5658 }
5659
5660 static void
5661 recorder_frame_notify(struct wl_listener *listener, void *data)
5662 {
5663         struct drm_output *output;
5664         struct drm_backend *b;
5665         int fd, ret;
5666
5667         output = container_of(listener, struct drm_output,
5668                               recorder_frame_listener);
5669         b = to_drm_backend(output->base.compositor);
5670
5671         if (!output->recorder)
5672                 return;
5673
5674         ret = drmPrimeHandleToFD(b->drm.fd,
5675                                  output->scanout_plane->state_cur->fb->handle,
5676                                  DRM_CLOEXEC, &fd);
5677         if (ret) {
5678                 weston_log("[libva recorder] "
5679                            "failed to create prime fd for front buffer\n");
5680                 return;
5681         }
5682
5683         ret = vaapi_recorder_frame(output->recorder, fd,
5684                                    output->scanout_plane->state_cur->fb->stride);
5685         if (ret < 0) {
5686                 weston_log("[libva recorder] aborted: %m\n");
5687                 recorder_destroy(output);
5688         }
5689 }
5690
5691 static void *
5692 create_recorder(struct drm_backend *b, int width, int height,
5693                 const char *filename)
5694 {
5695         int fd;
5696         drm_magic_t magic;
5697
5698         fd = open(b->drm.filename, O_RDWR | O_CLOEXEC);
5699         if (fd < 0)
5700                 return NULL;
5701
5702         drmGetMagic(fd, &magic);
5703         drmAuthMagic(b->drm.fd, magic);
5704
5705         return vaapi_recorder_create(fd, width, height, filename);
5706 }
5707
5708 static void
5709 recorder_binding(struct weston_keyboard *keyboard, const struct timespec *time,
5710                  uint32_t key, void *data)
5711 {
5712         struct drm_backend *b = data;
5713         struct drm_output *output;
5714         int width, height;
5715
5716         output = container_of(b->compositor->output_list.next,
5717                               struct drm_output, base.link);
5718
5719         if (!output->recorder) {
5720                 if (output->gbm_format != GBM_FORMAT_XRGB8888) {
5721                         weston_log("failed to start vaapi recorder: "
5722                                    "output format not supported\n");
5723                         return;
5724                 }
5725
5726                 width = output->base.current_mode->width;
5727                 height = output->base.current_mode->height;
5728
5729                 output->recorder =
5730                         create_recorder(b, width, height, "capture.h264");
5731                 if (!output->recorder) {
5732                         weston_log("failed to create vaapi recorder\n");
5733                         return;
5734                 }
5735
5736                 output->base.disable_planes++;
5737
5738                 output->recorder_frame_listener.notify = recorder_frame_notify;
5739                 wl_signal_add(&output->base.frame_signal,
5740                               &output->recorder_frame_listener);
5741
5742                 weston_output_schedule_repaint(&output->base);
5743
5744                 weston_log("[libva recorder] initialized\n");
5745         } else {
5746                 recorder_destroy(output);
5747         }
5748 }
5749 #else
5750 static void
5751 recorder_binding(struct weston_keyboard *keyboard, const struct timespec *time,
5752                  uint32_t key, void *data)
5753 {
5754         weston_log("Compiled without libva support\n");
5755 }
5756 #endif
5757
5758 static void
5759 switch_to_gl_renderer(struct drm_backend *b)
5760 {
5761         struct drm_output *output;
5762         bool dmabuf_support_inited;
5763
5764         if (!b->use_pixman)
5765                 return;
5766
5767         dmabuf_support_inited = !!b->compositor->renderer->import_dmabuf;
5768
5769         weston_log("Switching to GL renderer\n");
5770
5771         b->gbm = create_gbm_device(b->drm.fd);
5772         if (!b->gbm) {
5773                 weston_log("Failed to create gbm device. "
5774                            "Aborting renderer switch\n");
5775                 return;
5776         }
5777
5778         wl_list_for_each(output, &b->compositor->output_list, base.link)
5779                 pixman_renderer_output_destroy(&output->base);
5780
5781         b->compositor->renderer->destroy(b->compositor);
5782
5783         if (drm_backend_create_gl_renderer(b) < 0) {
5784                 gbm_device_destroy(b->gbm);
5785                 weston_log("Failed to create GL renderer. Quitting.\n");
5786                 /* FIXME: we need a function to shutdown cleanly */
5787                 assert(0);
5788         }
5789
5790         wl_list_for_each(output, &b->compositor->output_list, base.link)
5791                 drm_output_init_egl(output, b);
5792
5793         b->use_pixman = 0;
5794
5795         if (!dmabuf_support_inited && b->compositor->renderer->import_dmabuf) {
5796                 if (linux_dmabuf_setup(b->compositor) < 0)
5797                         weston_log("Error: initializing dmabuf "
5798                                    "support failed.\n");
5799         }
5800 }
5801
5802 static void
5803 renderer_switch_binding(struct weston_keyboard *keyboard,
5804                         const struct timespec *time, uint32_t key, void *data)
5805 {
5806         struct drm_backend *b =
5807                 to_drm_backend(keyboard->seat->compositor);
5808
5809         switch_to_gl_renderer(b);
5810 }
5811
5812 static const struct weston_drm_output_api api = {
5813         drm_output_set_mode,
5814         drm_output_set_gbm_format,
5815         drm_output_set_seat,
5816 };
5817
5818 static struct drm_backend *
5819 drm_backend_create(struct weston_compositor *compositor,
5820                    struct weston_drm_backend_config *config)
5821 {
5822         struct drm_backend *b;
5823         struct udev_device *drm_device;
5824         struct wl_event_loop *loop;
5825         const char *seat_id = default_seat;
5826         int ret;
5827
5828         weston_log("initializing drm backend\n");
5829
5830         b = zalloc(sizeof *b);
5831         if (b == NULL)
5832                 return NULL;
5833
5834         b->state_invalid = true;
5835         b->drm.fd = -1;
5836         wl_array_init(&b->unused_crtcs);
5837         wl_array_init(&b->unused_connectors);
5838
5839         /*
5840          * KMS support for hardware planes cannot properly synchronize
5841          * without nuclear page flip. Without nuclear/atomic, hw plane
5842          * and cursor plane updates would either tear or cause extra
5843          * waits for vblanks which means dropping the compositor framerate
5844          * to a fraction. For cursors, it's not so bad, so they are
5845          * enabled.
5846          *
5847          * These can be enabled again when nuclear/atomic support lands.
5848          */
5849         b->sprites_are_broken = 1;
5850         b->compositor = compositor;
5851         b->use_pixman = config->use_pixman;
5852         b->pageflip_timeout = config->pageflip_timeout;
5853
5854         compositor->backend = &b->base;
5855
5856         if (parse_gbm_format(config->gbm_format, GBM_FORMAT_XRGB8888, &b->gbm_format) < 0)
5857                 goto err_compositor;
5858
5859         if (config->seat_id)
5860                 seat_id = config->seat_id;
5861
5862         /* Check if we run drm-backend using weston-launch */
5863         compositor->launcher = weston_launcher_connect(compositor, config->tty,
5864                                                        seat_id, true);
5865         if (compositor->launcher == NULL) {
5866                 weston_log("fatal: drm backend should be run using "
5867                            "weston-launch binary, or your system should "
5868                            "provide the logind D-Bus API.\n");
5869                 goto err_compositor;
5870         }
5871
5872         b->udev = udev_new();
5873         if (b->udev == NULL) {
5874                 weston_log("failed to initialize udev context\n");
5875                 goto err_launcher;
5876         }
5877
5878         b->session_listener.notify = session_notify;
5879         wl_signal_add(&compositor->session_signal, &b->session_listener);
5880
5881         if (config->specific_device)
5882                 drm_device = open_specific_drm_device(b, config->specific_device);
5883         else
5884                 drm_device = find_primary_gpu(b, seat_id);
5885         if (drm_device == NULL) {
5886                 weston_log("no drm device found\n");
5887                 goto err_udev;
5888         }
5889
5890         if (init_kms_caps(b) < 0) {
5891                 weston_log("failed to initialize kms\n");
5892                 goto err_udev_dev;
5893         }
5894
5895         if (b->use_pixman) {
5896                 if (init_pixman(b) < 0) {
5897                         weston_log("failed to initialize pixman renderer\n");
5898                         goto err_udev_dev;
5899                 }
5900         } else {
5901                 if (init_egl(b) < 0) {
5902                         weston_log("failed to initialize egl\n");
5903                         goto err_udev_dev;
5904                 }
5905         }
5906
5907         b->base.destroy = drm_destroy;
5908         b->base.repaint_begin = drm_repaint_begin;
5909         b->base.repaint_flush = drm_repaint_flush;
5910         b->base.repaint_cancel = drm_repaint_cancel;
5911         b->base.create_output = drm_output_create;
5912
5913         weston_setup_vt_switch_bindings(compositor);
5914
5915         wl_list_init(&b->plane_list);
5916         create_sprites(b);
5917
5918         if (udev_input_init(&b->input,
5919                             compositor, b->udev, seat_id,
5920                             config->configure_device) < 0) {
5921                 weston_log("failed to create input devices\n");
5922                 goto err_sprite;
5923         }
5924
5925         if (create_outputs(b, drm_device) < 0) {
5926                 weston_log("failed to create output for %s\n", b->drm.filename);
5927                 goto err_udev_input;
5928         }
5929
5930         /* A this point we have some idea of whether or not we have a working
5931          * cursor plane. */
5932         if (!b->cursors_are_broken)
5933                 compositor->capabilities |= WESTON_CAP_CURSOR_PLANE;
5934
5935         loop = wl_display_get_event_loop(compositor->wl_display);
5936         b->drm_source =
5937                 wl_event_loop_add_fd(loop, b->drm.fd,
5938                                      WL_EVENT_READABLE, on_drm_input, b);
5939
5940         b->udev_monitor = udev_monitor_new_from_netlink(b->udev, "udev");
5941         if (b->udev_monitor == NULL) {
5942                 weston_log("failed to initialize udev monitor\n");
5943                 goto err_drm_source;
5944         }
5945         udev_monitor_filter_add_match_subsystem_devtype(b->udev_monitor,
5946                                                         "drm", NULL);
5947         b->udev_drm_source =
5948                 wl_event_loop_add_fd(loop,
5949                                      udev_monitor_get_fd(b->udev_monitor),
5950                                      WL_EVENT_READABLE, udev_drm_event, b);
5951
5952         if (udev_monitor_enable_receiving(b->udev_monitor) < 0) {
5953                 weston_log("failed to enable udev-monitor receiving\n");
5954                 goto err_udev_monitor;
5955         }
5956
5957         udev_device_unref(drm_device);
5958
5959         weston_compositor_add_debug_binding(compositor, KEY_O,
5960                                             planes_binding, b);
5961         weston_compositor_add_debug_binding(compositor, KEY_C,
5962                                             planes_binding, b);
5963         weston_compositor_add_debug_binding(compositor, KEY_V,
5964                                             planes_binding, b);
5965         weston_compositor_add_debug_binding(compositor, KEY_Q,
5966                                             recorder_binding, b);
5967         weston_compositor_add_debug_binding(compositor, KEY_W,
5968                                             renderer_switch_binding, b);
5969
5970         if (compositor->renderer->import_dmabuf) {
5971                 if (linux_dmabuf_setup(compositor) < 0)
5972                         weston_log("Error: initializing dmabuf "
5973                                    "support failed.\n");
5974         }
5975
5976         ret = weston_plugin_api_register(compositor, WESTON_DRM_OUTPUT_API_NAME,
5977                                          &api, sizeof(api));
5978
5979         if (ret < 0) {
5980                 weston_log("Failed to register output API.\n");
5981                 goto err_udev_monitor;
5982         }
5983
5984         return b;
5985
5986 err_udev_monitor:
5987         wl_event_source_remove(b->udev_drm_source);
5988         udev_monitor_unref(b->udev_monitor);
5989 err_drm_source:
5990         wl_event_source_remove(b->drm_source);
5991 err_udev_input:
5992         udev_input_destroy(&b->input);
5993 err_sprite:
5994         if (b->gbm)
5995                 gbm_device_destroy(b->gbm);
5996         destroy_sprites(b);
5997 err_udev_dev:
5998         udev_device_unref(drm_device);
5999 err_launcher:
6000         weston_launcher_destroy(compositor->launcher);
6001 err_udev:
6002         udev_unref(b->udev);
6003 err_compositor:
6004         weston_compositor_shutdown(compositor);
6005         free(b);
6006         return NULL;
6007 }
6008
6009 static void
6010 config_init_to_defaults(struct weston_drm_backend_config *config)
6011 {
6012 }
6013
6014 WL_EXPORT int
6015 weston_backend_init(struct weston_compositor *compositor,
6016                     struct weston_backend_config *config_base)
6017 {
6018         struct drm_backend *b;
6019         struct weston_drm_backend_config config = {{ 0, }};
6020
6021         if (config_base == NULL ||
6022             config_base->struct_version != WESTON_DRM_BACKEND_CONFIG_VERSION ||
6023             config_base->struct_size > sizeof(struct weston_drm_backend_config)) {
6024                 weston_log("drm backend config structure is invalid\n");
6025                 return -1;
6026         }
6027
6028         config_init_to_defaults(&config);
6029         memcpy(&config, config_base, config_base->struct_size);
6030
6031         b = drm_backend_create(compositor, &config);
6032         if (b == NULL)
6033                 return -1;
6034
6035         return 0;
6036 }