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