OSDN Git Service

drm_hwcomposer: Do not close gem handle if queued
[android-x86/external-drm_hwcomposer.git] / hwcomposer.cpp
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #define LOG_TAG "hwcomposer-drm"
18
19 #include <fcntl.h>
20 #include <errno.h>
21 #include <list>
22 #include <sys/param.h>
23 #include <sys/resource.h>
24 #include <pthread.h>
25
26 #include <cutils/log.h>
27
28 #include <xf86drm.h>
29 #include <xf86drmMode.h>
30
31 #include <hardware/hardware.h>
32 #include <hardware/hwcomposer.h>
33
34 #include <cutils/properties.h>
35 #include <sync/sync.h>
36 #include <sw_sync.h>
37
38 #include "drm_hwcomposer.h"
39
40 #define ARRAY_SIZE(arr) (int)(sizeof(arr) / sizeof((arr)[0]))
41
42 #define HWCOMPOSER_DRM_DEVICE "/dev/dri/card0"
43 #define MAX_NUM_DISPLAYS 3
44 #define UM_PER_INCH 25400
45
46 static const uint32_t panel_types[] = {
47         DRM_MODE_CONNECTOR_LVDS,
48         DRM_MODE_CONNECTOR_eDP,
49         DRM_MODE_CONNECTOR_DSI,
50 };
51
52 struct hwc_worker {
53         pthread_t thread;
54         pthread_mutex_t lock;
55         pthread_cond_t cond;
56         bool exit;
57 };
58
59 struct hwc_drm_display {
60         struct hwc_context_t *ctx;
61         int display;
62
63         uint32_t connector_id;
64
65         drmModeModeInfoPtr configs;
66         uint32_t num_configs;
67
68         drmModeModeInfo active_mode;
69         uint32_t active_crtc;
70         int active_pipe;
71         bool initial_modeset_required;
72
73         struct hwc_worker set_worker;
74
75         std::list<struct hwc_drm_bo> buf_queue;
76         struct hwc_drm_bo front;
77
78         int timeline_fd;
79         unsigned timeline_next;
80
81         struct hwc_worker vsync_worker;
82         bool enable_vsync_events;
83 };
84
85 struct hwc_context_t {
86         hwc_composer_device_1_t device;
87
88         int fd;
89
90         hwc_procs_t const *procs;
91         struct hwc_import_context *import_ctx;
92
93         struct hwc_drm_display displays[MAX_NUM_DISPLAYS];
94         int num_displays;
95 };
96
97 static int hwc_get_drm_display(struct hwc_context_t *ctx, int display,
98                         struct hwc_drm_display **hd)
99 {
100         if (display >= MAX_NUM_DISPLAYS) {
101                 ALOGE("Requested display is out-of-bounds %d %d", display,
102                         MAX_NUM_DISPLAYS);
103                 return -EINVAL;
104         }
105         *hd = &ctx->displays[display];
106         return 0;
107 }
108
109 static int hwc_prepare_layer(hwc_layer_1_t *layer)
110 {
111         /* TODO: We can't handle background right now, defer to sufaceFlinger */
112         if (layer->compositionType == HWC_BACKGROUND) {
113                 layer->compositionType = HWC_FRAMEBUFFER;
114                 ALOGV("Can't handle background layers yet");
115
116         /* TODO: Support sideband compositions */
117         } else if (layer->compositionType == HWC_SIDEBAND) {
118                 layer->compositionType = HWC_FRAMEBUFFER;
119                 ALOGV("Can't handle sideband content yet");
120         }
121
122         layer->hints = 0;
123
124         /* TODO: Handle cursor by setting compositionType=HWC_CURSOR_OVERLAY */
125         if (layer->flags & HWC_IS_CURSOR_LAYER) {
126                 ALOGV("Can't handle async cursors yet");
127         }
128
129         /* TODO: Handle transformations */
130         if (layer->transform) {
131                 ALOGV("Can't handle transformations yet");
132         }
133
134         /* TODO: Handle blending & plane alpha*/
135         if (layer->blending == HWC_BLENDING_PREMULT ||
136             layer->blending == HWC_BLENDING_COVERAGE) {
137                 ALOGV("Can't handle blending yet");
138         }
139
140         /* TODO: Handle cropping & scaling */
141
142         return 0;
143 }
144
145 static int hwc_prepare(hwc_composer_device_1_t */* dev */, size_t num_displays,
146                         hwc_display_contents_1_t** display_contents)
147 {
148         int ret = 0, i, j;
149
150         /* TODO: Check flags for HWC_GEOMETRY_CHANGED */
151
152         for (i = 0; i < (int)num_displays && i < MAX_NUM_DISPLAYS; i++) {
153
154                 if (!display_contents[i])
155                         continue;
156
157                 for (j = 0; j < (int)display_contents[i]->numHwLayers; j++) {
158                         ret = hwc_prepare_layer(
159                                         &display_contents[i]->hwLayers[j]);
160                         if (ret) {
161                                 ALOGE("Failed to prepare layer %d:%d", j, i);
162                                 return ret;
163                         }
164                 }
165         }
166
167         return ret;
168 }
169
170 static bool hwc_mode_is_equal(drmModeModeInfoPtr a, drmModeModeInfoPtr b)
171 {
172         return a->clock == b->clock &&
173                 a->hdisplay == b->hdisplay &&
174                 a->hsync_start == b->hsync_start &&
175                 a->hsync_end == b->hsync_end &&
176                 a->htotal == b->htotal &&
177                 a->hskew == b->hskew &&
178                 a->vdisplay == b->vdisplay &&
179                 a->vsync_start == b->vsync_start &&
180                 a->vsync_end == b->vsync_end &&
181                 a->vtotal == b->vtotal &&
182                 a->vscan == b->vscan &&
183                 a->vrefresh == b->vrefresh &&
184                 a->flags == b->flags &&
185                 a->type == b->type &&
186                 !strcmp(a->name, b->name);
187 }
188
189 static int hwc_modeset_required(struct hwc_drm_display *hd,
190                         bool *modeset_required)
191 {
192         drmModeCrtcPtr crtc;
193         drmModeModeInfoPtr m;
194
195         if (hd->initial_modeset_required) {
196                 *modeset_required = true;
197                 hd->initial_modeset_required = false;
198                 return 0;
199         }
200
201         crtc = drmModeGetCrtc(hd->ctx->fd, hd->active_crtc);
202         if (!crtc) {
203                 ALOGE("Failed to get crtc for display %d", hd->display);
204                 return -ENODEV;
205         }
206
207         m = &hd->active_mode;
208
209         /* Do a modeset if we haven't done one, or the mode has changed */
210         if (!crtc->mode_valid || !hwc_mode_is_equal(m, &crtc->mode))
211                 *modeset_required = true;
212         else
213                 *modeset_required = false;
214
215         drmModeFreeCrtc(crtc);
216
217         return 0;
218 }
219
220 static void hwc_flip_handler(int /* fd */, unsigned int /* sequence */,
221                 unsigned int /* tv_sec */, unsigned int /* tv_usec */,
222                 void */* user_data */)
223 {
224 }
225
226 static int hwc_flip(struct hwc_drm_display *hd, struct hwc_drm_bo *buf)
227 {
228         fd_set fds;
229         drmEventContext event_context;
230         int ret;
231         bool modeset_required;
232
233         ret = hwc_modeset_required(hd, &modeset_required);
234         if (ret) {
235                 ALOGE("Failed to determine if modeset is required %d", ret);
236                 return ret;
237         }
238         if (modeset_required) {
239                 ret = drmModeSetCrtc(hd->ctx->fd, hd->active_crtc, buf->fb_id,
240                         0, 0, &hd->connector_id, 1,
241                         &hd->active_mode);
242                 if (ret) {
243                         ALOGE("Modeset failed for crtc %d",
244                                 hd->active_crtc);
245                         return ret;
246                 }
247                 return 0;
248         }
249
250         FD_ZERO(&fds);
251         FD_SET(hd->ctx->fd, &fds);
252
253         event_context.version = DRM_EVENT_CONTEXT_VERSION;
254         event_context.page_flip_handler = hwc_flip_handler;
255
256         ret = drmModePageFlip(hd->ctx->fd, hd->active_crtc, buf->fb_id,
257                         DRM_MODE_PAGE_FLIP_EVENT, hd);
258         if (ret) {
259                 ALOGE("Failed to flip buffer for crtc %d",
260                         hd->active_crtc);
261                 return ret;
262         }
263
264         do {
265                 ret = select(hd->ctx->fd + 1, &fds, NULL, NULL, NULL);
266         } while (ret == -1 && errno == EINTR);
267
268         if (ret != 1) {
269                 ALOGE("Failed waiting for flip to complete\n");
270                 return -EINVAL;
271         }
272         drmHandleEvent(hd->ctx->fd, &event_context);
273
274         return 0;
275 }
276
277 static int hwc_wait_and_set(struct hwc_drm_display *hd,
278                         struct hwc_drm_bo *buf)
279 {
280         struct drm_gem_close args;
281         int ret, i;
282
283         if (buf->acquire_fence_fd >= 0) {
284                 ret = sync_wait(buf->acquire_fence_fd, -1);
285                 close(buf->acquire_fence_fd);
286                 buf->acquire_fence_fd = -1;
287                 if (ret) {
288                         ALOGE("Failed to wait for acquire %d", ret);
289                         return ret;
290                 }
291         }
292
293         ret = drmModeAddFB2(hd->ctx->fd, buf->width,
294                 buf->height, buf->format, buf->gem_handles, buf->pitches,
295                 buf->offsets, &buf->fb_id, 0);
296         if (ret) {
297                 ALOGE("could not create drm fb %d", ret);
298                 return ret;
299         }
300
301         ret = hwc_flip(hd, buf);
302         if (ret) {
303                 ALOGE("Failed to perform flip\n");
304                 return ret;
305         }
306
307         if (hd->front.fb_id) {
308                 ret = drmModeRmFB(hd->ctx->fd, hd->front.fb_id);
309                 if (ret) {
310                         ALOGE("Failed to rm fb from front %d", ret);
311                         return ret;
312                 }
313         }
314
315         memset(&args, 0, sizeof(args));
316         for (i = 0; i < ARRAY_SIZE(hd->front.gem_handles); i++) {
317                 if (!hd->front.gem_handles[i])
318                         continue;
319
320                 /* check for duplicate handle in buf_queue */
321                 bool found = false;
322                 std::list<struct hwc_drm_bo>::iterator bi;
323
324                 ret = pthread_mutex_lock(&hd->set_worker.lock);
325                 if (ret) {
326                         ALOGE("Failed to lock set lock in wait_and_set() %d", ret);
327                         continue;
328                 }
329
330                 found = false;
331                 for (bi = hd->buf_queue.begin();
332                      bi != hd->buf_queue.end();
333                      ++bi)
334                         for (int j = 0; j < ARRAY_SIZE(bi->gem_handles); j++)
335                                 if (hd->front.gem_handles[i] == bi->gem_handles[j])
336                                         found = true;
337
338                 if (!found) {
339                         args.handle = hd->front.gem_handles[i];
340                         drmIoctl(hd->ctx->fd, DRM_IOCTL_GEM_CLOSE, &args);
341                 }
342                 if (pthread_mutex_unlock(&hd->set_worker.lock))
343                         ALOGE("Failed to unlock set lock in wait_and_set() %d", ret);
344         }
345         hd->front = *buf;
346
347         return ret;
348 }
349
350 static void *hwc_set_worker(void *arg)
351 {
352         struct hwc_drm_display *hd = (struct hwc_drm_display *)arg;
353         int ret;
354
355         setpriority(PRIO_PROCESS, 0, HAL_PRIORITY_URGENT_DISPLAY);
356
357         do {
358                 struct hwc_drm_bo buf;
359
360                 ret = pthread_mutex_lock(&hd->set_worker.lock);
361                 if (ret) {
362                         ALOGE("Failed to lock set lock %d", ret);
363                         return NULL;
364                 }
365
366                 if (hd->set_worker.exit)
367                         goto out;
368
369                 if (hd->buf_queue.empty()) {
370                         ret = pthread_cond_wait(&hd->set_worker.cond,
371                                         &hd->set_worker.lock);
372                         if (ret) {
373                                 ALOGE("Failed to wait on condition %d", ret);
374                                 goto out;
375                         }
376                 }
377
378                 buf = hd->buf_queue.front();
379                 hd->buf_queue.pop_front();
380
381                 ret = pthread_mutex_unlock(&hd->set_worker.lock);
382                 if (ret) {
383                         ALOGE("Failed to unlock set lock %d", ret);
384                         return NULL;
385                 }
386
387                 ret = hwc_wait_and_set(hd, &buf);
388                 if (ret)
389                         ALOGE("Failed to wait and set %d", ret);
390
391                 ret = sw_sync_timeline_inc(hd->timeline_fd, 1);
392                 if (ret)
393                         ALOGE("Failed to increment sync timeline %d", ret);
394         } while (true);
395
396 out:
397         ret = pthread_mutex_unlock(&hd->set_worker.lock);
398         if (ret)
399                 ALOGE("Failed to unlock set lock while exiting %d", ret);
400
401         return NULL;
402 }
403
404 static int hwc_set_display(hwc_context_t *ctx, int display,
405                         hwc_display_contents_1_t* display_contents)
406 {
407         struct hwc_drm_display *hd = NULL;
408         hwc_layer_1_t *layer = NULL;
409         struct hwc_drm_bo buf;
410         int ret, i;
411         uint32_t fb_id;
412
413         memset(&buf, 0, sizeof(buf));
414
415         ret = hwc_get_drm_display(ctx, display, &hd);
416         if (ret)
417                 goto out;
418
419         if (!hd->active_crtc) {
420                 ALOGE("There is no active crtc for display %d", display);
421                 ret = -ENOENT;
422                 goto out;
423         }
424
425         /*
426          * TODO: We can only support one hw layer atm, so choose either the
427          * first one or the framebuffer target.
428          */
429         if (!display_contents->numHwLayers) {
430                 return 0;
431         } else if (display_contents->numHwLayers == 1) {
432                 layer = &display_contents->hwLayers[0];
433         } else {
434                 for (i = 0; i < (int)display_contents->numHwLayers; i++) {
435                         layer = &display_contents->hwLayers[i];
436                         if (layer->compositionType == HWC_FRAMEBUFFER_TARGET)
437                                 break;
438                 }
439                 if (i == (int)display_contents->numHwLayers) {
440                         ALOGE("Could not find a suitable layer for display %d",
441                                 display);
442                 }
443         }
444
445
446         ret = pthread_mutex_lock(&hd->set_worker.lock);
447         if (ret) {
448                 ALOGE("Failed to lock set lock in set() %d", ret);
449                 goto out;
450         }
451
452         ret = hwc_create_bo_from_import(ctx->fd, ctx->import_ctx, layer->handle,
453                                 &buf);
454         if (ret) {
455                 ALOGE("Failed to import handle to drm bo %d", ret);
456                 goto out;
457         }
458         buf.acquire_fence_fd = layer->acquireFenceFd;
459         layer->acquireFenceFd = -1;
460
461         /*
462          * TODO: Retire and release can use the same sync point here b/c hwc is
463          * restricted to one layer. Once that is no longer true, this will need
464          * to change
465          */
466         hd->timeline_next++;
467         display_contents->retireFenceFd = sw_sync_fence_create(hd->timeline_fd,
468                                         "drm_hwc_retire", hd->timeline_next);
469         layer->releaseFenceFd = sw_sync_fence_create(hd->timeline_fd,
470                                         "drm_hwc_release", hd->timeline_next);
471         hd->buf_queue.push_back(buf);
472
473         ret = pthread_cond_signal(&hd->set_worker.cond);
474         if (ret)
475                 ALOGE("Failed to signal set worker %d", ret);
476
477         if (pthread_mutex_unlock(&hd->set_worker.lock))
478                 ALOGE("Failed to unlock set lock in set()");
479
480 out:
481         /* Close input fences. */
482         for (i = 0; i < (int)display_contents->numHwLayers; i++) {
483                 layer = &display_contents->hwLayers[i];
484                 if (layer->acquireFenceFd >= 0) {
485                         close(layer->acquireFenceFd);
486                         layer->acquireFenceFd = -1;
487                 }
488         }
489         if (display_contents->outbufAcquireFenceFd >= 0) {
490                 close(display_contents->outbufAcquireFenceFd);
491                 display_contents->outbufAcquireFenceFd = -1;
492         }
493
494         return ret;
495 }
496
497 static int hwc_set(hwc_composer_device_1_t *dev, size_t num_displays,
498                         hwc_display_contents_1_t** display_contents)
499 {
500         struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
501         int ret = 0, i;
502
503         for (i = 0; i < (int)num_displays && i < MAX_NUM_DISPLAYS; i++) {
504                 if (display_contents[i])
505                         ret = hwc_set_display(ctx, i, display_contents[i]);
506         }
507
508         return ret;
509 }
510
511 static int hwc_wait_for_vsync(struct hwc_drm_display *hd)
512 {
513         drmVBlank vblank;
514         int ret;
515         uint32_t high_crtc;
516         int64_t timestamp;
517
518         if (hd->active_pipe == -1)
519                 return -EINVAL;
520
521         memset(&vblank, 0, sizeof(vblank));
522
523         high_crtc = (hd->active_pipe << DRM_VBLANK_HIGH_CRTC_SHIFT);
524         vblank.request.type = (drmVBlankSeqType)(DRM_VBLANK_RELATIVE |
525                 (high_crtc & DRM_VBLANK_HIGH_CRTC_MASK));
526         vblank.request.sequence = 1;
527
528         ret = drmWaitVBlank(hd->ctx->fd, &vblank);
529         if (ret) {
530                 ALOGE("Failed to wait for vblank %d", ret);
531                 return ret;
532         }
533
534         if (hd->ctx->procs->vsync) {
535                 timestamp = vblank.reply.tval_sec * 1000 * 1000 * 1000 +
536                         vblank.reply.tval_usec * 1000;
537                 hd->ctx->procs->vsync(hd->ctx->procs, hd->display, timestamp);
538         }
539
540         return 0;
541 }
542
543 static void *hwc_vsync_worker(void *arg)
544 {
545         struct hwc_drm_display *hd = (struct hwc_drm_display *)arg;
546         struct hwc_worker *w = &hd->vsync_worker;
547         int ret;
548
549         setpriority(PRIO_PROCESS, 0, HAL_PRIORITY_URGENT_DISPLAY);
550
551         do {
552                 ret = pthread_mutex_lock(&w->lock);
553                 if (ret) {
554                         ALOGE("Failed to lock vsync lock %d", ret);
555                         return NULL;
556                 }
557
558                 if (hd->active_pipe == -1) {
559                         ALOGE("Pipe is no longer active, disable events");
560                         hd->enable_vsync_events = false;
561                 }
562
563                 if (!hd->enable_vsync_events) {
564                         ret = pthread_cond_wait(&w->cond, &w->lock);
565                         if (ret) {
566                                 ALOGE("Failed to wait on vsync cond %d", ret);
567                                 break;
568                         }
569                 }
570
571                 if (w->exit)
572                         break;
573
574                 ret = pthread_mutex_unlock(&w->lock);
575                 if (ret) {
576                         ALOGE("Failed to unlock vsync lock %d", ret);
577                         return NULL;
578                 }
579
580                 if (!hd->enable_vsync_events)
581                         continue;
582
583                 ret = hwc_wait_for_vsync(hd);
584                 if (ret)
585                         ALOGE("Failed to wait for vsync %d", ret);
586
587         } while (true);
588
589 out:
590         ret = pthread_mutex_unlock(&hd->set_worker.lock);
591         if (ret)
592                 ALOGE("Failed to unlock set lock while exiting %d", ret);
593
594         return NULL;
595 }
596
597 static int hwc_event_control(struct hwc_composer_device_1* dev, int display,
598                         int event, int enabled)
599 {
600         struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
601         struct hwc_drm_display *hd = NULL;
602         int ret;
603
604         ret = hwc_get_drm_display(ctx, display, &hd);
605         if (ret)
606                 return ret;
607
608         if (event != HWC_EVENT_VSYNC || (enabled != 0 && enabled != 1))
609                 return -EINVAL;
610
611         if (hd->active_pipe == -1) {
612                 ALOGD("Can't service events for display %d, no pipe", display);
613                 return -EINVAL;
614         }
615
616         ret = pthread_mutex_lock(&hd->vsync_worker.lock);
617         if (ret) {
618                 ALOGE("Failed to lock vsync lock %d", ret);
619                 return ret;
620         }
621
622         hd->enable_vsync_events = !!enabled;
623
624         ret = pthread_cond_signal(&hd->vsync_worker.cond);
625         if (ret) {
626                 ALOGE("Failed to signal vsync thread %d", ret);
627                 goto out;
628         }
629
630         ret = pthread_mutex_unlock(&hd->vsync_worker.lock);
631         if (ret) {
632                 ALOGE("Failed to unlock vsync lock %d", ret);
633                 return ret;
634         }
635
636         return 0;
637
638 out:
639         if (pthread_mutex_unlock(&hd->vsync_worker.lock))
640                 ALOGE("Failed to unlock vsync worker in error path");
641
642         return ret;
643 }
644
645 static int hwc_set_power_mode(struct hwc_composer_device_1* dev, int display,
646                         int mode)
647 {
648         struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
649         struct hwc_drm_display *hd = NULL;
650         drmModeConnectorPtr c;
651         int ret, i;
652         uint32_t dpms_prop = 0;
653         uint64_t dpms_value = 0;
654
655         ret = hwc_get_drm_display(ctx, display, &hd);
656         if (ret)
657                 return ret;
658
659         c = drmModeGetConnector(ctx->fd, hd->connector_id);
660         if (!c) {
661                 ALOGE("Failed to get connector %d", display);
662                 return -ENODEV;
663         }
664
665         for (i = 0; !dpms_prop && i < c->count_props; i++) {
666                 drmModePropertyPtr p;
667
668                 p = drmModeGetProperty(ctx->fd, c->props[i]);
669                 if (!p)
670                         continue;
671
672                 if (!strcmp(p->name, "DPMS"))
673                         dpms_prop = c->props[i];
674
675                 drmModeFreeProperty(p);
676         }
677         if (!dpms_prop) {
678                 ALOGE("Failed to get DPMS property from display %d", display);
679                 ret = -ENOENT;
680                 goto out;
681         }
682
683         switch(mode) {
684         case HWC_POWER_MODE_OFF:
685                 dpms_value = DRM_MODE_DPMS_OFF;
686                 break;
687
688         /* We can't support dozing right now, so go full on */
689         case HWC_POWER_MODE_DOZE:
690         case HWC_POWER_MODE_DOZE_SUSPEND:
691         case HWC_POWER_MODE_NORMAL:
692                 dpms_value = DRM_MODE_DPMS_ON;
693                 break;
694         };
695
696         ret = drmModeConnectorSetProperty(ctx->fd, c->connector_id,
697                         dpms_prop, dpms_value);
698         if (ret) {
699                 ALOGE("Failed to set DPMS property for display %d", display);
700                 goto out;
701         }
702
703 out:
704         drmModeFreeConnector(c);
705         return ret;
706 }
707
708 static int hwc_query(struct hwc_composer_device_1 */* dev */, int what,
709                         int *value)
710 {
711         switch(what) {
712         case HWC_BACKGROUND_LAYER_SUPPORTED:
713                 *value = 0; /* TODO: We should do this */
714                 break;
715         case HWC_VSYNC_PERIOD:
716                 ALOGW("Query for deprecated vsync value, returning 60Hz");
717                 *value = 1000 * 1000 * 1000 / 60;
718                 break;
719         case HWC_DISPLAY_TYPES_SUPPORTED:
720                 *value = HWC_DISPLAY_PRIMARY | HWC_DISPLAY_EXTERNAL;
721                 break;
722         }
723         return 0;
724 }
725
726 static void hwc_register_procs(struct hwc_composer_device_1* dev,
727                         hwc_procs_t const* procs)
728 {
729         struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
730
731         ctx->procs = procs;
732 }
733
734 static int hwc_get_display_configs(struct hwc_composer_device_1* dev,
735                         int display, uint32_t* configs, size_t* numConfigs)
736 {
737         struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
738         struct hwc_drm_display *hd = NULL;
739         drmModeConnectorPtr c;
740         int ret = 0, i;
741
742         if (!*numConfigs)
743                 return 0;
744
745         ret = hwc_get_drm_display(ctx, display, &hd);
746         if (ret)
747                 return ret;
748
749         c = drmModeGetConnector(ctx->fd, hd->connector_id);
750         if (!c) {
751                 ALOGE("Failed to get connector %d", display);
752                 return -ENODEV;
753         }
754
755         if (hd->configs) {
756                 free(hd->configs);
757                 hd->configs = NULL;
758         }
759
760         if (c->connection == DRM_MODE_DISCONNECTED) {
761                 ret = -ENODEV;
762                 goto out;
763         }
764
765         hd->configs = (drmModeModeInfoPtr)calloc(c->count_modes,
766                                         sizeof(*hd->configs));
767         if (!hd->configs) {
768                 ALOGE("Failed to allocate config list for display %d", display);
769                 ret = -ENOMEM;
770                 hd->num_configs = 0;
771                 goto out;
772         }
773
774         for (i = 0; i < c->count_modes; i++) {
775                 drmModeModeInfoPtr m = &hd->configs[i];
776
777                 memcpy(m, &c->modes[i], sizeof(*m));
778
779                 if (i < (int)*numConfigs)
780                         configs[i] = i;
781         }
782
783         hd->num_configs = c->count_modes;
784         *numConfigs = MIN(c->count_modes, *numConfigs);
785
786 out:
787         drmModeFreeConnector(c);
788         return ret;
789 }
790
791 static int hwc_check_config_valid(struct hwc_context_t *ctx,
792                         drmModeConnectorPtr connector, int display,
793                         int config_idx)
794 {
795         struct hwc_drm_display *hd = NULL;
796         drmModeModeInfoPtr m = NULL;
797         int ret = 0, i;
798
799         ret = hwc_get_drm_display(ctx, display, &hd);
800         if (ret)
801                 return ret;
802
803         /* Make sure the requested config is still valid for the display */
804         for (i = 0; i < connector->count_modes; i++) {
805                 if (hwc_mode_is_equal(&connector->modes[i],
806                                 &hd->configs[config_idx])) {
807                         m = &hd->configs[config_idx];
808                         break;
809                 }
810         }
811         if (!m)
812                 return -ENOENT;
813
814         return 0;
815 }
816
817 static int hwc_get_display_attributes(struct hwc_composer_device_1* dev,
818                 int display, uint32_t config, const uint32_t* attributes,
819                 int32_t* values)
820 {
821         struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
822         struct hwc_drm_display *hd = NULL;
823         drmModeConnectorPtr c;
824         drmModeModeInfoPtr m;
825         int ret, i;
826
827         ret = hwc_get_drm_display(ctx, display, &hd);
828         if (ret)
829                 return ret;
830
831         if (config >= hd->num_configs) {
832                 ALOGE("Requested config is out-of-bounds %d %d", config,
833                         hd->num_configs);
834                 return -EINVAL;
835         }
836
837         c = drmModeGetConnector(ctx->fd, hd->connector_id);
838         if (!c) {
839                 ALOGE("Failed to get connector %d", display);
840                 return -ENODEV;
841         }
842
843         ret = hwc_check_config_valid(ctx, c, display, (int)config);
844         if (ret) {
845                 ALOGE("Provided config is no longer valid %u", config);
846                 goto out;
847         }
848
849         m = &hd->configs[config];
850         for (i = 0; attributes[i] != HWC_DISPLAY_NO_ATTRIBUTE; i++) {
851                 switch(attributes[i]) {
852                 case HWC_DISPLAY_VSYNC_PERIOD:
853                         values[i] = 1000 * 1000 * 1000 / m->vrefresh;
854                         break;
855                 case HWC_DISPLAY_WIDTH:
856                         values[i] = m->hdisplay;
857                         break;
858                 case HWC_DISPLAY_HEIGHT:
859                         values[i] = m->vdisplay;
860                         break;
861                 case HWC_DISPLAY_DPI_X:
862                         /* Dots per 1000 inches */
863                         values[i] = c->mmWidth ?
864                                 (m->hdisplay * UM_PER_INCH) / c->mmWidth : 0;
865                         break;
866                 case HWC_DISPLAY_DPI_Y:
867                         /* Dots per 1000 inches */
868                         values[i] = c->mmHeight ?
869                                 (m->vdisplay * UM_PER_INCH) / c->mmHeight : 0;
870                         break;
871                 }
872         }
873
874 out:
875         drmModeFreeConnector(c);
876         return ret;
877 }
878
879 static int hwc_get_active_config(struct hwc_composer_device_1* dev, int display)
880 {
881         struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
882         struct hwc_drm_display *hd = NULL;
883         int ret, i, index = -1;
884
885         ret = hwc_get_drm_display(ctx, display, &hd);
886         if (ret)
887                 return ret;
888
889         /* Find the current mode in the config list */
890         for (i = 0; i < (int)hd->num_configs; i++) {
891                 if (hwc_mode_is_equal(&hd->configs[i], &hd->active_mode)) {
892                         index = i;
893                         break;
894                 }
895         }
896
897         return index;
898 }
899
900 static bool hwc_crtc_is_bound(struct hwc_context_t *ctx, uint32_t crtc_id)
901 {
902         int i;
903
904         for (i = 0; i < MAX_NUM_DISPLAYS; i++) {
905                 if (ctx->displays[i].active_crtc == crtc_id)
906                         return true;
907         }
908         return false;
909 }
910
911 static int hwc_try_encoder(struct hwc_context_t *ctx, drmModeResPtr r,
912                         uint32_t encoder_id, uint32_t *crtc_id)
913 {
914         drmModeEncoderPtr e;
915         int ret, i;
916
917         e = drmModeGetEncoder(ctx->fd, encoder_id);
918         if (!e) {
919                 ALOGE("Failed to get encoder for connector %d", encoder_id);
920                 return -ENODEV;
921         }
922
923         /* First try to use the currently-bound crtc */
924         if (e->crtc_id) {
925                 if (!hwc_crtc_is_bound(ctx, e->crtc_id)) {
926                         *crtc_id = e->crtc_id;
927                         ret = 0;
928                         goto out;
929                 }
930         }
931
932         /* Try to find a possible crtc which will work */
933         for (i = 0; i < r->count_crtcs; i++) {
934                 if (!(e->possible_crtcs & (1 << i)))
935                         continue;
936
937                 /* We've already tried this earlier */
938                 if (e->crtc_id == r->crtcs[i])
939                         continue;
940
941                 if (!hwc_crtc_is_bound(ctx, r->crtcs[i])) {
942                         *crtc_id = r->crtcs[i];
943                         ret = 0;
944                         goto out;
945                 }
946         }
947
948         /* We can't use the encoder, but nothing went wrong, try another one */
949         ret = -EAGAIN;
950
951 out:
952         drmModeFreeEncoder(e);
953         return ret;
954 }
955
956 static int hwc_set_active_config(struct hwc_composer_device_1* dev, int display,
957                         int index)
958 {
959         struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
960         struct hwc_drm_display *hd = NULL;
961         drmModeResPtr r = NULL;
962         drmModeConnectorPtr c;
963         uint32_t crtc_id = 0;
964         int ret, i;
965         bool new_crtc, new_encoder;
966
967         ret = hwc_get_drm_display(ctx, display, &hd);
968         if (ret)
969                 return ret;
970
971         c = drmModeGetConnector(ctx->fd, hd->connector_id);
972         if (!c) {
973                 ALOGE("Failed to get connector %d", display);
974                 return -ENODEV;
975         }
976
977         if (c->connection == DRM_MODE_DISCONNECTED) {
978                 ALOGE("Tried to configure a disconnected display %d", display);
979                 ret = -ENODEV;
980                 goto out;
981         }
982
983         if (index >= c->count_modes) {
984                 ALOGE("Index is out-of-bounds %d/%d", index, c->count_modes);
985                 ret = -ENOENT;
986                 goto out;
987         }
988
989         r = drmModeGetResources(ctx->fd);
990         if (!r) {
991                 ALOGE("Failed to get drm resources");
992                 goto out;
993         }
994
995         /* We no longer have an active_crtc */
996         hd->active_crtc = 0;
997         hd->active_pipe = -1;
998
999         /* First, try to use the currently-connected encoder */
1000         if (c->encoder_id) {
1001                 ret = hwc_try_encoder(ctx, r, c->encoder_id, &crtc_id);
1002                 if (ret && ret != -EAGAIN) {
1003                         ALOGE("Encoder try failed %d", ret);
1004                         goto out;
1005                 }
1006         }
1007
1008         /* We couldn't find a crtc with the attached encoder, try the others */
1009         if (!crtc_id) {
1010                 for (i = 0; i < c->count_encoders; i++) {
1011                         ret = hwc_try_encoder(ctx, r, c->encoders[i], &crtc_id);
1012                         if (!ret) {
1013                                 break;
1014                         } else if (ret != -EAGAIN) {
1015                                 ALOGE("Encoder try failed %d", ret);
1016                                 goto out;
1017                         }
1018                 }
1019                 if (!crtc_id) {
1020                         ALOGE("Couldn't find valid crtc to modeset");
1021                         ret = -EINVAL;
1022                         goto out;
1023                 }
1024         }
1025
1026         hd->active_crtc = crtc_id;
1027
1028         memcpy(&hd->active_mode, &hd->configs[index], sizeof(hd->active_mode));
1029
1030         /* Find the pipe corresponding to the crtc_id */
1031         for (i = 0; i < r->count_crtcs; i++) {
1032                 /* We've already tried this earlier */
1033                 if (r->crtcs[i] == crtc_id) {
1034                         hd->active_pipe = i;
1035                         break;
1036                 }
1037         }
1038         /* This should never happen... hehehe */
1039         if (hd->active_pipe == -1) {
1040                 ALOGE("Active crtc was not found in resources!!");
1041                 ret = -ENODEV;
1042                 goto out;
1043         }
1044
1045         /* TODO: Once we have atomic, set the crtc timing info here */
1046
1047 out:
1048         if (r)
1049                 drmModeFreeResources(r);
1050
1051         drmModeFreeConnector(c);
1052         return ret;
1053 }
1054
1055 static int hwc_destroy_worker(struct hwc_worker *worker)
1056 {
1057         int ret;
1058
1059         ret = pthread_mutex_lock(&worker->lock);
1060         if (ret) {
1061                 ALOGE("Failed to lock in destroy() %d", ret);
1062                 return ret;
1063         }
1064
1065         worker->exit = true;
1066
1067         ret |= pthread_cond_signal(&worker->cond);
1068         if (ret)
1069                 ALOGE("Failed to signal cond in destroy() %d", ret);
1070
1071         ret |= pthread_mutex_unlock(&worker->lock);
1072         if (ret)
1073                 ALOGE("Failed to unlock in destroy() %d", ret);
1074
1075         ret |= pthread_join(worker->thread, NULL);
1076         if (ret && ret != ESRCH)
1077                 ALOGE("Failed to join thread in destroy() %d", ret);
1078
1079         return ret;
1080 }
1081
1082 static void hwc_destroy_display(struct hwc_drm_display *hd)
1083 {
1084         int ret;
1085
1086         if (hwc_destroy_worker(&hd->set_worker))
1087                 ALOGE("Destroy set worker failed");
1088
1089         if (hwc_destroy_worker(&hd->vsync_worker))
1090                 ALOGE("Destroy vsync worker failed");
1091 }
1092
1093 static int hwc_device_close(struct hw_device_t *dev)
1094 {
1095         struct hwc_context_t *ctx = (struct hwc_context_t *)dev;
1096         int ret, i;
1097
1098         for (i = 0; i < MAX_NUM_DISPLAYS; i++)
1099                 hwc_destroy_display(&ctx->displays[i]);
1100
1101         drmClose(ctx->fd);
1102
1103         ret = hwc_import_destroy(ctx->import_ctx);
1104         if (ret)
1105                 ALOGE("Could not destroy import %d", ret);
1106
1107         free(ctx);
1108
1109         return 0;
1110 }
1111
1112 static int hwc_initialize_worker(struct hwc_drm_display *hd,
1113                         struct hwc_worker *worker, void *(*routine)(void*))
1114 {
1115         int ret;
1116
1117         ret = pthread_cond_init(&worker->cond, NULL);
1118         if (ret) {
1119                 ALOGE("Failed to create worker condition %d", ret);
1120                 return ret;
1121         }
1122
1123         ret = pthread_mutex_init(&worker->lock, NULL);
1124         if (ret) {
1125                 ALOGE("Failed to initialize worker lock %d", ret);
1126                 goto err_cond;
1127         }
1128
1129         worker->exit = false;
1130
1131         ret = pthread_create(&worker->thread, NULL, routine, hd);
1132         if (ret) {
1133                 ALOGE("Could not create worker thread %d", ret);
1134                 goto err_lock;
1135         }
1136         return 0;
1137
1138 err_lock:
1139         pthread_mutex_destroy(&worker->lock);
1140 err_cond:
1141         pthread_cond_destroy(&worker->cond);
1142         return ret;
1143 }
1144
1145 /*
1146  * TODO: This function sets the active config to the first one in the list. This
1147  * should be fixed such that it selects the preferred mode for the display, or
1148  * some other, saner, method of choosing the config.
1149  */
1150 static int hwc_set_initial_config(struct hwc_drm_display *hd)
1151 {
1152         int ret;
1153         uint32_t config;
1154         size_t num_configs = 1;
1155
1156         ret = hwc_get_display_configs(&hd->ctx->device, hd->display, &config,
1157                 &num_configs);
1158         if (ret || !num_configs)
1159                 return 0;
1160
1161         ret = hwc_set_active_config(&hd->ctx->device, hd->display, 0);
1162         if (ret) {
1163                 ALOGE("Failed to set active config d=%d ret=%d", hd->display,
1164                         ret);
1165                 return ret;
1166         }
1167
1168         return ret;
1169 }
1170
1171 static int hwc_initialize_display(struct hwc_context_t *ctx, int display,
1172                         uint32_t connector_id)
1173 {
1174         struct hwc_drm_display *hd = NULL;
1175         int ret;
1176
1177         ret = hwc_get_drm_display(ctx, display, &hd);
1178         if (ret)
1179                 return ret;
1180
1181         hd->ctx = ctx;
1182         hd->display = display;
1183         hd->active_pipe = -1;
1184         hd->initial_modeset_required = true;
1185         hd->connector_id = connector_id;
1186
1187         ret = sw_sync_timeline_create();
1188         if (ret < 0) {
1189                 ALOGE("Failed to create sw sync timeline %d", ret);
1190                 return ret;
1191         }
1192         hd->timeline_fd = ret;
1193
1194         ret = hwc_set_initial_config(hd);
1195         if (ret) {
1196                 ALOGE("Failed to set initial config for d=%d ret=%d", display,
1197                         ret);
1198                 return ret;
1199         }
1200
1201         ret = hwc_initialize_worker(hd, &hd->set_worker, hwc_set_worker);
1202         if (ret) {
1203                 ALOGE("Failed to create set worker %d\n", ret);
1204                 return ret;
1205         }
1206
1207         ret = hwc_initialize_worker(hd, &hd->vsync_worker, hwc_vsync_worker);
1208         if (ret) {
1209                 ALOGE("Failed to create vsync worker %d", ret);
1210                 goto err;
1211         }
1212
1213         return 0;
1214
1215 err:
1216         if (hwc_destroy_worker(&hd->set_worker))
1217                 ALOGE("Failed to destroy set worker");
1218
1219         return ret;
1220 }
1221
1222 static int hwc_enumerate_displays(struct hwc_context_t *ctx)
1223 {
1224         struct hwc_drm_display *panel_hd;
1225         drmModeResPtr res;
1226         drmModeConnectorPtr *conn_list;
1227         int ret = 0, i, j;
1228
1229         res = drmModeGetResources(ctx->fd);
1230         if (!res) {
1231                 ALOGE("Failed to get drm resources");
1232                 return -ENODEV;
1233         }
1234
1235         conn_list = (drmModeConnector **)calloc(res->count_connectors,
1236                         sizeof(*conn_list));
1237         if (!conn_list) {
1238                 ALOGE("Failed to allocate connector list");
1239                 ret = -ENOMEM;
1240                 goto out;
1241         }
1242
1243         for (i = 0; i < res->count_connectors; i++) {
1244                 conn_list[i] = drmModeGetConnector(ctx->fd, res->connectors[i]);
1245                 if (!conn_list[i]) {
1246                         ALOGE("Failed to get connector %d", res->connectors[i]);
1247                         ret = -ENODEV;
1248                         goto out;
1249                 }
1250         }
1251
1252         ctx->num_displays = 0;
1253
1254         /* Find a connected, panel type connector for display 0 */
1255         for (i = 0; i < res->count_connectors; i++) {
1256                 drmModeConnectorPtr c = conn_list[i];
1257
1258                 for (j = 0; j < ARRAY_SIZE(panel_types); j++) {
1259                         if (c->connector_type == panel_types[j] &&
1260                             c->connection == DRM_MODE_CONNECTED)
1261                                 break;
1262                 }
1263                 if (j == ARRAY_SIZE(panel_types))
1264                         continue;
1265
1266                 hwc_initialize_display(ctx, ctx->num_displays, c->connector_id);
1267                 ctx->num_displays++;
1268                 break;
1269         }
1270
1271         ret = hwc_get_drm_display(ctx, 0, &panel_hd);
1272         if (ret)
1273                 goto out;
1274
1275         /* Fill in the other displays */
1276         for (i = 0; i < res->count_connectors; i++) {
1277                 drmModeConnectorPtr c = conn_list[i];
1278
1279                 if (panel_hd->connector_id == c->connector_id)
1280                         continue;
1281
1282                 hwc_initialize_display(ctx, ctx->num_displays, c->connector_id);
1283                 ctx->num_displays++;
1284         }
1285
1286 out:
1287         for (i = 0; i < res->count_connectors; i++) {
1288                 if (conn_list[i])
1289                         drmModeFreeConnector(conn_list[i]);
1290         }
1291         free(conn_list);
1292
1293         if (res)
1294                 drmModeFreeResources(res);
1295
1296         return ret;
1297 }
1298
1299 static int hwc_device_open(const struct hw_module_t* module, const char* name,
1300                         struct hw_device_t** dev)
1301 {
1302         int ret = 0;
1303         struct hwc_context_t *ctx;
1304         char path[PROPERTY_VALUE_MAX];
1305
1306         if (strcmp(name, HWC_HARDWARE_COMPOSER)) {
1307                 ALOGE("Invalid module name- %s", name);
1308                 return -EINVAL;
1309         }
1310
1311         ctx = new hwc_context_t();
1312         if (!ctx) {
1313                 ALOGE("Failed to allocate hwc context");
1314                 return -ENOMEM;
1315         }
1316
1317         ret = hwc_import_init(&ctx->import_ctx);
1318         if (ret) {
1319                 ALOGE("Failed to initialize import context");
1320                 goto out;
1321         }
1322
1323         property_get("hwc.drm.device", path, HWCOMPOSER_DRM_DEVICE);
1324         /* TODO: Use drmOpenControl here instead */
1325         ctx->fd = open(path, O_RDWR);
1326         if (ctx->fd < 0) {
1327                 ALOGE("Failed to open dri- %s", strerror(-errno));
1328                 goto out;
1329         }
1330
1331         ret = hwc_enumerate_displays(ctx);
1332         if (ret) {
1333                 ALOGE("Failed to enumerate displays: %s", strerror(ret));
1334                 goto out;
1335         }
1336
1337         ctx->device.common.tag = HARDWARE_DEVICE_TAG;
1338         ctx->device.common.version = HWC_DEVICE_API_VERSION_1_4;
1339         ctx->device.common.module = const_cast<hw_module_t*>(module);
1340         ctx->device.common.close = hwc_device_close;
1341
1342         ctx->device.prepare = hwc_prepare;
1343         ctx->device.set = hwc_set;
1344         ctx->device.eventControl = hwc_event_control;
1345         ctx->device.setPowerMode = hwc_set_power_mode;
1346         ctx->device.query = hwc_query;
1347         ctx->device.registerProcs = hwc_register_procs;
1348         ctx->device.getDisplayConfigs = hwc_get_display_configs;
1349         ctx->device.getDisplayAttributes = hwc_get_display_attributes;
1350         ctx->device.getActiveConfig = hwc_get_active_config;
1351         ctx->device.setActiveConfig = hwc_set_active_config;
1352         ctx->device.setCursorPositionAsync = NULL; /* TODO: Add cursor */
1353
1354         *dev = &ctx->device.common;
1355
1356         return 0;
1357 out:
1358         if (ctx->fd >= 0)
1359                 close(ctx->fd);
1360
1361         free(ctx);
1362         return ret;
1363 }
1364
1365 static struct hw_module_methods_t hwc_module_methods = {
1366         open: hwc_device_open
1367 };
1368
1369 hwc_module_t HAL_MODULE_INFO_SYM = {
1370         common: {
1371                 tag: HARDWARE_MODULE_TAG,
1372                 version_major: 1,
1373                 version_minor: 0,
1374                 id: HWC_HARDWARE_MODULE_ID,
1375                 name: "DRM hwcomposer module",
1376                 author: "The Android Open Source Project",
1377                 methods: &hwc_module_methods,
1378                 dso: NULL,
1379                 reserved: { 0 },
1380         }
1381 };