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