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