drm_hwcomposer: Wrap libdrm ops (minus modeset/flip) in C++ classes

This allows us to compartmentalize a bunch of code/logic from
hwcomposer.cpp into drm classes.

Signed-off-by: Sean Paul <seanpaul@chromium.org>

Change-Id: Id3f912126f1fdcd44d32c3eb4fba646f77590278
diff --git a/Android.mk b/Android.mk
index e3c3f0e..39279ed 100644
--- a/Android.mk
+++ b/Android.mk
@@ -38,7 +38,16 @@
 	system/core/libsync \
 	system/core/libsync/include \
 
-LOCAL_SRC_FILES := hwcomposer.cpp compositor.cpp
+LOCAL_SRC_FILES := \
+	compositor.cpp \
+	drmresources.cpp \
+	drmconnector.cpp \
+	drmcrtc.cpp \
+	drmencoder.cpp \
+	drmmode.cpp \
+	drmplane.cpp \
+	drmproperty.cpp \
+	hwcomposer.cpp
 
 ifeq ($(strip $(BUFFER_IMPORTER)),drm-gralloc)
 LOCAL_C_INCLUDES += external/drm_gralloc
diff --git a/drmconnector.cpp b/drmconnector.cpp
new file mode 100644
index 0000000..44864b9
--- /dev/null
+++ b/drmconnector.cpp
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "hwc-drm-connector"
+
+#include "drmconnector.h"
+#include "drmresources.h"
+
+#include <errno.h>
+#include <stdint.h>
+
+#include <cutils/log.h>
+#include <xf86drmMode.h>
+
+namespace android {
+
+DrmConnector::DrmConnector(DrmResources *drm, drmModeConnectorPtr c,
+                           DrmEncoder *current_encoder,
+                           std::vector<DrmEncoder *> &possible_encoders)
+    : drm_(drm),
+      id_(c->connector_id),
+      encoder_(current_encoder),
+      display_(-1),
+      type_(c->connector_type),
+      state_(c->connection),
+      mm_width_(c->mmWidth),
+      mm_height_(c->mmHeight),
+      possible_encoders_(possible_encoders) {
+}
+
+DrmConnector::~DrmConnector() {
+}
+
+int DrmConnector::Init() {
+  int ret = drm_->GetConnectorProperty(*this, "DPMS", &dpms_property_);
+  if (ret) {
+    ALOGE("Could not get DPMS property\n");
+    return ret;
+  }
+  return 0;
+}
+
+uint32_t DrmConnector::id() const {
+  return id_;
+}
+
+int DrmConnector::display() const {
+  return display_;
+}
+
+void DrmConnector::set_display(int display) {
+  display_ = display;
+}
+
+bool DrmConnector::built_in() const {
+  return type_ == DRM_MODE_CONNECTOR_LVDS || type_ == DRM_MODE_CONNECTOR_eDP ||
+         type_ == DRM_MODE_CONNECTOR_DSI;
+}
+
+int DrmConnector::UpdateModes() {
+  int fd = drm_->fd();
+
+  drmModeConnectorPtr c = drmModeGetConnector(fd, id_);
+  if (!c) {
+    ALOGE("Failed to get connector %d", id_);
+    return -ENODEV;
+  }
+
+  std::vector<DrmMode> new_modes;
+  for (int i = 0; i < c->count_modes; ++i) {
+    bool exists = false;
+    for (std::vector<DrmMode>::iterator iter = modes_.begin();
+         iter != modes_.end(); ++iter) {
+      if (*iter == c->modes[i]) {
+        new_modes.push_back(*iter);
+        exists = true;
+        break;
+      }
+    }
+    if (exists)
+      continue;
+
+    DrmMode m(&c->modes[i]);
+    m.set_id(drm_->next_mode_id());
+    new_modes.push_back(m);
+  }
+  modes_.swap(new_modes);
+  return 0;
+}
+
+const DrmMode &DrmConnector::active_mode() const {
+  return active_mode_;
+}
+
+int DrmConnector::set_active_mode(uint32_t mode_id) {
+  for (std::vector<DrmMode>::const_iterator iter = modes_.begin();
+       iter != modes_.end(); ++iter) {
+    if (iter->id() == mode_id) {
+      active_mode_ = *iter;
+      return 0;
+    }
+  }
+  return -ENOENT;
+}
+
+const DrmProperty &DrmConnector::dpms_property() const {
+  return dpms_property_;
+}
+
+DrmConnector::ModeIter DrmConnector::begin_modes() const {
+  return modes_.begin();
+}
+
+DrmConnector::ModeIter DrmConnector::end_modes() const {
+  return modes_.end();
+}
+
+DrmEncoder *DrmConnector::encoder() const {
+  return encoder_;
+}
+
+void DrmConnector::set_encoder(DrmEncoder *encoder) {
+  encoder_ = encoder;
+}
+
+DrmConnector::EncoderIter DrmConnector::begin_possible_encoders() const {
+  return possible_encoders_.begin();
+}
+
+DrmConnector::EncoderIter DrmConnector::end_possible_encoders() const {
+  return possible_encoders_.end();
+}
+
+uint32_t DrmConnector::mm_width() const {
+  return mm_width_;
+}
+
+uint32_t DrmConnector::mm_height() const {
+  return mm_height_;
+}
+}
diff --git a/drmconnector.h b/drmconnector.h
new file mode 100644
index 0000000..b31d9a9
--- /dev/null
+++ b/drmconnector.h
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_DRM_CONNECTOR_H_
+#define ANDROID_DRM_CONNECTOR_H_
+
+#include "drmencoder.h"
+#include "drmmode.h"
+#include "drmproperty.h"
+
+#include <stdint.h>
+#include <vector>
+#include <xf86drmMode.h>
+
+namespace android {
+
+class DrmResources;
+
+class DrmConnector {
+ public:
+  typedef std::vector<DrmEncoder *>::const_iterator EncoderIter;
+  typedef std::vector<DrmMode>::const_iterator ModeIter;
+
+  DrmConnector(DrmResources *drm, drmModeConnectorPtr c,
+               DrmEncoder *current_encoder,
+               std::vector<DrmEncoder *> &possible_encoders);
+  ~DrmConnector();
+
+  int Init();
+
+  uint32_t id() const;
+
+  int display() const;
+  void set_display(int display);
+
+  bool built_in() const;
+
+  int UpdateModes();
+
+  ModeIter begin_modes() const;
+  ModeIter end_modes() const;
+  const DrmMode &active_mode() const;
+  int set_active_mode(uint32_t mode_id);
+
+  const DrmProperty &dpms_property() const;
+
+  EncoderIter begin_possible_encoders() const;
+  EncoderIter end_possible_encoders() const;
+  DrmEncoder *encoder() const;
+  void set_encoder(DrmEncoder *encoder);
+
+  uint32_t mm_width() const;
+  uint32_t mm_height() const;
+
+ private:
+  DrmConnector(const DrmConnector &);
+
+  DrmResources *drm_;
+
+  uint32_t id_;
+  DrmEncoder *encoder_;
+  int display_;
+
+  uint32_t type_;
+  drmModeConnection state_;
+
+  uint32_t mm_width_;
+  uint32_t mm_height_;
+
+  DrmMode active_mode_;
+  std::vector<DrmMode> modes_;
+
+  DrmProperty dpms_property_;
+
+  std::vector<DrmEncoder *> possible_encoders_;
+};
+}
+
+#endif  // ANDROID_DRM_PLANE_H_
diff --git a/drmcrtc.cpp b/drmcrtc.cpp
new file mode 100644
index 0000000..a7b17c4
--- /dev/null
+++ b/drmcrtc.cpp
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "drmcrtc.h"
+#include "drmresources.h"
+
+#include <stdint.h>
+#include <xf86drmMode.h>
+
+namespace android {
+
+DrmCrtc::DrmCrtc(drmModeCrtcPtr c, unsigned pipe)
+    : id_(c->crtc_id),
+      pipe_(pipe),
+      display_(-1),
+      requires_modeset_(true),
+      x_(c->x),
+      y_(c->y),
+      width_(c->width),
+      height_(c->height),
+      mode_(&c->mode),
+      modeValid_(c->mode_valid) {
+}
+
+DrmCrtc::~DrmCrtc() {
+}
+
+uint32_t DrmCrtc::id() const {
+  return id_;
+}
+
+unsigned DrmCrtc::pipe() const {
+  return pipe_;
+}
+
+bool DrmCrtc::requires_modeset() const {
+  return requires_modeset_;
+}
+
+void DrmCrtc::set_requires_modeset(bool requires_modeset) {
+  requires_modeset_ = requires_modeset;
+}
+
+int DrmCrtc::display() const {
+  return display_;
+}
+
+void DrmCrtc::set_display(int display) {
+  display_ = display;
+  requires_modeset_ = true;
+}
+
+bool DrmCrtc::can_bind(int display) const {
+  return display_ == -1 || display_ == display;
+}
+}
diff --git a/drmcrtc.h b/drmcrtc.h
new file mode 100644
index 0000000..cf4ec65
--- /dev/null
+++ b/drmcrtc.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_DRM_CRTC_H_
+#define ANDROID_DRM_CRTC_H_
+
+#include "drmmode.h"
+
+#include <stdint.h>
+#include <xf86drmMode.h>
+
+namespace android {
+
+class DrmCrtc {
+ public:
+  DrmCrtc(drmModeCrtcPtr c, unsigned pipe);
+  ~DrmCrtc();
+
+  uint32_t id() const;
+  unsigned pipe() const;
+
+  bool requires_modeset() const;
+  void set_requires_modeset(bool requires_modeset);
+
+  int display() const;
+  void set_display(int display);
+
+  bool can_bind(int display) const;
+
+ private:
+  DrmCrtc(const DrmCrtc &);
+
+  uint32_t id_;
+  unsigned pipe_;
+  int display_;
+
+  bool requires_modeset_;
+
+  uint32_t x_;
+  uint32_t y_;
+  uint32_t width_;
+  uint32_t height_;
+
+  DrmMode mode_;
+  bool modeValid_;
+};
+}
+
+#endif  // ANDROID_DRM_CRTC_H_
diff --git a/drmencoder.cpp b/drmencoder.cpp
new file mode 100644
index 0000000..39ab88b
--- /dev/null
+++ b/drmencoder.cpp
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "drmcrtc.h"
+#include "drmencoder.h"
+#include "drmresources.h"
+
+#include <stdint.h>
+#include <xf86drmMode.h>
+
+namespace android {
+
+DrmEncoder::DrmEncoder(drmModeEncoderPtr e, DrmCrtc *current_crtc,
+                       const std::vector<DrmCrtc *> &possible_crtcs)
+    : id_(e->encoder_id),
+      crtc_(current_crtc),
+      type_(e->encoder_type),
+      possible_crtcs_(possible_crtcs) {
+}
+
+DrmEncoder::~DrmEncoder() {
+}
+
+uint32_t DrmEncoder::id() const {
+  return id_;
+}
+
+DrmCrtc *DrmEncoder::crtc() const {
+  return crtc_;
+}
+
+void DrmEncoder::set_crtc(DrmCrtc *crtc) {
+  crtc_ = crtc;
+}
+
+DrmEncoder::CrtcIter DrmEncoder::begin_possible_crtcs() const {
+  return possible_crtcs_.begin();
+}
+
+DrmEncoder::CrtcIter DrmEncoder::end_possible_crtcs() const {
+  return possible_crtcs_.end();
+}
+}
diff --git a/drmencoder.h b/drmencoder.h
new file mode 100644
index 0000000..cf33069
--- /dev/null
+++ b/drmencoder.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_DRM_ENCODER_H_
+#define ANDROID_DRM_ENCODER_H_
+
+#include "drmcrtc.h"
+
+#include <stdint.h>
+#include <vector>
+#include <xf86drmMode.h>
+
+namespace android {
+
+class DrmEncoder {
+ public:
+  typedef std::vector<DrmCrtc *>::const_iterator CrtcIter;
+
+  DrmEncoder(drmModeEncoderPtr e, DrmCrtc *current_crtc,
+             const std::vector<DrmCrtc *> &possible_crtcs);
+  ~DrmEncoder();
+
+  uint32_t id() const;
+
+  DrmCrtc *crtc() const;
+  void set_crtc(DrmCrtc *crtc);
+
+  CrtcIter begin_possible_crtcs() const;
+  CrtcIter end_possible_crtcs() const;
+
+ private:
+  DrmEncoder(const DrmEncoder &);
+
+  uint32_t id_;
+  DrmCrtc *crtc_;
+
+  uint32_t type_;
+
+  std::vector<DrmCrtc *> possible_crtcs_;
+};
+}
+
+#endif  // ANDROID_DRM_ENCODER_H_
diff --git a/drmmode.cpp b/drmmode.cpp
new file mode 100644
index 0000000..c2def1e
--- /dev/null
+++ b/drmmode.cpp
@@ -0,0 +1,163 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "drmmode.h"
+#include "drmresources.h"
+
+#include <stdint.h>
+#include <string>
+
+#include <xf86drmMode.h>
+
+namespace android {
+
+DrmMode::DrmMode(drmModeModeInfoPtr m)
+    : id_(0),
+      clock_(m->clock),
+      h_display_(m->hdisplay),
+      h_sync_start_(m->hsync_start),
+      h_sync_end_(m->hsync_end),
+      h_total_(m->htotal),
+      h_skew_(m->hskew),
+      v_display_(m->vdisplay),
+      v_sync_start_(m->vsync_start),
+      v_sync_end_(m->vsync_end),
+      v_total_(m->vtotal),
+      v_scan_(m->vscan),
+      v_refresh_(m->vrefresh),
+      flags_(m->flags),
+      type_(m->type),
+      name_(m->name) {
+}
+
+DrmMode::DrmMode()
+    : id_(0),
+      clock_(0),
+      h_display_(0),
+      h_sync_start_(0),
+      h_sync_end_(0),
+      h_total_(0),
+      h_skew_(0),
+      v_display_(0),
+      v_sync_start_(0),
+      v_sync_end_(0),
+      v_total_(0),
+      v_scan_(0),
+      v_refresh_(0),
+      flags_(0),
+      type_(0),
+      name_("") {
+}
+
+DrmMode::~DrmMode() {
+}
+
+bool DrmMode::operator==(const drmModeModeInfo &m) const {
+  return clock_ == m.clock && h_display_ == m.hdisplay &&
+         h_sync_start_ == m.hsync_start && h_sync_end_ == m.hsync_end &&
+         h_total_ == m.htotal && h_skew_ == m.hskew &&
+         v_display_ == m.vdisplay && v_sync_start_ == m.vsync_start &&
+         v_sync_end_ == m.vsync_end && v_total_ == m.vtotal &&
+         v_scan_ == m.vscan && v_refresh_ == m.vrefresh && flags_ == m.flags &&
+         type_ == m.type;
+}
+
+void DrmMode::ToModeModeInfo(drmModeModeInfo *m) const {
+  m->clock = clock_;
+  m->hdisplay = h_display_;
+  m->hsync_start = h_sync_start_;
+  m->hsync_end = h_sync_end_;
+  m->htotal = h_total_;
+  m->hskew = h_skew_;
+  m->vdisplay = v_display_;
+  m->vsync_start = v_sync_start_;
+  m->vsync_end = v_sync_end_;
+  m->vtotal = v_total_;
+  m->vscan = v_scan_;
+  m->vrefresh = v_refresh_;
+  m->flags = flags_;
+  m->type = type_;
+  strncpy(m->name, name_.c_str(), DRM_DISPLAY_MODE_LEN);
+}
+
+uint32_t DrmMode::id() const {
+  return id_;
+}
+
+void DrmMode::set_id(uint32_t id) {
+  id_ = id;
+}
+
+uint32_t DrmMode::clock() const {
+  return clock_;
+}
+
+uint32_t DrmMode::h_display() const {
+  return h_display_;
+}
+
+uint32_t DrmMode::h_sync_start() const {
+  return h_sync_start_;
+}
+
+uint32_t DrmMode::h_sync_end() const {
+  return h_sync_end_;
+}
+
+uint32_t DrmMode::h_total() const {
+  return h_total_;
+}
+
+uint32_t DrmMode::h_skew() const {
+  return h_skew_;
+}
+
+uint32_t DrmMode::v_display() const {
+  return v_display_;
+}
+
+uint32_t DrmMode::v_sync_start() const {
+  return v_sync_start_;
+}
+
+uint32_t DrmMode::v_sync_end() const {
+  return v_sync_end_;
+}
+
+uint32_t DrmMode::v_total() const {
+  return v_total_;
+}
+
+uint32_t DrmMode::v_scan() const {
+  return v_scan_;
+}
+
+uint32_t DrmMode::v_refresh() const {
+  return v_refresh_;
+}
+
+uint32_t DrmMode::flags() const {
+  return flags_;
+}
+
+uint32_t DrmMode::type() const {
+  return type_;
+}
+
+std::string DrmMode::name() const {
+  return name_;
+}
+}
diff --git a/drmmode.h b/drmmode.h
new file mode 100644
index 0000000..9e333bd
--- /dev/null
+++ b/drmmode.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_DRM_MODE_H_
+#define ANDROID_DRM_MODE_H_
+
+#include <stdint.h>
+#include <string>
+#include <xf86drmMode.h>
+
+namespace android {
+
+class DrmMode {
+ public:
+  DrmMode(drmModeModeInfoPtr m);
+  DrmMode();
+  ~DrmMode();
+
+  bool operator==(const drmModeModeInfo &m) const;
+  void ToModeModeInfo(drmModeModeInfo *m) const;
+
+  uint32_t id() const;
+  void set_id(uint32_t id);
+
+  uint32_t clock() const;
+
+  uint32_t h_display() const;
+  uint32_t h_sync_start() const;
+  uint32_t h_sync_end() const;
+  uint32_t h_total() const;
+  uint32_t h_skew() const;
+
+  uint32_t v_display() const;
+  uint32_t v_sync_start() const;
+  uint32_t v_sync_end() const;
+  uint32_t v_total() const;
+  uint32_t v_scan() const;
+  uint32_t v_refresh() const;
+
+  uint32_t flags() const;
+  uint32_t type() const;
+
+  std::string name() const;
+
+ private:
+  uint32_t id_;
+
+  uint32_t clock_;
+
+  uint32_t h_display_;
+  uint32_t h_sync_start_;
+  uint32_t h_sync_end_;
+  uint32_t h_total_;
+  uint32_t h_skew_;
+
+  uint32_t v_display_;
+  uint32_t v_sync_start_;
+  uint32_t v_sync_end_;
+  uint32_t v_total_;
+  uint32_t v_scan_;
+  uint32_t v_refresh_;
+
+  uint32_t flags_;
+  uint32_t type_;
+
+  std::string name_;
+};
+}
+
+#endif  // ANDROID_DRM_MODE_H_
diff --git a/drmplane.cpp b/drmplane.cpp
new file mode 100644
index 0000000..d6ac875
--- /dev/null
+++ b/drmplane.cpp
@@ -0,0 +1,177 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "hwc-drm-plane"
+
+#include "drmplane.h"
+#include "drmresources.h"
+
+#include <errno.h>
+#include <stdint.h>
+
+#include <cutils/log.h>
+#include <xf86drmMode.h>
+
+namespace android {
+
+DrmPlane::DrmPlane(DrmResources *drm, drmModePlanePtr p)
+    : drm_(drm), id_(p->plane_id), possible_crtc_mask_(p->possible_crtcs) {
+}
+
+DrmPlane::~DrmPlane() {
+}
+
+int DrmPlane::Init() {
+  DrmProperty p;
+
+  int ret = drm_->GetPlaneProperty(*this, "type", &p);
+  if (ret) {
+    ALOGE("Could not get plane type property");
+    return ret;
+  }
+
+  uint64_t type;
+  ret = p.value(&type);
+  if (ret) {
+    ALOGE("Failed to get plane type property value");
+    return ret;
+  }
+  switch (type) {
+    case DRM_PLANE_TYPE_OVERLAY:
+    case DRM_PLANE_TYPE_PRIMARY:
+    case DRM_PLANE_TYPE_CURSOR:
+      type_ = (uint32_t)type;
+      break;
+    default:
+      ALOGE("Invalid plane type %d", type);
+      return -EINVAL;
+  }
+
+  ret = drm_->GetPlaneProperty(*this, "CRTC_ID", &crtc_property_);
+  if (ret) {
+    ALOGE("Could not get CRTC_ID property");
+    return ret;
+  }
+
+  ret = drm_->GetPlaneProperty(*this, "FB_ID", &fb_property_);
+  if (ret) {
+    ALOGE("Could not get FB_ID property");
+    return ret;
+  }
+
+  ret = drm_->GetPlaneProperty(*this, "CRTC_X", &crtc_x_property_);
+  if (ret) {
+    ALOGE("Could not get CRTC_X property");
+    return ret;
+  }
+
+  ret = drm_->GetPlaneProperty(*this, "CRTC_Y", &crtc_y_property_);
+  if (ret) {
+    ALOGE("Could not get CRTC_Y property");
+    return ret;
+  }
+
+  ret = drm_->GetPlaneProperty(*this, "CRTC_W", &crtc_w_property_);
+  if (ret) {
+    ALOGE("Could not get CRTC_W property");
+    return ret;
+  }
+
+  ret = drm_->GetPlaneProperty(*this, "CRTC_H", &crtc_h_property_);
+  if (ret) {
+    ALOGE("Could not get CRTC_H property");
+    return ret;
+  }
+
+  ret = drm_->GetPlaneProperty(*this, "SRC_X", &src_x_property_);
+  if (ret) {
+    ALOGE("Could not get SRC_X property");
+    return ret;
+  }
+
+  ret = drm_->GetPlaneProperty(*this, "SRC_Y", &src_y_property_);
+  if (ret) {
+    ALOGE("Could not get SRC_Y property");
+    return ret;
+  }
+
+  ret = drm_->GetPlaneProperty(*this, "SRC_W", &src_w_property_);
+  if (ret) {
+    ALOGE("Could not get SRC_W property");
+    return ret;
+  }
+
+  ret = drm_->GetPlaneProperty(*this, "SRC_H", &src_h_property_);
+  if (ret) {
+    ALOGE("Could not get SRC_H property");
+    return ret;
+  }
+
+  return 0;
+}
+
+uint32_t DrmPlane::id() const {
+  return id_;
+}
+
+bool DrmPlane::GetCrtcSupported(const DrmCrtc &crtc) const {
+  return !!((1 << crtc.pipe()) & possible_crtc_mask_);
+}
+
+uint32_t DrmPlane::type() const {
+  return type_;
+}
+
+const DrmProperty &DrmPlane::crtc_property() const {
+  return crtc_property_;
+}
+
+const DrmProperty &DrmPlane::fb_property() const {
+  return fb_property_;
+}
+
+const DrmProperty &DrmPlane::crtc_x_property() const {
+  return crtc_x_property_;
+}
+
+const DrmProperty &DrmPlane::crtc_y_property() const {
+  return crtc_y_property_;
+}
+
+const DrmProperty &DrmPlane::crtc_w_property() const {
+  return crtc_w_property_;
+}
+
+const DrmProperty &DrmPlane::crtc_h_property() const {
+  return crtc_h_property_;
+}
+
+const DrmProperty &DrmPlane::src_x_property() const {
+  return src_x_property_;
+}
+
+const DrmProperty &DrmPlane::src_y_property() const {
+  return src_y_property_;
+}
+
+const DrmProperty &DrmPlane::src_w_property() const {
+  return src_w_property_;
+}
+
+const DrmProperty &DrmPlane::src_h_property() const {
+  return src_h_property_;
+}
+}
diff --git a/drmplane.h b/drmplane.h
new file mode 100644
index 0000000..96cd85c
--- /dev/null
+++ b/drmplane.h
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_DRM_PLANE_H_
+#define ANDROID_DRM_PLANE_H_
+
+#include "drmcrtc.h"
+#include "drmproperty.h"
+
+#include <stdint.h>
+#include <xf86drmMode.h>
+#include <vector>
+
+namespace android {
+
+class DrmResources;
+
+class DrmPlane {
+ public:
+  DrmPlane(DrmResources *drm, drmModePlanePtr p);
+  ~DrmPlane();
+
+  int Init();
+
+  uint32_t id() const;
+
+  bool GetCrtcSupported(const DrmCrtc &crtc) const;
+
+  uint32_t type() const;
+
+  const DrmProperty &crtc_property() const;
+  const DrmProperty &fb_property() const;
+  const DrmProperty &crtc_x_property() const;
+  const DrmProperty &crtc_y_property() const;
+  const DrmProperty &crtc_w_property() const;
+  const DrmProperty &crtc_h_property() const;
+  const DrmProperty &src_x_property() const;
+  const DrmProperty &src_y_property() const;
+  const DrmProperty &src_w_property() const;
+  const DrmProperty &src_h_property() const;
+
+ private:
+  DrmPlane(const DrmPlane &);
+
+  DrmResources *drm_;
+  uint32_t id_;
+
+  uint32_t possible_crtc_mask_;
+
+  uint32_t type_;
+
+  DrmProperty crtc_property_;
+  DrmProperty fb_property_;
+  DrmProperty crtc_x_property_;
+  DrmProperty crtc_y_property_;
+  DrmProperty crtc_w_property_;
+  DrmProperty crtc_h_property_;
+  DrmProperty src_x_property_;
+  DrmProperty src_y_property_;
+  DrmProperty src_w_property_;
+  DrmProperty src_h_property_;
+};
+}
+
+#endif  // ANDROID_DRM_PLANE_H_
diff --git a/drmproperty.cpp b/drmproperty.cpp
new file mode 100644
index 0000000..0acea17
--- /dev/null
+++ b/drmproperty.cpp
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "drmproperty.h"
+#include "drmresources.h"
+
+#include <errno.h>
+#include <stdint.h>
+#include <string>
+
+#include <xf86drmMode.h>
+
+namespace android {
+
+DrmProperty::DrmPropertyEnum::DrmPropertyEnum(drm_mode_property_enum *e)
+    : value_(e->value), name_(e->name) {
+}
+
+DrmProperty::DrmPropertyEnum::~DrmPropertyEnum() {
+}
+
+DrmProperty::DrmProperty(drmModePropertyPtr p, uint64_t value)
+    : id_(0), flags_(0), name_("") {
+  Init(p, value);
+}
+
+DrmProperty::DrmProperty() : id_(0), flags_(0), name_(""), value_(0) {
+}
+
+DrmProperty::~DrmProperty() {
+}
+
+void DrmProperty::Init(drmModePropertyPtr p, uint64_t value) {
+  id_ = p->prop_id;
+  flags_ = p->flags;
+  name_ = p->name;
+  value_ = value;
+
+  for (int i = 0; i < p->count_values; ++i)
+    values_.push_back(p->values[i]);
+
+  for (int i = 0; i < p->count_enums; ++i)
+    enums_.push_back(DrmPropertyEnum(&p->enums[i]));
+
+  for (int i = 0; i < p->count_blobs; ++i)
+    blob_ids_.push_back(p->blob_ids[i]);
+
+  if (flags_ & DRM_MODE_PROP_RANGE)
+    type_ = DRM_PROPERTY_TYPE_INT;
+  else if (flags_ & DRM_MODE_PROP_ENUM)
+    type_ = DRM_PROPERTY_TYPE_ENUM;
+}
+
+uint32_t DrmProperty::id() const {
+  return id_;
+}
+
+std::string DrmProperty::name() const {
+  return name_;
+}
+
+int DrmProperty::value(uint64_t *value) const {
+  if (values_.size() == 0)
+    return -ENOENT;
+
+  switch (type_) {
+    case DRM_PROPERTY_TYPE_INT:
+      *value = value_;
+      return 0;
+
+    case DRM_PROPERTY_TYPE_ENUM:
+      if (value_ >= enums_.size())
+        return -ENOENT;
+
+      *value = enums_[value_].value_;
+      return 0;
+
+    default:
+      return -EINVAL;
+  }
+}
+}
diff --git a/drmproperty.h b/drmproperty.h
new file mode 100644
index 0000000..eb5fcb5
--- /dev/null
+++ b/drmproperty.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_DRM_PROPERTY_H_
+#define ANDROID_DRM_PROPERTY_H_
+
+#include <stdint.h>
+#include <string>
+#include <xf86drmMode.h>
+#include <vector>
+
+namespace android {
+
+enum DrmPropertyType {
+  DRM_PROPERTY_TYPE_INT,
+  DRM_PROPERTY_TYPE_ENUM,
+};
+
+class DrmProperty {
+ public:
+  DrmProperty(drmModePropertyPtr p, uint64_t value);
+  DrmProperty();
+  ~DrmProperty();
+
+  void Init(drmModePropertyPtr p, uint64_t value);
+
+  uint32_t id() const;
+  std::string name() const;
+
+  int value(uint64_t *value) const;
+
+ private:
+  class DrmPropertyEnum {
+   public:
+    DrmPropertyEnum(drm_mode_property_enum *e);
+    ~DrmPropertyEnum();
+
+    uint64_t value_;
+    std::string name_;
+  };
+
+  DrmProperty(const DrmProperty &);
+
+  uint32_t id_;
+
+  DrmPropertyType type_;
+  uint32_t flags_;
+  std::string name_;
+  uint64_t value_;
+
+  std::vector<uint64_t> values_;
+  std::vector<DrmPropertyEnum> enums_;
+  std::vector<uint32_t> blob_ids_;
+};
+}
+
+#endif  // ANDROID_DRM_PROPERTY_H_
diff --git a/drmresources.cpp b/drmresources.cpp
new file mode 100644
index 0000000..3da0f04
--- /dev/null
+++ b/drmresources.cpp
@@ -0,0 +1,421 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "hwc-drm-resources"
+
+#include "drmconnector.h"
+#include "drmcrtc.h"
+#include "drmencoder.h"
+#include "drmplane.h"
+#include "drmresources.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdint.h>
+#include <xf86drm.h>
+#include <xf86drmMode.h>
+
+#include <cutils/log.h>
+#include <cutils/properties.h>
+
+namespace android {
+
+DrmResources::DrmResources() : fd_(-1), mode_id_(0) {
+}
+
+DrmResources::~DrmResources() {
+  for (std::vector<DrmConnector *>::const_iterator iter = connectors_.begin();
+       iter != connectors_.end(); ++iter)
+    delete *iter;
+  connectors_.clear();
+
+  for (std::vector<DrmEncoder *>::const_iterator iter = encoders_.begin();
+       iter != encoders_.end(); ++iter)
+    delete *iter;
+  encoders_.clear();
+
+  for (std::vector<DrmCrtc *>::const_iterator iter = crtcs_.begin();
+       iter != crtcs_.end(); ++iter)
+    delete *iter;
+  crtcs_.clear();
+
+  for (std::vector<DrmPlane *>::const_iterator iter = planes_.begin();
+       iter != planes_.end(); ++iter)
+    delete *iter;
+  planes_.clear();
+
+  if (fd_ >= 0)
+    close(fd_);
+}
+
+int DrmResources::Init() {
+  char path[PROPERTY_VALUE_MAX];
+  property_get("hwc.drm.device", path, "/dev/dri/card0");
+
+  /* TODO: Use drmOpenControl here instead */
+  fd_ = open(path, O_RDWR);
+  if (fd_ < 0) {
+    ALOGE("Failed to open dri- %s", strerror(-errno));
+    return -ENODEV;
+  }
+
+  int ret = drmSetClientCap(fd_, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1);
+  if (ret) {
+    ALOGE("Failed to set universal plane cap %d", ret);
+    return ret;
+  }
+
+  ret = drmSetClientCap(fd_, DRM_CLIENT_CAP_ATOMIC, 1);
+  if (ret) {
+    ALOGE("Failed to set atomic cap %d", ret);
+    return ret;
+  }
+
+  drmModeResPtr res = drmModeGetResources(fd_);
+  if (!res) {
+    ALOGE("Failed to get DrmResources resources");
+    return -ENODEV;
+  }
+
+  bool found_primary = false;
+  int display_num = 1;
+
+  for (int i = 0; !ret && i < res->count_crtcs; ++i) {
+    drmModeCrtcPtr c = drmModeGetCrtc(fd_, res->crtcs[i]);
+    if (!c) {
+      ALOGE("Failed to get crtc %d", res->crtcs[i]);
+      ret = -ENODEV;
+      break;
+    }
+
+    DrmCrtc *crtc = new DrmCrtc(c, i);
+
+    drmModeFreeCrtc(c);
+
+    if (!crtc) {
+      ALOGE("Failed to allocate crtc %d", res->crtcs[i]);
+      ret = -ENOMEM;
+      break;
+    }
+    crtcs_.push_back(crtc);
+  }
+
+  for (int i = 0; !ret && i < res->count_encoders; ++i) {
+    drmModeEncoderPtr e = drmModeGetEncoder(fd_, res->encoders[i]);
+    if (!e) {
+      ALOGE("Failed to get encoder %d", res->encoders[i]);
+      ret = -ENODEV;
+      break;
+    }
+
+    std::vector<DrmCrtc *> possible_crtcs;
+    DrmCrtc *current_crtc = NULL;
+    for (std::vector<DrmCrtc *>::const_iterator iter = crtcs_.begin();
+         iter != crtcs_.end(); ++iter) {
+      if ((1 << (*iter)->pipe()) & e->possible_crtcs)
+        possible_crtcs.push_back(*iter);
+
+      if ((*iter)->id() == e->crtc_id)
+        current_crtc = (*iter);
+    }
+
+    DrmEncoder *enc = new DrmEncoder(e, current_crtc, possible_crtcs);
+
+    drmModeFreeEncoder(e);
+
+    if (!enc) {
+      ALOGE("Failed to allocate enc %d", res->encoders[i]);
+      ret = -ENOMEM;
+      break;
+    }
+    encoders_.push_back(enc);
+  }
+
+  for (int i = 0; !ret && i < res->count_connectors; ++i) {
+    drmModeConnectorPtr c = drmModeGetConnector(fd_, res->connectors[i]);
+    if (!c) {
+      ALOGE("Failed to get connector %d", res->connectors[i]);
+      ret = -ENODEV;
+      break;
+    }
+
+    std::vector<DrmEncoder *> possible_encoders;
+    DrmEncoder *current_encoder = NULL;
+    for (int j = 0; j < c->count_encoders; ++j) {
+      for (std::vector<DrmEncoder *>::const_iterator iter = encoders_.begin();
+           iter != encoders_.end(); ++iter) {
+        if ((*iter)->id() == c->encoders[j])
+          possible_encoders.push_back((*iter));
+        if ((*iter)->id() == c->encoder_id)
+          current_encoder = *iter;
+      }
+    }
+
+    DrmConnector *conn =
+        new DrmConnector(this, c, current_encoder, possible_encoders);
+
+    drmModeFreeConnector(c);
+
+    if (!conn) {
+      ALOGE("Failed to allocate conn %d", res->connectors[i]);
+      ret = -ENOMEM;
+      break;
+    }
+
+    ret = conn->Init();
+    if (ret) {
+      ALOGE("Init connector %d failed", res->connectors[i]);
+      delete conn;
+      break;
+    }
+    connectors_.push_back(conn);
+
+    if (conn->built_in() && !found_primary) {
+      conn->set_display(0);
+      found_primary = true;
+    } else {
+      conn->set_display(display_num);
+      ++display_num;
+    }
+  }
+  if (res)
+    drmModeFreeResources(res);
+
+  // Catch-all for the above loops
+  if (ret)
+    return ret;
+
+  drmModePlaneResPtr plane_res = drmModeGetPlaneResources(fd_);
+  if (!plane_res) {
+    ALOGE("Failed to get plane resources");
+    return -ENOENT;
+  }
+
+  for (uint32_t i = 0; i < plane_res->count_planes; ++i) {
+    drmModePlanePtr p = drmModeGetPlane(fd_, plane_res->planes[i]);
+    if (!p) {
+      ALOGE("Failed to get plane %d", plane_res->planes[i]);
+      ret = -ENODEV;
+      break;
+    }
+
+    DrmPlane *plane = new DrmPlane(this, p);
+
+    drmModeFreePlane(p);
+
+    if (!plane) {
+      ALOGE("Allocate plane %d failed", plane_res->planes[i]);
+      ret = -ENOMEM;
+      break;
+    }
+
+    ret = plane->Init();
+    if (ret) {
+      ALOGE("Init plane %d failed", plane_res->planes[i]);
+      delete plane;
+      break;
+    }
+
+    planes_.push_back(plane);
+  }
+  drmModeFreePlaneResources(plane_res);
+  if (ret)
+    return ret;
+
+  return 0;
+}
+
+int DrmResources::fd() const {
+  return fd_;
+}
+
+DrmResources::ConnectorIter DrmResources::begin_connectors() const {
+  return connectors_.begin();
+}
+
+DrmResources::ConnectorIter DrmResources::end_connectors() const {
+  return connectors_.end();
+}
+
+DrmConnector *DrmResources::GetConnectorForDisplay(int display) const {
+  for (ConnectorIter iter = connectors_.begin(); iter != connectors_.end();
+       ++iter) {
+    if ((*iter)->display() == display)
+      return *iter;
+  }
+  return NULL;
+}
+
+DrmCrtc *DrmResources::GetCrtcForDisplay(int display) const {
+  for (std::vector<DrmCrtc *>::const_iterator iter = crtcs_.begin();
+       iter != crtcs_.end(); ++iter) {
+    if ((*iter)->display() == display)
+      return *iter;
+  }
+  return NULL;
+}
+
+DrmResources::PlaneIter DrmResources::begin_planes() const {
+  return planes_.begin();
+}
+
+DrmResources::PlaneIter DrmResources::end_planes() const {
+  return planes_.end();
+}
+
+DrmPlane *DrmResources::GetPlane(uint32_t id) const {
+  for (std::vector<DrmPlane *>::const_iterator iter = planes_.begin();
+       iter != planes_.end(); ++iter) {
+    if ((*iter)->id() == id)
+      return *iter;
+  }
+  return NULL;
+}
+
+uint32_t DrmResources::next_mode_id() {
+  return ++mode_id_;
+}
+
+int DrmResources::TryEncoderForDisplay(int display, DrmEncoder *enc) {
+  /* First try to use the currently-bound crtc */
+  DrmCrtc *crtc = enc->crtc();
+  if (crtc && crtc->can_bind(display)) {
+    crtc->set_display(display);
+    return 0;
+  }
+
+  /* Try to find a possible crtc which will work */
+  for (DrmEncoder::CrtcIter iter = enc->begin_possible_crtcs();
+       iter != enc->end_possible_crtcs(); ++iter) {
+    /* We've already tried this earlier */
+    if (*iter == enc->crtc())
+      continue;
+
+    if ((*iter)->can_bind(display)) {
+      enc->set_crtc(*iter);
+      (*iter)->set_display(display);
+      return 0;
+    }
+  }
+
+  /* We can't use the encoder, but nothing went wrong, try another one */
+  return -EAGAIN;
+}
+
+int DrmResources::SetDisplayActiveMode(int display, uint32_t mode_id) {
+  DrmEncoder *enc;
+  int ret;
+
+  DrmConnector *con = GetConnectorForDisplay(display);
+  if (!con) {
+    ALOGE("Could not locate connector for display %d", display);
+    return -ENODEV;
+  }
+
+  /* Try to use current setup first */
+  enc = con->encoder();
+  if (enc) {
+    ret = TryEncoderForDisplay(display, enc);
+    if (!ret) {
+      con->set_encoder(enc);
+      return con->set_active_mode(mode_id);
+    } else if (ret != -EAGAIN) {
+      ALOGE("Could not set mode %d/%d", display, ret);
+      return ret;
+    }
+  }
+
+  for (DrmConnector::EncoderIter iter = con->begin_possible_encoders();
+       iter != con->end_possible_encoders(); ++iter) {
+    ret = TryEncoderForDisplay(display, *iter);
+    if (!ret) {
+      con->set_encoder(*iter);
+      return con->set_active_mode(mode_id);
+    } else if (ret != -EAGAIN) {
+      ALOGE("Could not set mode %d/%d", display, ret);
+      return ret;
+    }
+  }
+
+  ALOGE("Could not find a suitable encoder/crtc for display %d", display);
+  return -EINVAL;
+}
+
+int DrmResources::SetDpmsMode(int display, uint64_t mode) {
+  if (mode != DRM_MODE_DPMS_ON && mode != DRM_MODE_DPMS_OFF) {
+    ALOGE("Invalid dpms mode %d", mode);
+    return -EINVAL;
+  }
+
+  DrmCrtc *crtc = GetCrtcForDisplay(display);
+  if (!crtc) {
+    ALOGE("Failed to get DrmCrtc for display %d", display);
+    return -ENODEV;
+  }
+  crtc->set_requires_modeset(true);
+
+  DrmConnector *c = GetConnectorForDisplay(display);
+  if (!c) {
+    ALOGE("Failed to get DrmConnector for display %d", display);
+    return -ENODEV;
+  }
+
+  const DrmProperty &prop = c->dpms_property();
+  int ret = drmModeConnectorSetProperty(fd_, c->id(), prop.id(), mode);
+  if (ret) {
+    ALOGE("Failed to set DPMS property for connector %d", c->id());
+    return ret;
+  }
+
+  return 0;
+}
+
+int DrmResources::GetProperty(uint32_t obj_id, uint32_t obj_type,
+                              const char *prop_name, DrmProperty *property) {
+  drmModeObjectPropertiesPtr props;
+
+  props = drmModeObjectGetProperties(fd_, obj_id, obj_type);
+  if (!props) {
+    ALOGE("Failed to get properties for %d/%x", obj_id, obj_type);
+    return -ENODEV;
+  }
+
+  bool found = false;
+  for (int i = 0; !found && (size_t)i < props->count_props; ++i) {
+    drmModePropertyPtr p = drmModeGetProperty(fd_, props->props[i]);
+    if (!strcmp(p->name, prop_name)) {
+      property->Init(p, props->prop_values[i]);
+      found = true;
+    }
+    drmModeFreeProperty(p);
+  }
+
+  drmModeFreeObjectProperties(props);
+  return found ? 0 : -ENOENT;
+}
+
+int DrmResources::GetPlaneProperty(const DrmPlane &plane, const char *prop_name,
+                                   DrmProperty *property) {
+  return GetProperty(plane.id(), DRM_MODE_OBJECT_PLANE, prop_name, property);
+}
+
+int DrmResources::GetConnectorProperty(const DrmConnector &connector,
+                                       const char *prop_name,
+                                       DrmProperty *property) {
+  return GetProperty(connector.id(), DRM_MODE_OBJECT_CONNECTOR, prop_name,
+                     property);
+}
+}
diff --git a/drmresources.h b/drmresources.h
new file mode 100644
index 0000000..f329bd9
--- /dev/null
+++ b/drmresources.h
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_DRM_H_
+#define ANDROID_DRM_H_
+
+#include "drmconnector.h"
+#include "drmcrtc.h"
+#include "drmencoder.h"
+#include "drmplane.h"
+
+#include <stdint.h>
+
+namespace android {
+
+class DrmResources {
+ public:
+  typedef std::vector<DrmConnector *>::const_iterator ConnectorIter;
+  typedef std::vector<DrmPlane *>::const_iterator PlaneIter;
+
+  DrmResources();
+  ~DrmResources();
+
+  int Init();
+
+  int fd() const;
+
+  ConnectorIter begin_connectors() const;
+  ConnectorIter end_connectors() const;
+  PlaneIter begin_planes() const;
+  PlaneIter end_planes() const;
+
+  DrmConnector *GetConnectorForDisplay(int display) const;
+  DrmCrtc *GetCrtcForDisplay(int display) const;
+  DrmPlane *GetPlane(uint32_t id) const;
+
+  int GetPlaneProperty(const DrmPlane &plane, const char *prop_name,
+                       DrmProperty *property);
+  int GetConnectorProperty(const DrmConnector &connector, const char *prop_name,
+                           DrmProperty *property);
+
+  uint32_t next_mode_id();
+  int SetDisplayActiveMode(int display, uint32_t mode_id);
+  int SetDpmsMode(int display, uint64_t mode);
+
+ private:
+  int TryEncoderForDisplay(int display, DrmEncoder *enc);
+  int GetProperty(uint32_t obj_id, uint32_t obj_type, const char *prop_name,
+                  DrmProperty *property);
+
+  int fd_;
+  uint32_t mode_id_;
+
+  std::vector<DrmConnector *> connectors_;
+  std::vector<DrmEncoder *> encoders_;
+  std::vector<DrmCrtc *> crtcs_;
+  std::vector<DrmPlane *> planes_;
+};
+}
+
+#endif  // ANDROID_DRM_H_
diff --git a/hwcomposer.cpp b/hwcomposer.cpp
index f2e04b4..628d343 100644
--- a/hwcomposer.cpp
+++ b/hwcomposer.cpp
@@ -17,6 +17,7 @@
 #define LOG_TAG "hwcomposer-drm"
 
 #include "drm_hwcomposer.h"
+#include "drmresources.h"
 
 #include <errno.h>
 #include <fcntl.h>
@@ -36,13 +37,10 @@
 
 #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,
-};
+namespace android {
 
 struct hwc_worker {
   pthread_t thread;
@@ -55,15 +53,7 @@
   struct hwc_context_t *ctx;
   int display;
 
-  uint32_t connector_id;
-
-  drmModeModeInfoPtr configs;
-  uint32_t num_configs;
-
-  drmModeModeInfo active_mode;
-  uint32_t active_crtc;
-  int active_pipe;
-  bool initial_modeset_required;
+  std::vector<uint32_t> config_ids;
 
   struct hwc_worker set_worker;
 
@@ -82,8 +72,6 @@
 struct hwc_context_t {
   hwc_composer_device_1_t device;
 
-  int fd;
-
   hwc_procs_t const *procs;
   struct hwc_import_context *import_ctx;
 
@@ -91,6 +79,8 @@
   int num_displays;
 
   struct hwc_worker event_worker;
+
+  DrmResources drm;
 };
 
 static int hwc_get_drm_display(struct hwc_context_t *ctx, int display,
@@ -160,22 +150,23 @@
 }
 
 static int hwc_queue_vblank_event(struct hwc_drm_display *hd) {
-  if (hd->active_pipe == -1) {
-    ALOGE("Active pipe is -1 disp=%d", hd->display);
-    return -EINVAL;
+  DrmCrtc *crtc = hd->ctx->drm.GetCrtcForDisplay(hd->display);
+  if (!crtc) {
+    ALOGE("Failed to get crtc for display");
+    return -ENODEV;
   }
 
   drmVBlank vblank;
   memset(&vblank, 0, sizeof(vblank));
 
-  uint32_t high_crtc = (hd->active_pipe << DRM_VBLANK_HIGH_CRTC_SHIFT);
+  uint32_t high_crtc = (crtc->pipe() << DRM_VBLANK_HIGH_CRTC_SHIFT);
   vblank.request.type = (drmVBlankSeqType)(
       DRM_VBLANK_ABSOLUTE | DRM_VBLANK_NEXTONMISS | DRM_VBLANK_EVENT |
       (high_crtc & DRM_VBLANK_HIGH_CRTC_MASK));
   vblank.request.signal = (unsigned long)hd;
   vblank.request.sequence = hd->vsync_sequence + 1;
 
-  int ret = drmWaitVBlank(hd->ctx->fd, &vblank);
+  int ret = drmWaitVBlank(hd->ctx->drm.fd(), &vblank);
   if (ret) {
     ALOGE("Failed to wait for vblank %d", ret);
     return ret;
@@ -239,7 +230,7 @@
   do {
     fd_set fds;
     FD_ZERO(&fds);
-    FD_SET(ctx->fd, &fds);
+    FD_SET(ctx->drm.fd(), &fds);
 
     drmEventContext event_context;
     event_context.version = DRM_EVENT_CONTEXT_VERSION;
@@ -248,7 +239,7 @@
 
     int ret;
     do {
-      ret = select(ctx->fd + 1, &fds, NULL, NULL, NULL);
+      ret = select(ctx->drm.fd() + 1, &fds, NULL, NULL, NULL);
     } while (ret == -1 && errno == EINTR);
 
     if (ret != 1) {
@@ -256,7 +247,7 @@
       continue;
     }
 
-    drmHandleEvent(ctx->fd, &event_context);
+    drmHandleEvent(ctx->drm.fd(), &event_context);
   } while (true);
 
   return NULL;
@@ -273,56 +264,37 @@
          !strcmp(a->name, b->name);
 }
 
-static int hwc_modeset_required(struct hwc_drm_display *hd,
-                                bool *modeset_required) {
-  if (hd->initial_modeset_required) {
-    *modeset_required = true;
-    hd->initial_modeset_required = false;
-    return 0;
-  }
-
-  drmModeCrtcPtr crtc;
-  crtc = drmModeGetCrtc(hd->ctx->fd, hd->active_crtc);
+static int hwc_flip(struct hwc_drm_display *hd, struct hwc_drm_bo *buf) {
+  DrmCrtc *crtc = hd->ctx->drm.GetCrtcForDisplay(hd->display);
   if (!crtc) {
     ALOGE("Failed to get crtc for display %d", hd->display);
     return -ENODEV;
   }
 
-  drmModeModeInfoPtr m;
-  m = &hd->active_mode;
-
-  /* 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))
-    *modeset_required = true;
-  else
-    *modeset_required = false;
-
-  drmModeFreeCrtc(crtc);
-
-  return 0;
-}
-
-static int hwc_flip(struct hwc_drm_display *hd, struct hwc_drm_bo *buf) {
-  bool modeset_required;
-  int ret = hwc_modeset_required(hd, &modeset_required);
-  if (ret) {
-    ALOGE("Failed to determine if modeset is required %d", ret);
-    return ret;
+  DrmConnector *connector = hd->ctx->drm.GetConnectorForDisplay(hd->display);
+  if (!connector) {
+    ALOGE("Failed to get connector for display %d", hd->display);
+    return -ENODEV;
   }
-  if (modeset_required) {
-    ret = drmModeSetCrtc(hd->ctx->fd, hd->active_crtc, buf->fb_id, 0, 0,
-                         &hd->connector_id, 1, &hd->active_mode);
+
+  int ret;
+  if (crtc->requires_modeset()) {
+    drmModeModeInfo drm_mode;
+    connector->active_mode().ToModeModeInfo(&drm_mode);
+    uint32_t connector_id = connector->id();
+    ret = drmModeSetCrtc(hd->ctx->drm.fd(), crtc->id(), buf->fb_id, 0, 0,
+                         &connector_id, 1, &drm_mode);
     if (ret) {
-      ALOGE("Modeset failed for crtc %d", hd->active_crtc);
+      ALOGE("Modeset failed for crtc %d", crtc->id());
       return ret;
     }
     return 0;
   }
 
-  ret = drmModePageFlip(hd->ctx->fd, hd->active_crtc, buf->fb_id,
+  ret = drmModePageFlip(hd->ctx->drm.fd(), crtc->id(), buf->fb_id,
                         DRM_MODE_PAGE_FLIP_EVENT, hd);
   if (ret) {
-    ALOGE("Failed to flip buffer for crtc %d", hd->active_crtc);
+    ALOGE("Failed to flip buffer for crtc %d", crtc->id());
     return ret;
   }
 
@@ -354,7 +326,8 @@
     return ret;
   }
 
-  if (hwc_import_bo_release(hd->ctx->fd, hd->ctx->import_ctx, &hd->front)) {
+  if (hwc_import_bo_release(hd->ctx->drm.fd(), hd->ctx->import_ctx,
+                            &hd->front)) {
     struct drm_gem_close args;
     memset(&args, 0, sizeof(args));
     for (int i = 0; i < ARRAY_SIZE(hd->front.gem_handles); ++i) {
@@ -381,7 +354,7 @@
 
       if (!found) {
         args.handle = hd->front.gem_handles[i];
-        drmIoctl(hd->ctx->fd, DRM_IOCTL_GEM_CLOSE, &args);
+        drmIoctl(hd->ctx->drm.fd(), DRM_IOCTL_GEM_CLOSE, &args);
       }
       if (pthread_mutex_unlock(&hd->set_worker.lock))
         ALOGE("Failed to unlock set lock in wait_and_set() %d", ret);
@@ -474,7 +447,8 @@
     return ret;
   }
 
-  if (!hd->active_crtc) {
+  DrmCrtc *crtc = hd->ctx->drm.GetCrtcForDisplay(display);
+  if (!crtc) {
     ALOGE("There is no active crtc for display %d", display);
     hwc_close_fences(display_contents);
     return -ENOENT;
@@ -510,7 +484,8 @@
 
   struct hwc_drm_bo buf;
   memset(&buf, 0, sizeof(buf));
-  ret = hwc_import_bo_create(ctx->fd, ctx->import_ctx, layer->handle, &buf);
+  ret =
+      hwc_import_bo_create(ctx->drm.fd(), ctx->import_ctx, layer->handle, &buf);
   if (ret) {
     ALOGE("Failed to import handle to drm bo %d", ret);
     hwc_close_fences(display_contents);
@@ -566,8 +541,9 @@
   if (event != HWC_EVENT_VSYNC || (enabled != 0 && enabled != 1))
     return -EINVAL;
 
-  if (hd->active_pipe == -1) {
-    ALOGD("Can't service events for display %d, no pipe", display);
+  DrmCrtc *crtc = ctx->drm.GetCrtcForDisplay(display);
+  if (!crtc) {
+    ALOGD("Can't service events for display %d, no crtc", display);
     return -EINVAL;
   }
 
@@ -596,60 +572,20 @@
                               int mode) {
   struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
 
-  struct hwc_drm_display *hd = NULL;
-  int ret = hwc_get_drm_display(ctx, display, &hd);
-  if (ret)
-    return ret;
-
-  drmModeConnectorPtr c = drmModeGetConnector(ctx->fd, hd->connector_id);
-  if (!c) {
-    ALOGE("Failed to get connector %d", display);
-    return -ENODEV;
-  }
-
-  uint32_t dpms_prop = 0;
-  for (int 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);
-    drmModeFreeConnector(c);
-    return -ENOENT;
-  }
-
-  uint64_t dpms_value = 0;
+  uint64_t dpmsValue = 0;
   switch (mode) {
     case HWC_POWER_MODE_OFF:
-      dpms_value = DRM_MODE_DPMS_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:
-      dpms_value = DRM_MODE_DPMS_ON;
+      dpmsValue = 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);
-    drmModeFreeConnector(c);
-    return ret;
-  }
-
-  drmModeFreeConnector(c);
-  return 0;
+  return ctx->drm.SetDpmsMode(display, dpmsValue);
 }
 
 static int hwc_query(struct hwc_composer_device_1 * /* dev */, int what,
@@ -678,8 +614,8 @@
 
 static int hwc_get_display_configs(struct hwc_composer_device_1 *dev,
                                    int display, uint32_t *configs,
-                                   size_t *numConfigs) {
-  if (!*numConfigs)
+                                   size_t *num_configs) {
+  if (!*num_configs)
     return 0;
 
   struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
@@ -688,67 +624,30 @@
   if (ret)
     return ret;
 
-  drmModeConnectorPtr c = drmModeGetConnector(ctx->fd, hd->connector_id);
-  if (!c) {
-    ALOGE("Failed to get connector %d", display);
+  hd->config_ids.clear();
+
+  DrmConnector *connector = ctx->drm.GetConnectorForDisplay(display);
+  if (!connector) {
+    ALOGE("Failed to get connector for display %d", display);
     return -ENODEV;
   }
 
-  if (hd->configs) {
-    free(hd->configs);
-    hd->configs = NULL;
-  }
-
-  if (c->connection == DRM_MODE_DISCONNECTED) {
-    drmModeFreeConnector(c);
-    return -ENODEV;
-  }
-
-  hd->configs =
-      (drmModeModeInfoPtr)calloc(c->count_modes, sizeof(*hd->configs));
-  if (!hd->configs) {
-    ALOGE("Failed to allocate config list for display %d", display);
-    hd->num_configs = 0;
-    drmModeFreeConnector(c);
-    return -ENOMEM;
-  }
-
-  for (int 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);
-
-  drmModeFreeConnector(c);
-  return 0;
-}
-
-static int hwc_check_config_valid(struct hwc_context_t *ctx,
-                                  drmModeConnectorPtr connector, int display,
-                                  int config_idx) {
-  struct hwc_drm_display *hd = NULL;
-  int ret = hwc_get_drm_display(ctx, display, &hd);
-  if (ret)
+  ret = connector->UpdateModes();
+  if (ret) {
+    ALOGE("Failed to update display modes %d", ret);
     return ret;
-
-  /* Make sure the requested config is still valid for the display */
-  drmModeModeInfoPtr m = NULL;
-  for (int 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;
+  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_get_display_attributes(struct hwc_composer_device_1 *dev,
@@ -756,53 +655,48 @@
                                       const uint32_t *attributes,
                                       int32_t *values) {
   struct hwc_context_t *ctx = (struct hwc_context_t *)&dev->common;
-  struct hwc_drm_display *hd = NULL;
-  int 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;
-  }
-
-  drmModeConnectorPtr c = drmModeGetConnector(ctx->fd, hd->connector_id);
+  DrmConnector *c = ctx->drm.GetConnectorForDisplay(display);
   if (!c) {
-    ALOGE("Failed to get connector %d", display);
+    ALOGE("Failed to get DrmConnector for display %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);
-    drmModeFreeConnector(c);
-    return ret;
+  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;
   }
 
-  drmModeModeInfoPtr m = &hd->configs[config];
+  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 / m->vrefresh;
+        values[i] = 1000 * 1000 * 1000 / mode.v_refresh();
         break;
       case HWC_DISPLAY_WIDTH:
-        values[i] = m->hdisplay;
+        values[i] = mode.h_display();
         break;
       case HWC_DISPLAY_HEIGHT:
-        values[i] = m->vdisplay;
+        values[i] = mode.v_display();
         break;
       case HWC_DISPLAY_DPI_X:
         /* Dots per 1000 inches */
-        values[i] = c->mmWidth ? (m->hdisplay * UM_PER_INCH) / c->mmWidth : 0;
+        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] = c->mmHeight ? (m->vdisplay * UM_PER_INCH) / c->mmHeight : 0;
+        values[i] =
+            mm_height ? (mode.v_display() * UM_PER_INCH) / mm_height : 0;
         break;
     }
   }
-
-  drmModeFreeConnector(c);
   return 0;
 }
 
@@ -814,62 +708,18 @@
   if (ret)
     return ret;
 
-  /* Find the current mode in the config list */
-  int index = -1;
-  for (int i = 0; i < (int)hd->num_configs; ++i) {
-    if (hwc_mode_is_equal(&hd->configs[i], &hd->active_mode)) {
-      index = i;
-      break;
-    }
-  }
-  return index;
-}
-
-static bool hwc_crtc_is_bound(struct hwc_context_t *ctx, uint32_t crtc_id) {
-  for (int i = 0; i < MAX_NUM_DISPLAYS; ++i) {
-    if (ctx->displays[i].active_crtc == crtc_id)
-      return true;
-  }
-  return false;
-}
-
-static int hwc_try_encoder(struct hwc_context_t *ctx, drmModeResPtr r,
-                           uint32_t encoder_id, uint32_t *crtc_id) {
-  drmModeEncoderPtr e = drmModeGetEncoder(ctx->fd, encoder_id);
-  if (!e) {
-    ALOGE("Failed to get encoder for connector %d", encoder_id);
+  DrmConnector *c = ctx->drm.GetConnectorForDisplay(display);
+  if (!c) {
+    ALOGE("Failed to get DrmConnector for display %d", display);
     return -ENODEV;
   }
 
-  /* First try to use the currently-bound crtc */
-  int ret = 0;
-  if (e->crtc_id) {
-    if (!hwc_crtc_is_bound(ctx, e->crtc_id)) {
-      *crtc_id = e->crtc_id;
-      drmModeFreeEncoder(e);
-      return 0;
-    }
+  DrmMode mode = c->active_mode();
+  for (size_t i = 0; i < hd->config_ids.size(); ++i) {
+    if (hd->config_ids[i] == mode.id())
+      return i;
   }
-
-  /* Try to find a possible crtc which will work */
-  for (int 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];
-      drmModeFreeEncoder(e);
-      return 0;
-    }
-  }
-
-  /* We can't use the encoder, but nothing went wrong, try another one */
-  drmModeFreeEncoder(e);
-  return -EAGAIN;
+  return -1;
 }
 
 static int hwc_set_active_config(struct hwc_composer_device_1 *dev, int display,
@@ -880,90 +730,19 @@
   if (ret)
     return ret;
 
-  drmModeConnectorPtr c = drmModeGetConnector(ctx->fd, hd->connector_id);
-  if (!c) {
-    ALOGE("Failed to get connector %d", display);
-    return -ENODEV;
+  if (index >= (int)hd->config_ids.size()) {
+    ALOGE("Invalid config index %d passed in", index);
+    return -EINVAL;
   }
 
-  if (c->connection == DRM_MODE_DISCONNECTED) {
-    ALOGE("Tried to configure a disconnected display %d", display);
-    drmModeFreeConnector(c);
-    return -ENODEV;
+  ret =
+      ctx->drm.SetDisplayActiveMode(display, hd->config_ids[index]);
+  if (ret) {
+    ALOGE("Failed to set config for display %d", display);
+    return ret;
   }
 
-  if (index >= c->count_modes) {
-    ALOGE("Index is out-of-bounds %d/%d", index, c->count_modes);
-    drmModeFreeConnector(c);
-    return -ENOENT;
-  }
-
-  drmModeResPtr r = drmModeGetResources(ctx->fd);
-  if (!r) {
-    ALOGE("Failed to get drm resources");
-    drmModeFreeResources(r);
-    drmModeFreeConnector(c);
-    return -ENODEV;
-  }
-
-  /* We no longer have an active_crtc */
-  hd->active_crtc = 0;
-  hd->active_pipe = -1;
-
-  /* First, try to use the currently-connected encoder */
-  uint32_t crtc_id = 0;
-  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);
-      drmModeFreeResources(r);
-      drmModeFreeConnector(c);
-      return ret;
-    }
-  }
-
-  /* We couldn't find a crtc with the attached encoder, try the others */
-  if (!crtc_id) {
-    for (int 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);
-        drmModeFreeResources(r);
-        drmModeFreeConnector(c);
-        return ret;
-      }
-    }
-    if (!crtc_id) {
-      ALOGE("Couldn't find valid crtc to modeset");
-      drmModeFreeConnector(c);
-      drmModeFreeResources(r);
-      return -EINVAL;
-    }
-  }
-  drmModeFreeConnector(c);
-
-  hd->active_crtc = crtc_id;
-  memcpy(&hd->active_mode, &hd->configs[index], sizeof(hd->active_mode));
-
-  /* Find the pipe corresponding to the crtc_id */
-  for (int i = 0; i < r->count_crtcs; ++i) {
-    /* We've already tried this earlier */
-    if (r->crtcs[i] == crtc_id) {
-      hd->active_pipe = i;
-      break;
-    }
-  }
-  drmModeFreeResources(r);
-  /* This should never happen... hehehe */
-  if (hd->active_pipe == -1) {
-    ALOGE("Active crtc was not found in resources!!");
-    return -ENODEV;
-  }
-
-  /* TODO: Once we have atomic, set the crtc timing info here */
-  return 0;
+  return ret;
 }
 
 static int hwc_destroy_worker(struct hwc_worker *worker) {
@@ -1004,8 +783,6 @@
   if (hwc_destroy_worker(&ctx->event_worker))
     ALOGE("Destroy event worker failed");
 
-  drmClose(ctx->fd);
-
   int ret = hwc_import_destroy(ctx->import_ctx);
   if (ret)
     ALOGE("Could not destroy import %d", ret);
@@ -1064,8 +841,7 @@
   return ret;
 }
 
-static int hwc_initialize_display(struct hwc_context_t *ctx, int display,
-                                  uint32_t connector_id) {
+static int hwc_initialize_display(struct hwc_context_t *ctx, int display) {
   struct hwc_drm_display *hd = NULL;
   int ret = hwc_get_drm_display(ctx, display, &hd);
   if (ret)
@@ -1073,9 +849,6 @@
 
   hd->ctx = ctx;
   hd->display = display;
-  hd->active_pipe = -1;
-  hd->initial_modeset_required = true;
-  hd->connector_id = connector_id;
   hd->enable_vsync_events = false;
   hd->vsync_sequence = 0;
 
@@ -1139,75 +912,15 @@
 }
 
 static int hwc_enumerate_displays(struct hwc_context_t *ctx) {
-  drmModeResPtr res = drmModeGetResources(ctx->fd);
-  if (!res) {
-    ALOGE("Failed to get drm resources");
-    return -ENODEV;
-  }
-  int num_connectors = res->count_connectors;
-
-  drmModeConnectorPtr *conn_list =
-      (drmModeConnector **)calloc(num_connectors, sizeof(*conn_list));
-  if (!conn_list) {
-    ALOGE("Failed to allocate connector list");
-    drmModeFreeResources(res);
-    return -ENOMEM;
-  }
-
-  for (int i = 0; i < num_connectors; ++i) {
-    conn_list[i] = drmModeGetConnector(ctx->fd, res->connectors[i]);
-    if (!conn_list[i]) {
-      ALOGE("Failed to get connector %d", res->connectors[i]);
-      drmModeFreeResources(res);
-      return -ENODEV;
+  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;
     }
   }
-  drmModeFreeResources(res);
-
-  ctx->num_displays = 0;
-
-  /* Find a connected, panel type connector for display 0 */
-  for (int i = 0; i < num_connectors; ++i) {
-    drmModeConnectorPtr c = conn_list[i];
-
-    int j;
-    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;
-  }
-
-  struct hwc_drm_display *panel_hd;
-  int ret = hwc_get_drm_display(ctx, 0, &panel_hd);
-  if (ret) {
-    hwc_free_conn_list(conn_list, num_connectors);
-    return ret;
-  }
-
-  /* Fill in the other displays */
-  for (int i = 0; i < num_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;
-  }
-  hwc_free_conn_list(conn_list, num_connectors);
-
-  ret = hwc_initialize_worker(&ctx->event_worker, hwc_event_worker, ctx);
-  if (ret) {
-    ALOGE("Failed to create event worker %d\n", ret);
-    return ret;
-  }
 
   return 0;
 }
@@ -1225,27 +938,30 @@
     return -ENOMEM;
   }
 
-  int ret = hwc_import_init(&ctx->import_ctx);
+  int ret = ctx->drm.Init();
+  if (ret) {
+    ALOGE("Can't initialize Drm object %d", ret);
+    delete ctx;
+    return ret;
+  }
+
+  ret = hwc_import_init(&ctx->import_ctx);
   if (ret) {
     ALOGE("Failed to initialize import context");
     delete ctx;
     return ret;
   }
 
-  char path[PROPERTY_VALUE_MAX];
-  property_get("hwc.drm.device", path, HWCOMPOSER_DRM_DEVICE);
-  /* TODO: Use drmOpenControl here instead */
-  ctx->fd = open(path, O_RDWR);
-  if (ctx->fd < 0) {
-    ALOGE("Failed to open dri- %s", strerror(-errno));
-    delete ctx;
-    return -ENOENT;
-  }
-
   ret = hwc_enumerate_displays(ctx);
   if (ret) {
     ALOGE("Failed to enumerate displays: %s", strerror(ret));
-    close(ctx->fd);
+    delete ctx;
+    return ret;
+  }
+
+  ret = hwc_initialize_worker(&ctx->event_worker, hwc_event_worker, ctx);
+  if (ret) {
+    ALOGE("Failed to create event worker %d\n", ret);
     delete ctx;
     return ret;
   }
@@ -1271,8 +987,11 @@
 
   return 0;
 }
+}
 
-static struct hw_module_methods_t hwc_module_methods = {open : hwc_device_open};
+static struct hw_module_methods_t hwc_module_methods = {
+  open : android::hwc_device_open
+};
 
 hwc_module_t HAL_MODULE_INFO_SYM = {
   common : {