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