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