compositor-drm: Follow gbm_bo_get_pitch rename to gbm_bo_get_stride
[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         if (es->transform.enabled)
485                 return 0;
486
487         return 1;
488 }
489
490 static int
491 drm_surface_overlap_supported(struct weston_output *output_base,
492                               pixman_region32_t *overlap)
493 {
494         /* We could potentially use a color key here if the surface left
495          * to display has rectangular regions
496          */
497         if (pixman_region32_not_empty(overlap))
498                 return 0;
499         return 1;
500 }
501
502 static void
503 drm_disable_unused_sprites(struct weston_output *output_base)
504 {
505         struct weston_compositor *ec = output_base->compositor;
506         struct drm_compositor *c =(struct drm_compositor *) ec;
507         struct drm_output *output = (struct drm_output *) output_base;
508         struct drm_sprite *s;
509         int ret;
510
511         wl_list_for_each(s, &c->sprite_list, link) {
512                 if (s->pending_fb_id)
513                         continue;
514
515                 ret = drmModeSetPlane(c->drm.fd, s->plane_id,
516                                       output->crtc_id, 0, 0,
517                                       0, 0, 0, 0, 0, 0, 0, 0);
518                 if (ret)
519                         weston_log("failed to disable plane: %d: %s\n",
520                                 ret, strerror(errno));
521                 drmModeRmFB(c->drm.fd, s->fb_id);
522
523                 if (s->surface) {
524                         s->surface = NULL;
525                         wl_list_remove(&s->destroy_listener.link);
526                 }
527
528                 assert(!s->pending_surface);
529                 s->fb_id = 0;
530                 s->pending_fb_id = 0;
531         }
532 }
533
534 /*
535  * This function must take care to damage any previously assigned surface
536  * if the sprite ends up binding to a different surface than in the
537  * previous frame.
538  */
539 static int
540 drm_output_prepare_overlay_surface(struct weston_output *output_base,
541                                    struct weston_surface *es,
542                                    pixman_region32_t *overlap)
543 {
544         struct weston_compositor *ec = output_base->compositor;
545         struct drm_compositor *c =(struct drm_compositor *) ec;
546         struct drm_sprite *s;
547         int found = 0;
548         EGLint handle, stride;
549         struct gbm_bo *bo;
550         uint32_t fb_id = 0;
551         uint32_t handles[4], pitches[4], offsets[4];
552         int ret = 0;
553         pixman_region32_t dest_rect, src_rect;
554         pixman_box32_t *box;
555         uint32_t format;
556
557         if (c->sprites_are_broken)
558                 return -1;
559
560         if (es->output_mask != (1u << output_base->id))
561                 return -1;
562
563         if (surface_is_primary(ec, es))
564                 return -1;
565
566         if (es->buffer == NULL)
567                 return -1;
568
569         if (!drm_surface_transform_supported(es))
570                 return -1;
571
572         if (!drm_surface_overlap_supported(output_base, overlap))
573                 return -1;
574
575         wl_list_for_each(s, &c->sprite_list, link) {
576                 if (!drm_sprite_crtc_supported(output_base, s->possible_crtcs))
577                         continue;
578
579                 if (!s->pending_fb_id) {
580                         found = 1;
581                         break;
582                 }
583         }
584
585         /* No sprites available */
586         if (!found)
587                 return -1;
588
589         bo = gbm_bo_import(c->gbm, GBM_BO_IMPORT_WL_BUFFER,
590                            es->buffer, GBM_BO_USE_SCANOUT);
591         if (!bo)
592                 return -1;
593
594         format = gbm_bo_get_format(bo);
595         handle = gbm_bo_get_handle(bo).s32;
596         stride = gbm_bo_get_stride(bo);
597
598         gbm_bo_destroy(bo);
599
600         if (!drm_surface_format_supported(s, format))
601                 return -1;
602
603         if (!handle)
604                 return -1;
605
606         handles[0] = handle;
607         pitches[0] = stride;
608         offsets[0] = 0;
609
610         ret = drmModeAddFB2(c->drm.fd, es->geometry.width, es->geometry.height,
611                             format, handles, pitches, offsets,
612                             &fb_id, 0);
613         if (ret) {
614                 weston_log("addfb2 failed: %d\n", ret);
615                 c->sprites_are_broken = 1;
616                 return -1;
617         }
618
619         if (s->surface && s->surface != es) {
620                 struct weston_surface *old_surf = s->surface;
621                 pixman_region32_fini(&old_surf->damage);
622                 pixman_region32_init_rect(&old_surf->damage,
623                                           old_surf->geometry.x, old_surf->geometry.y,
624                                           old_surf->geometry.width, old_surf->geometry.height);
625         }
626
627         s->pending_fb_id = fb_id;
628         s->pending_surface = es;
629         es->buffer->busy_count++;
630
631         /*
632          * Calculate the source & dest rects properly based on actual
633          * postion (note the caller has called weston_surface_update_transform()
634          * for us already).
635          */
636         pixman_region32_init(&dest_rect);
637         pixman_region32_intersect(&dest_rect, &es->transform.boundingbox,
638                                   &output_base->region);
639         pixman_region32_translate(&dest_rect, -output_base->x, -output_base->y);
640         box = pixman_region32_extents(&dest_rect);
641         s->dest_x = box->x1;
642         s->dest_y = box->y1;
643         s->dest_w = box->x2 - box->x1;
644         s->dest_h = box->y2 - box->y1;
645         pixman_region32_fini(&dest_rect);
646
647         pixman_region32_init(&src_rect);
648         pixman_region32_intersect(&src_rect, &es->transform.boundingbox,
649                                   &output_base->region);
650         pixman_region32_translate(&src_rect, -es->geometry.x, -es->geometry.y);
651         box = pixman_region32_extents(&src_rect);
652         s->src_x = box->x1 << 16;
653         s->src_y = box->y1 << 16;
654         s->src_w = (box->x2 - box->x1) << 16;
655         s->src_h = (box->y2 - box->y1) << 16;
656         pixman_region32_fini(&src_rect);
657
658         wl_signal_add(&es->buffer->resource.destroy_signal,
659                       &s->pending_destroy_listener);
660         return 0;
661 }
662
663 static int
664 drm_output_set_cursor(struct weston_output *output_base,
665                       struct weston_seat *es);
666
667 static void
668 weston_output_set_cursor(struct weston_output *output,
669                          struct weston_seat *seat,
670                          pixman_region32_t *overlap)
671 {
672         pixman_region32_t cursor_region;
673
674         if (seat->sprite == NULL)
675                 return;
676
677         pixman_region32_init(&cursor_region);
678         pixman_region32_intersect(&cursor_region,
679                                   &seat->sprite->transform.boundingbox,
680                                   &output->region);
681
682         if (!pixman_region32_not_empty(&cursor_region)) {
683                 drm_output_set_cursor(output, NULL);
684                 goto out;
685         }
686
687         if (pixman_region32_not_empty(overlap) ||
688             drm_output_set_cursor(output, seat) < 0) {
689                 if (seat->sprite->plane == WESTON_PLANE_DRM_CURSOR) {
690                         weston_surface_damage(seat->sprite);
691                         drm_output_set_cursor(output, NULL);
692                 }
693                 seat->sprite->plane = WESTON_PLANE_PRIMARY;
694         } else {
695                 if (seat->sprite->plane == WESTON_PLANE_PRIMARY)
696                         weston_surface_damage_below(seat->sprite);
697                 wl_list_remove(&seat->sprite->link);
698                 seat->sprite->plane = WESTON_PLANE_DRM_CURSOR;
699         }
700
701 out:
702         pixman_region32_fini(&cursor_region);
703 }
704
705 static void
706 drm_assign_planes(struct weston_output *output)
707 {
708         struct weston_compositor *ec = output->compositor;
709         struct weston_surface *es, *next;
710         pixman_region32_t overlap, surface_overlap;
711         struct weston_seat *seat;
712
713         /*
714          * Find a surface for each sprite in the output using some heuristics:
715          * 1) size
716          * 2) frequency of update
717          * 3) opacity (though some hw might support alpha blending)
718          * 4) clipping (this can be fixed with color keys)
719          *
720          * The idea is to save on blitting since this should save power.
721          * If we can get a large video surface on the sprite for example,
722          * the main display surface may not need to update at all, and
723          * the client buffer can be used directly for the sprite surface
724          * as we do for flipping full screen surfaces.
725          */
726         seat = (struct weston_seat *) ec->seat;
727         pixman_region32_init(&overlap);
728         wl_list_for_each_safe(es, next, &ec->surface_list, link) {
729                 /*
730                  * FIXME: try to assign hw cursors here too, they're just
731                  * special overlays
732                  */
733                 pixman_region32_init(&surface_overlap);
734                 pixman_region32_intersect(&surface_overlap, &overlap,
735                                           &es->transform.boundingbox);
736
737                 if (es == seat->sprite) {
738                         weston_output_set_cursor(output, seat,
739                                                  &surface_overlap);
740
741                         if (seat->sprite->plane == WESTON_PLANE_PRIMARY)
742                                 pixman_region32_union(&overlap, &overlap,
743                                                       &es->transform.boundingbox);
744                 } else if (!drm_output_prepare_overlay_surface(output, es,
745                                                                &surface_overlap)) {
746                         pixman_region32_fini(&es->damage);
747                         pixman_region32_init(&es->damage);
748                 } else {
749                         pixman_region32_union(&overlap, &overlap,
750                                               &es->transform.boundingbox);
751                 }
752                 pixman_region32_fini(&surface_overlap);
753         }
754         pixman_region32_fini(&overlap);
755
756         if (!seat->sprite || !weston_surface_is_mapped(seat->sprite))
757                 drm_output_set_cursor(output, NULL);
758
759         drm_disable_unused_sprites(output);
760 }
761
762 static int
763 drm_output_set_cursor(struct weston_output *output_base,
764                       struct weston_seat *es)
765 {
766         struct drm_output *output = (struct drm_output *) output_base;
767         struct drm_compositor *c =
768                 (struct drm_compositor *) output->base.compositor;
769         EGLint handle, stride;
770         int ret = -1;
771         struct gbm_bo *bo;
772         uint32_t buf[64 * 64];
773         unsigned char *d, *s, *end;
774
775         if (es == NULL) {
776                 drmModeSetCursor(c->drm.fd, output->crtc_id, 0, 0, 0);
777                 return 0;
778         }
779
780         if (es->sprite->buffer == NULL ||
781             !wl_buffer_is_shm(es->sprite->buffer))
782                 goto out;
783
784         if (es->sprite->geometry.width > 64 ||
785             es->sprite->geometry.height > 64)
786                 goto out;
787
788         output->current_cursor ^= 1;
789         bo = output->cursor_bo[output->current_cursor];
790         if (bo == NULL)
791                 goto out;
792
793         memset(buf, 0, sizeof buf);
794         d = (unsigned char *) buf;
795         stride = wl_shm_buffer_get_stride(es->sprite->buffer);
796         s = wl_shm_buffer_get_data(es->sprite->buffer);
797         end = s + stride * es->sprite->geometry.height;
798         while (s < end) {
799                 memcpy(d, s, es->sprite->geometry.width * 4);
800                 s += stride;
801                 d += 64 * 4;
802         }
803
804         if (gbm_bo_write(bo, buf, sizeof buf) < 0)
805                 goto out;
806
807         handle = gbm_bo_get_handle(bo).s32;
808         ret = drmModeSetCursor(c->drm.fd, output->crtc_id, handle, 64, 64);
809         if (ret) {
810                 weston_log("failed to set cursor: %s\n", strerror(-ret));
811                 goto out;
812         }
813
814         ret = drmModeMoveCursor(c->drm.fd, output->crtc_id,
815                                 es->sprite->geometry.x - output->base.x,
816                                 es->sprite->geometry.y - output->base.y);
817         if (ret) {
818                 weston_log("failed to move cursor: %s\n", strerror(-ret));
819                 goto out;
820         }
821
822 out:
823         if (ret)
824                 drmModeSetCursor(c->drm.fd, output->crtc_id, 0, 0, 0);
825         return ret;
826 }
827
828 static void
829 drm_output_destroy(struct weston_output *output_base)
830 {
831         struct drm_output *output = (struct drm_output *) output_base;
832         struct drm_compositor *c =
833                 (struct drm_compositor *) output->base.compositor;
834         drmModeCrtcPtr origcrtc = output->original_crtc;
835
836         if (output->backlight)
837                 backlight_destroy(output->backlight);
838
839         /* Turn off hardware cursor */
840         drm_output_set_cursor(&output->base, NULL);
841
842         /* Restore original CRTC state */
843         drmModeSetCrtc(c->drm.fd, origcrtc->crtc_id, origcrtc->buffer_id,
844                        origcrtc->x, origcrtc->y,
845                        &output->connector_id, 1, &origcrtc->mode);
846         drmModeFreeCrtc(origcrtc);
847
848         c->crtc_allocator &= ~(1 << output->crtc_id);
849         c->connector_allocator &= ~(1 << output->connector_id);
850
851         eglDestroySurface(c->base.egl_display, output->egl_surface);
852         gbm_surface_destroy(output->surface);
853
854         weston_output_destroy(&output->base);
855         wl_list_remove(&output->base.link);
856
857         free(output);
858 }
859
860 static struct drm_mode *
861 choose_mode (struct drm_output *output, struct weston_mode *target_mode)
862 {
863         struct drm_mode *tmp_mode = NULL, *mode;
864
865         if (output->base.current->width == target_mode->width && 
866             output->base.current->height == target_mode->height &&
867             (output->base.current->refresh == target_mode->refresh ||
868              target_mode->refresh == 0))
869                 return (struct drm_mode *)output->base.current;
870
871         wl_list_for_each(mode, &output->base.mode_list, base.link) {
872                 if (mode->mode_info.hdisplay == target_mode->width &&
873                     mode->mode_info.vdisplay == target_mode->height) {
874                         if (mode->mode_info.vrefresh == target_mode->refresh || 
875                             target_mode->refresh == 0) {
876                                 return mode;
877                         } else if (!tmp_mode) 
878                                 tmp_mode = mode;
879                 }
880         }
881
882         return tmp_mode;
883 }
884
885 static int
886 drm_output_switch_mode(struct weston_output *output_base, struct weston_mode *mode)
887 {
888         struct drm_output *output;
889         struct drm_mode *drm_mode;
890         int ret;
891         struct drm_compositor *ec;
892         struct gbm_surface *surface;
893         EGLSurface egl_surface;
894
895         if (output_base == NULL) {
896                 weston_log("output is NULL.\n");
897                 return -1;
898         }
899
900         if (mode == NULL) {
901                 weston_log("mode is NULL.\n");
902                 return -1;
903         }
904
905         ec = (struct drm_compositor *)output_base->compositor;
906         output = (struct drm_output *)output_base;
907         drm_mode  = choose_mode (output, mode);
908
909         if (!drm_mode) {
910                 weston_log("%s, invalid resolution:%dx%d\n", __func__, mode->width, mode->height);
911                 return -1;
912         } else if (&drm_mode->base == output->base.current) {
913                 return 0;
914         } else if (drm_mode->base.width == output->base.current->width &&
915                    drm_mode->base.height == output->base.current->height) {
916                 /* only change refresh value */
917                 ret = drmModeSetCrtc(ec->drm.fd,
918                                      output->crtc_id,
919                                      output->current->fb_id, 0, 0,
920                                      &output->connector_id, 1, &drm_mode->mode_info);
921
922                 if (ret) {
923                         weston_log("failed to set mode (%dx%d) %u Hz\n",
924                                 drm_mode->base.width,
925                                 drm_mode->base.height,
926                                 drm_mode->base.refresh / 1000);
927                         ret = -1;
928                 } else {
929                         output->base.current->flags = 0;
930                         output->base.current = &drm_mode->base;
931                         drm_mode->base.flags = 
932                                 WL_OUTPUT_MODE_CURRENT | WL_OUTPUT_MODE_PREFERRED;
933                         ret = 0;
934                 }
935
936                 return ret;
937         }
938
939         drm_mode->base.flags =
940                 WL_OUTPUT_MODE_CURRENT | WL_OUTPUT_MODE_PREFERRED;
941
942         surface = gbm_surface_create(ec->gbm,
943                                  drm_mode->base.width,
944                                  drm_mode->base.height,
945                                  GBM_FORMAT_XRGB8888,
946                                  GBM_BO_USE_SCANOUT |
947                                  GBM_BO_USE_RENDERING);
948         if (!surface) {
949                 weston_log("failed to create gbm surface\n");
950                 return -1;
951         }
952
953         egl_surface =
954                 eglCreateWindowSurface(ec->base.egl_display,
955                                        ec->base.egl_config,
956                                        surface, NULL);
957
958         if (egl_surface == EGL_NO_SURFACE) {
959                 weston_log("failed to create egl surface\n");
960                 goto err;
961         }
962
963         ret = drmModeSetCrtc(ec->drm.fd,
964                              output->crtc_id,
965                              output->current->fb_id, 0, 0,
966                              &output->connector_id, 1, &drm_mode->mode_info);
967         if (ret) {
968                 weston_log("failed to set mode\n");
969                 goto err;
970         }
971
972         /* reset rendering stuff. */
973         if (output->current) {
974                 if (output->current->is_client_buffer)
975                         gbm_bo_destroy(output->current->bo);
976                 else
977                         gbm_surface_release_buffer(output->surface,
978                                                    output->current->bo);
979         }
980         output->current = NULL;
981
982         if (output->next) {
983                 if (output->next->is_client_buffer)
984                         gbm_bo_destroy(output->next->bo);
985                 else
986                         gbm_surface_release_buffer(output->surface,
987                                                    output->next->bo);
988         }
989         output->next = NULL;
990
991         eglDestroySurface(ec->base.egl_display, output->egl_surface);
992         gbm_surface_destroy(output->surface);
993         output->egl_surface = egl_surface;
994         output->surface = surface;
995
996         /*update output*/
997         output->base.current = &drm_mode->base;
998         output->base.dirty = 1;
999         weston_output_move(&output->base, output->base.x, output->base.y);
1000         return 0;
1001
1002 err:
1003         eglDestroySurface(ec->base.egl_display, egl_surface);
1004         gbm_surface_destroy(surface);
1005         return -1;
1006 }
1007
1008 static int
1009 on_drm_input(int fd, uint32_t mask, void *data)
1010 {
1011         drmEventContext evctx;
1012
1013         memset(&evctx, 0, sizeof evctx);
1014         evctx.version = DRM_EVENT_CONTEXT_VERSION;
1015         evctx.page_flip_handler = page_flip_handler;
1016         evctx.vblank_handler = vblank_handler;
1017         drmHandleEvent(fd, &evctx);
1018
1019         return 1;
1020 }
1021
1022 static int
1023 init_egl(struct drm_compositor *ec, struct udev_device *device)
1024 {
1025         EGLint major, minor, n;
1026         const char *filename, *sysnum;
1027         int fd;
1028         static const EGLint context_attribs[] = {
1029                 EGL_CONTEXT_CLIENT_VERSION, 2,
1030                 EGL_NONE
1031         };
1032
1033         static const EGLint config_attribs[] = {
1034                 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
1035                 EGL_RED_SIZE, 1,
1036                 EGL_GREEN_SIZE, 1,
1037                 EGL_BLUE_SIZE, 1,
1038                 EGL_ALPHA_SIZE, 0,
1039                 EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
1040                 EGL_NONE
1041         };
1042
1043         sysnum = udev_device_get_sysnum(device);
1044         if (sysnum)
1045                 ec->drm.id = atoi(sysnum);
1046         if (!sysnum || ec->drm.id < 0) {
1047                 weston_log("cannot get device sysnum\n");
1048                 return -1;
1049         }
1050
1051         filename = udev_device_get_devnode(device);
1052         fd = open(filename, O_RDWR | O_CLOEXEC);
1053         if (fd < 0) {
1054                 /* Probably permissions error */
1055                 weston_log("couldn't open %s, skipping\n",
1056                         udev_device_get_devnode(device));
1057                 return -1;
1058         }
1059
1060         weston_log("using %s\n", filename);
1061
1062         ec->drm.fd = fd;
1063         ec->gbm = gbm_create_device(ec->drm.fd);
1064         ec->base.egl_display = eglGetDisplay(ec->gbm);
1065         if (ec->base.egl_display == NULL) {
1066                 weston_log("failed to create display\n");
1067                 return -1;
1068         }
1069
1070         if (!eglInitialize(ec->base.egl_display, &major, &minor)) {
1071                 weston_log("failed to initialize display\n");
1072                 return -1;
1073         }
1074
1075         if (!eglBindAPI(EGL_OPENGL_ES_API)) {
1076                 weston_log("failed to bind api EGL_OPENGL_ES_API\n");
1077                 return -1;
1078         }
1079
1080         if (!eglChooseConfig(ec->base.egl_display, config_attribs,
1081                              &ec->base.egl_config, 1, &n) || n != 1) {
1082                 weston_log("failed to choose config: %d\n", n);
1083                 return -1;
1084         }
1085
1086         ec->base.egl_context =
1087                 eglCreateContext(ec->base.egl_display, ec->base.egl_config,
1088                                  EGL_NO_CONTEXT, context_attribs);
1089         if (ec->base.egl_context == NULL) {
1090                 weston_log("failed to create context\n");
1091                 return -1;
1092         }
1093
1094         ec->dummy_surface = gbm_surface_create(ec->gbm, 10, 10,
1095                                                GBM_FORMAT_XRGB8888,
1096                                                GBM_BO_USE_RENDERING);
1097         if (!ec->dummy_surface) {
1098                 weston_log("failed to create dummy gbm surface\n");
1099                 return -1;
1100         }
1101
1102         ec->dummy_egl_surface =
1103                 eglCreateWindowSurface(ec->base.egl_display,
1104                                        ec->base.egl_config,
1105                                        ec->dummy_surface,
1106                                        NULL);
1107         if (ec->dummy_egl_surface == EGL_NO_SURFACE) {
1108                 weston_log("failed to create egl surface\n");
1109                 return -1;
1110         }
1111
1112         if (!eglMakeCurrent(ec->base.egl_display, ec->dummy_egl_surface,
1113                             ec->dummy_egl_surface, ec->base.egl_context)) {
1114                 weston_log("failed to make context current\n");
1115                 return -1;
1116         }
1117
1118         return 0;
1119 }
1120
1121 static int
1122 drm_output_add_mode(struct drm_output *output, drmModeModeInfo *info)
1123 {
1124         struct drm_mode *mode;
1125         uint64_t refresh;
1126
1127         mode = malloc(sizeof *mode);
1128         if (mode == NULL)
1129                 return -1;
1130
1131         mode->base.flags = 0;
1132         mode->base.width = info->hdisplay;
1133         mode->base.height = info->vdisplay;
1134
1135         /* Calculate higher precision (mHz) refresh rate */
1136         refresh = (info->clock * 1000000LL / info->htotal +
1137                    info->vtotal / 2) / info->vtotal;
1138
1139         if (info->flags & DRM_MODE_FLAG_INTERLACE)
1140                 refresh *= 2;
1141         if (info->flags & DRM_MODE_FLAG_DBLSCAN)
1142                 refresh /= 2;
1143         if (info->vscan > 1)
1144             refresh /= info->vscan;
1145
1146         mode->base.refresh = refresh;
1147         mode->mode_info = *info;
1148
1149         if (info->type & DRM_MODE_TYPE_PREFERRED)
1150                 mode->base.flags |= WL_OUTPUT_MODE_PREFERRED;
1151
1152         wl_list_insert(output->base.mode_list.prev, &mode->base.link);
1153
1154         return 0;
1155 }
1156
1157 static int
1158 drm_subpixel_to_wayland(int drm_value)
1159 {
1160         switch (drm_value) {
1161         default:
1162         case DRM_MODE_SUBPIXEL_UNKNOWN:
1163                 return WL_OUTPUT_SUBPIXEL_UNKNOWN;
1164         case DRM_MODE_SUBPIXEL_NONE:
1165                 return WL_OUTPUT_SUBPIXEL_NONE;
1166         case DRM_MODE_SUBPIXEL_HORIZONTAL_RGB:
1167                 return WL_OUTPUT_SUBPIXEL_HORIZONTAL_RGB;
1168         case DRM_MODE_SUBPIXEL_HORIZONTAL_BGR:
1169                 return WL_OUTPUT_SUBPIXEL_HORIZONTAL_BGR;
1170         case DRM_MODE_SUBPIXEL_VERTICAL_RGB:
1171                 return WL_OUTPUT_SUBPIXEL_VERTICAL_RGB;
1172         case DRM_MODE_SUBPIXEL_VERTICAL_BGR:
1173                 return WL_OUTPUT_SUBPIXEL_VERTICAL_BGR;
1174         }
1175 }
1176
1177 static void
1178 sprite_handle_buffer_destroy(struct wl_listener *listener, void *data)
1179 {
1180         struct drm_sprite *sprite =
1181                 container_of(listener, struct drm_sprite,
1182                              destroy_listener);
1183         struct drm_compositor *compositor = sprite->compositor;
1184
1185         sprite->surface = NULL;
1186         drmModeRmFB(compositor->drm.fd, sprite->fb_id);
1187         sprite->fb_id = 0;
1188 }
1189
1190 static void
1191 sprite_handle_pending_buffer_destroy(struct wl_listener *listener, void *data)
1192 {
1193         struct drm_sprite *sprite =
1194                 container_of(listener, struct drm_sprite,
1195                              pending_destroy_listener);
1196         struct drm_compositor *compositor = sprite->compositor;
1197
1198         sprite->pending_surface = NULL;
1199         drmModeRmFB(compositor->drm.fd, sprite->pending_fb_id);
1200         sprite->pending_fb_id = 0;
1201 }
1202
1203 /* returns a value between 0-255 range, where higher is brighter */
1204 static uint32_t
1205 drm_get_backlight(struct drm_output *output)
1206 {
1207         long brightness, max_brightness, norm;
1208
1209         brightness = backlight_get_brightness(output->backlight);
1210         max_brightness = backlight_get_max_brightness(output->backlight);
1211
1212         /* convert it on a scale of 0 to 255 */
1213         norm = (brightness * 255)/(max_brightness);
1214
1215         return (uint32_t) norm;
1216 }
1217
1218 /* values accepted are between 0-255 range */
1219 static void
1220 drm_set_backlight(struct weston_output *output_base, uint32_t value)
1221 {
1222         struct drm_output *output = (struct drm_output *) output_base;
1223         long max_brightness, new_brightness;
1224
1225         if (!output->backlight)
1226                 return;
1227
1228         if (value > 255)
1229                 return;
1230
1231         max_brightness = backlight_get_max_brightness(output->backlight);
1232
1233         /* get denormalized value */
1234         new_brightness = (value * max_brightness) / 255;
1235
1236         backlight_set_brightness(output->backlight, new_brightness);
1237 }
1238
1239 static drmModePropertyPtr
1240 drm_get_prop(int fd, drmModeConnectorPtr connector, const char *name)
1241 {
1242         drmModePropertyPtr props;
1243         int i;
1244
1245         for (i = 0; i < connector->count_props; i++) {
1246                 props = drmModeGetProperty(fd, connector->props[i]);
1247                 if (!props)
1248                         continue;
1249
1250                 if (!strcmp(props->name, name))
1251                         return props;
1252
1253                 drmModeFreeProperty(props);
1254         }
1255
1256         return NULL;
1257 }
1258
1259 static void
1260 drm_set_dpms(struct weston_output *output_base, enum dpms_enum level)
1261 {
1262         struct drm_output *output = (struct drm_output *) output_base;
1263         struct weston_compositor *ec = output_base->compositor;
1264         struct drm_compositor *c = (struct drm_compositor *) ec;
1265         drmModeConnectorPtr connector;
1266         drmModePropertyPtr prop;
1267
1268         connector = drmModeGetConnector(c->drm.fd, output->connector_id);
1269         if (!connector)
1270                 return;
1271
1272         prop = drm_get_prop(c->drm.fd, connector, "DPMS");
1273         if (!prop) {
1274                 drmModeFreeConnector(connector);
1275                 return;
1276         }
1277
1278         drmModeConnectorSetProperty(c->drm.fd, connector->connector_id,
1279                                     prop->prop_id, level);
1280         drmModeFreeProperty(prop);
1281         drmModeFreeConnector(connector);
1282 }
1283
1284 static int
1285 create_output_for_connector(struct drm_compositor *ec,
1286                             drmModeRes *resources,
1287                             drmModeConnector *connector,
1288                             int x, int y, struct udev_device *drm_device)
1289 {
1290         struct drm_output *output;
1291         struct drm_mode *drm_mode, *next;
1292         struct weston_mode *m, *preferred, *current;
1293         drmModeEncoder *encoder;
1294         drmModeModeInfo crtc_mode;
1295         drmModeCrtc *crtc;
1296         int i, ret;
1297
1298         encoder = drmModeGetEncoder(ec->drm.fd, connector->encoders[0]);
1299         if (encoder == NULL) {
1300                 weston_log("No encoder for connector.\n");
1301                 return -1;
1302         }
1303
1304         for (i = 0; i < resources->count_crtcs; i++) {
1305                 if (encoder->possible_crtcs & (1 << i) &&
1306                     !(ec->crtc_allocator & (1 << resources->crtcs[i])))
1307                         break;
1308         }
1309         if (i == resources->count_crtcs) {
1310                 weston_log("No usable crtc for encoder.\n");
1311                 drmModeFreeEncoder(encoder);
1312                 return -1;
1313         }
1314
1315         output = malloc(sizeof *output);
1316         if (output == NULL) {
1317                 drmModeFreeEncoder(encoder);
1318                 return -1;
1319         }
1320
1321         memset(output, 0, sizeof *output);
1322         output->base.subpixel = drm_subpixel_to_wayland(connector->subpixel);
1323         output->base.make = "unknown";
1324         output->base.model = "unknown";
1325         wl_list_init(&output->base.mode_list);
1326
1327         output->crtc_id = resources->crtcs[i];
1328         ec->crtc_allocator |= (1 << output->crtc_id);
1329         output->connector_id = connector->connector_id;
1330         ec->connector_allocator |= (1 << output->connector_id);
1331
1332         output->original_crtc = drmModeGetCrtc(ec->drm.fd, output->crtc_id);
1333         drmModeFreeEncoder(encoder);
1334
1335         /* Get the current mode on the crtc that's currently driving
1336          * this connector. */
1337         encoder = drmModeGetEncoder(ec->drm.fd, connector->encoder_id);
1338         if (encoder == NULL)
1339                 goto err_free;
1340         crtc = drmModeGetCrtc(ec->drm.fd, encoder->crtc_id);
1341         drmModeFreeEncoder(encoder);
1342         if (crtc == NULL)
1343                 goto err_free;
1344         crtc_mode = crtc->mode;
1345         drmModeFreeCrtc(crtc);
1346
1347         for (i = 0; i < connector->count_modes; i++) {
1348                 ret = drm_output_add_mode(output, &connector->modes[i]);
1349                 if (ret)
1350                         goto err_free;
1351         }
1352
1353         preferred = NULL;
1354         current = NULL;
1355         wl_list_for_each(drm_mode, &output->base.mode_list, base.link) {
1356                 if (!memcmp(&crtc_mode, &drm_mode->mode_info, sizeof crtc_mode)) {
1357                         drm_mode->base.flags |= WL_OUTPUT_MODE_CURRENT;
1358                         current = &drm_mode->base;
1359                 }
1360                 if (drm_mode->base.flags & WL_OUTPUT_MODE_PREFERRED)
1361                         preferred = &drm_mode->base;
1362         }
1363
1364         if (current == NULL) {
1365                 ret = drm_output_add_mode(output, &crtc_mode);
1366                 if (ret)
1367                         goto err_free;
1368                 current = container_of(output->base.mode_list.prev,
1369                                        struct weston_mode, link);
1370                 current->flags |= WL_OUTPUT_MODE_CURRENT;
1371         }
1372
1373         if (preferred == NULL)
1374                 preferred = current;
1375
1376         if (option_current_mode) {
1377                 output->base.current = current;
1378         } else {
1379                 output->base.current = preferred;
1380                 current->flags &= ~WL_OUTPUT_MODE_CURRENT;
1381                 preferred->flags |= WL_OUTPUT_MODE_CURRENT;
1382         }
1383
1384         output->surface = gbm_surface_create(ec->gbm,
1385                                              output->base.current->width,
1386                                              output->base.current->height,
1387                                              GBM_FORMAT_XRGB8888,
1388                                              GBM_BO_USE_SCANOUT |
1389                                              GBM_BO_USE_RENDERING);
1390         if (!output->surface) {
1391                 weston_log("failed to create gbm surface\n");
1392                 goto err_free;
1393         }
1394
1395         output->egl_surface =
1396                 eglCreateWindowSurface(ec->base.egl_display,
1397                                        ec->base.egl_config,
1398                                        output->surface,
1399                                        NULL);
1400         if (output->egl_surface == EGL_NO_SURFACE) {
1401                 weston_log("failed to create egl surface\n");
1402                 goto err_surface;
1403         }
1404
1405         output->cursor_bo[0] =
1406                 gbm_bo_create(ec->gbm, 64, 64, GBM_FORMAT_ARGB8888,
1407                               GBM_BO_USE_CURSOR_64X64 | GBM_BO_USE_WRITE);
1408         output->cursor_bo[1] =
1409                 gbm_bo_create(ec->gbm, 64, 64, GBM_FORMAT_ARGB8888,
1410                               GBM_BO_USE_CURSOR_64X64 | GBM_BO_USE_WRITE);
1411
1412         output->backlight = backlight_init(drm_device,
1413                                            connector->connector_type);
1414         if (output->backlight) {
1415                 output->base.set_backlight = drm_set_backlight;
1416                 output->base.backlight_current = drm_get_backlight(output);
1417         }
1418
1419         weston_output_init(&output->base, &ec->base, x, y,
1420                            connector->mmWidth, connector->mmHeight,
1421                            WL_OUTPUT_FLIPPED);
1422
1423         wl_list_insert(ec->base.output_list.prev, &output->base.link);
1424
1425         output->base.origin = output->base.current;
1426         output->base.repaint = drm_output_repaint;
1427         output->base.destroy = drm_output_destroy;
1428         output->base.assign_planes = drm_assign_planes;
1429         output->base.set_dpms = drm_set_dpms;
1430         output->base.switch_mode = drm_output_switch_mode;
1431
1432         weston_log("kms connector %d, crtc %d\n",
1433                    output->connector_id, output->crtc_id);
1434         wl_list_for_each(m, &output->base.mode_list, link)
1435                 weston_log_continue("  mode %dx%d@%.1f%s%s%s\n",
1436                                     m->width, m->height, m->refresh / 1000.0,
1437                                     m->flags & WL_OUTPUT_MODE_PREFERRED ?
1438                                     ", preferred" : "",
1439                                     m->flags & WL_OUTPUT_MODE_CURRENT ?
1440                                     ", current" : "",
1441                                     connector->count_modes == 0 ?
1442                                     ", built-in" : "");
1443
1444         return 0;
1445
1446 err_surface:
1447         gbm_surface_destroy(output->surface);
1448 err_free:
1449         wl_list_for_each_safe(drm_mode, next, &output->base.mode_list,
1450                                                         base.link) {
1451                 wl_list_remove(&drm_mode->base.link);
1452                 free(drm_mode);
1453         }
1454
1455         drmModeFreeCrtc(output->original_crtc);
1456         ec->crtc_allocator &= ~(1 << output->crtc_id);
1457         ec->connector_allocator &= ~(1 << output->connector_id);
1458         free(output);
1459
1460         return -1;
1461 }
1462
1463 static void
1464 create_sprites(struct drm_compositor *ec)
1465 {
1466         struct drm_sprite *sprite;
1467         drmModePlaneRes *plane_res;
1468         drmModePlane *plane;
1469         uint32_t i;
1470
1471         plane_res = drmModeGetPlaneResources(ec->drm.fd);
1472         if (!plane_res) {
1473                 weston_log("failed to get plane resources: %s\n",
1474                         strerror(errno));
1475                 return;
1476         }
1477
1478         for (i = 0; i < plane_res->count_planes; i++) {
1479                 plane = drmModeGetPlane(ec->drm.fd, plane_res->planes[i]);
1480                 if (!plane)
1481                         continue;
1482
1483                 sprite = malloc(sizeof(*sprite) + ((sizeof(uint32_t)) *
1484                                                    plane->count_formats));
1485                 if (!sprite) {
1486                         weston_log("%s: out of memory\n",
1487                                 __func__);
1488                         free(plane);
1489                         continue;
1490                 }
1491
1492                 memset(sprite, 0, sizeof *sprite);
1493
1494                 sprite->possible_crtcs = plane->possible_crtcs;
1495                 sprite->plane_id = plane->plane_id;
1496                 sprite->surface = NULL;
1497                 sprite->pending_surface = NULL;
1498                 sprite->fb_id = 0;
1499                 sprite->pending_fb_id = 0;
1500                 sprite->destroy_listener.notify = sprite_handle_buffer_destroy;
1501                 sprite->pending_destroy_listener.notify =
1502                         sprite_handle_pending_buffer_destroy;
1503                 sprite->compositor = ec;
1504                 sprite->count_formats = plane->count_formats;
1505                 memcpy(sprite->formats, plane->formats,
1506                        plane->count_formats * sizeof(plane->formats[0]));
1507                 drmModeFreePlane(plane);
1508
1509                 wl_list_insert(&ec->sprite_list, &sprite->link);
1510         }
1511
1512         free(plane_res->planes);
1513         free(plane_res);
1514 }
1515
1516 static void
1517 destroy_sprites(struct drm_compositor *compositor)
1518 {
1519         struct drm_sprite *sprite, *next;
1520         struct drm_output *output;
1521
1522         output = container_of(compositor->base.output_list.next,
1523                               struct drm_output, base.link);
1524
1525         wl_list_for_each_safe(sprite, next, &compositor->sprite_list, link) {
1526                 drmModeSetPlane(compositor->drm.fd,
1527                                 sprite->plane_id,
1528                                 output->crtc_id, 0, 0,
1529                                 0, 0, 0, 0, 0, 0, 0, 0);
1530                 drmModeRmFB(compositor->drm.fd, sprite->fb_id);
1531                 free(sprite);
1532         }
1533 }
1534
1535 static int
1536 create_outputs(struct drm_compositor *ec, uint32_t option_connector,
1537                struct udev_device *drm_device)
1538 {
1539         drmModeConnector *connector;
1540         drmModeRes *resources;
1541         int i;
1542         int x = 0, y = 0;
1543
1544         resources = drmModeGetResources(ec->drm.fd);
1545         if (!resources) {
1546                 weston_log("drmModeGetResources failed\n");
1547                 return -1;
1548         }
1549
1550         ec->crtcs = calloc(resources->count_crtcs, sizeof(uint32_t));
1551         if (!ec->crtcs) {
1552                 drmModeFreeResources(resources);
1553                 return -1;
1554         }
1555
1556         ec->num_crtcs = resources->count_crtcs;
1557         memcpy(ec->crtcs, resources->crtcs, sizeof(uint32_t) * ec->num_crtcs);
1558
1559         for (i = 0; i < resources->count_connectors; i++) {
1560                 connector = drmModeGetConnector(ec->drm.fd,
1561                                                 resources->connectors[i]);
1562                 if (connector == NULL)
1563                         continue;
1564
1565                 if (connector->connection == DRM_MODE_CONNECTED &&
1566                     (option_connector == 0 ||
1567                      connector->connector_id == option_connector)) {
1568                         if (create_output_for_connector(ec, resources,
1569                                                         connector, x, y,
1570                                                         drm_device) < 0) {
1571                                 drmModeFreeConnector(connector);
1572                                 continue;
1573                         }
1574
1575                         x += container_of(ec->base.output_list.prev,
1576                                           struct weston_output,
1577                                           link)->current->width;
1578                 }
1579
1580                 drmModeFreeConnector(connector);
1581         }
1582
1583         if (wl_list_empty(&ec->base.output_list)) {
1584                 weston_log("No currently active connector found.\n");
1585                 drmModeFreeResources(resources);
1586                 return -1;
1587         }
1588
1589         drmModeFreeResources(resources);
1590
1591         return 0;
1592 }
1593
1594 static void
1595 update_outputs(struct drm_compositor *ec, struct udev_device *drm_device)
1596 {
1597         drmModeConnector *connector;
1598         drmModeRes *resources;
1599         struct drm_output *output, *next;
1600         int x = 0, y = 0;
1601         int x_offset = 0, y_offset = 0;
1602         uint32_t connected = 0, disconnects = 0;
1603         int i;
1604
1605         resources = drmModeGetResources(ec->drm.fd);
1606         if (!resources) {
1607                 weston_log("drmModeGetResources failed\n");
1608                 return;
1609         }
1610
1611         /* collect new connects */
1612         for (i = 0; i < resources->count_connectors; i++) {
1613                 int connector_id = resources->connectors[i];
1614
1615                 connector = drmModeGetConnector(ec->drm.fd, connector_id);
1616                 if (connector == NULL)
1617                         continue;
1618
1619                 if (connector->connection != DRM_MODE_CONNECTED) {
1620                         drmModeFreeConnector(connector);
1621                         continue;
1622                 }
1623
1624                 connected |= (1 << connector_id);
1625
1626                 if (!(ec->connector_allocator & (1 << connector_id))) {
1627                         struct weston_output *last =
1628                                 container_of(ec->base.output_list.prev,
1629                                              struct weston_output, link);
1630
1631                         /* XXX: not yet needed, we die with 0 outputs */
1632                         if (!wl_list_empty(&ec->base.output_list))
1633                                 x = last->x + last->current->width;
1634                         else
1635                                 x = 0;
1636                         y = 0;
1637                         create_output_for_connector(ec, resources,
1638                                                     connector, x, y,
1639                                                     drm_device);
1640                         weston_log("connector %d connected\n", connector_id);
1641
1642                 }
1643                 drmModeFreeConnector(connector);
1644         }
1645         drmModeFreeResources(resources);
1646
1647         disconnects = ec->connector_allocator & ~connected;
1648         if (disconnects) {
1649                 wl_list_for_each_safe(output, next, &ec->base.output_list,
1650                                       base.link) {
1651                         if (x_offset != 0 || y_offset != 0) {
1652                                 weston_output_move(&output->base,
1653                                                  output->base.x - x_offset,
1654                                                  output->base.y - y_offset);
1655                         }
1656
1657                         if (disconnects & (1 << output->connector_id)) {
1658                                 disconnects &= ~(1 << output->connector_id);
1659                                 weston_log("connector %d disconnected\n",
1660                                        output->connector_id);
1661                                 x_offset += output->base.current->width;
1662                                 drm_output_destroy(&output->base);
1663                         }
1664                 }
1665         }
1666
1667         /* FIXME: handle zero outputs, without terminating */   
1668         if (ec->connector_allocator == 0)
1669                 wl_display_terminate(ec->base.wl_display);
1670 }
1671
1672 static int
1673 udev_event_is_hotplug(struct drm_compositor *ec, struct udev_device *device)
1674 {
1675         const char *sysnum;
1676         const char *val;
1677
1678         sysnum = udev_device_get_sysnum(device);
1679         if (!sysnum || atoi(sysnum) != ec->drm.id)
1680                 return 0;
1681
1682         val = udev_device_get_property_value(device, "HOTPLUG");
1683         if (!val)
1684                 return 0;
1685
1686         return strcmp(val, "1") == 0;
1687 }
1688
1689 static int
1690 udev_drm_event(int fd, uint32_t mask, void *data)
1691 {
1692         struct drm_compositor *ec = data;
1693         struct udev_device *event;
1694
1695         event = udev_monitor_receive_device(ec->udev_monitor);
1696
1697         if (udev_event_is_hotplug(ec, event))
1698                 update_outputs(ec, event);
1699
1700         udev_device_unref(event);
1701
1702         return 1;
1703 }
1704
1705 static void
1706 drm_destroy(struct weston_compositor *ec)
1707 {
1708         struct drm_compositor *d = (struct drm_compositor *) ec;
1709         struct weston_seat *seat, *next;
1710
1711         wl_list_for_each_safe(seat, next, &ec->seat_list, link)
1712                 evdev_input_destroy(seat);
1713
1714         wl_event_source_remove(d->udev_drm_source);
1715         wl_event_source_remove(d->drm_source);
1716
1717         weston_compositor_shutdown(ec);
1718
1719         /* Work around crash in egl_dri2.c's dri2_make_current() */
1720         eglMakeCurrent(ec->egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE,
1721                        EGL_NO_CONTEXT);
1722         eglTerminate(ec->egl_display);
1723         eglReleaseThread();
1724
1725         gbm_device_destroy(d->gbm);
1726         destroy_sprites(d);
1727         if (weston_launcher_drm_set_master(&d->base, d->drm.fd, 0) < 0)
1728                 weston_log("failed to drop master: %m\n");
1729         tty_destroy(d->tty);
1730
1731         free(d);
1732 }
1733
1734 static void
1735 drm_compositor_set_modes(struct drm_compositor *compositor)
1736 {
1737         struct drm_output *output;
1738         struct drm_mode *drm_mode;
1739         int ret;
1740
1741         wl_list_for_each(output, &compositor->base.output_list, base.link) {
1742                 drm_mode = (struct drm_mode *) output->base.current;
1743                 ret = drmModeSetCrtc(compositor->drm.fd, output->crtc_id,
1744                                      output->current->fb_id, 0, 0,
1745                                      &output->connector_id, 1,
1746                                      &drm_mode->mode_info);
1747                 if (ret < 0) {
1748                         weston_log(
1749                                 "failed to set mode %dx%d for output at %d,%d: %m\n",
1750                                 drm_mode->base.width, drm_mode->base.height, 
1751                                 output->base.x, output->base.y);
1752                 }
1753         }
1754 }
1755
1756 static void
1757 vt_func(struct weston_compositor *compositor, int event)
1758 {
1759         struct drm_compositor *ec = (struct drm_compositor *) compositor;
1760         struct weston_output *output;
1761         struct weston_seat *seat;
1762         struct drm_sprite *sprite;
1763         struct drm_output *drm_output;
1764
1765         switch (event) {
1766         case TTY_ENTER_VT:
1767                 compositor->focus = 1;
1768                 if (weston_launcher_drm_set_master(&ec->base, ec->drm.fd, 1)) {
1769                         weston_log("failed to set master: %m\n");
1770                         wl_display_terminate(compositor->wl_display);
1771                 }
1772                 compositor->state = ec->prev_state;
1773                 drm_compositor_set_modes(ec);
1774                 weston_compositor_damage_all(compositor);
1775                 wl_list_for_each(seat, &compositor->seat_list, link) {
1776                         evdev_add_devices(ec->udev, seat);
1777                         evdev_enable_udev_monitor(ec->udev, seat);
1778                 }
1779                 break;
1780         case TTY_LEAVE_VT:
1781                 wl_list_for_each(seat, &compositor->seat_list, link) {
1782                         evdev_disable_udev_monitor(seat);
1783                         evdev_remove_devices(seat);
1784                 }
1785
1786                 compositor->focus = 0;
1787                 ec->prev_state = compositor->state;
1788                 compositor->state = WESTON_COMPOSITOR_SLEEPING;
1789
1790                 /* If we have a repaint scheduled (either from a
1791                  * pending pageflip or the idle handler), make sure we
1792                  * cancel that so we don't try to pageflip when we're
1793                  * vt switched away.  The SLEEPING state will prevent
1794                  * further attemps at repainting.  When we switch
1795                  * back, we schedule a repaint, which will process
1796                  * pending frame callbacks. */
1797
1798                 wl_list_for_each(output, &ec->base.output_list, link) {
1799                         output->repaint_needed = 0;
1800                         drm_output_set_cursor(output, NULL);
1801                 }
1802
1803                 drm_output = container_of(ec->base.output_list.next,
1804                                           struct drm_output, base.link);
1805
1806                 wl_list_for_each(sprite, &ec->sprite_list, link)
1807                         drmModeSetPlane(ec->drm.fd,
1808                                         sprite->plane_id,
1809                                         drm_output->crtc_id, 0, 0,
1810                                         0, 0, 0, 0, 0, 0, 0, 0);
1811
1812                 if (weston_launcher_drm_set_master(&ec->base, ec->drm.fd, 0) < 0)
1813                         weston_log("failed to drop master: %m\n");
1814
1815                 break;
1816         };
1817 }
1818
1819 static void
1820 switch_vt_binding(struct wl_seat *seat, uint32_t time, uint32_t key, void *data)
1821 {
1822         struct drm_compositor *ec = data;
1823
1824         tty_activate_vt(ec->tty, key - KEY_F1 + 1);
1825 }
1826
1827 static const char default_seat[] = "seat0";
1828
1829 static struct weston_compositor *
1830 drm_compositor_create(struct wl_display *display,
1831                       int connector, const char *seat, int tty,
1832                       int argc, char *argv[], const char *config_file)
1833 {
1834         struct drm_compositor *ec;
1835         struct udev_enumerate *e;
1836         struct udev_list_entry *entry;
1837         struct udev_device *device, *drm_device;
1838         const char *path, *device_seat;
1839         struct wl_event_loop *loop;
1840         struct weston_seat *weston_seat, *next;
1841         uint32_t key;
1842
1843         weston_log("initializing drm backend\n");
1844
1845         ec = malloc(sizeof *ec);
1846         if (ec == NULL)
1847                 return NULL;
1848         memset(ec, 0, sizeof *ec);
1849
1850         if (weston_compositor_init(&ec->base, display, argc, argv,
1851                                    config_file) < 0) {
1852                 weston_log("weston_compositor_init failed\n");
1853                 goto err_base;
1854         }
1855
1856         ec->udev = udev_new();
1857         if (ec->udev == NULL) {
1858                 weston_log("failed to initialize udev context\n");
1859                 goto err_compositor;
1860         }
1861
1862         ec->base.wl_display = display;
1863         ec->tty = tty_create(&ec->base, vt_func, tty);
1864         if (!ec->tty) {
1865                 weston_log("failed to initialize tty\n");
1866                 goto err_udev;
1867         }
1868
1869         e = udev_enumerate_new(ec->udev);
1870         udev_enumerate_add_match_subsystem(e, "drm");
1871         udev_enumerate_add_match_sysname(e, "card[0-9]*");
1872
1873         udev_enumerate_scan_devices(e);
1874         drm_device = NULL;
1875         udev_list_entry_foreach(entry, udev_enumerate_get_list_entry(e)) {
1876                 path = udev_list_entry_get_name(entry);
1877                 device = udev_device_new_from_syspath(ec->udev, path);
1878                 device_seat =
1879                         udev_device_get_property_value(device, "ID_SEAT");
1880                 if (!device_seat)
1881                         device_seat = default_seat;
1882                 if (strcmp(device_seat, seat) == 0) {
1883                         drm_device = device;
1884                         break;
1885                 }
1886                 udev_device_unref(device);
1887         }
1888
1889         if (drm_device == NULL) {
1890                 weston_log("no drm device found\n");
1891                 goto err_udev_enum;
1892         }
1893
1894         if (init_egl(ec, drm_device) < 0) {
1895                 weston_log("failed to initialize egl\n");
1896                 goto err_udev_dev;
1897         }
1898
1899         ec->base.destroy = drm_destroy;
1900
1901         ec->base.focus = 1;
1902
1903         ec->prev_state = WESTON_COMPOSITOR_ACTIVE;
1904
1905         if (weston_compositor_init_gl(&ec->base) < 0)
1906                 goto err_egl;
1907
1908         for (key = KEY_F1; key < KEY_F9; key++)
1909                 weston_compositor_add_key_binding(&ec->base, key,
1910                                                   MODIFIER_CTRL | MODIFIER_ALT,
1911                                                   switch_vt_binding, ec);
1912
1913         wl_list_init(&ec->sprite_list);
1914         create_sprites(ec);
1915
1916         if (create_outputs(ec, connector, drm_device) < 0) {
1917                 weston_log("failed to create output for %s\n", path);
1918                 goto err_sprite;
1919         }
1920
1921         path = NULL;
1922
1923         evdev_input_create(&ec->base, ec->udev, seat);
1924
1925         loop = wl_display_get_event_loop(ec->base.wl_display);
1926         ec->drm_source =
1927                 wl_event_loop_add_fd(loop, ec->drm.fd,
1928                                      WL_EVENT_READABLE, on_drm_input, ec);
1929
1930         ec->udev_monitor = udev_monitor_new_from_netlink(ec->udev, "udev");
1931         if (ec->udev_monitor == NULL) {
1932                 weston_log("failed to intialize udev monitor\n");
1933                 goto err_drm_source;
1934         }
1935         udev_monitor_filter_add_match_subsystem_devtype(ec->udev_monitor,
1936                                                         "drm", NULL);
1937         ec->udev_drm_source =
1938                 wl_event_loop_add_fd(loop,
1939                                      udev_monitor_get_fd(ec->udev_monitor),
1940                                      WL_EVENT_READABLE, udev_drm_event, ec);
1941
1942         if (udev_monitor_enable_receiving(ec->udev_monitor) < 0) {
1943                 weston_log("failed to enable udev-monitor receiving\n");
1944                 goto err_udev_monitor;
1945         }
1946
1947         udev_device_unref(drm_device);
1948         udev_enumerate_unref(e);
1949
1950         return &ec->base;
1951
1952 err_udev_monitor:
1953         wl_event_source_remove(ec->udev_drm_source);
1954         udev_monitor_unref(ec->udev_monitor);
1955 err_drm_source:
1956         wl_event_source_remove(ec->drm_source);
1957         wl_list_for_each_safe(weston_seat, next, &ec->base.seat_list, link)
1958                 evdev_input_destroy(weston_seat);
1959 err_sprite:
1960         destroy_sprites(ec);
1961 err_egl:
1962         eglMakeCurrent(ec->base.egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE,
1963                        EGL_NO_CONTEXT);
1964         eglTerminate(ec->base.egl_display);
1965         eglReleaseThread();
1966         gbm_device_destroy(ec->gbm);
1967 err_udev_dev:
1968         udev_device_unref(drm_device);
1969 err_udev_enum:
1970         udev_enumerate_unref(e);
1971         tty_destroy(ec->tty);
1972 err_udev:
1973         udev_unref(ec->udev);
1974 err_compositor:
1975         weston_compositor_shutdown(&ec->base);
1976 err_base:
1977         free(ec);
1978         return NULL;
1979 }
1980
1981 WL_EXPORT struct weston_compositor *
1982 backend_init(struct wl_display *display, int argc, char *argv[],
1983              const char *config_file)
1984 {
1985         int connector = 0, tty = 0;
1986         const char *seat = default_seat;
1987
1988         const struct weston_option drm_options[] = {
1989                 { WESTON_OPTION_INTEGER, "connector", 0, &connector },
1990                 { WESTON_OPTION_STRING, "seat", 0, &seat },
1991                 { WESTON_OPTION_INTEGER, "tty", 0, &tty },
1992                 { WESTON_OPTION_BOOLEAN, "current-mode", 0, &option_current_mode },
1993         };
1994
1995         parse_options(drm_options, ARRAY_LENGTH(drm_options), argc, argv);
1996
1997         return drm_compositor_create(display, connector, seat, tty, argc, argv,
1998                                      config_file);
1999 }