compositor-drm: Make composite bypass work on secondary outputs
[profile/ivi/weston-ivi-shell.git] / src / compositor-drm.c
1 /*
2  * Copyright © 2008-2011 Kristian Høgsberg
3  * Copyright © 2011 Intel Corporation
4  *
5  * Permission to use, copy, modify, distribute, and sell this software and
6  * its documentation for any purpose is hereby granted without fee, provided
7  * that the above copyright notice appear in all copies and that both that
8  * copyright notice and this permission notice appear in supporting
9  * documentation, and that the name of the copyright holders not be used in
10  * advertising or publicity pertaining to distribution of the software
11  * without specific, written prior permission.  The copyright holders make
12  * no representations about the suitability of this software for any
13  * purpose.  It is provided "as is" without express or implied warranty.
14  *
15  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
16  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
17  * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
18  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
19  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
20  * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
21  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22  */
23
24 #include "config.h"
25
26 #include <errno.h>
27 #include <stdlib.h>
28 #include <ctype.h>
29 #include <string.h>
30 #include <fcntl.h>
31 #include <unistd.h>
32 #include <linux/input.h>
33 #include <linux/vt.h>
34 #include <assert.h>
35 #include <sys/mman.h>
36 #include <dlfcn.h>
37 #include <time.h>
38
39 #include <xf86drm.h>
40 #include <xf86drmMode.h>
41 #include <drm_fourcc.h>
42
43 #include <gbm.h>
44 #include <libbacklight.h>
45 #include <libudev.h>
46
47 #include "compositor.h"
48 #include "gl-renderer.h"
49 #include "pixman-renderer.h"
50 #include "udev-seat.h"
51 #include "launcher-util.h"
52 #include "vaapi-recorder.h"
53
54 #ifndef DRM_CAP_TIMESTAMP_MONOTONIC
55 #define DRM_CAP_TIMESTAMP_MONOTONIC 0x6
56 #endif
57
58 static int option_current_mode = 0;
59
60 enum output_config {
61         OUTPUT_CONFIG_INVALID = 0,
62         OUTPUT_CONFIG_OFF,
63         OUTPUT_CONFIG_PREFERRED,
64         OUTPUT_CONFIG_CURRENT,
65         OUTPUT_CONFIG_MODE,
66         OUTPUT_CONFIG_MODELINE
67 };
68
69 struct drm_compositor {
70         struct weston_compositor base;
71
72         struct udev *udev;
73         struct wl_event_source *drm_source;
74
75         struct udev_monitor *udev_monitor;
76         struct wl_event_source *udev_drm_source;
77
78         struct {
79                 int id;
80                 int fd;
81                 char *filename;
82         } drm;
83         struct gbm_device *gbm;
84         uint32_t *crtcs;
85         int num_crtcs;
86         uint32_t crtc_allocator;
87         uint32_t connector_allocator;
88         struct wl_listener session_listener;
89         uint32_t format;
90
91         /* we need these parameters in order to not fail drmModeAddFB2()
92          * due to out of bounds dimensions, and then mistakenly set
93          * sprites_are_broken:
94          */
95         uint32_t min_width, max_width;
96         uint32_t min_height, max_height;
97         int no_addfb2;
98
99         struct wl_list sprite_list;
100         int sprites_are_broken;
101         int sprites_hidden;
102
103         int cursors_are_broken;
104
105         int use_pixman;
106
107         uint32_t prev_state;
108
109         clockid_t clock;
110         struct udev_input input;
111 };
112
113 struct drm_mode {
114         struct weston_mode base;
115         drmModeModeInfo mode_info;
116 };
117
118 struct drm_output;
119
120 struct drm_fb {
121         struct drm_output *output;
122         uint32_t fb_id, stride, handle, size;
123         int fd;
124         int is_client_buffer;
125         struct weston_buffer_reference buffer_ref;
126
127         /* Used by gbm fbs */
128         struct gbm_bo *bo;
129
130         /* Used by dumb fbs */
131         void *map;
132 };
133
134 struct drm_edid {
135         char eisa_id[13];
136         char monitor_name[13];
137         char pnp_id[5];
138         char serial_number[13];
139 };
140
141 struct drm_output {
142         struct weston_output   base;
143
144         uint32_t crtc_id;
145         int pipe;
146         uint32_t connector_id;
147         drmModeCrtcPtr original_crtc;
148         struct drm_edid edid;
149         drmModePropertyPtr dpms_prop;
150
151         int vblank_pending;
152         int page_flip_pending;
153         int destroy_pending;
154
155         struct gbm_surface *surface;
156         struct gbm_bo *cursor_bo[2];
157         struct weston_plane cursor_plane;
158         struct weston_plane fb_plane;
159         struct weston_view *cursor_view;
160         int current_cursor;
161         struct drm_fb *current, *next;
162         struct backlight *backlight;
163
164         struct drm_fb *dumb[2];
165         pixman_image_t *image[2];
166         int current_image;
167         pixman_region32_t previous_damage;
168
169         struct vaapi_recorder *recorder;
170         struct wl_listener recorder_frame_listener;
171 };
172
173 /*
174  * An output has a primary display plane plus zero or more sprites for
175  * blending display contents.
176  */
177 struct drm_sprite {
178         struct wl_list link;
179
180         struct weston_plane plane;
181
182         struct drm_fb *current, *next;
183         struct drm_output *output;
184         struct drm_compositor *compositor;
185
186         uint32_t possible_crtcs;
187         uint32_t plane_id;
188         uint32_t count_formats;
189
190         int32_t src_x, src_y;
191         uint32_t src_w, src_h;
192         uint32_t dest_x, dest_y;
193         uint32_t dest_w, dest_h;
194
195         uint32_t formats[];
196 };
197
198 struct drm_parameters {
199         int connector;
200         int tty;
201         int use_pixman;
202         const char *seat_id;
203 };
204
205 static struct gl_renderer_interface *gl_renderer;
206
207 static const char default_seat[] = "seat0";
208
209 static void
210 drm_output_set_cursor(struct drm_output *output);
211
212 static int
213 drm_sprite_crtc_supported(struct weston_output *output_base, uint32_t supported)
214 {
215         struct weston_compositor *ec = output_base->compositor;
216         struct drm_compositor *c =(struct drm_compositor *) ec;
217         struct drm_output *output = (struct drm_output *) output_base;
218         int crtc;
219
220         for (crtc = 0; crtc < c->num_crtcs; crtc++) {
221                 if (c->crtcs[crtc] != output->crtc_id)
222                         continue;
223
224                 if (supported & (1 << crtc))
225                         return -1;
226         }
227
228         return 0;
229 }
230
231 static void
232 drm_fb_destroy_callback(struct gbm_bo *bo, void *data)
233 {
234         struct drm_fb *fb = data;
235         struct gbm_device *gbm = gbm_bo_get_device(bo);
236
237         if (fb->fb_id)
238                 drmModeRmFB(gbm_device_get_fd(gbm), fb->fb_id);
239
240         weston_buffer_reference(&fb->buffer_ref, NULL);
241
242         free(data);
243 }
244
245 static struct drm_fb *
246 drm_fb_create_dumb(struct drm_compositor *ec, unsigned width, unsigned height)
247 {
248         struct drm_fb *fb;
249         int ret;
250
251         struct drm_mode_create_dumb create_arg;
252         struct drm_mode_destroy_dumb destroy_arg;
253         struct drm_mode_map_dumb map_arg;
254
255         fb = zalloc(sizeof *fb);
256         if (!fb)
257                 return NULL;
258
259         memset(&create_arg, 0, sizeof create_arg);
260         create_arg.bpp = 32;
261         create_arg.width = width;
262         create_arg.height = height;
263
264         ret = drmIoctl(ec->drm.fd, DRM_IOCTL_MODE_CREATE_DUMB, &create_arg);
265         if (ret)
266                 goto err_fb;
267
268         fb->handle = create_arg.handle;
269         fb->stride = create_arg.pitch;
270         fb->size = create_arg.size;
271         fb->fd = ec->drm.fd;
272
273         ret = drmModeAddFB(ec->drm.fd, width, height, 24, 32,
274                            fb->stride, fb->handle, &fb->fb_id);
275         if (ret)
276                 goto err_bo;
277
278         memset(&map_arg, 0, sizeof map_arg);
279         map_arg.handle = fb->handle;
280         ret = drmIoctl(fb->fd, DRM_IOCTL_MODE_MAP_DUMB, &map_arg);
281         if (ret)
282                 goto err_add_fb;
283
284         fb->map = mmap(0, fb->size, PROT_WRITE,
285                        MAP_SHARED, ec->drm.fd, map_arg.offset);
286         if (fb->map == MAP_FAILED)
287                 goto err_add_fb;
288
289         return fb;
290
291 err_add_fb:
292         drmModeRmFB(ec->drm.fd, fb->fb_id);
293 err_bo:
294         memset(&destroy_arg, 0, sizeof(destroy_arg));
295         destroy_arg.handle = create_arg.handle;
296         drmIoctl(ec->drm.fd, DRM_IOCTL_MODE_DESTROY_DUMB, &destroy_arg);
297 err_fb:
298         free(fb);
299         return NULL;
300 }
301
302 static void
303 drm_fb_destroy_dumb(struct drm_fb *fb)
304 {
305         struct drm_mode_destroy_dumb destroy_arg;
306
307         if (!fb->map)
308                 return;
309
310         if (fb->fb_id)
311                 drmModeRmFB(fb->fd, fb->fb_id);
312
313         weston_buffer_reference(&fb->buffer_ref, NULL);
314
315         munmap(fb->map, fb->size);
316
317         memset(&destroy_arg, 0, sizeof(destroy_arg));
318         destroy_arg.handle = fb->handle;
319         drmIoctl(fb->fd, DRM_IOCTL_MODE_DESTROY_DUMB, &destroy_arg);
320
321         free(fb);
322 }
323
324 static struct drm_fb *
325 drm_fb_get_from_bo(struct gbm_bo *bo,
326                    struct drm_compositor *compositor, uint32_t format)
327 {
328         struct drm_fb *fb = gbm_bo_get_user_data(bo);
329         uint32_t width, height;
330         uint32_t handles[4], pitches[4], offsets[4];
331         int ret;
332
333         if (fb)
334                 return fb;
335
336         fb = calloc(1, sizeof *fb);
337         if (!fb)
338                 return NULL;
339
340         fb->bo = bo;
341
342         width = gbm_bo_get_width(bo);
343         height = gbm_bo_get_height(bo);
344         fb->stride = gbm_bo_get_stride(bo);
345         fb->handle = gbm_bo_get_handle(bo).u32;
346         fb->size = fb->stride * height;
347         fb->fd = compositor->drm.fd;
348
349         if (compositor->min_width > width || width > compositor->max_width ||
350             compositor->min_height > height ||
351             height > compositor->max_height) {
352                 weston_log("bo geometry out of bounds\n");
353                 goto err_free;
354         }
355
356         ret = -1;
357
358         if (format && !compositor->no_addfb2) {
359                 handles[0] = fb->handle;
360                 pitches[0] = fb->stride;
361                 offsets[0] = 0;
362
363                 ret = drmModeAddFB2(compositor->drm.fd, width, height,
364                                     format, handles, pitches, offsets,
365                                     &fb->fb_id, 0);
366                 if (ret) {
367                         weston_log("addfb2 failed: %m\n");
368                         compositor->no_addfb2 = 1;
369                         compositor->sprites_are_broken = 1;
370                 }
371         }
372
373         if (ret)
374                 ret = drmModeAddFB(compositor->drm.fd, width, height, 24, 32,
375                                    fb->stride, fb->handle, &fb->fb_id);
376
377         if (ret) {
378                 weston_log("failed to create kms fb: %m\n");
379                 goto err_free;
380         }
381
382         gbm_bo_set_user_data(bo, fb, drm_fb_destroy_callback);
383
384         return fb;
385
386 err_free:
387         free(fb);
388         return NULL;
389 }
390
391 static void
392 drm_fb_set_buffer(struct drm_fb *fb, struct weston_buffer *buffer)
393 {
394         assert(fb->buffer_ref.buffer == NULL);
395
396         fb->is_client_buffer = 1;
397
398         weston_buffer_reference(&fb->buffer_ref, buffer);
399 }
400
401 static void
402 drm_output_release_fb(struct drm_output *output, struct drm_fb *fb)
403 {
404         if (!fb)
405                 return;
406
407         if (fb->map &&
408             (fb != output->dumb[0] && fb != output->dumb[1])) {
409                 drm_fb_destroy_dumb(fb);
410         } else if (fb->bo) {
411                 if (fb->is_client_buffer)
412                         gbm_bo_destroy(fb->bo);
413                 else
414                         gbm_surface_release_buffer(output->surface,
415                                                    fb->bo);
416         }
417 }
418
419 static uint32_t
420 drm_output_check_scanout_format(struct drm_output *output,
421                                 struct weston_surface *es, struct gbm_bo *bo)
422 {
423         struct drm_compositor *c =
424                 (struct drm_compositor *) output->base.compositor;
425         uint32_t format;
426         pixman_region32_t r;
427
428         format = gbm_bo_get_format(bo);
429
430         if (format == GBM_FORMAT_ARGB8888) {
431                 /* We can scanout an ARGB buffer if the surface's
432                  * opaque region covers the whole output, but we have
433                  * to use XRGB as the KMS format code. */
434                 pixman_region32_init_rect(&r, 0, 0,
435                                           output->base.width,
436                                           output->base.height);
437                 pixman_region32_subtract(&r, &r, &es->opaque);
438
439                 if (!pixman_region32_not_empty(&r))
440                         format = GBM_FORMAT_XRGB8888;
441
442                 pixman_region32_fini(&r);
443         }
444
445         if (c->format == format)
446                 return format;
447
448         return 0;
449 }
450
451 static struct weston_plane *
452 drm_output_prepare_scanout_view(struct weston_output *_output,
453                                 struct weston_view *ev)
454 {
455         struct drm_output *output = (struct drm_output *) _output;
456         struct drm_compositor *c =
457                 (struct drm_compositor *) output->base.compositor;
458         struct weston_buffer *buffer = ev->surface->buffer_ref.buffer;
459         struct gbm_bo *bo;
460         uint32_t format;
461
462         if (ev->geometry.x != output->base.x ||
463             ev->geometry.y != output->base.y ||
464             buffer == NULL || c->gbm == NULL ||
465             buffer->width != output->base.current_mode->width ||
466             buffer->height != output->base.current_mode->height ||
467             output->base.transform != ev->surface->buffer_viewport.transform ||
468             ev->transform.enabled)
469                 return NULL;
470
471         bo = gbm_bo_import(c->gbm, GBM_BO_IMPORT_WL_BUFFER,
472                            buffer->resource, GBM_BO_USE_SCANOUT);
473
474         /* Unable to use the buffer for scanout */
475         if (!bo)
476                 return NULL;
477
478         format = drm_output_check_scanout_format(output, ev->surface, bo);
479         if (format == 0) {
480                 gbm_bo_destroy(bo);
481                 return NULL;
482         }
483
484         output->next = drm_fb_get_from_bo(bo, c, format);
485         if (!output->next) {
486                 gbm_bo_destroy(bo);
487                 return NULL;
488         }
489
490         drm_fb_set_buffer(output->next, buffer);
491
492         return &output->fb_plane;
493 }
494
495 static void
496 drm_output_render_gl(struct drm_output *output, pixman_region32_t *damage)
497 {
498         struct drm_compositor *c =
499                 (struct drm_compositor *) output->base.compositor;
500         struct gbm_bo *bo;
501
502         c->base.renderer->repaint_output(&output->base, damage);
503
504         bo = gbm_surface_lock_front_buffer(output->surface);
505         if (!bo) {
506                 weston_log("failed to lock front buffer: %m\n");
507                 return;
508         }
509
510         output->next = drm_fb_get_from_bo(bo, c, c->format);
511         if (!output->next) {
512                 weston_log("failed to get drm_fb for bo\n");
513                 gbm_surface_release_buffer(output->surface, bo);
514                 return;
515         }
516 }
517
518 static void
519 drm_output_render_pixman(struct drm_output *output, pixman_region32_t *damage)
520 {
521         struct weston_compositor *ec = output->base.compositor;
522         pixman_region32_t total_damage, previous_damage;
523
524         pixman_region32_init(&total_damage);
525         pixman_region32_init(&previous_damage);
526
527         pixman_region32_copy(&previous_damage, damage);
528
529         pixman_region32_union(&total_damage, damage, &output->previous_damage);
530         pixman_region32_copy(&output->previous_damage, &previous_damage);
531
532         output->current_image ^= 1;
533
534         output->next = output->dumb[output->current_image];
535         pixman_renderer_output_set_buffer(&output->base,
536                                           output->image[output->current_image]);
537
538         ec->renderer->repaint_output(&output->base, &total_damage);
539
540         pixman_region32_fini(&total_damage);
541         pixman_region32_fini(&previous_damage);
542 }
543
544 static void
545 drm_output_render(struct drm_output *output, pixman_region32_t *damage)
546 {
547         struct drm_compositor *c =
548                 (struct drm_compositor *) output->base.compositor;
549
550         if (c->use_pixman)
551                 drm_output_render_pixman(output, damage);
552         else
553                 drm_output_render_gl(output, damage);
554
555         pixman_region32_subtract(&c->base.primary_plane.damage,
556                                  &c->base.primary_plane.damage, damage);
557 }
558
559 static void
560 drm_output_set_gamma(struct weston_output *output_base,
561                      uint16_t size, uint16_t *r, uint16_t *g, uint16_t *b)
562 {
563         int rc;
564         struct drm_output *output = (struct drm_output *) output_base;
565         struct drm_compositor *compositor = (struct drm_compositor *) output->base.compositor;
566
567         /* check */
568         if (output_base->gamma_size != size)
569                 return;
570         if (!output->original_crtc)
571                 return;
572
573         rc = drmModeCrtcSetGamma(compositor->drm.fd,
574                                  output->crtc_id,
575                                  size, r, g, b);
576         if (rc)
577                 weston_log("set gamma failed: %m\n");
578 }
579
580 static int
581 drm_output_repaint(struct weston_output *output_base,
582                    pixman_region32_t *damage)
583 {
584         struct drm_output *output = (struct drm_output *) output_base;
585         struct drm_compositor *compositor =
586                 (struct drm_compositor *) output->base.compositor;
587         struct drm_sprite *s;
588         struct drm_mode *mode;
589         int ret = 0;
590
591         if (output->destroy_pending)
592                 return -1;
593
594         if (!output->next)
595                 drm_output_render(output, damage);
596         if (!output->next)
597                 return -1;
598
599         mode = container_of(output->base.current_mode, struct drm_mode, base);
600         if (!output->current ||
601             output->current->stride != output->next->stride) {
602                 ret = drmModeSetCrtc(compositor->drm.fd, output->crtc_id,
603                                      output->next->fb_id, 0, 0,
604                                      &output->connector_id, 1,
605                                      &mode->mode_info);
606                 if (ret) {
607                         weston_log("set mode failed: %m\n");
608                         goto err_pageflip;
609                 }
610                 output_base->set_dpms(output_base, WESTON_DPMS_ON);
611         }
612
613         if (drmModePageFlip(compositor->drm.fd, output->crtc_id,
614                             output->next->fb_id,
615                             DRM_MODE_PAGE_FLIP_EVENT, output) < 0) {
616                 weston_log("queueing pageflip failed: %m\n");
617                 goto err_pageflip;
618         }
619
620         output->page_flip_pending = 1;
621
622         drm_output_set_cursor(output);
623
624         /*
625          * Now, update all the sprite surfaces
626          */
627         wl_list_for_each(s, &compositor->sprite_list, link) {
628                 uint32_t flags = 0, fb_id = 0;
629                 drmVBlank vbl = {
630                         .request.type = DRM_VBLANK_RELATIVE | DRM_VBLANK_EVENT,
631                         .request.sequence = 1,
632                 };
633
634                 if ((!s->current && !s->next) ||
635                     !drm_sprite_crtc_supported(output_base, s->possible_crtcs))
636                         continue;
637
638                 if (s->next && !compositor->sprites_hidden)
639                         fb_id = s->next->fb_id;
640
641                 ret = drmModeSetPlane(compositor->drm.fd, s->plane_id,
642                                       output->crtc_id, fb_id, flags,
643                                       s->dest_x, s->dest_y,
644                                       s->dest_w, s->dest_h,
645                                       s->src_x, s->src_y,
646                                       s->src_w, s->src_h);
647                 if (ret)
648                         weston_log("setplane failed: %d: %s\n",
649                                 ret, strerror(errno));
650
651                 if (output->pipe > 0)
652                         vbl.request.type |= DRM_VBLANK_SECONDARY;
653
654                 /*
655                  * Queue a vblank signal so we know when the surface
656                  * becomes active on the display or has been replaced.
657                  */
658                 vbl.request.signal = (unsigned long)s;
659                 ret = drmWaitVBlank(compositor->drm.fd, &vbl);
660                 if (ret) {
661                         weston_log("vblank event request failed: %d: %s\n",
662                                 ret, strerror(errno));
663                 }
664
665                 s->output = output;
666                 output->vblank_pending = 1;
667         }
668
669         return 0;
670
671 err_pageflip:
672         if (output->next) {
673                 drm_output_release_fb(output, output->next);
674                 output->next = NULL;
675         }
676
677         return -1;
678 }
679
680 static void
681 drm_output_start_repaint_loop(struct weston_output *output_base)
682 {
683         struct drm_output *output = (struct drm_output *) output_base;
684         struct drm_compositor *compositor = (struct drm_compositor *)
685                 output_base->compositor;
686         uint32_t fb_id;
687         uint32_t msec;
688         struct timespec ts;
689
690         if (output->destroy_pending)
691                 return;
692
693         if (!output->current) {
694                 /* We can't page flip if there's no mode set */
695                 goto finish_frame;
696         }
697
698         fb_id = output->current->fb_id;
699
700         if (drmModePageFlip(compositor->drm.fd, output->crtc_id, fb_id,
701                             DRM_MODE_PAGE_FLIP_EVENT, output) < 0) {
702                 weston_log("queueing pageflip failed: %m\n");
703                 goto finish_frame;
704         }
705
706         return;
707
708 finish_frame:
709         /* if we cannot page-flip, immediately finish frame */
710         clock_gettime(compositor->clock, &ts);
711         msec = ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
712         weston_output_finish_frame(output_base, msec);
713 }
714
715 static void
716 vblank_handler(int fd, unsigned int frame, unsigned int sec, unsigned int usec,
717                void *data)
718 {
719         struct drm_sprite *s = (struct drm_sprite *)data;
720         struct drm_output *output = s->output;
721         uint32_t msecs;
722
723         output->vblank_pending = 0;
724
725         drm_output_release_fb(output, s->current);
726         s->current = s->next;
727         s->next = NULL;
728
729         if (!output->page_flip_pending) {
730                 msecs = sec * 1000 + usec / 1000;
731                 weston_output_finish_frame(&output->base, msecs);
732         }
733 }
734
735 static void
736 drm_output_destroy(struct weston_output *output_base);
737
738 static void
739 page_flip_handler(int fd, unsigned int frame,
740                   unsigned int sec, unsigned int usec, void *data)
741 {
742         struct drm_output *output = (struct drm_output *) data;
743         uint32_t msecs;
744
745         /* We don't set page_flip_pending on start_repaint_loop, in that case
746          * we just want to page flip to the current buffer to get an accurate
747          * timestamp */
748         if (output->page_flip_pending) {
749                 drm_output_release_fb(output, output->current);
750                 output->current = output->next;
751                 output->next = NULL;
752         }
753
754         output->page_flip_pending = 0;
755
756         if (output->destroy_pending)
757                 drm_output_destroy(&output->base);
758         else if (!output->vblank_pending) {
759                 msecs = sec * 1000 + usec / 1000;
760                 weston_output_finish_frame(&output->base, msecs);
761
762                 /* We can't call this from frame_notify, because the output's
763                  * repaint needed flag is cleared just after that */
764                 if (output->recorder)
765                         weston_output_schedule_repaint(&output->base);
766         }
767 }
768
769 static uint32_t
770 drm_output_check_sprite_format(struct drm_sprite *s,
771                                struct weston_view *ev, struct gbm_bo *bo)
772 {
773         uint32_t i, format;
774
775         format = gbm_bo_get_format(bo);
776
777         if (format == GBM_FORMAT_ARGB8888) {
778                 pixman_region32_t r;
779
780                 pixman_region32_init_rect(&r, 0, 0,
781                                           ev->surface->width,
782                                           ev->surface->height);
783                 pixman_region32_subtract(&r, &r, &ev->surface->opaque);
784
785                 if (!pixman_region32_not_empty(&r))
786                         format = GBM_FORMAT_XRGB8888;
787
788                 pixman_region32_fini(&r);
789         }
790
791         for (i = 0; i < s->count_formats; i++)
792                 if (s->formats[i] == format)
793                         return format;
794
795         return 0;
796 }
797
798 static int
799 drm_view_transform_supported(struct weston_view *ev)
800 {
801         return !ev->transform.enabled ||
802                 (ev->transform.matrix.type < WESTON_MATRIX_TRANSFORM_ROTATE);
803 }
804
805 static struct weston_plane *
806 drm_output_prepare_overlay_view(struct weston_output *output_base,
807                                 struct weston_view *ev)
808 {
809         struct weston_compositor *ec = output_base->compositor;
810         struct drm_compositor *c =(struct drm_compositor *) ec;
811         struct drm_sprite *s;
812         int found = 0;
813         struct gbm_bo *bo;
814         pixman_region32_t dest_rect, src_rect;
815         pixman_box32_t *box, tbox;
816         uint32_t format;
817         wl_fixed_t sx1, sy1, sx2, sy2;
818
819         if (c->gbm == NULL)
820                 return NULL;
821
822         if (ev->surface->buffer_viewport.transform != output_base->transform)
823                 return NULL;
824
825         if (ev->surface->buffer_viewport.scale != output_base->current_scale)
826                 return NULL;
827
828         if (c->sprites_are_broken)
829                 return NULL;
830
831         if (ev->output_mask != (1u << output_base->id))
832                 return NULL;
833
834         if (ev->surface->buffer_ref.buffer == NULL)
835                 return NULL;
836
837         if (ev->alpha != 1.0f)
838                 return NULL;
839
840         if (wl_shm_buffer_get(ev->surface->buffer_ref.buffer->resource))
841                 return NULL;
842
843         if (!drm_view_transform_supported(ev))
844                 return NULL;
845
846         wl_list_for_each(s, &c->sprite_list, link) {
847                 if (!drm_sprite_crtc_supported(output_base, s->possible_crtcs))
848                         continue;
849
850                 if (!s->next) {
851                         found = 1;
852                         break;
853                 }
854         }
855
856         /* No sprites available */
857         if (!found)
858                 return NULL;
859
860         bo = gbm_bo_import(c->gbm, GBM_BO_IMPORT_WL_BUFFER,
861                            ev->surface->buffer_ref.buffer->resource,
862                            GBM_BO_USE_SCANOUT);
863         if (!bo)
864                 return NULL;
865
866         format = drm_output_check_sprite_format(s, ev, bo);
867         if (format == 0) {
868                 gbm_bo_destroy(bo);
869                 return NULL;
870         }
871
872         s->next = drm_fb_get_from_bo(bo, c, format);
873         if (!s->next) {
874                 gbm_bo_destroy(bo);
875                 return NULL;
876         }
877
878         drm_fb_set_buffer(s->next, ev->surface->buffer_ref.buffer);
879
880         box = pixman_region32_extents(&ev->transform.boundingbox);
881         s->plane.x = box->x1;
882         s->plane.y = box->y1;
883
884         /*
885          * Calculate the source & dest rects properly based on actual
886          * position (note the caller has called weston_surface_update_transform()
887          * for us already).
888          */
889         pixman_region32_init(&dest_rect);
890         pixman_region32_intersect(&dest_rect, &ev->transform.boundingbox,
891                                   &output_base->region);
892         pixman_region32_translate(&dest_rect, -output_base->x, -output_base->y);
893         box = pixman_region32_extents(&dest_rect);
894         tbox = weston_transformed_rect(output_base->width,
895                                        output_base->height,
896                                        output_base->transform,
897                                        output_base->current_scale,
898                                        *box);
899         s->dest_x = tbox.x1;
900         s->dest_y = tbox.y1;
901         s->dest_w = tbox.x2 - tbox.x1;
902         s->dest_h = tbox.y2 - tbox.y1;
903         pixman_region32_fini(&dest_rect);
904
905         pixman_region32_init(&src_rect);
906         pixman_region32_intersect(&src_rect, &ev->transform.boundingbox,
907                                   &output_base->region);
908         box = pixman_region32_extents(&src_rect);
909
910         weston_view_from_global_fixed(ev,
911                                       wl_fixed_from_int(box->x1),
912                                       wl_fixed_from_int(box->y1),
913                                       &sx1, &sy1);
914         weston_view_from_global_fixed(ev,
915                                       wl_fixed_from_int(box->x2),
916                                       wl_fixed_from_int(box->y2),
917                                       &sx2, &sy2);
918
919         if (sx1 < 0)
920                 sx1 = 0;
921         if (sy1 < 0)
922                 sy1 = 0;
923         if (sx2 > wl_fixed_from_int(ev->surface->width))
924                 sx2 = wl_fixed_from_int(ev->surface->width);
925         if (sy2 > wl_fixed_from_int(ev->surface->height))
926                 sy2 = wl_fixed_from_int(ev->surface->height);
927
928         tbox.x1 = sx1;
929         tbox.y1 = sy1;
930         tbox.x2 = sx2;
931         tbox.y2 = sy2;
932
933         tbox = weston_transformed_rect(wl_fixed_from_int(ev->surface->width),
934                                        wl_fixed_from_int(ev->surface->height),
935                                        ev->surface->buffer_viewport.transform,
936                                        ev->surface->buffer_viewport.scale,
937                                        tbox);
938
939         s->src_x = tbox.x1 << 8;
940         s->src_y = tbox.y1 << 8;
941         s->src_w = (tbox.x2 - tbox.x1) << 8;
942         s->src_h = (tbox.y2 - tbox.y1) << 8;
943         pixman_region32_fini(&src_rect);
944
945         return &s->plane;
946 }
947
948 static struct weston_plane *
949 drm_output_prepare_cursor_view(struct weston_output *output_base,
950                                struct weston_view *ev)
951 {
952         struct drm_compositor *c =
953                 (struct drm_compositor *) output_base->compositor;
954         struct drm_output *output = (struct drm_output *) output_base;
955
956         if (c->gbm == NULL)
957                 return NULL;
958         if (output->base.transform != WL_OUTPUT_TRANSFORM_NORMAL)
959                 return NULL;
960         if (output->cursor_view)
961                 return NULL;
962         if (ev->output_mask != (1u << output_base->id))
963                 return NULL;
964         if (c->cursors_are_broken)
965                 return NULL;
966         if (ev->surface->buffer_ref.buffer == NULL ||
967             !wl_shm_buffer_get(ev->surface->buffer_ref.buffer->resource) ||
968             ev->surface->width > 64 || ev->surface->height > 64)
969                 return NULL;
970
971         output->cursor_view = ev;
972
973         return &output->cursor_plane;
974 }
975
976 static void
977 drm_output_set_cursor(struct drm_output *output)
978 {
979         struct weston_view *ev = output->cursor_view;
980         struct weston_buffer *buffer;
981         struct drm_compositor *c =
982                 (struct drm_compositor *) output->base.compositor;
983         EGLint handle, stride;
984         struct gbm_bo *bo;
985         uint32_t buf[64 * 64];
986         unsigned char *s;
987         int i, x, y;
988
989         output->cursor_view = NULL;
990         if (ev == NULL) {
991                 drmModeSetCursor(c->drm.fd, output->crtc_id, 0, 0, 0);
992                 return;
993         }
994
995         buffer = ev->surface->buffer_ref.buffer;
996
997         if (buffer &&
998             pixman_region32_not_empty(&output->cursor_plane.damage)) {
999                 pixman_region32_fini(&output->cursor_plane.damage);
1000                 pixman_region32_init(&output->cursor_plane.damage);
1001                 output->current_cursor ^= 1;
1002                 bo = output->cursor_bo[output->current_cursor];
1003                 memset(buf, 0, sizeof buf);
1004                 stride = wl_shm_buffer_get_stride(buffer->shm_buffer);
1005                 s = wl_shm_buffer_get_data(buffer->shm_buffer);
1006                 wl_shm_buffer_begin_access(buffer->shm_buffer);
1007                 for (i = 0; i < ev->surface->height; i++)
1008                         memcpy(buf + i * 64, s + i * stride,
1009                                ev->surface->width * 4);
1010                 wl_shm_buffer_end_access(buffer->shm_buffer);
1011
1012                 if (gbm_bo_write(bo, buf, sizeof buf) < 0)
1013                         weston_log("failed update cursor: %m\n");
1014
1015                 handle = gbm_bo_get_handle(bo).s32;
1016                 if (drmModeSetCursor(c->drm.fd,
1017                                      output->crtc_id, handle, 64, 64)) {
1018                         weston_log("failed to set cursor: %m\n");
1019                         c->cursors_are_broken = 1;
1020                 }
1021         }
1022
1023         x = (ev->geometry.x - output->base.x) * output->base.current_scale;
1024         y = (ev->geometry.y - output->base.y) * output->base.current_scale;
1025         if (output->cursor_plane.x != x || output->cursor_plane.y != y) {
1026                 if (drmModeMoveCursor(c->drm.fd, output->crtc_id, x, y)) {
1027                         weston_log("failed to move cursor: %m\n");
1028                         c->cursors_are_broken = 1;
1029                 }
1030
1031                 output->cursor_plane.x = x;
1032                 output->cursor_plane.y = y;
1033         }
1034 }
1035
1036 static void
1037 drm_assign_planes(struct weston_output *output)
1038 {
1039         struct drm_compositor *c =
1040                 (struct drm_compositor *) output->compositor;
1041         struct weston_view *ev, *next;
1042         pixman_region32_t overlap, surface_overlap;
1043         struct weston_plane *primary, *next_plane;
1044
1045         /*
1046          * Find a surface for each sprite in the output using some heuristics:
1047          * 1) size
1048          * 2) frequency of update
1049          * 3) opacity (though some hw might support alpha blending)
1050          * 4) clipping (this can be fixed with color keys)
1051          *
1052          * The idea is to save on blitting since this should save power.
1053          * If we can get a large video surface on the sprite for example,
1054          * the main display surface may not need to update at all, and
1055          * the client buffer can be used directly for the sprite surface
1056          * as we do for flipping full screen surfaces.
1057          */
1058         pixman_region32_init(&overlap);
1059         primary = &c->base.primary_plane;
1060
1061         wl_list_for_each_safe(ev, next, &c->base.view_list, link) {
1062                 struct weston_surface *es = ev->surface;
1063
1064                 /* Test whether this buffer can ever go into a plane:
1065                  * non-shm, or small enough to be a cursor.
1066                  *
1067                  * Also, keep a reference when using the pixman renderer.
1068                  * That makes it possible to do a seamless switch to the GL
1069                  * renderer and since the pixman renderer keeps a reference
1070                  * to the buffer anyway, there is no side effects.
1071                  */
1072                 if (c->use_pixman ||
1073                     (es->buffer_ref.buffer &&
1074                     (!wl_shm_buffer_get(es->buffer_ref.buffer->resource) ||
1075                      (ev->surface->width <= 64 && ev->surface->height <= 64))))
1076                         es->keep_buffer = 1;
1077                 else
1078                         es->keep_buffer = 0;
1079
1080                 pixman_region32_init(&surface_overlap);
1081                 pixman_region32_intersect(&surface_overlap, &overlap,
1082                                           &ev->transform.boundingbox);
1083
1084                 next_plane = NULL;
1085                 if (pixman_region32_not_empty(&surface_overlap))
1086                         next_plane = primary;
1087                 if (next_plane == NULL)
1088                         next_plane = drm_output_prepare_cursor_view(output, ev);
1089                 if (next_plane == NULL)
1090                         next_plane = drm_output_prepare_scanout_view(output, ev);
1091                 if (next_plane == NULL)
1092                         next_plane = drm_output_prepare_overlay_view(output, ev);
1093                 if (next_plane == NULL)
1094                         next_plane = primary;
1095                 weston_view_move_to_plane(ev, next_plane);
1096                 if (next_plane == primary)
1097                         pixman_region32_union(&overlap, &overlap,
1098                                               &ev->transform.boundingbox);
1099
1100                 pixman_region32_fini(&surface_overlap);
1101         }
1102         pixman_region32_fini(&overlap);
1103 }
1104
1105 static void
1106 drm_output_fini_pixman(struct drm_output *output);
1107
1108 static void
1109 drm_output_destroy(struct weston_output *output_base)
1110 {
1111         struct drm_output *output = (struct drm_output *) output_base;
1112         struct drm_compositor *c =
1113                 (struct drm_compositor *) output->base.compositor;
1114         drmModeCrtcPtr origcrtc = output->original_crtc;
1115
1116         if (output->page_flip_pending) {
1117                 output->destroy_pending = 1;
1118                 weston_log("destroy output while page flip pending\n");
1119                 return;
1120         }
1121
1122         if (output->backlight)
1123                 backlight_destroy(output->backlight);
1124
1125         drmModeFreeProperty(output->dpms_prop);
1126
1127         /* Turn off hardware cursor */
1128         drmModeSetCursor(c->drm.fd, output->crtc_id, 0, 0, 0);
1129
1130         /* Restore original CRTC state */
1131         drmModeSetCrtc(c->drm.fd, origcrtc->crtc_id, origcrtc->buffer_id,
1132                        origcrtc->x, origcrtc->y,
1133                        &output->connector_id, 1, &origcrtc->mode);
1134         drmModeFreeCrtc(origcrtc);
1135
1136         c->crtc_allocator &= ~(1 << output->crtc_id);
1137         c->connector_allocator &= ~(1 << output->connector_id);
1138
1139         if (c->use_pixman) {
1140                 drm_output_fini_pixman(output);
1141         } else {
1142                 gl_renderer->output_destroy(output_base);
1143                 gbm_surface_destroy(output->surface);
1144         }
1145
1146         weston_plane_release(&output->fb_plane);
1147         weston_plane_release(&output->cursor_plane);
1148
1149         weston_output_destroy(&output->base);
1150
1151         free(output);
1152 }
1153
1154 static struct drm_mode *
1155 choose_mode (struct drm_output *output, struct weston_mode *target_mode)
1156 {
1157         struct drm_mode *tmp_mode = NULL, *mode;
1158
1159         if (output->base.current_mode->width == target_mode->width &&
1160             output->base.current_mode->height == target_mode->height &&
1161             (output->base.current_mode->refresh == target_mode->refresh ||
1162              target_mode->refresh == 0))
1163                 return (struct drm_mode *)output->base.current_mode;
1164
1165         wl_list_for_each(mode, &output->base.mode_list, base.link) {
1166                 if (mode->mode_info.hdisplay == target_mode->width &&
1167                     mode->mode_info.vdisplay == target_mode->height) {
1168                         if (mode->mode_info.vrefresh == target_mode->refresh || 
1169                             target_mode->refresh == 0) {
1170                                 return mode;
1171                         } else if (!tmp_mode) 
1172                                 tmp_mode = mode;
1173                 }
1174         }
1175
1176         return tmp_mode;
1177 }
1178
1179 static int
1180 drm_output_init_egl(struct drm_output *output, struct drm_compositor *ec);
1181 static int
1182 drm_output_init_pixman(struct drm_output *output, struct drm_compositor *c);
1183
1184 static int
1185 drm_output_switch_mode(struct weston_output *output_base, struct weston_mode *mode)
1186 {
1187         struct drm_output *output;
1188         struct drm_mode *drm_mode;
1189         struct drm_compositor *ec;
1190
1191         if (output_base == NULL) {
1192                 weston_log("output is NULL.\n");
1193                 return -1;
1194         }
1195
1196         if (mode == NULL) {
1197                 weston_log("mode is NULL.\n");
1198                 return -1;
1199         }
1200
1201         ec = (struct drm_compositor *)output_base->compositor;
1202         output = (struct drm_output *)output_base;
1203         drm_mode  = choose_mode (output, mode);
1204
1205         if (!drm_mode) {
1206                 weston_log("%s, invalid resolution:%dx%d\n", __func__, mode->width, mode->height);
1207                 return -1;
1208         }
1209
1210         if (&drm_mode->base == output->base.current_mode)
1211                 return 0;
1212
1213         output->base.current_mode->flags = 0;
1214
1215         output->base.current_mode = &drm_mode->base;
1216         output->base.current_mode->flags =
1217                 WL_OUTPUT_MODE_CURRENT | WL_OUTPUT_MODE_PREFERRED;
1218
1219         /* reset rendering stuff. */
1220         drm_output_release_fb(output, output->current);
1221         drm_output_release_fb(output, output->next);
1222         output->current = output->next = NULL;
1223
1224         if (ec->use_pixman) {
1225                 drm_output_fini_pixman(output);
1226                 if (drm_output_init_pixman(output, ec) < 0) {
1227                         weston_log("failed to init output pixman state with "
1228                                    "new mode\n");
1229                         return -1;
1230                 }
1231         } else {
1232                 gl_renderer->output_destroy(&output->base);
1233                 gbm_surface_destroy(output->surface);
1234
1235                 if (drm_output_init_egl(output, ec) < 0) {
1236                         weston_log("failed to init output egl state with "
1237                                    "new mode");
1238                         return -1;
1239                 }
1240         }
1241
1242         return 0;
1243 }
1244
1245 static int
1246 on_drm_input(int fd, uint32_t mask, void *data)
1247 {
1248         drmEventContext evctx;
1249
1250         memset(&evctx, 0, sizeof evctx);
1251         evctx.version = DRM_EVENT_CONTEXT_VERSION;
1252         evctx.page_flip_handler = page_flip_handler;
1253         evctx.vblank_handler = vblank_handler;
1254         drmHandleEvent(fd, &evctx);
1255
1256         return 1;
1257 }
1258
1259 static int
1260 init_drm(struct drm_compositor *ec, struct udev_device *device)
1261 {
1262         const char *filename, *sysnum;
1263         uint64_t cap;
1264         int fd, ret;
1265
1266         sysnum = udev_device_get_sysnum(device);
1267         if (sysnum)
1268                 ec->drm.id = atoi(sysnum);
1269         if (!sysnum || ec->drm.id < 0) {
1270                 weston_log("cannot get device sysnum\n");
1271                 return -1;
1272         }
1273
1274         filename = udev_device_get_devnode(device);
1275         fd = weston_launcher_open(ec->base.launcher, filename, O_RDWR);
1276         if (fd < 0) {
1277                 /* Probably permissions error */
1278                 weston_log("couldn't open %s, skipping\n",
1279                         udev_device_get_devnode(device));
1280                 return -1;
1281         }
1282
1283         weston_log("using %s\n", filename);
1284
1285         ec->drm.fd = fd;
1286         ec->drm.filename = strdup(filename);
1287
1288         ret = drmGetCap(fd, DRM_CAP_TIMESTAMP_MONOTONIC, &cap);
1289         if (ret == 0 && cap == 1)
1290                 ec->clock = CLOCK_MONOTONIC;
1291         else
1292                 ec->clock = CLOCK_REALTIME;
1293
1294         return 0;
1295 }
1296
1297 static struct gbm_device *
1298 create_gbm_device(int fd)
1299 {
1300         struct gbm_device *gbm;
1301
1302         gl_renderer = weston_load_module("gl-renderer.so",
1303                                          "gl_renderer_interface");
1304         if (!gl_renderer)
1305                 return NULL;
1306
1307         /* GBM will load a dri driver, but even though they need symbols from
1308          * libglapi, in some version of Mesa they are not linked to it. Since
1309          * only the gl-renderer module links to it, the call above won't make
1310          * these symbols globally available, and loading the DRI driver fails.
1311          * Workaround this by dlopen()'ing libglapi with RTLD_GLOBAL. */
1312         dlopen("libglapi.so.0", RTLD_LAZY | RTLD_GLOBAL);
1313
1314         gbm = gbm_create_device(fd);
1315
1316         return gbm;
1317 }
1318
1319 static int
1320 drm_compositor_create_gl_renderer(struct drm_compositor *ec)
1321 {
1322         EGLint format;
1323
1324         format = ec->format;
1325         if (gl_renderer->create(&ec->base, ec->gbm,
1326                                gl_renderer->opaque_attribs, &format) < 0) {
1327                 return -1;
1328         }
1329
1330         return 0;
1331 }
1332
1333 static int
1334 init_egl(struct drm_compositor *ec)
1335 {
1336         ec->gbm = create_gbm_device(ec->drm.fd);
1337
1338         if (!ec->gbm)
1339                 return -1;
1340
1341         if (drm_compositor_create_gl_renderer(ec) < 0) {
1342                 gbm_device_destroy(ec->gbm);
1343                 return -1;
1344         }
1345
1346         return 0;
1347 }
1348
1349 static int
1350 init_pixman(struct drm_compositor *ec)
1351 {
1352         return pixman_renderer_init(&ec->base);
1353 }
1354
1355 static struct drm_mode *
1356 drm_output_add_mode(struct drm_output *output, drmModeModeInfo *info)
1357 {
1358         struct drm_mode *mode;
1359         uint64_t refresh;
1360
1361         mode = malloc(sizeof *mode);
1362         if (mode == NULL)
1363                 return NULL;
1364
1365         mode->base.flags = 0;
1366         mode->base.width = info->hdisplay;
1367         mode->base.height = info->vdisplay;
1368
1369         /* Calculate higher precision (mHz) refresh rate */
1370         refresh = (info->clock * 1000000LL / info->htotal +
1371                    info->vtotal / 2) / info->vtotal;
1372
1373         if (info->flags & DRM_MODE_FLAG_INTERLACE)
1374                 refresh *= 2;
1375         if (info->flags & DRM_MODE_FLAG_DBLSCAN)
1376                 refresh /= 2;
1377         if (info->vscan > 1)
1378             refresh /= info->vscan;
1379
1380         mode->base.refresh = refresh;
1381         mode->mode_info = *info;
1382
1383         if (info->type & DRM_MODE_TYPE_PREFERRED)
1384                 mode->base.flags |= WL_OUTPUT_MODE_PREFERRED;
1385
1386         wl_list_insert(output->base.mode_list.prev, &mode->base.link);
1387
1388         return mode;
1389 }
1390
1391 static int
1392 drm_subpixel_to_wayland(int drm_value)
1393 {
1394         switch (drm_value) {
1395         default:
1396         case DRM_MODE_SUBPIXEL_UNKNOWN:
1397                 return WL_OUTPUT_SUBPIXEL_UNKNOWN;
1398         case DRM_MODE_SUBPIXEL_NONE:
1399                 return WL_OUTPUT_SUBPIXEL_NONE;
1400         case DRM_MODE_SUBPIXEL_HORIZONTAL_RGB:
1401                 return WL_OUTPUT_SUBPIXEL_HORIZONTAL_RGB;
1402         case DRM_MODE_SUBPIXEL_HORIZONTAL_BGR:
1403                 return WL_OUTPUT_SUBPIXEL_HORIZONTAL_BGR;
1404         case DRM_MODE_SUBPIXEL_VERTICAL_RGB:
1405                 return WL_OUTPUT_SUBPIXEL_VERTICAL_RGB;
1406         case DRM_MODE_SUBPIXEL_VERTICAL_BGR:
1407                 return WL_OUTPUT_SUBPIXEL_VERTICAL_BGR;
1408         }
1409 }
1410
1411 /* returns a value between 0-255 range, where higher is brighter */
1412 static uint32_t
1413 drm_get_backlight(struct drm_output *output)
1414 {
1415         long brightness, max_brightness, norm;
1416
1417         brightness = backlight_get_brightness(output->backlight);
1418         max_brightness = backlight_get_max_brightness(output->backlight);
1419
1420         /* convert it on a scale of 0 to 255 */
1421         norm = (brightness * 255)/(max_brightness);
1422
1423         return (uint32_t) norm;
1424 }
1425
1426 /* values accepted are between 0-255 range */
1427 static void
1428 drm_set_backlight(struct weston_output *output_base, uint32_t value)
1429 {
1430         struct drm_output *output = (struct drm_output *) output_base;
1431         long max_brightness, new_brightness;
1432
1433         if (!output->backlight)
1434                 return;
1435
1436         if (value > 255)
1437                 return;
1438
1439         max_brightness = backlight_get_max_brightness(output->backlight);
1440
1441         /* get denormalized value */
1442         new_brightness = (value * max_brightness) / 255;
1443
1444         backlight_set_brightness(output->backlight, new_brightness);
1445 }
1446
1447 static drmModePropertyPtr
1448 drm_get_prop(int fd, drmModeConnectorPtr connector, const char *name)
1449 {
1450         drmModePropertyPtr props;
1451         int i;
1452
1453         for (i = 0; i < connector->count_props; i++) {
1454                 props = drmModeGetProperty(fd, connector->props[i]);
1455                 if (!props)
1456                         continue;
1457
1458                 if (!strcmp(props->name, name))
1459                         return props;
1460
1461                 drmModeFreeProperty(props);
1462         }
1463
1464         return NULL;
1465 }
1466
1467 static void
1468 drm_set_dpms(struct weston_output *output_base, enum dpms_enum level)
1469 {
1470         struct drm_output *output = (struct drm_output *) output_base;
1471         struct weston_compositor *ec = output_base->compositor;
1472         struct drm_compositor *c = (struct drm_compositor *) ec;
1473
1474         if (!output->dpms_prop)
1475                 return;
1476
1477         drmModeConnectorSetProperty(c->drm.fd, output->connector_id,
1478                                     output->dpms_prop->prop_id, level);
1479 }
1480
1481 static const char *connector_type_names[] = {
1482         "None",
1483         "VGA",
1484         "DVI",
1485         "DVI",
1486         "DVI",
1487         "Composite",
1488         "TV",
1489         "LVDS",
1490         "CTV",
1491         "DIN",
1492         "DP",
1493         "HDMI",
1494         "HDMI",
1495         "TV",
1496         "eDP",
1497 };
1498
1499 static int
1500 find_crtc_for_connector(struct drm_compositor *ec,
1501                         drmModeRes *resources, drmModeConnector *connector)
1502 {
1503         drmModeEncoder *encoder;
1504         uint32_t possible_crtcs;
1505         int i, j;
1506
1507         for (j = 0; j < connector->count_encoders; j++) {
1508                 encoder = drmModeGetEncoder(ec->drm.fd, connector->encoders[j]);
1509                 if (encoder == NULL) {
1510                         weston_log("Failed to get encoder.\n");
1511                         return -1;
1512                 }
1513                 possible_crtcs = encoder->possible_crtcs;
1514                 drmModeFreeEncoder(encoder);
1515
1516                 for (i = 0; i < resources->count_crtcs; i++) {
1517                         if (possible_crtcs & (1 << i) &&
1518                             !(ec->crtc_allocator & (1 << resources->crtcs[i])))
1519                                 return i;
1520                 }
1521         }
1522
1523         return -1;
1524 }
1525
1526 /* Init output state that depends on gl or gbm */
1527 static int
1528 drm_output_init_egl(struct drm_output *output, struct drm_compositor *ec)
1529 {
1530         int i, flags;
1531
1532         output->surface = gbm_surface_create(ec->gbm,
1533                                              output->base.current_mode->width,
1534                                              output->base.current_mode->height,
1535                                              ec->format,
1536                                              GBM_BO_USE_SCANOUT |
1537                                              GBM_BO_USE_RENDERING);
1538         if (!output->surface) {
1539                 weston_log("failed to create gbm surface\n");
1540                 return -1;
1541         }
1542
1543         if (gl_renderer->output_create(&output->base, output->surface) < 0) {
1544                 weston_log("failed to create gl renderer output state\n");
1545                 gbm_surface_destroy(output->surface);
1546                 return -1;
1547         }
1548
1549         flags = GBM_BO_USE_CURSOR_64X64 | GBM_BO_USE_WRITE;
1550
1551         for (i = 0; i < 2; i++) {
1552                 if (output->cursor_bo[i])
1553                         continue;
1554
1555                 output->cursor_bo[i] =
1556                         gbm_bo_create(ec->gbm, 64, 64, GBM_FORMAT_ARGB8888,
1557                                       flags);
1558         }
1559
1560         if (output->cursor_bo[0] == NULL || output->cursor_bo[1] == NULL) {
1561                 weston_log("cursor buffers unavailable, using gl cursors\n");
1562                 ec->cursors_are_broken = 1;
1563         }
1564
1565         return 0;
1566 }
1567
1568 static int
1569 drm_output_init_pixman(struct drm_output *output, struct drm_compositor *c)
1570 {
1571         int w = output->base.current_mode->width;
1572         int h = output->base.current_mode->height;
1573         unsigned int i;
1574
1575         /* FIXME error checking */
1576
1577         for (i = 0; i < ARRAY_LENGTH(output->dumb); i++) {
1578                 output->dumb[i] = drm_fb_create_dumb(c, w, h);
1579                 if (!output->dumb[i])
1580                         goto err;
1581
1582                 output->image[i] =
1583                         pixman_image_create_bits(PIXMAN_x8r8g8b8, w, h,
1584                                                  output->dumb[i]->map,
1585                                                  output->dumb[i]->stride);
1586                 if (!output->image[i])
1587                         goto err;
1588         }
1589
1590         if (pixman_renderer_output_create(&output->base) < 0)
1591                 goto err;
1592
1593         pixman_region32_init_rect(&output->previous_damage,
1594                                   output->base.x, output->base.y, output->base.width, output->base.height);
1595
1596         return 0;
1597
1598 err:
1599         for (i = 0; i < ARRAY_LENGTH(output->dumb); i++) {
1600                 if (output->dumb[i])
1601                         drm_fb_destroy_dumb(output->dumb[i]);
1602                 if (output->image[i])
1603                         pixman_image_unref(output->image[i]);
1604
1605                 output->dumb[i] = NULL;
1606                 output->image[i] = NULL;
1607         }
1608
1609         return -1;
1610 }
1611
1612 static void
1613 drm_output_fini_pixman(struct drm_output *output)
1614 {
1615         unsigned int i;
1616
1617         pixman_renderer_output_destroy(&output->base);
1618         pixman_region32_fini(&output->previous_damage);
1619
1620         for (i = 0; i < ARRAY_LENGTH(output->dumb); i++) {
1621                 drm_fb_destroy_dumb(output->dumb[i]);
1622                 pixman_image_unref(output->image[i]);
1623                 output->dumb[i] = NULL;
1624                 output->image[i] = NULL;
1625         }
1626 }
1627
1628 static void
1629 edid_parse_string(const uint8_t *data, char text[])
1630 {
1631         int i;
1632         int replaced = 0;
1633
1634         /* this is always 12 bytes, but we can't guarantee it's null
1635          * terminated or not junk. */
1636         strncpy(text, (const char *) data, 12);
1637
1638         /* remove insane chars */
1639         for (i = 0; text[i] != '\0'; i++) {
1640                 if (text[i] == '\n' ||
1641                     text[i] == '\r') {
1642                         text[i] = '\0';
1643                         break;
1644                 }
1645         }
1646
1647         /* ensure string is printable */
1648         for (i = 0; text[i] != '\0'; i++) {
1649                 if (!isprint(text[i])) {
1650                         text[i] = '-';
1651                         replaced++;
1652                 }
1653         }
1654
1655         /* if the string is random junk, ignore the string */
1656         if (replaced > 4)
1657                 text[0] = '\0';
1658 }
1659
1660 #define EDID_DESCRIPTOR_ALPHANUMERIC_DATA_STRING        0xfe
1661 #define EDID_DESCRIPTOR_DISPLAY_PRODUCT_NAME            0xfc
1662 #define EDID_DESCRIPTOR_DISPLAY_PRODUCT_SERIAL_NUMBER   0xff
1663 #define EDID_OFFSET_DATA_BLOCKS                         0x36
1664 #define EDID_OFFSET_LAST_BLOCK                          0x6c
1665 #define EDID_OFFSET_PNPID                               0x08
1666 #define EDID_OFFSET_SERIAL                              0x0c
1667
1668 static int
1669 edid_parse(struct drm_edid *edid, const uint8_t *data, size_t length)
1670 {
1671         int i;
1672         uint32_t serial_number;
1673
1674         /* check header */
1675         if (length < 128)
1676                 return -1;
1677         if (data[0] != 0x00 || data[1] != 0xff)
1678                 return -1;
1679
1680         /* decode the PNP ID from three 5 bit words packed into 2 bytes
1681          * /--08--\/--09--\
1682          * 7654321076543210
1683          * |\---/\---/\---/
1684          * R  C1   C2   C3 */
1685         edid->pnp_id[0] = 'A' + ((data[EDID_OFFSET_PNPID + 0] & 0x7c) / 4) - 1;
1686         edid->pnp_id[1] = 'A' + ((data[EDID_OFFSET_PNPID + 0] & 0x3) * 8) + ((data[EDID_OFFSET_PNPID + 1] & 0xe0) / 32) - 1;
1687         edid->pnp_id[2] = 'A' + (data[EDID_OFFSET_PNPID + 1] & 0x1f) - 1;
1688         edid->pnp_id[3] = '\0';
1689
1690         /* maybe there isn't a ASCII serial number descriptor, so use this instead */
1691         serial_number = (uint32_t) data[EDID_OFFSET_SERIAL + 0];
1692         serial_number += (uint32_t) data[EDID_OFFSET_SERIAL + 1] * 0x100;
1693         serial_number += (uint32_t) data[EDID_OFFSET_SERIAL + 2] * 0x10000;
1694         serial_number += (uint32_t) data[EDID_OFFSET_SERIAL + 3] * 0x1000000;
1695         if (serial_number > 0)
1696                 sprintf(edid->serial_number, "%lu", (unsigned long) serial_number);
1697
1698         /* parse EDID data */
1699         for (i = EDID_OFFSET_DATA_BLOCKS;
1700              i <= EDID_OFFSET_LAST_BLOCK;
1701              i += 18) {
1702                 /* ignore pixel clock data */
1703                 if (data[i] != 0)
1704                         continue;
1705                 if (data[i+2] != 0)
1706                         continue;
1707
1708                 /* any useful blocks? */
1709                 if (data[i+3] == EDID_DESCRIPTOR_DISPLAY_PRODUCT_NAME) {
1710                         edid_parse_string(&data[i+5],
1711                                           edid->monitor_name);
1712                 } else if (data[i+3] == EDID_DESCRIPTOR_DISPLAY_PRODUCT_SERIAL_NUMBER) {
1713                         edid_parse_string(&data[i+5],
1714                                           edid->serial_number);
1715                 } else if (data[i+3] == EDID_DESCRIPTOR_ALPHANUMERIC_DATA_STRING) {
1716                         edid_parse_string(&data[i+5],
1717                                           edid->eisa_id);
1718                 }
1719         }
1720         return 0;
1721 }
1722
1723 static void
1724 find_and_parse_output_edid(struct drm_compositor *ec,
1725                            struct drm_output *output,
1726                            drmModeConnector *connector)
1727 {
1728         drmModePropertyBlobPtr edid_blob = NULL;
1729         drmModePropertyPtr property;
1730         int i;
1731         int rc;
1732
1733         for (i = 0; i < connector->count_props && !edid_blob; i++) {
1734                 property = drmModeGetProperty(ec->drm.fd, connector->props[i]);
1735                 if (!property)
1736                         continue;
1737                 if ((property->flags & DRM_MODE_PROP_BLOB) &&
1738                     !strcmp(property->name, "EDID")) {
1739                         edid_blob = drmModeGetPropertyBlob(ec->drm.fd,
1740                                                            connector->prop_values[i]);
1741                 }
1742                 drmModeFreeProperty(property);
1743         }
1744         if (!edid_blob)
1745                 return;
1746
1747         rc = edid_parse(&output->edid,
1748                         edid_blob->data,
1749                         edid_blob->length);
1750         if (!rc) {
1751                 weston_log("EDID data '%s', '%s', '%s'\n",
1752                            output->edid.pnp_id,
1753                            output->edid.monitor_name,
1754                            output->edid.serial_number);
1755                 if (output->edid.pnp_id[0] != '\0')
1756                         output->base.make = output->edid.pnp_id;
1757                 if (output->edid.monitor_name[0] != '\0')
1758                         output->base.model = output->edid.monitor_name;
1759                 if (output->edid.serial_number[0] != '\0')
1760                         output->base.serial_number = output->edid.serial_number;
1761         }
1762         drmModeFreePropertyBlob(edid_blob);
1763 }
1764
1765
1766
1767 static int
1768 parse_modeline(const char *s, drmModeModeInfo *mode)
1769 {
1770         char hsync[16];
1771         char vsync[16];
1772         float fclock;
1773
1774         mode->type = DRM_MODE_TYPE_USERDEF;
1775         mode->hskew = 0;
1776         mode->vscan = 0;
1777         mode->vrefresh = 0;
1778         mode->flags = 0;
1779
1780         if (sscanf(s, "%f %hd %hd %hd %hd %hd %hd %hd %hd %15s %15s",
1781                    &fclock,
1782                    &mode->hdisplay,
1783                    &mode->hsync_start,
1784                    &mode->hsync_end,
1785                    &mode->htotal,
1786                    &mode->vdisplay,
1787                    &mode->vsync_start,
1788                    &mode->vsync_end,
1789                    &mode->vtotal, hsync, vsync) != 11)
1790                 return -1;
1791
1792         mode->clock = fclock * 1000;
1793         if (strcmp(hsync, "+hsync") == 0)
1794                 mode->flags |= DRM_MODE_FLAG_PHSYNC;
1795         else if (strcmp(hsync, "-hsync") == 0)
1796                 mode->flags |= DRM_MODE_FLAG_NHSYNC;
1797         else
1798                 return -1;
1799
1800         if (strcmp(vsync, "+vsync") == 0)
1801                 mode->flags |= DRM_MODE_FLAG_PVSYNC;
1802         else if (strcmp(vsync, "-vsync") == 0)
1803                 mode->flags |= DRM_MODE_FLAG_NVSYNC;
1804         else
1805                 return -1;
1806
1807         return 0;
1808 }
1809
1810 static uint32_t
1811 parse_transform(const char *transform, const char *output_name)
1812 {
1813         static const struct { const char *name; uint32_t token; } names[] = {
1814                 { "normal",     WL_OUTPUT_TRANSFORM_NORMAL },
1815                 { "90",         WL_OUTPUT_TRANSFORM_90 },
1816                 { "180",        WL_OUTPUT_TRANSFORM_180 },
1817                 { "270",        WL_OUTPUT_TRANSFORM_270 },
1818                 { "flipped",    WL_OUTPUT_TRANSFORM_FLIPPED },
1819                 { "flipped-90", WL_OUTPUT_TRANSFORM_FLIPPED_90 },
1820                 { "flipped-180", WL_OUTPUT_TRANSFORM_FLIPPED_180 },
1821                 { "flipped-270", WL_OUTPUT_TRANSFORM_FLIPPED_270 },
1822         };
1823         unsigned int i;
1824
1825         for (i = 0; i < ARRAY_LENGTH(names); i++)
1826                 if (strcmp(names[i].name, transform) == 0)
1827                         return names[i].token;
1828
1829         weston_log("Invalid transform \"%s\" for output %s\n",
1830                    transform, output_name);
1831
1832         return WL_OUTPUT_TRANSFORM_NORMAL;
1833 }
1834
1835 static void
1836 setup_output_seat_constraint(struct drm_compositor *ec,
1837                              struct weston_output *output,
1838                              const char *s)
1839 {
1840         if (strcmp(s, "") != 0) {
1841                 struct udev_seat *seat;
1842
1843                 seat = udev_seat_get_named(&ec->base, s);
1844                 if (seat)
1845                         seat->base.output = output;
1846
1847                 if (seat && seat->base.pointer)
1848                         weston_pointer_clamp(seat->base.pointer,
1849                                              &seat->base.pointer->x,
1850                                              &seat->base.pointer->y);
1851         }
1852 }
1853
1854 static int
1855 create_output_for_connector(struct drm_compositor *ec,
1856                             drmModeRes *resources,
1857                             drmModeConnector *connector,
1858                             int x, int y, struct udev_device *drm_device)
1859 {
1860         struct drm_output *output;
1861         struct drm_mode *drm_mode, *next, *preferred, *current, *configured, *best;
1862         struct weston_mode *m;
1863         struct weston_config_section *section;
1864         drmModeEncoder *encoder;
1865         drmModeModeInfo crtc_mode, modeline;
1866         drmModeCrtc *crtc;
1867         int i, width, height, scale;
1868         char name[32], *s;
1869         const char *type_name;
1870         enum output_config config;
1871         uint32_t transform;
1872
1873         i = find_crtc_for_connector(ec, resources, connector);
1874         if (i < 0) {
1875                 weston_log("No usable crtc/encoder pair for connector.\n");
1876                 return -1;
1877         }
1878
1879         output = zalloc(sizeof *output);
1880         if (output == NULL)
1881                 return -1;
1882
1883         output->base.subpixel = drm_subpixel_to_wayland(connector->subpixel);
1884         output->base.make = "unknown";
1885         output->base.model = "unknown";
1886         output->base.serial_number = "unknown";
1887         wl_list_init(&output->base.mode_list);
1888
1889         if (connector->connector_type < ARRAY_LENGTH(connector_type_names))
1890                 type_name = connector_type_names[connector->connector_type];
1891         else
1892                 type_name = "UNKNOWN";
1893         snprintf(name, 32, "%s%d", type_name, connector->connector_type_id);
1894         output->base.name = strdup(name);
1895
1896         section = weston_config_get_section(ec->base.config, "output", "name",
1897                                             output->base.name);
1898         weston_config_section_get_string(section, "mode", &s, "preferred");
1899         if (strcmp(s, "off") == 0)
1900                 config = OUTPUT_CONFIG_OFF;
1901         else if (strcmp(s, "preferred") == 0)
1902                 config = OUTPUT_CONFIG_PREFERRED;
1903         else if (strcmp(s, "current") == 0)
1904                 config = OUTPUT_CONFIG_CURRENT;
1905         else if (sscanf(s, "%dx%d", &width, &height) == 2)
1906                 config = OUTPUT_CONFIG_MODE;
1907         else if (parse_modeline(s, &modeline) == 0)
1908                 config = OUTPUT_CONFIG_MODELINE;
1909         else {
1910                 weston_log("Invalid mode \"%s\" for output %s\n",
1911                            s, output->base.name);
1912                 config = OUTPUT_CONFIG_PREFERRED;
1913         }
1914         free(s);
1915
1916         weston_config_section_get_int(section, "scale", &scale, 1);
1917         weston_config_section_get_string(section, "transform", &s, "normal");
1918         transform = parse_transform(s, output->base.name);
1919         free(s);
1920
1921         weston_config_section_get_string(section, "seat", &s, "");
1922         setup_output_seat_constraint(ec, &output->base, s);
1923         free(s);
1924
1925         output->crtc_id = resources->crtcs[i];
1926         output->pipe = i;
1927         ec->crtc_allocator |= (1 << output->crtc_id);
1928         output->connector_id = connector->connector_id;
1929         ec->connector_allocator |= (1 << output->connector_id);
1930
1931         output->original_crtc = drmModeGetCrtc(ec->drm.fd, output->crtc_id);
1932         output->dpms_prop = drm_get_prop(ec->drm.fd, connector, "DPMS");
1933
1934         /* Get the current mode on the crtc that's currently driving
1935          * this connector. */
1936         encoder = drmModeGetEncoder(ec->drm.fd, connector->encoder_id);
1937         memset(&crtc_mode, 0, sizeof crtc_mode);
1938         if (encoder != NULL) {
1939                 crtc = drmModeGetCrtc(ec->drm.fd, encoder->crtc_id);
1940                 drmModeFreeEncoder(encoder);
1941                 if (crtc == NULL)
1942                         goto err_free;
1943                 if (crtc->mode_valid)
1944                         crtc_mode = crtc->mode;
1945                 drmModeFreeCrtc(crtc);
1946         }
1947
1948         for (i = 0; i < connector->count_modes; i++) {
1949                 drm_mode = drm_output_add_mode(output, &connector->modes[i]);
1950                 if (!drm_mode)
1951                         goto err_free;
1952         }
1953
1954         if (config == OUTPUT_CONFIG_OFF) {
1955                 weston_log("Disabling output %s\n", output->base.name);
1956                 drmModeSetCrtc(ec->drm.fd, output->crtc_id,
1957                                0, 0, 0, 0, 0, NULL);
1958                 goto err_free;
1959         }
1960
1961         preferred = NULL;
1962         current = NULL;
1963         configured = NULL;
1964         best = NULL;
1965
1966         wl_list_for_each_reverse(drm_mode, &output->base.mode_list, base.link) {
1967                 if (config == OUTPUT_CONFIG_MODE &&
1968                     width == drm_mode->base.width &&
1969                     height == drm_mode->base.height)
1970                         configured = drm_mode;
1971                 if (!memcmp(&crtc_mode, &drm_mode->mode_info, sizeof crtc_mode))
1972                         current = drm_mode;
1973                 if (drm_mode->base.flags & WL_OUTPUT_MODE_PREFERRED)
1974                         preferred = drm_mode;
1975                 best = drm_mode;
1976         }
1977
1978         if (config == OUTPUT_CONFIG_MODELINE) {
1979                 configured = drm_output_add_mode(output, &modeline);
1980                 if (!configured)
1981                         goto err_free;
1982         }
1983
1984         if (current == NULL && crtc_mode.clock != 0) {
1985                 current = drm_output_add_mode(output, &crtc_mode);
1986                 if (!current)
1987                         goto err_free;
1988         }
1989
1990         if (config == OUTPUT_CONFIG_CURRENT)
1991                 configured = current;
1992
1993         if (option_current_mode && current)
1994                 output->base.current_mode = &current->base;
1995         else if (configured)
1996                 output->base.current_mode = &configured->base;
1997         else if (preferred)
1998                 output->base.current_mode = &preferred->base;
1999         else if (current)
2000                 output->base.current_mode = &current->base;
2001         else if (best)
2002                 output->base.current_mode = &best->base;
2003
2004         if (output->base.current_mode == NULL) {
2005                 weston_log("no available modes for %s\n", output->base.name);
2006                 goto err_free;
2007         }
2008
2009         output->base.current_mode->flags |= WL_OUTPUT_MODE_CURRENT;
2010
2011         weston_output_init(&output->base, &ec->base, x, y,
2012                            connector->mmWidth, connector->mmHeight,
2013                            transform, scale);
2014
2015         if (ec->use_pixman) {
2016                 if (drm_output_init_pixman(output, ec) < 0) {
2017                         weston_log("Failed to init output pixman state\n");
2018                         goto err_output;
2019                 }
2020         } else if (drm_output_init_egl(output, ec) < 0) {
2021                 weston_log("Failed to init output gl state\n");
2022                 goto err_output;
2023         }
2024
2025         output->backlight = backlight_init(drm_device,
2026                                            connector->connector_type);
2027         if (output->backlight) {
2028                 weston_log("Initialized backlight, device %s\n",
2029                            output->backlight->path);
2030                 output->base.set_backlight = drm_set_backlight;
2031                 output->base.backlight_current = drm_get_backlight(output);
2032         } else {
2033                 weston_log("Failed to initialize backlight\n");
2034         }
2035
2036         wl_list_insert(ec->base.output_list.prev, &output->base.link);
2037
2038         find_and_parse_output_edid(ec, output, connector);
2039         if (connector->connector_type == DRM_MODE_CONNECTOR_LVDS)
2040                 output->base.connection_internal = 1;
2041
2042         output->base.start_repaint_loop = drm_output_start_repaint_loop;
2043         output->base.repaint = drm_output_repaint;
2044         output->base.destroy = drm_output_destroy;
2045         output->base.assign_planes = drm_assign_planes;
2046         output->base.set_dpms = drm_set_dpms;
2047         output->base.switch_mode = drm_output_switch_mode;
2048
2049         output->base.gamma_size = output->original_crtc->gamma_size;
2050         output->base.set_gamma = drm_output_set_gamma;
2051
2052         weston_plane_init(&output->cursor_plane, &ec->base, 0, 0);
2053         weston_plane_init(&output->fb_plane, &ec->base, 0, 0);
2054
2055         weston_compositor_stack_plane(&ec->base, &output->cursor_plane, NULL);
2056         weston_compositor_stack_plane(&ec->base, &output->fb_plane,
2057                                       &ec->base.primary_plane);
2058
2059         weston_log("Output %s, (connector %d, crtc %d)\n",
2060                    output->base.name, output->connector_id, output->crtc_id);
2061         wl_list_for_each(m, &output->base.mode_list, link)
2062                 weston_log_continue("  mode %dx%d@%.1f%s%s%s\n",
2063                                     m->width, m->height, m->refresh / 1000.0,
2064                                     m->flags & WL_OUTPUT_MODE_PREFERRED ?
2065                                     ", preferred" : "",
2066                                     m->flags & WL_OUTPUT_MODE_CURRENT ?
2067                                     ", current" : "",
2068                                     connector->count_modes == 0 ?
2069                                     ", built-in" : "");
2070
2071         return 0;
2072
2073 err_output:
2074         weston_output_destroy(&output->base);
2075 err_free:
2076         wl_list_for_each_safe(drm_mode, next, &output->base.mode_list,
2077                                                         base.link) {
2078                 wl_list_remove(&drm_mode->base.link);
2079                 free(drm_mode);
2080         }
2081
2082         drmModeFreeCrtc(output->original_crtc);
2083         ec->crtc_allocator &= ~(1 << output->crtc_id);
2084         ec->connector_allocator &= ~(1 << output->connector_id);
2085         free(output);
2086
2087         return -1;
2088 }
2089
2090 static void
2091 create_sprites(struct drm_compositor *ec)
2092 {
2093         struct drm_sprite *sprite;
2094         drmModePlaneRes *plane_res;
2095         drmModePlane *plane;
2096         uint32_t i;
2097
2098         plane_res = drmModeGetPlaneResources(ec->drm.fd);
2099         if (!plane_res) {
2100                 weston_log("failed to get plane resources: %s\n",
2101                         strerror(errno));
2102                 return;
2103         }
2104
2105         for (i = 0; i < plane_res->count_planes; i++) {
2106                 plane = drmModeGetPlane(ec->drm.fd, plane_res->planes[i]);
2107                 if (!plane)
2108                         continue;
2109
2110                 sprite = zalloc(sizeof(*sprite) + ((sizeof(uint32_t)) *
2111                                                    plane->count_formats));
2112                 if (!sprite) {
2113                         weston_log("%s: out of memory\n",
2114                                 __func__);
2115                         drmModeFreePlane(plane);
2116                         continue;
2117                 }
2118
2119                 sprite->possible_crtcs = plane->possible_crtcs;
2120                 sprite->plane_id = plane->plane_id;
2121                 sprite->current = NULL;
2122                 sprite->next = NULL;
2123                 sprite->compositor = ec;
2124                 sprite->count_formats = plane->count_formats;
2125                 memcpy(sprite->formats, plane->formats,
2126                        plane->count_formats * sizeof(plane->formats[0]));
2127                 drmModeFreePlane(plane);
2128                 weston_plane_init(&sprite->plane, &ec->base, 0, 0);
2129                 weston_compositor_stack_plane(&ec->base, &sprite->plane,
2130                                               &ec->base.primary_plane);
2131
2132                 wl_list_insert(&ec->sprite_list, &sprite->link);
2133         }
2134
2135         drmModeFreePlaneResources(plane_res);
2136 }
2137
2138 static void
2139 destroy_sprites(struct drm_compositor *compositor)
2140 {
2141         struct drm_sprite *sprite, *next;
2142         struct drm_output *output;
2143
2144         output = container_of(compositor->base.output_list.next,
2145                               struct drm_output, base.link);
2146
2147         wl_list_for_each_safe(sprite, next, &compositor->sprite_list, link) {
2148                 drmModeSetPlane(compositor->drm.fd,
2149                                 sprite->plane_id,
2150                                 output->crtc_id, 0, 0,
2151                                 0, 0, 0, 0, 0, 0, 0, 0);
2152                 drm_output_release_fb(output, sprite->current);
2153                 drm_output_release_fb(output, sprite->next);
2154                 weston_plane_release(&sprite->plane);
2155                 free(sprite);
2156         }
2157 }
2158
2159 static int
2160 create_outputs(struct drm_compositor *ec, uint32_t option_connector,
2161                struct udev_device *drm_device)
2162 {
2163         drmModeConnector *connector;
2164         drmModeRes *resources;
2165         int i;
2166         int x = 0, y = 0;
2167
2168         resources = drmModeGetResources(ec->drm.fd);
2169         if (!resources) {
2170                 weston_log("drmModeGetResources failed\n");
2171                 return -1;
2172         }
2173
2174         ec->crtcs = calloc(resources->count_crtcs, sizeof(uint32_t));
2175         if (!ec->crtcs) {
2176                 drmModeFreeResources(resources);
2177                 return -1;
2178         }
2179
2180         ec->min_width  = resources->min_width;
2181         ec->max_width  = resources->max_width;
2182         ec->min_height = resources->min_height;
2183         ec->max_height = resources->max_height;
2184
2185         ec->num_crtcs = resources->count_crtcs;
2186         memcpy(ec->crtcs, resources->crtcs, sizeof(uint32_t) * ec->num_crtcs);
2187
2188         for (i = 0; i < resources->count_connectors; i++) {
2189                 connector = drmModeGetConnector(ec->drm.fd,
2190                                                 resources->connectors[i]);
2191                 if (connector == NULL)
2192                         continue;
2193
2194                 if (connector->connection == DRM_MODE_CONNECTED &&
2195                     (option_connector == 0 ||
2196                      connector->connector_id == option_connector)) {
2197                         if (create_output_for_connector(ec, resources,
2198                                                         connector, x, y,
2199                                                         drm_device) < 0) {
2200                                 drmModeFreeConnector(connector);
2201                                 continue;
2202                         }
2203
2204                         x += container_of(ec->base.output_list.prev,
2205                                           struct weston_output,
2206                                           link)->width;
2207                 }
2208
2209                 drmModeFreeConnector(connector);
2210         }
2211
2212         if (wl_list_empty(&ec->base.output_list)) {
2213                 weston_log("No currently active connector found.\n");
2214                 drmModeFreeResources(resources);
2215                 return -1;
2216         }
2217
2218         drmModeFreeResources(resources);
2219
2220         return 0;
2221 }
2222
2223 static void
2224 update_outputs(struct drm_compositor *ec, struct udev_device *drm_device)
2225 {
2226         drmModeConnector *connector;
2227         drmModeRes *resources;
2228         struct drm_output *output, *next;
2229         int x = 0, y = 0;
2230         uint32_t connected = 0, disconnects = 0;
2231         int i;
2232
2233         resources = drmModeGetResources(ec->drm.fd);
2234         if (!resources) {
2235                 weston_log("drmModeGetResources failed\n");
2236                 return;
2237         }
2238
2239         /* collect new connects */
2240         for (i = 0; i < resources->count_connectors; i++) {
2241                 int connector_id = resources->connectors[i];
2242
2243                 connector = drmModeGetConnector(ec->drm.fd, connector_id);
2244                 if (connector == NULL)
2245                         continue;
2246
2247                 if (connector->connection != DRM_MODE_CONNECTED) {
2248                         drmModeFreeConnector(connector);
2249                         continue;
2250                 }
2251
2252                 connected |= (1 << connector_id);
2253
2254                 if (!(ec->connector_allocator & (1 << connector_id))) {
2255                         struct weston_output *last =
2256                                 container_of(ec->base.output_list.prev,
2257                                              struct weston_output, link);
2258
2259                         /* XXX: not yet needed, we die with 0 outputs */
2260                         if (!wl_list_empty(&ec->base.output_list))
2261                                 x = last->x + last->width;
2262                         else
2263                                 x = 0;
2264                         y = 0;
2265                         create_output_for_connector(ec, resources,
2266                                                     connector, x, y,
2267                                                     drm_device);
2268                         weston_log("connector %d connected\n", connector_id);
2269
2270                 }
2271                 drmModeFreeConnector(connector);
2272         }
2273         drmModeFreeResources(resources);
2274
2275         disconnects = ec->connector_allocator & ~connected;
2276         if (disconnects) {
2277                 wl_list_for_each_safe(output, next, &ec->base.output_list,
2278                                       base.link) {
2279                         if (disconnects & (1 << output->connector_id)) {
2280                                 disconnects &= ~(1 << output->connector_id);
2281                                 weston_log("connector %d disconnected\n",
2282                                        output->connector_id);
2283                                 drm_output_destroy(&output->base);
2284                         }
2285                 }
2286         }
2287
2288         /* FIXME: handle zero outputs, without terminating */   
2289         if (ec->connector_allocator == 0)
2290                 wl_display_terminate(ec->base.wl_display);
2291 }
2292
2293 static int
2294 udev_event_is_hotplug(struct drm_compositor *ec, struct udev_device *device)
2295 {
2296         const char *sysnum;
2297         const char *val;
2298
2299         sysnum = udev_device_get_sysnum(device);
2300         if (!sysnum || atoi(sysnum) != ec->drm.id)
2301                 return 0;
2302
2303         val = udev_device_get_property_value(device, "HOTPLUG");
2304         if (!val)
2305                 return 0;
2306
2307         return strcmp(val, "1") == 0;
2308 }
2309
2310 static int
2311 udev_drm_event(int fd, uint32_t mask, void *data)
2312 {
2313         struct drm_compositor *ec = data;
2314         struct udev_device *event;
2315
2316         event = udev_monitor_receive_device(ec->udev_monitor);
2317
2318         if (udev_event_is_hotplug(ec, event))
2319                 update_outputs(ec, event);
2320
2321         udev_device_unref(event);
2322
2323         return 1;
2324 }
2325
2326 static void
2327 drm_restore(struct weston_compositor *ec)
2328 {
2329         weston_launcher_restore(ec->launcher);
2330 }
2331
2332 static void
2333 drm_destroy(struct weston_compositor *ec)
2334 {
2335         struct drm_compositor *d = (struct drm_compositor *) ec;
2336
2337         udev_input_destroy(&d->input);
2338
2339         wl_event_source_remove(d->udev_drm_source);
2340         wl_event_source_remove(d->drm_source);
2341
2342         destroy_sprites(d);
2343
2344         weston_compositor_shutdown(ec);
2345
2346         if (d->gbm)
2347                 gbm_device_destroy(d->gbm);
2348
2349         weston_launcher_destroy(d->base.launcher);
2350
2351         close(d->drm.fd);
2352
2353         free(d);
2354 }
2355
2356 static void
2357 drm_compositor_set_modes(struct drm_compositor *compositor)
2358 {
2359         struct drm_output *output;
2360         struct drm_mode *drm_mode;
2361         int ret;
2362
2363         wl_list_for_each(output, &compositor->base.output_list, base.link) {
2364                 if (!output->current) {
2365                         /* If something that would cause the output to
2366                          * switch mode happened while in another vt, we
2367                          * might not have a current drm_fb. In that case,
2368                          * schedule a repaint and let drm_output_repaint
2369                          * handle setting the mode. */
2370                         weston_output_schedule_repaint(&output->base);
2371                         continue;
2372                 }
2373
2374                 drm_mode = (struct drm_mode *) output->base.current_mode;
2375                 ret = drmModeSetCrtc(compositor->drm.fd, output->crtc_id,
2376                                      output->current->fb_id, 0, 0,
2377                                      &output->connector_id, 1,
2378                                      &drm_mode->mode_info);
2379                 if (ret < 0) {
2380                         weston_log(
2381                                 "failed to set mode %dx%d for output at %d,%d: %m\n",
2382                                 drm_mode->base.width, drm_mode->base.height, 
2383                                 output->base.x, output->base.y);
2384                 }
2385         }
2386 }
2387
2388 static void
2389 session_notify(struct wl_listener *listener, void *data)
2390 {
2391         struct weston_compositor *compositor = data;
2392         struct drm_compositor *ec = data;
2393         struct drm_sprite *sprite;
2394         struct drm_output *output;
2395
2396         if (ec->base.session_active) {
2397                 weston_log("activating session\n");
2398                 compositor->state = ec->prev_state;
2399                 drm_compositor_set_modes(ec);
2400                 weston_compositor_damage_all(compositor);
2401                 udev_input_enable(&ec->input, ec->udev);
2402         } else {
2403                 weston_log("deactivating session\n");
2404                 udev_input_disable(&ec->input);
2405
2406                 ec->prev_state = compositor->state;
2407                 weston_compositor_offscreen(compositor);
2408
2409                 /* If we have a repaint scheduled (either from a
2410                  * pending pageflip or the idle handler), make sure we
2411                  * cancel that so we don't try to pageflip when we're
2412                  * vt switched away.  The OFFSCREEN state will prevent
2413                  * further attemps at repainting.  When we switch
2414                  * back, we schedule a repaint, which will process
2415                  * pending frame callbacks. */
2416
2417                 wl_list_for_each(output, &ec->base.output_list, base.link) {
2418                         output->base.repaint_needed = 0;
2419                         drmModeSetCursor(ec->drm.fd, output->crtc_id, 0, 0, 0);
2420                 }
2421
2422                 output = container_of(ec->base.output_list.next,
2423                                       struct drm_output, base.link);
2424
2425                 wl_list_for_each(sprite, &ec->sprite_list, link)
2426                         drmModeSetPlane(ec->drm.fd,
2427                                         sprite->plane_id,
2428                                         output->crtc_id, 0, 0,
2429                                         0, 0, 0, 0, 0, 0, 0, 0);
2430         };
2431 }
2432
2433 static void
2434 switch_vt_binding(struct weston_seat *seat, uint32_t time, uint32_t key, void *data)
2435 {
2436         struct weston_compositor *compositor = data;
2437
2438         weston_launcher_activate_vt(compositor->launcher, key - KEY_F1 + 1);
2439 }
2440
2441 /*
2442  * Find primary GPU
2443  * Some systems may have multiple DRM devices attached to a single seat. This
2444  * function loops over all devices and tries to find a PCI device with the
2445  * boot_vga sysfs attribute set to 1.
2446  * If no such device is found, the first DRM device reported by udev is used.
2447  */
2448 static struct udev_device*
2449 find_primary_gpu(struct drm_compositor *ec, const char *seat)
2450 {
2451         struct udev_enumerate *e;
2452         struct udev_list_entry *entry;
2453         const char *path, *device_seat, *id;
2454         struct udev_device *device, *drm_device, *pci;
2455
2456         e = udev_enumerate_new(ec->udev);
2457         udev_enumerate_add_match_subsystem(e, "drm");
2458         udev_enumerate_add_match_sysname(e, "card[0-9]*");
2459
2460         udev_enumerate_scan_devices(e);
2461         drm_device = NULL;
2462         udev_list_entry_foreach(entry, udev_enumerate_get_list_entry(e)) {
2463                 path = udev_list_entry_get_name(entry);
2464                 device = udev_device_new_from_syspath(ec->udev, path);
2465                 if (!device)
2466                         continue;
2467                 device_seat = udev_device_get_property_value(device, "ID_SEAT");
2468                 if (!device_seat)
2469                         device_seat = default_seat;
2470                 if (strcmp(device_seat, seat)) {
2471                         udev_device_unref(device);
2472                         continue;
2473                 }
2474
2475                 pci = udev_device_get_parent_with_subsystem_devtype(device,
2476                                                                 "pci", NULL);
2477                 if (pci) {
2478                         id = udev_device_get_sysattr_value(pci, "boot_vga");
2479                         if (id && !strcmp(id, "1")) {
2480                                 if (drm_device)
2481                                         udev_device_unref(drm_device);
2482                                 drm_device = device;
2483                                 break;
2484                         }
2485                 }
2486
2487                 if (!drm_device)
2488                         drm_device = device;
2489                 else
2490                         udev_device_unref(device);
2491         }
2492
2493         udev_enumerate_unref(e);
2494         return drm_device;
2495 }
2496
2497 static void
2498 planes_binding(struct weston_seat *seat, uint32_t time, uint32_t key, void *data)
2499 {
2500         struct drm_compositor *c = data;
2501
2502         switch (key) {
2503         case KEY_C:
2504                 c->cursors_are_broken ^= 1;
2505                 break;
2506         case KEY_V:
2507                 c->sprites_are_broken ^= 1;
2508                 break;
2509         case KEY_O:
2510                 c->sprites_hidden ^= 1;
2511                 break;
2512         default:
2513                 break;
2514         }
2515 }
2516
2517 #ifdef BUILD_VAAPI_RECORDER
2518 static void
2519 recorder_frame_notify(struct wl_listener *listener, void *data)
2520 {
2521         struct drm_output *output;
2522         struct drm_compositor *c;
2523         int fd, ret;
2524
2525         output = container_of(listener, struct drm_output,
2526                               recorder_frame_listener);
2527         c = (struct drm_compositor *) output->base.compositor;
2528
2529         if (!output->recorder)
2530                 return;
2531
2532         ret = drmPrimeHandleToFD(c->drm.fd, output->current->handle,
2533                                  DRM_CLOEXEC, &fd);
2534         if (ret) {
2535                 weston_log("[libva recorder] "
2536                            "failed to create prime fd for front buffer\n");
2537                 return;
2538         }
2539
2540         vaapi_recorder_frame(output->recorder, fd, output->current->stride / 4);
2541 }
2542
2543 static void *
2544 create_recorder(struct drm_compositor *c, int width, int height,
2545                 const char *filename)
2546 {
2547         int fd;
2548         drm_magic_t magic;
2549
2550         fd = open(c->drm.filename, O_RDWR | O_CLOEXEC);
2551         if (fd < 0)
2552                 return NULL;
2553
2554         drmGetMagic(fd, &magic);
2555         drmAuthMagic(c->drm.fd, magic);
2556
2557         return vaapi_recorder_create(fd, width, height, filename);
2558 }
2559
2560 static void
2561 recorder_binding(struct weston_seat *seat, uint32_t time, uint32_t key,
2562                  void *data)
2563 {
2564         struct drm_compositor *c = data;
2565         struct drm_output *output;
2566         int width, height;
2567
2568         output = container_of(c->base.output_list.next,
2569                               struct drm_output, base.link);
2570
2571         if (!output->recorder) {
2572                 width = output->base.current_mode->width;
2573                 height = output->base.current_mode->height;
2574
2575                 output->recorder =
2576                         create_recorder(c, width, height, "capture.h264");
2577                 if (!output->recorder) {
2578                         weston_log("failed to create vaapi recorder\n");
2579                         return;
2580                 }
2581
2582                 output->base.disable_planes++;
2583
2584                 output->recorder_frame_listener.notify = recorder_frame_notify;
2585                 wl_signal_add(&output->base.frame_signal,
2586                               &output->recorder_frame_listener);
2587
2588                 weston_output_schedule_repaint(&output->base);
2589
2590                 weston_log("[libva recorder] initialized\n");
2591         } else {
2592                 vaapi_recorder_destroy(output->recorder);
2593                 output->recorder = NULL;
2594
2595                 output->base.disable_planes--;
2596
2597                 wl_list_remove(&output->recorder_frame_listener.link);
2598                 weston_log("[libva recorder] done\n");
2599         }
2600 }
2601 #else
2602 static void
2603 recorder_binding(struct weston_seat *seat, uint32_t time, uint32_t key,
2604                  void *data)
2605 {
2606         weston_log("Compiled without libva support\n");
2607 }
2608 #endif
2609
2610 static void
2611 switch_to_gl_renderer(struct drm_compositor *c)
2612 {
2613         struct drm_output *output;
2614
2615         if (!c->use_pixman)
2616                 return;
2617
2618         weston_log("Switching to GL renderer\n");
2619
2620         c->gbm = create_gbm_device(c->drm.fd);
2621         if (!c->gbm) {
2622                 weston_log("Failed to create gbm device. "
2623                            "Aborting renderer switch\n");
2624                 return;
2625         }
2626
2627         wl_list_for_each(output, &c->base.output_list, base.link)
2628                 pixman_renderer_output_destroy(&output->base);
2629
2630         c->base.renderer->destroy(&c->base);
2631
2632         if (drm_compositor_create_gl_renderer(c) < 0) {
2633                 gbm_device_destroy(c->gbm);
2634                 weston_log("Failed to create GL renderer. Quitting.\n");
2635                 /* FIXME: we need a function to shutdown cleanly */
2636                 assert(0);
2637         }
2638
2639         wl_list_for_each(output, &c->base.output_list, base.link)
2640                 drm_output_init_egl(output, c);
2641
2642         c->use_pixman = 0;
2643 }
2644
2645 static void
2646 renderer_switch_binding(struct weston_seat *seat, uint32_t time, uint32_t key,
2647                         void *data)
2648 {
2649         struct drm_compositor *c = (struct drm_compositor *) seat->compositor;
2650
2651         switch_to_gl_renderer(c);
2652 }
2653
2654 static struct weston_compositor *
2655 drm_compositor_create(struct wl_display *display,
2656                       struct drm_parameters *param,
2657                       int *argc, char *argv[],
2658                       struct weston_config *config)
2659 {
2660         struct drm_compositor *ec;
2661         struct weston_config_section *section;
2662         struct udev_device *drm_device;
2663         struct wl_event_loop *loop;
2664         const char *path;
2665         char *s;
2666         uint32_t key;
2667
2668         weston_log("initializing drm backend\n");
2669
2670         ec = zalloc(sizeof *ec);
2671         if (ec == NULL)
2672                 return NULL;
2673
2674         /* KMS support for sprites is not complete yet, so disable the
2675          * functionality for now. */
2676         ec->sprites_are_broken = 1;
2677
2678         section = weston_config_get_section(config, "core", NULL, NULL);
2679         weston_config_section_get_string(section,
2680                                          "gbm-format", &s, "xrgb8888");
2681         if (strcmp(s, "xrgb8888") == 0)
2682                 ec->format = GBM_FORMAT_XRGB8888;
2683         else if (strcmp(s, "rgb565") == 0)
2684                 ec->format = GBM_FORMAT_RGB565;
2685         else if (strcmp(s, "xrgb2101010") == 0)
2686                 ec->format = GBM_FORMAT_XRGB2101010;
2687         else {
2688                 weston_log("fatal: unrecognized pixel format: %s\n", s);
2689                 free(s);
2690                 goto err_base;
2691         }
2692         free(s);
2693
2694         ec->use_pixman = param->use_pixman;
2695
2696         if (weston_compositor_init(&ec->base, display, argc, argv,
2697                                    config) < 0) {
2698                 weston_log("%s failed\n", __func__);
2699                 goto err_base;
2700         }
2701
2702         /* Check if we run drm-backend using weston-launch */
2703         ec->base.launcher = weston_launcher_connect(&ec->base, param->tty,
2704                                                     param->seat_id);
2705         if (ec->base.launcher == NULL) {
2706                 weston_log("fatal: drm backend should be run "
2707                            "using weston-launch binary or as root\n");
2708                 goto err_compositor;
2709         }
2710
2711         ec->udev = udev_new();
2712         if (ec->udev == NULL) {
2713                 weston_log("failed to initialize udev context\n");
2714                 goto err_launcher;
2715         }
2716
2717         ec->base.wl_display = display;
2718         ec->session_listener.notify = session_notify;
2719         wl_signal_add(&ec->base.session_signal, &ec->session_listener);
2720
2721         drm_device = find_primary_gpu(ec, param->seat_id);
2722         if (drm_device == NULL) {
2723                 weston_log("no drm device found\n");
2724                 goto err_udev;
2725         }
2726         path = udev_device_get_syspath(drm_device);
2727
2728         if (init_drm(ec, drm_device) < 0) {
2729                 weston_log("failed to initialize kms\n");
2730                 goto err_udev_dev;
2731         }
2732
2733         if (ec->use_pixman) {
2734                 if (init_pixman(ec) < 0) {
2735                         weston_log("failed to initialize pixman renderer\n");
2736                         goto err_udev_dev;
2737                 }
2738         } else {
2739                 if (init_egl(ec) < 0) {
2740                         weston_log("failed to initialize egl\n");
2741                         goto err_udev_dev;
2742                 }
2743         }
2744
2745         ec->base.destroy = drm_destroy;
2746         ec->base.restore = drm_restore;
2747
2748         ec->prev_state = WESTON_COMPOSITOR_ACTIVE;
2749
2750         for (key = KEY_F1; key < KEY_F9; key++)
2751                 weston_compositor_add_key_binding(&ec->base, key,
2752                                                   MODIFIER_CTRL | MODIFIER_ALT,
2753                                                   switch_vt_binding, ec);
2754
2755         wl_list_init(&ec->sprite_list);
2756         create_sprites(ec);
2757
2758         if (create_outputs(ec, param->connector, drm_device) < 0) {
2759                 weston_log("failed to create output for %s\n", path);
2760                 goto err_sprite;
2761         }
2762
2763         path = NULL;
2764
2765         if (udev_input_init(&ec->input,
2766                             &ec->base, ec->udev, param->seat_id) < 0) {
2767                 weston_log("failed to create input devices\n");
2768                 goto err_sprite;
2769         }
2770
2771         loop = wl_display_get_event_loop(ec->base.wl_display);
2772         ec->drm_source =
2773                 wl_event_loop_add_fd(loop, ec->drm.fd,
2774                                      WL_EVENT_READABLE, on_drm_input, ec);
2775
2776         ec->udev_monitor = udev_monitor_new_from_netlink(ec->udev, "udev");
2777         if (ec->udev_monitor == NULL) {
2778                 weston_log("failed to intialize udev monitor\n");
2779                 goto err_drm_source;
2780         }
2781         udev_monitor_filter_add_match_subsystem_devtype(ec->udev_monitor,
2782                                                         "drm", NULL);
2783         ec->udev_drm_source =
2784                 wl_event_loop_add_fd(loop,
2785                                      udev_monitor_get_fd(ec->udev_monitor),
2786                                      WL_EVENT_READABLE, udev_drm_event, ec);
2787
2788         if (udev_monitor_enable_receiving(ec->udev_monitor) < 0) {
2789                 weston_log("failed to enable udev-monitor receiving\n");
2790                 goto err_udev_monitor;
2791         }
2792
2793         udev_device_unref(drm_device);
2794
2795         weston_compositor_add_debug_binding(&ec->base, KEY_O,
2796                                             planes_binding, ec);
2797         weston_compositor_add_debug_binding(&ec->base, KEY_C,
2798                                             planes_binding, ec);
2799         weston_compositor_add_debug_binding(&ec->base, KEY_V,
2800                                             planes_binding, ec);
2801         weston_compositor_add_debug_binding(&ec->base, KEY_Q,
2802                                             recorder_binding, ec);
2803         weston_compositor_add_debug_binding(&ec->base, KEY_W,
2804                                             renderer_switch_binding, ec);
2805
2806         return &ec->base;
2807
2808 err_udev_monitor:
2809         wl_event_source_remove(ec->udev_drm_source);
2810         udev_monitor_unref(ec->udev_monitor);
2811 err_drm_source:
2812         wl_event_source_remove(ec->drm_source);
2813         udev_input_destroy(&ec->input);
2814 err_sprite:
2815         ec->base.renderer->destroy(&ec->base);
2816         gbm_device_destroy(ec->gbm);
2817         destroy_sprites(ec);
2818 err_udev_dev:
2819         udev_device_unref(drm_device);
2820 err_launcher:
2821         weston_launcher_destroy(ec->base.launcher);
2822 err_udev:
2823         udev_unref(ec->udev);
2824 err_compositor:
2825         weston_compositor_shutdown(&ec->base);
2826 err_base:
2827         free(ec);
2828         return NULL;
2829 }
2830
2831 WL_EXPORT struct weston_compositor *
2832 backend_init(struct wl_display *display, int *argc, char *argv[],
2833              struct weston_config *config)
2834 {
2835         struct drm_parameters param = { 0, };
2836
2837         const struct weston_option drm_options[] = {
2838                 { WESTON_OPTION_INTEGER, "connector", 0, &param.connector },
2839                 { WESTON_OPTION_STRING, "seat", 0, &param.seat_id },
2840                 { WESTON_OPTION_INTEGER, "tty", 0, &param.tty },
2841                 { WESTON_OPTION_BOOLEAN, "current-mode", 0, &option_current_mode },
2842                 { WESTON_OPTION_BOOLEAN, "use-pixman", 0, &param.use_pixman },
2843         };
2844
2845         param.seat_id = default_seat;
2846
2847         parse_options(drm_options, ARRAY_LENGTH(drm_options), argc, argv);
2848
2849         return drm_compositor_create(display, &param, argc, argv, config);
2850 }