Merge "display: set compiler option to print all warning messages"
diff --git a/common.mk b/common.mk
index da38ded..d8ea260 100644
--- a/common.mk
+++ b/common.mk
@@ -18,10 +18,6 @@
 #Common libraries external to display HAL
 common_libs := liblog libutils libcutils libhardware
 
-ifeq ($(TARGET_USES_POST_PROCESSING),true)
-    common_libs += libmm-abl
-endif
-
 #Common C flags
 common_flags := -DDEBUG_CALC_FPS -Wno-missing-field-initializers
 #TODO: Add -Werror back once all the current warnings are fixed
diff --git a/libexternal/external.cpp b/libexternal/external.cpp
index e6395fb..1268b0f 100644
--- a/libexternal/external.cpp
+++ b/libexternal/external.cpp
@@ -175,6 +175,7 @@
     int len = -1;
     char scanInfo[17];
     char *ce_info_str = NULL;
+    char *save_ptr;
     const char token[] = ", \n";
     int ce_info = -1;
     char sysFsScanInfoFilePath[MAX_SYSFS_FILE_PATH];
@@ -210,13 +211,13 @@
      */
 
     /* PT */
-    ce_info_str = strtok(scanInfo, token);
+    ce_info_str = strtok_r(scanInfo, token, &save_ptr);
     if (ce_info_str) {
         /* IT */
-        ce_info_str = strtok(NULL, token);
+        ce_info_str = strtok_r(NULL, token, &save_ptr);
         if (ce_info_str) {
             /* CE */
-            ce_info_str = strtok(NULL, token);
+            ce_info_str = strtok_r(NULL, token, &save_ptr);
             if (ce_info_str)
                 ce_info = atoi(ce_info_str);
         }
diff --git a/libgralloc/alloc_controller.cpp b/libgralloc/alloc_controller.cpp
index 42f3c77..88b9b00 100644
--- a/libgralloc/alloc_controller.cpp
+++ b/libgralloc/alloc_controller.cpp
@@ -393,6 +393,7 @@
             case  HAL_PIXEL_FORMAT_RGBA_8888:
             case  HAL_PIXEL_FORMAT_RGBX_8888:
             case  HAL_PIXEL_FORMAT_BGRA_8888:
+            case  HAL_PIXEL_FORMAT_RGB_565:
                 {
                     tileEnabled = true;
                     // check the usage flags
@@ -566,9 +567,7 @@
             tileEnabled,
             alignedw,
             alignedh);
-
-    if(size)
-        size = getSize(format, width, height, alignedw, alignedh);
+    size = getSize(format, width, height, alignedw, alignedh);
 }
 
 
diff --git a/libgralloc/framebuffer.cpp b/libgralloc/framebuffer.cpp
index 3109303..a7a58dc 100644
--- a/libgralloc/framebuffer.cpp
+++ b/libgralloc/framebuffer.cpp
@@ -134,12 +134,16 @@
     memset(&module->commit, 0, sizeof(struct mdp_display_commit));
 
     struct fb_fix_screeninfo finfo;
-    if (ioctl(fd, FBIOGET_FSCREENINFO, &finfo) == -1)
+    if (ioctl(fd, FBIOGET_FSCREENINFO, &finfo) == -1) {
+        close(fd);
         return -errno;
+    }
 
     struct fb_var_screeninfo info;
-    if (ioctl(fd, FBIOGET_VSCREENINFO, &info) == -1)
+    if (ioctl(fd, FBIOGET_VSCREENINFO, &info) == -1) {
+        close(fd);
         return -errno;
+    }
 
     info.reserved[0] = 0;
     info.reserved[1] = 0;
@@ -232,8 +236,10 @@
               info.yres_virtual, info.yres*2);
     }
 
-    if (ioctl(fd, FBIOGET_VSCREENINFO, &info) == -1)
+    if (ioctl(fd, FBIOGET_VSCREENINFO, &info) == -1) {
+        close(fd);
         return -errno;
+    }
 
     if (int(info.width) <= 0 || int(info.height) <= 0) {
         // the driver doesn't return that information
@@ -250,6 +256,7 @@
     metadata.op = metadata_op_frame_rate;
     if (ioctl(fd, MSMFB_METADATA_GET, &metadata) == -1) {
         ALOGE("Error retrieving panel frame rate");
+        close(fd);
         return -errno;
     }
     float fps  = metadata.data.panel_frame_rate;
@@ -289,11 +296,15 @@
          );
 
 
-    if (ioctl(fd, FBIOGET_FSCREENINFO, &finfo) == -1)
+    if (ioctl(fd, FBIOGET_FSCREENINFO, &finfo) == -1) {
+        close(fd);
         return -errno;
+    }
 
-    if (finfo.smem_len <= 0)
+    if (finfo.smem_len <= 0) {
+        close(fd);
         return -errno;
+    }
 
     module->flags = flags;
     module->info = info;
@@ -322,6 +333,7 @@
     void* vaddr = mmap(0, fbSize, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
     if (vaddr == MAP_FAILED) {
         ALOGE("Error mapping the framebuffer (%s)", strerror(errno));
+        close(fd);
         return -errno;
     }
     module->framebuffer->base = intptr_t(vaddr);
@@ -373,6 +385,10 @@
 
         /* initialize our state here */
         fb_context_t *dev = (fb_context_t*)malloc(sizeof(*dev));
+        if(dev == NULL) {
+            gralloc_close(gralloc_device);
+            return status;
+        }
         memset(dev, 0, sizeof(*dev));
 
         /* initialize the procs */
diff --git a/libhwcomposer/hwc.cpp b/libhwcomposer/hwc.cpp
index db456bc..f1c54f2 100644
--- a/libhwcomposer/hwc.cpp
+++ b/libhwcomposer/hwc.cpp
@@ -484,9 +484,6 @@
     case HWC_COLOR_FILL:
         value[0] = 1;
         break;
-    case HWC_MAX_WRITEBACK_WIDTH:
-        value[0] = qdutils::MAX_DISPLAY_DIM;
-        break;
     default:
         return -EINVAL;
     }
@@ -777,6 +774,8 @@
     if (!strcmp(name, HWC_HARDWARE_COMPOSER)) {
         struct hwc_context_t *dev;
         dev = (hwc_context_t*)malloc(sizeof(*dev));
+        if(dev == NULL)
+            return status;
         memset(dev, 0, sizeof(*dev));
 
         //Initialize hwc context
diff --git a/libhwcomposer/hwc_copybit.cpp b/libhwcomposer/hwc_copybit.cpp
index 8c83469..d47853a 100644
--- a/libhwcomposer/hwc_copybit.cpp
+++ b/libhwcomposer/hwc_copybit.cpp
@@ -517,7 +517,7 @@
                src.format != HAL_PIXEL_FORMAT_RGBA_8888) {
            format = HAL_PIXEL_FORMAT_RGBX_8888;
        }
-       if (0 == alloc_buffer(&tmpHnd, tmp_w, tmp_h, format, usage)){
+       if (0 == alloc_buffer(&tmpHnd, tmp_w, tmp_h, format, usage) && tmpHnd) {
             copybit_image_t tmp_dst;
             copybit_rect_t tmp_rect;
             tmp_dst.w = tmp_w;
diff --git a/libhwcomposer/hwc_dump_layers.cpp b/libhwcomposer/hwc_dump_layers.cpp
index 6df8ce3..bebcc18 100644
--- a/libhwcomposer/hwc_dump_layers.cpp
+++ b/libhwcomposer/hwc_dump_layers.cpp
@@ -61,11 +61,12 @@
   mDpy(dpy) {
     char dumpPropStr[PROPERTY_VALUE_MAX];
     if(mDpy) {
-        strncpy(mDisplayName, "external", strlen("external"));
+        strlcpy(mDisplayName, "external", sizeof(mDisplayName));
     } else {
-        strncpy(mDisplayName, "primary", strlen("primary"));
+        strlcpy(mDisplayName, "primary", sizeof(mDisplayName));
     }
-    sprintf(mDumpPropKeyDisplayType, "debug.sf.dump.%s", (char *)mDisplayName);
+    snprintf(mDumpPropKeyDisplayType, sizeof(mDumpPropKeyDisplayType),
+             "debug.sf.dump.%s", (char *)mDisplayName);
 
     if ((property_get("debug.sf.dump.enable", dumpPropStr, NULL) > 0)) {
         if(!strncmp(dumpPropStr, "true", strlen("true"))) {
@@ -113,7 +114,7 @@
     if ((property_get("debug.sf.dump.png", dumpPropStr, NULL) > 0) &&
             (strncmp(dumpPropStr, mDumpPropStrPng, PROPERTY_VALUE_MAX - 1))) {
         // Strings exist & not equal implies it has changed, so trigger a dump
-        strncpy(mDumpPropStrPng, dumpPropStr, PROPERTY_VALUE_MAX - 1);
+        strlcpy(mDumpPropStrPng, dumpPropStr, sizeof(mDumpPropStrPng));
         mDumpCntLimPng = atoi(dumpPropStr);
         if (mDumpCntLimPng > MAX_ALLOWED_FRAMEDUMPS) {
             ALOGW("Warning: Using debug.sf.dump.png %d (= max)",
@@ -122,7 +123,7 @@
         }
         mDumpCntLimPng = (mDumpCntLimPng < 0) ? 0: mDumpCntLimPng;
         if (mDumpCntLimPng) {
-            sprintf(mDumpDirPng,
+            snprintf(mDumpDirPng, sizeof(mDumpDirPng),
                     "/data/sfdump.png.%04d.%02d.%02d.%02d.%02d.%02d",
                     dumpTime.tm_year + 1900, dumpTime.tm_mon + 1,
                     dumpTime.tm_mday, dumpTime.tm_hour,
@@ -143,7 +144,7 @@
     if ((property_get("debug.sf.dump", dumpPropStr, NULL) > 0) &&
             (strncmp(dumpPropStr, mDumpPropStrRaw, PROPERTY_VALUE_MAX - 1))) {
         // Strings exist & not equal implies it has changed, so trigger a dump
-        strncpy(mDumpPropStrRaw, dumpPropStr, PROPERTY_VALUE_MAX - 1);
+        strlcpy(mDumpPropStrRaw, dumpPropStr, sizeof(mDumpPropStrRaw));
         mDumpCntLimRaw = atoi(dumpPropStr);
         if (mDumpCntLimRaw > MAX_ALLOWED_FRAMEDUMPS) {
             ALOGW("Warning: Using debug.sf.dump %d (= max)",
@@ -152,7 +153,7 @@
         }
         mDumpCntLimRaw = (mDumpCntLimRaw < 0) ? 0: mDumpCntLimRaw;
         if (mDumpCntLimRaw) {
-            sprintf(mDumpDirRaw,
+            snprintf(mDumpDirRaw, sizeof(mDumpDirRaw),
                     "/data/sfdump.raw.%04d.%02d.%02d.%02d.%02d.%02d",
                     dumpTime.tm_year + 1900, dumpTime.tm_mon + 1,
                     dumpTime.tm_mday, dumpTime.tm_hour,
@@ -277,11 +278,13 @@
     bool needDumpRaw = (mDumpCntrRaw <= mDumpCntLimRaw)? true:false;
 
     if (needDumpPng) {
-        sprintf(dumpLogStrPng, "[png-dump-frame: %03d of %03d]", mDumpCntrPng,
+        snprintf(dumpLogStrPng, sizeof(dumpLogStrPng),
+            "[png-dump-frame: %03d of %03d]", mDumpCntrPng,
             mDumpCntLimPng);
     }
     if (needDumpRaw) {
-        sprintf(dumpLogStrRaw, "[raw-dump-frame: %03d of %03d]", mDumpCntrRaw,
+        snprintf(dumpLogStrRaw, sizeof(dumpLogStrRaw),
+            "[raw-dump-frame: %03d of %03d]", mDumpCntrRaw,
             mDumpCntLimRaw);
     }
 
@@ -311,7 +314,8 @@
         char dumpFilename[PATH_MAX];
         SkBitmap *tempSkBmp = new SkBitmap();
         SkBitmap::Config tempSkBmpConfig = SkBitmap::kNo_Config;
-        sprintf(dumpFilename, "%s/sfdump%03d.layer%zu.%s.png", mDumpDirPng,
+        snprintf(dumpFilename, sizeof(dumpFilename),
+            "%s/sfdump%03d.layer%d.%s.png", mDumpDirPng,
             mDumpCntrPng, layerIndex, mDisplayName);
 
         switch (hnd->format) {
@@ -347,7 +351,8 @@
     if (needDumpRaw && hnd->base) {
         char dumpFilename[PATH_MAX];
         bool bResult = false;
-        sprintf(dumpFilename, "%s/sfdump%03d.layer%zu.%dx%d.%s.%s.raw",
+        snprintf(dumpFilename, sizeof(dumpFilename),
+            "%s/sfdump%03d.layer%d.%dx%d.%s.%s.raw",
             mDumpDirRaw, mDumpCntrRaw,
             layerIndex, getWidth(hnd), getHeight(hnd),
             pixFormatStr, mDisplayName);
@@ -369,65 +374,65 @@
 
     switch(format) {
         case HAL_PIXEL_FORMAT_RGBA_8888:
-            strcpy(pixFormatStr, "RGBA_8888");
+            strlcpy(pixFormatStr, "RGBA_8888", sizeof(pixFormatStr));
             break;
         case HAL_PIXEL_FORMAT_RGBX_8888:
-            strcpy(pixFormatStr, "RGBX_8888");
+            strlcpy(pixFormatStr, "RGBX_8888", sizeof(pixFormatStr));
             break;
         case HAL_PIXEL_FORMAT_RGB_888:
-            strcpy(pixFormatStr, "RGB_888");
+            strlcpy(pixFormatStr, "RGB_888", sizeof(pixFormatStr));
             break;
         case HAL_PIXEL_FORMAT_RGB_565:
-            strcpy(pixFormatStr, "RGB_565");
+            strlcpy(pixFormatStr, "RGB_565", sizeof(pixFormatStr));
             break;
         case HAL_PIXEL_FORMAT_BGRA_8888:
-            strcpy(pixFormatStr, "BGRA_8888");
+            strlcpy(pixFormatStr, "BGRA_8888", sizeof(pixFormatStr));
             break;
         case HAL_PIXEL_FORMAT_YV12:
-            strcpy(pixFormatStr, "YV12");
+            strlcpy(pixFormatStr, "YV12", sizeof(pixFormatStr));
             break;
         case HAL_PIXEL_FORMAT_YCbCr_422_SP:
-            strcpy(pixFormatStr, "YCbCr_422_SP_NV16");
+            strlcpy(pixFormatStr, "YCbCr_422_SP_NV16", sizeof(pixFormatStr));
             break;
         case HAL_PIXEL_FORMAT_YCrCb_420_SP:
-            strcpy(pixFormatStr, "YCrCb_420_SP_NV21");
+            strlcpy(pixFormatStr, "YCrCb_420_SP_NV21", sizeof(pixFormatStr));
             break;
         case HAL_PIXEL_FORMAT_YCbCr_422_I:
-            strcpy(pixFormatStr, "YCbCr_422_I_YUY2");
+            strlcpy(pixFormatStr, "YCbCr_422_I_YUY2", sizeof(pixFormatStr));
             break;
         case HAL_PIXEL_FORMAT_YCrCb_422_I:
-            strlcpy(pixFormatStr, "YCrCb_422_I_YVYU",
-                            sizeof("YCrCb_422_I_YVYU"));
+            strlcpy(pixFormatStr, "YCrCb_422_I_YVYU", sizeof(pixFormatStr));
             break;
         case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:
-            strcpy(pixFormatStr, "NV12_ENCODEABLE");
+            strlcpy(pixFormatStr, "NV12_ENCODEABLE", sizeof(pixFormatStr));
             break;
         case HAL_PIXEL_FORMAT_YCbCr_420_SP_TILED:
-            strcpy(pixFormatStr, "YCbCr_420_SP_TILED_TILE_4x2");
+            strlcpy(pixFormatStr, "YCbCr_420_SP_TILED_TILE_4x2",
+                   sizeof(pixFormatStr));
             break;
         case HAL_PIXEL_FORMAT_YCbCr_420_SP:
-            strcpy(pixFormatStr, "YCbCr_420_SP");
+            strlcpy(pixFormatStr, "YCbCr_420_SP", sizeof(pixFormatStr));
             break;
         case HAL_PIXEL_FORMAT_YCrCb_420_SP_ADRENO:
-            strcpy(pixFormatStr, "YCrCb_420_SP_ADRENO");
+            strlcpy(pixFormatStr, "YCrCb_420_SP_ADRENO", sizeof(pixFormatStr));
             break;
         case HAL_PIXEL_FORMAT_YCrCb_422_SP:
-            strcpy(pixFormatStr, "YCrCb_422_SP");
+            strlcpy(pixFormatStr, "YCrCb_422_SP", sizeof(pixFormatStr));
             break;
         case HAL_PIXEL_FORMAT_R_8:
-            strcpy(pixFormatStr, "R_8");
+            strlcpy(pixFormatStr, "R_8", sizeof(pixFormatStr));
             break;
         case HAL_PIXEL_FORMAT_RG_88:
-            strcpy(pixFormatStr, "RG_88");
+            strlcpy(pixFormatStr, "RG_88", sizeof(pixFormatStr));
             break;
         case HAL_PIXEL_FORMAT_INTERLACE:
-            strcpy(pixFormatStr, "INTERLACE");
+            strlcpy(pixFormatStr, "INTERLACE", sizeof(pixFormatStr));
             break;
         case HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS:
-            strcpy(pixFormatStr, "YCbCr_420_SP_VENUS");
+            strlcpy(pixFormatStr, "YCbCr_420_SP_VENUS", sizeof(pixFormatStr));
             break;
         default:
-            sprintf(pixFormatStr, "Unknown0x%X", format);
+            snprintf(pixFormatStr, sizeof(pixFormatStr), "Unknown0x%X", format);
             break;
     }
 }
diff --git a/libhwcomposer/hwc_fbupdate.cpp b/libhwcomposer/hwc_fbupdate.cpp
index b81494d..cc9e3b9 100644
--- a/libhwcomposer/hwc_fbupdate.cpp
+++ b/libhwcomposer/hwc_fbupdate.cpp
@@ -45,7 +45,7 @@
 }
 
 IFBUpdate::IFBUpdate(hwc_context_t *ctx, const int& dpy) : mDpy(dpy) {
-    size_t size;
+    size_t size = 0;
     getBufferAttributes(ctx->dpyAttr[mDpy].xres,
             ctx->dpyAttr[mDpy].yres,
             HAL_PIXEL_FORMAT_RGBA_8888,
@@ -62,7 +62,8 @@
 
 bool IFBUpdate::prepareAndValidate(hwc_context_t *ctx,
             hwc_display_contents_1 *list, int fbZorder) {
-    return prepare(ctx, list, fbZorder) &&
+    hwc_layer_1_t *layer = &list->hwLayers[list->numHwLayers - 1];
+    return prepare(ctx, list, layer->displayFrame, fbZorder) &&
             ctx->mOverlay->validateAndSet(mDpy, ctx->dpyAttr[mDpy].fd);
 }
 
@@ -106,19 +107,19 @@
 }
 
 bool FBUpdateNonSplit::prepare(hwc_context_t *ctx, hwc_display_contents_1 *list,
-                             int fbZorder) {
+                             hwc_rect_t fbUpdatingRect, int fbZorder) {
     if(!ctx->mMDP.hasOverlay) {
         ALOGD_IF(DEBUG_FBUPDATE, "%s, this hw doesnt support overlays",
                  __FUNCTION__);
         return false;
     }
-    mModeOn = configure(ctx, list, fbZorder);
+    mModeOn = configure(ctx, list, fbUpdatingRect, fbZorder);
     return mModeOn;
 }
 
 // Configure
 bool FBUpdateNonSplit::configure(hwc_context_t *ctx, hwc_display_contents_1 *list,
-                               int fbZorder) {
+                               hwc_rect_t fbUpdatingRect, int fbZorder) {
     bool ret = false;
     hwc_layer_1_t *layer = &list->hwLayers[list->numHwLayers - 1];
     if (LIKELY(ctx->mOverlay)) {
@@ -159,6 +160,15 @@
 
         hwc_rect_t sourceCrop = integerizeSourceCrop(layer->sourceCropf);
         hwc_rect_t displayFrame = layer->displayFrame;
+
+        // No FB update optimization on (1) Custom FB resolution,
+        // (2) External Mirror mode, (3) External orientation
+        if(!ctx->dpyAttr[mDpy].customFBSize && !ctx->mBufferMirrorMode
+           && !ctx->mExtOrientation) {
+            sourceCrop = fbUpdatingRect;
+            displayFrame = fbUpdatingRect;
+        }
+
         int transform = layer->transform;
         int rotFlags = ovutils::ROT_FLAGS_NONE;
 
@@ -251,20 +261,20 @@
 }
 
 bool FBUpdateSplit::prepare(hwc_context_t *ctx, hwc_display_contents_1 *list,
-                              int fbZorder) {
+                              hwc_rect_t fbUpdatingRect, int fbZorder) {
     if(!ctx->mMDP.hasOverlay) {
         ALOGD_IF(DEBUG_FBUPDATE, "%s, this hw doesnt support overlays",
                  __FUNCTION__);
         return false;
     }
     ALOGD_IF(DEBUG_FBUPDATE, "%s, mModeOn = %d", __FUNCTION__, mModeOn);
-    mModeOn = configure(ctx, list, fbZorder);
+    mModeOn = configure(ctx, list, fbUpdatingRect, fbZorder);
     return mModeOn;
 }
 
 // Configure
 bool FBUpdateSplit::configure(hwc_context_t *ctx,
-        hwc_display_contents_1 *list, int fbZorder) {
+        hwc_display_contents_1 *list, hwc_rect_t fbUpdatingRect, int fbZorder) {
     bool ret = false;
     hwc_layer_1_t *layer = &list->hwLayers[list->numHwLayers - 1];
     if (LIKELY(ctx->mOverlay)) {
@@ -328,8 +338,8 @@
                                 getBlending(layer->blending));
         ov.setSource(pargR, destR);
 
-        hwc_rect_t sourceCrop = integerizeSourceCrop(layer->sourceCropf);
-        hwc_rect_t displayFrame = layer->displayFrame;
+        hwc_rect_t sourceCrop = fbUpdatingRect;
+        hwc_rect_t displayFrame = fbUpdatingRect;
 
         const float xres = ctx->dpyAttr[mDpy].xres;
         const int lSplit = getLeftSplit(ctx, mDpy);
diff --git a/libhwcomposer/hwc_fbupdate.h b/libhwcomposer/hwc_fbupdate.h
index da4cdfc..c8347fa 100644
--- a/libhwcomposer/hwc_fbupdate.h
+++ b/libhwcomposer/hwc_fbupdate.h
@@ -39,7 +39,7 @@
     virtual ~IFBUpdate() {};
     // Sets up members and prepares overlay if conditions are met
     virtual bool prepare(hwc_context_t *ctx, hwc_display_contents_1 *list,
-            int fbZorder) = 0;
+            hwc_rect_t fbUpdatingRect, int fbZorder) = 0;
     virtual bool prepareAndValidate(hwc_context_t *ctx,
             hwc_display_contents_1 *list, int fbZorder);
     // Draws layer
@@ -64,12 +64,12 @@
     explicit FBUpdateNonSplit(hwc_context_t *ctx, const int& dpy);
     virtual ~FBUpdateNonSplit() {};
     bool prepare(hwc_context_t *ctx, hwc_display_contents_1 *list,
-            int fbZorder);
+            hwc_rect_t fbUpdatingRect, int fbZorder);
     bool draw(hwc_context_t *ctx, private_handle_t *hnd);
     void reset();
 private:
     bool configure(hwc_context_t *ctx, hwc_display_contents_1 *list,
-            int fbZorder);
+            hwc_rect_t fbUpdatingRect, int fbZorder);
     bool preRotateExtDisplay(hwc_context_t *ctx,
                                  hwc_layer_1_t *layer,
                                  ovutils::Whf &info,
@@ -85,12 +85,12 @@
     explicit FBUpdateSplit(hwc_context_t *ctx, const int& dpy);
     virtual ~FBUpdateSplit() {};
     bool prepare(hwc_context_t *ctx, hwc_display_contents_1 *list,
-            int fbZorder);
+            hwc_rect_t fbUpdatingRect, int fbZorder);
     bool draw(hwc_context_t *ctx, private_handle_t *hnd);
     void reset();
 private:
     bool configure(hwc_context_t *ctx, hwc_display_contents_1 *list,
-            int fbZorder);
+            hwc_rect_t fbUpdatingRect, int fbZorder);
     ovutils::eDest mDestLeft; //left pipe to draw on
     ovutils::eDest mDestRight; //right pipe to draw on
 };
diff --git a/libhwcomposer/hwc_mdpcomp.cpp b/libhwcomposer/hwc_mdpcomp.cpp
index 6ff1aa3..469ffba 100644
--- a/libhwcomposer/hwc_mdpcomp.cpp
+++ b/libhwcomposer/hwc_mdpcomp.cpp
@@ -38,6 +38,7 @@
 
 IdleInvalidator *MDPComp::idleInvalidator = NULL;
 bool MDPComp::sIdleFallBack = false;
+bool MDPComp::sHandleTimeout = false;
 bool MDPComp::sDebugLogs = false;
 bool MDPComp::sEnabled = false;
 bool MDPComp::sEnableMixedMode = true;
@@ -114,7 +115,7 @@
             sDebugLogs = true;
     }
 
-    if(property_get("persist.hwc.partialupdate.enable", property, NULL) > 0) {
+    if(property_get("persist.hwc.partialupdate", property, NULL) > 0) {
         if((atoi(property) != 0) && ctx->mMDP.panel == MIPI_CMD_PANEL &&
            qdutils::MDPVersion::getInstance().is8x74v2())
             sEnablePartialFrameUpdate = true;
@@ -171,7 +172,12 @@
         ALOGE("%s: received empty data in timer callback", __FUNCTION__);
         return;
     }
-
+    Locker::Autolock _l(ctx->mDrawLock);
+    // Handle timeout event only if the previous composition is MDP or MIXED.
+    if(!sHandleTimeout) {
+        ALOGD_IF(isDebug(), "%s:Do not handle this timeout", __FUNCTION__);
+        return;
+    }
     if(!ctx->proc) {
         ALOGE("%s: HWC proc not registered", __FUNCTION__);
         return;
@@ -1212,6 +1218,22 @@
              mCurrentFrame.fbCount);
 }
 
+hwc_rect_t MDPComp::getUpdatingFBRect(hwc_context_t *ctx,
+        hwc_display_contents_1_t* list){
+    hwc_rect_t fbRect = (struct hwc_rect){0, 0, 0, 0};
+    hwc_layer_1_t *fbLayer = &list->hwLayers[mCurrentFrame.layerCount];
+
+    /* Update only the region of FB needed for composition */
+    for(int i = 0; i < mCurrentFrame.layerCount; i++ ) {
+        if(mCurrentFrame.isFBComposed[i] && !mCurrentFrame.drop[i]) {
+            hwc_layer_1_t* layer = &list->hwLayers[i];
+            hwc_rect_t dst = layer->displayFrame;
+            fbRect = getUnion(fbRect, dst);
+        }
+    }
+    return fbRect;
+}
+
 bool MDPComp::postHeuristicsHandling(hwc_context_t *ctx,
         hwc_display_contents_1_t* list) {
 
@@ -1229,7 +1251,9 @@
 
     //Configure framebuffer first if applicable
     if(mCurrentFrame.fbZ >= 0) {
-        if(!ctx->mFBUpdate[mDpy]->prepare(ctx, list, mCurrentFrame.fbZ)) {
+        hwc_rect_t fbRect = getUpdatingFBRect(ctx, list);
+        if(!ctx->mFBUpdate[mDpy]->prepare(ctx, list, fbRect, mCurrentFrame.fbZ))
+        {
             ALOGD_IF(isDebug(), "%s configure framebuffer failed",
                     __FUNCTION__);
             return false;
@@ -1295,13 +1319,6 @@
         ALOGD_IF(isDebug(), "%s: Exceeds MAX_PIPES_PER_MIXER",__FUNCTION__);
         return false;
     }
-
-    double size = calcMDPBytesRead(ctx, list);
-    if(!bandwidthCheck(ctx, size)) {
-        ALOGD_IF(isDebug(), "%s: Exceeds bandwidth",__FUNCTION__);
-        return false;
-    }
-
     return true;
 }
 
@@ -1344,20 +1361,6 @@
     return size;
 }
 
-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;
-}
-
 bool MDPComp::hwLimitationsCheck(hwc_context_t* ctx,
         hwc_display_contents_1_t* list) {
 
@@ -1619,9 +1622,10 @@
         return true;
     }
 
-    /* reset Invalidator */
-    if(idleInvalidator && !sIdleFallBack && mCurrentFrame.mdpCount)
-        idleInvalidator->handleUpdateEvent();
+    // Set the Handle timeout to true for MDP or MIXED composition.
+    if(idleInvalidator && !sIdleFallBack && mCurrentFrame.mdpCount) {
+        sHandleTimeout = true;
+    }
 
     overlay::Overlay& ov = *ctx->mOverlay;
     LayerProp *layerProp = ctx->layerProp[mDpy];
@@ -1865,9 +1869,10 @@
         return true;
     }
 
-    /* reset Invalidator */
-    if(idleInvalidator && !sIdleFallBack && mCurrentFrame.mdpCount)
-        idleInvalidator->handleUpdateEvent();
+    // Set the Handle timeout to true for MDP or MIXED composition.
+    if(idleInvalidator && !sIdleFallBack && mCurrentFrame.mdpCount) {
+        sHandleTimeout = true;
+    }
 
     overlay::Overlay& ov = *ctx->mOverlay;
     LayerProp *layerProp = ctx->layerProp[mDpy];
diff --git a/libhwcomposer/hwc_mdpcomp.h b/libhwcomposer/hwc_mdpcomp.h
index f2a8eda..4215881 100644
--- a/libhwcomposer/hwc_mdpcomp.h
+++ b/libhwcomposer/hwc_mdpcomp.h
@@ -52,7 +52,7 @@
     /* Initialize MDP comp*/
     static bool init(hwc_context_t *ctx);
     static void resetIdleFallBack() { sIdleFallBack = false; }
-    static void reset() { sBwClaimed = 0.0; };
+    static void reset() { sBwClaimed = 0.0; sHandleTimeout = false; };
 
 protected:
     enum { MAX_SEC_LAYERS = 1 }; //TODO add property support
@@ -179,8 +179,6 @@
     /* 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 double& size);
     /* checks if MDP/MDSS can process current list w.r.to HW limitations
      * All peculiar HW limitations should go here */
     bool hwLimitationsCheck(hwc_context_t* ctx, hwc_display_contents_1_t* list);
@@ -223,6 +221,8 @@
     void reset(hwc_context_t *ctx);
     bool isSupportedForMDPComp(hwc_context_t *ctx, hwc_layer_1_t* layer);
     bool resourceCheck(hwc_context_t *ctx, hwc_display_contents_1_t *list);
+    hwc_rect_t getUpdatingFBRect(hwc_context_t *ctx,
+            hwc_display_contents_1_t* list);
 
     int mDpy;
     static bool sEnabled;
@@ -231,6 +231,8 @@
     static bool sEnablePartialFrameUpdate;
     static bool sDebugLogs;
     static bool sIdleFallBack;
+    /* Handles the timeout event from kernel, if the value is set to true */
+    static bool sHandleTimeout;
     static int sMaxPipesPerMixer;
     //Max bandwidth. Value is in GBPS. For ex: 2.3 means 2.3GBPS
     static double sMaxBw;
diff --git a/libhwcomposer/hwc_utils.cpp b/libhwcomposer/hwc_utils.cpp
index ce2da87..d2104ed 100644
--- a/libhwcomposer/hwc_utils.cpp
+++ b/libhwcomposer/hwc_utils.cpp
@@ -490,7 +490,7 @@
     // the position based on the new width and height
     if ((extOrientation & HWC_TRANSFORM_ROT_90) &&
                         isOrientationPortrait(ctx)) {
-        hwc_rect_t r;
+        hwc_rect_t r = {0, 0, 0, 0};
         //Calculate the position
         xRatio = (outPos.x - xPos)/width;
         // GetaspectRatio -- tricky to get the correct aspect ratio
@@ -781,6 +781,28 @@
     }
 }
 
+hwc_rect_t calculateDisplayViewFrame(hwc_context_t *ctx, int dpy) {
+    int dstWidth = ctx->dpyAttr[dpy].xres;
+    int dstHeight = ctx->dpyAttr[dpy].yres;
+    int srcWidth = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres;
+    int srcHeight = ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres;
+    // default we assume viewframe as a full frame for primary display
+    hwc_rect outRect = {0, 0, dstWidth, dstHeight};
+    if(dpy) {
+        // swap srcWidth and srcHeight, if the device orientation is 90 or 270.
+        if(ctx->deviceOrientation & 0x1) {
+            swap(srcWidth, srcHeight);
+        }
+        // Get Aspect Ratio for external
+        getAspectRatioPosition(dstWidth, dstHeight, srcWidth,
+                            srcHeight, outRect);
+    }
+    ALOGD_IF(HWC_UTILS_DEBUG, "%s: view frame for dpy %d is [%d %d %d %d]",
+        __FUNCTION__, dpy, outRect.left, outRect.top,
+        outRect.right, outRect.bottom);
+    return outRect;
+}
+
 void setListStats(hwc_context_t *ctx,
         hwc_display_contents_1_t *list, int dpy) {
     const int prevYuvCount = ctx->listStats[dpy].yuvCount;
@@ -804,13 +826,14 @@
     trimList(ctx, list, dpy);
     optimizeLayerRects(list);
 
+    // Calculate view frame of ext display from primary resolution
+    // and primary device orientation.
+    ctx->mViewFrame[dpy] = calculateDisplayViewFrame(ctx, dpy);
+
     for (size_t i = 0; i < (size_t)ctx->listStats[dpy].numAppLayers; i++) {
         hwc_layer_1_t const* layer = &list->hwLayers[i];
         private_handle_t *hnd = (private_handle_t *)layer->handle;
 
-        // Calculate view frame of each display from the layer displayframe
-        ctx->mViewFrame[dpy] = getUnion(ctx->mViewFrame[dpy],
-                                        layer->displayFrame);
 #ifdef QCOM_BSP
         if (layer->flags & HWC_SCREENSHOT_ANIMATOR_LAYER) {
             ctx->listStats[dpy].isDisplayAnimating = true;
@@ -1232,25 +1255,30 @@
     for(uint32_t i = 0; i < ctx->mLayerRotMap[dpy]->getCount(); i++) {
         int rotFd = ctx->mRotMgr->getRotDevFd();
         int rotReleaseFd = -1;
+        overlay::Rotator* currRot = ctx->mLayerRotMap[dpy]->getRot(i);
+        hwc_layer_1_t* currLayer = ctx->mLayerRotMap[dpy]->getLayer(i);
+        if((currRot == NULL) || (currLayer == NULL)) {
+            continue;
+        }
         struct mdp_buf_sync rotData;
         memset(&rotData, 0, sizeof(rotData));
         rotData.acq_fen_fd =
-                &ctx->mLayerRotMap[dpy]->getLayer(i)->acquireFenceFd;
+                &currLayer->acquireFenceFd;
         rotData.rel_fen_fd = &rotReleaseFd; //driver to populate this
-        rotData.session_id = ctx->mLayerRotMap[dpy]->getRot(i)->getSessId();
+        rotData.session_id = currRot->getSessId();
         int ret = 0;
         ret = ioctl(rotFd, MSMFB_BUFFER_SYNC, &rotData);
         if(ret < 0) {
             ALOGE("%s: ioctl MSMFB_BUFFER_SYNC failed for rot sync, err=%s",
                     __FUNCTION__, strerror(errno));
         } else {
-            close(ctx->mLayerRotMap[dpy]->getLayer(i)->acquireFenceFd);
+            close(currLayer->acquireFenceFd);
             //For MDP to wait on.
-            ctx->mLayerRotMap[dpy]->getLayer(i)->acquireFenceFd =
+            currLayer->acquireFenceFd =
                     dup(rotReleaseFd);
             //A buffer is free to be used by producer as soon as its copied to
             //rotator
-            ctx->mLayerRotMap[dpy]->getLayer(i)->releaseFenceFd =
+            currLayer->releaseFenceFd =
                     rotReleaseFd;
         }
     }
diff --git a/libhwcomposer/hwc_utils.h b/libhwcomposer/hwc_utils.h
index 25d1c21..8293505 100644
--- a/libhwcomposer/hwc_utils.h
+++ b/libhwcomposer/hwc_utils.h
@@ -211,6 +211,11 @@
 // -----------------------------------------------------------------------------
 // Utility functions - implemented in hwc_utils.cpp
 void dumpLayer(hwc_layer_1_t const* l);
+
+// Calculate viewframe for external/primary display from primary resolution and
+// primary device orientation
+hwc_rect_t calculateDisplayViewFrame(hwc_context_t *ctx, int dpy);
+
 void setListStats(hwc_context_t *ctx, hwc_display_contents_1_t *list,
         int dpy);
 void initContext(hwc_context_t *ctx);
diff --git a/libhwcomposer/hwc_virtual.cpp b/libhwcomposer/hwc_virtual.cpp
index 28dc991..cc29d45 100644
--- a/libhwcomposer/hwc_virtual.cpp
+++ b/libhwcomposer/hwc_virtual.cpp
@@ -284,7 +284,7 @@
 
     closeAcquireFds(list);
 
-    if (list && !ctx->mVirtualonExtActive && (list->retireFenceFd < 0) ) {
+    if (list && list->outbuf && (list->retireFenceFd < 0) ) {
         // SF assumes HWC waits for the acquire fence and returns a new fence
         // that signals when we're done. Since we don't wait, and also don't
         // touch the buffer, we can just handle the acquire fence back to SF
diff --git a/liboverlay/overlay.cpp b/liboverlay/overlay.cpp
index 6feffc4..265aa9f 100644
--- a/liboverlay/overlay.cpp
+++ b/liboverlay/overlay.cpp
@@ -45,7 +45,8 @@
 
 
 Overlay::Overlay() {
-    PipeBook::NUM_PIPES = qdutils::MDPVersion::getInstance().getTotalPipes();
+    int numPipes = qdutils::MDPVersion::getInstance().getTotalPipes();
+    PipeBook::NUM_PIPES = (numPipes <= utils::OV_MAX)? numPipes : utils::OV_MAX;
     for(int i = 0; i < PipeBook::NUM_PIPES; i++) {
         mPipeBook[i].init();
     }
@@ -79,11 +80,11 @@
             //fds
             if(mPipeBook[i].valid()) {
                 char str[32];
-                sprintf(str, "Unset=%s dpy=%d mix=%d; ",
+                snprintf(str, 32, "Unset=%s dpy=%d mix=%d; ",
                         PipeBook::getDestStr((eDest)i),
                         mPipeBook[i].mDisplay, mPipeBook[i].mMixer);
 #if PIPE_DEBUG
-                strncat(mDumpStr, str, strlen(str));
+                strlcat(mDumpStr, str, sizeof(mDumpStr));
 #endif
             }
             mPipeBook[i].destroy();
@@ -146,7 +147,7 @@
             snprintf(str, 32, "Set=%s dpy=%d mix=%d; ",
                      PipeBook::getDestStr(dest), dpy, mixer);
 #if PIPE_DEBUG
-            strncat(mDumpStr, str, strlen(str));
+            strlcat(mDumpStr, str, sizeof(mDumpStr));
 #endif
         }
     } else {
@@ -396,19 +397,19 @@
 void Overlay::getDump(char *buf, size_t len) {
     int totalPipes = 0;
     const char *str = "\nOverlay State\n\n";
-    strncat(buf, str, strlen(str));
+    strlcat(buf, str, len);
     for(int i = 0; i < PipeBook::NUM_PIPES; i++) {
         if(mPipeBook[i].valid()) {
             mPipeBook[i].mPipe->getDump(buf, len);
             char str[64] = {'\0'};
             snprintf(str, 64, "Display=%d\n\n", mPipeBook[i].mDisplay);
-            strncat(buf, str, strlen(str));
+            strlcat(buf, str, len);
             totalPipes++;
         }
     }
     char str_pipes[64] = {'\0'};
     snprintf(str_pipes, 64, "Pipes=%d\n\n", totalPipes);
-    strncat(buf, str_pipes, strlen(str_pipes));
+    strlcat(buf, str_pipes, len);
 }
 
 void Overlay::clear(int dpy) {
diff --git a/liboverlay/overlayRotator.cpp b/liboverlay/overlayRotator.cpp
index 336d434..0e5b0ec 100644
--- a/liboverlay/overlayRotator.cpp
+++ b/liboverlay/overlayRotator.cpp
@@ -175,7 +175,7 @@
     }
     char str[4] = {'\0'};
     snprintf(str, 4, "\n");
-    strncat(buf, str, strlen(str));
+    strlcat(buf, str, len);
 }
 
 int RotMgr::getRotDevFd() {
diff --git a/liboverlay/overlayUtils.cpp b/liboverlay/overlayUtils.cpp
index 5cc4c03..ddba868 100644
--- a/liboverlay/overlayUtils.cpp
+++ b/liboverlay/overlayUtils.cpp
@@ -161,8 +161,7 @@
         case HAL_PIXEL_FORMAT_RGBX_8888:
             return MDP_RGBX_8888_TILE;
         case HAL_PIXEL_FORMAT_RGB_565:
-            // Currenty Driver doesnt support 565 tile format
-            return MDP_RGB_565;
+            return MDP_RGB_565_TILE;
         case HAL_PIXEL_FORMAT_BGRA_8888:
             return MDP_BGRA_8888_TILE;
         case HAL_PIXEL_FORMAT_BGRX_8888:
@@ -417,29 +416,29 @@
             "V.Deci=%d\n",
             prefix, ov.id, ov.z_order, ov.is_fg, ov.alpha,
             ov.transp_mask, ov.flags, ov.horz_deci, ov.vert_deci);
-    strncat(buf, str, strlen(str));
+    strlcat(buf, str, len);
     getDump(buf, len, "\tsrc", ov.src);
     getDump(buf, len, "\tsrc_rect", ov.src_rect);
     getDump(buf, len, "\tdst_rect", ov.dst_rect);
 }
 
-void getDump(char *buf, size_t /*len*/, const char *prefix,
+void getDump(char *buf, size_t len, const char *prefix,
         const msmfb_img& ov) {
     char str_src[256] = {'\0'};
     snprintf(str_src, 256,
             "%s w=%d h=%d format=%d %s\n",
             prefix, ov.width, ov.height, ov.format,
             overlay::utils::getFormatString(ov.format));
-    strncat(buf, str_src, strlen(str_src));
+    strlcat(buf, str_src, len);
 }
 
-void getDump(char *buf, size_t /*len*/, const char *prefix,
+void getDump(char *buf, size_t len, const char *prefix,
         const mdp_rect& ov) {
     char str_rect[256] = {'\0'};
     snprintf(str_rect, 256,
             "%s x=%d y=%d w=%d h=%d\n",
             prefix, ov.x, ov.y, ov.w, ov.h);
-    strncat(buf, str_rect, strlen(str_rect));
+    strlcat(buf, str_rect, len);
 }
 
 void getDump(char *buf, size_t len, const char *prefix,
@@ -448,17 +447,17 @@
     snprintf(str, 256,
             "%s id=%d\n",
             prefix, ov.id);
-    strncat(buf, str, strlen(str));
+    strlcat(buf, str, len);
     getDump(buf, len, "\tdata", ov.data);
 }
 
-void getDump(char *buf, size_t /*len*/, const char *prefix,
+void getDump(char *buf, size_t len, const char *prefix,
         const msmfb_data& ov) {
     char str_data[256] = {'\0'};
     snprintf(str_data, 256,
             "%s offset=%d memid=%d id=%d flags=0x%x\n",
             prefix, ov.offset, ov.memory_id, ov.id, ov.flags);
-    strncat(buf, str_data, strlen(str_data));
+    strlcat(buf, str_data, len);
 }
 
 void getDump(char *buf, size_t len, const char *prefix,
@@ -467,7 +466,7 @@
     snprintf(str, 256, "%s sessid=%u rot=%d, enable=%d downscale=%d\n",
             prefix, rot.session_id, rot.rotations, rot.enable,
             rot.downscale_ratio);
-    strncat(buf, str, strlen(str));
+    strlcat(buf, str, len);
     getDump(buf, len, "\tsrc", rot.src);
     getDump(buf, len, "\tdst", rot.dst);
     getDump(buf, len, "\tsrc_rect", rot.src_rect);
@@ -479,7 +478,7 @@
     snprintf(str, 256,
             "%s sessid=%u\n",
             prefix, rot.session_id);
-    strncat(buf, str, strlen(str));
+    strlcat(buf, str, len);
     getDump(buf, len, "\tsrc", rot.src);
     getDump(buf, len, "\tdst", rot.dst);
 }
diff --git a/liboverlay/overlayUtils.h b/liboverlay/overlayUtils.h
index 959dadf..c0066f3 100644
--- a/liboverlay/overlayUtils.h
+++ b/liboverlay/overlayUtils.h
@@ -555,6 +555,7 @@
     formats[MDP_XRGB_8888_TILE] = STR(MDP_XRGB_8888_TILE);
     formats[MDP_XBGR_8888_TILE] = STR(MDP_XBGR_8888_TILE);
     formats[MDP_BGRX_8888_TILE] = STR(MDP_BGRX_8888_TILE);
+    formats[MDP_RGB_565_TILE] = STR(MDP_RGB_565_TILE);
     formats[MDP_IMGTYPE_LIMIT] = STR(MDP_IMGTYPE_LIMIT);
 
     if(format < 0 || format >= MDP_IMGTYPE_LIMIT) {
@@ -816,7 +817,7 @@
 
 inline void OvFD::setPath(const char* const dev)
 {
-    ::strncpy(mPath, dev, utils::MAX_PATH_LEN);
+    ::strlcpy(mPath, dev, sizeof(mPath));
 }
 
 inline bool OvFD::close()
diff --git a/liboverlay/overlayWriteback.cpp b/liboverlay/overlayWriteback.cpp
index fdead74..08af00f 100644
--- a/liboverlay/overlayWriteback.cpp
+++ b/liboverlay/overlayWriteback.cpp
@@ -261,7 +261,7 @@
         utils::getDump(buf, len, "WBData", sWb->mFbData);
         char str[4] = {'\0'};
         snprintf(str, 4, "\n");
-        strncat(buf, str, strlen(str));
+        strlcat(buf, str, len);
         return true;
     }
     return false;
diff --git a/libqdutils/idle_invalidator.cpp b/libqdutils/idle_invalidator.cpp
index b53f1a3..d30375e 100644
--- a/libqdutils/idle_invalidator.cpp
+++ b/libqdutils/idle_invalidator.cpp
@@ -29,91 +29,99 @@
 
 #include "idle_invalidator.h"
 #include <unistd.h>
+#include <poll.h>
+#include <string.h>
+#include <fcntl.h>
 
 #define II_DEBUG 0
+#define IDLE_NOTIFY_PATH "/sys/devices/virtual/graphics/fb0/idle_notify"
+#define IDLE_TIME_PATH "/sys/devices/virtual/graphics/fb0/idle_time"
 
-static const char *threadName = "Invalidator";
+
+static const char *threadName = "IdleInvalidator";
 InvalidatorHandler IdleInvalidator::mHandler = NULL;
 android::sp<IdleInvalidator> IdleInvalidator::sInstance(0);
 
 IdleInvalidator::IdleInvalidator(): Thread(false), mHwcContext(0),
-    mSleepAgain(false), mSleepTime(0) {
-        ALOGD_IF(II_DEBUG, "%s", __func__);
-    }
+    mTimeoutEventFd(-1) {
+    ALOGD_IF(II_DEBUG, "IdleInvalidator::%s", __FUNCTION__);
+}
 
 int IdleInvalidator::init(InvalidatorHandler reg_handler, void* user_data,
-                          unsigned int idleSleepTime) {
-    ALOGD_IF(II_DEBUG, "%s", __func__);
-
-    Locker::Autolock _l(mLock);
-    /* store registered handler */
+                         unsigned int idleSleepTime) {
+    ALOGD_IF(II_DEBUG, "IdleInvalidator::%s idleSleepTime %d",
+        __FUNCTION__, idleSleepTime);
     mHandler = reg_handler;
     mHwcContext = user_data;
-    mSleepTime = idleSleepTime; //Time in millis
+
+    // Open a sysfs node to receive the timeout notification from driver.
+    mTimeoutEventFd = open(IDLE_NOTIFY_PATH, O_RDONLY);
+    if (mTimeoutEventFd < 0) {
+        ALOGE ("%s:not able to open %s node %s",
+                __FUNCTION__, IDLE_NOTIFY_PATH, strerror(errno));
+        return -1;
+    }
+
+    // Open a sysfs node to send the timeout value to driver.
+    int fd = open(IDLE_TIME_PATH, O_WRONLY);
+    if (fd < 0) {
+        ALOGE ("%s:not able to open %s node %s",
+                __FUNCTION__, IDLE_TIME_PATH, strerror(errno));
+        close(mTimeoutEventFd);
+        mTimeoutEventFd = -1;
+        return -1;
+    }
+    char strSleepTime[64];
+    snprintf(strSleepTime, sizeof(strSleepTime), "%d", idleSleepTime);
+    // Notify driver about the timeout value
+    ssize_t len = pwrite(fd, strSleepTime, strlen(strSleepTime), 0);
+    if(len < -1) {
+        ALOGE ("%s:not able to write into %s node %s",
+                __FUNCTION__, IDLE_TIME_PATH, strerror(errno));
+        close(mTimeoutEventFd);
+        mTimeoutEventFd = -1;
+        close(fd);
+        return -1;
+    }
+    close(fd);
+
+    //Triggers the threadLoop to run, if not already running.
+    run(threadName, android::PRIORITY_LOWEST);
     return 0;
 }
 
 bool IdleInvalidator::threadLoop() {
-    struct timeval lastUpdateTime;
-    ALOGD_IF(II_DEBUG, "%s", __func__);
-
-    {
-        //If we are here, update(s) happened, i.e mSleepAgain is set
-        Locker::Autolock _l(mLock);
-        mSleepAgain = false;
-        lastUpdateTime = mLastUpdateTime;
+    ALOGD_IF(II_DEBUG, "IdleInvalidator::%s", __FUNCTION__);
+    struct pollfd pFd;
+    pFd.fd = mTimeoutEventFd;
+    if (pFd.fd >= 0)
+        pFd.events = POLLPRI | POLLERR;
+    // Poll for an timeout event from driver
+    int err = poll(&pFd, 1, -1);
+    if(err > 0) {
+        if (pFd.revents & POLLPRI) {
+            char data[64];
+            // Consume the node by reading it
+            ssize_t len = pread(pFd.fd, data, 64, 0);
+            ALOGD_IF(II_DEBUG, "IdleInvalidator::%s Idle Timeout fired len %zu",
+                __FUNCTION__, len);
+            mHandler((void*)mHwcContext);
+        }
     }
-
-    struct timeval currentTime;
-    gettimeofday(&currentTime, NULL);
-    int timeSinceUpdateUs = (currentTime.tv_sec - lastUpdateTime.tv_sec) *
-            1000000 + (currentTime.tv_usec - lastUpdateTime.tv_usec);
-    int sleepDurationUs = mSleepTime * 1000 - timeSinceUpdateUs;
-
-    //Sleep only if the duration required is > 1ms, otherwise its not worth it.
-    if(sleepDurationUs > 1000) {
-        usleep(sleepDurationUs);
-        ALOGD_IF(II_DEBUG, "Slept for %d ms", sleepDurationUs / 1000);
-    }
-
-    Locker::Autolock _l(mLock);
-    //If an update happened while we were asleep, sleep again
-    if(mSleepAgain) {
-        //We need to sleep again!
-        mSleepAgain = false;
-        return true;
-    }
-
-#if II_DEBUG
-    gettimeofday(&currentTime, NULL);
-    timeSinceUpdateUs = (currentTime.tv_sec - lastUpdateTime.tv_sec) *
-            1000000 + (currentTime.tv_usec - lastUpdateTime.tv_usec);
-    ALOGD("Idle refresh after %dms", timeSinceUpdateUs / 1000);
-#endif
-
-    mHandler((void*)mHwcContext);
-    return false;
+    return true;
 }
 
 int IdleInvalidator::readyToRun() {
-    ALOGD_IF(II_DEBUG, "%s", __func__);
+    ALOGD_IF(II_DEBUG, "IdleInvalidator::%s", __FUNCTION__);
     return 0; /*NO_ERROR*/
 }
 
 void IdleInvalidator::onFirstRef() {
-    ALOGD_IF(II_DEBUG, "%s", __func__);
-}
-
-void IdleInvalidator::handleUpdateEvent() {
-    Locker::Autolock _l(mLock);
-    gettimeofday(&mLastUpdateTime, NULL);
-    mSleepAgain = true;
-    //Triggers the threadLoop to run, if not already running.
-    run(threadName, android::PRIORITY_AUDIO);
+    ALOGD_IF(II_DEBUG, "IdleInvalidator::%s", __FUNCTION__);
 }
 
 IdleInvalidator *IdleInvalidator::getInstance() {
-    ALOGD_IF(II_DEBUG, "%s", __func__);
+    ALOGD_IF(II_DEBUG, "IdleInvalidator::%s", __FUNCTION__);
     if(sInstance.get() == NULL)
         sInstance = new IdleInvalidator();
     return sInstance.get();
diff --git a/libqdutils/idle_invalidator.h b/libqdutils/idle_invalidator.h
index f41c15e..a881c4b 100644
--- a/libqdutils/idle_invalidator.h
+++ b/libqdutils/idle_invalidator.h
@@ -38,19 +38,15 @@
 
 class IdleInvalidator : public android::Thread {
     void *mHwcContext;
-    struct timeval mLastUpdateTime;
-    bool mSleepAgain;
-    unsigned int mSleepTime;
+    int mTimeoutEventFd;
     static InvalidatorHandler mHandler;
     static android::sp<IdleInvalidator> sInstance;
-    mutable Locker mLock;
 
     public:
     IdleInvalidator();
     /* init timer obj */
     int init(InvalidatorHandler reg_handler, void* user_data, unsigned int
              idleSleepTime);
-    void handleUpdateEvent();
     /*Overrides*/
     virtual bool        threadLoop();
     virtual int         readyToRun();
diff --git a/libqdutils/mdp_version.cpp b/libqdutils/mdp_version.cpp
index 9e36980..c341dfa 100644
--- a/libqdutils/mdp_version.cpp
+++ b/libqdutils/mdp_version.cpp
@@ -149,7 +149,7 @@
 // and parses and updates information accordingly.
 bool MDPVersion::updateSysFsInfo() {
     FILE *sysfsFd;
-    size_t len = 0;
+    size_t len = PAGE_SIZE;
     ssize_t read;
     char *line = NULL;
     char sysfsPath[255];
@@ -172,6 +172,7 @@
                 __FUNCTION__, sysfsPath);
         return false;
     } else {
+        line = (char *) malloc(len);
         while((read = getline(&line, &len, sysfsFd)) != -1) {
             int index=0;
             char *tokens[10];
@@ -221,9 +222,8 @@
                     }
                 }
             }
-            free(line);
-            line = NULL;
         }
+        free(line);
         fclose(sysfsFd);
     }
     ALOGD_IF(DEBUG, "%s: mMDPVersion: %d mMdpRev: %x mRGBPipes:%d,"
@@ -246,6 +246,7 @@
         if(fp){
             //Format "left right" space as delimiter
             if(fread(split, sizeof(char), 64, fp)) {
+                split[sizeof(split) - 1] = '\0';
                 mSplit.mLeft = atoi(split);
                 ALOGI_IF(mSplit.mLeft, "Left Split=%d", mSplit.mLeft);
                 char *rght = strpbrk(split, " ");
diff --git a/libqservice/IQService.cpp b/libqservice/IQService.cpp
index 096444f..f0d7576 100644
--- a/libqservice/IQService.cpp
+++ b/libqservice/IQService.cpp
@@ -123,7 +123,7 @@
     snprintf(buf, size, "/proc/%d/cmdline", pid);
     fd = open(buf, O_RDONLY);
     if (fd < 0) {
-        strcpy(buf, "Unknown");
+        strlcpy(buf, "Unknown", size);
     } else {
         int len = read(fd, buf, size - 1);
         buf[len] = 0;
diff --git a/libvirtual/virtual.cpp b/libvirtual/virtual.cpp
index 342044c..795d8a1 100644
--- a/libvirtual/virtual.cpp
+++ b/libvirtual/virtual.cpp
@@ -191,7 +191,7 @@
                                    getFbForDpy(HWC_DISPLAY_VIRTUAL);
 
         char strDevPath[MAX_SYSFS_FILE_PATH];
-        sprintf(strDevPath,"/dev/graphics/fb%d", fbNum);
+        snprintf(strDevPath,sizeof(strDevPath), "/dev/graphics/fb%d", fbNum);
 
         mFd = open(strDevPath, O_RDWR);
         if(mFd < 0) {