compositor-drm.c 93.1 KB
Newer Older
1
/*
2 3
 * Copyright © 2008-2011 Kristian Høgsberg
 * Copyright © 2011 Intel Corporation
4
 *
5 6 7 8 9 10 11
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
12
 *
13 14 15 16 17 18 19 20 21 22 23 24
 * The above copyright notice and this permission notice (including the
 * next paragraph) shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
25 26
 */

27
#include "config.h"
28

29
#include <errno.h>
30
#include <stdint.h>
31
#include <stdlib.h>
32
#include <ctype.h>
33 34 35
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
36
#include <linux/input.h>
37
#include <linux/vt.h>
38
#include <assert.h>
39
#include <sys/mman.h>
40
#include <dlfcn.h>
41
#include <time.h>
42

43 44
#include <xf86drm.h>
#include <xf86drmMode.h>
45
#include <drm_fourcc.h>
46

47
#include <gbm.h>
48
#include <libudev.h>
49

50 51
#include "compositor.h"
#include "compositor-drm.h"
52
#include "shared/helpers.h"
53
#include "shared/timespec-util.h"
54
#include "gl-renderer.h"
55
#include "weston-egl-ext.h"
56
#include "pixman-renderer.h"
57
#include "pixel-formats.h"
58
#include "libbacklight.h"
59
#include "libinput-seat.h"
60
#include "launcher-util.h"
61
#include "vaapi-recorder.h"
62
#include "presentation-time-server-protocol.h"
63
#include "linux-dmabuf.h"
64
#include "linux-dmabuf-unstable-v1-server-protocol.h"
65

66 67 68 69
#ifndef DRM_CAP_TIMESTAMP_MONOTONIC
#define DRM_CAP_TIMESTAMP_MONOTONIC 0x6
#endif

70 71 72 73 74 75 76 77 78 79 80 81
#ifndef DRM_CAP_CURSOR_WIDTH
#define DRM_CAP_CURSOR_WIDTH 0x8
#endif

#ifndef DRM_CAP_CURSOR_HEIGHT
#define DRM_CAP_CURSOR_HEIGHT 0x9
#endif

#ifndef GBM_BO_USE_CURSOR
#define GBM_BO_USE_CURSOR GBM_BO_USE_CURSOR_64X64
#endif

82 83 84
struct drm_backend {
	struct weston_backend base;
	struct weston_compositor *compositor;
85 86 87 88

	struct udev *udev;
	struct wl_event_source *drm_source;

89 90 91
	struct udev_monitor *udev_monitor;
	struct wl_event_source *udev_drm_source;

92
	struct {
93
		int id;
94
		int fd;
95
		char *filename;
96
	} drm;
97
	struct gbm_device *gbm;
98
	struct wl_listener session_listener;
99
	uint32_t gbm_format;
100

101 102 103 104
	/* we need these parameters in order to not fail drmModeAddFB2()
	 * due to out of bounds dimensions, and then mistakenly set
	 * sprites_are_broken:
	 */
105 106
	int min_width, max_width;
	int min_height, max_height;
107
	int no_addfb2;
108

109
	struct wl_list sprite_list;
110
	int sprites_are_broken;
111
	int sprites_hidden;
112

113 114
	int cursors_are_broken;

115 116
	int use_pixman;

117
	struct udev_input input;
118

119 120
	int32_t cursor_width;
	int32_t cursor_height;
121 122

	uint32_t connector;
123
	uint32_t pageflip_timeout;
124 125
};

126
struct drm_mode {
127
	struct weston_mode base;
128 129 130
	drmModeModeInfo mode_info;
};

131 132 133 134 135
enum drm_fb_type {
	BUFFER_INVALID = 0, /**< never used */
	BUFFER_CLIENT, /**< directly sourced from client */
	BUFFER_PIXMAN_DUMB, /**< internal Pixman rendering */
	BUFFER_GBM_SURFACE, /**< internal EGL rendering */
136
	BUFFER_CURSOR, /**< internal cursor buffer */
137 138
};

139
struct drm_fb {
140 141
	enum drm_fb_type type;

142 143
	int refcnt;

144
	uint32_t fb_id, stride, handle, size;
145
	const struct pixel_format_info *format;
146
	int width, height;
147
	int fd;
148
	struct weston_buffer_reference buffer_ref;
149 150 151

	/* Used by gbm fbs */
	struct gbm_bo *bo;
152
	struct gbm_surface *gbm_surface;
153 154 155

	/* Used by dumb fbs */
	void *map;
156 157
};

158 159 160 161 162 163 164
struct drm_edid {
	char eisa_id[13];
	char monitor_name[13];
	char pnp_id[5];
	char serial_number[13];
};

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
/**
 * A plane represents one buffer, positioned within a CRTC, and stacked
 * relative to other planes on the same CRTC.
 *
 * Each CRTC has a 'primary plane', which use used to display the classic
 * framebuffer contents, as accessed through the legacy drmModeSetCrtc
 * call (which combines setting the CRTC's actual physical mode, and the
 * properties of the primary plane).
 *
 * The cursor plane also has its own alternate legacy API.
 *
 * Other planes are used opportunistically to display content we do not
 * wish to blit into the primary plane. These non-primary/cursor planes
 * are referred to as 'sprites'.
 */
struct drm_plane {
	struct wl_list link;

	struct weston_plane base;

	struct drm_output *output;
	struct drm_backend *backend;

	uint32_t possible_crtcs;
	uint32_t plane_id;
	uint32_t count_formats;

	/* The last framebuffer submitted to the kernel for this plane. */
	struct drm_fb *fb_current;
	/* The previously-submitted framebuffer, where the hardware has not
	 * yet acknowledged display of fb_current. */
	struct drm_fb *fb_last;
	/* Framebuffer we are going to submit to the kernel when the current
	 * repaint is flushed. */
	struct drm_fb *fb_pending;

	int32_t src_x, src_y;
	uint32_t src_w, src_h;
	uint32_t dest_x, dest_y;
	uint32_t dest_w, dest_h;

	uint32_t formats[];
};

209
struct drm_output {
210 211
	struct weston_output base;
	drmModeConnector *connector;
212

213 214
	uint32_t crtc_id; /* object ID to pass to DRM functions */
	int pipe; /* index of CRTC in resource array / bitmasks */
215
	uint32_t connector_id;
216
	drmModeCrtcPtr original_crtc;
217
	struct drm_edid edid;
218
	drmModePropertyPtr dpms_prop;
219

220
	enum dpms_enum dpms;
221
	struct backlight *backlight;
222

223 224
	int vblank_pending;
	int page_flip_pending;
225
	int destroy_pending;
226
	int disable_pending;
227

228
	struct drm_fb *gbm_cursor_fb[2];
229
	struct weston_plane cursor_plane;
230
	struct weston_view *cursor_view;
231
	int current_cursor;
232 233 234 235 236

	struct gbm_surface *gbm_surface;
	uint32_t gbm_format;

	struct weston_plane fb_plane;
237 238 239 240 241 242 243 244 245

	/* The last framebuffer submitted to the kernel for this CRTC. */
	struct drm_fb *fb_current;
	/* The previously-submitted framebuffer, where the hardware has not
	 * yet acknowledged display of fb_current. */
	struct drm_fb *fb_last;
	/* Framebuffer we are going to submit to the kernel when the current
	 * repaint is flushed. */
	struct drm_fb *fb_pending;
246 247 248 249 250

	struct drm_fb *dumb[2];
	pixman_image_t *image[2];
	int current_image;
	pixman_region32_t previous_damage;
251 252 253

	struct vaapi_recorder *recorder;
	struct wl_listener recorder_frame_listener;
254 255

	struct wl_event_source *pageflip_timer;
256 257
};

258 259
static struct gl_renderer_interface *gl_renderer;

260
static const char default_seat[] = "seat0";
261

262 263 264 265 266 267 268 269 270 271 272 273
static inline struct drm_output *
to_drm_output(struct weston_output *base)
{
	return container_of(base, struct drm_output, base);
}

static inline struct drm_backend *
to_drm_backend(struct weston_compositor *base)
{
	return container_of(base->backend, struct drm_backend, base);
}

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
static int
pageflip_timeout(void *data) {
	/*
	 * Our timer just went off, that means we're not receiving drm
	 * page flip events anymore for that output. Let's gracefully exit
	 * weston with a return value so devs can debug what's going on.
	 */
	struct drm_output *output = data;
	struct weston_compositor *compositor = output->base.compositor;

	weston_log("Pageflip timeout reached on output %s, your "
	           "driver is probably buggy!  Exiting.\n",
		   output->base.name);
	weston_compositor_exit_with_code(compositor, EXIT_FAILURE);

	return 0;
}

/* Creates the pageflip timer. Note that it isn't armed by default */
static int
drm_output_pageflip_timer_create(struct drm_output *output)
{
	struct wl_event_loop *loop = NULL;
	struct weston_compositor *ec = output->base.compositor;

	loop = wl_display_get_event_loop(ec->wl_display);
	assert(loop);
	output->pageflip_timer = wl_event_loop_add_timer(loop,
	                                                 pageflip_timeout,
	                                                 output);

	if (output->pageflip_timer == NULL) {
		weston_log("creating drm pageflip timer failed: %m\n");
		return -1;
	}

	return 0;
}

313 314 315
static void
drm_output_set_cursor(struct drm_output *output);

316 317 318
static void
drm_output_update_msc(struct drm_output *output, unsigned int seq);

319
static int
320
drm_plane_crtc_supported(struct drm_output *output, struct drm_plane *plane)
321
{
322
	return !!(plane->possible_crtcs & (1 << output->pipe));
323 324
}

325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
static struct drm_output *
drm_output_find_by_crtc(struct drm_backend *b, uint32_t crtc_id)
{
	struct drm_output *output;

	wl_list_for_each(output, &b->compositor->output_list, base.link) {
		if (output->crtc_id == crtc_id)
			return output;
	}

	wl_list_for_each(output, &b->compositor->pending_output_list,
			 base.link) {
		if (output->crtc_id == crtc_id)
			return output;
	}

	return NULL;
}

344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
static struct drm_output *
drm_output_find_by_connector(struct drm_backend *b, uint32_t connector_id)
{
	struct drm_output *output;

	wl_list_for_each(output, &b->compositor->output_list, base.link) {
		if (output->connector_id == connector_id)
			return output;
	}

	wl_list_for_each(output, &b->compositor->pending_output_list,
			 base.link) {
		if (output->connector_id == connector_id)
			return output;
	}

	return NULL;
}

363
static void
364
drm_fb_destroy(struct drm_fb *fb)
365
{
366
	if (fb->fb_id != 0)
367
		drmModeRmFB(fb->fd, fb->fb_id);
368
	weston_buffer_reference(&fb->buffer_ref, NULL);
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
	free(fb);
}

static void
drm_fb_destroy_dumb(struct drm_fb *fb)
{
	struct drm_mode_destroy_dumb destroy_arg;

	assert(fb->type == BUFFER_PIXMAN_DUMB);

	if (fb->map && fb->size > 0)
		munmap(fb->map, fb->size);

	memset(&destroy_arg, 0, sizeof(destroy_arg));
	destroy_arg.handle = fb->handle;
	drmIoctl(fb->fd, DRM_IOCTL_MODE_DESTROY_DUMB, &destroy_arg);

	drm_fb_destroy(fb);
}

static void
drm_fb_destroy_gbm(struct gbm_bo *bo, void *data)
{
	struct drm_fb *fb = data;
393

394 395
	assert(fb->type == BUFFER_GBM_SURFACE || fb->type == BUFFER_CLIENT ||
	       fb->type == BUFFER_CURSOR);
396
	drm_fb_destroy(fb);
397 398
}

399
static struct drm_fb *
400
drm_fb_create_dumb(struct drm_backend *b, int width, int height,
401
		   uint32_t format)
402 403 404 405 406 407 408 409
{
	struct drm_fb *fb;
	int ret;

	struct drm_mode_create_dumb create_arg;
	struct drm_mode_destroy_dumb destroy_arg;
	struct drm_mode_map_dumb map_arg;

410
	fb = zalloc(sizeof *fb);
411 412 413
	if (!fb)
		return NULL;

414 415
	fb->refcnt = 1;

416 417 418 419 420 421 422 423 424 425 426
	fb->format = pixel_format_get_info(format);
	if (!fb->format) {
		weston_log("failed to look up format 0x%lx\n",
			   (unsigned long) format);
		goto err_fb;
	}

	if (!fb->format->depth || !fb->format->bpp) {
		weston_log("format 0x%lx is not compatible with dumb buffers\n",
			   (unsigned long) format);
		goto err_fb;
427 428
	}

429
	memset(&create_arg, 0, sizeof create_arg);
430
	create_arg.bpp = fb->format->bpp;
431 432 433
	create_arg.width = width;
	create_arg.height = height;

434
	ret = drmIoctl(b->drm.fd, DRM_IOCTL_MODE_CREATE_DUMB, &create_arg);
435 436 437
	if (ret)
		goto err_fb;

438
	fb->type = BUFFER_PIXMAN_DUMB;
439 440 441
	fb->handle = create_arg.handle;
	fb->stride = create_arg.pitch;
	fb->size = create_arg.size;
442 443
	fb->width = width;
	fb->height = height;
444
	fb->fd = b->drm.fd;
445

446 447 448
	ret = -1;

	if (!b->no_addfb2) {
449
		uint32_t handles[4] = { 0 }, pitches[4] = { 0 }, offsets[4] = { 0 };
450 451 452 453 454 455

		handles[0] = fb->handle;
		pitches[0] = fb->stride;
		offsets[0] = 0;

		ret = drmModeAddFB2(b->drm.fd, width, height,
456 457
				    fb->format->format,
				    handles, pitches, offsets,
458 459 460 461 462 463 464 465
				    &fb->fb_id, 0);
		if (ret) {
			weston_log("addfb2 failed: %m\n");
			b->no_addfb2 = 1;
		}
	}

	if (ret) {
466 467
		ret = drmModeAddFB(b->drm.fd, width, height,
				   fb->format->depth, fb->format->bpp,
468 469 470
				   fb->stride, fb->handle, &fb->fb_id);
	}

471 472 473
	if (ret)
		goto err_bo;

474
	memset(&map_arg, 0, sizeof map_arg);
475
	map_arg.handle = fb->handle;
476
	ret = drmIoctl(fb->fd, DRM_IOCTL_MODE_MAP_DUMB, &map_arg);
477 478 479
	if (ret)
		goto err_add_fb;

480
	fb->map = mmap(NULL, fb->size, PROT_WRITE,
481
		       MAP_SHARED, b->drm.fd, map_arg.offset);
482 483 484 485 486 487
	if (fb->map == MAP_FAILED)
		goto err_add_fb;

	return fb;

err_add_fb:
488
	drmModeRmFB(b->drm.fd, fb->fb_id);
489 490 491
err_bo:
	memset(&destroy_arg, 0, sizeof(destroy_arg));
	destroy_arg.handle = create_arg.handle;
492
	drmIoctl(b->drm.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &destroy_arg);
493 494 495 496 497
err_fb:
	free(fb);
	return NULL;
}

498 499 500 501 502 503 504
static struct drm_fb *
drm_fb_ref(struct drm_fb *fb)
{
	fb->refcnt++;
	return fb;
}

505
static struct drm_fb *
506 507
drm_fb_get_from_bo(struct gbm_bo *bo, struct drm_backend *backend,
		   uint32_t format, enum drm_fb_type type)
508 509
{
	struct drm_fb *fb = gbm_bo_get_user_data(bo);
510
	uint32_t handles[4] = { 0 }, pitches[4] = { 0 }, offsets[4] = { 0 };
511 512
	int ret;

513 514
	if (fb) {
		assert(fb->type == type);
515
		return drm_fb_ref(fb);
516
	}
517

518 519
	fb = zalloc(sizeof *fb);
	if (fb == NULL)
520
		return NULL;
521

522
	fb->type = type;
523
	fb->refcnt = 1;
524 525
	fb->bo = bo;

526 527
	fb->width = gbm_bo_get_width(bo);
	fb->height = gbm_bo_get_height(bo);
528 529
	fb->stride = gbm_bo_get_stride(bo);
	fb->handle = gbm_bo_get_handle(bo).u32;
530
	fb->format = pixel_format_get_info(format);
531
	fb->size = fb->stride * fb->height;
532
	fb->fd = backend->drm.fd;
533

534 535 536 537 538 539
	if (!fb->format) {
		weston_log("couldn't look up format 0x%lx\n",
			   (unsigned long) format);
		goto err_free;
	}

540 541 542 543
	if (backend->min_width > fb->width ||
	    fb->width > backend->max_width ||
	    backend->min_height > fb->height ||
	    fb->height > backend->max_height) {
544 545 546 547 548 549
		weston_log("bo geometry out of bounds\n");
		goto err_free;
	}

	ret = -1;

550
	if (format && !backend->no_addfb2) {
551 552
		handles[0] = fb->handle;
		pitches[0] = fb->stride;
553 554
		offsets[0] = 0;

555
		ret = drmModeAddFB2(backend->drm.fd, fb->width, fb->height,
556 557 558 559
				    format, handles, pitches, offsets,
				    &fb->fb_id, 0);
		if (ret) {
			weston_log("addfb2 failed: %m\n");
560 561
			backend->no_addfb2 = 1;
			backend->sprites_are_broken = 1;
562 563 564
		}
	}

565
	if (ret && fb->format->depth && fb->format->bpp)
566
		ret = drmModeAddFB(backend->drm.fd, fb->width, fb->height,
567 568
				   fb->format->depth, fb->format->bpp,
				   fb->stride, fb->handle, &fb->fb_id);
569

570
	if (ret) {
571
		weston_log("failed to create kms fb: %m\n");
572
		goto err_free;
573 574
	}

575
	gbm_bo_set_user_data(bo, fb, drm_fb_destroy_gbm);
576 577

	return fb;
578 579 580 581

err_free:
	free(fb);
	return NULL;
582 583
}

584
static void
585
drm_fb_set_buffer(struct drm_fb *fb, struct weston_buffer *buffer)
586
{
587
	assert(fb->buffer_ref.buffer == NULL);
588
	assert(fb->type == BUFFER_CLIENT);
589
	weston_buffer_reference(&fb->buffer_ref, buffer);
590 591
}

592
static void
593
drm_fb_unref(struct drm_fb *fb)
594 595 596 597
{
	if (!fb)
		return;

598 599 600 601
	assert(fb->refcnt > 0);
	if (--fb->refcnt > 0)
		return;

602 603
	switch (fb->type) {
	case BUFFER_PIXMAN_DUMB:
604
		drm_fb_destroy_dumb(fb);
605
		break;
606
	case BUFFER_CURSOR:
607 608 609 610
	case BUFFER_CLIENT:
		gbm_bo_destroy(fb->bo);
		break;
	case BUFFER_GBM_SURFACE:
611
		gbm_surface_release_buffer(fb->gbm_surface, fb->bo);
612 613 614 615
		break;
	default:
		assert(NULL);
		break;
616 617 618
	}
}

619 620 621 622 623 624 625
static int
drm_view_transform_supported(struct weston_view *ev)
{
	return !ev->transform.enabled ||
		(ev->transform.matrix.type < WESTON_MATRIX_TRANSFORM_ROTATE);
}

626
static uint32_t
627 628 629 630 631 632 633 634
drm_output_check_scanout_format(struct drm_output *output,
				struct weston_surface *es, struct gbm_bo *bo)
{
	uint32_t format;
	pixman_region32_t r;

	format = gbm_bo_get_format(bo);

635 636 637 638
	if (format == GBM_FORMAT_ARGB8888) {
		/* We can scanout an ARGB buffer if the surface's
		 * opaque region covers the whole output, but we have
		 * to use XRGB as the KMS format code. */
639 640 641 642
		pixman_region32_init_rect(&r, 0, 0,
					  output->base.width,
					  output->base.height);
		pixman_region32_subtract(&r, &r, &es->opaque);
643 644

		if (!pixman_region32_not_empty(&r))
645
			format = GBM_FORMAT_XRGB8888;
646 647

		pixman_region32_fini(&r);
648
	}
649

650
	if (output->gbm_format == format)
651
		return format;
652 653

	return 0;
654 655
}

656
static struct weston_plane *
657
drm_output_prepare_scanout_view(struct drm_output *output,
658
				struct weston_view *ev)
659
{
660
	struct drm_backend *b = to_drm_backend(output->base.compositor);
661
	struct weston_buffer *buffer = ev->surface->buffer_ref.buffer;
662
	struct weston_buffer_viewport *viewport = &ev->surface->buffer_viewport;
663
	struct gbm_bo *bo;
664
	uint32_t format;
665

666 667 668 669
	/* Don't import buffers which span multiple outputs. */
	if (ev->output_mask != (1u << output->base.id))
		return NULL;

670 671 672 673 674
	/* We use GBM to import buffers. */
	if (b->gbm == NULL)
		return NULL;

	if (buffer == NULL)
675
		return NULL;
676 677
	if (wl_shm_buffer_get(buffer->resource))
		return NULL;
678

679 680 681 682
	/* Make sure our view is exactly compatible with the output. */
	if (ev->geometry.x != output->base.x ||
	    ev->geometry.y != output->base.y)
		return NULL;
683 684 685 686
	if (buffer->width != output->base.current_mode->width ||
	    buffer->height != output->base.current_mode->height)
		return NULL;

687 688
	if (ev->transform.enabled)
		return NULL;
689 690
	if (ev->geometry.scissor_enabled)
		return NULL;
691 692
	if (viewport->buffer.transform != output->base.transform)
		return NULL;
693 694 695 696 697 698 699
	if (viewport->buffer.scale != output->base.current_scale)
		return NULL;
	if (!drm_view_transform_supported(ev))
		return NULL;

	if (ev->alpha != 1.0f)
		return NULL;
700

701
	bo = gbm_bo_import(b->gbm, GBM_BO_IMPORT_WL_BUFFER,
702
			   buffer->resource, GBM_BO_USE_SCANOUT);
703

704 705 706 707
	/* Unable to use the buffer for scanout */
	if (!bo)
		return NULL;

708
	format = drm_output_check_scanout_format(output, ev->surface, bo);
709
	if (format == 0) {
710
		gbm_bo_destroy(bo);
711
		return NULL;
712 713
	}

714 715
	output->fb_pending = drm_fb_get_from_bo(bo, b, format, BUFFER_CLIENT);
	if (!output->fb_pending) {
716
		gbm_bo_destroy(bo);
717
		return NULL;
718
	}
719

720
	drm_fb_set_buffer(output->fb_pending, buffer);
721

722
	return &output->fb_plane;
723 724
}

725
static struct drm_fb *
726
drm_output_render_gl(struct drm_output *output, pixman_region32_t *damage)
727
{
728
	struct drm_backend *b = to_drm_backend(output->base.compositor);
729
	struct gbm_bo *bo;
730
	struct drm_fb *ret;
731

732 733
	output->base.compositor->renderer->repaint_output(&output->base,
							  damage);
734

735
	bo = gbm_surface_lock_front_buffer(output->gbm_surface);
736
	if (!bo) {
737
		weston_log("failed to lock front buffer: %m\n");
738
		return NULL;
739
	}
740

741 742
	ret = drm_fb_get_from_bo(bo, b, output->gbm_format, BUFFER_GBM_SURFACE);
	if (!ret) {
743
		weston_log("failed to get drm_fb for bo\n");
744
		gbm_surface_release_buffer(output->gbm_surface, bo);
745
		return NULL;
746
	}
747 748 749
	ret->gbm_surface = output->gbm_surface;

	return ret;
750 751
}

752
static struct drm_fb *
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
drm_output_render_pixman(struct drm_output *output, pixman_region32_t *damage)
{
	struct weston_compositor *ec = output->base.compositor;
	pixman_region32_t total_damage, previous_damage;

	pixman_region32_init(&total_damage);
	pixman_region32_init(&previous_damage);

	pixman_region32_copy(&previous_damage, damage);

	pixman_region32_union(&total_damage, damage, &output->previous_damage);
	pixman_region32_copy(&output->previous_damage, &previous_damage);

	output->current_image ^= 1;

	pixman_renderer_output_set_buffer(&output->base,
					  output->image[output->current_image]);

	ec->renderer->repaint_output(&output->base, &total_damage);

	pixman_region32_fini(&total_damage);
	pixman_region32_fini(&previous_damage);
775 776

	return drm_fb_ref(output->dumb[output->current_image]);
777 778 779 780 781
}

static void
drm_output_render(struct drm_output *output, pixman_region32_t *damage)
{
782
	struct weston_compositor *c = output->base.compositor;
783
	struct drm_backend *b = to_drm_backend(c);
784
	struct drm_fb *fb;
785

786 787 788 789 790
	/* If we already have a client buffer promoted to scanout, then we don't
	 * want to render. */
	if (output->fb_pending)
		return;

791
	if (b->use_pixman)
792
		fb = drm_output_render_pixman(output, damage);
793
	else
794 795 796 797 798
		fb = drm_output_render_gl(output, damage);

	if (!fb)
		return;
	output->fb_pending = fb;
799

800 801
	pixman_region32_subtract(&c->primary_plane.damage,
				 &c->primary_plane.damage, damage);
802 803
}

804 805 806 807 808
static void
drm_output_set_gamma(struct weston_output *output_base,
		     uint16_t size, uint16_t *r, uint16_t *g, uint16_t *b)
{
	int rc;
809
	struct drm_output *output = to_drm_output(output_base);
810
	struct drm_backend *backend =
811
		to_drm_backend(output->base.compositor);
812 813 814 815 816 817 818

	/* check */
	if (output_base->gamma_size != size)
		return;
	if (!output->original_crtc)
		return;

819
	rc = drmModeCrtcSetGamma(backend->drm.fd,
820 821 822 823 824 825
				 output->crtc_id,
				 size, r, g, b);
	if (rc)
		weston_log("set gamma failed: %m\n");
}

826
/* Determine the type of vblank synchronization to use for the output.
827
 *
828 829 830 831 832
 * The pipe parameter indicates which CRTC is in use.  Knowing this, we
 * can determine which vblank sequence type to use for it.  Traditional
 * cards had only two CRTCs, with CRTC 0 using no special flags, and
 * CRTC 1 using DRM_VBLANK_SECONDARY.  The first bit of the pipe
 * parameter indicates this.
833
 *
834 835 836 837 838
 * Bits 1-5 of the pipe parameter are 5 bit wide pipe number between
 * 0-31.  If this is non-zero it indicates we're dealing with a
 * multi-gpu situation and we need to calculate the vblank sync
 * using DRM_BLANK_HIGH_CRTC_MASK.
 */
839 840
static unsigned int
drm_waitvblank_pipe(struct drm_output *output)
841 842 843 844 845 846 847 848 849 850
{
	if (output->pipe > 1)
		return (output->pipe << DRM_VBLANK_HIGH_CRTC_SHIFT) &
				DRM_VBLANK_HIGH_CRTC_MASK;
	else if (output->pipe > 0)
		return DRM_VBLANK_SECONDARY;
	else
		return 0;
}

851
static int
852
drm_output_repaint(struct weston_output *output_base,
853 854
		   pixman_region32_t *damage,
		   void *repaint_data)
855
{
856
	struct drm_output *output = to_drm_output(output_base);
857
	struct drm_backend *backend =
858
		to_drm_backend(output->base.compositor);
859
	struct drm_plane *s;
860
	struct drm_mode *mode;
861
	int ret = 0;
862

863
	if (output->disable_pending || output->destroy_pending)
864
		return -1;
865

866 867
	assert(!output->fb_last);

868
	drm_output_render(output, damage);
869
	if (!output->fb_pending)
870
		return -1;
871

872
	mode = container_of(output->base.current_mode, struct drm_mode, base);
873 874
	if (!output->fb_current ||
	    output->fb_current->stride != output->fb_pending->stride) {
875
		ret = drmModeSetCrtc(backend->drm.fd, output->crtc_id,
876
				     output->fb_pending->fb_id, 0, 0,
877 878 879
				     &output->connector_id, 1,
				     &mode->mode_info);
		if (ret) {
880
			weston_log("set mode failed: %m\n");
881
			goto err_pageflip;
882
		}
883
		output_base->set_dpms(output_base, WESTON_DPMS_ON);
884 885
	}

886
	if (drmModePageFlip(backend->drm.fd, output->crtc_id,
887
			    output->fb_pending->fb_id,
888
			    DRM_MODE_PAGE_FLIP_EVENT, output) < 0) {
889
		weston_log("queueing pageflip failed: %m\n");
890
		goto err_pageflip;
891
	}
892

893 894 895 896
	output->fb_last = output->fb_current;
	output->fb_current = output->fb_pending;
	output->fb_pending = NULL;

897
	assert(!output->page_flip_pending);
898 899
	output->page_flip_pending = 1;

900 901 902 903
	if (output->pageflip_timer)
		wl_event_source_timer_update(output->pageflip_timer,
		                             backend->pageflip_timeout);

904 905
	drm_output_set_cursor(output);

906 907 908
	/*
	 * Now, update all the sprite surfaces
	 */
909
	wl_list_for_each(s, &backend->sprite_list, link) {
910
		uint32_t flags = 0, fb_id = 0;
911 912 913 914 915
		drmVBlank vbl = {
			.request.type = DRM_VBLANK_RELATIVE | DRM_VBLANK_EVENT,
			.request.sequence = 1,
		};

916 917
		/* XXX: Set output much earlier, so we don't attempt to place
		 *      planes on entirely the wrong output. */
918
		if ((!s->fb_current && !s->fb_pending) ||
919
		    !drm_plane_crtc_supported(output, s))
920 921
			continue;

922 923
		if (s->fb_pending && !backend->sprites_hidden)
			fb_id = s->fb_pending->fb_id;
924

925
		ret = drmModeSetPlane(backend->drm.fd, s->plane_id,
926
				      output->crtc_id, fb_id, flags,
927 928 929 930 931
				      s->dest_x, s->dest_y,
				      s->dest_w, s->dest_h,
				      s->src_x, s->src_y,
				      s->src_w, s->src_h);
		if (ret)
932
			weston_log("setplane failed: %d: %s\n",
933 934
				ret, strerror(errno));

935
		vbl.request.type |= drm_waitvblank_pipe(output);
936

937 938 939 940 941
		/*
		 * Queue a vblank signal so we know when the surface
		 * becomes active on the display or has been replaced.
		 */
		vbl.request.signal = (unsigned long)s;
942
		ret = drmWaitVBlank(backend->drm.fd, &vbl);
943
		if (ret) {
944
			weston_log("vblank event request failed: %d: %s\n",
945 946
				ret, strerror(errno));
		}
947 948

		s->output = output;
949 950 951
		s->fb_last = s->fb_current;
		s->fb_current = s->fb_pending;
		s->fb_pending = NULL;
952
		output->vblank_pending++;
953 954
	}

955 956 957
	return 0;

err_pageflip:
958
	output->cursor_view = NULL;
959 960 961
	if (output->fb_pending) {
		drm_fb_unref(output->fb_pending);
		output->fb_pending = NULL;
962 963 964
	}

	return -1;
965 966
}

967 968 969
static void
drm_output_start_repaint_loop(struct weston_output *output_base)
{
970 971 972
	struct drm_output *output = to_drm_output(output_base);
	struct drm_backend *backend =
		to_drm_backend(output_base->compositor);
973
	uint32_t fb_id;
974 975 976 977 978 979 980 981 982
	struct timespec ts, tnow;
	struct timespec vbl2now;
	int64_t refresh_nsec;
	int ret;
	drmVBlank vbl = {
		.request.type = DRM_VBLANK_RELATIVE,
		.request.sequence = 0,
		.request.signal = 0,
	};
983

984
	if (output->disable_pending || output->destroy_pending)
985 986
		return;

987
	if (!output->fb_current) {
988
		/* We can't page flip if there's no mode set */
989
		goto finish_frame;
990 991
	}

992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
	/* Try to get current msc and timestamp via instant query */
	vbl.request.type |= drm_waitvblank_pipe(output);
	ret = drmWaitVBlank(backend->drm.fd, &vbl);

	/* Error ret or zero timestamp means failure to get valid timestamp */
	if ((ret == 0) && (vbl.reply.tval_sec > 0 || vbl.reply.tval_usec > 0)) {
		ts.tv_sec = vbl.reply.tval_sec;
		ts.tv_nsec = vbl.reply.tval_usec * 1000;

		/* Valid timestamp for most recent vblank - not stale?
		 * Stale ts could happen on Linux 3.17+, so make sure it
		 * is not older than 1 refresh duration since now.
		 */
		weston_compositor_read_presentation_clock(backend->compositor,
							  &tnow);
		timespec_sub(&vbl2now, &tnow, &ts);
		refresh_nsec =
			millihz_to_nsec(output->base.current_mode->refresh);
		if (timespec_to_nsec(&vbl2now) < refresh_nsec) {
			drm_output_update_msc(output, vbl.reply.sequence);
			weston_output_finish_frame(output_base, &ts,
1013
						WP_PRESENTATION_FEEDBACK_INVALID);
1014 1015 1016 1017 1018 1019 1020
			return;
		}
	}

	/* Immediate query didn't provide valid timestamp.
	 * Use pageflip fallback.
	 */
1021
	fb_id = output->fb_current->fb_id;
1022

1023 1024 1025
	assert(!output->page_flip_pending);
	assert(!output->fb_last);

1026
	if (drmModePageFlip(backend->drm.fd, output->crtc_id, fb_id,
1027 1028
			    DRM_MODE_PAGE_FLIP_EVENT, output) < 0) {
		weston_log("queueing pageflip failed: %m\n");
1029
		goto finish_frame;
1030
	}
1031

1032 1033 1034 1035
	if (output->pageflip_timer)
		wl_event_source_timer_update(output->pageflip_timer,
		                             backend->pageflip_timeout);

1036 1037 1038
	output->fb_last = drm_fb_ref(output->fb_current);
	output->page_flip_pending = 1;

1039 1040 1041 1042
	return;

finish_frame:
	/* if we cannot page-flip, immediately finish frame */
1043
	weston_output_finish_frame(output_base, NULL,
1044
				   WP_PRESENTATION_FEEDBACK_INVALID);
1045 1046
}

1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
static void
drm_output_update_msc(struct drm_output *output, unsigned int seq)
{
	uint64_t msc_hi = output->base.msc >> 32;

	if (seq < (output->base.msc & 0xffffffff))
		msc_hi++;

	output->base.msc = (msc_hi << 32) + seq;
}

1058 1059 1060 1061
static void
vblank_handler(int fd, unsigned int frame, unsigned int sec, unsigned int usec,
	       void *data)
{
1062
	struct drm_plane *s = (struct drm_plane *)data;
1063
	struct drm_output *output = s->output;
1064
	struct timespec ts;
1065 1066
	uint32_t flags = WP_PRESENTATION_FEEDBACK_KIND_HW_COMPLETION |
			 WP_PRESENTATION_FEEDBACK_KIND_HW_CLOCK;
1067

1068
	drm_output_update_msc(output, frame);
1069 1070
	output->vblank_pending--;
	assert(output->vblank_pending >= 0);
1071

1072 1073 1074
	assert(s->fb_last || s->fb_current);
	drm_fb_unref(s->fb_last);
	s->fb_last = NULL;
1075

1076
	if (!output->page_flip_pending && !output->vblank_pending) {
1077 1078 1079 1080
		/* Stop the pageflip timer instead of rearming it here */
		if (output->pageflip_timer)
			wl_event_source_timer_update(output->pageflip_timer, 0);

1081 1082
		ts.tv_sec = sec;
		ts.tv_nsec = usec * 1000;
1083
		weston_output_finish_frame(&output->base, &ts, flags);
1084
	}
1085 1086
}

1087
static void
1088
drm_output_destroy(struct weston_output *base);
1089

1090 1091 1092 1093
static void
page_flip_handler(int fd, unsigned int frame,
		  unsigned int sec, unsigned int usec, void *data)
{
1094
	struct drm_output *output = data;
1095
	struct timespec ts;
1096 1097 1098
	uint32_t flags = WP_PRESENTATION_FEEDBACK_KIND_VSYNC |
			 WP_PRESENTATION_FEEDBACK_KIND_HW_COMPLETION |
			 WP_PRESENTATION_FEEDBACK_KIND_HW_CLOCK;
1099

1100 1101
	drm_output_update_msc(output, frame);

1102
	assert(output->page_flip_pending);
1103
	output->page_flip_pending = 0;
1104

1105 1106 1107
	drm_fb_unref(output->fb_last);
	output->fb_last = NULL;

1108 1109
	if (output->destroy_pending)
		drm_output_destroy(&output->base);
1110 1111
	else if (output->disable_pending)
		weston_output_disable(&output->base);
1112
	else if (!output->vblank_pending) {
1113 1114 1115 1116
		/* Stop the pageflip timer instead of rearming it here */
		if (output->pageflip_timer)
			wl_event_source_timer_update(output->pageflip_timer, 0);

1117 1118
		ts.tv_sec = sec;
		ts.tv_nsec = usec * 1000;
1119
		weston_output_finish_frame(&output->base, &ts, flags);
1120 1121 1122 1123 1124

		/* We can't call this from frame_notify, because the output's
		 * repaint needed flag is cleared just after that */
		if (output->recorder)
			weston_output_schedule_repaint(&output->base);
1125
	}
1126 1127
}

1128
static uint32_t
1129
drm_output_check_plane_format(struct drm_plane *p,
1130
			       struct weston_view *ev, struct gbm_bo *bo)
1131
{
1132 1133 1134 1135 1136 1137 1138
	uint32_t i, format;

	format = gbm_bo_get_format(bo);

	if (format == GBM_FORMAT_ARGB8888) {
		pixman_region32_t r;

1139
		pixman_region32_init_rect(&r, 0, 0,
1140 1141
					  ev->surface->width,
					  ev->surface->height);
1142
		pixman_region32_subtract(&r, &r, &ev->surface->opaque);
1143 1144 1145 1146 1147 1148

		if (!pixman_region32_not_empty(&r))
			format = GBM_FORMAT_XRGB8888;

		pixman_region32_fini(&r);
	}
1149

1150 1151
	for (i = 0; i < p->count_formats; i++)
		if (p->formats[i] == format)
1152
			return format;
1153 1154 1155 1156

	return 0;
}

1157
static struct weston_plane *
1158
drm_output_prepare_overlay_view(struct drm_output *output,
1159
				struct weston_view *ev)
1160
{
1161
	struct weston_compositor *ec = output->base.compositor;
1162
	struct drm_backend *b = to_drm_backend(ec);
1163
	struct weston_buffer_viewport *viewport = &ev->surface->buffer_viewport;
1164
	struct wl_resource *buffer_resource;
1165
	struct drm_plane *p;
1166
	struct linux_dmabuf_buffer *dmabuf;
1167 1168 1169
	int found = 0;
	struct gbm_bo *bo;
	pixman_region32_t dest_rect, src_rect;
1170
	pixman_box32_t *box, tbox;
1171
	uint32_t format;
1172
	wl_fixed_t sx1, sy1, sx2, sy2;
1173

1174
	if (b->sprites_are_broken)
1175
		return NULL;
1176

1177
	/* Don't import buffers which span multiple outputs. */
1178
	if (ev->output_mask != (1u << output->base.id))
1179
		return NULL;
1180

1181 1182
	/* We can only import GBM buffers. */
	if (b->gbm == NULL)
1183
		return NULL;
1184

1185
	if (ev->surface->buffer_ref.buffer == NULL)
1186
		return NULL;
1187
	buffer_resource = ev->surface->buffer_ref.buffer->resource;
1188
	if (wl_shm_buffer_get(buffer_resource))
1189 1190
		return NULL;

1191 1192 1193 1194
	if (viewport->buffer.transform != output->base.transform)
		return NULL;
	if (viewport->buffer.scale != output->base.current_scale)
		return NULL;
1195
	if (!drm_view_transform_supported(ev))
1196
		return NULL;
1197

1198 1199 1200
	if (ev->alpha != 1.0f)
		return NULL;

1201 1202
	wl_list_for_each(p, &b->sprite_list, link) {
		if (!drm_plane_crtc_supported(output, p))
1203 1204
			continue;

1205
		if (!p->fb_pending) {
1206 1207 1208 1209 1210 1211 1212
			found = 1;
			break;
		}
	}

	/* No sprites available */
	if (!found)