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