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
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:
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.
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
38 #include <linux/input.h>
46 #include <xf86drmMode.h>
47 #include <drm_fourcc.h>
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"
68 #ifndef DRM_CAP_TIMESTAMP_MONOTONIC
69 #define DRM_CAP_TIMESTAMP_MONOTONIC 0x6
72 #ifndef DRM_CLIENT_CAP_UNIVERSAL_PLANES
73 #define DRM_CLIENT_CAP_UNIVERSAL_PLANES 2
76 #ifndef DRM_CLIENT_CAP_ASPECT_RATIO
77 #define DRM_CLIENT_CAP_ASPECT_RATIO 4
80 #ifndef DRM_CAP_CURSOR_WIDTH
81 #define DRM_CAP_CURSOR_WIDTH 0x8
84 #ifndef DRM_CAP_CURSOR_HEIGHT
85 #define DRM_CAP_CURSOR_HEIGHT 0x9
88 #ifndef GBM_BO_USE_CURSOR
89 #define GBM_BO_USE_CURSOR GBM_BO_USE_CURSOR_64X64
92 #define MAX_CLONED_CONNECTORS 4
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.
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)
104 * Represents the values of an enum-type KMS property
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 */
113 * Holds information on a DRM property, including its ID and the enum
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.
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.
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 */
133 * List of properties attached to DRM planes
135 enum wdrm_plane_property {
147 WDRM_PLANE_IN_FORMATS,
152 * Possible values for the WDRM_PLANE_TYPE property.
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
161 static struct drm_property_enum_info plane_type_enums[] = {
162 [WDRM_PLANE_TYPE_PRIMARY] = {
165 [WDRM_PLANE_TYPE_OVERLAY] = {
168 [WDRM_PLANE_TYPE_CURSOR] = {
173 static const struct drm_property_info plane_props[] = {
174 [WDRM_PLANE_TYPE] = {
176 .enum_values = plane_type_enums,
177 .num_enum_values = WDRM_PLANE_TYPE__COUNT,
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" },
193 * List of properties attached to a DRM connector
195 enum wdrm_connector_property {
196 WDRM_CONNECTOR_EDID = 0,
198 WDRM_CONNECTOR_CRTC_ID,
199 WDRM_CONNECTOR__COUNT
202 enum wdrm_dpms_state {
203 WDRM_DPMS_STATE_OFF = 0,
205 WDRM_DPMS_STATE_STANDBY, /* unused */
206 WDRM_DPMS_STATE_SUSPEND, /* unused */
207 WDRM_DPMS_STATE__COUNT
210 static struct drm_property_enum_info dpms_state_enums[] = {
211 [WDRM_DPMS_STATE_OFF] = {
214 [WDRM_DPMS_STATE_ON] = {
217 [WDRM_DPMS_STATE_STANDBY] = {
220 [WDRM_DPMS_STATE_SUSPEND] = {
225 static const struct drm_property_info connector_props[] = {
226 [WDRM_CONNECTOR_EDID] = { .name = "EDID" },
227 [WDRM_CONNECTOR_DPMS] = {
229 .enum_values = dpms_state_enums,
230 .num_enum_values = WDRM_DPMS_STATE__COUNT,
232 [WDRM_CONNECTOR_CRTC_ID] = { .name = "CRTC_ID", },
236 * List of properties attached to DRM CRTCs
238 enum wdrm_crtc_property {
239 WDRM_CRTC_MODE_ID = 0,
244 static const struct drm_property_info crtc_props[] = {
245 [WDRM_CRTC_MODE_ID] = { .name = "MODE_ID", },
246 [WDRM_CRTC_ACTIVE] = { .name = "ACTIVE", },
250 * Mode for drm_output_state_duplicate.
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 */
258 * Mode for drm_pending_state_apply and co.
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 */
267 struct weston_backend base;
268 struct weston_compositor *compositor;
271 struct wl_event_source *drm_source;
273 struct udev_monitor *udev_monitor;
274 struct wl_event_source *udev_drm_source;
281 struct gbm_device *gbm;
282 struct wl_listener session_listener;
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:
289 int min_width, max_width;
290 int min_height, max_height;
292 struct wl_list plane_list;
293 int sprites_are_broken;
300 /* CRTC IDs not used by any enabled output. */
301 struct wl_array unused_crtcs;
303 int cursors_are_broken;
305 bool universal_planes;
309 bool use_pixman_shadow;
311 struct udev_input input;
313 int32_t cursor_width;
314 int32_t cursor_height;
316 uint32_t pageflip_timeout;
320 bool aspect_ratio_supported;
324 struct weston_mode base;
325 drmModeModeInfo mode_info;
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 */
339 enum drm_fb_type type;
343 uint32_t fb_id, size;
347 const struct pixel_format_info *format;
351 struct weston_buffer_reference buffer_ref;
353 /* Used by gbm fbs */
355 struct gbm_surface *gbm_surface;
357 /* Used by dumb fbs */
363 char monitor_name[13];
365 char serial_number[13];
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.
374 struct drm_pending_state {
375 struct drm_backend *backend;
376 struct wl_list output_list;
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
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.
389 struct drm_output_state {
390 struct drm_pending_state *pending_state;
391 struct drm_output *output;
394 struct wl_list plane_list;
398 * Plane state holds the dynamic state for a plane: where it is positioned,
399 * and which buffer it is currently displaying.
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.
404 struct drm_plane_state {
405 struct drm_plane *plane;
406 struct drm_output *output;
407 struct drm_output_state *output_state;
411 struct weston_view *ev; /**< maintained for drm_assign_planes only */
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;
420 struct wl_list link; /* drm_output_state::plane_list */
424 * A plane represents one buffer, positioned within a CRTC, and stacked
425 * relative to other planes on the same CRTC.
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).
432 * The cursor plane also has its own alternate legacy API.
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'.
439 struct weston_plane base;
441 struct drm_backend *backend;
443 enum wdrm_plane_type type;
445 uint32_t possible_crtcs;
447 uint32_t count_formats;
449 struct drm_property_info props[WDRM_PLANE__COUNT];
451 /* The last state submitted to the kernel for this plane. */
452 struct drm_plane_state *state_cur;
458 uint32_t count_modifiers;
464 struct weston_head base;
465 struct drm_backend *backend;
467 drmModeConnector *connector;
468 uint32_t connector_id;
469 struct drm_edid edid;
471 /* Holds the properties for the connector */
472 struct drm_property_info props_conn[WDRM_CONNECTOR__COUNT];
474 struct backlight *backlight;
476 drmModeModeInfo inherited_mode; /**< Original mode on the connector */
477 uint32_t inherited_crtc_id; /**< Original CRTC assignment */
481 struct weston_output base;
483 uint32_t crtc_id; /* object ID to pass to DRM functions */
484 int pipe; /* index of CRTC in resource array / bitmasks */
486 /* Holds the properties for the CRTC */
487 struct drm_property_info props_crtc[WDRM_CRTC__COUNT];
490 int page_flip_pending;
491 int atomic_complete_pending;
494 int dpms_off_pending;
496 struct drm_fb *gbm_cursor_fb[2];
497 struct drm_plane *cursor_plane;
498 struct weston_view *cursor_view;
501 struct gbm_surface *gbm_surface;
504 /* Plane being displayed directly on the CRTC */
505 struct drm_plane *scanout_plane;
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;
513 struct drm_fb *dumb[2];
514 pixman_image_t *image[2];
516 pixman_region32_t previous_damage;
518 struct vaapi_recorder *recorder;
519 struct wl_listener recorder_frame_listener;
521 struct wl_event_source *pageflip_timer;
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",
532 static struct gl_renderer_interface *gl_renderer;
534 static const char default_seat[] = "seat0";
537 wl_array_remove_uint32(struct wl_array *array, uint32_t elm)
541 end = (uint32_t *) ((char *) array->data + array->size);
543 wl_array_for_each(pos, array) {
547 array->size -= sizeof(*pos);
551 memmove(pos, pos + 1, (char *) end - (char *) (pos + 1));
556 static inline struct drm_head *
557 to_drm_head(struct weston_head *base)
559 return container_of(base, struct drm_head, base);
562 static inline struct drm_output *
563 to_drm_output(struct weston_output *base)
565 return container_of(base, struct drm_output, base);
568 static inline struct drm_backend *
569 to_drm_backend(struct weston_compositor *base)
571 return container_of(base->backend, struct drm_backend, base);
575 pageflip_timeout(void *data) {
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.
581 struct drm_output *output = data;
582 struct weston_compositor *compositor = output->base.compositor;
584 weston_log("Pageflip timeout reached on output %s, your "
585 "driver is probably buggy! Exiting.\n",
587 weston_compositor_exit_with_code(compositor, EXIT_FAILURE);
592 /* Creates the pageflip timer. Note that it isn't armed by default */
594 drm_output_pageflip_timer_create(struct drm_output *output)
596 struct wl_event_loop *loop = NULL;
597 struct weston_compositor *ec = output->base.compositor;
599 loop = wl_display_get_event_loop(ec->wl_display);
601 output->pageflip_timer = wl_event_loop_add_timer(loop,
605 if (output->pageflip_timer == NULL) {
606 weston_log("creating drm pageflip timer failed: %m\n");
613 static inline struct drm_mode *
614 to_drm_mode(struct weston_mode *base)
616 return container_of(base, struct drm_mode, base);
620 * Get the current value of a KMS property
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.
627 * If the property is not present, the default value will be returned.
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
634 drm_property_get_value(struct drm_property_info *info,
635 const drmModeObjectProperties *props,
640 if (info->prop_id == 0)
643 for (i = 0; i < props->count_props; i++) {
646 if (props->props[i] != info->prop_id)
649 /* Simple (non-enum) types can return the value directly */
650 if (info->num_enum_values == 0)
651 return props->prop_values[i];
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)
657 if (info->enum_values[j].value != props->prop_values[i])
663 /* We don't have a mapping for this enum; return default. */
671 * Cache DRM property values
673 * Update a per-object array of drm_property_info structures, given the
674 * DRM properties of the object.
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).
681 * This updates the property IDs and enum values within the drm_property_info
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".
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.
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
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)
708 drmModePropertyRes *prop;
711 for (i = 0; i < num_infos; i++) {
714 info[i].name = src[i].name;
716 info[i].num_enum_values = src[i].num_enum_values;
718 if (src[i].num_enum_values == 0)
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;
731 for (i = 0; i < props->count_props; i++) {
734 prop = drmModeGetProperty(b->drm.fd, props->props[i]);
738 for (j = 0; j < num_infos; j++) {
739 if (!strcmp(prop->name, info[j].name))
743 /* We don't know/care about this property. */
744 if (j == num_infos) {
746 weston_log("DRM debug: unrecognized property %u '%s'\n",
747 prop->prop_id, prop->name);
749 drmModeFreeProperty(prop);
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);
761 info[j].prop_id = props->props[i];
763 if (info[j].num_enum_values == 0) {
764 drmModeFreeProperty(prop);
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);
776 for (k = 0; k < info[j].num_enum_values; k++) {
779 for (l = 0; l < prop->count_enums; l++) {
780 if (!strcmp(prop->enums[l].name,
781 info[j].enum_values[k].name))
785 if (l == prop->count_enums)
788 info[j].enum_values[k].valid = true;
789 info[j].enum_values[k].value = prop->enums[l].value;
792 drmModeFreeProperty(prop);
796 for (i = 0; i < num_infos; i++) {
797 if (info[i].prop_id == 0)
798 weston_log("DRM warning: property '%s' missing\n",
805 * Free DRM property information
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().
811 * @param info DRM property info array
812 * @param num_props Number of entries in array to free
815 drm_property_info_free(struct drm_property_info *info, int num_props)
819 for (i = 0; i < num_props; i++)
820 free(info[i].enum_values);
822 memset(info, 0, sizeof(*info) * num_props);
826 drm_output_set_cursor(struct drm_output_state *output_state);
829 drm_output_update_msc(struct drm_output *output, unsigned int seq);
832 drm_output_destroy(struct weston_output *output_base);
835 * Returns true if the plane can be used on the given output for its current
839 drm_plane_is_available(struct drm_plane *plane, struct drm_output *output)
841 assert(plane->state_cur);
843 /* The plane still has a request not yet completed by the kernel. */
844 if (!plane->state_cur->complete)
847 /* The plane is still active on another output. */
848 if (plane->state_cur->output && plane->state_cur->output != output)
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));
856 static struct drm_output *
857 drm_output_find_by_crtc(struct drm_backend *b, uint32_t crtc_id)
859 struct drm_output *output;
861 wl_list_for_each(output, &b->compositor->output_list, base.link) {
862 if (output->crtc_id == crtc_id)
869 static struct drm_head *
870 drm_head_find_by_connector(struct drm_backend *backend, uint32_t connector_id)
872 struct weston_head *base;
873 struct drm_head *head;
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)
886 drm_fb_destroy(struct drm_fb *fb)
889 drmModeRmFB(fb->fd, fb->fb_id);
890 weston_buffer_reference(&fb->buffer_ref, NULL);
895 drm_fb_destroy_dumb(struct drm_fb *fb)
897 struct drm_mode_destroy_dumb destroy_arg;
899 assert(fb->type == BUFFER_PIXMAN_DUMB);
901 if (fb->map && fb->size > 0)
902 munmap(fb->map, fb->size);
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);
912 drm_fb_destroy_gbm(struct gbm_bo *bo, void *data)
914 struct drm_fb *fb = data;
916 assert(fb->type == BUFFER_GBM_SURFACE || fb->type == BUFFER_CLIENT ||
917 fb->type == BUFFER_CURSOR);
922 drm_fb_addfb(struct drm_fb *fb)
925 #ifdef HAVE_DRM_ADDFB2_MODIFIERS
926 uint64_t mods[4] = { };
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
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,
940 fb->handles, fb->strides,
941 fb->offsets, mods, &fb->fb_id,
942 DRM_MODE_FB_MODIFIERS);
947 ret = drmModeAddFB2(fb->fd, fb->width, fb->height, fb->format->format,
948 fb->handles, fb->strides, fb->offsets, &fb->fb_id,
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)
958 /* Cannot fall back to AddFB for multi-planar formats either. */
959 if (fb->handles[1] || fb->handles[2] || fb->handles[3])
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);
968 static struct drm_fb *
969 drm_fb_create_dumb(struct drm_backend *b, int width, int height,
975 struct drm_mode_create_dumb create_arg;
976 struct drm_mode_destroy_dumb destroy_arg;
977 struct drm_mode_map_dumb map_arg;
979 fb = zalloc(sizeof *fb);
984 fb->format = pixel_format_get_info(format);
986 weston_log("failed to look up format 0x%lx\n",
987 (unsigned long) format);
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);
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;
1002 ret = drmIoctl(b->drm.fd, DRM_IOCTL_MODE_CREATE_DUMB, &create_arg);
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;
1012 fb->height = height;
1015 if (drm_fb_addfb(fb) != 0) {
1016 weston_log("failed to create kms fb: %m\n");
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);
1026 fb->map = mmap(NULL, fb->size, PROT_WRITE,
1027 MAP_SHARED, b->drm.fd, map_arg.offset);
1028 if (fb->map == MAP_FAILED)
1034 drmModeRmFB(b->drm.fd, fb->fb_id);
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);
1044 static struct drm_fb *
1045 drm_fb_ref(struct drm_fb *fb)
1052 drm_fb_destroy_dmabuf(struct drm_fb *fb)
1054 /* We deliberately do not close the GEM handles here; GBM manages
1055 * their lifetime through the BO. */
1057 gbm_bo_destroy(fb->bo);
1061 static struct drm_fb *
1062 drm_fb_get_from_dmabuf(struct linux_dmabuf_buffer *dmabuf,
1063 struct drm_backend *backend, bool is_opaque)
1065 #ifdef HAVE_GBM_FD_IMPORT
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],
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],
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
1092 if (dmabuf->attributes.flags)
1095 fb = zalloc(sizeof *fb);
1100 fb->type = BUFFER_DMABUF;
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));
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));
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));
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,
1134 GBM_BO_USE_SCANOUT);
1136 fb->bo = gbm_bo_import(backend->gbm, GBM_BO_IMPORT_FD,
1138 GBM_BO_USE_SCANOUT);
1144 fb->width = dmabuf->attributes.width;
1145 fb->height = dmabuf->attributes.height;
1146 fb->modifier = dmabuf->attributes.modifier[0];
1148 fb->fd = backend->drm.fd;
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));
1163 fb->format = pixel_format_get_info(dmabuf->attributes.format);
1165 weston_log("couldn't look up format info for 0x%lx\n",
1166 (unsigned long) dmabuf->attributes.format);
1171 fb->format = pixel_format_get_opaque_substitute(fb->format);
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");
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])
1187 if (drm_fb_addfb(fb) != 0) {
1188 weston_log("failed to create kms fb: %m\n");
1195 drm_fb_destroy_dmabuf(fb);
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)
1204 struct drm_fb *fb = gbm_bo_get_user_data(bo);
1205 #ifdef HAVE_GBM_MODIFIERS
1210 assert(fb->type == type);
1211 return drm_fb_ref(fb);
1214 fb = zalloc(sizeof *fb);
1221 fb->fd = backend->drm.fd;
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));
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);
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;
1242 weston_log("couldn't look up format 0x%lx\n",
1243 (unsigned long) gbm_bo_get_format(bo));
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. */
1250 fb->format = pixel_format_get_opaque_substitute(fb->format);
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");
1260 if (drm_fb_addfb(fb) != 0) {
1261 weston_log("failed to create kms fb: %m\n");
1265 gbm_bo_set_user_data(bo, fb, drm_fb_destroy_gbm);
1275 drm_fb_set_buffer(struct drm_fb *fb, struct weston_buffer *buffer)
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);
1283 drm_fb_unref(struct drm_fb *fb)
1288 assert(fb->refcnt > 0);
1289 if (--fb->refcnt > 0)
1293 case BUFFER_PIXMAN_DUMB:
1294 drm_fb_destroy_dumb(fb);
1298 gbm_bo_destroy(fb->bo);
1300 case BUFFER_GBM_SURFACE:
1301 gbm_surface_release_buffer(fb->gbm_surface, fb->bo);
1304 drm_fb_destroy_dmabuf(fb);
1313 * Allocate a new, empty, plane state.
1315 static struct drm_plane_state *
1316 drm_plane_state_alloc(struct drm_output_state *state_output,
1317 struct drm_plane *plane)
1319 struct drm_plane_state *state = zalloc(sizeof(*state));
1322 state->output_state = state_output;
1323 state->plane = plane;
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
1334 wl_list_insert(&state_output->plane_list, &state->link);
1336 wl_list_init(&state->link);
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.
1346 drm_plane_state_free(struct drm_plane_state *state, bool force)
1351 wl_list_remove(&state->link);
1352 wl_list_init(&state->link);
1353 state->output_state = NULL;
1355 if (force || state != state->plane->state_cur) {
1356 drm_fb_unref(state->fb);
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.
1366 static struct drm_plane_state *
1367 drm_plane_state_duplicate(struct drm_output_state *state_output,
1368 struct drm_plane_state *src)
1370 struct drm_plane_state *dst = malloc(sizeof(*dst));
1371 struct drm_plane_state *old, *tmp;
1376 wl_list_init(&dst->link);
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. */
1383 if (old->plane == dst->plane)
1384 drm_plane_state_free(old, false);
1387 wl_list_insert(&state_output->plane_list, &dst->link);
1389 dst->fb = drm_fb_ref(src->fb);
1390 dst->output_state = state_output;
1391 dst->complete = false;
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.
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
1409 drm_plane_state_put_back(struct drm_plane_state *state)
1411 struct drm_output_state *state_output;
1412 struct drm_plane *plane;
1417 state_output = state->output_state;
1418 plane = state->plane;
1419 drm_plane_state_free(state, false);
1421 /* Plane was previously disabled; no need to keep this temporary
1423 if (!plane->state_cur->fb)
1426 (void) drm_plane_state_alloc(state_output, plane);
1430 drm_view_transform_supported(struct weston_view *ev, struct weston_output *output)
1432 struct weston_buffer_viewport *viewport = &ev->surface->buffer_viewport;
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
1438 if (ev->transform.enabled &&
1439 ev->transform.matrix.type >= WESTON_MATRIX_TRANSFORM_ROTATE)
1442 if (viewport->buffer.transform != output->transform)
1449 * Given a weston_view, fill the drm_plane_state's co-ordinates to display on
1453 drm_plane_state_coords_for_view(struct drm_plane_state *state,
1454 struct weston_view *ev)
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;
1462 if (!drm_view_transform_supported(ev, &output->base))
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;
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,
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);
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);
1501 /* Buffer transforms may mean that x2 is to the left of x1, and/or that
1502 * y2 is above y1. */
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;
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
1525 if (state->src_x < 0)
1527 if (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;
1538 drm_view_is_opaque(struct weston_view *ev)
1540 pixman_region32_t r;
1543 pixman_region32_init_rect(&r, 0, 0,
1545 ev->surface->height);
1546 pixman_region32_subtract(&r, &r, &ev->surface->opaque);
1548 if (!pixman_region32_not_empty(&r))
1551 pixman_region32_fini(&r);
1556 static struct drm_fb *
1557 drm_fb_get_from_view(struct drm_output_state *state, struct weston_view *ev)
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;
1566 if (ev->alpha != 1.0f)
1569 if (!drm_view_transform_supported(ev, &output->base))
1575 if (wl_shm_buffer_get(buffer->resource))
1578 /* GBM is used for dmabuf import as well as from client wl_buffer. */
1582 dmabuf = linux_dmabuf_buffer_get(buffer->resource);
1584 fb = drm_fb_get_from_dmabuf(dmabuf, b, is_opaque);
1590 bo = gbm_bo_import(b->gbm, GBM_BO_IMPORT_WL_BUFFER,
1591 buffer->resource, GBM_BO_USE_SCANOUT);
1595 fb = drm_fb_get_from_bo(bo, b, is_opaque, BUFFER_CLIENT);
1602 drm_fb_set_buffer(fb, buffer);
1607 * Return a plane state from a drm_output_state.
1609 static struct drm_plane_state *
1610 drm_output_state_get_existing_plane(struct drm_output_state *state_output,
1611 struct drm_plane *plane)
1613 struct drm_plane_state *ps;
1615 wl_list_for_each(ps, &state_output->plane_list, link) {
1616 if (ps->plane == plane)
1624 * Return a plane state from a drm_output_state, either existing or
1625 * freshly allocated.
1627 static struct drm_plane_state *
1628 drm_output_state_get_plane(struct drm_output_state *state_output,
1629 struct drm_plane *plane)
1631 struct drm_plane_state *ps;
1633 ps = drm_output_state_get_existing_plane(state_output, plane);
1637 return drm_plane_state_alloc(state_output, plane);
1641 * Allocate a new, empty drm_output_state. This should not generally be used
1642 * in the repaint cycle; see drm_output_state_duplicate.
1644 static struct drm_output_state *
1645 drm_output_state_alloc(struct drm_output *output,
1646 struct drm_pending_state *pending_state)
1648 struct drm_output_state *state = zalloc(sizeof(*state));
1651 state->output = output;
1652 state->dpms = WESTON_DPMS_OFF;
1653 state->pending_state = pending_state;
1655 wl_list_insert(&pending_state->output_list, &state->link);
1657 wl_list_init(&state->link);
1659 wl_list_init(&state->plane_list);
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.
1669 * The mode determines whether the output will be reset to an a blank state,
1670 * or an exact mirror of the current state.
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)
1677 struct drm_output_state *dst = malloc(sizeof(*dst));
1678 struct drm_plane_state *ps;
1682 /* Copy the whole structure, then individually modify the
1683 * pending_state, as well as the list link into our pending
1687 dst->pending_state = pending_state;
1689 wl_list_insert(&pending_state->output_list, &dst->link);
1691 wl_list_init(&dst->link);
1693 wl_list_init(&dst->plane_list);
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. */
1701 if (plane_mode == DRM_OUTPUT_STATE_CLEAR_PLANES)
1702 (void) drm_plane_state_alloc(dst, ps->plane);
1704 (void) drm_plane_state_duplicate(dst, ps);
1711 * Free an unused drm_output_state.
1714 drm_output_state_free(struct drm_output_state *state)
1716 struct drm_plane_state *ps, *next;
1721 wl_list_for_each_safe(ps, next, &state->plane_list, link)
1722 drm_plane_state_free(ps, false);
1724 wl_list_remove(&state->link);
1730 * Get output state to disable output
1732 * Returns a pointer to an output_state object which can be used to disable
1733 * an output (e.g. DPMS off).
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
1739 static struct drm_output_state *
1740 drm_output_get_disable_state(struct drm_pending_state *pending_state,
1741 struct drm_output *output)
1743 struct drm_output_state *output_state;
1745 output_state = drm_output_state_duplicate(output->state_cur,
1747 DRM_OUTPUT_STATE_CLEAR_PLANES);
1748 output_state->dpms = WESTON_DPMS_OFF;
1750 return output_state;
1754 * Allocate a new drm_pending_state
1756 * Allocate a new, empty, 'pending state' structure to be used across a
1757 * repaint cycle or similar.
1759 * @param backend DRM backend
1760 * @returns Newly-allocated pending state structure
1762 static struct drm_pending_state *
1763 drm_pending_state_alloc(struct drm_backend *backend)
1765 struct drm_pending_state *ret;
1767 ret = calloc(1, sizeof(*ret));
1771 ret->backend = backend;
1772 wl_list_init(&ret->output_list);
1778 * Free a drm_pending_state structure
1780 * Frees a pending_state structure, as well as any output_states connected
1781 * to this pending state.
1783 * @param pending_state Pending state structure to free
1786 drm_pending_state_free(struct drm_pending_state *pending_state)
1788 struct drm_output_state *output_state, *tmp;
1793 wl_list_for_each_safe(output_state, tmp, &pending_state->output_list,
1795 drm_output_state_free(output_state);
1798 free(pending_state);
1802 * Find an output state in a pending state
1804 * Given a pending_state structure, find the output_state for a particular
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
1811 static struct drm_output_state *
1812 drm_pending_state_get_output(struct drm_pending_state *pending_state,
1813 struct drm_output *output)
1815 struct drm_output_state *output_state;
1817 wl_list_for_each(output_state, &pending_state->output_list, link) {
1818 if (output_state->output == output)
1819 return output_state;
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);
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.
1834 drm_output_update_complete(struct drm_output *output, uint32_t flags,
1835 unsigned int sec, unsigned int usec)
1837 struct drm_backend *b = to_drm_backend(output->base.compositor);
1838 struct drm_plane_state *ps;
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);
1845 wl_list_for_each(ps, &output->state_cur->plane_list, link)
1846 ps->complete = true;
1848 drm_output_state_free(output->state_last);
1849 output->state_last = NULL;
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);
1857 } else if (output->disable_pending) {
1858 output->disable_pending = 0;
1859 output->dpms_off_pending = 0;
1860 weston_output_disable(&output->base);
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);
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. */
1879 ts.tv_nsec = usec * 1000;
1880 weston_output_finish_frame(&output->base, &ts, flags);
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);
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).
1895 drm_output_assign_state(struct drm_output_state *state,
1896 enum drm_state_apply_mode mode)
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;
1902 assert(!output->state_last);
1904 if (mode == DRM_STATE_APPLY_ASYNC)
1905 output->state_last = output->state_cur;
1907 drm_output_state_free(output->state_cur);
1909 wl_list_remove(&state->link);
1910 wl_list_init(&state->link);
1911 state->pending_state = NULL;
1913 output->state_cur = state;
1915 if (b->atomic_modeset && mode == DRM_STATE_APPLY_ASYNC)
1916 output->atomic_complete_pending = 1;
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;
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;
1929 if (mode != DRM_STATE_APPLY_ASYNC) {
1930 plane_state->complete = true;
1934 if (b->atomic_modeset)
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;
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 DRM_OUTPUT_PROPOSE_STATE_PLANES_ONLY, /**< no renderer use, only planes */
1950 static struct drm_plane_state *
1951 drm_output_prepare_scanout_view(struct drm_output_state *output_state,
1952 struct weston_view *ev)
1954 struct drm_output *output = output_state->output;
1955 struct drm_backend *b = to_drm_backend(output->base.compositor);
1956 struct drm_plane *scanout_plane = output->scanout_plane;
1957 struct drm_plane_state *state;
1959 pixman_box32_t *extents;
1961 assert(!b->sprites_are_broken);
1963 /* Check the view spans exactly the output size, calculated in the
1964 * logical co-ordinate space. */
1965 extents = pixman_region32_extents(&ev->transform.boundingbox);
1966 if (extents->x1 != output->base.x ||
1967 extents->y1 != output->base.y ||
1968 extents->x2 != output->base.x + output->base.width ||
1969 extents->y2 != output->base.y + output->base.height)
1972 if (ev->alpha != 1.0f)
1975 fb = drm_fb_get_from_view(output_state, ev);
1979 /* Can't change formats with just a pageflip */
1980 if (fb->format->format != output->gbm_format) {
1985 state = drm_output_state_get_plane(output_state, scanout_plane);
1987 /* If there is already a framebuffer on the scanout plane,
1988 * a client view has already been placed on the scanout
1989 * view. In that case, do not free or put back the state,
1990 * but just leave it in place and quietly exit. */
1997 state->output = output;
1998 if (!drm_plane_state_coords_for_view(state, ev))
2001 /* The legacy API does not let us perform cropping or scaling. */
2002 if (state->src_x != 0 || state->src_y != 0 ||
2003 state->src_w != state->dest_w << 16 ||
2004 state->src_h != state->dest_h << 16 ||
2005 state->dest_x != 0 || state->dest_y != 0 ||
2006 state->dest_w != (unsigned) output->base.current_mode->width ||
2007 state->dest_h != (unsigned) output->base.current_mode->height)
2013 drm_plane_state_put_back(state);
2017 static struct drm_fb *
2018 drm_output_render_gl(struct drm_output_state *state, pixman_region32_t *damage)
2020 struct drm_output *output = state->output;
2021 struct drm_backend *b = to_drm_backend(output->base.compositor);
2025 output->base.compositor->renderer->repaint_output(&output->base,
2028 bo = gbm_surface_lock_front_buffer(output->gbm_surface);
2030 weston_log("failed to lock front buffer: %m\n");
2034 /* The renderer always produces an opaque image. */
2035 ret = drm_fb_get_from_bo(bo, b, true, BUFFER_GBM_SURFACE);
2037 weston_log("failed to get drm_fb for bo\n");
2038 gbm_surface_release_buffer(output->gbm_surface, bo);
2041 ret->gbm_surface = output->gbm_surface;
2046 static struct drm_fb *
2047 drm_output_render_pixman(struct drm_output_state *state,
2048 pixman_region32_t *damage)
2050 struct drm_output *output = state->output;
2051 struct weston_compositor *ec = output->base.compositor;
2053 output->current_image ^= 1;
2055 pixman_renderer_output_set_buffer(&output->base,
2056 output->image[output->current_image]);
2057 pixman_renderer_output_set_hw_extra_damage(&output->base,
2058 &output->previous_damage);
2060 ec->renderer->repaint_output(&output->base, damage);
2062 pixman_region32_copy(&output->previous_damage, damage);
2064 return drm_fb_ref(output->dumb[output->current_image]);
2068 drm_output_render(struct drm_output_state *state, pixman_region32_t *damage)
2070 struct drm_output *output = state->output;
2071 struct weston_compositor *c = output->base.compositor;
2072 struct drm_plane_state *scanout_state;
2073 struct drm_plane *scanout_plane = output->scanout_plane;
2074 struct drm_backend *b = to_drm_backend(c);
2077 /* If we already have a client buffer promoted to scanout, then we don't
2078 * want to render. */
2079 scanout_state = drm_output_state_get_plane(state,
2080 output->scanout_plane);
2081 if (scanout_state->fb)
2084 if (!pixman_region32_not_empty(damage) &&
2085 scanout_plane->state_cur->fb &&
2086 (scanout_plane->state_cur->fb->type == BUFFER_GBM_SURFACE ||
2087 scanout_plane->state_cur->fb->type == BUFFER_PIXMAN_DUMB) &&
2088 scanout_plane->state_cur->fb->width ==
2089 output->base.current_mode->width &&
2090 scanout_plane->state_cur->fb->height ==
2091 output->base.current_mode->height) {
2092 fb = drm_fb_ref(scanout_plane->state_cur->fb);
2093 } else if (b->use_pixman) {
2094 fb = drm_output_render_pixman(state, damage);
2096 fb = drm_output_render_gl(state, damage);
2100 drm_plane_state_put_back(scanout_state);
2104 scanout_state->fb = fb;
2105 scanout_state->output = output;
2107 scanout_state->src_x = 0;
2108 scanout_state->src_y = 0;
2109 scanout_state->src_w = output->base.current_mode->width << 16;
2110 scanout_state->src_h = output->base.current_mode->height << 16;
2112 scanout_state->dest_x = 0;
2113 scanout_state->dest_y = 0;
2114 scanout_state->dest_w = scanout_state->src_w >> 16;
2115 scanout_state->dest_h = scanout_state->src_h >> 16;
2118 pixman_region32_subtract(&c->primary_plane.damage,
2119 &c->primary_plane.damage, damage);
2123 drm_output_set_gamma(struct weston_output *output_base,
2124 uint16_t size, uint16_t *r, uint16_t *g, uint16_t *b)
2127 struct drm_output *output = to_drm_output(output_base);
2128 struct drm_backend *backend =
2129 to_drm_backend(output->base.compositor);
2132 if (output_base->gamma_size != size)
2135 rc = drmModeCrtcSetGamma(backend->drm.fd,
2139 weston_log("set gamma failed: %m\n");
2142 /* Determine the type of vblank synchronization to use for the output.
2144 * The pipe parameter indicates which CRTC is in use. Knowing this, we
2145 * can determine which vblank sequence type to use for it. Traditional
2146 * cards had only two CRTCs, with CRTC 0 using no special flags, and
2147 * CRTC 1 using DRM_VBLANK_SECONDARY. The first bit of the pipe
2148 * parameter indicates this.
2150 * Bits 1-5 of the pipe parameter are 5 bit wide pipe number between
2151 * 0-31. If this is non-zero it indicates we're dealing with a
2152 * multi-gpu situation and we need to calculate the vblank sync
2153 * using DRM_BLANK_HIGH_CRTC_MASK.
2156 drm_waitvblank_pipe(struct drm_output *output)
2158 if (output->pipe > 1)
2159 return (output->pipe << DRM_VBLANK_HIGH_CRTC_SHIFT) &
2160 DRM_VBLANK_HIGH_CRTC_MASK;
2161 else if (output->pipe > 0)
2162 return DRM_VBLANK_SECONDARY;
2168 drm_output_apply_state_legacy(struct drm_output_state *state)
2170 struct drm_output *output = state->output;
2171 struct drm_backend *backend = to_drm_backend(output->base.compositor);
2172 struct drm_plane *scanout_plane = output->scanout_plane;
2173 struct drm_property_info *dpms_prop;
2174 struct drm_plane_state *scanout_state;
2175 struct drm_plane_state *ps;
2176 struct drm_mode *mode;
2177 struct drm_head *head;
2178 uint32_t connectors[MAX_CLONED_CONNECTORS];
2180 struct timespec now;
2183 wl_list_for_each(head, &output->base.head_list, base.output_link) {
2184 assert(n_conn < MAX_CLONED_CONNECTORS);
2185 connectors[n_conn++] = head->connector_id;
2188 /* If disable_planes is set then assign_planes() wasn't
2189 * called for this render, so we could still have a stale
2190 * cursor plane set up.
2192 if (output->base.disable_planes) {
2193 output->cursor_view = NULL;
2194 if (output->cursor_plane) {
2195 output->cursor_plane->base.x = INT32_MIN;
2196 output->cursor_plane->base.y = INT32_MIN;
2200 if (state->dpms != WESTON_DPMS_ON) {
2201 wl_list_for_each(ps, &state->plane_list, link) {
2202 struct drm_plane *p = ps->plane;
2203 assert(ps->fb == NULL);
2204 assert(ps->output == NULL);
2206 if (p->type != WDRM_PLANE_TYPE_OVERLAY)
2209 ret = drmModeSetPlane(backend->drm.fd, p->plane_id,
2210 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
2212 weston_log("drmModeSetPlane failed disable: %m\n");
2215 if (output->cursor_plane) {
2216 ret = drmModeSetCursor(backend->drm.fd, output->crtc_id,
2219 weston_log("drmModeSetCursor failed disable: %m\n");
2222 ret = drmModeSetCrtc(backend->drm.fd, output->crtc_id, 0, 0, 0,
2225 weston_log("drmModeSetCrtc failed disabling: %m\n");
2227 drm_output_assign_state(state, DRM_STATE_APPLY_SYNC);
2228 weston_compositor_read_presentation_clock(output->base.compositor, &now);
2229 drm_output_update_complete(output,
2230 WP_PRESENTATION_FEEDBACK_KIND_HW_COMPLETION,
2231 now.tv_sec, now.tv_nsec / 1000);
2237 drm_output_state_get_existing_plane(state, scanout_plane);
2239 /* The legacy SetCrtc API doesn't allow us to do scaling, and the
2240 * legacy PageFlip API doesn't allow us to do clipping either. */
2241 assert(scanout_state->src_x == 0);
2242 assert(scanout_state->src_y == 0);
2243 assert(scanout_state->src_w ==
2244 (unsigned) (output->base.current_mode->width << 16));
2245 assert(scanout_state->src_h ==
2246 (unsigned) (output->base.current_mode->height << 16));
2247 assert(scanout_state->dest_x == 0);
2248 assert(scanout_state->dest_y == 0);
2249 assert(scanout_state->dest_w == scanout_state->src_w >> 16);
2250 assert(scanout_state->dest_h == scanout_state->src_h >> 16);
2252 mode = to_drm_mode(output->base.current_mode);
2253 if (backend->state_invalid ||
2254 !scanout_plane->state_cur->fb ||
2255 scanout_plane->state_cur->fb->strides[0] !=
2256 scanout_state->fb->strides[0]) {
2257 ret = drmModeSetCrtc(backend->drm.fd, output->crtc_id,
2258 scanout_state->fb->fb_id,
2263 weston_log("set mode failed: %m\n");
2268 if (drmModePageFlip(backend->drm.fd, output->crtc_id,
2269 scanout_state->fb->fb_id,
2270 DRM_MODE_PAGE_FLIP_EVENT, output) < 0) {
2271 weston_log("queueing pageflip failed: %m\n");
2275 assert(!output->page_flip_pending);
2277 if (output->pageflip_timer)
2278 wl_event_source_timer_update(output->pageflip_timer,
2279 backend->pageflip_timeout);
2281 drm_output_set_cursor(state);
2284 * Now, update all the sprite surfaces
2286 wl_list_for_each(ps, &state->plane_list, link) {
2287 uint32_t flags = 0, fb_id = 0;
2289 .request.type = DRM_VBLANK_RELATIVE | DRM_VBLANK_EVENT,
2290 .request.sequence = 1,
2292 struct drm_plane *p = ps->plane;
2294 if (p->type != WDRM_PLANE_TYPE_OVERLAY)
2297 assert(p->state_cur->complete);
2298 assert(!!p->state_cur->output == !!p->state_cur->fb);
2299 assert(!p->state_cur->output || p->state_cur->output == output);
2300 assert(!ps->complete);
2301 assert(!ps->output || ps->output == output);
2302 assert(!!ps->output == !!ps->fb);
2304 if (ps->fb && !backend->sprites_hidden)
2305 fb_id = ps->fb->fb_id;
2307 ret = drmModeSetPlane(backend->drm.fd, p->plane_id,
2308 output->crtc_id, fb_id, flags,
2309 ps->dest_x, ps->dest_y,
2310 ps->dest_w, ps->dest_h,
2311 ps->src_x, ps->src_y,
2312 ps->src_w, ps->src_h);
2314 weston_log("setplane failed: %d: %s\n",
2315 ret, strerror(errno));
2317 vbl.request.type |= drm_waitvblank_pipe(output);
2320 * Queue a vblank signal so we know when the surface
2321 * becomes active on the display or has been replaced.
2323 vbl.request.signal = (unsigned long) ps;
2324 ret = drmWaitVBlank(backend->drm.fd, &vbl);
2326 weston_log("vblank event request failed: %d: %s\n",
2327 ret, strerror(errno));
2331 if (state->dpms != output->state_cur->dpms) {
2332 wl_list_for_each(head, &output->base.head_list, base.output_link) {
2333 dpms_prop = &head->props_conn[WDRM_CONNECTOR_DPMS];
2334 if (dpms_prop->prop_id == 0)
2337 ret = drmModeConnectorSetProperty(backend->drm.fd,
2342 weston_log("DRM: DPMS: failed property set for %s\n",
2348 drm_output_assign_state(state, DRM_STATE_APPLY_ASYNC);
2353 output->cursor_view = NULL;
2354 drm_output_state_free(state);
2358 #ifdef HAVE_DRM_ATOMIC
2360 crtc_add_prop(drmModeAtomicReq *req, struct drm_output *output,
2361 enum wdrm_crtc_property prop, uint64_t val)
2363 struct drm_property_info *info = &output->props_crtc[prop];
2366 if (info->prop_id == 0)
2369 ret = drmModeAtomicAddProperty(req, output->crtc_id, info->prop_id,
2371 return (ret <= 0) ? -1 : 0;
2375 connector_add_prop(drmModeAtomicReq *req, struct drm_head *head,
2376 enum wdrm_connector_property prop, uint64_t val)
2378 struct drm_property_info *info = &head->props_conn[prop];
2381 if (info->prop_id == 0)
2384 ret = drmModeAtomicAddProperty(req, head->connector_id,
2385 info->prop_id, val);
2386 return (ret <= 0) ? -1 : 0;
2390 plane_add_prop(drmModeAtomicReq *req, struct drm_plane *plane,
2391 enum wdrm_plane_property prop, uint64_t val)
2393 struct drm_property_info *info = &plane->props[prop];
2396 if (info->prop_id == 0)
2399 ret = drmModeAtomicAddProperty(req, plane->plane_id, info->prop_id,
2401 return (ret <= 0) ? -1 : 0;
2405 drm_mode_ensure_blob(struct drm_backend *backend, struct drm_mode *mode)
2412 ret = drmModeCreatePropertyBlob(backend->drm.fd,
2414 sizeof(mode->mode_info),
2417 weston_log("failed to create mode property blob: %m\n");
2423 drm_output_apply_state_atomic(struct drm_output_state *state,
2424 drmModeAtomicReq *req,
2427 struct drm_output *output = state->output;
2428 struct drm_backend *backend = to_drm_backend(output->base.compositor);
2429 struct drm_plane_state *plane_state;
2430 struct drm_mode *current_mode = to_drm_mode(output->base.current_mode);
2431 struct drm_head *head;
2434 if (state->dpms != output->state_cur->dpms)
2435 *flags |= DRM_MODE_ATOMIC_ALLOW_MODESET;
2437 if (state->dpms == WESTON_DPMS_ON) {
2438 ret = drm_mode_ensure_blob(backend, current_mode);
2442 ret |= crtc_add_prop(req, output, WDRM_CRTC_MODE_ID,
2443 current_mode->blob_id);
2444 ret |= crtc_add_prop(req, output, WDRM_CRTC_ACTIVE, 1);
2446 /* No need for the DPMS property, since it is implicit in
2447 * routing and CRTC activity. */
2448 wl_list_for_each(head, &output->base.head_list, base.output_link) {
2449 ret |= connector_add_prop(req, head, WDRM_CONNECTOR_CRTC_ID,
2453 ret |= crtc_add_prop(req, output, WDRM_CRTC_MODE_ID, 0);
2454 ret |= crtc_add_prop(req, output, WDRM_CRTC_ACTIVE, 0);
2456 /* No need for the DPMS property, since it is implicit in
2457 * routing and CRTC activity. */
2458 wl_list_for_each(head, &output->base.head_list, base.output_link)
2459 ret |= connector_add_prop(req, head, WDRM_CONNECTOR_CRTC_ID, 0);
2463 weston_log("couldn't set atomic CRTC/connector state\n");
2467 wl_list_for_each(plane_state, &state->plane_list, link) {
2468 struct drm_plane *plane = plane_state->plane;
2470 ret |= plane_add_prop(req, plane, WDRM_PLANE_FB_ID,
2471 plane_state->fb ? plane_state->fb->fb_id : 0);
2472 ret |= plane_add_prop(req, plane, WDRM_PLANE_CRTC_ID,
2473 plane_state->fb ? output->crtc_id : 0);
2474 ret |= plane_add_prop(req, plane, WDRM_PLANE_SRC_X,
2475 plane_state->src_x);
2476 ret |= plane_add_prop(req, plane, WDRM_PLANE_SRC_Y,
2477 plane_state->src_y);
2478 ret |= plane_add_prop(req, plane, WDRM_PLANE_SRC_W,
2479 plane_state->src_w);
2480 ret |= plane_add_prop(req, plane, WDRM_PLANE_SRC_H,
2481 plane_state->src_h);
2482 ret |= plane_add_prop(req, plane, WDRM_PLANE_CRTC_X,
2483 plane_state->dest_x);
2484 ret |= plane_add_prop(req, plane, WDRM_PLANE_CRTC_Y,
2485 plane_state->dest_y);
2486 ret |= plane_add_prop(req, plane, WDRM_PLANE_CRTC_W,
2487 plane_state->dest_w);
2488 ret |= plane_add_prop(req, plane, WDRM_PLANE_CRTC_H,
2489 plane_state->dest_h);
2492 weston_log("couldn't set plane state\n");
2501 * Helper function used only by drm_pending_state_apply, with the same
2502 * guarantees and constraints as that function.
2505 drm_pending_state_apply_atomic(struct drm_pending_state *pending_state,
2506 enum drm_state_apply_mode mode)
2508 struct drm_backend *b = pending_state->backend;
2509 struct drm_output_state *output_state, *tmp;
2510 struct drm_plane *plane;
2511 drmModeAtomicReq *req = drmModeAtomicAlloc();
2518 if (b->state_invalid) {
2519 struct weston_head *head_base;
2520 struct drm_head *head;
2524 /* If we need to reset all our state (e.g. because we've
2525 * just started, or just been VT-switched in), explicitly
2526 * disable all the CRTCs and connectors we aren't using. */
2527 wl_list_for_each(head_base,
2528 &b->compositor->head_list, compositor_link) {
2529 struct drm_property_info *info;
2531 if (weston_head_is_enabled(head_base))
2534 head = to_drm_head(head_base);
2536 info = &head->props_conn[WDRM_CONNECTOR_CRTC_ID];
2537 err = drmModeAtomicAddProperty(req, head->connector_id,
2543 wl_array_for_each(unused, &b->unused_crtcs) {
2544 struct drm_property_info infos[WDRM_CRTC__COUNT];
2545 struct drm_property_info *info;
2546 drmModeObjectProperties *props;
2549 memset(infos, 0, sizeof(infos));
2551 /* We can't emit a disable on a CRTC that's already
2552 * off, as the kernel will refuse to generate an event
2553 * for an off->off state and fail the commit.
2555 props = drmModeObjectGetProperties(b->drm.fd,
2557 DRM_MODE_OBJECT_CRTC);
2563 drm_property_info_populate(b, crtc_props, infos,
2567 info = &infos[WDRM_CRTC_ACTIVE];
2568 active = drm_property_get_value(info, props, 0);
2569 drmModeFreeObjectProperties(props);
2571 drm_property_info_free(infos, WDRM_CRTC__COUNT);
2575 err = drmModeAtomicAddProperty(req, *unused,
2580 info = &infos[WDRM_CRTC_MODE_ID];
2581 err = drmModeAtomicAddProperty(req, *unused,
2586 drm_property_info_free(infos, WDRM_CRTC__COUNT);
2589 /* Disable all the planes; planes which are being used will
2590 * override this state in the output-state application. */
2591 wl_list_for_each(plane, &b->plane_list, link) {
2592 plane_add_prop(req, plane, WDRM_PLANE_CRTC_ID, 0);
2593 plane_add_prop(req, plane, WDRM_PLANE_FB_ID, 0);
2596 flags |= DRM_MODE_ATOMIC_ALLOW_MODESET;
2599 wl_list_for_each(output_state, &pending_state->output_list, link) {
2600 if (mode == DRM_STATE_APPLY_SYNC)
2601 assert(output_state->dpms == WESTON_DPMS_OFF);
2602 ret |= drm_output_apply_state_atomic(output_state, req, &flags);
2606 weston_log("atomic: couldn't compile atomic state\n");
2611 case DRM_STATE_APPLY_SYNC:
2613 case DRM_STATE_APPLY_ASYNC:
2614 flags |= DRM_MODE_PAGE_FLIP_EVENT | DRM_MODE_ATOMIC_NONBLOCK;
2616 case DRM_STATE_TEST_ONLY:
2617 flags |= DRM_MODE_ATOMIC_TEST_ONLY;
2621 ret = drmModeAtomicCommit(b->drm.fd, req, flags, b);
2623 /* Test commits do not take ownership of the state; return
2624 * without freeing here. */
2625 if (mode == DRM_STATE_TEST_ONLY) {
2626 drmModeAtomicFree(req);
2631 weston_log("atomic: couldn't commit new state: %m\n");
2635 wl_list_for_each_safe(output_state, tmp, &pending_state->output_list,
2637 drm_output_assign_state(output_state, mode);
2639 b->state_invalid = false;
2641 assert(wl_list_empty(&pending_state->output_list));
2644 drmModeAtomicFree(req);
2645 drm_pending_state_free(pending_state);
2651 * Tests a pending state, to see if the kernel will accept the update as
2654 * Using atomic modesetting, the kernel performs the same checks as it would
2655 * on a real commit, returning success or failure without actually modifying
2656 * the running state. It does not return -EBUSY if there are pending updates
2657 * in flight, so states may be tested at any point, however this means a
2658 * state which passed testing may fail on a real commit if the timing is not
2659 * respected (e.g. committing before the previous commit has completed).
2661 * Without atomic modesetting, we have no way to check, so we optimistically
2662 * claim it will work.
2664 * Unlike drm_pending_state_apply() and drm_pending_state_apply_sync(), this
2665 * function does _not_ take ownership of pending_state, nor does it clear
2669 drm_pending_state_test(struct drm_pending_state *pending_state)
2671 #ifdef HAVE_DRM_ATOMIC
2672 struct drm_backend *b = pending_state->backend;
2674 if (b->atomic_modeset)
2675 return drm_pending_state_apply_atomic(pending_state,
2676 DRM_STATE_TEST_ONLY);
2679 /* We have no way to test state before application on the legacy
2680 * modesetting API, so just claim it succeeded. */
2685 * Applies all of a pending_state asynchronously: the primary entry point for
2686 * applying KMS state to a device. Updates the state for all outputs in the
2687 * pending_state, as well as disabling any unclaimed outputs.
2689 * Unconditionally takes ownership of pending_state, and clears state_invalid.
2692 drm_pending_state_apply(struct drm_pending_state *pending_state)
2694 struct drm_backend *b = pending_state->backend;
2695 struct drm_output_state *output_state, *tmp;
2698 #ifdef HAVE_DRM_ATOMIC
2699 if (b->atomic_modeset)
2700 return drm_pending_state_apply_atomic(pending_state,
2701 DRM_STATE_APPLY_ASYNC);
2704 if (b->state_invalid) {
2705 /* If we need to reset all our state (e.g. because we've
2706 * just started, or just been VT-switched in), explicitly
2707 * disable all the CRTCs we aren't using. This also disables
2708 * all connectors on these CRTCs, so we don't need to do that
2709 * separately with the pre-atomic API. */
2710 wl_array_for_each(unused, &b->unused_crtcs)
2711 drmModeSetCrtc(b->drm.fd, *unused, 0, 0, 0, NULL, 0,
2715 wl_list_for_each_safe(output_state, tmp, &pending_state->output_list,
2717 struct drm_output *output = output_state->output;
2720 ret = drm_output_apply_state_legacy(output_state);
2722 weston_log("Couldn't apply state for output %s\n",
2727 b->state_invalid = false;
2729 assert(wl_list_empty(&pending_state->output_list));
2731 drm_pending_state_free(pending_state);
2737 * The synchronous version of drm_pending_state_apply. May only be used to
2738 * disable outputs. Does so synchronously: the request is guaranteed to have
2739 * completed on return, and the output will not be touched afterwards.
2741 * Unconditionally takes ownership of pending_state, and clears state_invalid.
2744 drm_pending_state_apply_sync(struct drm_pending_state *pending_state)
2746 struct drm_backend *b = pending_state->backend;
2747 struct drm_output_state *output_state, *tmp;
2750 #ifdef HAVE_DRM_ATOMIC
2751 if (b->atomic_modeset)
2752 return drm_pending_state_apply_atomic(pending_state,
2753 DRM_STATE_APPLY_SYNC);
2756 if (b->state_invalid) {
2757 /* If we need to reset all our state (e.g. because we've
2758 * just started, or just been VT-switched in), explicitly
2759 * disable all the CRTCs we aren't using. This also disables
2760 * all connectors on these CRTCs, so we don't need to do that
2761 * separately with the pre-atomic API. */
2762 wl_array_for_each(unused, &b->unused_crtcs)
2763 drmModeSetCrtc(b->drm.fd, *unused, 0, 0, 0, NULL, 0,
2767 wl_list_for_each_safe(output_state, tmp, &pending_state->output_list,
2771 assert(output_state->dpms == WESTON_DPMS_OFF);
2772 ret = drm_output_apply_state_legacy(output_state);
2774 weston_log("Couldn't apply state for output %s\n",
2775 output_state->output->base.name);
2779 b->state_invalid = false;
2781 assert(wl_list_empty(&pending_state->output_list));
2783 drm_pending_state_free(pending_state);
2789 drm_output_repaint(struct weston_output *output_base,
2790 pixman_region32_t *damage,
2793 struct drm_pending_state *pending_state = repaint_data;
2794 struct drm_output *output = to_drm_output(output_base);
2795 struct drm_output_state *state = NULL;
2796 struct drm_plane_state *scanout_state;
2798 if (output->disable_pending || output->destroy_pending)
2801 assert(!output->state_last);
2803 /* If planes have been disabled in the core, we might not have
2804 * hit assign_planes at all, so might not have valid output state
2806 state = drm_pending_state_get_output(pending_state, output);
2808 state = drm_output_state_duplicate(output->state_cur,
2810 DRM_OUTPUT_STATE_CLEAR_PLANES);
2811 state->dpms = WESTON_DPMS_ON;
2813 drm_output_render(state, damage);
2814 scanout_state = drm_output_state_get_plane(state,
2815 output->scanout_plane);
2816 if (!scanout_state || !scanout_state->fb)
2822 drm_output_state_free(state);
2827 drm_output_start_repaint_loop(struct weston_output *output_base)
2829 struct drm_output *output = to_drm_output(output_base);
2830 struct drm_pending_state *pending_state;
2831 struct drm_plane *scanout_plane = output->scanout_plane;
2832 struct drm_backend *backend =
2833 to_drm_backend(output_base->compositor);
2834 struct timespec ts, tnow;
2835 struct timespec vbl2now;
2836 int64_t refresh_nsec;
2839 .request.type = DRM_VBLANK_RELATIVE,
2840 .request.sequence = 0,
2841 .request.signal = 0,
2844 if (output->disable_pending || output->destroy_pending)
2847 if (!output->scanout_plane->state_cur->fb) {
2848 /* We can't page flip if there's no mode set */
2852 /* Need to smash all state in from scratch; current timings might not
2853 * be what we want, page flip might not work, etc.
2855 if (backend->state_invalid)
2858 assert(scanout_plane->state_cur->output == output);
2860 /* Try to get current msc and timestamp via instant query */
2861 vbl.request.type |= drm_waitvblank_pipe(output);
2862 ret = drmWaitVBlank(backend->drm.fd, &vbl);
2864 /* Error ret or zero timestamp means failure to get valid timestamp */
2865 if ((ret == 0) && (vbl.reply.tval_sec > 0 || vbl.reply.tval_usec > 0)) {
2866 ts.tv_sec = vbl.reply.tval_sec;
2867 ts.tv_nsec = vbl.reply.tval_usec * 1000;
2869 /* Valid timestamp for most recent vblank - not stale?
2870 * Stale ts could happen on Linux 3.17+, so make sure it
2871 * is not older than 1 refresh duration since now.
2873 weston_compositor_read_presentation_clock(backend->compositor,
2875 timespec_sub(&vbl2now, &tnow, &ts);
2877 millihz_to_nsec(output->base.current_mode->refresh);
2878 if (timespec_to_nsec(&vbl2now) < refresh_nsec) {
2879 drm_output_update_msc(output, vbl.reply.sequence);
2880 weston_output_finish_frame(output_base, &ts,
2881 WP_PRESENTATION_FEEDBACK_INVALID);
2886 /* Immediate query didn't provide valid timestamp.
2887 * Use pageflip fallback.
2890 assert(!output->page_flip_pending);
2891 assert(!output->state_last);
2893 pending_state = drm_pending_state_alloc(backend);
2894 drm_output_state_duplicate(output->state_cur, pending_state,
2895 DRM_OUTPUT_STATE_PRESERVE_PLANES);
2897 ret = drm_pending_state_apply(pending_state);
2899 weston_log("applying repaint-start state failed: %m\n");
2906 /* if we cannot page-flip, immediately finish frame */
2907 weston_output_finish_frame(output_base, NULL,
2908 WP_PRESENTATION_FEEDBACK_INVALID);
2912 drm_output_update_msc(struct drm_output *output, unsigned int seq)
2914 uint64_t msc_hi = output->base.msc >> 32;
2916 if (seq < (output->base.msc & 0xffffffff))
2919 output->base.msc = (msc_hi << 32) + seq;
2923 vblank_handler(int fd, unsigned int frame, unsigned int sec, unsigned int usec,
2926 struct drm_plane_state *ps = (struct drm_plane_state *) data;
2927 struct drm_output_state *os = ps->output_state;
2928 struct drm_output *output = os->output;
2929 struct drm_backend *b = to_drm_backend(output->base.compositor);
2930 uint32_t flags = WP_PRESENTATION_FEEDBACK_KIND_HW_COMPLETION |
2931 WP_PRESENTATION_FEEDBACK_KIND_HW_CLOCK;
2933 assert(!b->atomic_modeset);
2935 drm_output_update_msc(output, frame);
2936 output->vblank_pending--;
2937 assert(output->vblank_pending >= 0);
2941 if (output->page_flip_pending || output->vblank_pending)
2944 drm_output_update_complete(output, flags, sec, usec);
2948 page_flip_handler(int fd, unsigned int frame,
2949 unsigned int sec, unsigned int usec, void *data)
2951 struct drm_output *output = data;
2952 struct drm_backend *b = to_drm_backend(output->base.compositor);
2953 uint32_t flags = WP_PRESENTATION_FEEDBACK_KIND_VSYNC |
2954 WP_PRESENTATION_FEEDBACK_KIND_HW_COMPLETION |
2955 WP_PRESENTATION_FEEDBACK_KIND_HW_CLOCK;
2957 drm_output_update_msc(output, frame);
2959 assert(!b->atomic_modeset);
2960 assert(output->page_flip_pending);
2961 output->page_flip_pending = 0;
2963 if (output->vblank_pending)
2966 drm_output_update_complete(output, flags, sec, usec);
2970 * Begin a new repaint cycle
2972 * Called by the core compositor at the beginning of a repaint cycle. Creates
2973 * a new pending_state structure to own any output state created by individual
2974 * output repaint functions until the repaint is flushed or cancelled.
2977 drm_repaint_begin(struct weston_compositor *compositor)
2979 struct drm_backend *b = to_drm_backend(compositor);
2980 struct drm_pending_state *ret;
2982 ret = drm_pending_state_alloc(b);
2983 b->repaint_data = ret;
2989 * Flush a repaint set
2991 * Called by the core compositor when a repaint cycle has been completed
2992 * and should be flushed. Frees the pending state, transitioning ownership
2993 * of the output state from the pending state, to the update itself. When
2994 * the update completes (see drm_output_update_complete), the output
2995 * state will be freed.
2998 drm_repaint_flush(struct weston_compositor *compositor, void *repaint_data)
3000 struct drm_backend *b = to_drm_backend(compositor);
3001 struct drm_pending_state *pending_state = repaint_data;
3003 drm_pending_state_apply(pending_state);
3004 b->repaint_data = NULL;
3008 * Cancel a repaint set
3010 * Called by the core compositor when a repaint has finished, so the data
3011 * held across the repaint cycle should be discarded.
3014 drm_repaint_cancel(struct weston_compositor *compositor, void *repaint_data)
3016 struct drm_backend *b = to_drm_backend(compositor);
3017 struct drm_pending_state *pending_state = repaint_data;
3019 drm_pending_state_free(pending_state);
3020 b->repaint_data = NULL;
3023 #ifdef HAVE_DRM_ATOMIC
3025 atomic_flip_handler(int fd, unsigned int frame, unsigned int sec,
3026 unsigned int usec, unsigned int crtc_id, void *data)
3028 struct drm_backend *b = data;
3029 struct drm_output *output = drm_output_find_by_crtc(b, crtc_id);
3030 uint32_t flags = WP_PRESENTATION_FEEDBACK_KIND_VSYNC |
3031 WP_PRESENTATION_FEEDBACK_KIND_HW_COMPLETION |
3032 WP_PRESENTATION_FEEDBACK_KIND_HW_CLOCK;
3034 /* During the initial modeset, we can disable CRTCs which we don't
3035 * actually handle during normal operation; this will give us events
3036 * for unknown outputs. Ignore them. */
3037 if (!output || !output->base.enabled)
3040 drm_output_update_msc(output, frame);
3042 assert(b->atomic_modeset);
3043 assert(output->atomic_complete_pending);
3044 output->atomic_complete_pending = 0;
3046 drm_output_update_complete(output, flags, sec, usec);
3050 static struct drm_plane_state *
3051 drm_output_prepare_overlay_view(struct drm_output_state *output_state,
3052 struct weston_view *ev)
3054 struct drm_output *output = output_state->output;
3055 struct weston_compositor *ec = output->base.compositor;
3056 struct drm_backend *b = to_drm_backend(ec);
3057 struct drm_plane *p;
3058 struct drm_plane_state *state = NULL;
3062 assert(!b->sprites_are_broken);
3064 fb = drm_fb_get_from_view(output_state, ev);
3068 wl_list_for_each(p, &b->plane_list, link) {
3069 if (p->type != WDRM_PLANE_TYPE_OVERLAY)
3072 if (!drm_plane_is_available(p, output))
3075 /* Check whether the format is supported */
3076 for (i = 0; i < p->count_formats; i++) {
3079 if (p->formats[i].format != fb->format->format)
3082 if (fb->modifier == DRM_FORMAT_MOD_INVALID)
3085 for (j = 0; j < p->formats[i].count_modifiers; j++) {
3086 if (p->formats[i].modifiers[j] == fb->modifier)
3089 if (j != p->formats[i].count_modifiers)
3092 if (i == p->count_formats)
3095 state = drm_output_state_get_plane(output_state, p);
3104 /* No sprites available */
3112 state->output = output;
3114 if (!drm_plane_state_coords_for_view(state, ev))
3117 if (state->src_w != state->dest_w << 16 ||
3118 state->src_h != state->dest_h << 16)
3124 drm_plane_state_put_back(state);
3129 * Update the image for the current cursor surface
3131 * @param plane_state DRM cursor plane state
3132 * @param ev Source view for cursor
3135 cursor_bo_update(struct drm_plane_state *plane_state, struct weston_view *ev)
3137 struct drm_backend *b = plane_state->plane->backend;
3138 struct gbm_bo *bo = plane_state->fb->bo;
3139 struct weston_buffer *buffer = ev->surface->buffer_ref.buffer;
3140 uint32_t buf[b->cursor_width * b->cursor_height];
3145 assert(buffer && buffer->shm_buffer);
3146 assert(buffer->shm_buffer == wl_shm_buffer_get(buffer->resource));
3147 assert(buffer->width <= b->cursor_width);
3148 assert(buffer->height <= b->cursor_height);
3150 memset(buf, 0, sizeof buf);
3151 stride = wl_shm_buffer_get_stride(buffer->shm_buffer);
3152 s = wl_shm_buffer_get_data(buffer->shm_buffer);
3154 wl_shm_buffer_begin_access(buffer->shm_buffer);
3155 for (i = 0; i < buffer->height; i++)
3156 memcpy(buf + i * b->cursor_width,
3159 wl_shm_buffer_end_access(buffer->shm_buffer);
3161 if (gbm_bo_write(bo, buf, sizeof buf) < 0)
3162 weston_log("failed update cursor: %m\n");
3165 static struct drm_plane_state *
3166 drm_output_prepare_cursor_view(struct drm_output_state *output_state,
3167 struct weston_view *ev)
3169 struct drm_output *output = output_state->output;
3170 struct drm_backend *b = to_drm_backend(output->base.compositor);
3171 struct drm_plane *plane = output->cursor_plane;
3172 struct drm_plane_state *plane_state;
3173 struct wl_shm_buffer *shmbuf;
3174 bool needs_update = false;
3176 assert(!b->cursors_are_broken);
3181 if (!plane->state_cur->complete)
3184 if (plane->state_cur->output && plane->state_cur->output != output)
3187 /* We use GBM to import SHM buffers. */
3191 if (ev->surface->buffer_ref.buffer == NULL)
3193 shmbuf = wl_shm_buffer_get(ev->surface->buffer_ref.buffer->resource);
3196 if (wl_shm_buffer_get_format(shmbuf) != WL_SHM_FORMAT_ARGB8888)
3200 drm_output_state_get_plane(output_state, output->cursor_plane);
3202 if (plane_state && plane_state->fb)
3205 /* We can't scale with the legacy API, and we don't try to account for
3206 * simple cropping/translation in cursor_bo_update. */
3207 plane_state->output = output;
3208 if (!drm_plane_state_coords_for_view(plane_state, ev))
3211 if (plane_state->src_x != 0 || plane_state->src_y != 0 ||
3212 plane_state->src_w > (unsigned) b->cursor_width << 16 ||
3213 plane_state->src_h > (unsigned) b->cursor_height << 16 ||
3214 plane_state->src_w != plane_state->dest_w << 16 ||
3215 plane_state->src_h != plane_state->dest_h << 16)
3218 /* Since we're setting plane state up front, we need to work out
3219 * whether or not we need to upload a new cursor. We can't use the
3220 * plane damage, since the planes haven't actually been calculated
3221 * yet: instead try to figure it out directly. KMS cursor planes are
3222 * pretty unique here, in that they lie partway between a Weston plane
3223 * (direct scanout) and a renderer. */
3224 if (ev != output->cursor_view ||
3225 pixman_region32_not_empty(&ev->surface->damage)) {
3226 output->current_cursor++;
3227 output->current_cursor =
3228 output->current_cursor %
3229 ARRAY_LENGTH(output->gbm_cursor_fb);
3230 needs_update = true;
3233 output->cursor_view = ev;
3234 plane_state->ev = ev;
3237 drm_fb_ref(output->gbm_cursor_fb[output->current_cursor]);
3240 cursor_bo_update(plane_state, ev);
3242 /* The cursor API is somewhat special: in cursor_bo_update(), we upload
3243 * a buffer which is always cursor_width x cursor_height, even if the
3244 * surface we want to promote is actually smaller than this. Manually
3245 * mangle the plane state to deal with this. */
3246 plane_state->src_w = b->cursor_width << 16;
3247 plane_state->src_h = b->cursor_height << 16;
3248 plane_state->dest_w = b->cursor_width;
3249 plane_state->dest_h = b->cursor_height;
3254 drm_plane_state_put_back(plane_state);
3259 drm_output_set_cursor(struct drm_output_state *output_state)
3261 struct drm_output *output = output_state->output;
3262 struct drm_backend *b = to_drm_backend(output->base.compositor);
3263 struct drm_plane *plane = output->cursor_plane;
3264 struct drm_plane_state *state;
3271 state = drm_output_state_get_existing_plane(output_state, plane);
3276 pixman_region32_fini(&plane->base.damage);
3277 pixman_region32_init(&plane->base.damage);
3278 drmModeSetCursor(b->drm.fd, output->crtc_id, 0, 0, 0);
3282 assert(state->fb == output->gbm_cursor_fb[output->current_cursor]);
3283 assert(!plane->state_cur->output || plane->state_cur->output == output);
3285 if (plane->state_cur->fb != state->fb) {
3287 handle = gbm_bo_get_handle(bo).s32;
3288 if (drmModeSetCursor(b->drm.fd, output->crtc_id, handle,
3289 b->cursor_width, b->cursor_height)) {
3290 weston_log("failed to set cursor: %m\n");
3295 pixman_region32_fini(&plane->base.damage);
3296 pixman_region32_init(&plane->base.damage);
3298 if (drmModeMoveCursor(b->drm.fd, output->crtc_id,
3299 state->dest_x, state->dest_y)) {
3300 weston_log("failed to move cursor: %m\n");
3307 b->cursors_are_broken = 1;
3308 drmModeSetCursor(b->drm.fd, output->crtc_id, 0, 0, 0);
3311 static struct drm_output_state *
3312 drm_output_propose_state(struct weston_output *output_base,
3313 struct drm_pending_state *pending_state,
3314 enum drm_output_propose_state_mode mode)
3316 struct drm_output *output = to_drm_output(output_base);
3317 struct drm_backend *b = to_drm_backend(output->base.compositor);
3318 struct drm_output_state *state;
3319 struct weston_view *ev;
3320 pixman_region32_t surface_overlap, renderer_region, occluded_region;
3321 bool planes_ok = (mode != DRM_OUTPUT_PROPOSE_STATE_RENDERER_ONLY);
3322 bool renderer_ok = (mode != DRM_OUTPUT_PROPOSE_STATE_PLANES_ONLY);
3325 assert(!output->state_last);
3326 state = drm_output_state_duplicate(output->state_cur,
3328 DRM_OUTPUT_STATE_CLEAR_PLANES);
3331 * Find a surface for each sprite in the output using some heuristics:
3333 * 2) frequency of update
3334 * 3) opacity (though some hw might support alpha blending)
3335 * 4) clipping (this can be fixed with color keys)
3337 * The idea is to save on blitting since this should save power.
3338 * If we can get a large video surface on the sprite for example,
3339 * the main display surface may not need to update at all, and
3340 * the client buffer can be used directly for the sprite surface
3341 * as we do for flipping full screen surfaces.
3343 pixman_region32_init(&renderer_region);
3344 pixman_region32_init(&occluded_region);
3346 wl_list_for_each(ev, &output_base->compositor->view_list, link) {
3347 struct drm_plane_state *ps = NULL;
3348 bool force_renderer = false;
3349 pixman_region32_t clipped_view;
3350 bool occluded = false;
3352 /* If this view doesn't touch our output at all, there's no
3353 * reason to do anything with it. */
3354 if (!(ev->output_mask & (1u << output->base.id)))
3357 /* We only assign planes to views which are exclusively present
3359 if (ev->output_mask != (1u << output->base.id))
3360 force_renderer = true;
3362 if (!ev->surface->buffer_ref.buffer)
3363 force_renderer = true;
3365 /* Ignore views we know to be totally occluded. */
3366 pixman_region32_init(&clipped_view);
3367 pixman_region32_intersect(&clipped_view,
3368 &ev->transform.boundingbox,
3369 &output->base.region);
3371 pixman_region32_init(&surface_overlap);
3372 pixman_region32_subtract(&surface_overlap, &clipped_view,
3374 occluded = !pixman_region32_not_empty(&surface_overlap);
3376 pixman_region32_fini(&surface_overlap);
3377 pixman_region32_fini(&clipped_view);
3381 /* Since we process views from top to bottom, we know that if
3382 * the view intersects the calculated renderer region, it must
3383 * be part of, or occluded by, it, and cannot go on a plane. */
3384 pixman_region32_intersect(&surface_overlap, &renderer_region,
3386 if (pixman_region32_not_empty(&surface_overlap))
3387 force_renderer = true;
3389 /* We do not control the stacking order of overlay planes;
3390 * the scanout plane is strictly stacked bottom and the cursor
3391 * plane top, but the ordering of overlay planes with respect
3392 * to each other is undefined. Make sure we do not have two
3393 * planes overlapping each other. */
3394 pixman_region32_intersect(&surface_overlap, &occluded_region,
3396 if (pixman_region32_not_empty(&surface_overlap))
3397 force_renderer = true;
3398 pixman_region32_fini(&surface_overlap);
3400 /* The cursor plane is 'special' in the sense that we can still
3401 * place it in the legacy API, and we gate that with a separate
3402 * cursors_are_broken flag. */
3403 if (!force_renderer && !b->cursors_are_broken)
3404 ps = drm_output_prepare_cursor_view(state, ev);
3406 /* If sprites are disabled or the view is not fully opaque, we
3407 * must put the view into the renderer - unless it has already
3408 * been placed in the cursor plane, which can handle alpha. */
3409 if (!ps && !planes_ok)
3410 force_renderer = true;
3411 if (!ps && !drm_view_is_opaque(ev))
3412 force_renderer = true;
3414 if (!ps && !force_renderer)
3415 ps = drm_output_prepare_scanout_view(state, ev);
3416 if (!ps && !force_renderer)
3417 ps = drm_output_prepare_overlay_view(state, ev);
3420 /* If we have been assigned to an overlay or scanout
3421 * plane, add this area to the occluded region, so
3422 * other views are known to be behind it. The cursor
3423 * plane, however, is special, in that it blends with
3424 * the content underneath it: the area should neither
3425 * be added to the renderer region nor the occluded
3427 if (ps->plane->type != WDRM_PLANE_TYPE_CURSOR) {
3428 pixman_region32_union(&occluded_region,
3431 pixman_region32_fini(&clipped_view);
3436 /* We have been assigned to the primary (renderer) plane:
3437 * check if this is OK, and add ourselves to the renderer
3440 pixman_region32_fini(&clipped_view);
3444 pixman_region32_union(&renderer_region,
3447 pixman_region32_fini(&clipped_view);
3449 pixman_region32_fini(&renderer_region);
3450 pixman_region32_fini(&occluded_region);
3452 /* Check to see if this state will actually work. */
3453 ret = drm_pending_state_test(state->pending_state);
3460 pixman_region32_fini(&renderer_region);
3461 pixman_region32_fini(&occluded_region);
3463 drm_output_state_free(state);
3468 drm_assign_planes(struct weston_output *output_base, void *repaint_data)
3470 struct drm_backend *b = to_drm_backend(output_base->compositor);
3471 struct drm_pending_state *pending_state = repaint_data;
3472 struct drm_output *output = to_drm_output(output_base);
3473 struct drm_output_state *state = NULL;
3474 struct drm_plane_state *plane_state;
3475 struct weston_view *ev;
3476 struct weston_plane *primary = &output_base->compositor->primary_plane;
3478 if (!b->sprites_are_broken) {
3479 state = drm_output_propose_state(output_base, pending_state,
3480 DRM_OUTPUT_PROPOSE_STATE_PLANES_ONLY);
3482 state = drm_output_propose_state(output_base, pending_state,
3483 DRM_OUTPUT_PROPOSE_STATE_MIXED);
3487 state = drm_output_propose_state(output_base, pending_state,
3488 DRM_OUTPUT_PROPOSE_STATE_RENDERER_ONLY);
3492 wl_list_for_each(ev, &output_base->compositor->view_list, link) {
3493 struct drm_plane *target_plane = NULL;
3495 /* If this view doesn't touch our output at all, there's no
3496 * reason to do anything with it. */
3497 if (!(ev->output_mask & (1u << output->base.id)))
3500 /* Test whether this buffer can ever go into a plane:
3501 * non-shm, or small enough to be a cursor.
3503 * Also, keep a reference when using the pixman renderer.
3504 * That makes it possible to do a seamless switch to the GL
3505 * renderer and since the pixman renderer keeps a reference
3506 * to the buffer anyway, there is no side effects.
3508 if (b->use_pixman ||
3509 (ev->surface->buffer_ref.buffer &&
3510 (!wl_shm_buffer_get(ev->surface->buffer_ref.buffer->resource) ||
3511 (ev->surface->width <= b->cursor_width &&
3512 ev->surface->height <= b->cursor_height))))
3513 ev->surface->keep_buffer = true;
3515 ev->surface->keep_buffer = false;
3517 /* This is a bit unpleasant, but lacking a temporary place to
3518 * hang a plane off the view, we have to do a nested walk.
3519 * Our first-order iteration has to be planes rather than
3520 * views, because otherwise we won't reset views which were
3521 * previously on planes to being on the primary plane. */
3522 wl_list_for_each(plane_state, &state->plane_list, link) {
3523 if (plane_state->ev == ev) {
3524 plane_state->ev = NULL;
3525 target_plane = plane_state->plane;
3531 weston_view_move_to_plane(ev, &target_plane->base);
3533 weston_view_move_to_plane(ev, primary);
3535 if (!target_plane ||
3536 target_plane->type == WDRM_PLANE_TYPE_CURSOR) {
3537 /* cursor plane & renderer involve a copy */
3540 /* All other planes are a direct scanout of a
3541 * single client buffer.
3543 ev->psf_flags = WP_PRESENTATION_FEEDBACK_KIND_ZERO_COPY;
3547 /* We rely on output->cursor_view being both an accurate reflection of
3548 * the cursor plane's state, but also being maintained across repaints
3549 * to avoid unnecessary damage uploads, per the comment in
3550 * drm_output_prepare_cursor_view. In the event that we go from having
3551 * a cursor view to not having a cursor view, we need to clear it. */
3552 if (output->cursor_view) {
3554 drm_output_state_get_existing_plane(state,
3555 output->cursor_plane);
3556 if (!plane_state || !plane_state->fb)
3557 output->cursor_view = NULL;
3562 * Get the aspect-ratio from drmModeModeInfo mode flags.
3564 * @param drm_mode_flags- flags from drmModeModeInfo structure.
3565 * @returns aspect-ratio as encoded in enum 'weston_mode_aspect_ratio'.
3567 static enum weston_mode_aspect_ratio
3568 drm_to_weston_mode_aspect_ratio(uint32_t drm_mode_flags)
3570 return (drm_mode_flags & DRM_MODE_FLAG_PIC_AR_MASK) >>
3571 DRM_MODE_FLAG_PIC_AR_BITS_POS;
3575 aspect_ratio_to_string(enum weston_mode_aspect_ratio ratio)
3577 if (ratio < 0 || ratio >= ARRAY_LENGTH(aspect_ratio_as_string) ||
3578 !aspect_ratio_as_string[ratio])
3579 return " (unknown aspect ratio)";
3581 return aspect_ratio_as_string[ratio];
3585 * Find the closest-matching mode for a given target
3587 * Given a target mode, find the most suitable mode amongst the output's
3588 * current mode list to use, preferring the current mode if possible, to
3589 * avoid an expensive mode switch.
3591 * @param output DRM output
3592 * @param target_mode Mode to attempt to match
3593 * @returns Pointer to a mode from the output's mode list
3595 static struct drm_mode *
3596 choose_mode (struct drm_output *output, struct weston_mode *target_mode)
3598 struct drm_mode *tmp_mode = NULL, *mode_fall_back = NULL, *mode;
3599 enum weston_mode_aspect_ratio src_aspect = WESTON_MODE_PIC_AR_NONE;
3600 enum weston_mode_aspect_ratio target_aspect = WESTON_MODE_PIC_AR_NONE;
3601 struct drm_backend *b;
3603 b = to_drm_backend(output->base.compositor);
3604 target_aspect = target_mode->aspect_ratio;
3605 src_aspect = output->base.current_mode->aspect_ratio;
3606 if (output->base.current_mode->width == target_mode->width &&
3607 output->base.current_mode->height == target_mode->height &&
3608 (output->base.current_mode->refresh == target_mode->refresh ||
3609 target_mode->refresh == 0)) {
3610 if (!b->aspect_ratio_supported || src_aspect == target_aspect)
3611 return to_drm_mode(output->base.current_mode);
3614 wl_list_for_each(mode, &output->base.mode_list, base.link) {
3616 src_aspect = mode->base.aspect_ratio;
3617 if (mode->mode_info.hdisplay == target_mode->width &&
3618 mode->mode_info.vdisplay == target_mode->height) {
3619 if (mode->base.refresh == target_mode->refresh ||
3620 target_mode->refresh == 0) {
3621 if (!b->aspect_ratio_supported ||
3622 src_aspect == target_aspect)
3624 else if (!mode_fall_back)
3625 mode_fall_back = mode;
3626 } else if (!tmp_mode) {
3633 return mode_fall_back;
3639 drm_output_init_egl(struct drm_output *output, struct drm_backend *b);
3641 drm_output_fini_egl(struct drm_output *output);
3643 drm_output_init_pixman(struct drm_output *output, struct drm_backend *b);
3645 drm_output_fini_pixman(struct drm_output *output);
3648 drm_output_switch_mode(struct weston_output *output_base, struct weston_mode *mode)
3650 struct drm_output *output = to_drm_output(output_base);
3651 struct drm_backend *b = to_drm_backend(output_base->compositor);
3652 struct drm_mode *drm_mode = choose_mode(output, mode);
3655 weston_log("%s: invalid resolution %dx%d\n",
3656 output_base->name, mode->width, mode->height);
3660 if (&drm_mode->base == output->base.current_mode)
3663 output->base.current_mode->flags = 0;
3665 output->base.current_mode = &drm_mode->base;
3666 output->base.current_mode->flags =
3667 WL_OUTPUT_MODE_CURRENT | WL_OUTPUT_MODE_PREFERRED;
3669 /* XXX: This drops our current buffer too early, before we've started
3670 * displaying it. Ideally this should be much more atomic and
3671 * integrated with a full repaint cycle, rather than doing a
3672 * sledgehammer modeswitch first, and only later showing new
3675 b->state_invalid = true;
3677 if (b->use_pixman) {
3678 drm_output_fini_pixman(output);
3679 if (drm_output_init_pixman(output, b) < 0) {
3680 weston_log("failed to init output pixman state with "
3685 drm_output_fini_egl(output);
3686 if (drm_output_init_egl(output, b) < 0) {
3687 weston_log("failed to init output egl state with "
3697 on_drm_input(int fd, uint32_t mask, void *data)
3699 #ifdef HAVE_DRM_ATOMIC
3700 struct drm_backend *b = data;
3702 drmEventContext evctx;
3704 memset(&evctx, 0, sizeof evctx);
3705 #ifndef HAVE_DRM_ATOMIC
3709 if (b->atomic_modeset)
3710 evctx.page_flip_handler2 = atomic_flip_handler;
3713 evctx.page_flip_handler = page_flip_handler;
3714 evctx.vblank_handler = vblank_handler;
3715 drmHandleEvent(fd, &evctx);
3721 init_kms_caps(struct drm_backend *b)
3727 weston_log("using %s\n", b->drm.filename);
3729 ret = drmGetCap(b->drm.fd, DRM_CAP_TIMESTAMP_MONOTONIC, &cap);
3730 if (ret == 0 && cap == 1)
3731 clk_id = CLOCK_MONOTONIC;
3733 clk_id = CLOCK_REALTIME;
3735 if (weston_compositor_set_presentation_clock(b->compositor, clk_id) < 0) {
3736 weston_log("Error: failed to set presentation clock %d.\n",
3741 ret = drmGetCap(b->drm.fd, DRM_CAP_CURSOR_WIDTH, &cap);
3743 b->cursor_width = cap;
3745 b->cursor_width = 64;
3747 ret = drmGetCap(b->drm.fd, DRM_CAP_CURSOR_HEIGHT, &cap);
3749 b->cursor_height = cap;
3751 b->cursor_height = 64;
3753 if (!getenv("WESTON_DISABLE_UNIVERSAL_PLANES")) {
3754 ret = drmSetClientCap(b->drm.fd, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1);
3755 b->universal_planes = (ret == 0);
3757 weston_log("DRM: %s universal planes\n",
3758 b->universal_planes ? "supports" : "does not support");
3760 #ifdef HAVE_DRM_ATOMIC
3761 if (b->universal_planes && !getenv("WESTON_DISABLE_ATOMIC")) {
3762 ret = drmGetCap(b->drm.fd, DRM_CAP_CRTC_IN_VBLANK_EVENT, &cap);
3765 ret = drmSetClientCap(b->drm.fd, DRM_CLIENT_CAP_ATOMIC, 1);
3766 b->atomic_modeset = ((ret == 0) && (cap == 1));
3769 weston_log("DRM: %s atomic modesetting\n",
3770 b->atomic_modeset ? "supports" : "does not support");
3772 ret = drmSetClientCap(b->drm.fd, DRM_CLIENT_CAP_ASPECT_RATIO, 1);
3773 b->aspect_ratio_supported = (ret == 0);
3774 weston_log("DRM: %s picture aspect ratio\n",
3775 b->aspect_ratio_supported ? "supports" : "does not support");
3780 static struct gbm_device *
3781 create_gbm_device(int fd)
3783 struct gbm_device *gbm;
3785 gl_renderer = weston_load_module("gl-renderer.so",
3786 "gl_renderer_interface");
3790 /* GBM will load a dri driver, but even though they need symbols from
3791 * libglapi, in some version of Mesa they are not linked to it. Since
3792 * only the gl-renderer module links to it, the call above won't make
3793 * these symbols globally available, and loading the DRI driver fails.
3794 * Workaround this by dlopen()'ing libglapi with RTLD_GLOBAL. */
3795 dlopen("libglapi.so.0", RTLD_LAZY | RTLD_GLOBAL);
3797 gbm = gbm_create_device(fd);
3802 /* When initializing EGL, if the preferred buffer format isn't available
3803 * we may be able to substitute an ARGB format for an XRGB one.
3805 * This returns 0 if substitution isn't possible, but 0 might be a
3806 * legitimate format for other EGL platforms, so the caller is
3807 * responsible for checking for 0 before calling gl_renderer->create().
3809 * This works around https://bugs.freedesktop.org/show_bug.cgi?id=89689
3810 * but it's entirely possible we'll see this again on other implementations.
3813 fallback_format_for(uint32_t format)
3816 case GBM_FORMAT_XRGB8888:
3817 return GBM_FORMAT_ARGB8888;
3818 case GBM_FORMAT_XRGB2101010:
3819 return GBM_FORMAT_ARGB2101010;
3826 drm_backend_create_gl_renderer(struct drm_backend *b)
3828 EGLint format[3] = {
3830 fallback_format_for(b->gbm_format),
3837 if (gl_renderer->display_create(b->compositor,
3838 EGL_PLATFORM_GBM_KHR,
3841 gl_renderer->opaque_attribs,
3851 init_egl(struct drm_backend *b)
3853 b->gbm = create_gbm_device(b->drm.fd);
3858 if (drm_backend_create_gl_renderer(b) < 0) {
3859 gbm_device_destroy(b->gbm);
3867 init_pixman(struct drm_backend *b)
3869 return pixman_renderer_init(b->compositor);
3872 #ifdef HAVE_DRM_FORMATS_BLOB
3873 static inline uint32_t *
3874 formats_ptr(struct drm_format_modifier_blob *blob)
3876 return (uint32_t *)(((char *)blob) + blob->formats_offset);
3879 static inline struct drm_format_modifier *
3880 modifiers_ptr(struct drm_format_modifier_blob *blob)
3882 return (struct drm_format_modifier *)
3883 (((char *)blob) + blob->modifiers_offset);
3888 * Populates the plane's formats array, using either the IN_FORMATS blob
3889 * property (if available), or the plane's format list if not.
3892 drm_plane_populate_formats(struct drm_plane *plane, const drmModePlane *kplane,
3893 const drmModeObjectProperties *props)
3896 #ifdef HAVE_DRM_FORMATS_BLOB
3897 drmModePropertyBlobRes *blob;
3898 struct drm_format_modifier_blob *fmt_mod_blob;
3899 struct drm_format_modifier *blob_modifiers;
3900 uint32_t *blob_formats;
3903 blob_id = drm_property_get_value(&plane->props[WDRM_PLANE_IN_FORMATS],
3909 blob = drmModeGetPropertyBlob(plane->backend->drm.fd, blob_id);
3913 fmt_mod_blob = blob->data;
3914 blob_formats = formats_ptr(fmt_mod_blob);
3915 blob_modifiers = modifiers_ptr(fmt_mod_blob);
3917 if (plane->count_formats != fmt_mod_blob->count_formats) {
3918 weston_log("DRM backend: format count differs between "
3919 "plane (%d) and IN_FORMATS (%d)\n",
3920 plane->count_formats,
3921 fmt_mod_blob->count_formats);
3922 weston_log("This represents a kernel bug; Weston is "
3923 "unable to continue.\n");
3927 for (i = 0; i < fmt_mod_blob->count_formats; i++) {
3928 uint32_t count_modifiers = 0;
3929 uint64_t *modifiers = NULL;
3932 for (j = 0; j < fmt_mod_blob->count_modifiers; j++) {
3933 struct drm_format_modifier *mod = &blob_modifiers[j];
3935 if ((i < mod->offset) || (i > mod->offset + 63))
3937 if (!(mod->formats & (1 << (i - mod->offset))))
3940 modifiers = realloc(modifiers,
3941 (count_modifiers + 1) *
3942 sizeof(modifiers[0]));
3944 modifiers[count_modifiers++] = mod->modifier;
3947 plane->formats[i].format = blob_formats[i];
3948 plane->formats[i].modifiers = modifiers;
3949 plane->formats[i].count_modifiers = count_modifiers;
3952 drmModeFreePropertyBlob(blob);
3958 /* No IN_FORMATS blob available, so just use the old. */
3959 assert(plane->count_formats == kplane->count_formats);
3960 for (i = 0; i < kplane->count_formats; i++)
3961 plane->formats[i].format = kplane->formats[i];
3967 * Create a drm_plane for a hardware plane
3969 * Creates one drm_plane structure for a hardware plane, and initialises its
3970 * properties and formats.
3972 * In the absence of universal plane support, where KMS does not explicitly
3973 * expose the primary and cursor planes to userspace, this may also create
3974 * an 'internal' plane for internal management.
3976 * This function does not add the plane to the list of usable planes in Weston
3977 * itself; the caller is responsible for this.
3979 * Call drm_plane_destroy to clean up the plane.
3981 * @sa drm_output_find_special_plane
3982 * @param b DRM compositor backend
3983 * @param kplane DRM plane to create, or NULL if creating internal plane
3984 * @param output Output to create internal plane for, or NULL
3985 * @param type Type to use when creating internal plane, or invalid
3986 * @param format Format to use for internal planes, or 0
3988 static struct drm_plane *
3989 drm_plane_create(struct drm_backend *b, const drmModePlane *kplane,
3990 struct drm_output *output, enum wdrm_plane_type type,
3993 struct drm_plane *plane;
3994 drmModeObjectProperties *props;
3995 uint32_t num_formats = (kplane) ? kplane->count_formats : 1;
3997 plane = zalloc(sizeof(*plane) +
3998 (sizeof(plane->formats[0]) * num_formats));
4000 weston_log("%s: out of memory\n", __func__);
4005 plane->count_formats = num_formats;
4006 plane->state_cur = drm_plane_state_alloc(NULL, plane);
4007 plane->state_cur->complete = true;
4010 plane->possible_crtcs = kplane->possible_crtcs;
4011 plane->plane_id = kplane->plane_id;
4013 props = drmModeObjectGetProperties(b->drm.fd, kplane->plane_id,
4014 DRM_MODE_OBJECT_PLANE);
4016 weston_log("couldn't get plane properties\n");
4019 drm_property_info_populate(b, plane_props, plane->props,
4020 WDRM_PLANE__COUNT, props);
4022 drm_property_get_value(&plane->props[WDRM_PLANE_TYPE],
4024 WDRM_PLANE_TYPE__COUNT);
4026 if (drm_plane_populate_formats(plane, kplane, props) < 0) {
4027 drmModeFreeObjectProperties(props);
4031 drmModeFreeObjectProperties(props);
4034 plane->possible_crtcs = (1 << output->pipe);
4035 plane->plane_id = 0;
4036 plane->count_formats = 1;
4037 plane->formats[0].format = format;
4041 if (plane->type == WDRM_PLANE_TYPE__COUNT)
4044 /* With universal planes, everything is a DRM plane; without
4045 * universal planes, the only DRM planes are overlay planes.
4046 * Everything else is a fake plane. */
4047 if (b->universal_planes) {
4051 assert(plane->type == WDRM_PLANE_TYPE_OVERLAY);
4053 assert(plane->type != WDRM_PLANE_TYPE_OVERLAY &&
4057 weston_plane_init(&plane->base, b->compositor, 0, 0);
4058 wl_list_insert(&b->plane_list, &plane->link);
4063 drm_property_info_free(plane->props, WDRM_PLANE__COUNT);
4065 drm_plane_state_free(plane->state_cur, true);
4071 * Find, or create, a special-purpose plane
4073 * Primary and cursor planes are a special case, in that before universal
4074 * planes, they are driven by non-plane API calls. Without universal plane
4075 * support, the only way to configure a primary plane is via drmModeSetCrtc,
4076 * and the only way to configure a cursor plane is drmModeSetCursor2.
4078 * Although they may actually be regular planes in the hardware, without
4079 * universal plane support, these planes are not actually exposed to
4080 * userspace in the regular plane list.
4082 * However, for ease of internal tracking, we want to manage all planes
4083 * through the same drm_plane structures. Therefore, when we are running
4084 * without universal plane support, we create fake drm_plane structures
4085 * to track these planes.
4087 * @param b DRM backend
4088 * @param output Output to use for plane
4089 * @param type Type of plane
4091 static struct drm_plane *
4092 drm_output_find_special_plane(struct drm_backend *b, struct drm_output *output,
4093 enum wdrm_plane_type type)
4095 struct drm_plane *plane;
4097 if (!b->universal_planes) {
4101 case WDRM_PLANE_TYPE_CURSOR:
4102 format = GBM_FORMAT_ARGB8888;
4104 case WDRM_PLANE_TYPE_PRIMARY:
4105 /* We don't know what formats the primary plane supports
4106 * before universal planes, so we just assume that the
4107 * GBM format works; however, this isn't set until after
4108 * the output is created. */
4112 assert(!"invalid type in drm_output_find_special_plane");
4116 return drm_plane_create(b, NULL, output, type, format);
4119 wl_list_for_each(plane, &b->plane_list, link) {
4120 struct drm_output *tmp;
4121 bool found_elsewhere = false;
4123 if (plane->type != type)
4125 if (!drm_plane_is_available(plane, output))
4128 /* On some platforms, primary/cursor planes can roam
4129 * between different CRTCs, so make sure we don't claim the
4130 * same plane for two outputs. */
4131 wl_list_for_each(tmp, &b->compositor->output_list,
4133 if (tmp->cursor_plane == plane ||
4134 tmp->scanout_plane == plane) {
4135 found_elsewhere = true;
4140 if (found_elsewhere)
4143 plane->possible_crtcs = (1 << output->pipe);
4151 * Destroy one DRM plane
4153 * Destroy a DRM plane, removing it from screen and releasing its retained
4154 * buffers in the process. The counterpart to drm_plane_create.
4156 * @param plane Plane to deallocate (will be freed)
4159 drm_plane_destroy(struct drm_plane *plane)
4161 if (plane->type == WDRM_PLANE_TYPE_OVERLAY)
4162 drmModeSetPlane(plane->backend->drm.fd, plane->plane_id,
4163 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
4164 drm_plane_state_free(plane->state_cur, true);
4165 drm_property_info_free(plane->props, WDRM_PLANE__COUNT);
4166 weston_plane_release(&plane->base);
4167 wl_list_remove(&plane->link);
4172 * Initialise sprites (overlay planes)
4174 * Walk the list of provided DRM planes, and add overlay planes.
4176 * Call destroy_sprites to free these planes.
4178 * @param b DRM compositor backend
4181 create_sprites(struct drm_backend *b)
4183 drmModePlaneRes *kplane_res;
4184 drmModePlane *kplane;
4185 struct drm_plane *drm_plane;
4187 kplane_res = drmModeGetPlaneResources(b->drm.fd);
4189 weston_log("failed to get plane resources: %s\n",
4194 for (i = 0; i < kplane_res->count_planes; i++) {
4195 kplane = drmModeGetPlane(b->drm.fd, kplane_res->planes[i]);
4199 drm_plane = drm_plane_create(b, kplane, NULL,
4200 WDRM_PLANE_TYPE__COUNT, 0);
4201 drmModeFreePlane(kplane);
4205 if (drm_plane->type == WDRM_PLANE_TYPE_OVERLAY)
4206 weston_compositor_stack_plane(b->compositor,
4208 &b->compositor->primary_plane);
4211 drmModeFreePlaneResources(kplane_res);
4215 * Clean up sprites (overlay planes)
4217 * The counterpart to create_sprites.
4219 * @param b DRM compositor backend
4222 destroy_sprites(struct drm_backend *b)
4224 struct drm_plane *plane, *next;
4226 wl_list_for_each_safe(plane, next, &b->plane_list, link)
4227 drm_plane_destroy(plane);
4231 drm_refresh_rate_mHz(const drmModeModeInfo *info)
4235 /* Calculate higher precision (mHz) refresh rate */
4236 refresh = (info->clock * 1000000LL / info->htotal +
4237 info->vtotal / 2) / info->vtotal;
4239 if (info->flags & DRM_MODE_FLAG_INTERLACE)
4241 if (info->flags & DRM_MODE_FLAG_DBLSCAN)
4243 if (info->vscan > 1)
4244 refresh /= info->vscan;
4250 * Add a mode to output's mode list
4252 * Copy the supplied DRM mode into a Weston mode structure, and add it to the
4253 * output's mode list.
4255 * @param output DRM output to add mode to
4256 * @param info DRM mode structure to add
4257 * @returns Newly-allocated Weston/DRM mode structure
4259 static struct drm_mode *
4260 drm_output_add_mode(struct drm_output *output, const drmModeModeInfo *info)
4262 struct drm_mode *mode;
4264 mode = malloc(sizeof *mode);
4268 mode->base.flags = 0;
4269 mode->base.width = info->hdisplay;
4270 mode->base.height = info->vdisplay;
4272 mode->base.refresh = drm_refresh_rate_mHz(info);
4273 mode->mode_info = *info;
4276 if (info->type & DRM_MODE_TYPE_PREFERRED)
4277 mode->base.flags |= WL_OUTPUT_MODE_PREFERRED;
4279 mode->base.aspect_ratio = drm_to_weston_mode_aspect_ratio(info->flags);
4281 wl_list_insert(output->base.mode_list.prev, &mode->base.link);
4287 * Destroys a mode, and removes it from the list.
4290 drm_output_destroy_mode(struct drm_backend *backend, struct drm_mode *mode)
4293 drmModeDestroyPropertyBlob(backend->drm.fd, mode->blob_id);
4294 wl_list_remove(&mode->base.link);
4298 /** Destroy a list of drm_modes
4300 * @param backend The backend for releasing mode property blobs.
4301 * @param mode_list The list linked by drm_mode::base.link.
4304 drm_mode_list_destroy(struct drm_backend *backend, struct wl_list *mode_list)
4306 struct drm_mode *mode, *next;
4308 wl_list_for_each_safe(mode, next, mode_list, base.link)
4309 drm_output_destroy_mode(backend, mode);
4313 drm_subpixel_to_wayland(int drm_value)
4315 switch (drm_value) {
4317 case DRM_MODE_SUBPIXEL_UNKNOWN:
4318 return WL_OUTPUT_SUBPIXEL_UNKNOWN;
4319 case DRM_MODE_SUBPIXEL_NONE:
4320 return WL_OUTPUT_SUBPIXEL_NONE;
4321 case DRM_MODE_SUBPIXEL_HORIZONTAL_RGB:
4322 return WL_OUTPUT_SUBPIXEL_HORIZONTAL_RGB;
4323 case DRM_MODE_SUBPIXEL_HORIZONTAL_BGR:
4324 return WL_OUTPUT_SUBPIXEL_HORIZONTAL_BGR;
4325 case DRM_MODE_SUBPIXEL_VERTICAL_RGB:
4326 return WL_OUTPUT_SUBPIXEL_VERTICAL_RGB;
4327 case DRM_MODE_SUBPIXEL_VERTICAL_BGR:
4328 return WL_OUTPUT_SUBPIXEL_VERTICAL_BGR;
4332 /* returns a value between 0-255 range, where higher is brighter */
4334 drm_get_backlight(struct drm_head *head)
4336 long brightness, max_brightness, norm;
4338 brightness = backlight_get_brightness(head->backlight);
4339 max_brightness = backlight_get_max_brightness(head->backlight);
4341 /* convert it on a scale of 0 to 255 */
4342 norm = (brightness * 255)/(max_brightness);
4344 return (uint32_t) norm;
4347 /* values accepted are between 0-255 range */
4349 drm_set_backlight(struct weston_output *output_base, uint32_t value)
4351 struct drm_output *output = to_drm_output(output_base);
4352 struct drm_head *head;
4353 long max_brightness, new_brightness;
4358 wl_list_for_each(head, &output->base.head_list, base.output_link) {
4359 if (!head->backlight)
4362 max_brightness = backlight_get_max_brightness(head->backlight);
4364 /* get denormalized value */
4365 new_brightness = (value * max_brightness) / 255;
4367 backlight_set_brightness(head->backlight, new_brightness);
4372 drm_output_init_backlight(struct drm_output *output)
4374 struct weston_head *base;
4375 struct drm_head *head;
4377 output->base.set_backlight = NULL;
4379 wl_list_for_each(base, &output->base.head_list, output_link) {
4380 head = to_drm_head(base);
4382 if (head->backlight) {
4383 weston_log("Initialized backlight for head '%s', device %s\n",
4384 head->base.name, head->backlight->path);
4386 if (!output->base.set_backlight) {
4387 output->base.set_backlight = drm_set_backlight;
4388 output->base.backlight_current =
4389 drm_get_backlight(head);
4394 if (!output->base.set_backlight) {
4395 weston_log("No backlight control for output '%s'\n",
4401 * Power output on or off
4403 * The DPMS/power level of an output is used to switch it on or off. This
4404 * is DRM's hook for doing so, which can called either as part of repaint,
4405 * or independently of the repaint loop.
4407 * If we are called as part of repaint, we simply set the relevant bit in
4411 drm_set_dpms(struct weston_output *output_base, enum dpms_enum level)
4413 struct drm_output *output = to_drm_output(output_base);
4414 struct drm_backend *b = to_drm_backend(output_base->compositor);
4415 struct drm_pending_state *pending_state = b->repaint_data;
4416 struct drm_output_state *state;
4419 if (output->state_cur->dpms == level)
4422 /* If we're being called during the repaint loop, then this is
4423 * simple: discard any previously-generated state, and create a new
4424 * state where we disable everything. When we come to flush, this
4427 * However, we need to be careful: we can be called whilst another
4428 * output is in its repaint cycle (pending_state exists), but our
4429 * output still has an incomplete state application outstanding.
4430 * In that case, we need to wait until that completes. */
4431 if (pending_state && !output->state_last) {
4432 /* The repaint loop already sets DPMS on; we don't need to
4433 * explicitly set it on here, as it will already happen
4434 * whilst applying the repaint state. */
4435 if (level == WESTON_DPMS_ON)
4438 state = drm_pending_state_get_output(pending_state, output);
4440 drm_output_state_free(state);
4441 state = drm_output_get_disable_state(pending_state, output);
4445 /* As we throw everything away when disabling, just send us back through
4446 * a repaint cycle. */
4447 if (level == WESTON_DPMS_ON) {
4448 if (output->dpms_off_pending)
4449 output->dpms_off_pending = 0;
4450 weston_output_schedule_repaint(output_base);
4454 /* If we've already got a request in the pipeline, then we need to
4455 * park our DPMS request until that request has quiesced. */
4456 if (output->state_last) {
4457 output->dpms_off_pending = 1;
4461 pending_state = drm_pending_state_alloc(b);
4462 drm_output_get_disable_state(pending_state, output);
4463 ret = drm_pending_state_apply_sync(pending_state);
4465 weston_log("drm_set_dpms: couldn't disable output?\n");
4468 static const char * const connector_type_names[] = {
4469 [DRM_MODE_CONNECTOR_Unknown] = "Unknown",
4470 [DRM_MODE_CONNECTOR_VGA] = "VGA",
4471 [DRM_MODE_CONNECTOR_DVII] = "DVI-I",
4472 [DRM_MODE_CONNECTOR_DVID] = "DVI-D",
4473 [DRM_MODE_CONNECTOR_DVIA] = "DVI-A",
4474 [DRM_MODE_CONNECTOR_Composite] = "Composite",
4475 [DRM_MODE_CONNECTOR_SVIDEO] = "SVIDEO",
4476 [DRM_MODE_CONNECTOR_LVDS] = "LVDS",
4477 [DRM_MODE_CONNECTOR_Component] = "Component",
4478 [DRM_MODE_CONNECTOR_9PinDIN] = "DIN",
4479 [DRM_MODE_CONNECTOR_DisplayPort] = "DP",
4480 [DRM_MODE_CONNECTOR_HDMIA] = "HDMI-A",
4481 [DRM_MODE_CONNECTOR_HDMIB] = "HDMI-B",
4482 [DRM_MODE_CONNECTOR_TV] = "TV",
4483 [DRM_MODE_CONNECTOR_eDP] = "eDP",
4484 #ifdef DRM_MODE_CONNECTOR_DSI
4485 [DRM_MODE_CONNECTOR_VIRTUAL] = "Virtual",
4486 [DRM_MODE_CONNECTOR_DSI] = "DSI",
4490 /** Create a name given a DRM connector
4492 * \param con The DRM connector whose type and id form the name.
4493 * \return A newly allocate string, or NULL on error. Must be free()'d
4496 * The name does not identify the DRM display device.
4499 make_connector_name(const drmModeConnector *con)
4502 const char *type_name = NULL;
4505 if (con->connector_type < ARRAY_LENGTH(connector_type_names))
4506 type_name = connector_type_names[con->connector_type];
4509 type_name = "UNNAMED";
4511 ret = asprintf(&name, "%s-%d", type_name, con->connector_type_id);
4518 static void drm_output_fini_cursor_egl(struct drm_output *output)
4522 for (i = 0; i < ARRAY_LENGTH(output->gbm_cursor_fb); i++) {
4523 drm_fb_unref(output->gbm_cursor_fb[i]);
4524 output->gbm_cursor_fb[i] = NULL;
4529 drm_output_init_cursor_egl(struct drm_output *output, struct drm_backend *b)
4533 /* No point creating cursors if we don't have a plane for them. */
4534 if (!output->cursor_plane)
4537 for (i = 0; i < ARRAY_LENGTH(output->gbm_cursor_fb); i++) {
4540 bo = gbm_bo_create(b->gbm, b->cursor_width, b->cursor_height,
4541 GBM_FORMAT_ARGB8888,
4542 GBM_BO_USE_CURSOR | GBM_BO_USE_WRITE);
4546 output->gbm_cursor_fb[i] =
4547 drm_fb_get_from_bo(bo, b, false, BUFFER_CURSOR);
4548 if (!output->gbm_cursor_fb[i]) {
4557 weston_log("cursor buffers unavailable, using gl cursors\n");
4558 b->cursors_are_broken = 1;
4559 drm_output_fini_cursor_egl(output);
4563 /* Init output state that depends on gl or gbm */
4565 drm_output_init_egl(struct drm_output *output, struct drm_backend *b)
4567 EGLint format[2] = {
4569 fallback_format_for(output->gbm_format),
4572 struct weston_mode *mode = output->base.current_mode;
4573 struct drm_plane *plane = output->scanout_plane;
4576 for (i = 0; i < plane->count_formats; i++) {
4577 if (plane->formats[i].format == output->gbm_format)
4581 if (i == plane->count_formats) {
4582 weston_log("format 0x%x not supported by output %s\n",
4583 output->gbm_format, output->base.name);
4587 #ifdef HAVE_GBM_MODIFIERS
4588 if (plane->formats[i].count_modifiers > 0) {
4589 output->gbm_surface =
4590 gbm_surface_create_with_modifiers(b->gbm,
4594 plane->formats[i].modifiers,
4595 plane->formats[i].count_modifiers);
4599 output->gbm_surface =
4600 gbm_surface_create(b->gbm, mode->width, mode->height,
4602 GBM_BO_USE_RENDERING | GBM_BO_USE_SCANOUT);
4605 if (!output->gbm_surface) {
4606 weston_log("failed to create gbm surface\n");
4612 if (gl_renderer->output_window_create(&output->base,
4613 (EGLNativeWindowType)output->gbm_surface,
4614 output->gbm_surface,
4615 gl_renderer->opaque_attribs,
4618 weston_log("failed to create gl renderer output state\n");
4619 gbm_surface_destroy(output->gbm_surface);
4623 drm_output_init_cursor_egl(output, b);
4629 drm_output_fini_egl(struct drm_output *output)
4631 struct drm_backend *b = to_drm_backend(output->base.compositor);
4633 /* Destroying the GBM surface will destroy all our GBM buffers,
4634 * regardless of refcount. Ensure we destroy them here. */
4635 if (!b->shutting_down &&
4636 output->scanout_plane->state_cur->fb &&
4637 output->scanout_plane->state_cur->fb->type == BUFFER_GBM_SURFACE) {
4638 drm_plane_state_free(output->scanout_plane->state_cur, true);
4639 output->scanout_plane->state_cur =
4640 drm_plane_state_alloc(NULL, output->scanout_plane);
4641 output->scanout_plane->state_cur->complete = true;
4644 gl_renderer->output_destroy(&output->base);
4645 gbm_surface_destroy(output->gbm_surface);
4646 drm_output_fini_cursor_egl(output);
4650 drm_output_init_pixman(struct drm_output *output, struct drm_backend *b)
4652 int w = output->base.current_mode->width;
4653 int h = output->base.current_mode->height;
4654 uint32_t format = output->gbm_format;
4655 uint32_t pixman_format;
4660 case GBM_FORMAT_XRGB8888:
4661 pixman_format = PIXMAN_x8r8g8b8;
4663 case GBM_FORMAT_RGB565:
4664 pixman_format = PIXMAN_r5g6b5;
4667 weston_log("Unsupported pixman format 0x%x\n", format);
4671 /* FIXME error checking */
4672 for (i = 0; i < ARRAY_LENGTH(output->dumb); i++) {
4673 output->dumb[i] = drm_fb_create_dumb(b, w, h, format);
4674 if (!output->dumb[i])
4678 pixman_image_create_bits(pixman_format, w, h,
4679 output->dumb[i]->map,
4680 output->dumb[i]->strides[0]);
4681 if (!output->image[i])
4685 if (b->use_pixman_shadow)
4686 flags |= PIXMAN_RENDERER_OUTPUT_USE_SHADOW;
4688 if (pixman_renderer_output_create(&output->base, flags) < 0)
4691 weston_log("DRM: output %s %s shadow framebuffer.\n", output->base.name,
4692 b->use_pixman_shadow ? "uses" : "does not use");
4694 pixman_region32_init_rect(&output->previous_damage,
4695 output->base.x, output->base.y, output->base.width, output->base.height);
4700 for (i = 0; i < ARRAY_LENGTH(output->dumb); i++) {
4701 if (output->dumb[i])
4702 drm_fb_unref(output->dumb[i]);
4703 if (output->image[i])
4704 pixman_image_unref(output->image[i]);
4706 output->dumb[i] = NULL;
4707 output->image[i] = NULL;
4714 drm_output_fini_pixman(struct drm_output *output)
4716 struct drm_backend *b = to_drm_backend(output->base.compositor);
4719 /* Destroying the Pixman surface will destroy all our buffers,
4720 * regardless of refcount. Ensure we destroy them here. */
4721 if (!b->shutting_down &&
4722 output->scanout_plane->state_cur->fb &&
4723 output->scanout_plane->state_cur->fb->type == BUFFER_PIXMAN_DUMB) {
4724 drm_plane_state_free(output->scanout_plane->state_cur, true);
4725 output->scanout_plane->state_cur =
4726 drm_plane_state_alloc(NULL, output->scanout_plane);
4727 output->scanout_plane->state_cur->complete = true;
4730 pixman_renderer_output_destroy(&output->base);
4731 pixman_region32_fini(&output->previous_damage);
4733 for (i = 0; i < ARRAY_LENGTH(output->dumb); i++) {
4734 pixman_image_unref(output->image[i]);
4735 drm_fb_unref(output->dumb[i]);
4736 output->dumb[i] = NULL;
4737 output->image[i] = NULL;
4742 edid_parse_string(const uint8_t *data, char text[])
4747 /* this is always 12 bytes, but we can't guarantee it's null
4748 * terminated or not junk. */
4749 strncpy(text, (const char *) data, 12);
4751 /* guarantee our new string is null-terminated */
4754 /* remove insane chars */
4755 for (i = 0; text[i] != '\0'; i++) {
4756 if (text[i] == '\n' ||
4763 /* ensure string is printable */
4764 for (i = 0; text[i] != '\0'; i++) {
4765 if (!isprint(text[i])) {
4771 /* if the string is random junk, ignore the string */
4776 #define EDID_DESCRIPTOR_ALPHANUMERIC_DATA_STRING 0xfe
4777 #define EDID_DESCRIPTOR_DISPLAY_PRODUCT_NAME 0xfc
4778 #define EDID_DESCRIPTOR_DISPLAY_PRODUCT_SERIAL_NUMBER 0xff
4779 #define EDID_OFFSET_DATA_BLOCKS 0x36
4780 #define EDID_OFFSET_LAST_BLOCK 0x6c
4781 #define EDID_OFFSET_PNPID 0x08
4782 #define EDID_OFFSET_SERIAL 0x0c
4785 edid_parse(struct drm_edid *edid, const uint8_t *data, size_t length)
4788 uint32_t serial_number;
4793 if (data[0] != 0x00 || data[1] != 0xff)
4796 /* decode the PNP ID from three 5 bit words packed into 2 bytes
4801 edid->pnp_id[0] = 'A' + ((data[EDID_OFFSET_PNPID + 0] & 0x7c) / 4) - 1;
4802 edid->pnp_id[1] = 'A' + ((data[EDID_OFFSET_PNPID + 0] & 0x3) * 8) + ((data[EDID_OFFSET_PNPID + 1] & 0xe0) / 32) - 1;
4803 edid->pnp_id[2] = 'A' + (data[EDID_OFFSET_PNPID + 1] & 0x1f) - 1;
4804 edid->pnp_id[3] = '\0';
4806 /* maybe there isn't a ASCII serial number descriptor, so use this instead */
4807 serial_number = (uint32_t) data[EDID_OFFSET_SERIAL + 0];
4808 serial_number += (uint32_t) data[EDID_OFFSET_SERIAL + 1] * 0x100;
4809 serial_number += (uint32_t) data[EDID_OFFSET_SERIAL + 2] * 0x10000;
4810 serial_number += (uint32_t) data[EDID_OFFSET_SERIAL + 3] * 0x1000000;
4811 if (serial_number > 0)
4812 sprintf(edid->serial_number, "%lu", (unsigned long) serial_number);
4814 /* parse EDID data */
4815 for (i = EDID_OFFSET_DATA_BLOCKS;
4816 i <= EDID_OFFSET_LAST_BLOCK;
4818 /* ignore pixel clock data */
4824 /* any useful blocks? */
4825 if (data[i+3] == EDID_DESCRIPTOR_DISPLAY_PRODUCT_NAME) {
4826 edid_parse_string(&data[i+5],
4827 edid->monitor_name);
4828 } else if (data[i+3] == EDID_DESCRIPTOR_DISPLAY_PRODUCT_SERIAL_NUMBER) {
4829 edid_parse_string(&data[i+5],
4830 edid->serial_number);
4831 } else if (data[i+3] == EDID_DESCRIPTOR_ALPHANUMERIC_DATA_STRING) {
4832 edid_parse_string(&data[i+5],
4839 /** Parse monitor make, model and serial from EDID
4841 * \param head The head whose \c drm_edid to fill in.
4842 * \param props The DRM connector properties to get the EDID from.
4843 * \param make[out] The monitor make (PNP ID).
4844 * \param model[out] The monitor model (name).
4845 * \param serial_number[out] The monitor serial number.
4847 * Each of \c *make, \c *model and \c *serial_number are set only if the
4848 * information is found in the EDID. The pointers they are set to must not
4849 * be free()'d explicitly, instead they get implicitly freed when the
4850 * \c drm_head is destroyed.
4853 find_and_parse_output_edid(struct drm_head *head,
4854 drmModeObjectPropertiesPtr props,
4857 const char **serial_number)
4859 drmModePropertyBlobPtr edid_blob = NULL;
4864 drm_property_get_value(&head->props_conn[WDRM_CONNECTOR_EDID],
4869 edid_blob = drmModeGetPropertyBlob(head->backend->drm.fd, blob_id);
4873 rc = edid_parse(&head->edid,
4877 if (head->edid.pnp_id[0] != '\0')
4878 *make = head->edid.pnp_id;
4879 if (head->edid.monitor_name[0] != '\0')
4880 *model = head->edid.monitor_name;
4881 if (head->edid.serial_number[0] != '\0')
4882 *serial_number = head->edid.serial_number;
4884 drmModeFreePropertyBlob(edid_blob);
4888 parse_modeline(const char *s, drmModeModeInfo *mode)
4894 memset(mode, 0, sizeof *mode);
4896 mode->type = DRM_MODE_TYPE_USERDEF;
4902 if (sscanf(s, "%f %hd %hd %hd %hd %hd %hd %hd %hd %15s %15s",
4911 &mode->vtotal, hsync, vsync) != 11)
4914 mode->clock = fclock * 1000;
4915 if (strcasecmp(hsync, "+hsync") == 0)
4916 mode->flags |= DRM_MODE_FLAG_PHSYNC;
4917 else if (strcasecmp(hsync, "-hsync") == 0)
4918 mode->flags |= DRM_MODE_FLAG_NHSYNC;
4922 if (strcasecmp(vsync, "+vsync") == 0)
4923 mode->flags |= DRM_MODE_FLAG_PVSYNC;
4924 else if (strcasecmp(vsync, "-vsync") == 0)
4925 mode->flags |= DRM_MODE_FLAG_NVSYNC;
4929 snprintf(mode->name, sizeof mode->name, "%dx%d@%.3f",
4930 mode->hdisplay, mode->vdisplay, fclock);
4936 setup_output_seat_constraint(struct drm_backend *b,
4937 struct weston_output *output,
4940 if (strcmp(s, "") != 0) {
4941 struct weston_pointer *pointer;
4942 struct udev_seat *seat;
4944 seat = udev_seat_get_named(&b->input, s);
4948 seat->base.output = output;
4950 pointer = weston_seat_get_pointer(&seat->base);
4952 weston_pointer_clamp(pointer,
4959 drm_output_attach_head(struct weston_output *output_base,
4960 struct weston_head *head_base)
4962 struct drm_backend *b = to_drm_backend(output_base->compositor);
4964 if (wl_list_length(&output_base->head_list) >= MAX_CLONED_CONNECTORS)
4967 if (!output_base->enabled)
4970 /* XXX: ensure the configuration will work.
4971 * This is actually impossible without major infrastructure
4974 /* Need to go through modeset to add connectors. */
4975 /* XXX: Ideally we'd do this per-output, not globally. */
4976 /* XXX: Doing it globally, what guarantees another output's update
4977 * will not clear the flag before this output is updated?
4979 b->state_invalid = true;
4981 weston_output_schedule_repaint(output_base);
4987 drm_output_detach_head(struct weston_output *output_base,
4988 struct weston_head *head_base)
4990 struct drm_backend *b = to_drm_backend(output_base->compositor);
4992 if (!output_base->enabled)
4995 /* Need to go through modeset to drop connectors that should no longer
4997 /* XXX: Ideally we'd do this per-output, not globally. */
4998 b->state_invalid = true;
5000 weston_output_schedule_repaint(output_base);
5004 parse_gbm_format(const char *s, uint32_t default_value, uint32_t *gbm_format)
5009 *gbm_format = default_value;
5010 else if (strcmp(s, "xrgb8888") == 0)
5011 *gbm_format = GBM_FORMAT_XRGB8888;
5012 else if (strcmp(s, "rgb565") == 0)
5013 *gbm_format = GBM_FORMAT_RGB565;
5014 else if (strcmp(s, "xrgb2101010") == 0)
5015 *gbm_format = GBM_FORMAT_XRGB2101010;
5017 weston_log("fatal: unrecognized pixel format: %s\n", s);
5025 u32distance(uint32_t a, uint32_t b)
5033 /** Choose equivalent mode
5035 * If the two modes are not equivalent, return NULL.
5036 * Otherwise return the mode that is more likely to work in place of both.
5038 * None of the fuzzy matching criteria in this function have any justification.
5040 * typedef struct _drmModeModeInfo {
5042 * uint16_t hdisplay, hsync_start, hsync_end, htotal, hskew;
5043 * uint16_t vdisplay, vsync_start, vsync_end, vtotal, vscan;
5045 * uint32_t vrefresh;
5049 * char name[DRM_DISPLAY_MODE_LEN];
5050 * } drmModeModeInfo, *drmModeModeInfoPtr;
5052 static const drmModeModeInfo *
5053 drm_mode_pick_equivalent(const drmModeModeInfo *a, const drmModeModeInfo *b)
5055 uint32_t refresh_a, refresh_b;
5057 if (a->hdisplay != b->hdisplay || a->vdisplay != b->vdisplay)
5060 if (a->flags != b->flags)
5064 if (u32distance(a->clock, b->clock) > 500)
5067 refresh_a = drm_refresh_rate_mHz(a);
5068 refresh_b = drm_refresh_rate_mHz(b);
5069 if (u32distance(refresh_a, refresh_b) > 50)
5072 if ((a->type ^ b->type) & DRM_MODE_TYPE_PREFERRED) {
5073 if (a->type & DRM_MODE_TYPE_PREFERRED)
5082 /* If the given mode info is not already in the list, add it.
5083 * If it is in the list, either keep the existing or replace it,
5084 * depending on which one is "better".
5087 drm_output_try_add_mode(struct drm_output *output, const drmModeModeInfo *info)
5089 struct weston_mode *base;
5090 struct drm_mode *mode;
5091 struct drm_backend *backend;
5092 const drmModeModeInfo *chosen = NULL;
5096 wl_list_for_each(base, &output->base.mode_list, link) {
5097 mode = to_drm_mode(base);
5098 chosen = drm_mode_pick_equivalent(&mode->mode_info, info);
5103 if (chosen == info) {
5104 backend = to_drm_backend(output->base.compositor);
5105 drm_output_destroy_mode(backend, mode);
5110 mode = drm_output_add_mode(output, info);
5114 /* else { the equivalent mode is already in the list } */
5119 /** Rewrite the output's mode list
5121 * @param output The output.
5122 * @return 0 on success, -1 on failure.
5124 * Destroy all existing modes in the list, and reconstruct a new list from
5125 * scratch, based on the currently attached heads.
5127 * On failure the output's mode list may contain some modes.
5130 drm_output_update_modelist_from_heads(struct drm_output *output)
5132 struct drm_backend *backend = to_drm_backend(output->base.compositor);
5133 struct weston_head *head_base;
5134 struct drm_head *head;
5138 assert(!output->base.enabled);
5140 drm_mode_list_destroy(backend, &output->base.mode_list);
5142 wl_list_for_each(head_base, &output->base.head_list, output_link) {
5143 head = to_drm_head(head_base);
5144 for (i = 0; i < head->connector->count_modes; i++) {
5145 ret = drm_output_try_add_mode(output,
5146 &head->connector->modes[i]);
5156 * Choose suitable mode for an output
5158 * Find the most suitable mode to use for initial setup (or reconfiguration on
5159 * hotplug etc) for a DRM output.
5161 * @param output DRM output to choose mode for
5162 * @param kind Strategy and preference to use when choosing mode
5163 * @param width Desired width for this output
5164 * @param height Desired height for this output
5165 * @param current_mode Mode currently being displayed on this output
5166 * @param modeline Manually-entered mode (may be NULL)
5167 * @returns A mode from the output's mode list, or NULL if none available
5169 static struct drm_mode *
5170 drm_output_choose_initial_mode(struct drm_backend *backend,
5171 struct drm_output *output,
5172 enum weston_drm_backend_output_mode mode,
5173 const char *modeline,
5174 const drmModeModeInfo *current_mode)
5176 struct drm_mode *preferred = NULL;
5177 struct drm_mode *current = NULL;
5178 struct drm_mode *configured = NULL;
5179 struct drm_mode *config_fall_back = NULL;
5180 struct drm_mode *best = NULL;
5181 struct drm_mode *drm_mode;
5182 drmModeModeInfo drm_modeline;
5185 uint32_t refresh = 0;
5186 uint32_t aspect_width = 0;
5187 uint32_t aspect_height = 0;
5188 enum weston_mode_aspect_ratio aspect_ratio = WESTON_MODE_PIC_AR_NONE;
5191 if (mode == WESTON_DRM_BACKEND_OUTPUT_PREFERRED && modeline) {
5192 n = sscanf(modeline, "%dx%d@%d %u:%u", &width, &height,
5193 &refresh, &aspect_width, &aspect_height);
5194 if (backend->aspect_ratio_supported && n == 5) {
5195 if (aspect_width == 4 && aspect_height == 3)
5196 aspect_ratio = WESTON_MODE_PIC_AR_4_3;
5197 else if (aspect_width == 16 && aspect_height == 9)
5198 aspect_ratio = WESTON_MODE_PIC_AR_16_9;
5199 else if (aspect_width == 64 && aspect_height == 27)
5200 aspect_ratio = WESTON_MODE_PIC_AR_64_27;
5201 else if (aspect_width == 256 && aspect_height == 135)
5202 aspect_ratio = WESTON_MODE_PIC_AR_256_135;
5204 weston_log("Invalid modeline \"%s\" for output %s\n",
5205 modeline, output->base.name);
5207 if (n != 2 && n != 3 && n != 5) {
5210 if (parse_modeline(modeline, &drm_modeline) == 0) {
5211 configured = drm_output_add_mode(output, &drm_modeline);
5215 weston_log("Invalid modeline \"%s\" for output %s\n",
5216 modeline, output->base.name);
5221 wl_list_for_each_reverse(drm_mode, &output->base.mode_list, base.link) {
5222 if (width == drm_mode->base.width &&
5223 height == drm_mode->base.height &&
5224 (refresh == 0 || refresh == drm_mode->mode_info.vrefresh)) {
5225 if (!backend->aspect_ratio_supported ||
5226 aspect_ratio == drm_mode->base.aspect_ratio)
5227 configured = drm_mode;
5229 config_fall_back = drm_mode;
5232 if (memcmp(current_mode, &drm_mode->mode_info,
5233 sizeof *current_mode) == 0)
5236 if (drm_mode->base.flags & WL_OUTPUT_MODE_PREFERRED)
5237 preferred = drm_mode;
5242 if (current == NULL && current_mode->clock != 0) {
5243 current = drm_output_add_mode(output, current_mode);
5248 if (mode == WESTON_DRM_BACKEND_OUTPUT_CURRENT)
5249 configured = current;
5254 if (config_fall_back)
5255 return config_fall_back;
5266 weston_log("no available modes for %s\n", output->base.name);
5271 drm_head_read_current_setup(struct drm_head *head, struct drm_backend *backend)
5273 int drm_fd = backend->drm.fd;
5274 drmModeEncoder *encoder;
5277 /* Get the current mode on the crtc that's currently driving
5278 * this connector. */
5279 encoder = drmModeGetEncoder(drm_fd, head->connector->encoder_id);
5280 if (encoder != NULL) {
5281 head->inherited_crtc_id = encoder->crtc_id;
5283 crtc = drmModeGetCrtc(drm_fd, encoder->crtc_id);
5284 drmModeFreeEncoder(encoder);
5288 if (crtc->mode_valid)
5289 head->inherited_mode = crtc->mode;
5290 drmModeFreeCrtc(crtc);
5297 drm_output_set_mode(struct weston_output *base,
5298 enum weston_drm_backend_output_mode mode,
5299 const char *modeline)
5301 struct drm_output *output = to_drm_output(base);
5302 struct drm_backend *b = to_drm_backend(base->compositor);
5303 struct drm_head *head = to_drm_head(weston_output_get_first_head(base));
5305 struct drm_mode *current;
5307 if (drm_output_update_modelist_from_heads(output) < 0)
5310 current = drm_output_choose_initial_mode(b, output, mode, modeline,
5311 &head->inherited_mode);
5315 output->base.current_mode = ¤t->base;
5316 output->base.current_mode->flags |= WL_OUTPUT_MODE_CURRENT;
5318 /* Set native_ fields, so weston_output_mode_switch_to_native() works */
5319 output->base.native_mode = output->base.current_mode;
5320 output->base.native_scale = output->base.current_scale;
5326 drm_output_set_gbm_format(struct weston_output *base,
5327 const char *gbm_format)
5329 struct drm_output *output = to_drm_output(base);
5330 struct drm_backend *b = to_drm_backend(base->compositor);
5332 if (parse_gbm_format(gbm_format, b->gbm_format, &output->gbm_format) == -1)
5333 output->gbm_format = b->gbm_format;
5335 /* Without universal planes, we can't discover which formats are
5336 * supported by the primary plane; we just hope that the GBM format
5338 if (!b->universal_planes)
5339 output->scanout_plane->formats[0].format = output->gbm_format;
5343 drm_output_set_seat(struct weston_output *base,
5346 struct drm_output *output = to_drm_output(base);
5347 struct drm_backend *b = to_drm_backend(base->compositor);
5349 setup_output_seat_constraint(b, &output->base,
5354 drm_output_init_gamma_size(struct drm_output *output)
5356 struct drm_backend *backend = to_drm_backend(output->base.compositor);
5359 assert(output->base.compositor);
5360 assert(output->crtc_id != 0);
5361 crtc = drmModeGetCrtc(backend->drm.fd, output->crtc_id);
5365 output->base.gamma_size = crtc->gamma_size;
5367 drmModeFreeCrtc(crtc);
5373 drm_head_get_possible_crtcs_mask(struct drm_head *head)
5375 uint32_t possible_crtcs = 0;
5376 drmModeEncoder *encoder;
5379 for (i = 0; i < head->connector->count_encoders; i++) {
5380 encoder = drmModeGetEncoder(head->backend->drm.fd,
5381 head->connector->encoders[i]);
5385 possible_crtcs |= encoder->possible_crtcs;
5386 drmModeFreeEncoder(encoder);
5389 return possible_crtcs;
5393 drm_crtc_get_index(drmModeRes *resources, uint32_t crtc_id)
5397 for (i = 0; i < resources->count_crtcs; i++) {
5398 if (resources->crtcs[i] == crtc_id)
5402 assert(0 && "unknown crtc id");
5406 /** Pick a CRTC that might be able to drive all attached connectors
5408 * @param output The output whose attached heads to include.
5409 * @param resources The DRM KMS resources.
5410 * @return CRTC index, or -1 on failure or not found.
5413 drm_output_pick_crtc(struct drm_output *output, drmModeRes *resources)
5415 struct drm_backend *backend;
5416 struct weston_head *base;
5417 struct drm_head *head;
5418 uint32_t possible_crtcs = 0xffffffff;
5419 int existing_crtc[32];
5422 int best_crtc_index = -1;
5423 int fallback_crtc_index = -1;
5427 backend = to_drm_backend(output->base.compositor);
5429 /* This algorithm ignores drmModeEncoder::possible_clones restriction,
5430 * because it is more often set wrong than not in the kernel. */
5432 /* Accumulate a mask of possible crtcs and find existing routings. */
5433 wl_list_for_each(base, &output->base.head_list, output_link) {
5434 head = to_drm_head(base);
5436 possible_crtcs &= drm_head_get_possible_crtcs_mask(head);
5438 crtc_id = head->inherited_crtc_id;
5439 if (crtc_id > 0 && n < ARRAY_LENGTH(existing_crtc))
5440 existing_crtc[n++] = drm_crtc_get_index(resources,
5444 /* Find a crtc that could drive each connector individually at least,
5445 * and prefer existing routings. */
5446 for (i = 0; i < resources->count_crtcs; i++) {
5447 crtc_id = resources->crtcs[i];
5449 /* Could the crtc not drive each connector? */
5450 if (!(possible_crtcs & (1 << i)))
5453 /* Is the crtc already in use? */
5454 if (drm_output_find_by_crtc(backend, crtc_id))
5457 /* Try to preserve the existing CRTC -> connector routing;
5458 * it makes initialisation faster, and also since we have a
5459 * very dumb picking algorithm, may preserve a better
5461 for (j = 0; j < n; j++) {
5462 if (existing_crtc[j] == i)
5466 /* Check if any other head had existing routing to this CRTC.
5467 * If they did, this is not the best CRTC as it might be needed
5468 * for another output we haven't enabled yet. */
5470 wl_list_for_each(base, &backend->compositor->head_list,
5472 head = to_drm_head(base);
5474 if (head->base.output == &output->base)
5477 if (weston_head_is_enabled(&head->base))
5480 if (head->inherited_crtc_id == crtc_id) {
5486 best_crtc_index = i;
5488 fallback_crtc_index = i;
5491 if (best_crtc_index != -1)
5492 return best_crtc_index;
5494 if (fallback_crtc_index != -1)
5495 return fallback_crtc_index;
5497 /* Likely possible_crtcs was empty due to asking for clones,
5498 * but since the DRM documentation says the kernel lies, let's
5499 * pick one crtc anyway. Trial and error is the only way to
5500 * be sure if something doesn't work. */
5502 /* First pick any existing assignment. */
5503 for (j = 0; j < n; j++) {
5504 crtc_id = resources->crtcs[existing_crtc[j]];
5505 if (!drm_output_find_by_crtc(backend, crtc_id))
5506 return existing_crtc[j];
5509 /* Otherwise pick any available crtc. */
5510 for (i = 0; i < resources->count_crtcs; i++) {
5511 crtc_id = resources->crtcs[i];
5513 if (!drm_output_find_by_crtc(backend, crtc_id))
5520 /** Allocate a CRTC for the output
5522 * @param output The output with no allocated CRTC.
5523 * @param resources DRM KMS resources.
5524 * @return 0 on success, -1 on failure.
5526 * Finds a free CRTC that might drive the attached connectors, reserves the CRTC
5527 * for the output, and loads the CRTC properties.
5529 * Populates the cursor and scanout planes.
5531 * On failure, the output remains without a CRTC.
5534 drm_output_init_crtc(struct drm_output *output, drmModeRes *resources)
5536 struct drm_backend *b = to_drm_backend(output->base.compositor);
5537 drmModeObjectPropertiesPtr props;
5540 assert(output->crtc_id == 0);
5542 i = drm_output_pick_crtc(output, resources);
5544 weston_log("Output '%s': No available CRTCs.\n",
5549 output->crtc_id = resources->crtcs[i];
5552 props = drmModeObjectGetProperties(b->drm.fd, output->crtc_id,
5553 DRM_MODE_OBJECT_CRTC);
5555 weston_log("failed to get CRTC properties\n");
5558 drm_property_info_populate(b, crtc_props, output->props_crtc,
5559 WDRM_CRTC__COUNT, props);
5560 drmModeFreeObjectProperties(props);
5562 output->scanout_plane =
5563 drm_output_find_special_plane(b, output,
5564 WDRM_PLANE_TYPE_PRIMARY);
5565 if (!output->scanout_plane) {
5566 weston_log("Failed to find primary plane for output %s\n",
5571 /* Failing to find a cursor plane is not fatal, as we'll fall back
5572 * to software cursor. */
5573 output->cursor_plane =
5574 drm_output_find_special_plane(b, output,
5575 WDRM_PLANE_TYPE_CURSOR);
5577 wl_array_remove_uint32(&b->unused_crtcs, output->crtc_id);
5582 output->crtc_id = 0;
5588 /** Free the CRTC from the output
5590 * @param output The output whose CRTC to deallocate.
5592 * The CRTC reserved for the given output becomes free to use again.
5595 drm_output_fini_crtc(struct drm_output *output)
5597 struct drm_backend *b = to_drm_backend(output->base.compositor);
5600 if (!b->universal_planes && !b->shutting_down) {
5601 /* With universal planes, the 'special' planes are allocated at
5602 * startup, freed at shutdown, and live on the plane list in
5603 * between. We want the planes to continue to exist and be freed
5604 * up for other outputs.
5606 * Without universal planes, our special planes are
5607 * pseudo-planes allocated at output creation, freed at output
5608 * destruction, and not usable by other outputs.
5610 * On the other hand, if the compositor is already shutting down,
5611 * the plane has already been destroyed.
5613 if (output->cursor_plane)
5614 drm_plane_destroy(output->cursor_plane);
5615 if (output->scanout_plane)
5616 drm_plane_destroy(output->scanout_plane);
5619 drm_property_info_free(output->props_crtc, WDRM_CRTC__COUNT);
5621 assert(output->crtc_id != 0);
5623 unused = wl_array_add(&b->unused_crtcs, sizeof(*unused));
5624 *unused = output->crtc_id;
5626 /* Force resetting unused CRTCs */
5627 b->state_invalid = true;
5629 output->crtc_id = 0;
5630 output->cursor_plane = NULL;
5631 output->scanout_plane = NULL;
5635 drm_output_print_modes(struct drm_output *output)
5637 struct weston_mode *m;
5638 struct drm_mode *dm;
5639 const char *aspect_ratio;
5641 wl_list_for_each(m, &output->base.mode_list, link) {
5642 dm = to_drm_mode(m);
5644 aspect_ratio = aspect_ratio_to_string(m->aspect_ratio);
5645 weston_log_continue(STAMP_SPACE "%dx%d@%.1f%s%s%s, %.1f MHz\n",
5646 m->width, m->height, m->refresh / 1000.0,
5648 m->flags & WL_OUTPUT_MODE_PREFERRED ?
5650 m->flags & WL_OUTPUT_MODE_CURRENT ?
5652 dm->mode_info.clock / 1000.0);
5657 drm_output_enable(struct weston_output *base)
5659 struct drm_output *output = to_drm_output(base);
5660 struct drm_backend *b = to_drm_backend(base->compositor);
5661 drmModeRes *resources;
5664 resources = drmModeGetResources(b->drm.fd);
5666 weston_log("drmModeGetResources failed\n");
5669 ret = drm_output_init_crtc(output, resources);
5670 drmModeFreeResources(resources);
5674 if (drm_output_init_gamma_size(output) < 0)
5677 if (b->pageflip_timeout)
5678 drm_output_pageflip_timer_create(output);
5680 if (b->use_pixman) {
5681 if (drm_output_init_pixman(output, b) < 0) {
5682 weston_log("Failed to init output pixman state\n");
5685 } else if (drm_output_init_egl(output, b) < 0) {
5686 weston_log("Failed to init output gl state\n");
5690 drm_output_init_backlight(output);
5692 output->base.start_repaint_loop = drm_output_start_repaint_loop;
5693 output->base.repaint = drm_output_repaint;
5694 output->base.assign_planes = drm_assign_planes;
5695 output->base.set_dpms = drm_set_dpms;
5696 output->base.switch_mode = drm_output_switch_mode;
5697 output->base.set_gamma = drm_output_set_gamma;
5699 if (output->cursor_plane)
5700 weston_compositor_stack_plane(b->compositor,
5701 &output->cursor_plane->base,
5704 b->cursors_are_broken = 1;
5706 weston_compositor_stack_plane(b->compositor,
5707 &output->scanout_plane->base,
5708 &b->compositor->primary_plane);
5710 weston_log("Output %s (crtc %d) video modes:\n",
5711 output->base.name, output->crtc_id);
5712 drm_output_print_modes(output);
5717 drm_output_fini_crtc(output);
5723 drm_output_deinit(struct weston_output *base)
5725 struct drm_output *output = to_drm_output(base);
5726 struct drm_backend *b = to_drm_backend(base->compositor);
5729 drm_output_fini_pixman(output);
5731 drm_output_fini_egl(output);
5733 /* Since our planes are no longer in use anywhere, remove their base
5734 * weston_plane's link from the plane stacking list, unless we're
5735 * shutting down, in which case the plane has already been
5737 if (!b->shutting_down) {
5738 wl_list_remove(&output->scanout_plane->base.link);
5739 wl_list_init(&output->scanout_plane->base.link);
5741 if (output->cursor_plane) {
5742 wl_list_remove(&output->cursor_plane->base.link);
5743 wl_list_init(&output->cursor_plane->base.link);
5744 /* Turn off hardware cursor */
5745 drmModeSetCursor(b->drm.fd, output->crtc_id, 0, 0, 0);
5749 drm_output_fini_crtc(output);
5753 drm_head_destroy(struct drm_head *head);
5756 drm_output_destroy(struct weston_output *base)
5758 struct drm_output *output = to_drm_output(base);
5759 struct drm_backend *b = to_drm_backend(base->compositor);
5761 if (output->page_flip_pending || output->vblank_pending ||
5762 output->atomic_complete_pending) {
5763 output->destroy_pending = 1;
5764 weston_log("destroy output while page flip pending\n");
5768 if (output->base.enabled)
5769 drm_output_deinit(&output->base);
5771 drm_mode_list_destroy(b, &output->base.mode_list);
5773 if (output->pageflip_timer)
5774 wl_event_source_remove(output->pageflip_timer);
5776 weston_output_release(&output->base);
5778 assert(!output->state_last);
5779 drm_output_state_free(output->state_cur);
5785 drm_output_disable(struct weston_output *base)
5787 struct drm_output *output = to_drm_output(base);
5789 if (output->page_flip_pending || output->vblank_pending ||
5790 output->atomic_complete_pending) {
5791 output->disable_pending = 1;
5795 weston_log("Disabling output %s\n", output->base.name);
5797 if (output->base.enabled)
5798 drm_output_deinit(&output->base);
5800 output->disable_pending = 0;
5806 * Update the list of unused connectors and CRTCs
5808 * This keeps the unused_crtc arrays up to date.
5810 * @param b Weston backend structure
5811 * @param resources DRM resources for this device
5814 drm_backend_update_unused_outputs(struct drm_backend *b, drmModeRes *resources)
5818 wl_array_release(&b->unused_crtcs);
5819 wl_array_init(&b->unused_crtcs);
5821 for (i = 0; i < resources->count_crtcs; i++) {
5822 struct drm_output *output;
5825 output = drm_output_find_by_crtc(b, resources->crtcs[i]);
5826 if (output && output->base.enabled)
5829 crtc_id = wl_array_add(&b->unused_crtcs, sizeof(*crtc_id));
5830 *crtc_id = resources->crtcs[i];
5834 /** Replace connector data and monitor information
5836 * @param head The head to update.
5837 * @param connector The connector data to be owned by the head, must match
5838 * the head's connector ID.
5839 * @return 0 on success, -1 on failure.
5841 * Takes ownership of @c connector on success, not on failure.
5843 * May schedule a heads changed call.
5846 drm_head_assign_connector_info(struct drm_head *head,
5847 drmModeConnector *connector)
5849 drmModeObjectProperties *props;
5850 const char *make = "unknown";
5851 const char *model = "unknown";
5852 const char *serial_number = "unknown";
5855 assert(head->connector_id == connector->connector_id);
5857 props = drmModeObjectGetProperties(head->backend->drm.fd,
5859 DRM_MODE_OBJECT_CONNECTOR);
5861 weston_log("Error: failed to get connector '%s' properties\n",
5866 if (head->connector)
5867 drmModeFreeConnector(head->connector);
5868 head->connector = connector;
5870 drm_property_info_populate(head->backend, connector_props,
5872 WDRM_CONNECTOR__COUNT, props);
5873 find_and_parse_output_edid(head, props, &make, &model, &serial_number);
5874 weston_head_set_monitor_strings(&head->base, make, model, serial_number);
5875 weston_head_set_subpixel(&head->base,
5876 drm_subpixel_to_wayland(head->connector->subpixel));
5878 weston_head_set_physical_size(&head->base, head->connector->mmWidth,
5879 head->connector->mmHeight);
5881 drmModeFreeObjectProperties(props);
5883 /* Unknown connection status is assumed disconnected. */
5884 weston_head_set_connection_status(&head->base,
5885 head->connector->connection == DRM_MODE_CONNECTED);
5891 drm_head_log_info(struct drm_head *head, const char *msg)
5893 if (head->base.connected) {
5894 weston_log("DRM: head '%s' %s, connector %d is connected, "
5895 "EDID make '%s', model '%s', serial '%s'\n",
5896 head->base.name, msg, head->connector_id,
5897 head->base.make, head->base.model,
5898 head->base.serial_number ?: "");
5900 weston_log("DRM: head '%s' %s, connector %d is disconnected.\n",
5901 head->base.name, msg, head->connector_id);
5905 /** Update connector and monitor information
5907 * @param head The head to update.
5909 * Re-reads the DRM property lists for the connector and updates monitor
5910 * information and connection status. This may schedule a heads changed call
5914 drm_head_update_info(struct drm_head *head)
5916 drmModeConnector *connector;
5918 connector = drmModeGetConnector(head->backend->drm.fd,
5919 head->connector_id);
5921 weston_log("DRM: getting connector info for '%s' failed.\n",
5926 if (drm_head_assign_connector_info(head, connector) < 0)
5927 drmModeFreeConnector(connector);
5929 if (head->base.device_changed)
5930 drm_head_log_info(head, "updated");
5934 * Create a Weston head for a connector
5936 * Given a DRM connector, create a matching drm_head structure and add it
5937 * to Weston's head list.
5939 * @param b Weston backend structure
5940 * @param connector_id DRM connector ID for the head
5941 * @param drm_device udev device pointer
5942 * @returns The new head, or NULL on failure.
5944 static struct drm_head *
5945 drm_head_create(struct drm_backend *backend, uint32_t connector_id,
5946 struct udev_device *drm_device)
5948 struct drm_head *head;
5949 drmModeConnector *connector;
5952 head = zalloc(sizeof *head);
5956 connector = drmModeGetConnector(backend->drm.fd, connector_id);
5960 name = make_connector_name(connector);
5964 weston_head_init(&head->base, name);
5967 head->connector_id = connector_id;
5968 head->backend = backend;
5970 head->backlight = backlight_init(drm_device, connector->connector_type);
5972 if (drm_head_assign_connector_info(head, connector) < 0)
5975 if (head->connector->connector_type == DRM_MODE_CONNECTOR_LVDS ||
5976 head->connector->connector_type == DRM_MODE_CONNECTOR_eDP)
5977 weston_head_set_internal(&head->base);
5979 if (drm_head_read_current_setup(head, backend) < 0) {
5980 weston_log("Failed to retrieve current mode from connector %d.\n",
5981 head->connector_id);
5985 weston_compositor_add_head(backend->compositor, &head->base);
5986 drm_head_log_info(head, "found");
5991 weston_head_release(&head->base);
5995 drmModeFreeConnector(connector);
6003 drm_head_destroy(struct drm_head *head)
6005 weston_head_release(&head->base);
6007 drm_property_info_free(head->props_conn, WDRM_CONNECTOR__COUNT);
6008 drmModeFreeConnector(head->connector);
6010 if (head->backlight)
6011 backlight_destroy(head->backlight);
6017 * Create a Weston output structure
6019 * Create an "empty" drm_output. This is the implementation of
6020 * weston_backend::create_output.
6022 * Creating an output is usually followed by drm_output_attach_head()
6023 * and drm_output_enable() to make use of it.
6025 * @param compositor The compositor instance.
6026 * @param name Name for the new output.
6027 * @returns The output, or NULL on failure.
6029 static struct weston_output *
6030 drm_output_create(struct weston_compositor *compositor, const char *name)
6032 struct drm_backend *b = to_drm_backend(compositor);
6033 struct drm_output *output;
6035 output = zalloc(sizeof *output);
6039 weston_output_init(&output->base, compositor, name);
6041 output->base.enable = drm_output_enable;
6042 output->base.destroy = drm_output_destroy;
6043 output->base.disable = drm_output_disable;
6044 output->base.attach_head = drm_output_attach_head;
6045 output->base.detach_head = drm_output_detach_head;
6047 output->destroy_pending = 0;
6048 output->disable_pending = 0;
6050 output->state_cur = drm_output_state_alloc(output, NULL);
6052 weston_compositor_add_pending_output(&output->base, b->compositor);
6054 return &output->base;
6058 drm_backend_create_heads(struct drm_backend *b, struct udev_device *drm_device)
6060 struct drm_head *head;
6061 drmModeRes *resources;
6064 resources = drmModeGetResources(b->drm.fd);
6066 weston_log("drmModeGetResources failed\n");
6070 b->min_width = resources->min_width;
6071 b->max_width = resources->max_width;
6072 b->min_height = resources->min_height;
6073 b->max_height = resources->max_height;
6075 for (i = 0; i < resources->count_connectors; i++) {
6076 uint32_t connector_id = resources->connectors[i];
6078 head = drm_head_create(b, connector_id, drm_device);
6080 weston_log("DRM: failed to create head for connector %d.\n",
6085 drm_backend_update_unused_outputs(b, resources);
6087 drmModeFreeResources(resources);
6093 drm_backend_update_heads(struct drm_backend *b, struct udev_device *drm_device)
6095 drmModeRes *resources;
6096 struct weston_head *base, *next;
6097 struct drm_head *head;
6100 resources = drmModeGetResources(b->drm.fd);
6102 weston_log("drmModeGetResources failed\n");
6106 /* collect new connectors that have appeared, e.g. MST */
6107 for (i = 0; i < resources->count_connectors; i++) {
6108 uint32_t connector_id = resources->connectors[i];
6110 head = drm_head_find_by_connector(b, connector_id);
6112 drm_head_update_info(head);
6114 head = drm_head_create(b, connector_id, drm_device);
6116 weston_log("DRM: failed to create head for hot-added connector %d.\n",
6121 /* Remove connectors that have disappeared. */
6122 wl_list_for_each_safe(base, next,
6123 &b->compositor->head_list, compositor_link) {
6124 bool removed = true;
6126 head = to_drm_head(base);
6128 for (i = 0; i < resources->count_connectors; i++) {
6129 if (resources->connectors[i] == head->connector_id) {
6138 weston_log("DRM: head '%s' (connector %d) disappeared.\n",
6139 head->base.name, head->connector_id);
6140 drm_head_destroy(head);
6143 drm_backend_update_unused_outputs(b, resources);
6145 drmModeFreeResources(resources);
6149 udev_event_is_hotplug(struct drm_backend *b, struct udev_device *device)
6154 sysnum = udev_device_get_sysnum(device);
6155 if (!sysnum || atoi(sysnum) != b->drm.id)
6158 val = udev_device_get_property_value(device, "HOTPLUG");
6162 return strcmp(val, "1") == 0;
6166 udev_drm_event(int fd, uint32_t mask, void *data)
6168 struct drm_backend *b = data;
6169 struct udev_device *event;
6171 event = udev_monitor_receive_device(b->udev_monitor);
6173 if (udev_event_is_hotplug(b, event))
6174 drm_backend_update_heads(b, event);
6176 udev_device_unref(event);
6182 drm_destroy(struct weston_compositor *ec)
6184 struct drm_backend *b = to_drm_backend(ec);
6185 struct weston_head *base, *next;
6187 udev_input_destroy(&b->input);
6189 wl_event_source_remove(b->udev_drm_source);
6190 wl_event_source_remove(b->drm_source);
6192 b->shutting_down = true;
6196 weston_compositor_shutdown(ec);
6198 wl_list_for_each_safe(base, next, &ec->head_list, compositor_link)
6199 drm_head_destroy(to_drm_head(base));
6202 gbm_device_destroy(b->gbm);
6204 udev_monitor_unref(b->udev_monitor);
6205 udev_unref(b->udev);
6207 weston_launcher_destroy(ec->launcher);
6209 wl_array_release(&b->unused_crtcs);
6212 free(b->drm.filename);
6217 session_notify(struct wl_listener *listener, void *data)
6219 struct weston_compositor *compositor = data;
6220 struct drm_backend *b = to_drm_backend(compositor);
6221 struct drm_plane *plane;
6222 struct drm_output *output;
6224 if (compositor->session_active) {
6225 weston_log("activating session\n");
6226 weston_compositor_wake(compositor);
6227 weston_compositor_damage_all(compositor);
6228 b->state_invalid = true;
6229 udev_input_enable(&b->input);
6231 weston_log("deactivating session\n");
6232 udev_input_disable(&b->input);
6234 weston_compositor_offscreen(compositor);
6236 /* If we have a repaint scheduled (either from a
6237 * pending pageflip or the idle handler), make sure we
6238 * cancel that so we don't try to pageflip when we're
6239 * vt switched away. The OFFSCREEN state will prevent
6240 * further attempts at repainting. When we switch
6241 * back, we schedule a repaint, which will process
6242 * pending frame callbacks. */
6244 wl_list_for_each(output, &compositor->output_list, base.link) {
6245 output->base.repaint_needed = false;
6246 if (output->cursor_plane)
6247 drmModeSetCursor(b->drm.fd, output->crtc_id,
6251 output = container_of(compositor->output_list.next,
6252 struct drm_output, base.link);
6254 wl_list_for_each(plane, &b->plane_list, link) {
6255 if (plane->type != WDRM_PLANE_TYPE_OVERLAY)
6258 drmModeSetPlane(b->drm.fd,
6260 output->crtc_id, 0, 0,
6261 0, 0, 0, 0, 0, 0, 0, 0);
6267 * Determines whether or not a device is capable of modesetting. If successful,
6268 * sets b->drm.fd and b->drm.filename to the opened device.
6271 drm_device_is_kms(struct drm_backend *b, struct udev_device *device)
6273 const char *filename = udev_device_get_devnode(device);
6274 const char *sysnum = udev_device_get_sysnum(device);
6281 fd = weston_launcher_open(b->compositor->launcher, filename, O_RDWR);
6285 res = drmModeGetResources(fd);
6289 if (res->count_crtcs <= 0 || res->count_connectors <= 0 ||
6290 res->count_encoders <= 0)
6295 if (!sysnum || id < 0) {
6296 weston_log("couldn't get sysnum for device %s\n", filename);
6300 /* We can be called successfully on multiple devices; if we have,
6301 * clean up old entries. */
6303 weston_launcher_close(b->compositor->launcher, b->drm.fd);
6304 free(b->drm.filename);
6308 b->drm.filename = strdup(filename);
6310 drmModeFreeResources(res);
6315 drmModeFreeResources(res);
6317 weston_launcher_close(b->compositor->launcher, fd);
6323 * Some systems may have multiple DRM devices attached to a single seat. This
6324 * function loops over all devices and tries to find a PCI device with the
6325 * boot_vga sysfs attribute set to 1.
6326 * If no such device is found, the first DRM device reported by udev is used.
6327 * Devices are also vetted to make sure they are are capable of modesetting,
6328 * rather than pure render nodes (GPU with no display), or pure
6329 * memory-allocation devices (VGEM).
6331 static struct udev_device*
6332 find_primary_gpu(struct drm_backend *b, const char *seat)
6334 struct udev_enumerate *e;
6335 struct udev_list_entry *entry;
6336 const char *path, *device_seat, *id;
6337 struct udev_device *device, *drm_device, *pci;
6339 e = udev_enumerate_new(b->udev);
6340 udev_enumerate_add_match_subsystem(e, "drm");
6341 udev_enumerate_add_match_sysname(e, "card[0-9]*");
6343 udev_enumerate_scan_devices(e);
6345 udev_list_entry_foreach(entry, udev_enumerate_get_list_entry(e)) {
6346 bool is_boot_vga = false;
6348 path = udev_list_entry_get_name(entry);
6349 device = udev_device_new_from_syspath(b->udev, path);
6352 device_seat = udev_device_get_property_value(device, "ID_SEAT");
6354 device_seat = default_seat;
6355 if (strcmp(device_seat, seat)) {
6356 udev_device_unref(device);
6360 pci = udev_device_get_parent_with_subsystem_devtype(device,
6363 id = udev_device_get_sysattr_value(pci, "boot_vga");
6364 if (id && !strcmp(id, "1"))
6368 /* If we already have a modesetting-capable device, and this
6369 * device isn't our boot-VGA device, we aren't going to use
6371 if (!is_boot_vga && drm_device) {
6372 udev_device_unref(device);
6376 /* Make sure this device is actually capable of modesetting;
6377 * if this call succeeds, b->drm.{fd,filename} will be set,
6378 * and any old values freed. */
6379 if (!drm_device_is_kms(b, device)) {
6380 udev_device_unref(device);
6384 /* There can only be one boot_vga device, and we try to use it
6388 udev_device_unref(drm_device);
6389 drm_device = device;
6393 /* Per the (!is_boot_vga && drm_device) test above, we only
6394 * trump existing saved devices with boot-VGA devices, so if
6395 * we end up here, this must be the first device we've seen. */
6396 assert(!drm_device);
6397 drm_device = device;
6400 /* If we're returning a device to use, we must have an open FD for
6402 assert(!!drm_device == (b->drm.fd >= 0));
6404 udev_enumerate_unref(e);
6408 static struct udev_device *
6409 open_specific_drm_device(struct drm_backend *b, const char *name)
6411 struct udev_device *device;
6413 device = udev_device_new_from_subsystem_sysname(b->udev, "drm", name);
6415 weston_log("ERROR: could not open DRM device '%s'\n", name);
6419 if (!drm_device_is_kms(b, device)) {
6420 udev_device_unref(device);
6421 weston_log("ERROR: DRM device '%s' is not a KMS device.\n", name);
6425 /* If we're returning a device to use, we must have an open FD for
6427 assert(b->drm.fd >= 0);
6433 planes_binding(struct weston_keyboard *keyboard, const struct timespec *time,
6434 uint32_t key, void *data)
6436 struct drm_backend *b = data;
6440 b->cursors_are_broken ^= 1;
6443 b->sprites_are_broken ^= 1;
6446 b->sprites_hidden ^= 1;
6453 #ifdef BUILD_VAAPI_RECORDER
6455 recorder_destroy(struct drm_output *output)
6457 vaapi_recorder_destroy(output->recorder);
6458 output->recorder = NULL;
6460 output->base.disable_planes--;
6462 wl_list_remove(&output->recorder_frame_listener.link);
6463 weston_log("[libva recorder] done\n");
6467 recorder_frame_notify(struct wl_listener *listener, void *data)
6469 struct drm_output *output;
6470 struct drm_backend *b;
6473 output = container_of(listener, struct drm_output,
6474 recorder_frame_listener);
6475 b = to_drm_backend(output->base.compositor);
6477 if (!output->recorder)
6480 ret = drmPrimeHandleToFD(b->drm.fd,
6481 output->scanout_plane->state_cur->fb->handles[0],
6484 weston_log("[libva recorder] "
6485 "failed to create prime fd for front buffer\n");
6489 ret = vaapi_recorder_frame(output->recorder, fd,
6490 output->scanout_plane->state_cur->fb->strides[0]);
6492 weston_log("[libva recorder] aborted: %m\n");
6493 recorder_destroy(output);
6498 create_recorder(struct drm_backend *b, int width, int height,
6499 const char *filename)
6504 fd = open(b->drm.filename, O_RDWR | O_CLOEXEC);
6508 drmGetMagic(fd, &magic);
6509 drmAuthMagic(b->drm.fd, magic);
6511 return vaapi_recorder_create(fd, width, height, filename);
6515 recorder_binding(struct weston_keyboard *keyboard, const struct timespec *time,
6516 uint32_t key, void *data)
6518 struct drm_backend *b = data;
6519 struct drm_output *output;
6522 output = container_of(b->compositor->output_list.next,
6523 struct drm_output, base.link);
6525 if (!output->recorder) {
6526 if (output->gbm_format != GBM_FORMAT_XRGB8888) {
6527 weston_log("failed to start vaapi recorder: "
6528 "output format not supported\n");
6532 width = output->base.current_mode->width;
6533 height = output->base.current_mode->height;
6536 create_recorder(b, width, height, "capture.h264");
6537 if (!output->recorder) {
6538 weston_log("failed to create vaapi recorder\n");
6542 output->base.disable_planes++;
6544 output->recorder_frame_listener.notify = recorder_frame_notify;
6545 wl_signal_add(&output->base.frame_signal,
6546 &output->recorder_frame_listener);
6548 weston_output_schedule_repaint(&output->base);
6550 weston_log("[libva recorder] initialized\n");
6552 recorder_destroy(output);
6557 recorder_binding(struct weston_keyboard *keyboard, const struct timespec *time,
6558 uint32_t key, void *data)
6560 weston_log("Compiled without libva support\n");
6565 switch_to_gl_renderer(struct drm_backend *b)
6567 struct drm_output *output;
6568 bool dmabuf_support_inited;
6573 dmabuf_support_inited = !!b->compositor->renderer->import_dmabuf;
6575 weston_log("Switching to GL renderer\n");
6577 b->gbm = create_gbm_device(b->drm.fd);
6579 weston_log("Failed to create gbm device. "
6580 "Aborting renderer switch\n");
6584 wl_list_for_each(output, &b->compositor->output_list, base.link)
6585 pixman_renderer_output_destroy(&output->base);
6587 b->compositor->renderer->destroy(b->compositor);
6589 if (drm_backend_create_gl_renderer(b) < 0) {
6590 gbm_device_destroy(b->gbm);
6591 weston_log("Failed to create GL renderer. Quitting.\n");
6592 /* FIXME: we need a function to shutdown cleanly */
6596 wl_list_for_each(output, &b->compositor->output_list, base.link)
6597 drm_output_init_egl(output, b);
6601 if (!dmabuf_support_inited && b->compositor->renderer->import_dmabuf) {
6602 if (linux_dmabuf_setup(b->compositor) < 0)
6603 weston_log("Error: initializing dmabuf "
6604 "support failed.\n");
6609 renderer_switch_binding(struct weston_keyboard *keyboard,
6610 const struct timespec *time, uint32_t key, void *data)
6612 struct drm_backend *b =
6613 to_drm_backend(keyboard->seat->compositor);
6615 switch_to_gl_renderer(b);
6618 static const struct weston_drm_output_api api = {
6619 drm_output_set_mode,
6620 drm_output_set_gbm_format,
6621 drm_output_set_seat,
6624 static struct drm_backend *
6625 drm_backend_create(struct weston_compositor *compositor,
6626 struct weston_drm_backend_config *config)
6628 struct drm_backend *b;
6629 struct udev_device *drm_device;
6630 struct wl_event_loop *loop;
6631 const char *seat_id = default_seat;
6632 const char *session_seat;
6635 session_seat = getenv("XDG_SEAT");
6637 seat_id = session_seat;
6639 if (config->seat_id)
6640 seat_id = config->seat_id;
6642 weston_log("initializing drm backend\n");
6644 b = zalloc(sizeof *b);
6648 b->state_invalid = true;
6650 wl_array_init(&b->unused_crtcs);
6653 * KMS support for hardware planes cannot properly synchronize
6654 * without nuclear page flip. Without nuclear/atomic, hw plane
6655 * and cursor plane updates would either tear or cause extra
6656 * waits for vblanks which means dropping the compositor framerate
6657 * to a fraction. For cursors, it's not so bad, so they are
6660 * These can be enabled again when nuclear/atomic support lands.
6662 b->sprites_are_broken = 1;
6663 b->compositor = compositor;
6664 b->use_pixman = config->use_pixman;
6665 b->pageflip_timeout = config->pageflip_timeout;
6666 b->use_pixman_shadow = config->use_pixman_shadow;
6668 compositor->backend = &b->base;
6670 if (parse_gbm_format(config->gbm_format, GBM_FORMAT_XRGB8888, &b->gbm_format) < 0)
6671 goto err_compositor;
6673 /* Check if we run drm-backend using weston-launch */
6674 compositor->launcher = weston_launcher_connect(compositor, config->tty,
6676 if (compositor->launcher == NULL) {
6677 weston_log("fatal: drm backend should be run using "
6678 "weston-launch binary, or your system should "
6679 "provide the logind D-Bus API.\n");
6680 goto err_compositor;
6683 b->udev = udev_new();
6684 if (b->udev == NULL) {
6685 weston_log("failed to initialize udev context\n");
6689 b->session_listener.notify = session_notify;
6690 wl_signal_add(&compositor->session_signal, &b->session_listener);
6692 if (config->specific_device)
6693 drm_device = open_specific_drm_device(b, config->specific_device);
6695 drm_device = find_primary_gpu(b, seat_id);
6696 if (drm_device == NULL) {
6697 weston_log("no drm device found\n");
6701 if (init_kms_caps(b) < 0) {
6702 weston_log("failed to initialize kms\n");
6706 if (b->use_pixman) {
6707 if (init_pixman(b) < 0) {
6708 weston_log("failed to initialize pixman renderer\n");
6712 if (init_egl(b) < 0) {
6713 weston_log("failed to initialize egl\n");
6718 b->base.destroy = drm_destroy;
6719 b->base.repaint_begin = drm_repaint_begin;
6720 b->base.repaint_flush = drm_repaint_flush;
6721 b->base.repaint_cancel = drm_repaint_cancel;
6722 b->base.create_output = drm_output_create;
6724 weston_setup_vt_switch_bindings(compositor);
6726 wl_list_init(&b->plane_list);
6729 if (udev_input_init(&b->input,
6730 compositor, b->udev, seat_id,
6731 config->configure_device) < 0) {
6732 weston_log("failed to create input devices\n");
6736 if (drm_backend_create_heads(b, drm_device) < 0) {
6737 weston_log("Failed to create heads for %s\n", b->drm.filename);
6738 goto err_udev_input;
6741 /* A this point we have some idea of whether or not we have a working
6743 if (!b->cursors_are_broken)
6744 compositor->capabilities |= WESTON_CAP_CURSOR_PLANE;
6746 loop = wl_display_get_event_loop(compositor->wl_display);
6748 wl_event_loop_add_fd(loop, b->drm.fd,
6749 WL_EVENT_READABLE, on_drm_input, b);
6751 b->udev_monitor = udev_monitor_new_from_netlink(b->udev, "udev");
6752 if (b->udev_monitor == NULL) {
6753 weston_log("failed to initialize udev monitor\n");
6754 goto err_drm_source;
6756 udev_monitor_filter_add_match_subsystem_devtype(b->udev_monitor,
6758 b->udev_drm_source =
6759 wl_event_loop_add_fd(loop,
6760 udev_monitor_get_fd(b->udev_monitor),
6761 WL_EVENT_READABLE, udev_drm_event, b);
6763 if (udev_monitor_enable_receiving(b->udev_monitor) < 0) {
6764 weston_log("failed to enable udev-monitor receiving\n");
6765 goto err_udev_monitor;
6768 udev_device_unref(drm_device);
6770 weston_compositor_add_debug_binding(compositor, KEY_O,
6772 weston_compositor_add_debug_binding(compositor, KEY_C,
6774 weston_compositor_add_debug_binding(compositor, KEY_V,
6776 weston_compositor_add_debug_binding(compositor, KEY_Q,
6777 recorder_binding, b);
6778 weston_compositor_add_debug_binding(compositor, KEY_W,
6779 renderer_switch_binding, b);
6781 if (compositor->renderer->import_dmabuf) {
6782 if (linux_dmabuf_setup(compositor) < 0)
6783 weston_log("Error: initializing dmabuf "
6784 "support failed.\n");
6787 ret = weston_plugin_api_register(compositor, WESTON_DRM_OUTPUT_API_NAME,
6791 weston_log("Failed to register output API.\n");
6792 goto err_udev_monitor;
6798 wl_event_source_remove(b->udev_drm_source);
6799 udev_monitor_unref(b->udev_monitor);
6801 wl_event_source_remove(b->drm_source);
6803 udev_input_destroy(&b->input);
6806 gbm_device_destroy(b->gbm);
6809 udev_device_unref(drm_device);
6811 weston_launcher_destroy(compositor->launcher);
6813 udev_unref(b->udev);
6815 weston_compositor_shutdown(compositor);
6821 config_init_to_defaults(struct weston_drm_backend_config *config)
6823 config->use_pixman_shadow = true;
6827 weston_backend_init(struct weston_compositor *compositor,
6828 struct weston_backend_config *config_base)
6830 struct drm_backend *b;
6831 struct weston_drm_backend_config config = {{ 0, }};
6833 if (config_base == NULL ||
6834 config_base->struct_version != WESTON_DRM_BACKEND_CONFIG_VERSION ||
6835 config_base->struct_size > sizeof(struct weston_drm_backend_config)) {
6836 weston_log("drm backend config structure is invalid\n");
6840 config_init_to_defaults(&config);
6841 memcpy(&config, config_base, config_base->struct_size);
6843 b = drm_backend_create(compositor, &config);