compositor-drm: Close drm fd on exec
[profile/ivi/weston.git] / compositor / compositor-drm.c
1 /*
2  * Copyright © 2008-2010 Kristian Høgsberg
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  */
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <fcntl.h>
23 #include <unistd.h>
24
25 #include <xf86drm.h>
26 #include <xf86drmMode.h>
27
28 #define GL_GLEXT_PROTOTYPES
29 #define EGL_EGLEXT_PROTOTYPES
30 #include <GLES2/gl2.h>
31 #include <GLES2/gl2ext.h>
32 #include <EGL/egl.h>
33 #include <EGL/eglext.h>
34
35 #include "compositor.h"
36
37 struct drm_compositor {
38         struct wlsc_compositor base;
39
40         struct udev *udev;
41         struct wl_event_source *drm_source;
42
43         struct udev_monitor *udev_monitor;
44         struct wl_event_source *udev_drm_source;
45
46         struct {
47                 int fd;
48         } drm;
49         uint32_t crtc_allocator;
50         uint32_t connector_allocator;
51         struct tty *tty;
52 };
53
54 struct drm_output {
55         struct wlsc_output   base;
56
57         drmModeModeInfo mode;
58         uint32_t crtc_id;
59         uint32_t connector_id;
60         GLuint rbo[2];
61         uint32_t fb_id[2];
62         EGLImageKHR image[2];
63         uint32_t current;       
64 };
65
66 static int
67 drm_output_prepare_render(struct wlsc_output *output_base)
68 {
69         struct drm_output *output = (struct drm_output *) output_base;
70
71         glFramebufferRenderbuffer(GL_FRAMEBUFFER,
72                                   GL_COLOR_ATTACHMENT0,
73                                   GL_RENDERBUFFER,
74                                   output->rbo[output->current]);
75
76         if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
77                 return -1;
78
79         return 0;
80 }
81
82 static void
83 drm_compositor_present(struct wlsc_compositor *ec)
84 {
85         struct drm_compositor *c = (struct drm_compositor *) ec;
86         struct drm_output *output;
87
88         wl_list_for_each(output, &ec->output_list, base.link) {
89                 if (drm_output_prepare_render(&output->base))
90                         continue;
91                 glFlush();
92
93                 output->current ^= 1;
94
95                 drmModePageFlip(c->drm.fd, output->crtc_id,
96                                 output->fb_id[output->current ^ 1],
97                                 DRM_MODE_PAGE_FLIP_EVENT, output);
98         }       
99 }
100
101 static void
102 page_flip_handler(int fd, unsigned int frame,
103                   unsigned int sec, unsigned int usec, void *data)
104 {
105         struct wlsc_output *output = data;
106         struct wlsc_compositor *compositor = output->compositor;
107         uint32_t msecs;
108
109         /* run synchronized to first output, ignore other pflip events.
110          * FIXME: support per output/surface frame callbacks */
111         if (output == container_of(compositor->output_list.prev,
112                                    struct wlsc_output, link)) {
113                 msecs = sec * 1000 + usec / 1000;
114                 wlsc_compositor_finish_frame(compositor, msecs);
115         }
116 }
117
118 static void
119 on_drm_input(int fd, uint32_t mask, void *data)
120 {
121         drmEventContext evctx;
122
123         memset(&evctx, 0, sizeof evctx);
124         evctx.version = DRM_EVENT_CONTEXT_VERSION;
125         evctx.page_flip_handler = page_flip_handler;
126         drmHandleEvent(fd, &evctx);
127 }
128
129 static int
130 init_egl(struct drm_compositor *ec, struct udev_device *device)
131 {
132         EGLint major, minor;
133         const char *extensions, *filename;
134         int fd;
135         static const EGLint context_attribs[] = {
136                 EGL_CONTEXT_CLIENT_VERSION, 2,
137                 EGL_NONE
138         };
139
140         filename = udev_device_get_devnode(device);
141         fd = open(filename, O_RDWR, O_CLOEXEC);
142         if (fd < 0) {
143                 /* Probably permissions error */
144                 fprintf(stderr, "couldn't open %s, skipping\n",
145                         udev_device_get_devnode(device));
146                 return -1;
147         }
148
149         ec->drm.fd = fd;
150         ec->base.display = eglGetDRMDisplayMESA(ec->drm.fd);
151         if (ec->base.display == NULL) {
152                 fprintf(stderr, "failed to create display\n");
153                 return -1;
154         }
155
156         if (!eglInitialize(ec->base.display, &major, &minor)) {
157                 fprintf(stderr, "failed to initialize display\n");
158                 return -1;
159         }
160
161         extensions = eglQueryString(ec->base.display, EGL_EXTENSIONS);
162         if (!strstr(extensions, "EGL_KHR_surfaceless_opengl")) {
163                 fprintf(stderr, "EGL_KHR_surfaceless_opengl not available\n");
164                 return -1;
165         }
166
167         if (!eglBindAPI(EGL_OPENGL_ES_API)) {
168                 fprintf(stderr, "failed to bind api EGL_OPENGL_ES_API\n");
169                 return -1;
170         }
171
172         ec->base.context = eglCreateContext(ec->base.display, NULL,
173                                             EGL_NO_CONTEXT, context_attribs);
174         if (ec->base.context == NULL) {
175                 fprintf(stderr, "failed to create context\n");
176                 return -1;
177         }
178
179         if (!eglMakeCurrent(ec->base.display, EGL_NO_SURFACE,
180                             EGL_NO_SURFACE, ec->base.context)) {
181                 fprintf(stderr, "failed to make context current\n");
182                 return -1;
183         }
184
185         return 0;
186 }
187
188 static drmModeModeInfo builtin_1024x768 = {
189         63500,                  /* clock */
190         1024, 1072, 1176, 1328, 0,
191         768, 771, 775, 798, 0,
192         59920,
193         DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC,
194         0,
195         "1024x768"
196 };
197
198 static int
199 create_output_for_connector(struct drm_compositor *ec,
200                             drmModeRes *resources,
201                             drmModeConnector *connector,
202                             int x, int y)
203 {
204         struct drm_output *output;
205         drmModeEncoder *encoder;
206         drmModeModeInfo *mode;
207         int i, ret;
208         EGLint handle, stride, attribs[] = {
209                 EGL_WIDTH,              0,
210                 EGL_HEIGHT,             0,
211                 EGL_DRM_BUFFER_FORMAT_MESA,     EGL_DRM_BUFFER_FORMAT_ARGB32_MESA,
212                 EGL_DRM_BUFFER_USE_MESA,        EGL_DRM_BUFFER_USE_SCANOUT_MESA,
213                 EGL_NONE
214         };
215
216         output = malloc(sizeof *output);
217         if (output == NULL)
218                 return -1;
219
220         if (connector->count_modes > 0) 
221                 mode = &connector->modes[0];
222         else
223                 mode = &builtin_1024x768;
224
225         encoder = drmModeGetEncoder(ec->drm.fd, connector->encoders[0]);
226         if (encoder == NULL) {
227                 fprintf(stderr, "No encoder for connector.\n");
228                 return -1;
229         }
230
231         for (i = 0; i < resources->count_crtcs; i++) {
232                 if (encoder->possible_crtcs & (1 << i) &&
233                     !(ec->crtc_allocator & (1 << resources->crtcs[i])))
234                         break;
235         }
236         if (i == resources->count_crtcs) {
237                 fprintf(stderr, "No usable crtc for encoder.\n");
238                 return -1;
239         }
240
241         memset(output, 0, sizeof *output);
242         wlsc_output_init(&output->base, &ec->base, x, y,
243                          mode->hdisplay, mode->vdisplay, 0);
244
245         output->crtc_id = resources->crtcs[i];
246         ec->crtc_allocator |= (1 << output->crtc_id);
247
248         output->connector_id = connector->connector_id;
249         ec->connector_allocator |= (1 << output->connector_id);
250         output->mode = *mode;
251
252         drmModeFreeEncoder(encoder);
253
254         glGenRenderbuffers(2, output->rbo);
255         for (i = 0; i < 2; i++) {
256                 glBindRenderbuffer(GL_RENDERBUFFER, output->rbo[i]);
257
258                 attribs[1] = output->base.width;
259                 attribs[3] = output->base.height;
260                 output->image[i] =
261                         eglCreateDRMImageMESA(ec->base.display, attribs);
262                 glEGLImageTargetRenderbufferStorageOES(GL_RENDERBUFFER,
263                                                        output->image[i]);
264                 eglExportDRMImageMESA(ec->base.display, output->image[i],
265                                       NULL, &handle, &stride);
266
267                 ret = drmModeAddFB(ec->drm.fd,
268                                    output->base.width, output->base.height,
269                                    32, 32, stride, handle, &output->fb_id[i]);
270                 if (ret) {
271                         fprintf(stderr, "failed to add fb %d: %m\n", i);
272                         return -1;
273                 }
274         }
275
276         output->current = 0;
277         glFramebufferRenderbuffer(GL_FRAMEBUFFER,
278                                   GL_COLOR_ATTACHMENT0,
279                                   GL_RENDERBUFFER,
280                                   output->rbo[output->current]);
281         ret = drmModeSetCrtc(ec->drm.fd, output->crtc_id,
282                              output->fb_id[output->current ^ 1], 0, 0,
283                              &output->connector_id, 1, &output->mode);
284         if (ret) {
285                 fprintf(stderr, "failed to set mode: %m\n");
286                 return -1;
287         }
288
289         output->base.prepare_render = drm_output_prepare_render;
290
291         wl_list_insert(ec->base.output_list.prev, &output->base.link);
292
293         return 0;
294 }
295
296 static int
297 create_outputs(struct drm_compositor *ec, int option_connector)
298 {
299         drmModeConnector *connector;
300         drmModeRes *resources;
301         int i;
302         int x = 0, y = 0;
303
304         resources = drmModeGetResources(ec->drm.fd);
305         if (!resources) {
306                 fprintf(stderr, "drmModeGetResources failed\n");
307                 return -1;
308         }
309
310         for (i = 0; i < resources->count_connectors; i++) {
311                 connector = drmModeGetConnector(ec->drm.fd, resources->connectors[i]);
312                 if (connector == NULL)
313                         continue;
314
315                 if (connector->connection == DRM_MODE_CONNECTED &&
316                     (option_connector == 0 ||
317                      connector->connector_id == option_connector))
318                         if (create_output_for_connector(ec, resources,
319                                                         connector, x, y) < 0)
320                                 return -1;
321
322                 x += container_of(ec->base.output_list.prev, struct wlsc_output,
323                                   link)->width;
324
325                 drmModeFreeConnector(connector);
326         }
327
328         if (wl_list_empty(&ec->base.output_list)) {
329                 fprintf(stderr, "No currently active connector found.\n");
330                 return -1;
331         }
332
333         drmModeFreeResources(resources);
334
335         return 0;
336 }
337
338 static int
339 destroy_output(struct drm_output *output)
340 {
341         struct drm_compositor *ec =
342                 (struct drm_compositor *) output->base.compositor;
343         int i;
344
345         glFramebufferRenderbuffer(GL_FRAMEBUFFER,
346                                   GL_COLOR_ATTACHMENT0,
347                                   GL_RENDERBUFFER,
348                                   0);
349
350         glBindRenderbuffer(GL_RENDERBUFFER, 0);
351         glDeleteRenderbuffers(2, output->rbo);
352
353         for (i = 0; i < 2; i++) {
354                 eglDestroyImageKHR(ec->base.display, output->image[i]);
355                 drmModeRmFB(ec->drm.fd, output->fb_id[i]);
356         }
357         
358         ec->crtc_allocator &= ~(1 << output->crtc_id);
359         ec->connector_allocator &= ~(1 << output->connector_id);
360
361         wlsc_output_destroy(&output->base);
362         wl_list_remove(&output->base.link);
363
364         free(output);
365
366         return 0;
367 }
368
369 static void
370 update_outputs(struct drm_compositor *ec)
371 {
372         drmModeConnector *connector;
373         drmModeRes *resources;
374         struct drm_output *output, *next;
375         int x = 0, y = 0;
376         int x_offset = 0, y_offset = 0;
377         uint32_t connected = 0, disconnects = 0;
378         int i;
379
380         resources = drmModeGetResources(ec->drm.fd);
381         if (!resources) {
382                 fprintf(stderr, "drmModeGetResources failed\n");
383                 return;
384         }
385
386         /* collect new connects */
387         for (i = 0; i < resources->count_connectors; i++) {
388                 connector =
389                         drmModeGetConnector(ec->drm.fd,
390                                             resources->connectors[i]);
391                 if (connector == NULL ||
392                     connector->connection != DRM_MODE_CONNECTED)
393                         continue;
394
395                 connected |= (1 << connector->connector_id);
396                 
397                 if (!(ec->connector_allocator & (1 << connector->connector_id))) {
398                         struct wlsc_output *last_output =
399                                 container_of(ec->base.output_list.prev,
400                                              struct wlsc_output, link);
401
402                         /* XXX: not yet needed, we die with 0 outputs */
403                         if (!wl_list_empty(&ec->base.output_list))
404                                 x = last_output->x + last_output->width;
405                         else
406                                 x = 0;
407                         y = 0;
408                         create_output_for_connector(ec, resources,
409                                                     connector, x, y);
410                         printf("connector %d connected\n",
411                                connector->connector_id);
412                                 
413                 }
414                 drmModeFreeConnector(connector);
415         }
416         drmModeFreeResources(resources);
417
418         disconnects = ec->connector_allocator & ~connected;
419         if (disconnects) {
420                 wl_list_for_each_safe(output, next, &ec->base.output_list,
421                                       base.link) {
422                         if (x_offset != 0 || y_offset != 0) {
423                                 wlsc_output_move(&output->base,
424                                                  output->base.x - x_offset,
425                                                  output->base.y - y_offset);
426                         }
427
428                         if (disconnects & (1 << output->connector_id)) {
429                                 disconnects &= ~(1 << output->connector_id);
430                                 printf("connector %d disconnected\n",
431                                        output->connector_id);
432                                 x_offset += output->base.width;
433                                 destroy_output(output);
434                         }
435                 }
436         }
437
438         /* FIXME: handle zero outputs, without terminating */   
439         if (ec->connector_allocator == 0)
440                 wl_display_terminate(ec->base.wl_display);
441 }
442
443 static int
444 udev_event_is_hotplug(struct udev_device *device)
445 {
446         struct udev_list_entry *list, *hotplug_entry;
447         
448         list = udev_device_get_properties_list_entry(device);
449
450         hotplug_entry = udev_list_entry_get_by_name(list, "HOTPLUG");
451         if (hotplug_entry == NULL)
452                 return 0;
453
454         return strcmp(udev_list_entry_get_value(hotplug_entry), "1") == 0;
455 }
456
457 static void
458 udev_drm_event(int fd, uint32_t mask, void *data)
459 {
460         struct drm_compositor *ec = data;
461         struct udev_device *event;
462
463         event = udev_monitor_receive_device(ec->udev_monitor);
464         
465         if (udev_event_is_hotplug(event))
466                 update_outputs(ec);
467
468         udev_device_unref(event);
469 }
470
471 static void
472 drm_destroy(struct wlsc_compositor *ec)
473 {
474         struct drm_compositor *d = (struct drm_compositor *) ec;
475
476         tty_destroy(d->tty);
477
478         free(d);
479 }
480
481 struct wlsc_compositor *
482 drm_compositor_create(struct wl_display *display, int connector)
483 {
484         struct drm_compositor *ec;
485         struct udev_enumerate *e;
486         struct udev_list_entry *entry;
487         struct udev_device *device;
488         const char *path;
489         struct wl_event_loop *loop;
490
491         ec = malloc(sizeof *ec);
492         if (ec == NULL)
493                 return NULL;
494
495         memset(ec, 0, sizeof *ec);
496         ec->udev = udev_new();
497         if (ec->udev == NULL) {
498                 fprintf(stderr, "failed to initialize udev context\n");
499                 return NULL;
500         }
501
502         e = udev_enumerate_new(ec->udev);
503         udev_enumerate_add_match_subsystem(e, "drm");
504         udev_enumerate_add_match_property(e, "WAYLAND_SEAT", "1");
505         udev_enumerate_scan_devices(e);
506         device = NULL;
507         udev_list_entry_foreach(entry, udev_enumerate_get_list_entry(e)) {
508                 path = udev_list_entry_get_name(entry);
509                 device = udev_device_new_from_syspath(ec->udev, path);
510                 break;
511         }
512         udev_enumerate_unref(e);
513
514         if (device == NULL) {
515                 fprintf(stderr, "no drm device found\n");
516                 return NULL;
517         }
518
519         ec->base.wl_display = display;
520         if (init_egl(ec, device) < 0) {
521                 fprintf(stderr, "failed to initialize egl\n");
522                 return NULL;
523         }
524
525         ec->base.destroy = drm_destroy;
526         ec->base.present = drm_compositor_present;
527         ec->base.create_buffer = wlsc_shm_buffer_create;
528         ec->base.focus = 1;
529
530         glGenFramebuffers(1, &ec->base.fbo);
531         glBindFramebuffer(GL_FRAMEBUFFER, ec->base.fbo);
532
533         /* Can't init base class until we have a current egl context */
534         if (wlsc_compositor_init(&ec->base, display) < 0)
535                 return NULL;
536
537         if (create_outputs(ec, connector) < 0) {
538                 fprintf(stderr, "failed to create output for %s\n", path);
539                 return NULL;
540         }
541
542         evdev_input_add_devices(&ec->base, ec->udev);
543
544         loop = wl_display_get_event_loop(ec->base.wl_display);
545         ec->drm_source =
546                 wl_event_loop_add_fd(loop, ec->drm.fd,
547                                      WL_EVENT_READABLE, on_drm_input, ec);
548         ec->tty = tty_create(&ec->base);
549
550         ec->udev_monitor = udev_monitor_new_from_netlink(ec->udev, "udev");
551         if (ec->udev_monitor == NULL) {
552                 fprintf(stderr, "failed to intialize udev monitor\n");
553                 return NULL;
554         }
555         udev_monitor_filter_add_match_subsystem_devtype(ec->udev_monitor,
556                                                         "drm", NULL);
557         ec->udev_drm_source =
558                 wl_event_loop_add_fd(loop, udev_monitor_get_fd(ec->udev_monitor),
559                                      WL_EVENT_READABLE, udev_drm_event, ec);
560
561         if (udev_monitor_enable_receiving(ec->udev_monitor) < 0) {
562                 fprintf(stderr, "failed to enable udev-monitor receiving\n");
563                 return NULL;
564         }
565
566         return &ec->base;
567 }