Merge "HWC: Use 2 VG pipes for YUV layer with width > 2048"
diff --git a/libcopybit/copybit.cpp b/libcopybit/copybit.cpp
index 5d8da05..47d9b93 100644
--- a/libcopybit/copybit.cpp
+++ b/libcopybit/copybit.cpp
@@ -714,6 +714,10 @@
     ctx->mAlpha = MDP_ALPHA_NOP;
     ctx->mFlags = 0;
     ctx->sync.flags = 0;
+    ctx->relFence = -1;
+    for (int i=0; i < MDP_MAX_FENCE_FD; i++) {
+        ctx->acqFence[i] = -1;
+    }
     ctx->sync.acq_fen_fd = ctx->acqFence;
     ctx->sync.rel_fen_fd = &ctx->relFence;
     ctx->list.count = 0;
diff --git a/libhwcomposer/hwc_mdpcomp.cpp b/libhwcomposer/hwc_mdpcomp.cpp
index 1f86f59..a0b9646 100644
--- a/libhwcomposer/hwc_mdpcomp.cpp
+++ b/libhwcomposer/hwc_mdpcomp.cpp
@@ -43,7 +43,7 @@
 bool MDPComp::sEnableMixedMode = true;
 bool MDPComp::sEnablePartialFrameUpdate = false;
 int MDPComp::sMaxPipesPerMixer = MAX_PIPES_PER_MIXER;
-float MDPComp::sMaxBw = 2.3f;
+double MDPComp::sMaxBw = 0.0;
 double MDPComp::sBwClaimed = 0.0;
 bool MDPComp::sEnable4k2kYUVSplit = false;
 
@@ -129,13 +129,6 @@
             sMaxPipesPerMixer = min(val, MAX_PIPES_PER_MIXER);
     }
 
-    if(property_get("debug.mdpcomp.bw", property, "0") > 0) {
-        float val = atof(property);
-        if(val > 0.0f) {
-            sMaxBw = val;
-        }
-    }
-
     if(ctx->mMDP.panel != MIPI_CMD_PANEL) {
         // Idle invalidation is not necessary on command mode panels
         long idle_timeout = DEFAULT_IDLE_TIME;
@@ -300,6 +293,10 @@
     private_handle_t *hnd = (private_handle_t *)layer->handle;
 
     if(!hnd) {
+        if (layer->flags & HWC_COLOR_FILL) {
+            // Color layer
+            return true;
+        }
         ALOGE("%s: layer handle is NULL", __FUNCTION__);
         return false;
     }
@@ -329,23 +326,25 @@
     if((crop_w < 5)||(crop_h < 5))
         return false;
 
-    const uint32_t downscale =
+    if((w_dscale > 1.0f) || (h_dscale > 1.0f)) {
+        const uint32_t downscale =
             qdutils::MDPVersion::getInstance().getMaxMDPDownscale();
-    if(ctx->mMDP.version >= qdutils::MDSS_V5) {
-        /* Workaround for downscales larger than 4x.
-         * Will be removed once decimator block is enabled for MDSS
-         */
-        if(!qdutils::MDPVersion::getInstance().supportsDecimation()) {
-            if(crop_w > MAX_DISPLAY_DIM || w_dscale > downscale ||
-                    h_dscale > downscale)
-                return false;
-        } else {
-            if(w_dscale > 64 || h_dscale > 64)
+        if(ctx->mMDP.version >= qdutils::MDSS_V5) {
+            /* Workaround for downscales larger than 4x.
+             * Will be removed once decimator block is enabled for MDSS
+             */
+            if(!qdutils::MDPVersion::getInstance().supportsDecimation()) {
+                if(crop_w > MAX_DISPLAY_DIM || w_dscale > downscale ||
+                   h_dscale > downscale)
+                    return false;
+            } else {
+                if(w_dscale > 64 || h_dscale > 64)
+                    return false;
+            }
+        } else { //A-family
+            if(w_dscale > downscale || h_dscale > downscale)
                 return false;
         }
-    } else { //A-family
-        if(w_dscale > downscale || h_dscale > downscale)
-            return false;
     }
 
     return true;
@@ -1192,7 +1191,7 @@
         return false;
     }
 
-    uint32_t size = calcMDPBytesRead(ctx, list);
+    double size = calcMDPBytesRead(ctx, list);
     if(!bandwidthCheck(ctx, size)) {
         ALOGD_IF(isDebug(), "%s: Exceeds bandwidth",__FUNCTION__);
         return false;
@@ -1201,12 +1200,15 @@
     return true;
 }
 
-uint32_t MDPComp::calcMDPBytesRead(hwc_context_t *ctx,
+double MDPComp::calcMDPBytesRead(hwc_context_t *ctx,
         hwc_display_contents_1_t* list) {
-    uint32_t size = 0;
+    double size = 0;
+    const double GIG = 1000000000.0;
 
-    if(!qdutils::MDPVersion::getInstance().is8x74v2())
-        return 0;
+    //Skip for targets where no device tree value for bw is supplied
+    if(sMaxBw <= 0.0) {
+        return 0.0;
+    }
 
     for (uint32_t i = 0; i < list->numHwLayers - 1; i++) {
         if(!mCurrentFrame.isFBComposed[i]) {
@@ -1216,33 +1218,37 @@
                 hwc_rect_t crop = integerizeSourceCrop(layer->sourceCropf);
                 hwc_rect_t dst = layer->displayFrame;
                 float bpp = ((float)hnd->size) / (hnd->width * hnd->height);
-                size += bpp * (crop.right - crop.left) *
-                    (crop.bottom - crop.top) *
-                    ctx->dpyAttr[mDpy].yres / (dst.bottom - dst.top);
+                size += (bpp * (crop.right - crop.left) *
+                        (crop.bottom - crop.top) *
+                        ctx->dpyAttr[mDpy].yres / (dst.bottom - dst.top)) /
+                        GIG;
             }
         }
     }
 
     if(mCurrentFrame.fbCount) {
         hwc_layer_1_t* layer = &list->hwLayers[list->numHwLayers - 1];
-        private_handle_t *hnd = (private_handle_t *)layer->handle;
-        if (hnd)
-            size += hnd->size;
+        int tempw, temph;
+        size += (getBufferSizeAndDimensions(
+                    layer->displayFrame.right - layer->displayFrame.left,
+                    layer->displayFrame.bottom - layer->displayFrame.top,
+                    HAL_PIXEL_FORMAT_RGBA_8888,
+                    tempw, temph)) / GIG;
     }
 
     return size;
 }
 
-bool MDPComp::bandwidthCheck(hwc_context_t *ctx, const uint32_t& size) {
-    //Will be added for other targets if we run into bandwidth issues and when
-    //we have profiling data to set an upper limit.
-    if(qdutils::MDPVersion::getInstance().is8x74v2()) {
-        const uint32_t ONE_GIG = 1000 * 1000 * 1000;
-        double panelRefRate =
-                1000000000.0 / ctx->dpyAttr[mDpy].vsync_period;
-        if((size * panelRefRate) > ((sMaxBw - sBwClaimed) * ONE_GIG)) {
-            return false;
-        }
+bool MDPComp::bandwidthCheck(hwc_context_t *ctx, const double& size) {
+    //Skip for targets where no device tree value for bw is supplied
+    if(sMaxBw <= 0.0) {
+        return true;
+    }
+
+    double panelRefRate =
+            1000000000.0 / ctx->dpyAttr[mDpy].vsync_period;
+    if((size * panelRefRate) > (sMaxBw - sBwClaimed)) {
+        return false;
     }
     return true;
 }
@@ -1250,6 +1256,7 @@
 int MDPComp::prepare(hwc_context_t *ctx, hwc_display_contents_1_t* list) {
     int ret = 0;
     const int numLayers = ctx->listStats[mDpy].numAppLayers;
+    MDPVersion& mdpVersion = qdutils::MDPVersion::getInstance();
 
     //reset old data
     mCurrentFrame.reset(numLayers);
@@ -1277,6 +1284,12 @@
 
     generateROI(ctx, list);
 
+    //Convert from kbps to gbps
+    sMaxBw = mdpVersion.getHighBw() / 1000000.0;
+    if (ctx->mExtDisplay->isConnected() || ctx->mMDP.panel != MIPI_CMD_PANEL) {
+        sMaxBw = mdpVersion.getLowBw() / 1000000.0;
+    }
+
     //Check whether layers marked for MDP Composition is actually doable.
     if(isFullFrameDoable(ctx, list)) {
         mCurrentFrame.map();
@@ -1374,9 +1387,9 @@
     }
 
 exit:
-    //gbps (bytes / nanosec = gigabytes / sec)
-    sBwClaimed += calcMDPBytesRead(ctx, list) /
-            (double)ctx->dpyAttr[mDpy].vsync_period;
+    double panelRefRate =
+            1000000000.0 / ctx->dpyAttr[mDpy].vsync_period;
+    sBwClaimed += calcMDPBytesRead(ctx, list) * panelRefRate;
     return ret;
 }
 
@@ -1575,8 +1588,13 @@
         hwc_layer_1_t *layer = &list->hwLayers[i];
         private_handle_t *hnd = (private_handle_t *)layer->handle;
         if(!hnd) {
-            ALOGE("%s handle null", __FUNCTION__);
-            return false;
+            if (!(layer->flags & HWC_COLOR_FILL)) {
+                ALOGE("%s handle null", __FUNCTION__);
+                return false;
+            }
+            // No PLAY for Color layer
+            layerProp[i].mFlags &= ~HWC_MDPCOMP;
+            continue;
         }
 
         int mdpIndex = mCurrentFrame.layerToMDP[i];
diff --git a/libhwcomposer/hwc_mdpcomp.h b/libhwcomposer/hwc_mdpcomp.h
index 715a572..7e646d7 100644
--- a/libhwcomposer/hwc_mdpcomp.h
+++ b/libhwcomposer/hwc_mdpcomp.h
@@ -176,11 +176,11 @@
             bool secureOnly);
     /* checks for conditions where YUV layers cannot be bypassed */
     bool isYUVDoable(hwc_context_t* ctx, hwc_layer_1_t* layer);
-    /* calcs bytes read by MDP for a given frame */
-    uint32_t calcMDPBytesRead(hwc_context_t *ctx,
+    /* calcs bytes read by MDP in gigs for a given frame */
+    double calcMDPBytesRead(hwc_context_t *ctx,
             hwc_display_contents_1_t* list);
     /* checks if the required bandwidth exceeds a certain max */
-    bool bandwidthCheck(hwc_context_t *ctx, const uint32_t& size);
+    bool bandwidthCheck(hwc_context_t *ctx, const double& size);
     /* generates ROI based on the modified area of the frame */
     void generateROI(hwc_context_t *ctx, hwc_display_contents_1_t* list);
     bool validateAndApplyROI(hwc_context_t *ctx, hwc_display_contents_1_t* list,
@@ -223,7 +223,7 @@
     static bool sIdleFallBack;
     static int sMaxPipesPerMixer;
     //Max bandwidth. Value is in GBPS. For ex: 2.3 means 2.3GBPS
-    static float sMaxBw;
+    static double sMaxBw;
     //Tracks composition bandwidth claimed. Represented as the total
     //w*h*bpp*fps (gigabytes-per-second) going to MDP mixers.
     static double sBwClaimed;
diff --git a/libhwcomposer/hwc_qclient.cpp b/libhwcomposer/hwc_qclient.cpp
index a17565b..3b98788 100644
--- a/libhwcomposer/hwc_qclient.cpp
+++ b/libhwcomposer/hwc_qclient.cpp
@@ -51,57 +51,28 @@
     ALOGD_IF(QCLIENT_DEBUG,"QClient Destructor invoked");
 }
 
-status_t QClient::notifyCallback(uint32_t msg, uint32_t value) {
-
-    if (msg > IQService::VPU_COMMAND_LIST_START &&
-        msg < IQService::VPU_COMMAND_LIST_END) {
-        return vpuCommand(msg, value);
-    }
-
-    switch(msg) {
-        case IQService::SECURING:
-            securing(value);
-            break;
-        case IQService::UNSECURING:
-            unsecuring(value);
-            break;
-        case IQService::SCREEN_REFRESH:
-            return screenRefresh();
-            break;
-        case IQService::EXTERNAL_ORIENTATION:
-            setExtOrientation(value);
-            break;
-        case IQService::BUFFER_MIRRORMODE:
-            setBufferMirrorMode(value);
-            break;
-        default:
-            return NO_ERROR;
-    }
-    return NO_ERROR;
-}
-
-void QClient::securing(uint32_t startEnd) {
-    Locker::Autolock _sl(mHwcContext->mDrawLock);
+static void securing(hwc_context_t *ctx, uint32_t startEnd) {
+    Locker::Autolock _sl(ctx->mDrawLock);
     //The only way to make this class in this process subscribe to media
     //player's death.
     IMediaDeathNotifier::getMediaPlayerService();
 
-    mHwcContext->mSecuring = startEnd;
+    ctx->mSecuring = startEnd;
     //We're done securing
     if(startEnd == IQService::END)
-        mHwcContext->mSecureMode = true;
-    if(mHwcContext->proc)
-        mHwcContext->proc->invalidate(mHwcContext->proc);
+        ctx->mSecureMode = true;
+    if(ctx->proc)
+        ctx->proc->invalidate(ctx->proc);
 }
 
-void QClient::unsecuring(uint32_t startEnd) {
-    Locker::Autolock _sl(mHwcContext->mDrawLock);
-    mHwcContext->mSecuring = startEnd;
+static void unsecuring(hwc_context_t *ctx, uint32_t startEnd) {
+    Locker::Autolock _sl(ctx->mDrawLock);
+    ctx->mSecuring = startEnd;
     //We're done unsecuring
     if(startEnd == IQService::END)
-        mHwcContext->mSecureMode = false;
-    if(mHwcContext->proc)
-        mHwcContext->proc->invalidate(mHwcContext->proc);
+        ctx->mSecureMode = false;
+    if(ctx->proc)
+        ctx->proc->invalidate(ctx->proc);
 }
 
 void QClient::MPDeathNotifier::died() {
@@ -113,33 +84,68 @@
         mHwcContext->proc->invalidate(mHwcContext->proc);
 }
 
-android::status_t QClient::screenRefresh() {
+static android::status_t screenRefresh(hwc_context_t *ctx) {
     status_t result = NO_INIT;
 #ifdef QCOM_BSP
-    if(mHwcContext->proc) {
-        mHwcContext->proc->invalidate(mHwcContext->proc);
+    if(ctx->proc) {
+        ctx->proc->invalidate(ctx->proc);
         result = NO_ERROR;
     }
 #endif
     return result;
 }
 
-android::status_t QClient::vpuCommand(uint32_t command, uint32_t setting) {
+static android::status_t vpuCommand(hwc_context_t *ctx,
+        uint32_t command,
+        const Parcel* inParcel,
+        Parcel* outParcel) {
     status_t result = NO_INIT;
 #ifdef QCOM_BSP
 #ifdef VPU_TARGET
-    result = mHwcContext->mVPUClient->processCommand(command, setting);
+    result = ctx->mVPUClient->processCommand(command, inParcel, outParcel);
 #endif
 #endif
     return result;
 }
 
-void QClient::setExtOrientation(uint32_t orientation) {
-    mHwcContext->mExtOrientation = orientation;
+static void setExtOrientation(hwc_context_t *ctx, uint32_t orientation) {
+    ctx->mExtOrientation = orientation;
 }
 
-void QClient::setBufferMirrorMode(uint32_t enable) {
-    mHwcContext->mBufferMirrorMode = enable;
+static void setBufferMirrorMode(hwc_context_t *ctx, uint32_t enable) {
+    ctx->mBufferMirrorMode = enable;
 }
 
+status_t QClient::notifyCallback(uint32_t command, const Parcel* inParcel,
+        Parcel* outParcel) {
+
+    if (command > IQService::VPU_COMMAND_LIST_START &&
+        command < IQService::VPU_COMMAND_LIST_END) {
+        return vpuCommand(mHwcContext, command, inParcel, outParcel);
+    }
+
+    switch(command) {
+        case IQService::SECURING:
+            securing(mHwcContext, inParcel->readInt32());
+            break;
+        case IQService::UNSECURING:
+            unsecuring(mHwcContext, inParcel->readInt32());
+            break;
+        case IQService::SCREEN_REFRESH:
+            return screenRefresh(mHwcContext);
+            break;
+        case IQService::EXTERNAL_ORIENTATION:
+            setExtOrientation(mHwcContext, inParcel->readInt32());
+            break;
+        case IQService::BUFFER_MIRRORMODE:
+            setBufferMirrorMode(mHwcContext, inParcel->readInt32());
+            break;
+        default:
+            return NO_ERROR;
+    }
+    return NO_ERROR;
+}
+
+
+
 }
diff --git a/libhwcomposer/hwc_qclient.h b/libhwcomposer/hwc_qclient.h
index fa1d6b0..d955377 100644
--- a/libhwcomposer/hwc_qclient.h
+++ b/libhwcomposer/hwc_qclient.h
@@ -39,6 +39,7 @@
 
 struct hwc_context_t;
 
+class Params;
 namespace qClient {
 // ----------------------------------------------------------------------------
 
@@ -46,7 +47,9 @@
 public:
     QClient(hwc_context_t *ctx);
     virtual ~QClient();
-    virtual android::status_t notifyCallback(uint32_t msg, uint32_t value);
+    virtual android::status_t notifyCallback(uint32_t command,
+            const android::Parcel* inParcel,
+            android::Parcel* outParcel);
 
 private:
     //Notifies of Media Player death
@@ -57,13 +60,6 @@
         hwc_context_t *mHwcContext;
     };
 
-    void securing(uint32_t startEnd);
-    void unsecuring(uint32_t startEnd);
-    android::status_t screenRefresh();
-    void setExtOrientation(uint32_t orientation);
-    void setBufferMirrorMode(uint32_t enable);
-    android::status_t vpuCommand(uint32_t command, uint32_t setting);
-
     hwc_context_t *mHwcContext;
     const android::sp<android::IMediaDeathNotifier> mMPDeathNotifier;
 };
diff --git a/libhwcomposer/hwc_utils.cpp b/libhwcomposer/hwc_utils.cpp
index 1a66451..1167f3a 100644
--- a/libhwcomposer/hwc_utils.cpp
+++ b/libhwcomposer/hwc_utils.cpp
@@ -1374,6 +1374,42 @@
     return 0;
 }
 
+int configColorLayer(hwc_context_t *ctx, hwc_layer_1_t *layer,
+        const int& dpy, eMdpFlags& mdpFlags, eZorder& z,
+        eIsFg& isFg, const eDest& dest) {
+
+    hwc_rect_t dst = layer->displayFrame;
+    trimLayer(ctx, dpy, 0, dst, dst);
+
+    int w = ctx->dpyAttr[dpy].xres;
+    int h = ctx->dpyAttr[dpy].yres;
+    int dst_w = dst.right - dst.left;
+    int dst_h = dst.bottom - dst.top;
+    uint32_t color = layer->transform;
+    Whf whf(w, h, getMdpFormat(HAL_PIXEL_FORMAT_RGBA_8888), 0);
+
+    if (layer->blending == HWC_BLENDING_PREMULT)
+        ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_BLEND_FG_PREMULT);
+
+    PipeArgs parg(mdpFlags, whf, z, isFg, static_cast<eRotFlags>(0),
+                  layer->planeAlpha,
+                  (ovutils::eBlending) getBlending(layer->blending));
+
+    // Configure MDP pipe for Color layer
+    Dim pos(dst.left, dst.top, dst_w, dst_h);
+    ctx->mOverlay->setSource(parg, dest);
+    ctx->mOverlay->setColor(color, dest);
+    ctx->mOverlay->setTransform(0, dest);
+    ctx->mOverlay->setCrop(pos, dest);
+    ctx->mOverlay->setPosition(pos, dest);
+
+    if (!ctx->mOverlay->commit(dest)) {
+        ALOGE("%s: Configure color layer failed!", __FUNCTION__);
+        return -1;
+    }
+    return 0;
+}
+
 void updateSource(eTransform& orient, Whf& whf,
         hwc_rect_t& crop) {
     Dim srcCrop(crop.left, crop.top,
@@ -1404,7 +1440,12 @@
         eIsFg& isFg, const eDest& dest, Rotator **rot) {
 
     private_handle_t *hnd = (private_handle_t *)layer->handle;
+
     if(!hnd) {
+        if (layer->flags & HWC_COLOR_FILL) {
+            // Configure Color layer
+            return configColorLayer(ctx, layer, dpy, mdpFlags, z, isFg, dest);
+        }
         ALOGE("%s: layer handle is NULL", __FUNCTION__);
         return -1;
     }
diff --git a/libhwcomposer/hwc_utils.h b/libhwcomposer/hwc_utils.h
index 12998cf..29b38fc 100644
--- a/libhwcomposer/hwc_utils.h
+++ b/libhwcomposer/hwc_utils.h
@@ -270,6 +270,10 @@
         const hwc_rect_t& pos, const MetaData_t *metadata,
         const ovutils::eDest& dest);
 
+int configColorLayer(hwc_context_t *ctx, hwc_layer_1_t *layer, const int& dpy,
+        ovutils::eMdpFlags& mdpFlags, ovutils::eZorder& z,
+        ovutils::eIsFg& isFg, const ovutils::eDest& dest);
+
 void updateSource(ovutils::eTransform& orient, ovutils::Whf& whf,
         hwc_rect_t& crop);
 
@@ -474,7 +478,8 @@
 }
 
 static inline bool has90Transform(hwc_layer_1_t *layer) {
-    return (layer->transform & HWC_TRANSFORM_ROT_90);
+    return ((layer->transform & HWC_TRANSFORM_ROT_90) &&
+            !(layer->flags & HWC_COLOR_FILL));
 }
 
 inline bool isSecurePresent(hwc_context_t *ctx, int dpy) {
diff --git a/libhwcomposer/hwc_vpuclient.cpp b/libhwcomposer/hwc_vpuclient.cpp
index bdfeae5..23c6841 100644
--- a/libhwcomposer/hwc_vpuclient.cpp
+++ b/libhwcomposer/hwc_vpuclient.cpp
@@ -31,9 +31,11 @@
 #include "hwc_vpuclient.h"
 #include "hwc_utils.h"
 #include <vpu/vpu.h>
+#include <binder/Parcel.h>
 
 
 using namespace vpu;
+using namespace android;
 namespace qhwc {
 
 VPUClient::VPUClient()
@@ -78,11 +80,14 @@
     return err;
 }
 
-int VPUClient::processCommand(uint32_t command, uint32_t setting)
+int VPUClient::processCommand(uint32_t command,
+        const Parcel* inParcel, Parcel* outParcel)
 {
     if(!mVPU)
         return 0;
-    return mVPU->processCommand(command, setting);
+    //XXX: Enable when VPU enables it
+    //return mVPU->processCommand(command, inParcel, outParcel);
+    return 0;
 }
 
 }; // namespace qhwc
diff --git a/libhwcomposer/hwc_vpuclient.h b/libhwcomposer/hwc_vpuclient.h
index 8cc7137..9985517 100644
--- a/libhwcomposer/hwc_vpuclient.h
+++ b/libhwcomposer/hwc_vpuclient.h
@@ -39,6 +39,9 @@
 namespace vpu {
 class VPU;
 };
+namespace android {
+class Parcel;
+};
 
 namespace qhwc {
 
@@ -52,7 +55,8 @@
 
     int draw(hwc_context_t *ctx, hwc_display_contents_1_t* list);
 
-    int processCommand(uint32_t command, uint32_t setting);
+    int processCommand(uint32_t command,
+            const android::Parcel* inParcel, android::Parcel* outParcel);
 
 private:
     vpu::VPU *mVPU;
diff --git a/liboverlay/overlay.cpp b/liboverlay/overlay.cpp
index 9222af5..432ba81 100644
--- a/liboverlay/overlay.cpp
+++ b/liboverlay/overlay.cpp
@@ -80,7 +80,8 @@
 
 void Overlay::configDone() {
     for(int i = 0; i < PipeBook::NUM_PIPES; i++) {
-        if(PipeBook::isNotUsed(i)) {
+        if((PipeBook::isNotUsed(i) && !sessionInProgress((eDest)i)) ||
+                    isSessionEnded((eDest)i)) {
             //Forces UNSET on pipes, flushes rotator memory and session, closes
             //fds
             if(mPipeBook[i].valid()) {
@@ -106,6 +107,27 @@
 #endif
 }
 
+int Overlay::getPipeId(utils::eDest dest) {
+    return mPipeBook[(int)dest].mPipe->getPipeId();
+}
+
+eDest Overlay::getDest(int pipeid) {
+    eDest dest = OV_INVALID;
+    // finding the dest corresponding to the given pipe
+    for(int i=0; i < PipeBook::NUM_PIPES; ++i) {
+        if(mPipeBook[i].valid() && mPipeBook[i].mPipe->getPipeId() == pipeid) {
+            return (eDest)i;
+        }
+    }
+    return dest;
+}
+
+eDest Overlay::reservePipe(int pipeid) {
+    eDest dest = getDest(pipeid);
+    PipeBook::setAllocation((int)dest);
+    return dest;
+}
+
 eDest Overlay::nextPipe(eMdpPipeType type, int dpy, int mixer) {
     eDest dest = OV_INVALID;
 
@@ -131,6 +153,7 @@
         mPipeBook[index].mMixer = mixer;
         if(not mPipeBook[index].valid()) {
             mPipeBook[index].mPipe = new GenericPipe(dpy);
+            mPipeBook[index].mSession = PipeBook::NONE;
             char str[32];
             snprintf(str, 32, "Set=%s dpy=%d mix=%d; ",
                      PipeBook::getDestStr(dest), dpy, mixer);
@@ -146,6 +169,13 @@
     return dest;
 }
 
+void Overlay::endAllSessions() {
+    for(int i = 0; i < PipeBook::NUM_PIPES; i++) {
+        if(mPipeBook[i].valid() && mPipeBook[i].mSession==PipeBook::START)
+            mPipeBook[i].mSession = PipeBook::END;
+    }
+}
+
 bool Overlay::isPipeTypeAttached(eMdpPipeType type) {
     for(int i = 0; i < PipeBook::NUM_PIPES; i++) {
         if(type == PipeBook::getPipeType((eDest)i) &&
@@ -200,6 +230,13 @@
     mPipeBook[index].mPipe->setCrop(d);
 }
 
+void Overlay::setColor(const uint32_t color,
+        utils::eDest dest) {
+    int index = (int)dest;
+    validate(index);
+    mPipeBook[index].mPipe->setColor(color);
+}
+
 void Overlay::setPosition(const utils::Dim& d,
         utils::eDest dest) {
     int index = (int)dest;
@@ -453,6 +490,7 @@
     }
     mDisplay = DPY_UNUSED;
     mMixer = MIXER_UNUSED;
+    mSession = NONE;
 }
 
 Overlay* Overlay::sInstance = 0;
diff --git a/liboverlay/overlay.h b/liboverlay/overlay.h
index 854fa30..e88c89c 100644
--- a/liboverlay/overlay.h
+++ b/liboverlay/overlay.h
@@ -76,15 +76,33 @@
      * asisgned to a mixer within a display it cannot be reused for another
      * mixer without being UNSET once*/
     utils::eDest nextPipe(utils::eMdpPipeType, int dpy, int mixer);
+    /* Returns the eDest corresponding to an already allocated pipeid.
+     * Useful for the reservation case, when libvpu reserves the pipe at its
+     * end, and expect the overlay to allocate a given pipe for a layer.
+     */
+    utils::eDest reservePipe(int pipeid);
+    /* getting dest for the given pipeid */
+    utils::eDest getDest(int pipeid);
+    /* getting overlay.pipeid for the given dest */
+    int getPipeId(utils::eDest dest);
 
     void setSource(const utils::PipeArgs args, utils::eDest dest);
     void setCrop(const utils::Dim& d, utils::eDest dest);
+    void setColor(const uint32_t color, utils::eDest dest);
     void setTransform(const int orientation, utils::eDest dest);
     void setPosition(const utils::Dim& dim, utils::eDest dest);
     void setVisualParams(const MetaData_t& data, utils::eDest dest);
     bool commit(utils::eDest dest);
     bool queueBuffer(int fd, uint32_t offset, utils::eDest dest);
 
+    /* pipe reservation session is running */
+    bool sessionInProgress(utils::eDest dest);
+    /* pipe reservation session has ended*/
+    bool isSessionEnded(utils::eDest dest);
+    /* start session for the pipe reservation */
+    void startSession(utils::eDest dest);
+    /* end all started sesisons */
+    void endAllSessions();
     /* Returns available ("unallocated") pipes for a display's mixer */
     int availablePipes(int dpy, int mixer);
     /* Returns available ("unallocated") pipes for a display */
@@ -160,7 +178,13 @@
 
         static int NUM_PIPES;
         static utils::eMdpPipeType pipeTypeLUT[utils::OV_MAX];
-
+        /* Session for reserved pipes */
+        enum Session {
+            NONE,
+            START,
+            END
+        };
+        Session mSession;
 
     private:
         //usage tracks if a successful commit happened. So a pipe could be
@@ -312,6 +336,18 @@
     return pipeTypeLUT[(int)dest];
 }
 
+inline void Overlay::startSession(utils::eDest dest) {
+    mPipeBook[(int)dest].mSession = PipeBook::START;
+}
+
+inline bool Overlay::sessionInProgress(utils::eDest dest) {
+    return (mPipeBook[(int)dest].mSession == PipeBook::START);
+}
+
+inline bool Overlay::isSessionEnded(utils::eDest dest) {
+    return (mPipeBook[(int)dest].mSession == PipeBook::END);
+}
+
 inline const char* Overlay::PipeBook::getDestStr(utils::eDest dest) {
     switch(getPipeType(dest)) {
         case utils::OV_MDP_PIPE_RGB: return "RGB";
diff --git a/liboverlay/overlayCtrlData.h b/liboverlay/overlayCtrlData.h
index 6746792..18ef5e6 100644
--- a/liboverlay/overlayCtrlData.h
+++ b/liboverlay/overlayCtrlData.h
@@ -61,6 +61,8 @@
     void setSource(const utils::PipeArgs& args);
     /* set crop info and pass it down to mdp */
     void setCrop(const utils::Dim& d);
+    /* set color for mdp pipe */
+    void setColor(const uint32_t color);
     /* set orientation */
     void setTransform(const utils::eTransform& p);
     /* set mdp position using dim */
@@ -174,6 +176,11 @@
     mMdp.setCrop(d);
 }
 
+inline void Ctrl::setColor(const uint32_t color)
+{
+    mMdp.setColor(color);
+}
+
 inline bool Ctrl::setVisualParams(const MetaData_t &metadata)
 {
     if (!mMdp.setVisualParams(metadata)) {
diff --git a/liboverlay/overlayMdp.cpp b/liboverlay/overlayMdp.cpp
index b4058bd..fbb173e 100644
--- a/liboverlay/overlayMdp.cpp
+++ b/liboverlay/overlayMdp.cpp
@@ -122,6 +122,10 @@
     setSrcRectDim(d);
 }
 
+void MdpCtrl::setColor(const uint32_t color) {
+    mOVInfo.bg_color = color;
+}
+
 void MdpCtrl::setPosition(const overlay::utils::Dim& d) {
     setDstRectDim(d);
 }
diff --git a/liboverlay/overlayMdp.h b/liboverlay/overlayMdp.h
index fe4ad69..6dd3976 100644
--- a/liboverlay/overlayMdp.h
+++ b/liboverlay/overlayMdp.h
@@ -57,6 +57,8 @@
      * Dim - ROI dimensions.
      */
     void setCrop(const utils::Dim& d);
+    /* set color for mdp pipe */
+    void setColor(const uint32_t color);
     void setTransform(const utils::eTransform& orient);
     /* given a dim and w/h, set overlay dim */
     void setPosition(const utils::Dim& dim);
diff --git a/liboverlay/pipes/overlayGenPipe.cpp b/liboverlay/pipes/overlayGenPipe.cpp
index 06e8257..c03378b 100644
--- a/liboverlay/pipes/overlayGenPipe.cpp
+++ b/liboverlay/pipes/overlayGenPipe.cpp
@@ -84,6 +84,10 @@
     mCtrlData.ctrl.setCrop(d);
 }
 
+void GenericPipe::setColor(const uint32_t color) {
+    mCtrlData.ctrl.setColor(color);
+}
+
 void GenericPipe::setTransform(const utils::eTransform& orient) {
     mCtrlData.ctrl.setTransform(orient);
 }
@@ -167,4 +171,8 @@
     mCtrlData.ctrl.forceSet();
 }
 
+int GenericPipe::getPipeId() {
+    return mCtrlData.ctrl.getPipeId();
+}
+
 } //namespace overlay
diff --git a/liboverlay/pipes/overlayGenPipe.h b/liboverlay/pipes/overlayGenPipe.h
index 2472f4e..5c963bc 100644
--- a/liboverlay/pipes/overlayGenPipe.h
+++ b/liboverlay/pipes/overlayGenPipe.h
@@ -48,6 +48,8 @@
     void setSource(const utils::PipeArgs& args);
     /* set crop a.k.a the region of interest */
     void setCrop(const utils::Dim& d);
+    /* set color for mdp pipe */
+    void setColor(const uint32_t color);
     /* set orientation*/
     void setTransform(const utils::eTransform& param);
     /* set mdp posision using dim */
@@ -77,6 +79,7 @@
      * even if they haven't changed
      */
     void forceSet();
+    int getPipeId();
 
 private:
     /* set Closed pipe */
diff --git a/libqdutils/mdp_version.cpp b/libqdutils/mdp_version.cpp
index 1850801..e12b319 100644
--- a/libqdutils/mdp_version.cpp
+++ b/libqdutils/mdp_version.cpp
@@ -27,9 +27,6 @@
  * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 #include <cutils/log.h>
-#include <fcntl.h>
-#include <sys/ioctl.h>
-#include <linux/fb.h>
 #include <linux/msm_mdp.h>
 #include "mdp_version.h"
 
@@ -42,81 +39,35 @@
 
 MDPVersion::MDPVersion()
 {
-    int fb_fd = open("/dev/graphics/fb0", O_RDWR);
-    char panel_type = 0;
-    struct fb_fix_screeninfo fb_finfo;
-
-    mMDPVersion = MDP_V_UNKNOWN;
+    mMDPVersion = MDSS_V5;
     mMdpRev = 0;
     mRGBPipes = 0;
     mVGPipes = 0;
     mDMAPipes = 0;
     mFeatures = 0;
     mMDPUpscale = 0;
-    //TODO get this from driver, default for A-fam to 8
-    mMDPDownscale = 8;
-    mFd = fb_fd;
+    mMDPDownscale = 0;
+    mPanelType = NO_PANEL;
+    mLowBw = 0;
+    mHighBw = 0;
 
-    if (ioctl(fb_fd, FBIOGET_FSCREENINFO, &fb_finfo) < 0) {
-        ALOGE("FBIOGET_FSCREENINFO failed");
-    } else {
-        if(!strncmp(fb_finfo.id, "msmfb", 5)) {
-            char str_ver[4] = { 0 };
-            memcpy(str_ver, &fb_finfo.id[5], 3);
-            str_ver[3] = '\0';
-            mMDPVersion = atoi(str_ver);
-            //Normalize MDP version to ease comparison.
-            //This is needed only because
-            //MDP 3.0.3 reports value as 303 which
-            //is more than all the others
-            if (mMDPVersion < 100)
-                mMDPVersion *= 10;
-
-            mRGBPipes = mVGPipes = 2;
-
-        } else if (!strncmp(fb_finfo.id, "mdssfb", 6)) {
-            mMDPVersion = MDSS_V5;
-            if(!updateSysFsInfo()) {
-                ALOGE("Unable to read updateSysFsInfo");
-            }
-            if (mMdpRev == MDP_V3_0_4){
-                mMDPVersion = MDP_V3_0_4;
-            }
-        }
-
-        /* Assumes panel type is 2nd element in '_' delimited id string */
-        char * ptype = strstr(fb_finfo.id, "_");
-        if (!ptype || (*(++ptype) == '\0')) {
-            ALOGE("Invalid framebuffer info string: %s", fb_finfo.id);
-            ptype = fb_finfo.id;
-        }
-        panel_type = *ptype;
+    if(!updatePanelInfo()) {
+        ALOGE("Unable to read Primary Panel Information");
     }
-    mPanelType = panel_type;
+    if(!updateSysFsInfo()) {
+        ALOGE("Unable to read display sysfs node");
+    }
+    if (mMdpRev == MDP_V3_0_4){
+        mMDPVersion = MDP_V3_0_4;
+    }
+
     mHasOverlay = false;
     if((mMDPVersion >= MDP_V4_0) ||
        (mMDPVersion == MDP_V_UNKNOWN) ||
        (mMDPVersion == MDP_V3_0_4))
         mHasOverlay = true;
-    if(mMDPVersion >= MDSS_V5) {
-        char split[64] = {0};
-        FILE* fp = fopen("/sys/class/graphics/fb0/msm_fb_split", "r");
-        if(fp){
-            //Format "left right" space as delimiter
-            if(fread(split, sizeof(char), 64, fp)) {
-                mSplit.mLeft = atoi(split);
-                ALOGI_IF(mSplit.mLeft, "Left Split=%d", mSplit.mLeft);
-                char *rght = strpbrk(split, " ");
-                if(rght)
-                    mSplit.mRight = atoi(rght + 1);
-                ALOGI_IF(rght, "Right Split=%d", mSplit.mRight);
-            }
-        } else {
-            ALOGE("Failed to open mdss_fb_split node");
-        }
-
-        if(fp)
-            fclose(fp);
+    if(!updateSplitInfo()) {
+        ALOGE("Unable to read display split node");
     }
 }
 
@@ -140,7 +91,39 @@
     *idx = index;
     return 0;
 }
+// This function reads the sysfs node to read the primary panel type
+// and updates information accordingly
+bool MDPVersion::updatePanelInfo() {
+    FILE *displayDeviceFP = NULL;
+    const int MAX_FRAME_BUFFER_NAME_SIZE = 128;
+    char fbType[MAX_FRAME_BUFFER_NAME_SIZE];
+    const char *strCmdPanel = "mipi dsi cmd panel";
+    const char *strVideoPanel = "mipi dsi video panel";
+    const char *strLVDSPanel = "lvds panel";
+    const char *strEDPPanel = "edp panel";
 
+    displayDeviceFP = fopen("/sys/class/graphics/fb0/msm_fb_type", "r");
+    if(displayDeviceFP){
+        fread(fbType, sizeof(char), MAX_FRAME_BUFFER_NAME_SIZE,
+                displayDeviceFP);
+        if(strncmp(fbType, strCmdPanel, strlen(strCmdPanel)) == 0) {
+            mPanelType = MIPI_CMD_PANEL;
+        }
+        else if(strncmp(fbType, strVideoPanel, strlen(strVideoPanel)) == 0) {
+            mPanelType = MIPI_VIDEO_PANEL;
+        }
+        else if(strncmp(fbType, strLVDSPanel, strlen(strLVDSPanel)) == 0) {
+            mPanelType = LVDS_PANEL;
+        }
+        else if(strncmp(fbType, strEDPPanel, strlen(strEDPPanel)) == 0) {
+            mPanelType = EDP_PANEL;
+        }
+        fclose(displayDeviceFP);
+        return true;
+    }else {
+        return false;
+    }
+}
 
 // This function reads the sysfs node to read MDP capabilities
 // and parses and updates information accordingly.
@@ -187,8 +170,13 @@
                 else if(!strncmp(tokens[0], "max_upscale_ratio",
                                 strlen("max_upscale_ratio"))) {
                     mMDPUpscale = atoi(tokens[1]);
-                }
-                else if(!strncmp(tokens[0], "features", strlen("features"))) {
+                } else if(!strncmp(tokens[0], "max_bandwidth_low",
+                        strlen("max_bandwidth_low"))) {
+                    mLowBw = atol(tokens[1]);
+                } else if(!strncmp(tokens[0], "max_bandwidth_high",
+                        strlen("max_bandwidth_high"))) {
+                    mHighBw = atol(tokens[1]);
+                } else if(!strncmp(tokens[0], "features", strlen("features"))) {
                     for(int i=1; i<index;i++) {
                         if(!strncmp(tokens[i], "bwc", strlen("bwc"))) {
                            mFeatures |= MDP_BWC_EN;
@@ -210,9 +198,39 @@
                     mRGBPipes, mVGPipes);
     ALOGD_IF(DEBUG, "%s:mDMAPipes:%d \t mMDPDownscale:%d, mFeatures:%d",
                      __FUNCTION__,  mDMAPipes, mMDPDownscale, mFeatures);
+    ALOGD_IF(DEBUG, "%s:mLowBw: %lu mHighBw: %lu", __FUNCTION__,  mLowBw,
+            mHighBw);
+
     return true;
 }
 
+// This function reads the sysfs node to read MDP capabilities
+// and parses and updates information accordingly.
+bool MDPVersion::updateSplitInfo() {
+    if(mMDPVersion >= MDSS_V5) {
+        char split[64] = {0};
+        FILE* fp = fopen("/sys/class/graphics/fb0/msm_fb_split", "r");
+        if(fp){
+            //Format "left right" space as delimiter
+            if(fread(split, sizeof(char), 64, fp)) {
+                mSplit.mLeft = atoi(split);
+                ALOGI_IF(mSplit.mLeft, "Left Split=%d", mSplit.mLeft);
+                char *rght = strpbrk(split, " ");
+                if(rght)
+                    mSplit.mRight = atoi(rght + 1);
+                ALOGI_IF(mSplit.mRight, "Right Split=%d", mSplit.mRight);
+            }
+        } else {
+            ALOGE("Failed to open mdss_fb_split node");
+            return false;
+        }
+        if(fp)
+            fclose(fp);
+    }
+    return true;
+}
+
+
 bool MDPVersion::supportsDecimation() {
     return mFeatures & MDP_DECIMATION_EN;
 }
diff --git a/libqdutils/mdp_version.h b/libqdutils/mdp_version.h
index b995582..fb7920e 100644
--- a/libqdutils/mdp_version.h
+++ b/libqdutils/mdp_version.h
@@ -38,6 +38,10 @@
 */
 using namespace android;
 namespace qdutils {
+// These panel definitions are available at mdss_mdp.h which is internal header
+// file and is not available at <linux/mdss_mdp.h>.
+// ToDo: once it is available at linux/mdss_mdp.h, these below definitions can
+// be removed.
 enum mdp_version {
     MDP_V_UNKNOWN = 0,
     MDP_V2_2    = 220,
@@ -65,6 +69,7 @@
     MAX_DISPLAY_DIM = 2048,
 };
 
+#define NO_PANEL         '0'
 #define MDDI_PANEL       '1'
 #define EBI2_PANEL       '2'
 #define LCDC_PANEL       '3'
@@ -75,6 +80,7 @@
 #define MIPI_CMD_PANEL   '9'
 #define WRITEBACK_PANEL  'a'
 #define LVDS_PANEL       'b'
+#define EDP_PANEL        'c'
 
 class MDPVersion;
 
@@ -107,8 +113,12 @@
     bool is8x92();
     int getLeftSplit() { return mSplit.left(); }
     int getRightSplit() { return mSplit.right(); }
+    unsigned long getLowBw() { return mLowBw; }
+    unsigned long getHighBw() { return mHighBw; }
 private:
     bool updateSysFsInfo();
+    bool updatePanelInfo();
+    bool updateSplitInfo();
     int tokenizeParams(char *inputParams, const char *delim,
                         char* tokenStr[], int *idx);
     int mFd;
@@ -123,6 +133,8 @@
     uint32_t mMDPDownscale;
     uint32_t mMDPUpscale;
     Split mSplit;
+    unsigned long mLowBw; //kbps
+    unsigned long mHighBw; //kbps
 };
 }; //namespace qdutils
 #endif //INCLUDE_LIBQCOMUTILS_MDPVER
diff --git a/libqservice/IQClient.cpp b/libqservice/IQClient.cpp
index 30fbb64..a6251c8 100644
--- a/libqservice/IQClient.cpp
+++ b/libqservice/IQClient.cpp
@@ -28,6 +28,9 @@
 using namespace android;
 
 // ---------------------------------------------------------------------------
+// XXX: Since qservice currently runs as part of hwc instead of a standalone
+// process, the implementation below is overridden and the notifyCallback in
+// hwc_qclient is directly called.
 
 namespace qClient {
 
@@ -41,13 +44,17 @@
     BpQClient(const sp<IBinder>& impl)
         : BpInterface<IQClient>(impl) {}
 
-    virtual status_t notifyCallback(uint32_t msg, uint32_t value) {
-        Parcel data, reply;
+    virtual status_t notifyCallback(uint32_t command,
+            const Parcel* inParcel,
+            Parcel* outParcel) {
+        Parcel data;
+        Parcel *reply = outParcel;
         data.writeInterfaceToken(IQClient::getInterfaceDescriptor());
-        data.writeInt32(msg);
-        data.writeInt32(value);
-        remote()->transact(NOTIFY_CALLBACK, data, &reply);
-        status_t result = reply.readInt32();
+        data.writeInt32(command);
+        if (inParcel->dataAvail())
+            data.appendFrom(inParcel, inParcel->dataPosition(),
+                    inParcel->dataAvail());
+        status_t result = remote()->transact(NOTIFY_CALLBACK, data, reply);
         return result;
     }
 };
@@ -55,21 +62,21 @@
 IMPLEMENT_META_INTERFACE(QClient, "android.display.IQClient");
 
 // ----------------------------------------------------------------------
-
+//Stub implementation - nothing needed here
 status_t BnQClient::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
     switch(code) {
         case NOTIFY_CALLBACK: {
             CHECK_INTERFACE(IQClient, data, reply);
-            uint32_t msg = data.readInt32();
-            uint32_t value = data.readInt32();
-            notifyCallback(msg, value);
+            uint32_t command = data.readInt32();
+            notifyCallback(command, &data, reply);
             return NO_ERROR;
         } break;
         default:
             return BBinder::onTransact(code, data, reply, flags);
     }
+
 }
 
 }; // namespace qClient
diff --git a/libqservice/IQClient.h b/libqservice/IQClient.h
index a28f826..7d816d2 100644
--- a/libqservice/IQClient.h
+++ b/libqservice/IQClient.h
@@ -33,7 +33,9 @@
 {
 public:
     DECLARE_META_INTERFACE(QClient);
-    virtual android::status_t notifyCallback(uint32_t msg, uint32_t value) = 0;
+    virtual android::status_t notifyCallback(uint32_t command,
+            const android::Parcel* inParcel,
+            android::Parcel* outParcel) = 0;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/libqservice/IQService.cpp b/libqservice/IQService.cpp
index 33f79c6..d2180bb 100644
--- a/libqservice/IQService.cpp
+++ b/libqservice/IQService.cpp
@@ -27,9 +27,10 @@
 #include <binder/IPCThreadState.h>
 #include <utils/Errors.h>
 #include <private/android_filesystem_config.h>
-
 #include <IQService.h>
 
+#define QSERVICE_DEBUG 0
+
 using namespace android;
 using namespace qClient;
 
@@ -43,56 +44,25 @@
     BpQService(const sp<IBinder>& impl)
         : BpInterface<IQService>(impl) {}
 
-    virtual void securing(uint32_t startEnd) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IQService::getInterfaceDescriptor());
-        data.writeInt32(startEnd);
-        remote()->transact(SECURING, data, &reply);
-    }
-
-    virtual void unsecuring(uint32_t startEnd) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IQService::getInterfaceDescriptor());
-        data.writeInt32(startEnd);
-        remote()->transact(UNSECURING, data, &reply);
-    }
-
     virtual void connect(const sp<IQClient>& client) {
+        ALOGD_IF(QSERVICE_DEBUG, "%s: connect client", __FUNCTION__);
         Parcel data, reply;
         data.writeInterfaceToken(IQService::getInterfaceDescriptor());
         data.writeStrongBinder(client->asBinder());
         remote()->transact(CONNECT, data, &reply);
     }
 
-    virtual status_t screenRefresh() {
-        Parcel data, reply;
+    virtual android::status_t dispatch(uint32_t command, const Parcel* inParcel,
+            Parcel* outParcel) {
+        ALOGD_IF(QSERVICE_DEBUG, "%s: dispatch in:%p", __FUNCTION__, inParcel);
+        status_t err = android::FAILED_TRANSACTION;
+        Parcel data;
+        Parcel *reply = outParcel;
         data.writeInterfaceToken(IQService::getInterfaceDescriptor());
-        remote()->transact(SCREEN_REFRESH, data, &reply);
-        status_t result = reply.readInt32();
-        return result;
-    }
-
-    virtual void setExtOrientation(uint32_t orientation) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IQService::getInterfaceDescriptor());
-        data.writeInt32(orientation);
-        remote()->transact(EXTERNAL_ORIENTATION, data, &reply);
-    }
-
-    virtual void setBufferMirrorMode(uint32_t enable) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IQService::getInterfaceDescriptor());
-        data.writeInt32(enable);
-        remote()->transact(BUFFER_MIRRORMODE, data, &reply);
-    }
-
-    virtual status_t vpuCommand(uint32_t command, uint32_t setting) {
-        Parcel data, reply;
-        data.writeInterfaceToken(IQService::getInterfaceDescriptor());
-        data.writeInt32(setting);
-        remote()->transact(command, data, &reply);
-        status_t result = reply.readInt32();
-        return result;
+        if (inParcel && inParcel->dataSize() > 0)
+            data.appendFrom(inParcel, 0, inParcel->dataSize());
+        err = remote()->transact(command, data, reply);
+        return err;
     }
 };
 
@@ -105,7 +75,8 @@
 status_t BnQService::onTransact(
     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
 {
-    // IPC should be from mediaserver only
+    ALOGD_IF(QSERVICE_DEBUG, "%s: code: %d", __FUNCTION__, code);
+    // IPC should be from certain processes only
     IPCThreadState* ipc = IPCThreadState::self();
     const int callerPid = ipc->getCallingPid();
     const int callerUid = ipc->getCallingUid();
@@ -114,94 +85,35 @@
 
     getProcName(callerPid, callingProcName, MAX_BUF_SIZE);
 
-    const bool permission = (callerUid == AID_MEDIA);
+    const bool permission = (callerUid == AID_MEDIA ||
+            callerUid == AID_GRAPHICS ||
+            callerUid == AID_ROOT ||
+            callerUid == AID_SYSTEM);
 
-    if (code > VPU_COMMAND_LIST_START && code < VPU_COMMAND_LIST_END) {
-        if(callerUid != AID_SYSTEM && callerUid != AID_ROOT) {
-            ALOGE("display.qservice VPU command access denied: \
-                  pid=%d uid=%d process=%s",callerPid,
+    if (code == CONNECT) {
+        CHECK_INTERFACE(IQService, data, reply);
+        if(callerUid != AID_GRAPHICS) {
+            ALOGE("display.qservice CONNECT access denied: \
+                    pid=%d uid=%d process=%s",
+                    callerPid, callerUid, callingProcName);
+            return PERMISSION_DENIED;
+        }
+        sp<IQClient> client =
+                interface_cast<IQClient>(data.readStrongBinder());
+        connect(client);
+        return NO_ERROR;
+    } else if (code > COMMAND_LIST_START && code < COMMAND_LIST_END) {
+        if(!permission) {
+            ALOGE("display.qservice access denied: command=%d\
+                  pid=%d uid=%d process=%s", code, callerPid,
                   callerUid, callingProcName);
             return PERMISSION_DENIED;
         }
         CHECK_INTERFACE(IQService, data, reply);
-        int32_t setting = data.readInt32();
-        return vpuCommand(code, setting);
-    }
-
-    switch(code) {
-        case SECURING: {
-            if(!permission) {
-                ALOGE("display.qservice SECURING access denied: \
-                      pid=%d uid=%d process=%s",
-                      callerPid, callerUid, callingProcName);
-                return PERMISSION_DENIED;
-            }
-            CHECK_INTERFACE(IQService, data, reply);
-            uint32_t startEnd = data.readInt32();
-            securing(startEnd);
-            return NO_ERROR;
-        } break;
-        case UNSECURING: {
-            if(!permission) {
-                ALOGE("display.qservice UNSECURING access denied: \
-                      pid=%d uid=%d process=%s",
-                      callerPid, callerUid, callingProcName);
-                return PERMISSION_DENIED;
-            }
-            CHECK_INTERFACE(IQService, data, reply);
-            uint32_t startEnd = data.readInt32();
-            unsecuring(startEnd);
-            return NO_ERROR;
-        } break;
-        case CONNECT: {
-            CHECK_INTERFACE(IQService, data, reply);
-            if(callerUid != AID_GRAPHICS) {
-                ALOGE("display.qservice CONNECT access denied: \
-                      pid=%d uid=%d process=%s",
-                      callerPid, callerUid, callingProcName);
-                return PERMISSION_DENIED;
-            }
-            sp<IQClient> client =
-                interface_cast<IQClient>(data.readStrongBinder());
-            connect(client);
-            return NO_ERROR;
-        } break;
-        case SCREEN_REFRESH: {
-            CHECK_INTERFACE(IQService, data, reply);
-            if(callerUid != AID_SYSTEM) {
-                ALOGE("display.qservice SCREEN_REFRESH access denied: \
-                      pid=%d uid=%d process=%s",callerPid,
-                      callerUid, callingProcName);
-                return PERMISSION_DENIED;
-            }
-            return screenRefresh();
-        } break;
-        case EXTERNAL_ORIENTATION: {
-            CHECK_INTERFACE(IQService, data, reply);
-            if(callerUid != AID_SYSTEM) {
-                ALOGE("display.qservice EXTERNAL_ORIENTATION access denied: \
-                      pid=%d uid=%d process=%s",callerPid,
-                      callerUid, callingProcName);
-                return PERMISSION_DENIED;
-            }
-            uint32_t orientation = data.readInt32();
-            setExtOrientation(orientation);
-            return NO_ERROR;
-        } break;
-        case BUFFER_MIRRORMODE: {
-            CHECK_INTERFACE(IQService, data, reply);
-            if(callerUid != AID_SYSTEM) {
-                ALOGE("display.qservice BUFFER_MIRRORMODE access denied: \
-                      pid=%d uid=%d process=%s",callerPid,
-                      callerUid, callingProcName);
-                return PERMISSION_DENIED;
-            }
-            uint32_t enable = data.readInt32();
-            setBufferMirrorMode(enable);
-            return NO_ERROR;
-        } break;
-        default:
-            return BBinder::onTransact(code, data, reply, flags);
+        dispatch(code, &data, reply);
+        return NO_ERROR;
+    } else {
+        return BBinder::onTransact(code, data, reply, flags);
     }
 }
 
diff --git a/libqservice/IQService.h b/libqservice/IQService.h
index 9cd122e..7ad443d 100644
--- a/libqservice/IQService.h
+++ b/libqservice/IQService.h
@@ -29,35 +29,39 @@
 #include <binder/IBinder.h>
 #include <IQClient.h>
 
+
 namespace qService {
 // ----------------------------------------------------------------------------
+
 class IQService : public android::IInterface
 {
 public:
     DECLARE_META_INTERFACE(QService);
     enum {
-        // Hardware securing start/end notification
-        SECURING = android::IBinder::FIRST_CALL_TRANSACTION,
-        UNSECURING, // Hardware unsecuring start/end notification
-        CONNECT,
-        SCREEN_REFRESH,
-        EXTERNAL_ORIENTATION,
-        BUFFER_MIRRORMODE,
-        //VPU command codes - list is defined in vpu.h
-        VPU_COMMAND_LIST_START = 100,
-        VPU_COMMAND_LIST_END = 200,
+        COMMAND_LIST_START = android::IBinder::FIRST_CALL_TRANSACTION,
+        SECURING,                // Hardware securing start/end notification
+        UNSECURING,              // Hardware unsecuring start/end notification
+        CONNECT,                 // Connect to qservice
+        SCREEN_REFRESH,          // Refresh screen through SF invalidate
+        EXTERNAL_ORIENTATION,    // Set external orientation
+        BUFFER_MIRRORMODE,       // Buffer mirrormode
+        VPU_COMMAND_LIST_START = 100, //Reserved block for VPU commands
+        VPU_COMMAND_LIST_END   = 200,
+        COMMAND_LIST_END = 400,
     };
+
     enum {
         END = 0,
         START,
     };
-    virtual void securing(uint32_t startEnd) = 0;
-    virtual void unsecuring(uint32_t startEnd) = 0;
+
+    // Register a client that can be notified
     virtual void connect(const android::sp<qClient::IQClient>& client) = 0;
-    virtual android::status_t screenRefresh() = 0;
-    virtual void setExtOrientation(uint32_t orientation) = 0;
-    virtual void setBufferMirrorMode(uint32_t enable) = 0;
-    virtual android::status_t vpuCommand(uint32_t command, uint32_t setting) = 0;
+    // Generic function to dispatch binder commands
+    // The type of command decides how the data is parceled
+    virtual android::status_t dispatch(uint32_t command,
+            const android::Parcel* inParcel,
+            android::Parcel* outParcel) = 0;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/libqservice/QService.cpp b/libqservice/QService.cpp
index 327888c..aac5788 100644
--- a/libqservice/QService.cpp
+++ b/libqservice/QService.cpp
@@ -47,49 +47,19 @@
     ALOGD_IF(QSERVICE_DEBUG,"QService Destructor invoked");
 }
 
-void QService::securing(uint32_t startEnd) {
-    if(mClient.get()) {
-        mClient->notifyCallback(SECURING, startEnd);
-    }
-}
-
-void QService::unsecuring(uint32_t startEnd) {
-    if(mClient.get()) {
-        mClient->notifyCallback(UNSECURING, startEnd);
-    }
-}
-
 void QService::connect(const sp<qClient::IQClient>& client) {
+    ALOGD_IF(QSERVICE_DEBUG,"client connected");
     mClient = client;
 }
 
-android::status_t QService::screenRefresh() {
-    status_t result = NO_ERROR;
-    if(mClient.get()) {
-        result = mClient->notifyCallback(SCREEN_REFRESH, 0);
+status_t QService::dispatch(uint32_t command, const Parcel* inParcel,
+        Parcel* outParcel) {
+    status_t err = FAILED_TRANSACTION;
+    if (mClient.get()) {
+        ALOGD_IF(QSERVICE_DEBUG, "Dispatching command: %d", command);
+        err = mClient->notifyCallback(command, inParcel, outParcel);
     }
-    return result;
-}
-
-android::status_t QService::vpuCommand(uint32_t command, uint32_t setting ) {
-    status_t result = NO_ERROR;
-    if(mClient.get()) {
-        result = mClient->notifyCallback(command, setting);
-    }
-    return result;
-}
-
-
-void QService::setExtOrientation(uint32_t orientation) {
-    if(mClient.get()) {
-        mClient->notifyCallback(EXTERNAL_ORIENTATION, orientation);
-    }
-}
-
-void QService::setBufferMirrorMode(uint32_t enable) {
-    if(mClient.get()) {
-        mClient->notifyCallback(BUFFER_MIRRORMODE, enable);
-    }
+    return err;
 }
 
 void QService::init()
diff --git a/libqservice/QService.h b/libqservice/QService.h
index de18b59..a8e4cdb 100644
--- a/libqservice/QService.h
+++ b/libqservice/QService.h
@@ -45,13 +45,10 @@
 class QService : public BnQService {
 public:
     virtual ~QService();
-    virtual void securing(uint32_t startEnd);
-    virtual void unsecuring(uint32_t startEnd);
     virtual void connect(const android::sp<qClient::IQClient>& client);
-    virtual android::status_t screenRefresh();
-    virtual void setExtOrientation(uint32_t orientation);
-    virtual void setBufferMirrorMode(uint32_t enable);
-    virtual android::status_t vpuCommand(uint32_t command, uint32_t setting);
+    virtual android::status_t dispatch(uint32_t command,
+            const android::Parcel* data,
+            android::Parcel* reply);
     static void init();
 private:
     QService();
diff --git a/libqservice/QServiceUtils.h b/libqservice/QServiceUtils.h
new file mode 100644
index 0000000..3d1adc0
--- /dev/null
+++ b/libqservice/QServiceUtils.h
@@ -0,0 +1,86 @@
+/*
+* Copyright (c) 2013 The Linux Foundation. All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are
+* met:
+*    * Redistributions of source code must retain the above copyright
+*      notice, this list of conditions and the following disclaimer.
+*    * Redistributions in binary form must reproduce the above
+*      copyright notice, this list of conditions and the following
+*      disclaimer in the documentation and/or other materials provided
+*      with the distribution.
+*    * Neither the name of The Linux Foundation. nor the names of its
+*      contributors may be used to endorse or promote products derived
+*      from this software without specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
+* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
+* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
+* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
+* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef QSERVICEUTILS_H
+#define QSERVICEUTILS_H
+#include <binder/Parcel.h>
+#include <binder/IServiceManager.h>
+#include <utils/RefBase.h>
+#include <IQService.h>
+
+// ----------------------------------------------------------------------------
+// Helpers
+// ----------------------------------------------------------------------------
+inline android::sp<qService::IQService> getBinder() {
+    android::sp<android::IServiceManager> sm = android::defaultServiceManager();
+    android::sp<qService::IQService> binder =
+            android::interface_cast<qService::IQService>
+            (sm->getService(android::String16("display.qservice")));
+    if (binder == NULL) {
+        ALOGE("%s: invalid binder object", __FUNCTION__);
+    }
+    return binder;
+}
+
+inline android::status_t sendSingleParam(uint32_t command, uint32_t value) {
+    android::status_t err = android::FAILED_TRANSACTION;
+    android::sp<qService::IQService> binder = getBinder();
+    android::Parcel inParcel, outParcel;
+    inParcel.writeInt32(value);
+    if(binder != NULL) {
+        err = binder->dispatch(command, &inParcel , &outParcel);
+    }
+    return err;
+}
+
+// ----------------------------------------------------------------------------
+// Convenience wrappers that clients can call
+// ----------------------------------------------------------------------------
+inline android::status_t securing(uint32_t startEnd) {
+    return sendSingleParam(qService::IQService::SECURING, startEnd);
+}
+
+inline android::status_t unsecuring(uint32_t startEnd) {
+    return sendSingleParam(qService::IQService::UNSECURING, startEnd);
+}
+
+inline android::status_t screenRefresh() {
+    return sendSingleParam(qService::IQService::SCREEN_REFRESH, 1);
+}
+
+inline android::status_t setExtOrientation(uint32_t orientation) {
+    return sendSingleParam(qService::IQService::EXTERNAL_ORIENTATION,
+            orientation);
+}
+
+inline android::status_t setBufferMirrorMode(uint32_t enable) {
+    return sendSingleParam(qService::IQService::BUFFER_MIRRORMODE, enable);
+}
+
+#endif /* end of include guard: QSERVICEUTILS_H */