DO NOT MERGE: drm_hwcomposer: Don\'t use Plan() in SquashAll
am: 8eb85ff7d7  -s ours

* commit '8eb85ff7d7704a4783cbb97eec480ae2c93d7f3b':
  DO NOT MERGE: drm_hwcomposer: Don't use Plan() in SquashAll

Change-Id: I00ad6d2959a3ac22424c0175d7a275dcd55ce4b2
diff --git a/Android.mk b/Android.mk
index 5ebdbee..5308225 100644
--- a/Android.mk
+++ b/Android.mk
@@ -30,6 +30,7 @@
 
 
 LOCAL_C_INCLUDES := \
+        external/drm_gralloc \
 	external/libdrm \
 	external/libdrm/include/drm \
 	system/core/include/utils \
@@ -53,17 +54,17 @@
 	drmproperty.cpp \
 	glworker.cpp \
 	hwcomposer.cpp \
+        platform.cpp \
+        platformdrmgeneric.cpp \
+        platformnv.cpp \
 	separate_rects.cpp \
 	virtualcompositorworker.cpp \
 	vsyncworker.cpp \
 	worker.cpp
 
 ifeq ($(strip $(BOARD_DRM_HWCOMPOSER_BUFFER_IMPORTER)),nvidia-gralloc)
-LOCAL_SRC_FILES += platformnv.cpp
 LOCAL_CPPFLAGS += -DUSE_NVIDIA_IMPORTER
 else
-LOCAL_C_INCLUDES += external/drm_gralloc
-LOCAL_SRC_FILES += platformdrmgeneric.cpp
 LOCAL_CPPFLAGS += -DUSE_DRM_GENERIC_IMPORTER
 endif
 
diff --git a/drmcomposition.cpp b/drmcomposition.cpp
index 72f00f1..1aaf920 100644
--- a/drmcomposition.cpp
+++ b/drmcomposition.cpp
@@ -20,6 +20,7 @@
 #include "drmcrtc.h"
 #include "drmplane.h"
 #include "drmresources.h"
+#include "platform.h"
 
 #include <stdlib.h>
 
@@ -30,8 +31,9 @@
 
 namespace android {
 
-DrmComposition::DrmComposition(DrmResources *drm, Importer *importer)
-    : drm_(drm), importer_(importer) {
+DrmComposition::DrmComposition(DrmResources *drm, Importer *importer,
+                               Planner *planner)
+    : drm_(drm), importer_(importer), planner_(planner) {
   char use_overlay_planes_prop[PROPERTY_VALUE_MAX];
   property_get("hwc.drm.use_overlay_planes", use_overlay_planes_prop, "1");
   bool use_overlay_planes = atoi(use_overlay_planes_prop);
@@ -56,7 +58,8 @@
     // If the display hasn't been modeset yet, this will be NULL
     DrmCrtc *crtc = drm_->GetCrtcForDisplay(display);
 
-    int ret = composition_map_[display]->Init(drm_, crtc, importer_, frame_no);
+    int ret = composition_map_[display]->Init(drm_, crtc, importer_, planner_,
+                                              frame_no);
     if (ret) {
       ALOGE("Failed to init display composition for %d", display);
       return ret;
diff --git a/drmcomposition.h b/drmcomposition.h
index ccb7184..eae8cde 100644
--- a/drmcomposition.h
+++ b/drmcomposition.h
@@ -44,7 +44,7 @@
 
 class DrmComposition {
  public:
-  DrmComposition(DrmResources *drm, Importer *importer);
+  DrmComposition(DrmResources *drm, Importer *importer, Planner *planner);
 
   int Init(uint64_t frame_no);
 
@@ -63,6 +63,7 @@
 
   DrmResources *drm_;
   Importer *importer_;
+  Planner *planner_;
 
   std::vector<DrmPlane *> primary_planes_;
   std::vector<DrmPlane *> overlay_planes_;
diff --git a/drmcompositor.cpp b/drmcompositor.cpp
index 09da6bf..c1f3ed8 100644
--- a/drmcompositor.cpp
+++ b/drmcompositor.cpp
@@ -19,6 +19,7 @@
 #include "drmcompositor.h"
 #include "drmdisplaycompositor.h"
 #include "drmresources.h"
+#include "platform.h"
 
 #include <sstream>
 #include <stdlib.h>
@@ -42,6 +43,11 @@
       return ret;
     }
   }
+  planner_ = Planner::CreateInstance(drm_);
+  if (!planner_) {
+    ALOGE("Failed to create planner instance for composition");
+    return -ENOMEM;
+  }
 
   return 0;
 }
@@ -49,7 +55,7 @@
 std::unique_ptr<DrmComposition> DrmCompositor::CreateComposition(
     Importer *importer) {
   std::unique_ptr<DrmComposition> composition(
-      new DrmComposition(drm_, importer));
+      new DrmComposition(drm_, importer, planner_.get()));
   int ret = composition->Init(++frame_no_);
   if (ret) {
     ALOGE("Failed to initialize drm composition %d", ret);
diff --git a/drmcompositor.h b/drmcompositor.h
index 27623d9..19271b5 100644
--- a/drmcompositor.h
+++ b/drmcompositor.h
@@ -44,6 +44,7 @@
   DrmCompositor(const DrmCompositor &) = delete;
 
   DrmResources *drm_;
+  std::unique_ptr<Planner> planner_;
 
   uint64_t frame_no_;
 
diff --git a/drmconnector.cpp b/drmconnector.cpp
index 8f9ad49..ccb38e2 100644
--- a/drmconnector.cpp
+++ b/drmconnector.cpp
@@ -69,7 +69,7 @@
 
 bool DrmConnector::built_in() const {
   return type_ == DRM_MODE_CONNECTOR_LVDS || type_ == DRM_MODE_CONNECTOR_eDP ||
-         type_ == DRM_MODE_CONNECTOR_DSI;
+         type_ == DRM_MODE_CONNECTOR_DSI || type_ == DRM_MODE_CONNECTOR_VIRTUAL;
 }
 
 int DrmConnector::UpdateModes() {
diff --git a/drmdisplaycomposition.cpp b/drmdisplaycomposition.cpp
index d5450ff..949f4a3 100644
--- a/drmdisplaycomposition.cpp
+++ b/drmdisplaycomposition.cpp
@@ -20,6 +20,7 @@
 #include "drmcrtc.h"
 #include "drmplane.h"
 #include "drmresources.h"
+#include "platform.h"
 
 #include <stdlib.h>
 
@@ -41,10 +42,12 @@
 }
 
 int DrmDisplayComposition::Init(DrmResources *drm, DrmCrtc *crtc,
-                                Importer *importer, uint64_t frame_no) {
+                                Importer *importer, Planner *planner,
+                                uint64_t frame_no) {
   drm_ = drm;
   crtc_ = crtc;  // Can be NULL if we haven't modeset yet
   importer_ = importer;
+  planner_ = planner;
   frame_no_ = frame_no;
 
   int ret = sw_sync_timeline_create();
@@ -118,65 +121,8 @@
   return 0;
 }
 
-static size_t CountUsablePlanes(DrmCrtc *crtc,
-                                std::vector<DrmPlane *> *primary_planes,
-                                std::vector<DrmPlane *> *overlay_planes) {
-  return std::count_if(
-             primary_planes->begin(), primary_planes->end(),
-             [=](DrmPlane *plane) { return plane->GetCrtcSupported(*crtc); }) +
-         std::count_if(
-             overlay_planes->begin(), overlay_planes->end(),
-             [=](DrmPlane *plane) { return plane->GetCrtcSupported(*crtc); });
-}
-
-static DrmPlane *TakePlane(DrmCrtc *crtc, std::vector<DrmPlane *> *planes) {
-  for (auto iter = planes->begin(); iter != planes->end(); ++iter) {
-    if ((*iter)->GetCrtcSupported(*crtc)) {
-      DrmPlane *plane = *iter;
-      planes->erase(iter);
-      return plane;
-    }
-  }
-  return NULL;
-}
-
-static DrmPlane *TakePlane(DrmCrtc *crtc,
-                           std::vector<DrmPlane *> *primary_planes,
-                           std::vector<DrmPlane *> *overlay_planes) {
-  DrmPlane *plane = TakePlane(crtc, primary_planes);
-  if (plane)
-    return plane;
-  return TakePlane(crtc, overlay_planes);
-}
-
-void DrmDisplayComposition::EmplaceCompositionPlane(
-    DrmCompositionPlane::Type type, std::vector<DrmPlane *> *primary_planes,
-    std::vector<DrmPlane *> *overlay_planes) {
-  DrmPlane *plane = TakePlane(crtc_, primary_planes, overlay_planes);
-  if (plane == NULL) {
-    ALOGE(
-        "Failed to add composition plane because there are no planes "
-        "remaining");
-    return;
-  }
-  composition_planes_.emplace_back(type, plane, crtc_);
-}
-
-void DrmDisplayComposition::EmplaceCompositionPlane(
-    size_t source_layer, std::vector<DrmPlane *> *primary_planes,
-    std::vector<DrmPlane *> *overlay_planes) {
-  DrmPlane *plane = TakePlane(crtc_, primary_planes, overlay_planes);
-  if (plane == NULL) {
-    ALOGE(
-        "Failed to add composition plane because there are no planes "
-        "remaining");
-    return;
-  }
-  composition_planes_.emplace_back(DrmCompositionPlane::Type::kLayer, plane,
-                                   crtc_, source_layer);
-}
-
-static std::vector<size_t> SetBitsToVector(uint64_t in, size_t *index_map) {
+static std::vector<size_t> SetBitsToVector(
+    uint64_t in, const std::vector<size_t> &index_map) {
   std::vector<size_t> out;
   size_t msb = sizeof(in) * 8 - 1;
   uint64_t mask = (uint64_t)1 << msb;
@@ -191,9 +137,7 @@
   return 0;
 }
 
-void DrmDisplayComposition::SeparateLayers(size_t *used_layers,
-                                           size_t num_used_layers,
-                                           DrmHwcRect<int> *exclude_rects,
+void DrmDisplayComposition::SeparateLayers(DrmHwcRect<int> *exclude_rects,
                                            size_t num_exclude_rects) {
   DrmCompositionPlane *comp = NULL;
   std::vector<size_t> dedicated_layers;
@@ -212,18 +156,19 @@
   if (!comp)
     return;
 
-  if (num_used_layers > 64) {
+  const std::vector<size_t> &comp_layers = comp->source_layers();
+  if (comp_layers.size() > 64) {
     ALOGE("Failed to separate layers because there are more than 64");
     return;
   }
 
   // Index at which the actual layers begin
   size_t layer_offset = num_exclude_rects + dedicated_layers.size();
-  if (num_used_layers + layer_offset > 64) {
+  if (comp_layers.size() + layer_offset > 64) {
     ALOGW(
         "Exclusion rectangles are being truncated to make the rectangle count "
         "fit into 64");
-    num_exclude_rects = 64 - num_used_layers - dedicated_layers.size();
+    num_exclude_rects = 64 - comp_layers.size() - dedicated_layers.size();
   }
 
   // We inject all the exclude rects into the rects list. Any resulting rect
@@ -231,14 +176,14 @@
   // exclude rects, we add the lower layers. The rects that intersect with
   // these layers will be inspected and only those which are to be composited
   // above the layer will be included in the composition regions.
-  std::vector<DrmHwcRect<int>> layer_rects(num_used_layers + layer_offset);
+  std::vector<DrmHwcRect<int>> layer_rects(comp_layers.size() + layer_offset);
   std::copy(exclude_rects, exclude_rects + num_exclude_rects,
             layer_rects.begin());
   std::transform(
       dedicated_layers.begin(), dedicated_layers.end(),
       layer_rects.begin() + num_exclude_rects,
       [=](size_t layer_index) { return layers_[layer_index].display_frame; });
-  std::transform(used_layers, used_layers + num_used_layers,
+  std::transform(comp_layers.begin(), comp_layers.end(),
                  layer_rects.begin() + layer_offset, [=](size_t layer_index) {
     return layers_[layer_index].display_frame;
   });
@@ -265,8 +210,8 @@
       if (!(dedicated_intersect & (1 << (i + num_exclude_rects))))
         continue;
 
-      for (size_t j = 0; j < num_used_layers; ++j) {
-        if (used_layers[j] < dedicated_layers[i])
+      for (size_t j = 0; j < comp_layers.size(); ++j) {
+        if (comp_layers[j] < dedicated_layers[i])
           region.id_set.subtract(j + layer_offset);
       }
     }
@@ -275,7 +220,7 @@
 
     pre_comp_regions_.emplace_back(DrmCompositionRegion{
         region.rect,
-        SetBitsToVector(region.id_set.getBits() >> layer_offset, used_layers)});
+        SetBitsToVector(region.id_set.getBits() >> layer_offset, comp_layers)});
   }
 }
 
@@ -344,19 +289,19 @@
   if (type_ != DRM_COMPOSITION_TYPE_FRAME)
     return 0;
 
-  size_t planes_can_use =
-      CountUsablePlanes(crtc_, primary_planes, overlay_planes);
-  if (planes_can_use == 0) {
-    ALOGE("Display %d has no usable planes", crtc_->display());
-    return -ENODEV;
-  }
+  // Used to track which layers should be sent to the planner. We exclude layers
+  // that are entirely squashed so the planner can provision a precomposition
+  // layer as appropriate (ex: if 5 layers are squashed and 1 is not, we don't
+  // want to plan a precomposition layer that will be comprised of the already
+  // squashed layers).
+  std::map<size_t, DrmHwcLayer *> to_composite;
 
   bool use_squash_framebuffer = false;
   // Used to determine which layers were entirely squashed
   std::vector<int> layer_squash_area(layers_.size(), 0);
   // Used to avoid rerendering regions that were squashed
   std::vector<DrmHwcRect<int>> exclude_rects;
-  if (squash != NULL && planes_can_use >= 3) {
+  if (squash != NULL) {
     if (geometry_changed_) {
       squash->Init(layers_.data(), layers_.size());
     } else {
@@ -404,95 +349,55 @@
         }
       }
     }
+
+    for (size_t i = 0; i < layers_.size(); ++i) {
+      if (layer_squash_area[i] < layers_[i].display_frame.area())
+        to_composite.emplace(std::make_pair(i, &layers_[i]));
+    }
+  } else {
+    for (size_t i = 0; i < layers_.size(); ++i)
+      to_composite.emplace(std::make_pair(i, &layers_[i]));
   }
 
-  // All protected layers get first usage of planes
-  std::vector<size_t> layers_remaining;
-  std::vector<size_t> protected_layers;
-  for (size_t layer_index = 0; layer_index < layers_.size(); layer_index++) {
-    if (!layers_[layer_index].protected_usage() || planes_can_use == 0) {
-      layers_remaining.push_back(layer_index);
+  int ret;
+  std::vector<DrmCompositionPlane> plan;
+  std::tie(ret, composition_planes_) =
+      planner_->ProvisionPlanes(to_composite, use_squash_framebuffer, crtc_,
+                                primary_planes, overlay_planes);
+  if (ret) {
+    ALOGE("Planner failed provisioning planes ret=%d", ret);
+    return ret;
+  }
+
+  // Remove the planes we used from the pool before returning. This ensures they
+  // won't be reused by another display in the composition.
+  for (auto &i : composition_planes_) {
+    if (!i.plane())
       continue;
-    }
-    protected_layers.push_back(layer_index);
-    planes_can_use--;
-  }
 
-  if (planes_can_use == 0 && layers_remaining.size() > 0) {
-    for (auto i : protected_layers)
-      EmplaceCompositionPlane(i, primary_planes, overlay_planes);
-
-    ALOGE("Protected layers consumed all hardware planes");
-    return CreateAndAssignReleaseFences();
-  }
-
-  std::vector<size_t> layers_remaining_if_squash;
-  for (size_t layer_index : layers_remaining) {
-    if (layer_squash_area[layer_index] <
-        layers_[layer_index].display_frame.area())
-      layers_remaining_if_squash.push_back(layer_index);
-  }
-
-  if (use_squash_framebuffer) {
-    if (planes_can_use > 1 || layers_remaining_if_squash.size() == 0) {
-      layers_remaining = std::move(layers_remaining_if_squash);
-      planes_can_use--;  // Reserve plane for squashing
-    } else {
-      use_squash_framebuffer = false;  // The squash buffer is still rendered
+    std::vector<DrmPlane *> *container;
+    if (i.plane()->type() == DRM_PLANE_TYPE_PRIMARY)
+      container = primary_planes;
+    else
+      container = overlay_planes;
+    for (auto j = container->begin(); j != container->end(); ++j) {
+      if (*j == i.plane()) {
+        container->erase(j);
+        break;
+      }
     }
   }
 
-  if (layers_remaining.size() > planes_can_use)
-    planes_can_use--;  // Reserve one for pre-compositing
-
-  // Whatever planes that are not reserved get assigned a layer
-  size_t last_hw_comp_layer = 0;
-  size_t protected_idx = 0;
-  while(last_hw_comp_layer < layers_remaining.size() && planes_can_use > 0) {
-    size_t idx = layers_remaining[last_hw_comp_layer];
-
-    // Put the protected layers into the composition at the right place. We've
-    // already reserved them by decrementing planes_can_use, so no need to do
-    // that again.
-    if (protected_idx < protected_layers.size() &&
-        idx > protected_layers[protected_idx]) {
-      EmplaceCompositionPlane(protected_layers[protected_idx], primary_planes,
-                              overlay_planes);
-      protected_idx++;
-      continue;
-    }
-
-    EmplaceCompositionPlane(layers_remaining[last_hw_comp_layer],
-                            primary_planes, overlay_planes);
-    last_hw_comp_layer++;
-    planes_can_use--;
-  }
-
-  layers_remaining.erase(layers_remaining.begin(),
-                         layers_remaining.begin() + last_hw_comp_layer);
-
-  // Enqueue the rest of the protected layers (if any) between the hw composited
-  // overlay layers and the squash/precomp layers.
-  for (size_t i = protected_idx; i < protected_layers.size(); ++i)
-    EmplaceCompositionPlane(protected_layers[i], primary_planes,
-                            overlay_planes);
-
-  if (layers_remaining.size() > 0) {
-    EmplaceCompositionPlane(DrmCompositionPlane::Type::kPrecomp, primary_planes,
-                            overlay_planes);
-    SeparateLayers(layers_remaining.data(), layers_remaining.size(),
-                   exclude_rects.data(), exclude_rects.size());
-  }
-
-  if (use_squash_framebuffer) {
-    EmplaceCompositionPlane(DrmCompositionPlane::Type::kSquash, primary_planes,
-                            overlay_planes);
-  }
-
-  return FinalizeComposition();
+  return FinalizeComposition(exclude_rects.data(), exclude_rects.size());
 }
 
 int DrmDisplayComposition::FinalizeComposition() {
+  return FinalizeComposition(NULL, 0);
+}
+
+int DrmDisplayComposition::FinalizeComposition(DrmHwcRect<int> *exclude_rects,
+                                               size_t num_exclude_rects) {
+  SeparateLayers(exclude_rects, num_exclude_rects);
   return CreateAndAssignReleaseFences();
 }
 
diff --git a/drmdisplaycomposition.h b/drmdisplaycomposition.h
index 6c52664..13da19d 100644
--- a/drmdisplaycomposition.h
+++ b/drmdisplaycomposition.h
@@ -21,7 +21,6 @@
 #include "drmhwcomposer.h"
 #include "drmplane.h"
 #include "glworker.h"
-#include "platform.h"
 
 #include <sstream>
 #include <vector>
@@ -32,6 +31,8 @@
 
 namespace android {
 
+class Importer;
+class Planner;
 class SquashState;
 
 enum DrmCompositionType {
@@ -106,7 +107,7 @@
   ~DrmDisplayComposition();
 
   int Init(DrmResources *drm, DrmCrtc *crtc, Importer *importer,
-           uint64_t frame_no);
+           Planner *planner, uint64_t frame_no);
 
   int SetLayers(DrmHwcLayer *layers, size_t num_layers, bool geometry_changed);
   int AddPlaneComposition(DrmCompositionPlane plane);
@@ -174,6 +175,10 @@
     return importer_;
   }
 
+  Planner *planner() const {
+    return planner_;
+  }
+
   void Dump(std::ostringstream *out) const;
 
  private:
@@ -181,19 +186,15 @@
 
   int IncreaseTimelineToPoint(int point);
 
-  void EmplaceCompositionPlane(DrmCompositionPlane::Type type,
-                               std::vector<DrmPlane *> *primary_planes,
-                               std::vector<DrmPlane *> *overlay_planes);
-  void EmplaceCompositionPlane(size_t source_layer,
-                               std::vector<DrmPlane *> *primary_planes,
-                               std::vector<DrmPlane *> *overlay_planes);
-  void SeparateLayers(size_t *used_layers, size_t num_used_layers,
-                      DrmHwcRect<int> *exclude_rects, size_t num_exclude_rects);
+  int FinalizeComposition(DrmHwcRect<int> *exclude_rects,
+                          size_t num_exclude_rects);
+  void SeparateLayers(DrmHwcRect<int> *exclude_rects, size_t num_exclude_rects);
   int CreateAndAssignReleaseFences();
 
   DrmResources *drm_ = NULL;
   DrmCrtc *crtc_ = NULL;
   Importer *importer_ = NULL;
+  Planner *planner_ = NULL;
 
   DrmCompositionType type_ = DRM_COMPOSITION_TYPE_EMPTY;
   uint32_t dpms_mode_ = DRM_MODE_DPMS_ON;
diff --git a/drmdisplaycompositor.cpp b/drmdisplaycompositor.cpp
index 10a1ffc..0b2506f 100644
--- a/drmdisplaycompositor.cpp
+++ b/drmdisplaycompositor.cpp
@@ -1048,7 +1048,8 @@
 
   int pre_comp_layer_index;
 
-  int ret = dst->Init(drm_, src->crtc(), src->importer(), src->frame_no());
+  int ret = dst->Init(drm_, src->crtc(), src->importer(), src->planner(),
+                      src->frame_no());
   if (ret) {
     ALOGE("Failed to init squash all composition %d", ret);
     return ret;
@@ -1065,8 +1066,10 @@
       goto move_layers_back;
     }
 
-    if (comp_plane.type() == DrmCompositionPlane::Type::kDisable)
+    if (comp_plane.type() == DrmCompositionPlane::Type::kDisable) {
+      dst->AddPlaneDisable(comp_plane.plane());
       continue;
+    }
 
     for (auto i : comp_plane.source_layers()) {
       DrmHwcLayer &layer = src_layers[i];
diff --git a/platform.cpp b/platform.cpp
new file mode 100644
index 0000000..105d8f7
--- /dev/null
+++ b/platform.cpp
@@ -0,0 +1,167 @@
+/*
+ * Copyright (C) 2016 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-platform"
+
+#include "drmresources.h"
+#include "platform.h"
+
+#include <cutils/log.h>
+
+namespace android {
+
+std::vector<DrmPlane *> Planner::GetUsablePlanes(
+    DrmCrtc *crtc, std::vector<DrmPlane *> *primary_planes,
+    std::vector<DrmPlane *> *overlay_planes) {
+  std::vector<DrmPlane *> usable_planes;
+  std::copy_if(primary_planes->begin(), primary_planes->end(),
+               std::back_inserter(usable_planes),
+               [=](DrmPlane *plane) { return plane->GetCrtcSupported(*crtc); });
+  std::copy_if(overlay_planes->begin(), overlay_planes->end(),
+               std::back_inserter(usable_planes),
+               [=](DrmPlane *plane) { return plane->GetCrtcSupported(*crtc); });
+  return usable_planes;
+}
+
+std::tuple<int, std::vector<DrmCompositionPlane>> Planner::ProvisionPlanes(
+    std::map<size_t, DrmHwcLayer *> &layers, bool use_squash_fb, DrmCrtc *crtc,
+    std::vector<DrmPlane *> *primary_planes,
+    std::vector<DrmPlane *> *overlay_planes) {
+  std::vector<DrmCompositionPlane> composition;
+  std::vector<DrmPlane *> planes =
+      GetUsablePlanes(crtc, primary_planes, overlay_planes);
+  if (planes.empty()) {
+    ALOGE("Display %d has no usable planes", crtc->display());
+    return std::make_tuple(-ENODEV, std::vector<DrmCompositionPlane>());
+  }
+
+  // If needed, reserve the squash plane at the highest z-order
+  DrmPlane *squash_plane = NULL;
+  if (use_squash_fb) {
+    if (!planes.empty()) {
+      squash_plane = planes.back();
+      planes.pop_back();
+    } else {
+      ALOGI("Not enough planes to reserve for squash fb");
+    }
+  }
+
+  // If needed, reserve the precomp plane at the next highest z-order
+  DrmPlane *precomp_plane = NULL;
+  if (layers.size() > planes.size()) {
+    if (!planes.empty()) {
+      precomp_plane = planes.back();
+      planes.pop_back();
+      composition.emplace_back(DrmCompositionPlane::Type::kPrecomp,
+                               precomp_plane, crtc);
+    } else {
+      ALOGE("Not enough planes to reserve for precomp fb");
+    }
+  }
+
+  // Go through the provisioning stages and provision planes
+  for (auto &i : stages_) {
+    int ret = i->ProvisionPlanes(&composition, layers, crtc, &planes);
+    if (ret) {
+      ALOGE("Failed provision stage with ret %d", ret);
+      return std::make_tuple(ret, std::vector<DrmCompositionPlane>());
+    }
+  }
+
+  if (squash_plane)
+    composition.emplace_back(DrmCompositionPlane::Type::kSquash, squash_plane,
+                             crtc);
+
+  return std::make_tuple(0, std::move(composition));
+}
+
+int PlanStageProtected::ProvisionPlanes(
+    std::vector<DrmCompositionPlane> *composition,
+    std::map<size_t, DrmHwcLayer *> &layers, DrmCrtc *crtc,
+    std::vector<DrmPlane *> *planes) {
+  int ret;
+  int protected_zorder = -1;
+  for (auto i = layers.begin(); i != layers.end();) {
+    if (!i->second->protected_usage()) {
+      ++i;
+      continue;
+    }
+
+    ret = Emplace(composition, planes, DrmCompositionPlane::Type::kLayer, crtc,
+                  i->first);
+    if (ret)
+      ALOGE("Failed to dedicate protected layer! Dropping it.");
+
+    protected_zorder = i->first;
+    i = layers.erase(i);
+  }
+
+  if (protected_zorder == -1)
+    return 0;
+
+  // Add any layers below the protected content to the precomposition since we
+  // need to punch a hole through them.
+  for (auto i = layers.begin(); i != layers.end();) {
+    // Skip layers above the z-order of the protected content
+    if (i->first > static_cast<size_t>(protected_zorder)) {
+      ++i;
+      continue;
+    }
+
+    // If there's no precomp layer already queued, queue one now.
+    DrmCompositionPlane *precomp = GetPrecomp(composition);
+    if (precomp) {
+      precomp->source_layers().emplace_back(i->first);
+    } else {
+      if (!planes->empty()) {
+        DrmPlane *precomp_plane = planes->back();
+        planes->pop_back();
+        composition->emplace_back(DrmCompositionPlane::Type::kPrecomp,
+                                  precomp_plane, crtc, i->first);
+      } else {
+        ALOGE("Not enough planes to reserve for precomp fb");
+      }
+    }
+    i = layers.erase(i);
+  }
+  return 0;
+}
+
+int PlanStageGreedy::ProvisionPlanes(
+    std::vector<DrmCompositionPlane> *composition,
+    std::map<size_t, DrmHwcLayer *> &layers, DrmCrtc *crtc,
+    std::vector<DrmPlane *> *planes) {
+  // Fill up the remaining planes
+  for (auto i = layers.begin(); i != layers.end(); i = layers.erase(i)) {
+    int ret = Emplace(composition, planes, DrmCompositionPlane::Type::kLayer,
+                      crtc, i->first);
+    // We don't have any planes left
+    if (ret == -ENOENT)
+      break;
+    else if (ret)
+      ALOGE("Failed to emplace layer %zu, dropping it", i->first);
+  }
+
+  // Put the rest of the layers in the precomp plane
+  DrmCompositionPlane *precomp = GetPrecomp(composition);
+  if (precomp) {
+    for (auto i = layers.begin(); i != layers.end(); i = layers.erase(i))
+      precomp->source_layers().emplace_back(i->first);
+  }
+
+  return 0;
+}
+}
diff --git a/platform.h b/platform.h
index 059c40e..da6b7cb 100644
--- a/platform.h
+++ b/platform.h
@@ -17,11 +17,15 @@
 #ifndef ANDROID_DRM_PLATFORM_H_
 #define ANDROID_DRM_PLATFORM_H_
 
+#include "drmdisplaycomposition.h"
 #include "drmhwcomposer.h"
 
 #include <hardware/hardware.h>
 #include <hardware/hwcomposer.h>
 
+#include <map>
+#include <vector>
+
 namespace android {
 
 class DrmResources;
@@ -46,5 +50,116 @@
   //       implementation is responsible for ensuring thread safety.
   virtual int ReleaseBuffer(hwc_drm_bo_t *bo) = 0;
 };
+
+class Planner {
+ public:
+  class PlanStage {
+   public:
+    virtual ~PlanStage() {
+    }
+
+    virtual int ProvisionPlanes(std::vector<DrmCompositionPlane> *composition,
+                                std::map<size_t, DrmHwcLayer *> &layers,
+                                DrmCrtc *crtc,
+                                std::vector<DrmPlane *> *planes) = 0;
+
+   protected:
+    // Removes and returns the next available plane from planes
+    static DrmPlane *PopPlane(std::vector<DrmPlane *> *planes) {
+      if (planes->empty())
+        return NULL;
+      DrmPlane *plane = planes->front();
+      planes->erase(planes->begin());
+      return plane;
+    }
+
+    // Finds and returns the squash layer from the composition
+    static DrmCompositionPlane *GetPrecomp(
+        std::vector<DrmCompositionPlane> *composition) {
+      auto l = GetPrecompIter(composition);
+      if (l == composition->end())
+        return NULL;
+      return &(*l);
+    }
+
+    // Inserts the given layer:plane in the composition right before the precomp
+    // layer
+    static int Emplace(std::vector<DrmCompositionPlane> *composition,
+                       std::vector<DrmPlane *> *planes,
+                       DrmCompositionPlane::Type type, DrmCrtc *crtc,
+                       size_t source_layer) {
+      DrmPlane *plane = PopPlane(planes);
+      if (!plane)
+        return -ENOENT;
+
+      auto precomp = GetPrecompIter(composition);
+      composition->emplace(precomp, type, plane, crtc, source_layer);
+      return 0;
+    }
+
+   private:
+    static std::vector<DrmCompositionPlane>::iterator GetPrecompIter(
+        std::vector<DrmCompositionPlane> *composition) {
+      return std::find_if(composition->begin(), composition->end(),
+                          [](const DrmCompositionPlane &p) {
+        return p.type() == DrmCompositionPlane::Type::kPrecomp;
+      });
+    }
+  };
+
+  // Creates a planner instance with platform-specific planning stages
+  static std::unique_ptr<Planner> CreateInstance(DrmResources *drm);
+
+  // Takes a stack of layers and provisions hardware planes for them. If the
+  // entire stack can't fit in hardware, the Planner may place the remaining
+  // layers in a PRECOMP plane. Layers in the PRECOMP plane will be composited
+  // using GL. PRECOMP planes should be placed above any 1:1 layer:plane
+  // compositions. If use_squash_fb is true, the Planner should try to reserve a
+  // plane at the highest z-order with type SQUASH.
+  //
+  // @layers: a map of index:layer of layers to composite
+  // @use_squash_fb: reserve a squash framebuffer
+  // @primary_planes: a vector of primary planes available for this frame
+  // @overlay_planes: a vector of overlay planes available for this frame
+  //
+  // Returns: A tuple with the status of the operation (0 for success) and
+  //          a vector of the resulting plan (ie: layer->plane mapping).
+  std::tuple<int, std::vector<DrmCompositionPlane>> ProvisionPlanes(
+      std::map<size_t, DrmHwcLayer *> &layers, bool use_squash_fb,
+      DrmCrtc *crtc, std::vector<DrmPlane *> *primary_planes,
+      std::vector<DrmPlane *> *overlay_planes);
+
+  template <typename T, typename... A>
+  void AddStage(A &&... args) {
+    stages_.emplace_back(
+        std::unique_ptr<PlanStage>(new T(std::forward(args)...)));
+  }
+
+ private:
+  std::vector<DrmPlane *> GetUsablePlanes(
+      DrmCrtc *crtc, std::vector<DrmPlane *> *primary_planes,
+      std::vector<DrmPlane *> *overlay_planes);
+
+  std::vector<std::unique_ptr<PlanStage>> stages_;
+};
+
+// This plan stage extracts all protected layers and places them on dedicated
+// planes.
+class PlanStageProtected : public Planner::PlanStage {
+ public:
+  int ProvisionPlanes(std::vector<DrmCompositionPlane> *composition,
+                      std::map<size_t, DrmHwcLayer *> &layers, DrmCrtc *crtc,
+                      std::vector<DrmPlane *> *planes);
+};
+
+// This plan stage places as many layers on dedicated planes as possible (first
+// come first serve), and then sticks the rest in a precomposition plane (if
+// needed).
+class PlanStageGreedy : public Planner::PlanStage {
+ public:
+  int ProvisionPlanes(std::vector<DrmCompositionPlane> *composition,
+                      std::map<size_t, DrmHwcLayer *> &layers, DrmCrtc *crtc,
+                      std::vector<DrmPlane *> *planes);
+};
 }
 #endif
diff --git a/platformdrmgeneric.cpp b/platformdrmgeneric.cpp
index 95ea11e..90ba0e2 100644
--- a/platformdrmgeneric.cpp
+++ b/platformdrmgeneric.cpp
@@ -25,8 +25,6 @@
 #include <xf86drmMode.h>
 
 #include <cutils/log.h>
-#include <gralloc_drm.h>
-#include <gralloc_drm_priv.h>
 #include <gralloc_drm_handle.h>
 #include <hardware/gralloc.h>
 
@@ -90,12 +88,6 @@
   if (!gr_handle)
     return -EINVAL;
 
-  struct gralloc_drm_bo_t *gralloc_bo = gr_handle->data;
-  if (!gralloc_bo) {
-    ALOGE("Could not get drm bo from handle");
-    return -EINVAL;
-  }
-
   uint32_t gem_handle;
   int ret = drmPrimeFDToHandle(drm_->fd(), gr_handle->prime_fd, &gem_handle);
   if (ret) {
@@ -142,4 +134,12 @@
   }
   return 0;
 }
+
+#ifdef USE_DRM_GENERIC_IMPORTER
+std::unique_ptr<Planner> Planner::CreateInstance(DrmResources *) {
+  std::unique_ptr<Planner> planner(new Planner);
+  planner->AddStage<PlanStageGreedy>();
+  return planner;
+}
+#endif
 }
diff --git a/platformnv.cpp b/platformnv.cpp
index 5b79826..db7ee36 100644
--- a/platformnv.cpp
+++ b/platformnv.cpp
@@ -183,4 +183,92 @@
                            GRALLOC_MODULE_PERFORM_SET_IMPORTER_PRIVATE, handle,
                            NvGrallocRelease, buf);
 }
+
+#ifdef USE_NVIDIA_IMPORTER
+// static
+std::unique_ptr<Planner> Planner::CreateInstance(DrmResources *) {
+  std::unique_ptr<Planner> planner(new Planner);
+  planner->AddStage<PlanStageProtectedRotated>();
+  planner->AddStage<PlanStageProtected>();
+  planner->AddStage<PlanStageGreedy>();
+  return planner;
+}
+#endif
+
+static DrmPlane *GetCrtcPrimaryPlane(DrmCrtc *crtc,
+                                     std::vector<DrmPlane *> *planes) {
+  for (auto i = planes->begin(); i != planes->end(); ++i) {
+    if ((*i)->GetCrtcSupported(*crtc)) {
+      DrmPlane *plane = *i;
+      planes->erase(i);
+      return plane;
+    }
+  }
+  return NULL;
+}
+
+int PlanStageProtectedRotated::ProvisionPlanes(
+    std::vector<DrmCompositionPlane> *composition,
+    std::map<size_t, DrmHwcLayer *> &layers, DrmCrtc *crtc,
+    std::vector<DrmPlane *> *planes) {
+  int ret;
+  int protected_zorder = -1;
+  for (auto i = layers.begin(); i != layers.end();) {
+    if (!i->second->protected_usage() || !i->second->transform) {
+      ++i;
+      continue;
+    }
+
+    auto primary_iter = planes->begin();
+    for (; primary_iter != planes->end(); ++primary_iter) {
+      if ((*primary_iter)->type() == DRM_PLANE_TYPE_PRIMARY)
+        break;
+    }
+
+    // We cheat a little here. Since there can only be one primary plane per
+    // crtc, we know we'll only hit this case once. So we blindly insert the
+    // protected content at the beginning of the composition, knowing this path
+    // won't be taken a second time during the loop.
+    if (primary_iter != planes->end()) {
+      composition->emplace(composition->begin(),
+                           DrmCompositionPlane::Type::kLayer, *primary_iter,
+                           crtc, i->first);
+      planes->erase(primary_iter);
+      protected_zorder = i->first;
+    } else {
+      ALOGE("Could not provision primary plane for protected/rotated layer");
+    }
+    i = layers.erase(i);
+  }
+
+  if (protected_zorder == -1)
+    return 0;
+
+  // Add any layers below the protected content to the precomposition since we
+  // need to punch a hole through them.
+  for (auto i = layers.begin(); i != layers.end();) {
+    // Skip layers above the z-order of the protected content
+    if (i->first > static_cast<size_t>(protected_zorder)) {
+      ++i;
+      continue;
+    }
+
+    // If there's no precomp layer already queued, queue one now.
+    DrmCompositionPlane *precomp = GetPrecomp(composition);
+    if (precomp) {
+      precomp->source_layers().emplace_back(i->first);
+    } else {
+      if (planes->size()) {
+        DrmPlane *precomp_plane = planes->back();
+        planes->pop_back();
+        composition->emplace_back(DrmCompositionPlane::Type::kPrecomp,
+                                  precomp_plane, crtc, i->first);
+      } else {
+        ALOGE("Not enough planes to reserve for precomp fb");
+      }
+    }
+    i = layers.erase(i);
+  }
+  return 0;
+}
 }
diff --git a/platformnv.h b/platformnv.h
index 652409b..a9e5d39 100644
--- a/platformnv.h
+++ b/platformnv.h
@@ -19,6 +19,7 @@
 
 #include "drmresources.h"
 #include "platform.h"
+#include "platformdrmgeneric.h"
 
 #include <stdatomic.h>
 
@@ -53,6 +54,23 @@
 
   const gralloc_module_t *gralloc_;
 };
+
+// This stage looks for any layers that contain transformed protected content
+// and puts it in the primary plane since Tegra doesn't support planar rotation
+// on the overlay planes.
+//
+// There are two caveats to this approach: 1- Protected content isn't
+// necessarily planar, but it's usually a safe bet, and 2- This doesn't catch
+// non-protected planar content. If we wanted to fix this, we'd need to import
+// the buffer in this stage and peek at it's format. The overhead of doing this
+// doesn't seem worth it since we'll end up displaying the right thing in both
+// cases anyways.
+class PlanStageProtectedRotated : public Planner::PlanStage {
+ public:
+  int ProvisionPlanes(std::vector<DrmCompositionPlane> *composition,
+                      std::map<size_t, DrmHwcLayer *> &layers, DrmCrtc *crtc,
+                      std::vector<DrmPlane *> *planes);
+};
 }
 
 #endif