OSDN Git Service

drm_hwcomposer: fix small class consistency issues
[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 ATRACE_TAG ATRACE_TAG_GRAPHICS
18 #define LOG_TAG "hwcomposer-drm"
19
20 #include "drm_hwcomposer.h"
21 #include "drmresources.h"
22 #include "importer.h"
23 #include "virtualcompositorworker.h"
24 #include "vsyncworker.h"
25
26 #include <stdlib.h>
27
28 #include <map>
29 #include <vector>
30 #include <sstream>
31
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <pthread.h>
35 #include <sys/param.h>
36 #include <sys/resource.h>
37 #include <xf86drm.h>
38 #include <xf86drmMode.h>
39
40 #include <cutils/log.h>
41 #include <cutils/properties.h>
42 #include <hardware/hardware.h>
43 #include <hardware/hwcomposer.h>
44 #include <sw_sync.h>
45 #include <sync/sync.h>
46 #include <utils/Trace.h>
47
48 #define UM_PER_INCH 25400
49 #define HWC_FB_BUFFERS 3
50
51 namespace android {
52
53 class DummySwSyncTimeline {
54  public:
55   int Init() {
56     int ret = timeline_fd_.Set(sw_sync_timeline_create());
57     if (ret < 0)
58       return ret;
59     return 0;
60   }
61
62   UniqueFd CreateDummyFence() {
63     int ret = sw_sync_fence_create(timeline_fd_.get(), "dummy fence",
64                                    timeline_pt_ + 1);
65     if (ret < 0) {
66       ALOGE("Failed to create dummy fence %d", ret);
67       return ret;
68     }
69
70     UniqueFd ret_fd(ret);
71
72     ret = sw_sync_timeline_inc(timeline_fd_.get(), 1);
73     if (ret) {
74       ALOGE("Failed to increment dummy sync timeline %d", ret);
75       return ret;
76     }
77
78     ++timeline_pt_;
79     return ret_fd;
80   }
81
82  private:
83   UniqueFd timeline_fd_;
84   int timeline_pt_ = 0;
85 };
86
87 struct CheckedOutputFd {
88   CheckedOutputFd(int *fd, const char *description,
89                   DummySwSyncTimeline &timeline)
90       : fd_(fd), description_(description), timeline_(timeline) {
91   }
92   CheckedOutputFd(CheckedOutputFd &&rhs)
93       : description_(rhs.description_), timeline_(rhs.timeline_) {
94     std::swap(fd_, rhs.fd_);
95   }
96
97   CheckedOutputFd &operator=(const CheckedOutputFd &rhs) = delete;
98
99   ~CheckedOutputFd() {
100     if (fd_ == NULL)
101       return;
102
103     if (*fd_ >= 0)
104       return;
105
106     *fd_ = timeline_.CreateDummyFence().Release();
107
108     if (*fd_ < 0)
109       ALOGE("Failed to fill %s (%p == %d) before destruction",
110             description_.c_str(), fd_, *fd_);
111   }
112
113  private:
114   int *fd_ = NULL;
115   std::string description_;
116   DummySwSyncTimeline &timeline_;
117 };
118
119 typedef struct hwc_drm_display {
120   struct hwc_context_t *ctx;
121   int display;
122
123   std::vector<uint32_t> config_ids;
124
125   VSyncWorker vsync_worker;
126 } hwc_drm_display_t;
127
128 struct hwc_context_t {
129   // map of display:hwc_drm_display_t
130   typedef std::map<int, hwc_drm_display_t> DisplayMap;
131   typedef DisplayMap::iterator DisplayMapIter;
132
133   hwc_context_t() : procs(NULL), importer(NULL), use_framebuffer_target(false) {
134   }
135
136   ~hwc_context_t() {
137     virtual_compositor_worker.Exit();
138     delete importer;
139   }
140
141   hwc_composer_device_1_t device;
142   hwc_procs_t const *procs;
143
144   DisplayMap displays;
145   DrmResources drm;
146   Importer *importer;
147   const gralloc_module_t *gralloc;
148   DummySwSyncTimeline dummy_timeline;
149   bool use_framebuffer_target;
150   VirtualCompositorWorker virtual_compositor_worker;
151 };
152
153 static native_handle_t *dup_buffer_handle(buffer_handle_t handle) {
154   native_handle_t *new_handle =
155       native_handle_create(handle->numFds, handle->numInts);
156   if (new_handle == NULL)
157     return NULL;
158
159   const int *old_data = handle->data;
160   int *new_data = new_handle->data;
161   for (int i = 0; i < handle->numFds; i++) {
162     *new_data = dup(*old_data);
163     old_data++;
164     new_data++;
165   }
166   memcpy(new_data, old_data, sizeof(int) * handle->numInts);
167
168   return new_handle;
169 }
170
171 static void free_buffer_handle(native_handle_t *handle) {
172   int ret = native_handle_close(handle);
173   if (ret)
174     ALOGE("Failed to close native handle %d", ret);
175   ret = native_handle_delete(handle);
176   if (ret)
177     ALOGE("Failed to delete native handle %d", ret);
178 }
179
180 OutputFd &OutputFd::operator=(OutputFd &&rhs) {
181   if (fd_ == NULL) {
182     std::swap(fd_, rhs.fd_);
183   } else {
184     if (*fd_ < 0) {
185       ALOGE("Failed to fill OutputFd %p before assignment", fd_);
186     }
187     fd_ = rhs.fd_;
188     rhs.fd_ = NULL;
189   }
190
191   return *this;
192 }
193
194 const hwc_drm_bo *DrmHwcBuffer::operator->() const {
195   if (importer_ == NULL) {
196     ALOGE("Access of non-existent BO");
197     exit(1);
198     return NULL;
199   }
200   return &bo_;
201 }
202
203 void DrmHwcBuffer::Clear() {
204   if (importer_ != NULL) {
205     importer_->ReleaseBuffer(&bo_);
206     importer_ = NULL;
207   }
208 }
209
210 int DrmHwcBuffer::ImportBuffer(buffer_handle_t handle, Importer *importer) {
211   hwc_drm_bo tmp_bo;
212
213   int ret = importer->ImportBuffer(handle, &tmp_bo);
214   if (ret)
215     return ret;
216
217   if (importer_ != NULL) {
218     importer_->ReleaseBuffer(&bo_);
219   }
220
221   importer_ = importer;
222
223   bo_ = tmp_bo;
224
225   return 0;
226 }
227
228 int DrmHwcNativeHandle::CopyBufferHandle(buffer_handle_t handle,
229                                          const gralloc_module_t *gralloc) {
230   native_handle_t *handle_copy = dup_buffer_handle(handle);
231   if (handle_copy == NULL) {
232     ALOGE("Failed to duplicate handle");
233     return -ENOMEM;
234   }
235
236   int ret = gralloc->registerBuffer(gralloc, handle_copy);
237   if (ret) {
238     ALOGE("Failed to register buffer handle %d", ret);
239     free_buffer_handle(handle_copy);
240     return ret;
241   }
242
243   Clear();
244
245   gralloc_ = gralloc;
246   handle_ = handle_copy;
247
248   return 0;
249 }
250
251 DrmHwcNativeHandle::~DrmHwcNativeHandle() {
252   Clear();
253 }
254
255 void DrmHwcNativeHandle::Clear() {
256   if (gralloc_ != NULL && handle_ != NULL) {
257     gralloc_->unregisterBuffer(gralloc_, handle_);
258     free_buffer_handle(handle_);
259     gralloc_ = NULL;
260     handle_ = NULL;
261   }
262 }
263
264 int DrmHwcLayer::InitFromHwcLayer(hwc_layer_1_t *sf_layer, Importer *importer,
265                                   const gralloc_module_t *gralloc) {
266   sf_handle = sf_layer->handle;
267   int ret = buffer.ImportBuffer(sf_layer->handle, importer);
268   if (ret)
269     return ret;
270
271   ret = handle.CopyBufferHandle(sf_layer->handle, gralloc);
272   if (ret)
273     return ret;
274
275   alpha = sf_layer->planeAlpha;
276
277   switch (sf_layer->transform) {
278     case 0:
279       transform = DrmHwcTransform::kIdentity;
280       break;
281     case HWC_TRANSFORM_FLIP_H:
282       transform = DrmHwcTransform::kFlipH;
283       break;
284     case HWC_TRANSFORM_FLIP_V:
285       transform = DrmHwcTransform::kFlipV;
286       break;
287     case HWC_TRANSFORM_ROT_90:
288       transform = DrmHwcTransform::kRotate90;
289       break;
290     case HWC_TRANSFORM_ROT_180:
291       transform = DrmHwcTransform::kRotate180;
292       break;
293     case HWC_TRANSFORM_ROT_270:
294       transform = DrmHwcTransform::kRotate270;
295       break;
296     default:
297       ALOGE("Invalid transform in hwc_layer_1_t %d", sf_layer->transform);
298       return -EINVAL;
299   }
300
301   switch (sf_layer->blending) {
302     case HWC_BLENDING_NONE:
303       blending = DrmHwcBlending::kNone;
304       break;
305     case HWC_BLENDING_PREMULT:
306       blending = DrmHwcBlending::kPreMult;
307       break;
308     case HWC_BLENDING_COVERAGE:
309       blending = DrmHwcBlending::kCoverage;
310       break;
311     default:
312       ALOGE("Invalid blending in hwc_layer_1_t %d", sf_layer->blending);
313       return -EINVAL;
314   }
315
316   source_crop = DrmHwcRect<float>(
317       sf_layer->sourceCropf.left, sf_layer->sourceCropf.top,
318       sf_layer->sourceCropf.right, sf_layer->sourceCropf.bottom);
319   display_frame = DrmHwcRect<int>(
320       sf_layer->displayFrame.left, sf_layer->displayFrame.top,
321       sf_layer->displayFrame.right, sf_layer->displayFrame.bottom);
322
323   return 0;
324 }
325
326 static void hwc_dump(struct hwc_composer_device_1 *dev, char *buff,
327                      int buff_len) {
328   struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
329   std::ostringstream out;
330
331   ctx->drm.compositor()->Dump(&out);
332   std::string out_str = out.str();
333   strncpy(buff, out_str.c_str(), std::min((size_t)buff_len, out_str.length()));
334 }
335
336 static int hwc_prepare(hwc_composer_device_1_t *dev, size_t num_displays,
337                        hwc_display_contents_1_t **display_contents) {
338   struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
339
340   char use_framebuffer_target[PROPERTY_VALUE_MAX];
341   property_get("hwc.drm.use_framebuffer_target", use_framebuffer_target, "0");
342   bool new_use_framebuffer_target = atoi(use_framebuffer_target);
343   if (ctx->use_framebuffer_target != new_use_framebuffer_target)
344     ALOGW("Starting to %s HWC_FRAMEBUFFER_TARGET",
345           new_use_framebuffer_target ? "use" : "not use");
346   ctx->use_framebuffer_target = new_use_framebuffer_target;
347
348   for (int i = 0; i < (int)num_displays; ++i) {
349     if (!display_contents[i])
350       continue;
351
352     bool use_framebuffer_target = ctx->use_framebuffer_target;
353     if (i == HWC_DISPLAY_VIRTUAL) {
354       use_framebuffer_target = true;
355     } else {
356       DrmCrtc *crtc = ctx->drm.GetCrtcForDisplay(i);
357       if (!crtc) {
358         ALOGE("No crtc for display %d", i);
359         return -ENODEV;
360       }
361     }
362
363     int num_layers = display_contents[i]->numHwLayers;
364     for (int j = 0; j < num_layers; j++) {
365       hwc_layer_1_t *layer = &display_contents[i]->hwLayers[j];
366
367       if (!use_framebuffer_target) {
368         if (layer->compositionType == HWC_FRAMEBUFFER)
369           layer->compositionType = HWC_OVERLAY;
370       } else {
371         switch (layer->compositionType) {
372           case HWC_OVERLAY:
373           case HWC_BACKGROUND:
374           case HWC_SIDEBAND:
375           case HWC_CURSOR_OVERLAY:
376             layer->compositionType = HWC_FRAMEBUFFER;
377             break;
378         }
379       }
380     }
381   }
382
383   return 0;
384 }
385
386 static void hwc_add_layer_to_retire_fence(
387     hwc_layer_1_t *layer, hwc_display_contents_1_t *display_contents) {
388   if (layer->releaseFenceFd < 0)
389     return;
390
391   if (display_contents->retireFenceFd >= 0) {
392     int old_retire_fence = display_contents->retireFenceFd;
393     display_contents->retireFenceFd =
394         sync_merge("dc_retire", old_retire_fence, layer->releaseFenceFd);
395     close(old_retire_fence);
396   } else {
397     display_contents->retireFenceFd = dup(layer->releaseFenceFd);
398   }
399 }
400
401 static int hwc_set(hwc_composer_device_1_t *dev, size_t num_displays,
402                    hwc_display_contents_1_t **sf_display_contents) {
403   ATRACE_CALL();
404   struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
405   int ret = 0;
406
407   std::vector<CheckedOutputFd> checked_output_fences;
408   std::vector<DrmHwcDisplayContents> displays_contents;
409   std::vector<DrmCompositionDisplayLayersMap> layers_map;
410   std::vector<std::vector<size_t>> layers_indices;
411   displays_contents.reserve(num_displays);
412   // layers_map.reserve(num_displays);
413   layers_indices.reserve(num_displays);
414
415   // Phase one does nothing that would cause errors. Only take ownership of FDs.
416   for (size_t i = 0; i < num_displays; ++i) {
417     hwc_display_contents_1_t *dc = sf_display_contents[i];
418     displays_contents.emplace_back();
419     DrmHwcDisplayContents &display_contents = displays_contents.back();
420     layers_indices.emplace_back();
421     std::vector<size_t> &indices_to_composite = layers_indices.back();
422
423     if (!sf_display_contents[i])
424       continue;
425
426     if (i == HWC_DISPLAY_VIRTUAL) {
427       ctx->virtual_compositor_worker.QueueComposite(dc);
428       continue;
429     }
430
431     std::ostringstream display_index_formatter;
432     display_index_formatter << "retire fence for display " << i;
433     std::string display_fence_description(display_index_formatter.str());
434     checked_output_fences.emplace_back(&dc->retireFenceFd,
435                                        display_fence_description.c_str(),
436                                        ctx->dummy_timeline);
437     display_contents.retire_fence = OutputFd(&dc->retireFenceFd);
438
439     size_t num_dc_layers = dc->numHwLayers;
440     int framebuffer_target_index = -1;
441     for (size_t j = 0; j < num_dc_layers; ++j) {
442       hwc_layer_1_t *sf_layer = &dc->hwLayers[j];
443
444       display_contents.layers.emplace_back();
445       DrmHwcLayer &layer = display_contents.layers.back();
446
447       if (sf_layer->flags & HWC_SKIP_LAYER)
448         continue;
449
450       if (!ctx->use_framebuffer_target) {
451         if (sf_layer->compositionType == HWC_OVERLAY)
452           indices_to_composite.push_back(j);
453         if (sf_layer->compositionType == HWC_FRAMEBUFFER_TARGET)
454           framebuffer_target_index = j;
455       } else {
456         if (sf_layer->compositionType == HWC_FRAMEBUFFER_TARGET)
457           indices_to_composite.push_back(j);
458       }
459
460       layer.acquire_fence.Set(sf_layer->acquireFenceFd);
461       sf_layer->acquireFenceFd = -1;
462
463       std::ostringstream layer_fence_formatter;
464       layer_fence_formatter << "release fence for layer " << j << " of display "
465                             << i;
466       std::string layer_fence_description(layer_fence_formatter.str());
467       checked_output_fences.emplace_back(&sf_layer->releaseFenceFd,
468                                          layer_fence_description.c_str(),
469                                          ctx->dummy_timeline);
470       layer.release_fence = OutputFd(&sf_layer->releaseFenceFd);
471     }
472
473     if (ctx->use_framebuffer_target) {
474       if (indices_to_composite.size() != 1) {
475         ALOGE("Expected 1 (got %d) layer with HWC_FRAMEBUFFER_TARGET",
476               indices_to_composite.size());
477         ret = -EINVAL;
478       }
479     } else {
480       if (indices_to_composite.empty() && framebuffer_target_index >= 0) {
481         hwc_layer_1_t *sf_layer = &dc->hwLayers[framebuffer_target_index];
482         if (!sf_layer->handle || (sf_layer->flags & HWC_SKIP_LAYER)) {
483           ALOGE(
484               "Expected valid layer with HWC_FRAMEBUFFER_TARGET when all "
485               "HWC_OVERLAY layers are skipped.");
486           ret = -EINVAL;
487         }
488         indices_to_composite.push_back(framebuffer_target_index);
489       }
490     }
491   }
492
493   if (ret)
494     return ret;
495
496   for (size_t i = 0; i < num_displays; ++i) {
497     hwc_display_contents_1_t *dc = sf_display_contents[i];
498     DrmHwcDisplayContents &display_contents = displays_contents[i];
499     if (!sf_display_contents[i])
500       continue;
501
502     layers_map.emplace_back();
503     DrmCompositionDisplayLayersMap &map = layers_map.back();
504     std::vector<size_t> &indices_to_composite = layers_indices[i];
505     for (size_t j : indices_to_composite) {
506       hwc_layer_1_t *sf_layer = &dc->hwLayers[j];
507
508       DrmHwcLayer &layer = display_contents.layers[j];
509
510       layer.InitFromHwcLayer(sf_layer, ctx->importer, ctx->gralloc);
511       map.layers.emplace_back(std::move(layer));
512     }
513   }
514
515   std::unique_ptr<DrmComposition> composition(
516       ctx->drm.compositor()->CreateComposition(ctx->importer));
517   if (!composition) {
518     ALOGE("Drm composition init failed");
519     return -EINVAL;
520   }
521
522   ret = composition->SetLayers(layers_map.size(), layers_map.data());
523   if (ret) {
524     return -EINVAL;
525   }
526
527   ret = ctx->drm.compositor()->QueueComposition(std::move(composition));
528   if (ret) {
529     return -EINVAL;
530   }
531
532   for (size_t i = 0; i < num_displays; ++i) {
533     hwc_display_contents_1_t *dc = sf_display_contents[i];
534     if (!dc)
535       continue;
536
537     size_t num_dc_layers = dc->numHwLayers;
538     for (size_t j = 0; j < num_dc_layers; ++j) {
539       hwc_layer_1_t *layer = &dc->hwLayers[j];
540       if (layer->flags & HWC_SKIP_LAYER)
541         continue;
542       hwc_add_layer_to_retire_fence(layer, dc);
543     }
544   }
545
546   composition.reset(NULL);
547
548   return ret;
549 }
550
551 static int hwc_event_control(struct hwc_composer_device_1 *dev, int display,
552                              int event, int enabled) {
553   if (event != HWC_EVENT_VSYNC || (enabled != 0 && enabled != 1))
554     return -EINVAL;
555
556   struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
557   hwc_drm_display_t *hd = &ctx->displays[display];
558   return hd->vsync_worker.VSyncControl(enabled);
559 }
560
561 static int hwc_set_power_mode(struct hwc_composer_device_1 *dev, int display,
562                               int mode) {
563   struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
564
565   uint64_t dpmsValue = 0;
566   switch (mode) {
567     case HWC_POWER_MODE_OFF:
568       dpmsValue = DRM_MODE_DPMS_OFF;
569       break;
570
571     /* We can't support dozing right now, so go full on */
572     case HWC_POWER_MODE_DOZE:
573     case HWC_POWER_MODE_DOZE_SUSPEND:
574     case HWC_POWER_MODE_NORMAL:
575       dpmsValue = DRM_MODE_DPMS_ON;
576       break;
577   };
578   return ctx->drm.SetDpmsMode(display, dpmsValue);
579 }
580
581 static int hwc_query(struct hwc_composer_device_1 * /* dev */, int what,
582                      int *value) {
583   switch (what) {
584     case HWC_BACKGROUND_LAYER_SUPPORTED:
585       *value = 0; /* TODO: We should do this */
586       break;
587     case HWC_VSYNC_PERIOD:
588       ALOGW("Query for deprecated vsync value, returning 60Hz");
589       *value = 1000 * 1000 * 1000 / 60;
590       break;
591     case HWC_DISPLAY_TYPES_SUPPORTED:
592       *value = HWC_DISPLAY_PRIMARY | HWC_DISPLAY_EXTERNAL | HWC_DISPLAY_VIRTUAL;
593       break;
594   }
595   return 0;
596 }
597
598 static void hwc_register_procs(struct hwc_composer_device_1 *dev,
599                                hwc_procs_t const *procs) {
600   struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
601
602   ctx->procs = procs;
603
604   for (hwc_context_t::DisplayMapIter iter = ctx->displays.begin();
605        iter != ctx->displays.end(); ++iter) {
606     iter->second.vsync_worker.SetProcs(procs);
607   }
608 }
609
610 static int hwc_get_display_configs(struct hwc_composer_device_1 *dev,
611                                    int display, uint32_t *configs,
612                                    size_t *num_configs) {
613   if (!*num_configs)
614     return 0;
615
616   struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
617   hwc_drm_display_t *hd = &ctx->displays[display];
618   hd->config_ids.clear();
619
620   DrmConnector *connector = ctx->drm.GetConnectorForDisplay(display);
621   if (!connector) {
622     ALOGE("Failed to get connector for display %d", display);
623     return -ENODEV;
624   }
625
626   int ret = connector->UpdateModes();
627   if (ret) {
628     ALOGE("Failed to update display modes %d", ret);
629     return ret;
630   }
631
632   for (DrmConnector::ModeIter iter = connector->begin_modes();
633        iter != connector->end_modes(); ++iter) {
634     size_t idx = hd->config_ids.size();
635     if (idx == *num_configs)
636       break;
637     hd->config_ids.push_back(iter->id());
638     configs[idx] = iter->id();
639   }
640   *num_configs = hd->config_ids.size();
641   return *num_configs == 0 ? -1 : 0;
642 }
643
644 static int hwc_get_display_attributes(struct hwc_composer_device_1 *dev,
645                                       int display, uint32_t config,
646                                       const uint32_t *attributes,
647                                       int32_t *values) {
648   struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
649   DrmConnector *c = ctx->drm.GetConnectorForDisplay(display);
650   if (!c) {
651     ALOGE("Failed to get DrmConnector for display %d", display);
652     return -ENODEV;
653   }
654   DrmMode mode;
655   for (DrmConnector::ModeIter iter = c->begin_modes(); iter != c->end_modes();
656        ++iter) {
657     if (iter->id() == config) {
658       mode = *iter;
659       break;
660     }
661   }
662   if (mode.id() == 0) {
663     ALOGE("Failed to find active mode for display %d", display);
664     return -ENOENT;
665   }
666
667   uint32_t mm_width = c->mm_width();
668   uint32_t mm_height = c->mm_height();
669   for (int i = 0; attributes[i] != HWC_DISPLAY_NO_ATTRIBUTE; ++i) {
670     switch (attributes[i]) {
671       case HWC_DISPLAY_VSYNC_PERIOD:
672         values[i] = 1000 * 1000 * 1000 / mode.v_refresh();
673         break;
674       case HWC_DISPLAY_WIDTH:
675         values[i] = mode.h_display();
676         break;
677       case HWC_DISPLAY_HEIGHT:
678         values[i] = mode.v_display();
679         break;
680       case HWC_DISPLAY_DPI_X:
681         /* Dots per 1000 inches */
682         values[i] = mm_width ? (mode.h_display() * UM_PER_INCH) / mm_width : 0;
683         break;
684       case HWC_DISPLAY_DPI_Y:
685         /* Dots per 1000 inches */
686         values[i] =
687             mm_height ? (mode.v_display() * UM_PER_INCH) / mm_height : 0;
688         break;
689     }
690   }
691   return 0;
692 }
693
694 static int hwc_get_active_config(struct hwc_composer_device_1 *dev,
695                                  int display) {
696   struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
697   DrmConnector *c = ctx->drm.GetConnectorForDisplay(display);
698   if (!c) {
699     ALOGE("Failed to get DrmConnector for display %d", display);
700     return -ENODEV;
701   }
702
703   DrmMode mode = c->active_mode();
704   hwc_drm_display_t *hd = &ctx->displays[display];
705   for (size_t i = 0; i < hd->config_ids.size(); ++i) {
706     if (hd->config_ids[i] == mode.id())
707       return i;
708   }
709   return -1;
710 }
711
712 static int hwc_set_active_config(struct hwc_composer_device_1 *dev, int display,
713                                  int index) {
714   struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
715   hwc_drm_display_t *hd = &ctx->displays[display];
716   if (index >= (int)hd->config_ids.size()) {
717     ALOGE("Invalid config index %d passed in", index);
718     return -EINVAL;
719   }
720
721   DrmConnector *c = ctx->drm.GetConnectorForDisplay(display);
722   if (!c) {
723     ALOGE("Failed to get connector for display %d", display);
724     return -ENODEV;
725   }
726   DrmMode mode;
727   for (DrmConnector::ModeIter iter = c->begin_modes(); iter != c->end_modes();
728        ++iter) {
729     if (iter->id() == hd->config_ids[index]) {
730       mode = *iter;
731       break;
732     }
733   }
734   if (mode.id() != hd->config_ids[index]) {
735     ALOGE("Could not find active mode for %d/%d", index, hd->config_ids[index]);
736     return -ENOENT;
737   }
738   int ret = ctx->drm.SetDisplayActiveMode(display, mode);
739   if (ret) {
740     ALOGE("Failed to set active config %d", ret);
741     return ret;
742   }
743   return ret;
744 }
745
746 static int hwc_device_close(struct hw_device_t *dev) {
747   struct hwc_context_t *ctx = (struct hwc_context_t *)dev;
748   delete ctx;
749   return 0;
750 }
751
752 /*
753  * TODO: This function sets the active config to the first one in the list. This
754  * should be fixed such that it selects the preferred mode for the display, or
755  * some other, saner, method of choosing the config.
756  */
757 static int hwc_set_initial_config(hwc_drm_display_t *hd) {
758   uint32_t config;
759   size_t num_configs = 1;
760   int ret = hwc_get_display_configs(&hd->ctx->device, hd->display, &config,
761                                     &num_configs);
762   if (ret || !num_configs)
763     return 0;
764
765   ret = hwc_set_active_config(&hd->ctx->device, hd->display, 0);
766   if (ret) {
767     ALOGE("Failed to set active config d=%d ret=%d", hd->display, ret);
768     return ret;
769   }
770
771   return ret;
772 }
773
774 static int hwc_initialize_display(struct hwc_context_t *ctx, int display) {
775   hwc_drm_display_t *hd = &ctx->displays[display];
776   hd->ctx = ctx;
777   hd->display = display;
778
779   int ret = hwc_set_initial_config(hd);
780   if (ret) {
781     ALOGE("Failed to set initial config for d=%d ret=%d", display, ret);
782     return ret;
783   }
784
785   ret = hd->vsync_worker.Init(&ctx->drm, display);
786   if (ret) {
787     ALOGE("Failed to create event worker for display %d %d\n", display, ret);
788     return ret;
789   }
790
791   return 0;
792 }
793
794 static int hwc_enumerate_displays(struct hwc_context_t *ctx) {
795   int ret;
796   for (DrmResources::ConnectorIter c = ctx->drm.begin_connectors();
797        c != ctx->drm.end_connectors(); ++c) {
798     ret = hwc_initialize_display(ctx, (*c)->display());
799     if (ret) {
800       ALOGE("Failed to initialize display %d", (*c)->display());
801       return ret;
802     }
803   }
804
805   ret = ctx->virtual_compositor_worker.Init();
806   if (ret) {
807     ALOGE("Failed to initialize virtual compositor worker");
808     return ret;
809   }
810   return 0;
811 }
812
813 static int hwc_device_open(const struct hw_module_t *module, const char *name,
814                            struct hw_device_t **dev) {
815   if (strcmp(name, HWC_HARDWARE_COMPOSER)) {
816     ALOGE("Invalid module name- %s", name);
817     return -EINVAL;
818   }
819
820   struct hwc_context_t *ctx = new hwc_context_t();
821   if (!ctx) {
822     ALOGE("Failed to allocate hwc context");
823     return -ENOMEM;
824   }
825
826   int ret = ctx->drm.Init();
827   if (ret) {
828     ALOGE("Can't initialize Drm object %d", ret);
829     delete ctx;
830     return ret;
831   }
832
833   ret = hw_get_module(GRALLOC_HARDWARE_MODULE_ID,
834                       (const hw_module_t **)&ctx->gralloc);
835   if (ret) {
836     ALOGE("Failed to open gralloc module %d", ret);
837     delete ctx;
838     return ret;
839   }
840
841   ret = ctx->dummy_timeline.Init();
842   if (ret) {
843     ALOGE("Failed to create dummy sw sync timeline %d", ret);
844     return ret;
845   }
846
847   ctx->importer = Importer::CreateInstance(&ctx->drm);
848   if (!ctx->importer) {
849     ALOGE("Failed to create importer instance");
850     delete ctx;
851     return ret;
852   }
853
854   ret = hwc_enumerate_displays(ctx);
855   if (ret) {
856     ALOGE("Failed to enumerate displays: %s", strerror(ret));
857     delete ctx;
858     return ret;
859   }
860
861   ctx->device.common.tag = HARDWARE_DEVICE_TAG;
862   ctx->device.common.version = HWC_DEVICE_API_VERSION_1_4;
863   ctx->device.common.module = const_cast<hw_module_t *>(module);
864   ctx->device.common.close = hwc_device_close;
865
866   ctx->device.dump = hwc_dump;
867   ctx->device.prepare = hwc_prepare;
868   ctx->device.set = hwc_set;
869   ctx->device.eventControl = hwc_event_control;
870   ctx->device.setPowerMode = hwc_set_power_mode;
871   ctx->device.query = hwc_query;
872   ctx->device.registerProcs = hwc_register_procs;
873   ctx->device.getDisplayConfigs = hwc_get_display_configs;
874   ctx->device.getDisplayAttributes = hwc_get_display_attributes;
875   ctx->device.getActiveConfig = hwc_get_active_config;
876   ctx->device.setActiveConfig = hwc_set_active_config;
877   ctx->device.setCursorPositionAsync = NULL; /* TODO: Add cursor */
878
879   *dev = &ctx->device.common;
880
881   return 0;
882 }
883 }
884
885 static struct hw_module_methods_t hwc_module_methods = {
886   open : android::hwc_device_open
887 };
888
889 hwc_module_t HAL_MODULE_INFO_SYM = {
890   common : {
891     tag : HARDWARE_MODULE_TAG,
892     version_major : 1,
893     version_minor : 0,
894     id : HWC_HARDWARE_MODULE_ID,
895     name : "DRM hwcomposer module",
896     author : "The Android Open Source Project",
897     methods : &hwc_module_methods,
898     dso : NULL,
899     reserved : {0},
900   }
901 };