837da8cee6a6fc0f5f855f61eea8da7743107500
[profile/ivi/weston-ivi-shell.git] / src / compositor-drm.c
1 /*
2  * Copyright © 2008-2011 Kristian Høgsberg
3  * Copyright © 2011 Intel Corporation
4  *
5  * Permission to use, copy, modify, distribute, and sell this software and
6  * its documentation for any purpose is hereby granted without fee, provided
7  * that the above copyright notice appear in all copies and that both that
8  * copyright notice and this permission notice appear in supporting
9  * documentation, and that the name of the copyright holders not be used in
10  * advertising or publicity pertaining to distribution of the software
11  * without specific, written prior permission.  The copyright holders make
12  * no representations about the suitability of this software for any
13  * purpose.  It is provided "as is" without express or implied warranty.
14  *
15  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
16  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
17  * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
18  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
19  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
20  * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
21  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22  */
23
24 #define _GNU_SOURCE
25
26 #include <errno.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <fcntl.h>
31 #include <unistd.h>
32 #include <linux/input.h>
33
34 #include <xf86drm.h>
35 #include <xf86drmMode.h>
36 #include <drm_fourcc.h>
37
38 #include <gbm.h>
39 #include <libbacklight.h>
40
41 #include "compositor.h"
42 #include "evdev.h"
43 #include "launcher-util.h"
44
45 struct drm_compositor {
46         struct weston_compositor base;
47
48         struct udev *udev;
49         struct wl_event_source *drm_source;
50
51         struct udev_monitor *udev_monitor;
52         struct wl_event_source *udev_drm_source;
53
54         struct {
55                 int id;
56                 int fd;
57         } drm;
58         struct gbm_device *gbm;
59         uint32_t *crtcs;
60         int num_crtcs;
61         uint32_t crtc_allocator;
62         uint32_t connector_allocator;
63         struct tty *tty;
64
65         struct gbm_surface *dummy_surface;
66         EGLSurface dummy_egl_surface;
67
68         struct wl_list sprite_list;
69         int sprites_are_broken;
70
71         uint32_t prev_state;
72 };
73
74 struct drm_mode {
75         struct weston_mode base;
76         drmModeModeInfo mode_info;
77 };
78
79 struct drm_output {
80         struct weston_output   base;
81
82         uint32_t crtc_id;
83         uint32_t connector_id;
84         drmModeCrtcPtr original_crtc;
85
86         struct gbm_surface *surface;
87         EGLSurface egl_surface;
88         uint32_t current_fb_id;
89         uint32_t next_fb_id;
90         struct gbm_bo *current_bo;
91         struct gbm_bo *next_bo;
92
93         struct wl_buffer *scanout_buffer;
94         struct wl_listener scanout_buffer_destroy_listener;
95         struct wl_buffer *pending_scanout_buffer;
96         struct wl_listener pending_scanout_buffer_destroy_listener;
97         struct backlight *backlight;
98 };
99
100 /*
101  * An output has a primary display plane plus zero or more sprites for
102  * blending display contents.
103  */
104 struct drm_sprite {
105         struct wl_list link;
106
107         uint32_t fb_id;
108         uint32_t pending_fb_id;
109         struct weston_surface *surface;
110         struct weston_surface *pending_surface;
111
112         struct drm_compositor *compositor;
113
114         struct wl_listener destroy_listener;
115         struct wl_listener pending_destroy_listener;
116
117         uint32_t possible_crtcs;
118         uint32_t plane_id;
119         uint32_t count_formats;
120
121         int32_t src_x, src_y;
122         uint32_t src_w, src_h;
123         uint32_t dest_x, dest_y;
124         uint32_t dest_w, dest_h;
125
126         uint32_t formats[];
127 };
128
129 static int
130 surface_is_primary(struct weston_compositor *ec, struct weston_surface *es)
131 {
132         struct weston_surface *primary;
133
134         primary = container_of(ec->surface_list.next, struct weston_surface,
135                                link);
136         if (es == primary)
137                 return -1;
138         return 0;
139 }
140
141 static int
142 drm_sprite_crtc_supported(struct weston_output *output_base, uint32_t supported)
143 {
144         struct weston_compositor *ec = output_base->compositor;
145         struct drm_compositor *c =(struct drm_compositor *) ec;
146         struct drm_output *output = (struct drm_output *) output_base;
147         int crtc;
148
149         for (crtc = 0; crtc < c->num_crtcs; crtc++) {
150                 if (c->crtcs[crtc] != output->crtc_id)
151                         continue;
152
153                 if (supported & (1 << crtc))
154                         return -1;
155         }
156
157         return 0;
158 }
159
160 static int
161 drm_output_prepare_scanout_surface(struct drm_output *output)
162 {
163         struct drm_compositor *c =
164                 (struct drm_compositor *) output->base.compositor;
165         struct weston_surface *es;
166
167         es = container_of(c->base.surface_list.next,
168                           struct weston_surface, link);
169
170         /* Need to verify output->region contained in surface opaque
171          * region.  Or maybe just that format doesn't have alpha. */
172         return -1;
173
174         if (es->geometry.x != output->base.x ||
175             es->geometry.y != output->base.y ||
176             es->geometry.width != output->base.current->width ||
177             es->geometry.height != output->base.current->height ||
178             es->transform.enabled ||
179             es->image == EGL_NO_IMAGE_KHR)
180                 return -1;
181
182         output->next_bo =
183                 gbm_bo_create_from_egl_image(c->gbm,
184                                              c->base.display, es->image,
185                                              es->geometry.width,
186                                              es->geometry.height,
187                                              GBM_BO_USE_SCANOUT);
188
189         /* assert output->pending_scanout_buffer == NULL */
190         output->pending_scanout_buffer = es->buffer;
191         output->pending_scanout_buffer->busy_count++;
192
193         wl_signal_add(&output->pending_scanout_buffer->resource.destroy_signal,
194                       &output->pending_scanout_buffer_destroy_listener);
195
196         pixman_region32_fini(&es->damage);
197         pixman_region32_init(&es->damage);
198
199         return 0;
200 }
201
202 static void
203 drm_output_render(struct drm_output *output, pixman_region32_t *damage)
204 {
205         struct drm_compositor *compositor =
206                 (struct drm_compositor *) output->base.compositor;
207         struct weston_surface *surface;
208
209         if (!eglMakeCurrent(compositor->base.display, output->egl_surface,
210                             output->egl_surface, compositor->base.context)) {
211                 fprintf(stderr, "failed to make current\n");
212                 return;
213         }
214
215         wl_list_for_each_reverse(surface, &compositor->base.surface_list, link)
216                 weston_surface_draw(surface, &output->base, damage);
217
218         eglSwapBuffers(compositor->base.display, output->egl_surface);
219         output->next_bo = gbm_surface_lock_front_buffer(output->surface);
220         if (!output->next_bo) {
221                 fprintf(stderr, "failed to lock front buffer: %m\n");
222                 return;
223         }
224 }
225
226 static void
227 drm_output_repaint(struct weston_output *output_base,
228                    pixman_region32_t *damage)
229 {
230         struct drm_output *output = (struct drm_output *) output_base;
231         struct drm_compositor *compositor =
232                 (struct drm_compositor *) output->base.compositor;
233         struct drm_sprite *s;
234         struct drm_mode *mode;
235         uint32_t stride, handle;
236         int ret = 0;
237
238         drm_output_prepare_scanout_surface(output);
239         if (!output->next_bo)
240                 drm_output_render(output, damage);
241
242         stride = gbm_bo_get_pitch(output->next_bo);
243         handle = gbm_bo_get_handle(output->next_bo).u32;
244
245         /* Destroy and set to NULL now so we don't try to
246          * gbm_surface_release_buffer() a client buffer in the
247          * page_flip_handler. */
248         if (output->pending_scanout_buffer) {
249                 gbm_bo_destroy(output->next_bo);
250                 output->next_bo = NULL;
251         }
252
253         ret = drmModeAddFB(compositor->drm.fd,
254                            output->base.current->width,
255                            output->base.current->height,
256                            24, 32, stride, handle, &output->next_fb_id);
257         if (ret) {
258                 fprintf(stderr, "failed to create kms fb: %m\n");
259                 gbm_surface_release_buffer(output->surface, output->next_bo);
260                 output->next_bo = NULL;
261                 return;
262         }
263
264         mode = container_of(output->base.current, struct drm_mode, base);
265         if (output->current_fb_id == 0) {
266                 ret = drmModeSetCrtc(compositor->drm.fd, output->crtc_id,
267                                      output->next_fb_id, 0, 0,
268                                      &output->connector_id, 1,
269                                      &mode->mode_info);
270                 if (ret) {
271                         fprintf(stderr, "set mode failed: %m\n");
272                         return;
273                 }
274         }
275
276         if (drmModePageFlip(compositor->drm.fd, output->crtc_id,
277                             output->next_fb_id,
278                             DRM_MODE_PAGE_FLIP_EVENT, output) < 0) {
279                 fprintf(stderr, "queueing pageflip failed: %m\n");
280                 return;
281         }
282
283         /*
284          * Now, update all the sprite surfaces
285          */
286         wl_list_for_each(s, &compositor->sprite_list, link) {
287                 uint32_t flags = 0;
288                 drmVBlank vbl = {
289                         .request.type = DRM_VBLANK_RELATIVE | DRM_VBLANK_EVENT,
290                         .request.sequence = 1,
291                 };
292
293                 if (!drm_sprite_crtc_supported(output_base, s->possible_crtcs))
294                         continue;
295
296                 ret = drmModeSetPlane(compositor->drm.fd, s->plane_id,
297                                       output->crtc_id, s->pending_fb_id, flags,
298                                       s->dest_x, s->dest_y,
299                                       s->dest_w, s->dest_h,
300                                       s->src_x, s->src_y,
301                                       s->src_w, s->src_h);
302                 if (ret)
303                         fprintf(stderr, "setplane failed: %d: %s\n",
304                                 ret, strerror(errno));
305
306                 /*
307                  * Queue a vblank signal so we know when the surface
308                  * becomes active on the display or has been replaced.
309                  */
310                 vbl.request.signal = (unsigned long)s;
311                 ret = drmWaitVBlank(compositor->drm.fd, &vbl);
312                 if (ret) {
313                         fprintf(stderr, "vblank event request failed: %d: %s\n",
314                                 ret, strerror(errno));
315                 }
316         }
317
318         return;
319 }
320
321 static void
322 vblank_handler(int fd, unsigned int frame, unsigned int sec, unsigned int usec,
323                void *data)
324 {
325         struct drm_sprite *s = (struct drm_sprite *)data;
326         struct drm_compositor *c = s->compositor;
327
328         if (s->surface) {
329                 weston_buffer_post_release(s->surface->buffer);
330                 wl_list_remove(&s->destroy_listener.link);
331                 s->surface = NULL;
332                 drmModeRmFB(c->drm.fd, s->fb_id);
333                 s->fb_id = 0;
334         }
335
336         if (s->pending_surface) {
337                 wl_list_remove(&s->pending_destroy_listener.link);
338                 wl_signal_add(&s->pending_surface->buffer->resource.destroy_signal,
339                               &s->destroy_listener);
340                 s->surface = s->pending_surface;
341                 s->pending_surface = NULL;
342                 s->fb_id = s->pending_fb_id;
343                 s->pending_fb_id = 0;
344         }
345 }
346
347 static void
348 page_flip_handler(int fd, unsigned int frame,
349                   unsigned int sec, unsigned int usec, void *data)
350 {
351         struct drm_output *output = (struct drm_output *) data;
352         struct drm_compositor *c =
353                 (struct drm_compositor *) output->base.compositor;
354         uint32_t msecs;
355
356         if (output->current_fb_id)
357                 drmModeRmFB(c->drm.fd, output->current_fb_id);
358         output->current_fb_id = output->next_fb_id;
359         output->next_fb_id = 0;
360
361         if (output->scanout_buffer) {
362                 weston_buffer_post_release(output->scanout_buffer);
363                 wl_list_remove(&output->scanout_buffer_destroy_listener.link);
364                 output->scanout_buffer = NULL;
365         } else if (output->current_bo) {
366                 gbm_surface_release_buffer(output->surface,
367                                            output->current_bo);
368         }
369
370         output->current_bo = output->next_bo;
371         output->next_bo = NULL;
372
373         if (output->pending_scanout_buffer) {
374                 output->scanout_buffer = output->pending_scanout_buffer;
375                 wl_list_remove(&output->pending_scanout_buffer_destroy_listener.link);
376                 wl_signal_add(&output->scanout_buffer->resource.destroy_signal,
377                               &output->scanout_buffer_destroy_listener);
378                 output->pending_scanout_buffer = NULL;
379         }
380         msecs = sec * 1000 + usec / 1000;
381         weston_output_finish_frame(&output->base, msecs);
382 }
383
384 static int
385 drm_surface_format_supported(struct drm_sprite *s, uint32_t format)
386 {
387         uint32_t i;
388
389         for (i = 0; i < s->count_formats; i++)
390                 if (s->formats[i] == format)
391                         return 1;
392
393         return 0;
394 }
395
396 static int
397 drm_surface_transform_supported(struct weston_surface *es)
398 {
399         if (es->transform.enabled)
400                 return 0;
401
402         return 1;
403 }
404
405 static int
406 drm_surface_overlap_supported(struct weston_output *output_base,
407                               pixman_region32_t *overlap)
408 {
409         /* We could potentially use a color key here if the surface left
410          * to display has rectangular regions
411          */
412         if (pixman_region32_not_empty(overlap))
413                 return 0;
414         return 1;
415 }
416
417 static void
418 drm_disable_unused_sprites(struct weston_output *output_base)
419 {
420         struct weston_compositor *ec = output_base->compositor;
421         struct drm_compositor *c =(struct drm_compositor *) ec;
422         struct drm_output *output = (struct drm_output *) output_base;
423         struct drm_sprite *s;
424         int ret;
425
426         wl_list_for_each(s, &c->sprite_list, link) {
427                 if (s->pending_fb_id)
428                         continue;
429
430                 ret = drmModeSetPlane(c->drm.fd, s->plane_id,
431                                       output->crtc_id, 0, 0,
432                                       0, 0, 0, 0, 0, 0, 0, 0);
433                 if (ret)
434                         fprintf(stderr,
435                                 "failed to disable plane: %d: %s\n",
436                                 ret, strerror(errno));
437                 drmModeRmFB(c->drm.fd, s->fb_id);
438                 s->surface = NULL;
439                 s->pending_surface = NULL;
440                 s->fb_id = 0;
441                 s->pending_fb_id = 0;
442         }
443 }
444
445 /*
446  * This function must take care to damage any previously assigned surface
447  * if the sprite ends up binding to a different surface than in the
448  * previous frame.
449  */
450 static int
451 drm_output_prepare_overlay_surface(struct weston_output *output_base,
452                                    struct weston_surface *es,
453                                    pixman_region32_t *overlap)
454 {
455         struct weston_compositor *ec = output_base->compositor;
456         struct drm_compositor *c =(struct drm_compositor *) ec;
457         struct drm_sprite *s;
458         int found = 0;
459         EGLint handle, stride;
460         struct gbm_bo *bo;
461         uint32_t fb_id = 0;
462         uint32_t handles[4], pitches[4], offsets[4];
463         int ret = 0;
464         pixman_region32_t dest_rect, src_rect;
465         pixman_box32_t *box;
466         uint32_t format;
467
468         if (c->sprites_are_broken)
469                 return -1;
470
471         if (surface_is_primary(ec, es))
472                 return -1;
473
474         if (es->image == EGL_NO_IMAGE_KHR)
475                 return -1;
476
477         if (!drm_surface_transform_supported(es))
478                 return -1;
479
480         if (!drm_surface_overlap_supported(output_base, overlap))
481                 return -1;
482
483         wl_list_for_each(s, &c->sprite_list, link) {
484                 if (!drm_sprite_crtc_supported(output_base, s->possible_crtcs))
485                         continue;
486
487                 if (!s->pending_fb_id) {
488                         found = 1;
489                         break;
490                 }
491         }
492
493         /* No sprites available */
494         if (!found)
495                 return -1;
496
497         bo = gbm_bo_create_from_egl_image(c->gbm, c->base.display, es->image,
498                                           es->geometry.width, es->geometry.height,
499                                           GBM_BO_USE_SCANOUT);
500         format = gbm_bo_get_format(bo);
501         handle = gbm_bo_get_handle(bo).s32;
502         stride = gbm_bo_get_pitch(bo);
503
504         gbm_bo_destroy(bo);
505
506         if (!drm_surface_format_supported(s, format))
507                 return -1;
508
509         if (!handle)
510                 return -1;
511
512         handles[0] = handle;
513         pitches[0] = stride;
514         offsets[0] = 0;
515
516         ret = drmModeAddFB2(c->drm.fd, es->geometry.width, es->geometry.height,
517                             format, handles, pitches, offsets,
518                             &fb_id, 0);
519         if (ret) {
520                 fprintf(stderr, "addfb2 failed: %d\n", ret);
521                 c->sprites_are_broken = 1;
522                 return -1;
523         }
524
525         if (s->surface && s->surface != es) {
526                 struct weston_surface *old_surf = s->surface;
527                 pixman_region32_fini(&old_surf->damage);
528                 pixman_region32_init_rect(&old_surf->damage,
529                                           old_surf->geometry.x, old_surf->geometry.y,
530                                           old_surf->geometry.width, old_surf->geometry.height);
531         }
532
533         s->pending_fb_id = fb_id;
534         s->pending_surface = es;
535         es->buffer->busy_count++;
536
537         /*
538          * Calculate the source & dest rects properly based on actual
539          * postion (note the caller has called weston_surface_update_transform()
540          * for us already).
541          */
542         pixman_region32_init(&dest_rect);
543         pixman_region32_intersect(&dest_rect, &es->transform.boundingbox,
544                                   &output_base->region);
545         pixman_region32_translate(&dest_rect, -output_base->x, -output_base->y);
546         box = pixman_region32_extents(&dest_rect);
547         s->dest_x = box->x1;
548         s->dest_y = box->y1;
549         s->dest_w = box->x2 - box->x1;
550         s->dest_h = box->y2 - box->y1;
551         pixman_region32_fini(&dest_rect);
552
553         pixman_region32_init(&src_rect);
554         pixman_region32_intersect(&src_rect, &es->transform.boundingbox,
555                                   &output_base->region);
556         pixman_region32_translate(&src_rect, -es->geometry.x, -es->geometry.y);
557         box = pixman_region32_extents(&src_rect);
558         s->src_x = box->x1 << 16;
559         s->src_y = box->y1 << 16;
560         s->src_w = (box->x2 - box->x1) << 16;
561         s->src_h = (box->y2 - box->y1) << 16;
562         pixman_region32_fini(&src_rect);
563
564         wl_signal_add(&es->buffer->resource.destroy_signal,
565                       &s->pending_destroy_listener);
566         return 0;
567 }
568
569 static int
570 drm_output_set_cursor(struct weston_output *output_base,
571                       struct weston_input_device *eid);
572
573 static void
574 weston_output_set_cursor(struct weston_output *output,
575                          struct weston_input_device *device,
576                          pixman_region32_t *overlap)
577 {
578         pixman_region32_t cursor_region;
579         int prior_was_hardware;
580
581         if (device->sprite == NULL)
582                 return;
583
584         pixman_region32_init(&cursor_region);
585         pixman_region32_intersect(&cursor_region,
586                                   &device->sprite->transform.boundingbox,
587                                   &output->region);
588
589         if (!pixman_region32_not_empty(&cursor_region)) {
590                 drm_output_set_cursor(output, NULL);
591                 goto out;
592         }
593
594         prior_was_hardware = device->hw_cursor;
595         if (pixman_region32_not_empty(overlap) ||
596             drm_output_set_cursor(output, device) < 0) {
597                 if (prior_was_hardware) {
598                         weston_surface_damage(device->sprite);
599                         drm_output_set_cursor(output, NULL);
600                 }
601                 device->hw_cursor = 0;
602         } else {
603                 if (!prior_was_hardware)
604                         weston_surface_damage_below(device->sprite);
605                 pixman_region32_fini(&device->sprite->damage);
606                 pixman_region32_init(&device->sprite->damage);
607                 device->hw_cursor = 1;
608         }
609
610 out:
611         pixman_region32_fini(&cursor_region);
612 }
613
614 static void
615 drm_assign_planes(struct weston_output *output)
616 {
617         struct weston_compositor *ec = output->compositor;
618         struct weston_surface *es;
619         pixman_region32_t overlap, surface_overlap;
620         struct weston_input_device *device;
621
622         /*
623          * Find a surface for each sprite in the output using some heuristics:
624          * 1) size
625          * 2) frequency of update
626          * 3) opacity (though some hw might support alpha blending)
627          * 4) clipping (this can be fixed with color keys)
628          *
629          * The idea is to save on blitting since this should save power.
630          * If we can get a large video surface on the sprite for example,
631          * the main display surface may not need to update at all, and
632          * the client buffer can be used directly for the sprite surface
633          * as we do for flipping full screen surfaces.
634          */
635         pixman_region32_init(&overlap);
636         wl_list_for_each(es, &ec->surface_list, link) {
637                 /*
638                  * FIXME: try to assign hw cursors here too, they're just
639                  * special overlays
640                  */
641                 pixman_region32_init(&surface_overlap);
642                 pixman_region32_intersect(&surface_overlap, &overlap,
643                                           &es->transform.boundingbox);
644
645                 device = (struct weston_input_device *) ec->input_device;
646                 if (es == device->sprite) {
647                         weston_output_set_cursor(output, device,
648                                                  &surface_overlap);
649
650                         if (!device->hw_cursor)
651                                 pixman_region32_union(&overlap, &overlap,
652                                                       &es->transform.boundingbox);
653                 } else if (!drm_output_prepare_overlay_surface(output, es,
654                                                                &surface_overlap)) {
655                         pixman_region32_fini(&es->damage);
656                         pixman_region32_init(&es->damage);
657                 } else {
658                         pixman_region32_union(&overlap, &overlap,
659                                               &es->transform.boundingbox);
660                 }
661                 pixman_region32_fini(&surface_overlap);
662         }
663         pixman_region32_fini(&overlap);
664
665         drm_disable_unused_sprites(output);
666 }
667
668 static int
669 drm_output_set_cursor(struct weston_output *output_base,
670                       struct weston_input_device *eid)
671 {
672         struct drm_output *output = (struct drm_output *) output_base;
673         struct drm_compositor *c =
674                 (struct drm_compositor *) output->base.compositor;
675         EGLint handle, stride;
676         int ret = -1;
677         struct gbm_bo *bo;
678
679         if (eid == NULL) {
680                 drmModeSetCursor(c->drm.fd, output->crtc_id, 0, 0, 0);
681                 return 0;
682         }
683
684         if (eid->sprite->image == EGL_NO_IMAGE_KHR)
685                 goto out;
686
687         if (eid->sprite->geometry.width > 64 ||
688             eid->sprite->geometry.height > 64)
689                 goto out;
690
691         bo = gbm_bo_create_from_egl_image(c->gbm,
692                                           c->base.display,
693                                           eid->sprite->image, 64, 64,
694                                           GBM_BO_USE_CURSOR_64X64);
695         /* Not suitable for hw cursor, fall back */
696         if (bo == NULL)
697                 goto out;
698
699         handle = gbm_bo_get_handle(bo).s32;
700         stride = gbm_bo_get_pitch(bo);
701         gbm_bo_destroy(bo);
702
703         /* gbm_bo_create_from_egl_image() didn't always validate the usage
704          * flags, and in that case we might end up with a bad stride. */
705         if (stride != 64 * 4)
706                 goto out;
707
708         ret = drmModeSetCursor(c->drm.fd, output->crtc_id, handle, 64, 64);
709         if (ret) {
710                 fprintf(stderr, "failed to set cursor: %s\n", strerror(-ret));
711                 goto out;
712         }
713
714         ret = drmModeMoveCursor(c->drm.fd, output->crtc_id,
715                                 eid->sprite->geometry.x - output->base.x,
716                                 eid->sprite->geometry.y - output->base.y);
717         if (ret) {
718                 fprintf(stderr, "failed to move cursor: %s\n", strerror(-ret));
719                 goto out;
720         }
721
722 out:
723         if (ret)
724                 drmModeSetCursor(c->drm.fd, output->crtc_id, 0, 0, 0);
725         return ret;
726 }
727
728 static void
729 drm_output_destroy(struct weston_output *output_base)
730 {
731         struct drm_output *output = (struct drm_output *) output_base;
732         struct drm_compositor *c =
733                 (struct drm_compositor *) output->base.compositor;
734         drmModeCrtcPtr origcrtc = output->original_crtc;
735
736         if (output->backlight)
737                 backlight_destroy(output->backlight);
738
739         /* Turn off hardware cursor */
740         drm_output_set_cursor(&output->base, NULL);
741
742         /* Restore original CRTC state */
743         drmModeSetCrtc(c->drm.fd, origcrtc->crtc_id, origcrtc->buffer_id,
744                        origcrtc->x, origcrtc->y,
745                        &output->connector_id, 1, &origcrtc->mode);
746         drmModeFreeCrtc(origcrtc);
747
748         c->crtc_allocator &= ~(1 << output->crtc_id);
749         c->connector_allocator &= ~(1 << output->connector_id);
750
751         eglDestroySurface(c->base.display, output->egl_surface);
752         gbm_surface_destroy(output->surface);
753
754         weston_output_destroy(&output->base);
755         wl_list_remove(&output->base.link);
756
757         free(output);
758 }
759
760 static struct drm_mode *
761 choose_mode (struct drm_output *output, struct weston_mode *target_mode)
762 {
763         struct drm_mode *tmp_mode = NULL, *mode;
764
765         if (output->base.current->width == target_mode->width && 
766             output->base.current->height == target_mode->height &&
767             (output->base.current->refresh == target_mode->refresh ||
768              target_mode->refresh == 0))
769                 return (struct drm_mode *)output->base.current;
770
771         wl_list_for_each(mode, &output->base.mode_list, base.link) {
772                 if (mode->mode_info.hdisplay == target_mode->width &&
773                     mode->mode_info.vdisplay == target_mode->height) {
774                         if (mode->mode_info.vrefresh == target_mode->refresh || 
775                             target_mode->refresh == 0) {
776                                 return mode;
777                         } else if (!tmp_mode) 
778                                 tmp_mode = mode;
779                 }
780         }
781
782         return tmp_mode;
783 }
784
785 static int
786 drm_output_switch_mode(struct weston_output *output_base, struct weston_mode *mode)
787 {
788         struct drm_output *output;
789         struct drm_mode *drm_mode;
790         int ret;
791         struct drm_compositor *ec;
792         struct gbm_surface *surface;
793         EGLSurface egl_surface;
794
795         if (output_base == NULL) {
796                 fprintf(stderr, "output is NULL.\n");
797                 return -1;
798         }
799
800         if (mode == NULL) {
801                 fprintf(stderr, "mode is NULL.\n");
802                 return -1;
803         }
804
805         ec = (struct drm_compositor *)output_base->compositor;
806         output = (struct drm_output *)output_base;
807         drm_mode  = choose_mode (output, mode);
808
809         if (!drm_mode) {
810                 printf("%s, invalid resolution:%dx%d\n", __func__, mode->width, mode->height);
811                 return -1;
812         } else if (&drm_mode->base == output->base.current) {
813                 return 0;
814         } else if (drm_mode->base.width == output->base.current->width &&
815                    drm_mode->base.height == output->base.current->height) {
816                 /* only change refresh value */
817                 ret = drmModeSetCrtc(ec->drm.fd,
818                                      output->crtc_id,
819                                      output->current_fb_id, 0, 0,
820                                      &output->connector_id, 1, &drm_mode->mode_info);
821
822                 if (ret) {
823                         fprintf(stderr, "failed to set mode (%dx%d) %u Hz\n",
824                                 drm_mode->base.width,
825                                 drm_mode->base.height,
826                                 drm_mode->base.refresh);
827                         ret = -1;
828                 } else {
829                         output->base.current->flags = 0;
830                         output->base.current = &drm_mode->base;
831                         drm_mode->base.flags = 
832                                 WL_OUTPUT_MODE_CURRENT | WL_OUTPUT_MODE_PREFERRED;
833                         ret = 0;
834                 }
835
836                 return ret;
837         }
838
839         drm_mode->base.flags =
840                 WL_OUTPUT_MODE_CURRENT | WL_OUTPUT_MODE_PREFERRED;
841
842         surface = gbm_surface_create(ec->gbm,
843                                  drm_mode->base.width,
844                                  drm_mode->base.height,
845                                  GBM_FORMAT_XRGB8888,
846                                  GBM_BO_USE_SCANOUT |
847                                  GBM_BO_USE_RENDERING);
848         if (!surface) {
849                 fprintf(stderr, "failed to create gbm surface\n");
850                 return -1;
851         }
852
853         egl_surface =
854                 eglCreateWindowSurface(ec->base.display,
855                                        ec->base.config,
856                                        surface, NULL);
857
858         if (egl_surface == EGL_NO_SURFACE) {
859                 fprintf(stderr, "failed to create egl surface\n");
860                 goto err;
861         }
862
863         ret = drmModeSetCrtc(ec->drm.fd,
864                              output->crtc_id,
865                              output->current_fb_id, 0, 0,
866                              &output->connector_id, 1, &drm_mode->mode_info);
867         if (ret) {
868                 fprintf(stderr, "failed to set mode\n");
869                 goto err;
870         }
871
872         /* reset rendering stuff. */
873         if (output->current_fb_id)
874                 drmModeRmFB(ec->drm.fd, output->current_fb_id);
875         output->current_fb_id = 0;
876
877         if (output->next_fb_id)
878                 drmModeRmFB(ec->drm.fd, output->next_fb_id);
879         output->next_fb_id = 0;
880
881         if (output->current_bo)
882                 gbm_surface_release_buffer(output->surface,
883                                            output->current_bo);
884                 output->current_bo = NULL;
885
886         if (output->next_bo)
887                 gbm_surface_release_buffer(output->surface,
888                                            output->next_bo);
889         output->next_bo = NULL;
890
891         eglDestroySurface(ec->base.display, output->egl_surface);
892         gbm_surface_destroy(output->surface);
893         output->egl_surface = egl_surface;
894         output->surface = surface;
895
896         /*update output*/
897         output->base.current = &drm_mode->base;
898         output->base.dirty = 1;
899         weston_output_move(&output->base, output->base.x, output->base.y);
900         return 0;
901
902 err:
903         eglDestroySurface(ec->base.display, egl_surface);
904         gbm_surface_destroy(surface);
905         return -1;
906 }
907
908 static int
909 on_drm_input(int fd, uint32_t mask, void *data)
910 {
911         drmEventContext evctx;
912
913         memset(&evctx, 0, sizeof evctx);
914         evctx.version = DRM_EVENT_CONTEXT_VERSION;
915         evctx.page_flip_handler = page_flip_handler;
916         evctx.vblank_handler = vblank_handler;
917         drmHandleEvent(fd, &evctx);
918
919         return 1;
920 }
921
922 static int
923 init_egl(struct drm_compositor *ec, struct udev_device *device)
924 {
925         EGLint major, minor, n;
926         const char *filename, *sysnum;
927         int fd;
928         static const EGLint context_attribs[] = {
929                 EGL_CONTEXT_CLIENT_VERSION, 2,
930                 EGL_NONE
931         };
932
933         sysnum = udev_device_get_sysnum(device);
934         if (sysnum)
935                 ec->drm.id = atoi(sysnum);
936         if (!sysnum || ec->drm.id < 0) {
937                 fprintf(stderr, "cannot get device sysnum\n");
938                 return -1;
939         }
940
941         static const EGLint config_attribs[] = {
942                 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
943                 EGL_RED_SIZE, 1,
944                 EGL_GREEN_SIZE, 1,
945                 EGL_BLUE_SIZE, 1,
946                 EGL_ALPHA_SIZE, 0,
947                 EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
948                 EGL_NONE
949         };
950
951         filename = udev_device_get_devnode(device);
952         fd = open(filename, O_RDWR | O_CLOEXEC);
953         if (fd < 0) {
954                 /* Probably permissions error */
955                 fprintf(stderr, "couldn't open %s, skipping\n",
956                         udev_device_get_devnode(device));
957                 return -1;
958         }
959
960         ec->drm.fd = fd;
961         ec->gbm = gbm_create_device(ec->drm.fd);
962         ec->base.display = eglGetDisplay(ec->gbm);
963         if (ec->base.display == NULL) {
964                 fprintf(stderr, "failed to create display\n");
965                 return -1;
966         }
967
968         if (!eglInitialize(ec->base.display, &major, &minor)) {
969                 fprintf(stderr, "failed to initialize display\n");
970                 return -1;
971         }
972
973         if (!eglBindAPI(EGL_OPENGL_ES_API)) {
974                 fprintf(stderr, "failed to bind api EGL_OPENGL_ES_API\n");
975                 return -1;
976         }
977
978         if (!eglChooseConfig(ec->base.display, config_attribs,
979                              &ec->base.config, 1, &n) || n != 1) {
980                 fprintf(stderr, "failed to choose config: %d\n", n);
981                 return -1;
982         }
983
984         ec->base.context = eglCreateContext(ec->base.display, ec->base.config,
985                                             EGL_NO_CONTEXT, context_attribs);
986         if (ec->base.context == NULL) {
987                 fprintf(stderr, "failed to create context\n");
988                 return -1;
989         }
990
991         ec->dummy_surface = gbm_surface_create(ec->gbm, 10, 10,
992                                                GBM_FORMAT_XRGB8888,
993                                                GBM_BO_USE_RENDERING);
994         if (!ec->dummy_surface) {
995                 fprintf(stderr, "failed to create dummy gbm surface\n");
996                 return -1;
997         }
998
999         ec->dummy_egl_surface =
1000                 eglCreateWindowSurface(ec->base.display, ec->base.config,
1001                                        ec->dummy_surface, NULL);
1002         if (ec->dummy_egl_surface == EGL_NO_SURFACE) {
1003                 fprintf(stderr, "failed to create egl surface\n");
1004                 return -1;
1005         }
1006
1007         if (!eglMakeCurrent(ec->base.display, ec->dummy_egl_surface,
1008                             ec->dummy_egl_surface, ec->base.context)) {
1009                 fprintf(stderr, "failed to make context current\n");
1010                 return -1;
1011         }
1012
1013         return 0;
1014 }
1015
1016 static drmModeModeInfo builtin_1024x768 = {
1017         63500,                  /* clock */
1018         1024, 1072, 1176, 1328, 0,
1019         768, 771, 775, 798, 0,
1020         59920,
1021         DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC,
1022         0,
1023         "1024x768"
1024 };
1025
1026
1027 static int
1028 drm_output_add_mode(struct drm_output *output, drmModeModeInfo *info)
1029 {
1030         struct drm_mode *mode;
1031
1032         mode = malloc(sizeof *mode);
1033         if (mode == NULL)
1034                 return -1;
1035
1036         mode->base.flags = 0;
1037         mode->base.width = info->hdisplay;
1038         mode->base.height = info->vdisplay;
1039         mode->base.refresh = info->vrefresh;
1040         mode->mode_info = *info;
1041         wl_list_insert(output->base.mode_list.prev, &mode->base.link);
1042
1043         return 0;
1044 }
1045
1046 static int
1047 drm_subpixel_to_wayland(int drm_value)
1048 {
1049         switch (drm_value) {
1050         default:
1051         case DRM_MODE_SUBPIXEL_UNKNOWN:
1052                 return WL_OUTPUT_SUBPIXEL_UNKNOWN;
1053         case DRM_MODE_SUBPIXEL_NONE:
1054                 return WL_OUTPUT_SUBPIXEL_NONE;
1055         case DRM_MODE_SUBPIXEL_HORIZONTAL_RGB:
1056                 return WL_OUTPUT_SUBPIXEL_HORIZONTAL_RGB;
1057         case DRM_MODE_SUBPIXEL_HORIZONTAL_BGR:
1058                 return WL_OUTPUT_SUBPIXEL_HORIZONTAL_BGR;
1059         case DRM_MODE_SUBPIXEL_VERTICAL_RGB:
1060                 return WL_OUTPUT_SUBPIXEL_VERTICAL_RGB;
1061         case DRM_MODE_SUBPIXEL_VERTICAL_BGR:
1062                 return WL_OUTPUT_SUBPIXEL_VERTICAL_BGR;
1063         }
1064 }
1065
1066 static void
1067 output_handle_scanout_buffer_destroy(struct wl_listener *listener, void *data)
1068 {
1069         struct drm_output *output =
1070                 container_of(listener, struct drm_output,
1071                              scanout_buffer_destroy_listener);
1072
1073         output->scanout_buffer = NULL;
1074
1075         if (!output->pending_scanout_buffer)
1076                 weston_compositor_schedule_repaint(output->base.compositor);
1077 }
1078
1079 static void
1080 output_handle_pending_scanout_buffer_destroy(struct wl_listener *listener,
1081                                              void *data)
1082 {
1083         struct drm_output *output =
1084                 container_of(listener, struct drm_output,
1085                              pending_scanout_buffer_destroy_listener);
1086
1087         output->pending_scanout_buffer = NULL;
1088
1089         weston_compositor_schedule_repaint(output->base.compositor);
1090 }
1091
1092 static void
1093 sprite_handle_buffer_destroy(struct wl_listener *listener, void *data)
1094 {
1095         struct drm_sprite *sprite =
1096                 container_of(listener, struct drm_sprite,
1097                              destroy_listener);
1098
1099         sprite->surface = NULL;
1100 }
1101
1102 static void
1103 sprite_handle_pending_buffer_destroy(struct wl_listener *listener, void *data)
1104 {
1105         struct drm_sprite *sprite =
1106                 container_of(listener, struct drm_sprite,
1107                              pending_destroy_listener);
1108
1109         sprite->pending_surface = NULL;
1110 }
1111
1112 /* returns a value between 0-255 range, where higher is brighter */
1113 static uint32_t
1114 drm_get_backlight(struct drm_output *output)
1115 {
1116         long brightness, max_brightness, norm;
1117
1118         brightness = backlight_get_brightness(output->backlight);
1119         max_brightness = backlight_get_max_brightness(output->backlight);
1120
1121         /* convert it on a scale of 0 to 255 */
1122         norm = (brightness * 255)/(max_brightness);
1123
1124         return (uint32_t) norm;
1125 }
1126
1127 /* values accepted are between 0-255 range */
1128 static void
1129 drm_set_backlight(struct weston_output *output_base, uint32_t value)
1130 {
1131         struct drm_output *output = (struct drm_output *) output_base;
1132         long max_brightness, new_brightness;
1133
1134         if (!output->backlight)
1135                 return;
1136
1137         if (value > 255)
1138                 return;
1139
1140         max_brightness = backlight_get_max_brightness(output->backlight);
1141
1142         /* get denormalized value */
1143         new_brightness = (value * max_brightness) / 255;
1144
1145         backlight_set_brightness(output->backlight, new_brightness);
1146 }
1147
1148 static drmModePropertyPtr
1149 drm_get_prop(int fd, drmModeConnectorPtr connector, const char *name)
1150 {
1151         drmModePropertyPtr props;
1152         int i;
1153
1154         for (i = 0; i < connector->count_props; i++) {
1155                 props = drmModeGetProperty(fd, connector->props[i]);
1156                 if (!props)
1157                         continue;
1158
1159                 if (!strcmp(props->name, name))
1160                         return props;
1161
1162                 drmModeFreeProperty(props);
1163         }
1164
1165         return NULL;
1166 }
1167
1168 static void
1169 drm_set_dpms(struct weston_output *output_base, enum dpms_enum level)
1170 {
1171         struct drm_output *output = (struct drm_output *) output_base;
1172         struct weston_compositor *ec = output_base->compositor;
1173         struct drm_compositor *c = (struct drm_compositor *) ec;
1174         drmModeConnectorPtr connector;
1175         drmModePropertyPtr prop;
1176
1177         connector = drmModeGetConnector(c->drm.fd, output->connector_id);
1178         if (!connector)
1179                 return;
1180
1181         prop = drm_get_prop(c->drm.fd, connector, "DPMS");
1182         if (!prop) {
1183                 drmModeFreeConnector(connector);
1184                 return;
1185         }
1186
1187         drmModeConnectorSetProperty(c->drm.fd, connector->connector_id,
1188                                     prop->prop_id, level);
1189         drmModeFreeProperty(prop);
1190         drmModeFreeConnector(connector);
1191 }
1192
1193 static void
1194 drm_output_read_pixels(struct weston_output *output_base, void *data)
1195 {
1196         struct drm_output *output = (struct drm_output *) output_base;
1197         struct drm_compositor *compositor =
1198                 (struct drm_compositor *) output->base.compositor;
1199
1200         eglMakeCurrent(compositor->base.display, output->egl_surface,
1201                         output->egl_surface, compositor->base.context);
1202
1203         glReadPixels(0, 0, output_base->current->width,
1204                      output_base->current->height,
1205                      compositor->base.read_format, GL_UNSIGNED_BYTE, data);
1206 }
1207
1208 static int
1209 create_output_for_connector(struct drm_compositor *ec,
1210                             drmModeRes *resources,
1211                             drmModeConnector *connector,
1212                             int x, int y, struct udev_device *drm_device)
1213 {
1214         struct drm_output *output;
1215         struct drm_mode *drm_mode, *next;
1216         drmModeEncoder *encoder;
1217         int i, ret;
1218
1219         encoder = drmModeGetEncoder(ec->drm.fd, connector->encoders[0]);
1220         if (encoder == NULL) {
1221                 fprintf(stderr, "No encoder for connector.\n");
1222                 return -1;
1223         }
1224
1225         for (i = 0; i < resources->count_crtcs; i++) {
1226                 if (encoder->possible_crtcs & (1 << i) &&
1227                     !(ec->crtc_allocator & (1 << resources->crtcs[i])))
1228                         break;
1229         }
1230         if (i == resources->count_crtcs) {
1231                 fprintf(stderr, "No usable crtc for encoder.\n");
1232                 drmModeFreeEncoder(encoder);
1233                 return -1;
1234         }
1235
1236         output = malloc(sizeof *output);
1237         if (output == NULL) {
1238                 drmModeFreeEncoder(encoder);
1239                 return -1;
1240         }
1241
1242         memset(output, 0, sizeof *output);
1243         output->base.subpixel = drm_subpixel_to_wayland(connector->subpixel);
1244         output->base.make = "unknown";
1245         output->base.model = "unknown";
1246         wl_list_init(&output->base.mode_list);
1247
1248         output->crtc_id = resources->crtcs[i];
1249         ec->crtc_allocator |= (1 << output->crtc_id);
1250         output->connector_id = connector->connector_id;
1251         ec->connector_allocator |= (1 << output->connector_id);
1252
1253         output->original_crtc = drmModeGetCrtc(ec->drm.fd, output->crtc_id);
1254         drmModeFreeEncoder(encoder);
1255
1256         for (i = 0; i < connector->count_modes; i++) {
1257                 ret = drm_output_add_mode(output, &connector->modes[i]);
1258                 if (ret)
1259                         goto err_free;
1260         }
1261
1262         if (connector->count_modes == 0) {
1263                 ret = drm_output_add_mode(output, &builtin_1024x768);
1264                 if (ret)
1265                         goto err_free;
1266         }
1267
1268         drm_mode = container_of(output->base.mode_list.next,
1269                                 struct drm_mode, base.link);
1270         output->base.current = &drm_mode->base;
1271         drm_mode->base.flags =
1272                 WL_OUTPUT_MODE_CURRENT | WL_OUTPUT_MODE_PREFERRED;
1273
1274         output->surface = gbm_surface_create(ec->gbm,
1275                                              output->base.current->width,
1276                                              output->base.current->height,
1277                                              GBM_FORMAT_XRGB8888,
1278                                              GBM_BO_USE_SCANOUT |
1279                                              GBM_BO_USE_RENDERING);
1280         if (!output->surface) {
1281                 fprintf(stderr, "failed to create gbm surface\n");
1282                 goto err_free;
1283         }
1284
1285         output->egl_surface =
1286                 eglCreateWindowSurface(ec->base.display, ec->base.config,
1287                                        output->surface, NULL);
1288         if (output->egl_surface == EGL_NO_SURFACE) {
1289                 fprintf(stderr, "failed to create egl surface\n");
1290                 goto err_surface;
1291         }
1292
1293         output->backlight = backlight_init(drm_device,
1294                                            connector->connector_type);
1295         if (output->backlight) {
1296                 output->base.set_backlight = drm_set_backlight;
1297                 output->base.backlight_current = drm_get_backlight(output);
1298         }
1299
1300         weston_output_init(&output->base, &ec->base, x, y,
1301                            connector->mmWidth, connector->mmHeight,
1302                            WL_OUTPUT_FLIPPED);
1303
1304         wl_list_insert(ec->base.output_list.prev, &output->base.link);
1305
1306         output->scanout_buffer_destroy_listener.notify =
1307                 output_handle_scanout_buffer_destroy;
1308         output->pending_scanout_buffer_destroy_listener.notify =
1309                 output_handle_pending_scanout_buffer_destroy;
1310
1311         output->next_fb_id = 0;
1312         output->base.origin = output->base.current;
1313         output->base.repaint = drm_output_repaint;
1314         output->base.destroy = drm_output_destroy;
1315         output->base.assign_planes = drm_assign_planes;
1316         output->base.read_pixels = drm_output_read_pixels;
1317         output->base.set_dpms = drm_set_dpms;
1318         output->base.switch_mode = drm_output_switch_mode;
1319
1320         return 0;
1321
1322 err_surface:
1323         gbm_surface_destroy(output->surface);
1324 err_free:
1325         wl_list_for_each_safe(drm_mode, next, &output->base.mode_list,
1326                                                         base.link) {
1327                 wl_list_remove(&drm_mode->base.link);
1328                 free(drm_mode);
1329         }
1330
1331         drmModeFreeCrtc(output->original_crtc);
1332         ec->crtc_allocator &= ~(1 << output->crtc_id);
1333         ec->connector_allocator &= ~(1 << output->connector_id);
1334         free(output);
1335
1336         return -1;
1337 }
1338
1339 static void
1340 create_sprites(struct drm_compositor *ec)
1341 {
1342         struct drm_sprite *sprite;
1343         drmModePlaneRes *plane_res;
1344         drmModePlane *plane;
1345         uint32_t i;
1346
1347         plane_res = drmModeGetPlaneResources(ec->drm.fd);
1348         if (!plane_res) {
1349                 fprintf(stderr, "failed to get plane resources: %s\n",
1350                         strerror(errno));
1351                 return;
1352         }
1353
1354         for (i = 0; i < plane_res->count_planes; i++) {
1355                 plane = drmModeGetPlane(ec->drm.fd, plane_res->planes[i]);
1356                 if (!plane)
1357                         continue;
1358
1359                 sprite = malloc(sizeof(*sprite) + ((sizeof(uint32_t)) *
1360                                                    plane->count_formats));
1361                 if (!sprite) {
1362                         fprintf(stderr, "%s: out of memory\n",
1363                                 __func__);
1364                         free(plane);
1365                         continue;
1366                 }
1367
1368                 memset(sprite, 0, sizeof *sprite);
1369
1370                 sprite->possible_crtcs = plane->possible_crtcs;
1371                 sprite->plane_id = plane->plane_id;
1372                 sprite->surface = NULL;
1373                 sprite->pending_surface = NULL;
1374                 sprite->fb_id = 0;
1375                 sprite->pending_fb_id = 0;
1376                 sprite->destroy_listener.notify = sprite_handle_buffer_destroy;
1377                 sprite->pending_destroy_listener.notify =
1378                         sprite_handle_pending_buffer_destroy;
1379                 sprite->compositor = ec;
1380                 sprite->count_formats = plane->count_formats;
1381                 memcpy(sprite->formats, plane->formats,
1382                        plane->count_formats * sizeof(plane->formats[0]));
1383                 drmModeFreePlane(plane);
1384
1385                 wl_list_insert(&ec->sprite_list, &sprite->link);
1386         }
1387
1388         free(plane_res->planes);
1389         free(plane_res);
1390 }
1391
1392 static void
1393 destroy_sprites(struct drm_compositor *compositor)
1394 {
1395         struct drm_sprite *sprite, *next;
1396         struct drm_output *output;
1397
1398         output = container_of(compositor->base.output_list.next,
1399                               struct drm_output, base.link);
1400
1401         wl_list_for_each_safe(sprite, next, &compositor->sprite_list, link) {
1402                 drmModeSetPlane(compositor->drm.fd,
1403                                 sprite->plane_id,
1404                                 output->crtc_id, 0, 0,
1405                                 0, 0, 0, 0, 0, 0, 0, 0);
1406                 drmModeRmFB(compositor->drm.fd, sprite->fb_id);
1407                 free(sprite);
1408         }
1409 }
1410
1411 static int
1412 create_outputs(struct drm_compositor *ec, uint32_t option_connector,
1413                struct udev_device *drm_device)
1414 {
1415         drmModeConnector *connector;
1416         drmModeRes *resources;
1417         int i;
1418         int x = 0, y = 0;
1419
1420         resources = drmModeGetResources(ec->drm.fd);
1421         if (!resources) {
1422                 fprintf(stderr, "drmModeGetResources failed\n");
1423                 return -1;
1424         }
1425
1426         ec->crtcs = calloc(resources->count_crtcs, sizeof(uint32_t));
1427         if (!ec->crtcs) {
1428                 drmModeFreeResources(resources);
1429                 return -1;
1430         }
1431
1432         ec->num_crtcs = resources->count_crtcs;
1433         memcpy(ec->crtcs, resources->crtcs, sizeof(uint32_t) * ec->num_crtcs);
1434
1435         for (i = 0; i < resources->count_connectors; i++) {
1436                 connector = drmModeGetConnector(ec->drm.fd,
1437                                                 resources->connectors[i]);
1438                 if (connector == NULL)
1439                         continue;
1440
1441                 if (connector->connection == DRM_MODE_CONNECTED &&
1442                     (option_connector == 0 ||
1443                      connector->connector_id == option_connector)) {
1444                         if (create_output_for_connector(ec, resources,
1445                                                         connector, x, y,
1446                                                         drm_device) < 0) {
1447                                 drmModeFreeConnector(connector);
1448                                 continue;
1449                         }
1450
1451                         x += container_of(ec->base.output_list.prev,
1452                                           struct weston_output,
1453                                           link)->current->width;
1454                 }
1455
1456                 drmModeFreeConnector(connector);
1457         }
1458
1459         if (wl_list_empty(&ec->base.output_list)) {
1460                 fprintf(stderr, "No currently active connector found.\n");
1461                 drmModeFreeResources(resources);
1462                 return -1;
1463         }
1464
1465         drmModeFreeResources(resources);
1466
1467         return 0;
1468 }
1469
1470 static void
1471 update_outputs(struct drm_compositor *ec, struct udev_device *drm_device)
1472 {
1473         drmModeConnector *connector;
1474         drmModeRes *resources;
1475         struct drm_output *output, *next;
1476         int x = 0, y = 0;
1477         int x_offset = 0, y_offset = 0;
1478         uint32_t connected = 0, disconnects = 0;
1479         int i;
1480
1481         resources = drmModeGetResources(ec->drm.fd);
1482         if (!resources) {
1483                 fprintf(stderr, "drmModeGetResources failed\n");
1484                 return;
1485         }
1486
1487         /* collect new connects */
1488         for (i = 0; i < resources->count_connectors; i++) {
1489                 int connector_id = resources->connectors[i];
1490
1491                 connector = drmModeGetConnector(ec->drm.fd, connector_id);
1492                 if (connector == NULL)
1493                         continue;
1494
1495                 if (connector->connection != DRM_MODE_CONNECTED) {
1496                         drmModeFreeConnector(connector);
1497                         continue;
1498                 }
1499
1500                 connected |= (1 << connector_id);
1501
1502                 if (!(ec->connector_allocator & (1 << connector_id))) {
1503                         struct weston_output *last =
1504                                 container_of(ec->base.output_list.prev,
1505                                              struct weston_output, link);
1506
1507                         /* XXX: not yet needed, we die with 0 outputs */
1508                         if (!wl_list_empty(&ec->base.output_list))
1509                                 x = last->x + last->current->width;
1510                         else
1511                                 x = 0;
1512                         y = 0;
1513                         create_output_for_connector(ec, resources,
1514                                                     connector, x, y,
1515                                                     drm_device);
1516                         printf("connector %d connected\n", connector_id);
1517
1518                 }
1519                 drmModeFreeConnector(connector);
1520         }
1521         drmModeFreeResources(resources);
1522
1523         disconnects = ec->connector_allocator & ~connected;
1524         if (disconnects) {
1525                 wl_list_for_each_safe(output, next, &ec->base.output_list,
1526                                       base.link) {
1527                         if (x_offset != 0 || y_offset != 0) {
1528                                 weston_output_move(&output->base,
1529                                                  output->base.x - x_offset,
1530                                                  output->base.y - y_offset);
1531                         }
1532
1533                         if (disconnects & (1 << output->connector_id)) {
1534                                 disconnects &= ~(1 << output->connector_id);
1535                                 printf("connector %d disconnected\n",
1536                                        output->connector_id);
1537                                 x_offset += output->base.current->width;
1538                                 drm_output_destroy(&output->base);
1539                         }
1540                 }
1541         }
1542
1543         /* FIXME: handle zero outputs, without terminating */   
1544         if (ec->connector_allocator == 0)
1545                 wl_display_terminate(ec->base.wl_display);
1546 }
1547
1548 static int
1549 udev_event_is_hotplug(struct drm_compositor *ec, struct udev_device *device)
1550 {
1551         const char *sysnum;
1552         const char *val;
1553
1554         sysnum = udev_device_get_sysnum(device);
1555         if (!sysnum || atoi(sysnum) != ec->drm.id)
1556                 return 0;
1557
1558         val = udev_device_get_property_value(device, "HOTPLUG");
1559         if (!val)
1560                 return 0;
1561
1562         return strcmp(val, "1") == 0;
1563 }
1564
1565 static int
1566 udev_drm_event(int fd, uint32_t mask, void *data)
1567 {
1568         struct drm_compositor *ec = data;
1569         struct udev_device *event;
1570
1571         event = udev_monitor_receive_device(ec->udev_monitor);
1572
1573         if (udev_event_is_hotplug(ec, event))
1574                 update_outputs(ec, event);
1575
1576         udev_device_unref(event);
1577
1578         return 1;
1579 }
1580
1581 static void
1582 drm_destroy(struct weston_compositor *ec)
1583 {
1584         struct drm_compositor *d = (struct drm_compositor *) ec;
1585         struct weston_input_device *input, *next;
1586
1587         wl_list_for_each_safe(input, next, &ec->input_device_list, link)
1588                 evdev_input_destroy(input);
1589
1590         wl_event_source_remove(d->udev_drm_source);
1591         wl_event_source_remove(d->drm_source);
1592
1593         weston_compositor_shutdown(ec);
1594
1595         gbm_device_destroy(d->gbm);
1596         destroy_sprites(d);
1597         if (weston_launcher_drm_set_master(&d->base, d->drm.fd, 0) < 0)
1598                 fprintf(stderr, "failed to drop master: %m\n");
1599         tty_destroy(d->tty);
1600
1601         free(d);
1602 }
1603
1604 static void
1605 drm_compositor_set_modes(struct drm_compositor *compositor)
1606 {
1607         struct drm_output *output;
1608         struct drm_mode *drm_mode;
1609         int ret;
1610
1611         wl_list_for_each(output, &compositor->base.output_list, base.link) {
1612                 drm_mode = (struct drm_mode *) output->base.current;
1613                 ret = drmModeSetCrtc(compositor->drm.fd, output->crtc_id,
1614                                      output->current_fb_id, 0, 0,
1615                                      &output->connector_id, 1,
1616                                      &drm_mode->mode_info);
1617                 if (ret < 0) {
1618                         fprintf(stderr,
1619                                 "failed to set mode %dx%d for output at %d,%d: %m\n",
1620                                 drm_mode->base.width, drm_mode->base.height, 
1621                                 output->base.x, output->base.y);
1622                 }
1623         }
1624 }
1625
1626 static void
1627 vt_func(struct weston_compositor *compositor, int event)
1628 {
1629         struct drm_compositor *ec = (struct drm_compositor *) compositor;
1630         struct weston_output *output;
1631         struct weston_input_device *input;
1632         struct drm_sprite *sprite;
1633         struct drm_output *drm_output;
1634
1635         switch (event) {
1636         case TTY_ENTER_VT:
1637                 compositor->focus = 1;
1638                 if (weston_launcher_drm_set_master(&ec->base, ec->drm.fd, 1)) {
1639                         fprintf(stderr, "failed to set master: %m\n");
1640                         wl_display_terminate(compositor->wl_display);
1641                 }
1642                 compositor->state = ec->prev_state;
1643                 drm_compositor_set_modes(ec);
1644                 weston_compositor_damage_all(compositor);
1645                 wl_list_for_each(input, &compositor->input_device_list, link) {
1646                         evdev_add_devices(ec->udev, input);
1647                         evdev_enable_udev_monitor(ec->udev, input);
1648                 }
1649                 break;
1650         case TTY_LEAVE_VT:
1651                 wl_list_for_each(input, &compositor->input_device_list, link) {
1652                         evdev_disable_udev_monitor(input);
1653                         evdev_remove_devices(input);
1654                 }
1655
1656                 compositor->focus = 0;
1657                 ec->prev_state = compositor->state;
1658                 compositor->state = WESTON_COMPOSITOR_SLEEPING;
1659
1660                 /* If we have a repaint scheduled (either from a
1661                  * pending pageflip or the idle handler), make sure we
1662                  * cancel that so we don't try to pageflip when we're
1663                  * vt switched away.  The SLEEPING state will prevent
1664                  * further attemps at repainting.  When we switch
1665                  * back, we schedule a repaint, which will process
1666                  * pending frame callbacks. */
1667
1668                 wl_list_for_each(output, &ec->base.output_list, link) {
1669                         output->repaint_needed = 0;
1670                         drm_output_set_cursor(output, NULL);
1671                 }
1672
1673                 drm_output = container_of(ec->base.output_list.next,
1674                                           struct drm_output, base.link);
1675
1676                 wl_list_for_each(sprite, &ec->sprite_list, link)
1677                         drmModeSetPlane(ec->drm.fd,
1678                                         sprite->plane_id,
1679                                         drm_output->crtc_id, 0, 0,
1680                                         0, 0, 0, 0, 0, 0, 0, 0);
1681
1682                 if (weston_launcher_drm_set_master(&ec->base, ec->drm.fd, 0) < 0)
1683                         fprintf(stderr, "failed to drop master: %m\n");
1684
1685                 break;
1686         };
1687 }
1688
1689 static void
1690 switch_vt_binding(struct wl_input_device *device, uint32_t time,
1691                   uint32_t key, uint32_t button, uint32_t axis, int32_t state, void *data)
1692 {
1693         struct drm_compositor *ec = data;
1694
1695         if (state)
1696                 tty_activate_vt(ec->tty, key - KEY_F1 + 1);
1697 }
1698
1699 static const char default_seat[] = "seat0";
1700
1701 static struct weston_compositor *
1702 drm_compositor_create(struct wl_display *display,
1703                       int connector, const char *seat, int tty)
1704 {
1705         struct drm_compositor *ec;
1706         struct udev_enumerate *e;
1707         struct udev_list_entry *entry;
1708         struct udev_device *device, *drm_device;
1709         const char *path, *device_seat;
1710         struct wl_event_loop *loop;
1711         uint32_t key;
1712
1713         ec = malloc(sizeof *ec);
1714         if (ec == NULL)
1715                 return NULL;
1716
1717         memset(ec, 0, sizeof *ec);
1718         ec->udev = udev_new();
1719         if (ec->udev == NULL) {
1720                 fprintf(stderr, "failed to initialize udev context\n");
1721                 return NULL;
1722         }
1723
1724         ec->base.wl_display = display;
1725         ec->tty = tty_create(&ec->base, vt_func, tty);
1726         if (!ec->tty) {
1727                 fprintf(stderr, "failed to initialize tty\n");
1728                 free(ec);
1729                 return NULL;
1730         }
1731
1732         e = udev_enumerate_new(ec->udev);
1733         udev_enumerate_add_match_subsystem(e, "drm");
1734         udev_enumerate_add_match_sysname(e, "card[0-9]*");
1735
1736         udev_enumerate_scan_devices(e);
1737         drm_device = NULL;
1738         udev_list_entry_foreach(entry, udev_enumerate_get_list_entry(e)) {
1739                 path = udev_list_entry_get_name(entry);
1740                 device = udev_device_new_from_syspath(ec->udev, path);
1741                 device_seat =
1742                         udev_device_get_property_value(device, "ID_SEAT");
1743                 if (!device_seat)
1744                         device_seat = default_seat;
1745                 if (strcmp(device_seat, seat) == 0) {
1746                         drm_device = device;
1747                         break;
1748                 }
1749                 udev_device_unref(device);
1750         }
1751
1752         if (drm_device == NULL) {
1753                 fprintf(stderr, "no drm device found\n");
1754                 return NULL;
1755         }
1756
1757         if (init_egl(ec, drm_device) < 0) {
1758                 fprintf(stderr, "failed to initialize egl\n");
1759                 return NULL;
1760         }
1761
1762         ec->base.destroy = drm_destroy;
1763
1764         ec->base.focus = 1;
1765
1766         ec->prev_state = WESTON_COMPOSITOR_ACTIVE;
1767
1768         /* Can't init base class until we have a current egl context */
1769         if (weston_compositor_init(&ec->base, display) < 0)
1770                 return NULL;
1771
1772         for (key = KEY_F1; key < KEY_F9; key++)
1773                 weston_compositor_add_binding(&ec->base, key, 0, 0,
1774                                               MODIFIER_CTRL | MODIFIER_ALT,
1775                                               switch_vt_binding, ec);
1776
1777         wl_list_init(&ec->sprite_list);
1778         create_sprites(ec);
1779
1780         if (create_outputs(ec, connector, drm_device) < 0) {
1781                 fprintf(stderr, "failed to create output for %s\n", path);
1782                 return NULL;
1783         }
1784
1785         udev_device_unref(drm_device);
1786         udev_enumerate_unref(e);
1787         path = NULL;
1788
1789         evdev_input_create(&ec->base, ec->udev, seat);
1790
1791         loop = wl_display_get_event_loop(ec->base.wl_display);
1792         ec->drm_source =
1793                 wl_event_loop_add_fd(loop, ec->drm.fd,
1794                                      WL_EVENT_READABLE, on_drm_input, ec);
1795
1796         ec->udev_monitor = udev_monitor_new_from_netlink(ec->udev, "udev");
1797         if (ec->udev_monitor == NULL) {
1798                 fprintf(stderr, "failed to intialize udev monitor\n");
1799                 return NULL;
1800         }
1801         udev_monitor_filter_add_match_subsystem_devtype(ec->udev_monitor,
1802                                                         "drm", NULL);
1803         ec->udev_drm_source =
1804                 wl_event_loop_add_fd(loop,
1805                                      udev_monitor_get_fd(ec->udev_monitor),
1806                                      WL_EVENT_READABLE, udev_drm_event, ec);
1807
1808         if (udev_monitor_enable_receiving(ec->udev_monitor) < 0) {
1809                 fprintf(stderr, "failed to enable udev-monitor receiving\n");
1810                 return NULL;
1811         }
1812
1813         return &ec->base;
1814 }
1815
1816 WL_EXPORT struct weston_compositor *
1817 backend_init(struct wl_display *display, int argc, char *argv[])
1818 {
1819         int connector = 0, tty = 0;
1820         const char *seat = default_seat;
1821
1822         const struct weston_option drm_options[] = {
1823                 { WESTON_OPTION_INTEGER, "connector", 0, &connector },
1824                 { WESTON_OPTION_STRING, "seat", 0, &seat },
1825                 { WESTON_OPTION_INTEGER, "tty", 0, &tty },
1826         };
1827
1828         parse_options(drm_options, ARRAY_LENGTH(drm_options), argc, argv);
1829
1830         return drm_compositor_create(display, connector, seat, tty);
1831 }