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