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