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