OSDN Git Service

Merge "drm_hwcomposer: ground work for squashing" into mnc-dr-dev
[android-x86/external-drm_hwcomposer.git] / hwcomposer.cpp
index 0629f84..6a0f4cd 100644 (file)
  * limitations under the License.
  */
 
+#define ATRACE_TAG ATRACE_TAG_GRAPHICS
 #define LOG_TAG "hwcomposer-drm"
 
-#include <fcntl.h>
-#include <errno.h>
-#include <sys/param.h>
+#include "drm_hwcomposer.h"
+#include "drmresources.h"
+#include "importer.h"
+#include "virtualcompositorworker.h"
+#include "vsyncworker.h"
 
-#include <cutils/log.h>
+#include <stdlib.h>
+
+#include <map>
+#include <vector>
+#include <sstream>
 
+#include <errno.h>
+#include <fcntl.h>
+#include <pthread.h>
+#include <sys/param.h>
+#include <sys/resource.h>
 #include <xf86drm.h>
 #include <xf86drmMode.h>
-#include <drm/drm_fourcc.h>
 
+#include <cutils/log.h>
+#include <cutils/properties.h>
 #include <hardware/hardware.h>
 #include <hardware/hwcomposer.h>
+#include <sw_sync.h>
+#include <sync/sync.h>
+#include <utils/Trace.h>
 
-#include <gralloc_drm.h>
-#include <gralloc_drm_priv.h>
-#include <gralloc_drm_handle.h>
-
-#define ARRAY_SIZE(arr) (int)(sizeof(arr) / sizeof((arr)[0]))
-
-#define HWCOMPOSER_DRM_DEVICE "/dev/dri/card0"
-#define MAX_NUM_DISPLAYS 3
 #define UM_PER_INCH 25400
-
-static const uint32_t panel_types[] = {
-       DRM_MODE_CONNECTOR_LVDS,
-       DRM_MODE_CONNECTOR_eDP,
-       DRM_MODE_CONNECTOR_DSI,
+#define HWC_FB_BUFFERS 3
+
+namespace android {
+
+class DummySwSyncTimeline {
+ public:
+  int Init() {
+    int ret = timeline_fd_.Set(sw_sync_timeline_create());
+    if (ret < 0)
+      return ret;
+    return 0;
+  }
+
+  UniqueFd CreateDummyFence() {
+    int ret = sw_sync_fence_create(timeline_fd_.get(), "dummy fence",
+                                   timeline_pt_ + 1);
+    if (ret < 0) {
+      ALOGE("Failed to create dummy fence %d", ret);
+      return ret;
+    }
+
+    UniqueFd ret_fd(ret);
+
+    ret = sw_sync_timeline_inc(timeline_fd_.get(), 1);
+    if (ret) {
+      ALOGE("Failed to increment dummy sync timeline %d", ret);
+      return ret;
+    }
+
+    ++timeline_pt_;
+    return ret_fd;
+  }
+
+ private:
+  UniqueFd timeline_fd_;
+  int timeline_pt_ = 0;
 };
 
-struct hwc_drm_display {
-       uint32_t connector_id;
+struct CheckedOutputFd {
+  CheckedOutputFd(int *fd, const char *description,
+                  DummySwSyncTimeline &timeline)
+      : fd_(fd), description_(description), timeline_(timeline) {
+  }
+  CheckedOutputFd(CheckedOutputFd &&rhs)
+      : description_(rhs.description_), timeline_(rhs.timeline_) {
+    std::swap(fd_, rhs.fd_);
+  }
 
-       drmModeModeInfoPtr configs;
-       uint32_t num_configs;
+  CheckedOutputFd &operator=(const CheckedOutputFd &rhs) = delete;
 
-       int active_config;
-       uint32_t active_crtc;
-};
+  ~CheckedOutputFd() {
+    if (fd_ == NULL)
+      return;
 
-struct hwc_context_t {
-       hwc_composer_device_1_t device;
+    if (*fd_ >= 0)
+      return;
 
-       int fd;
-       struct drm_module_t *gralloc_module; /* TODO: NUKE THIS */
+    *fd_ = timeline_.CreateDummyFence().Release();
 
-       hwc_procs_t const *procs;
+    if (*fd_ < 0)
+      ALOGE("Failed to fill %s (%p == %d) before destruction",
+            description_.c_str(), fd_, *fd_);
+  }
 
-       struct hwc_drm_display displays[MAX_NUM_DISPLAYS];
-       int num_displays;
+ private:
+  int *fd_ = NULL;
+  std::string description_;
+  DummySwSyncTimeline &timeline_;
 };
 
-static int hwc_get_drm_display(struct hwc_context_t *ctx, int display,
-                       struct hwc_drm_display **hd)
-{
-       if (display >= MAX_NUM_DISPLAYS) {
-               ALOGE("Requested display is out-of-bounds %d %d", display,
-                       MAX_NUM_DISPLAYS);
-               return -EINVAL;
-       }
-       *hd = &ctx->displays[display];
-       return 0;
-}
-
-static int hwc_prepare_layer(hwc_layer_1_t *layer)
-{
-       /* TODO: We can't handle background right now, defer to sufaceFlinger */
-       if (layer->compositionType == HWC_BACKGROUND) {
-               layer->compositionType = HWC_FRAMEBUFFER;
-               ALOGV("Can't handle background layers yet");
-
-       /* TODO: Support sideband compositions */
-       } else if (layer->compositionType == HWC_SIDEBAND) {
-               layer->compositionType = HWC_FRAMEBUFFER;
-               ALOGV("Can't handle sideband content yet");
-       }
-
-       layer->hints = 0;
+typedef struct hwc_drm_display {
+  struct hwc_context_t *ctx;
+  int display;
 
-       /* TODO: Handle cursor by setting compositionType=HWC_CURSOR_OVERLAY */
-       if (layer->flags & HWC_IS_CURSOR_LAYER) {
-               ALOGV("Can't handle async cursors yet");
-       }
+  std::vector<uint32_t> config_ids;
 
-       /* TODO: Handle transformations */
-       if (layer->transform) {
-               ALOGV("Can't handle transformations yet");
-       }
+  VSyncWorker vsync_worker;
+} hwc_drm_display_t;
 
-       /* TODO: Handle blending & plane alpha*/
-       if (layer->blending == HWC_BLENDING_PREMULT ||
-           layer->blending == HWC_BLENDING_COVERAGE) {
-               ALOGV("Can't handle blending yet");
-       }
+struct hwc_context_t {
+  // map of display:hwc_drm_display_t
+  typedef std::map<int, hwc_drm_display_t> DisplayMap;
+  typedef DisplayMap::iterator DisplayMapIter;
+
+  hwc_context_t() : procs(NULL), importer(NULL), use_framebuffer_target(false) {
+  }
+
+  ~hwc_context_t() {
+    virtual_compositor_worker.Exit();
+    delete importer;
+  }
+
+  hwc_composer_device_1_t device;
+  hwc_procs_t const *procs;
+
+  DisplayMap displays;
+  DrmResources drm;
+  Importer *importer;
+  const gralloc_module_t *gralloc;
+  DummySwSyncTimeline dummy_timeline;
+  bool use_framebuffer_target;
+  VirtualCompositorWorker virtual_compositor_worker;
+};
 
-       /* TODO: Handle cropping & scaling */
+static native_handle_t *dup_buffer_handle(buffer_handle_t handle) {
+  native_handle_t *new_handle =
+      native_handle_create(handle->numFds, handle->numInts);
+  if (new_handle == NULL)
+    return NULL;
+
+  const int *old_data = handle->data;
+  int *new_data = new_handle->data;
+  for (int i = 0; i < handle->numFds; i++) {
+    *new_data = dup(*old_data);
+    old_data++;
+    new_data++;
+  }
+  memcpy(new_data, old_data, sizeof(int) * handle->numInts);
+
+  return new_handle;
+}
 
-       return 0;
+static void free_buffer_handle(native_handle_t *handle) {
+  int ret = native_handle_close(handle);
+  if (ret)
+    ALOGE("Failed to close native handle %d", ret);
+  ret = native_handle_delete(handle);
+  if (ret)
+    ALOGE("Failed to delete native handle %d", ret);
 }
 
-static int hwc_prepare(hwc_composer_device_1_t */* dev */, size_t num_displays,
-                       hwc_display_contents_1_t** display_contents)
-{
-       int ret = 0, i, j;
-
-       /* TODO: Check flags for HWC_GEOMETRY_CHANGED */
-
-       for (i = 0; i < (int)num_displays && i < MAX_NUM_DISPLAYS; i++) {
-               for (j = 0; j < (int)display_contents[i]->numHwLayers; j++) {
-                       ret = hwc_prepare_layer(
-                                       &display_contents[i]->hwLayers[j]);
-                       if (ret) {
-                               ALOGE("Failed to prepare layer %d:%d", j, i);
-                               return ret;
-                       }
-               }
-       }
-
-       return ret;
+OutputFd &OutputFd::operator=(OutputFd &&rhs) {
+  if (fd_ == NULL) {
+    std::swap(fd_, rhs.fd_);
+  } else {
+    if (*fd_ < 0) {
+      ALOGE("Failed to fill OutputFd %p before assignment", fd_);
+    }
+    fd_ = rhs.fd_;
+    rhs.fd_ = NULL;
+  }
+
+  return *this;
 }
 
-static int hwc_bo_add_fb(hwc_context_t */* ctx */, struct gralloc_drm_bo_t *bo)
-{
-       uint32_t pitches[4] = { 0, 0, 0, 0 };
-       uint32_t handles[4] = { 0, 0, 0, 0 };
-       uint32_t offsets[4] = { 0, 0, 0, 0 };
-       int drm_format;
-
-       pitches[0] = bo->handle->stride;
-       handles[0] = bo->fb_handle;
-
-       switch(bo->handle->format) {
-               case HAL_PIXEL_FORMAT_RGB_888:
-                       drm_format = DRM_FORMAT_BGR888;
-                       break;
-               case HAL_PIXEL_FORMAT_BGRA_8888:
-                       drm_format = DRM_FORMAT_ARGB8888;
-                       break;
-               case HAL_PIXEL_FORMAT_RGBX_8888:
-                       drm_format = DRM_FORMAT_XBGR8888;
-                       break;
-               case HAL_PIXEL_FORMAT_RGBA_8888:
-                       drm_format = DRM_FORMAT_ABGR8888;
-                       break;
-               case HAL_PIXEL_FORMAT_RGB_565:
-                       drm_format = DRM_FORMAT_BGR565;
-                       break;
-               case HAL_PIXEL_FORMAT_YV12:
-                       drm_format = DRM_FORMAT_YVU420;
-                       break;
-               default:
-                       ALOGE("error resolving drm format");
-                       return -EINVAL;
-       }
-
-       return drmModeAddFB2(bo->drm->fd, bo->handle->width, bo->handle->height,
-               drm_format, handles, pitches, offsets, (uint32_t *) &bo->fb_id,
-               0);
+const hwc_drm_bo *DrmHwcBuffer::operator->() const {
+  if (importer_ == NULL) {
+    ALOGE("Access of non-existent BO");
+    exit(1);
+    return NULL;
+  }
+  return &bo_;
 }
 
-static bool hwc_mode_is_equal(drmModeModeInfoPtr a, drmModeModeInfoPtr b)
-{
-       return a->clock == b->clock &&
-               a->hdisplay == b->hdisplay &&
-               a->hsync_start == b->hsync_start &&
-               a->hsync_end == b->hsync_end &&
-               a->htotal == b->htotal &&
-               a->hskew == b->hskew &&
-               a->vdisplay == b->vdisplay &&
-               a->vsync_start == b->vsync_start &&
-               a->vsync_end == b->vsync_end &&
-               a->vtotal == b->vtotal &&
-               a->vscan == b->vscan &&
-               a->vrefresh == b->vrefresh &&
-               a->flags == b->flags &&
-               a->type == b->type &&
-               !strcmp(a->name, b->name);
+void DrmHwcBuffer::Clear() {
+  if (importer_ != NULL) {
+    importer_->ReleaseBuffer(&bo_);
+    importer_ = NULL;
+  }
 }
 
-static int hwc_set_display(hwc_context_t *ctx, int display,
-                       hwc_display_contents_1_t* display_contents)
-{
-       struct hwc_drm_display *hd = NULL;
-       drmModeCrtcPtr crtc;
-       drmModeModeInfoPtr m;
-       hwc_layer_1_t *layer = NULL;
-       int ret, i;
-
-       /* TODO: NUKE THIS */
-       gralloc_drm_t *drm = ctx->gralloc_module->drm;
-       gralloc_drm_handle_t *gr_handle;
-       struct gralloc_drm_bo_t *bo;
-
-       ret = hwc_get_drm_display(ctx, display, &hd);
-       if (ret)
-               return ret;
-
-       if (!hd->active_crtc) {
-               ALOGE("There is no active crtc for display %d", display);
-               return -ENOENT;
-       }
-
-       /*
-        * TODO: We can only support one hw layer atm, so choose either the
-        * first one or the framebuffer target.
-        */
-       if (!display_contents->numHwLayers) {
-               return 0;
-       } else if (display_contents->numHwLayers == 1) {
-               layer = &display_contents->hwLayers[0];
-       } else {
-               for (i = 0; i < (int)display_contents->numHwLayers; i++) {
-                       layer = &display_contents->hwLayers[i];
-                       if (layer->compositionType == HWC_FRAMEBUFFER_TARGET)
-                               break;
-               }
-               if (i == (int)display_contents->numHwLayers) {
-                       ALOGE("Could not find a suitable layer for display %d",
-                               display);
-               }
-       }
-
-       gr_handle = (gralloc_drm_handle_t *)layer->handle;
-
-       bo = gr_handle->data;
-       if (!bo) {
-               ALOGE("Could not get drm bo from handle");
-               return -EINVAL;
-       }
-
-       if (!bo->fb_id) {
-               ret = hwc_bo_add_fb(ctx, bo);
-               if (ret) {
-                       ALOGE("could not create drm fb %d", ret);
-                       return ret;
-               }
-       }
-
-       crtc = drmModeGetCrtc(ctx->fd, hd->active_crtc);
-       if (!crtc) {
-               ALOGE("Failed to get crtc for display %d", display);
-               return -ENODEV;
-       }
-
-       m = &hd->configs[hd->active_config];
-
-       /* Do a modeset if we haven't done one, or the mode has changed */
-       if (!crtc->mode_valid || !hwc_mode_is_equal(m, &crtc->mode)) {
-               ret = drmModeSetCrtc(ctx->fd, crtc->crtc_id, bo->fb_id, 0, 0,
-                       &hd->connector_id, 1, m);
-               if (ret) {
-                       ALOGE("Modeset failed for crtc %d", crtc->crtc_id);
-                       goto out;
-               }
-               goto out;
-       }
-
-       ret = drmModePageFlip(ctx->fd, crtc->crtc_id, bo->fb_id, 0, 0);
-       if (ret) {
-               ALOGE("Failed to flip buffer for crtc %d", crtc->crtc_id);
-               goto out;
-       }
-
-out:
-       drmModeFreeCrtc(crtc);
-       return ret;
+int DrmHwcBuffer::ImportBuffer(buffer_handle_t handle, Importer *importer) {
+  hwc_drm_bo tmp_bo;
+
+  int ret = importer->ImportBuffer(handle, &tmp_bo);
+  if (ret)
+    return ret;
+
+  if (importer_ != NULL) {
+    importer_->ReleaseBuffer(&bo_);
+  }
+
+  importer_ = importer;
+
+  bo_ = tmp_bo;
+
+  return 0;
 }
 
-static int hwc_set(hwc_composer_device_1_t *dev, size_t num_displays,
-                       hwc_display_contents_1_t** display_contents)
-{
-       struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
-       int ret = 0, i;
+int DrmHwcNativeHandle::CopyBufferHandle(buffer_handle_t handle,
+                                         const gralloc_module_t *gralloc) {
+  native_handle_t *handle_copy = dup_buffer_handle(handle);
+  if (handle_copy == NULL) {
+    ALOGE("Failed to duplicate handle");
+    return -ENOMEM;
+  }
 
-       /* TODO: Handle acquire & release fences */
+  int ret = gralloc->registerBuffer(gralloc, handle_copy);
+  if (ret) {
+    ALOGE("Failed to register buffer handle %d", ret);
+    free_buffer_handle(handle_copy);
+    return ret;
+  }
 
-       for (i = 0; i < (int)num_displays && i < MAX_NUM_DISPLAYS; i++) {
-               display_contents[i]->retireFenceFd = -1; /* TODO: sync */
+  Clear();
 
-               ret = hwc_set_display(ctx, i, display_contents[i]);
-       }
+  gralloc_ = gralloc;
+  handle_ = handle_copy;
 
-       return ret;
+  return 0;
 }
 
-static int hwc_event_control(struct hwc_composer_device_1 */* dev */,
-                       int /* display */, int /* event */, int /* enabled */)
-{
-       int ret;
+DrmHwcNativeHandle::~DrmHwcNativeHandle() {
+  Clear();
+}
 
-       /* TODO */
-       return 0;
+void DrmHwcNativeHandle::Clear() {
+  if (gralloc_ != NULL && handle_ != NULL) {
+    gralloc_->unregisterBuffer(gralloc_, handle_);
+    free_buffer_handle(handle_);
+    gralloc_ = NULL;
+    handle_ = NULL;
+  }
 }
 
-static int hwc_set_power_mode(struct hwc_composer_device_1* dev, int display,
-                       int mode)
-{
-       struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
-       struct hwc_drm_display *hd = NULL;
-       drmModeConnectorPtr c;
-       int ret, i;
-       uint32_t dpms_prop = 0;
-       uint64_t dpms_value = 0;
-
-       ret = hwc_get_drm_display(ctx, display, &hd);
-       if (ret)
-               return ret;
-
-       c = drmModeGetConnector(ctx->fd, hd->connector_id);
-       if (!c) {
-               ALOGE("Failed to get connector %d", display);
-               return -ENODEV;
-       }
-
-       for (i = 0; !dpms_prop && i < c->count_props; i++) {
-               drmModePropertyPtr p;
-
-               p = drmModeGetProperty(ctx->fd, c->props[i]);
-               if (!p)
-                       continue;
-
-               if (!strcmp(p->name, "DPMS"))
-                       dpms_prop = c->props[i];
-
-               drmModeFreeProperty(p);
-       }
-       if (!dpms_prop) {
-               ALOGE("Failed to get DPMS property from display %d", display);
-               ret = -ENOENT;
-               goto out;
-       }
-
-       switch(mode) {
-       case HWC_POWER_MODE_OFF:
-               dpms_value = DRM_MODE_DPMS_OFF;
-               break;
-
-       /* We can't support dozing right now, so go full on */
-       case HWC_POWER_MODE_DOZE:
-       case HWC_POWER_MODE_DOZE_SUSPEND:
-       case HWC_POWER_MODE_NORMAL:
-               dpms_value = DRM_MODE_DPMS_ON;
-               break;
-       };
-
-       ret = drmModeConnectorSetProperty(ctx->fd, c->connector_id,
-                       dpms_prop, dpms_value);
-       if (ret) {
-               ALOGE("Failed to set DPMS property for display %d", display);
-               goto out;
-       }
-
-out:
-       drmModeFreeConnector(c);
-       return ret;
+int DrmHwcLayer::InitFromHwcLayer(hwc_layer_1_t *sf_layer, Importer *importer,
+                                  const gralloc_module_t *gralloc) {
+  sf_handle = sf_layer->handle;
+  alpha = sf_layer->planeAlpha;
+
+  source_crop = DrmHwcRect<float>(
+      sf_layer->sourceCropf.left, sf_layer->sourceCropf.top,
+      sf_layer->sourceCropf.right, sf_layer->sourceCropf.bottom);
+  display_frame = DrmHwcRect<int>(
+      sf_layer->displayFrame.left, sf_layer->displayFrame.top,
+      sf_layer->displayFrame.right, sf_layer->displayFrame.bottom);
+
+  switch (sf_layer->transform) {
+    case 0:
+      transform = DrmHwcTransform::kIdentity;
+      break;
+    case HWC_TRANSFORM_FLIP_H:
+      transform = DrmHwcTransform::kFlipH;
+      break;
+    case HWC_TRANSFORM_FLIP_V:
+      transform = DrmHwcTransform::kFlipV;
+      break;
+    case HWC_TRANSFORM_ROT_90:
+      transform = DrmHwcTransform::kRotate90;
+      break;
+    case HWC_TRANSFORM_ROT_180:
+      transform = DrmHwcTransform::kRotate180;
+      break;
+    case HWC_TRANSFORM_ROT_270:
+      transform = DrmHwcTransform::kRotate270;
+      break;
+    default:
+      ALOGE("Invalid transform in hwc_layer_1_t %d", sf_layer->transform);
+      return -EINVAL;
+  }
+
+  switch (sf_layer->blending) {
+    case HWC_BLENDING_NONE:
+      blending = DrmHwcBlending::kNone;
+      break;
+    case HWC_BLENDING_PREMULT:
+      blending = DrmHwcBlending::kPreMult;
+      break;
+    case HWC_BLENDING_COVERAGE:
+      blending = DrmHwcBlending::kCoverage;
+      break;
+    default:
+      ALOGE("Invalid blending in hwc_layer_1_t %d", sf_layer->blending);
+      return -EINVAL;
+  }
+
+  int ret = buffer.ImportBuffer(sf_layer->handle, importer);
+  if (ret)
+    return ret;
+
+  ret = handle.CopyBufferHandle(sf_layer->handle, gralloc);
+  if (ret)
+    return ret;
+
+  return 0;
 }
 
-static int hwc_query(struct hwc_composer_device_1 */* dev */, int what,
-                       int *value)
-{
-       switch(what) {
-       case HWC_BACKGROUND_LAYER_SUPPORTED:
-               *value = 0; /* TODO: We should do this */
-               break;
-       case HWC_VSYNC_PERIOD:
-               ALOGW("Query for deprecated vsync value, returning 60Hz");
-               *value = 1000 * 1000 * 1000 / 60;
-               break;
-       case HWC_DISPLAY_TYPES_SUPPORTED:
-               *value = HWC_DISPLAY_PRIMARY | HWC_DISPLAY_EXTERNAL;
-               break;
-       }
-       return 0;
+static void hwc_dump(struct hwc_composer_device_1 *dev, char *buff,
+                     int buff_len) {
+  struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
+  std::ostringstream out;
+
+  ctx->drm.compositor()->Dump(&out);
+  std::string out_str = out.str();
+  strncpy(buff, out_str.c_str(), std::min((size_t)buff_len, out_str.length()));
 }
 
-static void hwc_register_procs(struct hwc_composer_device_1* dev,
-                       hwc_procs_t const* procs)
-{
-       struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
+static int hwc_prepare(hwc_composer_device_1_t *dev, size_t num_displays,
+                       hwc_display_contents_1_t **display_contents) {
+  struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
+
+  char use_framebuffer_target[PROPERTY_VALUE_MAX];
+  property_get("hwc.drm.use_framebuffer_target", use_framebuffer_target, "0");
+  bool new_use_framebuffer_target = atoi(use_framebuffer_target);
+  if (ctx->use_framebuffer_target != new_use_framebuffer_target)
+    ALOGW("Starting to %s HWC_FRAMEBUFFER_TARGET",
+          new_use_framebuffer_target ? "use" : "not use");
+  ctx->use_framebuffer_target = new_use_framebuffer_target;
+
+  for (int i = 0; i < (int)num_displays; ++i) {
+    if (!display_contents[i])
+      continue;
+
+    bool use_framebuffer_target = ctx->use_framebuffer_target;
+    if (i == HWC_DISPLAY_VIRTUAL) {
+      use_framebuffer_target = true;
+    } else {
+      DrmCrtc *crtc = ctx->drm.GetCrtcForDisplay(i);
+      if (!crtc) {
+        ALOGE("No crtc for display %d", i);
+        return -ENODEV;
+      }
+    }
+
+    int num_layers = display_contents[i]->numHwLayers;
+    for (int j = 0; j < num_layers; j++) {
+      hwc_layer_1_t *layer = &display_contents[i]->hwLayers[j];
+
+      if (!use_framebuffer_target) {
+        if (layer->compositionType == HWC_FRAMEBUFFER)
+          layer->compositionType = HWC_OVERLAY;
+      } else {
+        switch (layer->compositionType) {
+          case HWC_OVERLAY:
+          case HWC_BACKGROUND:
+          case HWC_SIDEBAND:
+          case HWC_CURSOR_OVERLAY:
+            layer->compositionType = HWC_FRAMEBUFFER;
+            break;
+        }
+      }
+    }
+  }
+
+  return 0;
+}
 
-       ctx->procs = procs;
+static void hwc_add_layer_to_retire_fence(
+    hwc_layer_1_t *layer, hwc_display_contents_1_t *display_contents) {
+  if (layer->releaseFenceFd < 0)
+    return;
+
+  if (display_contents->retireFenceFd >= 0) {
+    int old_retire_fence = display_contents->retireFenceFd;
+    display_contents->retireFenceFd =
+        sync_merge("dc_retire", old_retire_fence, layer->releaseFenceFd);
+    close(old_retire_fence);
+  } else {
+    display_contents->retireFenceFd = dup(layer->releaseFenceFd);
+  }
 }
 
-static int hwc_get_display_configs(struct hwc_composer_device_1* dev,
-                       int display, uint32_t* configs, size_t* numConfigs)
-{
-       struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
-       struct hwc_drm_display *hd = NULL;
-       drmModeConnectorPtr c;
-       int ret = 0, i;
-
-       if (!*numConfigs)
-               return 0;
-
-       ret = hwc_get_drm_display(ctx, display, &hd);
-       if (ret)
-               return ret;
-
-       c = drmModeGetConnector(ctx->fd, hd->connector_id);
-       if (!c) {
-               ALOGE("Failed to get connector %d", display);
-               return -ENODEV;
-       }
-
-       if (hd->configs)
-               free(hd->configs);
-
-       hd->active_config = -1;
-       hd->configs = (drmModeModeInfoPtr)calloc(c->count_modes,
-                                       sizeof(*hd->configs));
-       if (!hd->configs) {
-               ALOGE("Failed to allocate config list for display %d", display);
-               ret = -ENOMEM;
-               hd->num_configs = 0;
-               goto out;
-       }
-
-       for (i = 0; i < c->count_modes; i++) {
-               drmModeModeInfoPtr m = &hd->configs[i];
-
-               memcpy(m, &c->modes[i], sizeof(*m));
-
-               if (i < (int)*numConfigs)
-                       configs[i] = i;
-       }
-
-       hd->num_configs = c->count_modes;
-       *numConfigs = MIN(c->count_modes, *numConfigs);
-
-out:
-       drmModeFreeConnector(c);
-       return ret;
+static int hwc_set(hwc_composer_device_1_t *dev, size_t num_displays,
+                   hwc_display_contents_1_t **sf_display_contents) {
+  ATRACE_CALL();
+  struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
+  int ret = 0;
+
+  std::vector<CheckedOutputFd> checked_output_fences;
+  std::vector<DrmHwcDisplayContents> displays_contents;
+  std::vector<DrmCompositionDisplayLayersMap> layers_map;
+  std::vector<std::vector<size_t>> layers_indices;
+  displays_contents.reserve(num_displays);
+  // layers_map.reserve(num_displays);
+  layers_indices.reserve(num_displays);
+
+  // Phase one does nothing that would cause errors. Only take ownership of FDs.
+  for (size_t i = 0; i < num_displays; ++i) {
+    hwc_display_contents_1_t *dc = sf_display_contents[i];
+    displays_contents.emplace_back();
+    DrmHwcDisplayContents &display_contents = displays_contents.back();
+    layers_indices.emplace_back();
+    std::vector<size_t> &indices_to_composite = layers_indices.back();
+
+    if (!sf_display_contents[i])
+      continue;
+
+    if (i == HWC_DISPLAY_VIRTUAL) {
+      ctx->virtual_compositor_worker.QueueComposite(dc);
+      continue;
+    }
+
+    std::ostringstream display_index_formatter;
+    display_index_formatter << "retire fence for display " << i;
+    std::string display_fence_description(display_index_formatter.str());
+    checked_output_fences.emplace_back(&dc->retireFenceFd,
+                                       display_fence_description.c_str(),
+                                       ctx->dummy_timeline);
+    display_contents.retire_fence = OutputFd(&dc->retireFenceFd);
+
+    size_t num_dc_layers = dc->numHwLayers;
+    int framebuffer_target_index = -1;
+    for (size_t j = 0; j < num_dc_layers; ++j) {
+      hwc_layer_1_t *sf_layer = &dc->hwLayers[j];
+
+      display_contents.layers.emplace_back();
+      DrmHwcLayer &layer = display_contents.layers.back();
+
+      if (sf_layer->flags & HWC_SKIP_LAYER)
+        continue;
+
+      if (!ctx->use_framebuffer_target) {
+        if (sf_layer->compositionType == HWC_OVERLAY)
+          indices_to_composite.push_back(j);
+        if (sf_layer->compositionType == HWC_FRAMEBUFFER_TARGET)
+          framebuffer_target_index = j;
+      } else {
+        if (sf_layer->compositionType == HWC_FRAMEBUFFER_TARGET)
+          indices_to_composite.push_back(j);
+      }
+
+      layer.acquire_fence.Set(sf_layer->acquireFenceFd);
+      sf_layer->acquireFenceFd = -1;
+
+      std::ostringstream layer_fence_formatter;
+      layer_fence_formatter << "release fence for layer " << j << " of display "
+                            << i;
+      std::string layer_fence_description(layer_fence_formatter.str());
+      checked_output_fences.emplace_back(&sf_layer->releaseFenceFd,
+                                         layer_fence_description.c_str(),
+                                         ctx->dummy_timeline);
+      layer.release_fence = OutputFd(&sf_layer->releaseFenceFd);
+    }
+
+    if (ctx->use_framebuffer_target) {
+      if (indices_to_composite.size() != 1) {
+        ALOGE("Expected 1 (got %d) layer with HWC_FRAMEBUFFER_TARGET",
+              indices_to_composite.size());
+        ret = -EINVAL;
+      }
+    } else {
+      if (indices_to_composite.empty() && framebuffer_target_index >= 0) {
+        hwc_layer_1_t *sf_layer = &dc->hwLayers[framebuffer_target_index];
+        if (!sf_layer->handle || (sf_layer->flags & HWC_SKIP_LAYER)) {
+          ALOGE(
+              "Expected valid layer with HWC_FRAMEBUFFER_TARGET when all "
+              "HWC_OVERLAY layers are skipped.");
+          ret = -EINVAL;
+        }
+        indices_to_composite.push_back(framebuffer_target_index);
+      }
+    }
+  }
+
+  if (ret)
+    return ret;
+
+  for (size_t i = 0; i < num_displays; ++i) {
+    hwc_display_contents_1_t *dc = sf_display_contents[i];
+    DrmHwcDisplayContents &display_contents = displays_contents[i];
+    if (!sf_display_contents[i])
+      continue;
+
+    layers_map.emplace_back();
+    DrmCompositionDisplayLayersMap &map = layers_map.back();
+    map.display = i;
+    std::vector<size_t> &indices_to_composite = layers_indices[i];
+    for (size_t j : indices_to_composite) {
+      hwc_layer_1_t *sf_layer = &dc->hwLayers[j];
+
+      DrmHwcLayer &layer = display_contents.layers[j];
+
+      ret = layer.InitFromHwcLayer(sf_layer, ctx->importer, ctx->gralloc);
+      if (ret) {
+        ALOGE("Failed to init composition from layer %d", ret);
+        return ret;
+      }
+      map.layers.emplace_back(std::move(layer));
+    }
+  }
+
+  std::unique_ptr<DrmComposition> composition(
+      ctx->drm.compositor()->CreateComposition(ctx->importer));
+  if (!composition) {
+    ALOGE("Drm composition init failed");
+    return -EINVAL;
+  }
+
+  ret = composition->SetLayers(layers_map.size(), layers_map.data());
+  if (ret) {
+    return -EINVAL;
+  }
+
+  ret = ctx->drm.compositor()->QueueComposition(std::move(composition));
+  if (ret) {
+    return -EINVAL;
+  }
+
+  for (size_t i = 0; i < num_displays; ++i) {
+    hwc_display_contents_1_t *dc = sf_display_contents[i];
+    if (!dc)
+      continue;
+
+    size_t num_dc_layers = dc->numHwLayers;
+    for (size_t j = 0; j < num_dc_layers; ++j) {
+      hwc_layer_1_t *layer = &dc->hwLayers[j];
+      if (layer->flags & HWC_SKIP_LAYER)
+        continue;
+      hwc_add_layer_to_retire_fence(layer, dc);
+    }
+  }
+
+  composition.reset(NULL);
+
+  return ret;
 }
 
-static int hwc_check_config_valid(struct hwc_context_t *ctx,
-                       drmModeConnectorPtr connector, int display,
-                       int config_idx)
-{
-       struct hwc_drm_display *hd = NULL;
-       drmModeModeInfoPtr m = NULL;
-       int ret = 0, i;
-
-       ret = hwc_get_drm_display(ctx, display, &hd);
-       if (ret)
-               return ret;
-
-       /* Make sure the requested config is still valid for the display */
-       for (i = 0; i < connector->count_modes; i++) {
-               if (hwc_mode_is_equal(&connector->modes[i],
-                               &hd->configs[config_idx])) {
-                       m = &hd->configs[config_idx];
-                       break;
-               }
-       }
-       if (!m)
-               return -ENOENT;
-
-       return 0;
+static int hwc_event_control(struct hwc_composer_device_1 *dev, int display,
+                             int event, int enabled) {
+  if (event != HWC_EVENT_VSYNC || (enabled != 0 && enabled != 1))
+    return -EINVAL;
+
+  struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
+  hwc_drm_display_t *hd = &ctx->displays[display];
+  return hd->vsync_worker.VSyncControl(enabled);
 }
 
-static int hwc_get_display_attributes(struct hwc_composer_device_1* dev,
-               int display, uint32_t config, const uint32_t* attributes,
-               int32_t* values)
-{
-       struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
-       struct hwc_drm_display *hd = NULL;
-       drmModeConnectorPtr c;
-       drmModeModeInfoPtr m;
-       int ret, i;
-
-       ret = hwc_get_drm_display(ctx, display, &hd);
-       if (ret)
-               return ret;
-
-       if (config >= hd->num_configs) {
-               ALOGE("Requested config is out-of-bounds %d %d", config,
-                       hd->num_configs);
-               return -EINVAL;
-       }
-
-       c = drmModeGetConnector(ctx->fd, hd->connector_id);
-       if (!c) {
-               ALOGE("Failed to get connector %d", display);
-               return -ENODEV;
-       }
-
-       ret = hwc_check_config_valid(ctx, c, display, (int)config);
-       if (ret) {
-               ALOGE("Provided config is no longer valid %u", config);
-               goto out;
-       }
-
-       m = &hd->configs[config];
-       for (i = 0; attributes[i] != HWC_DISPLAY_NO_ATTRIBUTE; i++) {
-               switch(attributes[i]) {
-               case HWC_DISPLAY_VSYNC_PERIOD:
-                       values[i] = 1000 * 1000 * 1000 / m->vrefresh;
-                       break;
-               case HWC_DISPLAY_WIDTH:
-                       values[i] = m->hdisplay;
-                       break;
-               case HWC_DISPLAY_HEIGHT:
-                       values[i] = m->vdisplay;
-                       break;
-               case HWC_DISPLAY_DPI_X:
-                       /* Dots per 1000 inches */
-                       values[i] = c->mmWidth ?
-                               (m->hdisplay * UM_PER_INCH) / c->mmWidth : 0;
-                       break;
-               case HWC_DISPLAY_DPI_Y:
-                       /* Dots per 1000 inches */
-                       values[i] = c->mmHeight ?
-                               (m->vdisplay * UM_PER_INCH) / c->mmHeight : 0;
-                       break;
-               }
-       }
-
-out:
-       drmModeFreeConnector(c);
-       return ret;
+static int hwc_set_power_mode(struct hwc_composer_device_1 *dev, int display,
+                              int mode) {
+  struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
+
+  uint64_t dpmsValue = 0;
+  switch (mode) {
+    case HWC_POWER_MODE_OFF:
+      dpmsValue = DRM_MODE_DPMS_OFF;
+      break;
+
+    /* We can't support dozing right now, so go full on */
+    case HWC_POWER_MODE_DOZE:
+    case HWC_POWER_MODE_DOZE_SUSPEND:
+    case HWC_POWER_MODE_NORMAL:
+      dpmsValue = DRM_MODE_DPMS_ON;
+      break;
+  };
+  return ctx->drm.SetDpmsMode(display, dpmsValue);
 }
 
-static int hwc_get_active_config(struct hwc_composer_device_1* dev, int display)
-{
-       struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
-       struct hwc_drm_display *hd = NULL;
-       drmModeConnectorPtr c;
-       int ret;
-
-       ret = hwc_get_drm_display(ctx, display, &hd);
-       if (ret)
-               return ret;
-
-       if (hd->active_config < 0)
-               return -1;
-
-       c = drmModeGetConnector(ctx->fd, hd->connector_id);
-       if (!c) {
-               ALOGE("Failed to get connector %d", display);
-               return -ENODEV;
-       }
-
-       ret = hwc_check_config_valid(ctx, c, display, hd->active_config);
-       if (ret) {
-               ALOGE("Config is no longer valid %d", hd->active_config);
-               ret = -1;
-               goto out;
-       }
-
-       ret = hd->active_config;
-
-out:
-       drmModeFreeConnector(c);
-       return ret;
+static int hwc_query(struct hwc_composer_device_1 * /* dev */, int what,
+                     int *value) {
+  switch (what) {
+    case HWC_BACKGROUND_LAYER_SUPPORTED:
+      *value = 0; /* TODO: We should do this */
+      break;
+    case HWC_VSYNC_PERIOD:
+      ALOGW("Query for deprecated vsync value, returning 60Hz");
+      *value = 1000 * 1000 * 1000 / 60;
+      break;
+    case HWC_DISPLAY_TYPES_SUPPORTED:
+      *value = HWC_DISPLAY_PRIMARY | HWC_DISPLAY_EXTERNAL | HWC_DISPLAY_VIRTUAL;
+      break;
+  }
+  return 0;
 }
 
-static bool hwc_crtc_is_bound(struct hwc_context_t *ctx, uint32_t crtc_id)
-{
-       int i;
+static void hwc_register_procs(struct hwc_composer_device_1 *dev,
+                               hwc_procs_t const *procs) {
+  struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
+
+  ctx->procs = procs;
+
+  for (hwc_context_t::DisplayMapIter iter = ctx->displays.begin();
+       iter != ctx->displays.end(); ++iter) {
+    iter->second.vsync_worker.SetProcs(procs);
+  }
+}
 
-       for (i = 0; i < MAX_NUM_DISPLAYS; i++) {
-               if (ctx->displays[i].active_crtc == crtc_id)
-                       return true;
-       }
-       return false;
+static int hwc_get_display_configs(struct hwc_composer_device_1 *dev,
+                                   int display, uint32_t *configs,
+                                   size_t *num_configs) {
+  if (!*num_configs)
+    return 0;
+
+  struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
+  hwc_drm_display_t *hd = &ctx->displays[display];
+  hd->config_ids.clear();
+
+  DrmConnector *connector = ctx->drm.GetConnectorForDisplay(display);
+  if (!connector) {
+    ALOGE("Failed to get connector for display %d", display);
+    return -ENODEV;
+  }
+
+  int ret = connector->UpdateModes();
+  if (ret) {
+    ALOGE("Failed to update display modes %d", ret);
+    return ret;
+  }
+
+  for (DrmConnector::ModeIter iter = connector->begin_modes();
+       iter != connector->end_modes(); ++iter) {
+    size_t idx = hd->config_ids.size();
+    if (idx == *num_configs)
+      break;
+    hd->config_ids.push_back(iter->id());
+    configs[idx] = iter->id();
+  }
+  *num_configs = hd->config_ids.size();
+  return *num_configs == 0 ? -1 : 0;
 }
 
-static int hwc_try_encoder(struct hwc_context_t *ctx, drmModeResPtr r,
-                       uint32_t encoder_id, uint32_t *crtc_id)
-{
-       drmModeEncoderPtr e;
-       int ret, i;
-
-       e = drmModeGetEncoder(ctx->fd, encoder_id);
-       if (!e) {
-               ALOGE("Failed to get encoder for connector %d", encoder_id);
-               return -ENODEV;
-       }
-
-       /* First try to use the currently-bound crtc */
-       if (e->crtc_id) {
-               if (!hwc_crtc_is_bound(ctx, e->crtc_id)) {
-                       *crtc_id = e->crtc_id;
-                       ret = 0;
-                       goto out;
-               }
-       }
-
-       /* Try to find a possible crtc which will work */
-       for (i = 0; i < r->count_crtcs; i++) {
-               if (!(e->possible_crtcs & (1 << i)))
-                       continue;
-
-               /* We've already tried this earlier */
-               if (e->crtc_id == r->crtcs[i])
-                       continue;
-
-               if (!hwc_crtc_is_bound(ctx, r->crtcs[i])) {
-                       *crtc_id = r->crtcs[i];
-                       ret = 0;
-                       goto out;
-               }
-       }
-
-       /* We can't use the encoder, but nothing went wrong, try another one */
-       ret = -EAGAIN;
-
-out:
-       drmModeFreeEncoder(e);
-       return ret;
+static int hwc_get_display_attributes(struct hwc_composer_device_1 *dev,
+                                      int display, uint32_t config,
+                                      const uint32_t *attributes,
+                                      int32_t *values) {
+  struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
+  DrmConnector *c = ctx->drm.GetConnectorForDisplay(display);
+  if (!c) {
+    ALOGE("Failed to get DrmConnector for display %d", display);
+    return -ENODEV;
+  }
+  DrmMode mode;
+  for (DrmConnector::ModeIter iter = c->begin_modes(); iter != c->end_modes();
+       ++iter) {
+    if (iter->id() == config) {
+      mode = *iter;
+      break;
+    }
+  }
+  if (mode.id() == 0) {
+    ALOGE("Failed to find active mode for display %d", display);
+    return -ENOENT;
+  }
+
+  uint32_t mm_width = c->mm_width();
+  uint32_t mm_height = c->mm_height();
+  for (int i = 0; attributes[i] != HWC_DISPLAY_NO_ATTRIBUTE; ++i) {
+    switch (attributes[i]) {
+      case HWC_DISPLAY_VSYNC_PERIOD:
+        values[i] = 1000 * 1000 * 1000 / mode.v_refresh();
+        break;
+      case HWC_DISPLAY_WIDTH:
+        values[i] = mode.h_display();
+        break;
+      case HWC_DISPLAY_HEIGHT:
+        values[i] = mode.v_display();
+        break;
+      case HWC_DISPLAY_DPI_X:
+        /* Dots per 1000 inches */
+        values[i] = mm_width ? (mode.h_display() * UM_PER_INCH) / mm_width : 0;
+        break;
+      case HWC_DISPLAY_DPI_Y:
+        /* Dots per 1000 inches */
+        values[i] =
+            mm_height ? (mode.v_display() * UM_PER_INCH) / mm_height : 0;
+        break;
+    }
+  }
+  return 0;
 }
 
-static int hwc_set_active_config(struct hwc_composer_device_1* dev, int display,
-                       int index)
-{
-       struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
-       struct hwc_drm_display *hd = NULL;
-       drmModeResPtr r = NULL;
-       drmModeConnectorPtr c;
-       uint32_t crtc_id = 0;
-       int ret, i;
-       bool new_crtc, new_encoder;
-
-       ret = hwc_get_drm_display(ctx, display, &hd);
-       if (ret)
-               return ret;
-
-       c = drmModeGetConnector(ctx->fd, hd->connector_id);
-       if (!c) {
-               ALOGE("Failed to get connector %d", display);
-               return -ENODEV;
-       }
-
-       if (c->connection == DRM_MODE_DISCONNECTED) {
-               ALOGE("Tried to configure a disconnected display %d", display);
-               ret = -ENODEV;
-               goto out;
-       }
-
-       ret = hwc_check_config_valid(ctx, c, display, index);
-       if (ret) {
-               ALOGE("Provided config is no longer valid %u", index);
-               ret = -ENOENT;
-               goto out;
-       }
-
-       r = drmModeGetResources(ctx->fd);
-       if (!r) {
-               ALOGE("Failed to get drm resources");
-               goto out;
-       }
-
-       /* We no longer have an active_crtc */
-       hd->active_crtc = 0;
-
-       /* First, try to use the currently-connected encoder */
-       if (c->encoder_id) {
-               ret = hwc_try_encoder(ctx, r, c->encoder_id, &crtc_id);
-               if (ret && ret != -EAGAIN) {
-                       ALOGE("Encoder try failed %d", ret);
-                       goto out;
-               }
-       }
-
-       /* We couldn't find a crtc with the attached encoder, try the others */
-       if (!crtc_id) {
-               for (i = 0; i < c->count_encoders; i++) {
-                       ret = hwc_try_encoder(ctx, r, c->encoders[i], &crtc_id);
-                       if (!ret) {
-                               break;
-                       } else if (ret != -EAGAIN) {
-                               ALOGE("Encoder try failed %d", ret);
-                               goto out;
-                       }
-               }
-               if (!crtc_id) {
-                       ALOGE("Couldn't find valid crtc to modeset");
-                       ret = -EINVAL;
-                       goto out;
-               }
-       }
-
-       hd->active_crtc = crtc_id;
-       hd->active_config = index;
-
-       /* TODO: Once we have atomic, set the crtc timing info here */
-
-out:
-       if (r)
-               drmModeFreeResources(r);
-
-       drmModeFreeConnector(c);
-       return ret;
+static int hwc_get_active_config(struct hwc_composer_device_1 *dev,
+                                 int display) {
+  struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
+  DrmConnector *c = ctx->drm.GetConnectorForDisplay(display);
+  if (!c) {
+    ALOGE("Failed to get DrmConnector for display %d", display);
+    return -ENODEV;
+  }
+
+  DrmMode mode = c->active_mode();
+  hwc_drm_display_t *hd = &ctx->displays[display];
+  for (size_t i = 0; i < hd->config_ids.size(); ++i) {
+    if (hd->config_ids[i] == mode.id())
+      return i;
+  }
+  return -1;
 }
 
-static int hwc_device_close(struct hw_device_t *dev)
-{
-       struct hwc_context_t *ctx = (struct hwc_context_t *)dev;
+static int hwc_set_active_config(struct hwc_composer_device_1 *dev, int display,
+                                 int index) {
+  struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
+  hwc_drm_display_t *hd = &ctx->displays[display];
+  if (index >= (int)hd->config_ids.size()) {
+    ALOGE("Invalid config index %d passed in", index);
+    return -EINVAL;
+  }
+
+  DrmConnector *c = ctx->drm.GetConnectorForDisplay(display);
+  if (!c) {
+    ALOGE("Failed to get connector for display %d", display);
+    return -ENODEV;
+  }
+  DrmMode mode;
+  for (DrmConnector::ModeIter iter = c->begin_modes(); iter != c->end_modes();
+       ++iter) {
+    if (iter->id() == hd->config_ids[index]) {
+      mode = *iter;
+      break;
+    }
+  }
+  if (mode.id() != hd->config_ids[index]) {
+    ALOGE("Could not find active mode for %d/%d", index, hd->config_ids[index]);
+    return -ENOENT;
+  }
+  int ret = ctx->drm.SetDisplayActiveMode(display, mode);
+  if (ret) {
+    ALOGE("Failed to set active config %d", ret);
+    return ret;
+  }
+  return ret;
+}
 
-       free(ctx);
+static int hwc_device_close(struct hw_device_t *dev) {
+  struct hwc_context_t *ctx = (struct hwc_context_t *)dev;
+  delete ctx;
+  return 0;
+}
 
-       return 0;
+/*
+ * TODO: This function sets the active config to the first one in the list. This
+ * should be fixed such that it selects the preferred mode for the display, or
+ * some other, saner, method of choosing the config.
+ */
+static int hwc_set_initial_config(hwc_drm_display_t *hd) {
+  uint32_t config;
+  size_t num_configs = 1;
+  int ret = hwc_get_display_configs(&hd->ctx->device, hd->display, &config,
+                                    &num_configs);
+  if (ret || !num_configs)
+    return 0;
+
+  ret = hwc_set_active_config(&hd->ctx->device, hd->display, 0);
+  if (ret) {
+    ALOGE("Failed to set active config d=%d ret=%d", hd->display, ret);
+    return ret;
+  }
+
+  return ret;
 }
 
-static int hwc_initialize_display(struct hwc_context_t *ctx, int display,
-                       uint32_t connector_id)
-{
-       struct hwc_drm_display *hd = NULL;
-       int ret;
+static int hwc_initialize_display(struct hwc_context_t *ctx, int display) {
+  hwc_drm_display_t *hd = &ctx->displays[display];
+  hd->ctx = ctx;
+  hd->display = display;
 
-       ret = hwc_get_drm_display(ctx, display, &hd);
-       if (ret)
-               return ret;
+  int ret = hwc_set_initial_config(hd);
+  if (ret) {
+    ALOGE("Failed to set initial config for d=%d ret=%d", display, ret);
+    return ret;
+  }
 
-       hd->active_config = -1;
-       hd->connector_id = connector_id;
+  ret = hd->vsync_worker.Init(&ctx->drm, display);
+  if (ret) {
+    ALOGE("Failed to create event worker for display %d %d\n", display, ret);
+    return ret;
+  }
 
-       return 0;
+  return 0;
 }
 
-static int hwc_enumerate_displays(struct hwc_context_t *ctx)
-{
-       struct hwc_drm_display *panel_hd;
-       drmModeResPtr res;
-       drmModeConnectorPtr *conn_list;
-       int ret = 0, i, j;
-
-       res = drmModeGetResources(ctx->fd);
-       if (!res) {
-               ALOGE("Failed to get drm resources");
-               return -ENODEV;
-       }
-
-       conn_list = (drmModeConnector **)calloc(res->count_connectors,
-                       sizeof(*conn_list));
-       if (!conn_list) {
-               ALOGE("Failed to allocate connector list");
-               ret = -ENOMEM;
-               goto out;
-       }
-
-       for (i = 0; i < res->count_connectors; i++) {
-               conn_list[i] = drmModeGetConnector(ctx->fd, res->connectors[i]);
-               if (!conn_list[i]) {
-                       ALOGE("Failed to get connector %d", res->connectors[i]);
-                       ret = -ENODEV;
-                       goto out;
-               }
-       }
-
-       ctx->num_displays = 0;
-
-       /* Find a connected, panel type connector for display 0 */
-       for (i = 0; i < res->count_connectors; i++) {
-               drmModeConnectorPtr c = conn_list[i];
-
-               for (j = 0; j < ARRAY_SIZE(panel_types); j++) {
-                       if (c->connector_type == panel_types[j] &&
-                           c->connection == DRM_MODE_CONNECTED)
-                               break;
-               }
-               if (j == ARRAY_SIZE(panel_types))
-                       continue;
-
-               hwc_initialize_display(ctx, ctx->num_displays, c->connector_id);
-               ctx->num_displays++;
-               break;
-       }
-
-       ret = hwc_get_drm_display(ctx, 0, &panel_hd);
-       if (ret)
-               goto out;
-
-       /* Fill in the other displays */
-       for (i = 0; i < res->count_connectors; i++) {
-               drmModeConnectorPtr c = conn_list[i];
-
-               if (panel_hd->connector_id == c->connector_id)
-                       continue;
-
-               hwc_initialize_display(ctx, ctx->num_displays, c->connector_id);
-               ctx->num_displays++;
-       }
-
-out:
-       for (i = 0; i < res->count_connectors; i++) {
-               if (conn_list[i])
-                       drmModeFreeConnector(conn_list[i]);
-       }
-       free(conn_list);
-
-       if (res)
-               drmModeFreeResources(res);
-
-       return ret;
+static int hwc_enumerate_displays(struct hwc_context_t *ctx) {
+  int ret;
+  for (DrmResources::ConnectorIter c = ctx->drm.begin_connectors();
+       c != ctx->drm.end_connectors(); ++c) {
+    ret = hwc_initialize_display(ctx, (*c)->display());
+    if (ret) {
+      ALOGE("Failed to initialize display %d", (*c)->display());
+      return ret;
+    }
+  }
+
+  ret = ctx->virtual_compositor_worker.Init();
+  if (ret) {
+    ALOGE("Failed to initialize virtual compositor worker");
+    return ret;
+  }
+  return 0;
 }
 
-static int hwc_device_open(const struct hw_module_t* module, const char* name,
-                       struct hw_device_t** dev)
-{
-       int ret = 0;
-       struct hwc_context_t *ctx;
-
-       if (strcmp(name, HWC_HARDWARE_COMPOSER)) {
-               ALOGE("Invalid module name- %s", name);
-               return -EINVAL;
-       }
-
-       ctx = (hwc_context_t *)calloc(1, sizeof(*ctx));
-       if (!ctx) {
-               ALOGE("Failed to allocate hwc context");
-               return -ENOMEM;
-       }
-
-       /* TODO: NUKE THIS */
-       ret = hw_get_module(GRALLOC_HARDWARE_MODULE_ID,
-                       (const hw_module_t **)&ctx->gralloc_module);
-       if (ret) {
-               ALOGE("Failed to open gralloc module");
-               goto out;
-       }
-
-       /* TODO: Use drmOpenControl here instead */
-       ctx->fd = open(HWCOMPOSER_DRM_DEVICE, O_RDWR);
-       if (ctx->fd < 0) {
-               ALOGE("Failed to open dri- %s", strerror(-errno));
-               goto out;
-       }
-
-       ret = drmSetMaster(ctx->fd);
-       if (ret) {
-               ALOGE("Failed to set hwcomposer as drm master %d", ret);
-               goto out;
-       }
-
-       ret = hwc_enumerate_displays(ctx);
-       if (ret) {
-               ALOGE("Failed to enumerate displays: %s", strerror(ret));
-               goto out;
-       }
-
-       ctx->device.common.tag = HARDWARE_DEVICE_TAG;
-       ctx->device.common.version = HWC_DEVICE_API_VERSION_1_4;
-       ctx->device.common.module = const_cast<hw_module_t*>(module);
-       ctx->device.common.close = hwc_device_close;
-
-       ctx->device.prepare = hwc_prepare;
-       ctx->device.set = hwc_set;
-       ctx->device.eventControl = hwc_event_control;
-       ctx->device.setPowerMode = hwc_set_power_mode;
-       ctx->device.query = hwc_query;
-       ctx->device.registerProcs = hwc_register_procs;
-       ctx->device.getDisplayConfigs = hwc_get_display_configs;
-       ctx->device.getDisplayAttributes = hwc_get_display_attributes;
-       ctx->device.getActiveConfig = hwc_get_active_config;
-       ctx->device.setActiveConfig = hwc_set_active_config;
-       ctx->device.setCursorPositionAsync = NULL; /* TODO: Add cursor */
-
-       *dev = &ctx->device.common;
-
-       return 0;
-out:
-       if (ctx->fd >= 0)
-               close(ctx->fd);
-
-       free(ctx);
-       return ret;
+static int hwc_device_open(const struct hw_module_t *module, const char *name,
+                           struct hw_device_t **dev) {
+  if (strcmp(name, HWC_HARDWARE_COMPOSER)) {
+    ALOGE("Invalid module name- %s", name);
+    return -EINVAL;
+  }
+
+  struct hwc_context_t *ctx = new hwc_context_t();
+  if (!ctx) {
+    ALOGE("Failed to allocate hwc context");
+    return -ENOMEM;
+  }
+
+  int ret = ctx->drm.Init();
+  if (ret) {
+    ALOGE("Can't initialize Drm object %d", ret);
+    delete ctx;
+    return ret;
+  }
+
+  ret = hw_get_module(GRALLOC_HARDWARE_MODULE_ID,
+                      (const hw_module_t **)&ctx->gralloc);
+  if (ret) {
+    ALOGE("Failed to open gralloc module %d", ret);
+    delete ctx;
+    return ret;
+  }
+
+  ret = ctx->dummy_timeline.Init();
+  if (ret) {
+    ALOGE("Failed to create dummy sw sync timeline %d", ret);
+    return ret;
+  }
+
+  ctx->importer = Importer::CreateInstance(&ctx->drm);
+  if (!ctx->importer) {
+    ALOGE("Failed to create importer instance");
+    delete ctx;
+    return ret;
+  }
+
+  ret = hwc_enumerate_displays(ctx);
+  if (ret) {
+    ALOGE("Failed to enumerate displays: %s", strerror(ret));
+    delete ctx;
+    return ret;
+  }
+
+  ctx->device.common.tag = HARDWARE_DEVICE_TAG;
+  ctx->device.common.version = HWC_DEVICE_API_VERSION_1_4;
+  ctx->device.common.module = const_cast<hw_module_t *>(module);
+  ctx->device.common.close = hwc_device_close;
+
+  ctx->device.dump = hwc_dump;
+  ctx->device.prepare = hwc_prepare;
+  ctx->device.set = hwc_set;
+  ctx->device.eventControl = hwc_event_control;
+  ctx->device.setPowerMode = hwc_set_power_mode;
+  ctx->device.query = hwc_query;
+  ctx->device.registerProcs = hwc_register_procs;
+  ctx->device.getDisplayConfigs = hwc_get_display_configs;
+  ctx->device.getDisplayAttributes = hwc_get_display_attributes;
+  ctx->device.getActiveConfig = hwc_get_active_config;
+  ctx->device.setActiveConfig = hwc_set_active_config;
+  ctx->device.setCursorPositionAsync = NULL; /* TODO: Add cursor */
+
+  *dev = &ctx->device.common;
+
+  return 0;
+}
 }
 
 static struct hw_module_methods_t hwc_module_methods = {
-       open: hwc_device_open
+  open : android::hwc_device_open
 };
 
 hwc_module_t HAL_MODULE_INFO_SYM = {
-       common: {
-               tag: HARDWARE_MODULE_TAG,
-               version_major: 1,
-               version_minor: 0,
-               id: HWC_HARDWARE_MODULE_ID,
-               name: "DRM hwcomposer module",
-               author: "The Android Open Source Project",
-               methods: &hwc_module_methods,
-               dso: NULL,
-               reserved: { 0 },
-       }
+  common : {
+    tag : HARDWARE_MODULE_TAG,
+    version_major : 1,
+    version_minor : 0,
+    id : HWC_HARDWARE_MODULE_ID,
+    name : "DRM hwcomposer module",
+    author : "The Android Open Source Project",
+    methods : &hwc_module_methods,
+    dso : NULL,
+    reserved : {0},
+  }
 };