aboutsummaryrefslogtreecommitdiff
path: root/backend/drm/drm.c
blob: 94d79e5ce0d2dd41fa4e218defea803ecf1ed310 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <errno.h>
#include <xf86drm.h>
#include <xf86drmMode.h>
#include <drm_mode.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <gbm.h>
#include <GLES3/gl3.h>

#include "backend/drm/backend.h"
#include "backend/drm/drm.h"
#include "backend/drm/event.h"
#include "common/log.h"

static const char *conn_name[] = {
	[DRM_MODE_CONNECTOR_Unknown]     = "Unknown",
	[DRM_MODE_CONNECTOR_VGA]         = "VGA",
	[DRM_MODE_CONNECTOR_DVII]        = "DVI-I",
	[DRM_MODE_CONNECTOR_DVID]        = "DVI-D",
	[DRM_MODE_CONNECTOR_DVIA]        = "DVI-A",
	[DRM_MODE_CONNECTOR_Composite]   = "Composite",
	[DRM_MODE_CONNECTOR_SVIDEO]      = "SVIDEO",
	[DRM_MODE_CONNECTOR_LVDS]        = "LVDS",
	[DRM_MODE_CONNECTOR_Component]   = "Component",
	[DRM_MODE_CONNECTOR_9PinDIN]     = "DIN",
	[DRM_MODE_CONNECTOR_DisplayPort] = "DP",
	[DRM_MODE_CONNECTOR_HDMIA]       = "HDMI-A",
	[DRM_MODE_CONNECTOR_HDMIB]       = "HDMI-B",
	[DRM_MODE_CONNECTOR_TV]          = "TV",
	[DRM_MODE_CONNECTOR_eDP]         = "eDP",
	[DRM_MODE_CONNECTOR_VIRTUAL]     = "Virtual",
	[DRM_MODE_CONNECTOR_DSI]         = "DSI",
};

static const char *egl_error(void)
{
	switch (eglGetError()) {
	case EGL_SUCCESS:
		return "Success";
	case EGL_NOT_INITIALIZED:
		return "Not initialized";
	case EGL_BAD_ACCESS:
		return "Bad access";
	case EGL_BAD_ALLOC:
		return "Bad alloc";
	case EGL_BAD_ATTRIBUTE:
		return "Bad attribute";
	case EGL_BAD_CONTEXT:
		return "Bad Context";
	case EGL_BAD_CONFIG:
		return "Bad Config";
	case EGL_BAD_CURRENT_SURFACE:
		return "Bad current surface";
	case EGL_BAD_DISPLAY:
		return "Bad display";
	case EGL_BAD_SURFACE:
		return "Bad surface";
	case EGL_BAD_MATCH:
		return "Bad match";
	case EGL_BAD_PARAMETER:
		return "Bad parameter";
	case EGL_BAD_NATIVE_PIXMAP:
		return "Bad native pixmap";
	case EGL_BAD_NATIVE_WINDOW:
		return "Bad native window";
	case EGL_CONTEXT_LOST:
		return "Context lost";
	default:
		return "Unknown";
	}
}

// EGL extensions
PFNEGLGETPLATFORMDISPLAYEXTPROC get_platform_display;
PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC create_platform_window_surface;

static bool egl_exts()
{
	get_platform_display = (PFNEGLGETPLATFORMDISPLAYEXTPROC)
		eglGetProcAddress("eglGetPlatformDisplayEXT");

	if (!get_platform_display) {
		wlr_log(L_ERROR, "Failed to load EGL extension 'eglGetPlatformDisplayEXT'");
		return false;
	}

	create_platform_window_surface = (PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC)
		eglGetProcAddress("eglCreatePlatformWindowSurfaceEXT");

	if (!get_platform_display) {
		wlr_log(L_ERROR, "Failed to load EGL extension 'eglCreatePlatformWindowSurfaceEXT'");
		return false;
	}

	return true;
}

static bool egl_get_config(EGLDisplay disp, EGLConfig *out)
{
	EGLint count = 0, matched = 0, ret;

	ret = eglGetConfigs(disp, NULL, 0, &count);
	if (ret == EGL_FALSE || count == 0) {
		return false;
	}

	EGLConfig configs[count];

	ret = eglChooseConfig(disp, NULL, configs, count, &matched);
	if (ret == EGL_FALSE) {
		return false;
	}

	for (int i = 0; i < matched; ++i) {
		EGLint gbm_format;

		if (!eglGetConfigAttrib(disp,
					configs[i],
					EGL_NATIVE_VISUAL_ID,
					&gbm_format))
			continue;

		if (gbm_format == GBM_FORMAT_XRGB8888) {
			*out = configs[i];
			return true;
		}
	}

	return false;
}

bool wlr_drm_renderer_init(struct wlr_drm_renderer *renderer,
		struct wlr_drm_backend *backend, int fd)
{
	if (!egl_exts())
		return false;

	renderer->gbm = gbm_create_device(fd);
	if (!renderer->gbm) {
		wlr_log(L_ERROR, "Failed to create GBM device: %s", strerror(errno));
		return false;
	}

	if (eglBindAPI(EGL_OPENGL_ES_API) == EGL_FALSE) {
		wlr_log(L_ERROR, "Failed to bind to the OpenGL ES API: %s", egl_error());
		goto error_gbm;
	}

	renderer->egl.disp = get_platform_display(EGL_PLATFORM_GBM_MESA, renderer->gbm, NULL);
	if (renderer->egl.disp == EGL_NO_DISPLAY) {
		wlr_log(L_ERROR, "Failed to create EGL display: %s", egl_error());
		goto error_gbm;
	}

	if (eglInitialize(renderer->egl.disp, NULL, NULL) == EGL_FALSE) {
		wlr_log(L_ERROR, "Failed to initialize EGL: %s", egl_error());
		goto error_egl;
	}

	if (!egl_get_config(renderer->egl.disp, &renderer->egl.conf)) {
		wlr_log(L_ERROR, "Failed to get EGL config");
		goto error_egl;
	}

	static const EGLint attribs[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE};

	renderer->egl.context = eglCreateContext(renderer->egl.disp,
			renderer->egl.conf, EGL_NO_CONTEXT, attribs);

	if (renderer->egl.context == EGL_NO_CONTEXT) {
		wlr_log(L_ERROR, "Failed to create EGL context: %s", egl_error());
		goto error_egl;
	}

	renderer->fd = fd;
	renderer->backend = backend;

	return true;

error_egl:
	eglTerminate(renderer->egl.disp);
	eglReleaseThread();
	eglMakeCurrent(EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);

error_gbm:
	gbm_device_destroy(renderer->gbm);

	return false;
}

void wlr_drm_renderer_free(struct wlr_drm_renderer *renderer)
{
	if (!renderer)
		return;

	eglDestroyContext(renderer->egl.disp, renderer->egl.context);
	eglTerminate(renderer->egl.disp);
	eglReleaseThread();
	eglMakeCurrent(EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);

	gbm_device_destroy(renderer->gbm);
}

void wlr_drm_scan_connectors(struct wlr_drm_backend *backend)
{
	drmModeRes *res = drmModeGetResources(backend->fd);
	if (!res) {
		wlr_log(L_ERROR, "Failed to get DRM resources");
		return;
	}

	// I don't know if this needs to be allocated with realloc like this,
	// as it may not even be possible for the number of connectors to change.
	// I'll just have to see how DisplayPort MST works with DRM.
	if ((size_t)res->count_connectors > backend->display_len) {
		struct wlr_drm_display *new = realloc(backend->displays, sizeof *new * res->count_connectors);
		if (!new) {
			wlr_log(L_ERROR, "Allocation failed: %s", strerror(errno));
			goto error;
		}

		for (int i = backend->display_len; i < res->count_connectors; ++i) {
			new[i] = (struct wlr_drm_display) {
				.state = DRM_DISP_INVALID,
				.renderer = &backend->renderer,
			};
		}

		backend->display_len = res->count_connectors;
		backend->displays = new;
	}

	for (int i = 0; i < res->count_connectors; ++i) {
		struct wlr_drm_display *disp = &backend->displays[i];
		drmModeConnector *conn = drmModeGetConnector(backend->fd, res->connectors[i]);
		if (!conn)
			continue;

		if (backend->displays[i].state == DRM_DISP_INVALID) {
			disp->state = DRM_DISP_DISCONNECTED;
			disp->connector = res->connectors[i];
			snprintf(disp->name, sizeof disp->name, "%s-%"PRIu32,
				 conn_name[conn->connector_type],
				 conn->connector_type_id);
		}

		if (disp->state == DRM_DISP_DISCONNECTED &&
		    conn->connection == DRM_MODE_CONNECTED) {
			disp->state = DRM_DISP_NEEDS_MODESET;
			wlr_drm_add_event(backend, disp, DRM_EV_DISPLAY_ADD);

		} else if (disp->state == DRM_DISP_CONNECTED &&
		    conn->connection != DRM_MODE_CONNECTED) {
			disp->state = DRM_DISP_DISCONNECTED;
			wlr_drm_display_free(disp, false);
			wlr_drm_add_event(backend, disp, DRM_EV_DISPLAY_REM);
		}

		drmModeFreeConnector(conn);
	}

error:
	drmModeFreeResources(res);
}

static void free_fb(struct gbm_bo *bo, void *data)
{
	uint32_t *id = data;

	if (id && *id)
		drmModeRmFB(gbm_bo_get_fd(bo), *id);

	free(id);
}

static uint32_t get_fb_for_bo(int fd, struct gbm_bo *bo)
{
	uint32_t *id = gbm_bo_get_user_data(bo);

	if (id)
		return *id;

	id = calloc(1, sizeof *id);
	if (!id) {
		wlr_log(L_ERROR, "Allocation failed: %s", strerror(errno));
		return 0;
	}

	drmModeAddFB(fd, gbm_bo_get_width(bo), gbm_bo_get_height(bo), 24, 32,
		     gbm_bo_get_stride(bo), gbm_bo_get_handle(bo).u32, id);

	gbm_bo_set_user_data(bo, id, free_fb);

	return *id;
}

static bool display_init_renderer(struct wlr_drm_renderer *renderer,
		struct wlr_drm_display *disp)
{
	disp->renderer = renderer;

	disp->gbm = gbm_surface_create(renderer->gbm,
				       disp->width, disp->height,
				       GBM_FORMAT_XRGB8888,
				       GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING);
	if (!disp->gbm) {
		wlr_log(L_ERROR, "Failed to create GBM surface for %s: %s", disp->name,
			strerror(errno));
		return false;
	}

	disp->egl = create_platform_window_surface(renderer->egl.disp, renderer->egl.conf,
						   disp->gbm, NULL);
	if (disp->egl == EGL_NO_SURFACE) {
		wlr_log(L_ERROR, "Failed to create EGL surface for %s: %s", disp->name,
			egl_error());
		return false;
	}

	// Render black frame

	eglMakeCurrent(renderer->egl.disp, disp->egl, disp->egl, renderer->egl.context);

	glViewport(0, 0, disp->width, disp->height);
	glClearColor(0.0, 0.0, 0.0, 1.0);
	glClear(GL_COLOR_BUFFER_BIT);

	eglSwapBuffers(renderer->egl.disp, disp->egl);

	struct gbm_bo *bo = gbm_surface_lock_front_buffer(disp->gbm);
	uint32_t fb_id = get_fb_for_bo(renderer->fd, bo);

	drmModeSetCrtc(renderer->fd, disp->crtc, fb_id, 0, 0,
		       &disp->connector, 1, disp->active_mode);
	drmModePageFlip(renderer->fd, disp->crtc, fb_id, DRM_MODE_PAGE_FLIP_EVENT, disp);

	gbm_surface_release_buffer(disp->gbm, bo);

	return true;
}

static drmModeModeInfo *select_mode(size_t num_modes,
		drmModeModeInfo modes[static num_modes],
		drmModeCrtc *old_crtc,
		const char *str)
{
	if (strcmp(str, "preferred") == 0)
		return &modes[0];

	if (strcmp(str, "current") == 0) {
		if (!old_crtc) {
			wlr_log(L_ERROR, "Display does not have currently configured mode");
			return NULL;
		}

		for (size_t i = 0; i < num_modes; ++i) {
			if (memcmp(&modes[i], &old_crtc->mode, sizeof modes[0]) == 0)
				return &modes[i];
		}

		// We should never get here
		assert(0);
	}

	unsigned width = 0;
	unsigned height = 0;
	unsigned rate = 0;
	int ret;

	if ((ret = sscanf(str, "%ux%u@%u", &width, &height, &rate)) != 2 && ret != 3) {
		wlr_log(L_ERROR, "Invalid modesetting string '%s'", str);
		return NULL;
	}

	for (size_t i = 0; i < num_modes; ++i) {
		if (modes[i].hdisplay == width &&
		    modes[i].vdisplay == height &&
		    (!rate || modes[i].vrefresh == rate))
			return &modes[i];
	}

	wlr_log(L_ERROR, "Unable to find mode %ux%u@%u", width, height, rate);
	return NULL;
}

bool wlr_drm_display_modeset(struct wlr_drm_backend *backend,
		struct wlr_drm_display *disp, const char *str)
{
	wlr_log(L_INFO, "Modesetting %s with '%s'", disp->name, str);

	drmModeConnector *conn = drmModeGetConnector(backend->fd, disp->connector);
	if (!conn) {
		wlr_log(L_ERROR, "Failed to get DRM connector");
		goto error;
	}

	if (conn->connection != DRM_MODE_CONNECTED || conn->count_modes == 0) {
		wlr_log(L_ERROR, "%s is not connected", disp->name);
		goto error;
	}

	disp->num_modes = conn->count_modes;
	disp->modes = malloc(sizeof *disp->modes * disp->num_modes);
	if (!disp->modes) {
		wlr_log(L_ERROR, "Allocation failed: %s", strerror(errno));
		goto error;
	}
	memcpy(disp->modes, conn->modes, sizeof *disp->modes * disp->num_modes);

	wlr_log(L_INFO, "Detected modes:");
	for (size_t i = 0; i < disp->num_modes; ++i)
		wlr_log(L_INFO, "  %"PRIu16"@%"PRIu16"@%"PRIu32,
			disp->modes[i].hdisplay, disp->modes[i].vdisplay,
			disp->modes[i].vrefresh);

	drmModeEncoder *curr_enc = drmModeGetEncoder(backend->fd, conn->encoder_id);
	if (curr_enc) {
		disp->old_crtc = drmModeGetCrtc(backend->fd, curr_enc->crtc_id);
		free(curr_enc);
	}

	disp->active_mode = select_mode(disp->num_modes, disp->modes, disp->old_crtc, str);
	if (!disp->active_mode) {
		wlr_log(L_ERROR, "Failed to configure %s", disp->name);
		goto error;
	}

	drmModeRes *res = drmModeGetResources(backend->fd);
	if (!res) {
		wlr_log(L_ERROR, "Failed to get DRM resources");
		goto error;
	}

	bool success = false;
	for (int i = 0; !success && i < conn->count_encoders; ++i) {
		drmModeEncoder *enc = drmModeGetEncoder(backend->fd, conn->encoders[i]);
		if (!enc)
			continue;

		for (int j = 0; j < res->count_crtcs; ++j) {
			if ((enc->possible_crtcs & (1 << j)) == 0)
				continue;

			if ((backend->taken_crtcs & (1 << j)) == 0) {
				backend->taken_crtcs |= 1 << j;
				disp->crtc = res->crtcs[j];

				success = true;
				break;
			}
		}

		drmModeFreeEncoder(enc);
	}

	drmModeFreeResources(res);

	if (!success) {
		wlr_log(L_ERROR, "Failed to find CRTC for %s", disp->name);
		goto error;
	}

	disp->state = DRM_DISP_CONNECTED;

	disp->width = disp->active_mode->hdisplay;
	disp->height = disp->active_mode->vdisplay;

	if (!display_init_renderer(&backend->renderer, disp)) {
		wlr_log(L_ERROR, "Failed to initalise renderer for %s", disp->name);
		goto error;
	}

	drmModeFreeConnector(conn);

	wlr_log(L_INFO, "Configuring %s with mode %"PRIu16"x%"PRIu16"@%"PRIu32"\n",
		disp->name, disp->active_mode->hdisplay, disp->active_mode->vdisplay,
		disp->active_mode->vrefresh);

	return true;

error:
	disp->state = DRM_DISP_DISCONNECTED;
	drmModeFreeConnector(conn);
	free(disp->modes);

	wlr_drm_add_event(backend, disp, DRM_EV_DISPLAY_REM);

	return false;
}

static void page_flip_handler(int fd,
		unsigned seq,
		unsigned tv_sec,
		unsigned tv_usec,
		void *user)
{
	struct wlr_drm_display *disp = user;

	disp->pageflip_pending = true;
	if (!disp->cleanup)
		wlr_drm_add_event(disp->renderer->backend, disp, DRM_EV_RENDER);
}

void wlr_drm_display_free(struct wlr_drm_display *disp, bool restore)
{
	if (!disp || disp->state != DRM_DISP_CONNECTED)
		return;

	struct wlr_drm_renderer *renderer = disp->renderer;

	eglDestroySurface(renderer->egl.disp, disp->egl);
	gbm_surface_destroy(disp->gbm);

	free(disp->modes);
	disp->state = DRM_DISP_DISCONNECTED;

	if (!restore)
		return;

	drmModeCrtc *crtc = disp->old_crtc;
	if (crtc) {
		// Wait for exising page flips to finish

		drmEventContext event = {
			.version = DRM_EVENT_CONTEXT_VERSION,
			.page_flip_handler = page_flip_handler,
		};

		disp->cleanup = true;
		while (disp->pageflip_pending)
			drmHandleEvent(renderer->fd, &event);

		drmModeSetCrtc(renderer->fd, crtc->crtc_id, crtc->buffer_id,
			       crtc->x, crtc->y, &disp->connector,
			       1, &crtc->mode);
		drmModeFreeCrtc(crtc);
	}
}

void wlr_drm_event(int fd)
{
	drmEventContext event = {
		.version = DRM_EVENT_CONTEXT_VERSION,
		.page_flip_handler = page_flip_handler,
	};

	drmHandleEvent(fd, &event);
}

void wlr_drm_display_begin(struct wlr_drm_display *disp)
{
	struct wlr_drm_renderer *renderer = disp->renderer;
	eglMakeCurrent(renderer->egl.disp, disp->egl, disp->egl, renderer->egl.context);
}

void wlr_drm_display_end(struct wlr_drm_display *disp)
{
	struct wlr_drm_renderer *renderer = disp->renderer;
	eglSwapBuffers(renderer->egl.disp, disp->egl);

	struct gbm_bo *bo = gbm_surface_lock_front_buffer(disp->gbm);
	uint32_t fb_id = get_fb_for_bo(renderer->fd, bo);

	drmModePageFlip(renderer->fd, disp->crtc, fb_id, DRM_MODE_PAGE_FLIP_EVENT, disp);

	gbm_surface_release_buffer(disp->gbm, bo);

	disp->pageflip_pending = false;
}