qcom/display: Update HALs

- Update the display HAL from Code Aurora Forum
- Add updated overlay library
- Enable HWC with basic video going through overlay
- Cleanup some files

Change-Id: I65c687c51be458cee71213c79e03eeda962d9086
diff --git a/libgralloc/Android.mk b/libgralloc/Android.mk
index 5377d86..44108c7 100644
--- a/libgralloc/Android.mk
+++ b/libgralloc/Android.mk
@@ -11,65 +11,48 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-
-# Use this flag until pmem/ashmem is implemented in the new gralloc
 LOCAL_PATH := $(call my-dir)
 
 # HAL module implemenation, not prelinked and stored in
 # hw/<OVERLAY_HARDWARE_MODULE_ID>.<ro.product.board>.so
 include $(CLEAR_VARS)
-LOCAL_PRELINK_MODULE := false
-LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/hw
-LOCAL_SHARED_LIBRARIES := liblog libcutils libGLESv1_CM libutils libmemalloc libQcomUI
-LOCAL_SHARED_LIBRARIES += libgenlock
+LOCAL_PRELINK_MODULE   := false
+LOCAL_MODULE_PATH      := $(TARGET_OUT_SHARED_LIBRARIES)/hw
+LOCAL_SHARED_LIBRARIES := liblog libcutils libutils libmemalloc
+LOCAL_SHARED_LIBRARIES += libgenlock libQcomUI libGLESv1_CM
+LOCAL_C_INCLUDES       := hardware/qcom/display/liboverlay/
+LOCAL_C_INCLUDES       += hardware/qcom/display/libgenlock
+LOCAL_C_INCLUDES       += hardware/qcom/display/libqcomui
+LOCAL_MODULE           := gralloc.$(TARGET_BOARD_PLATFORM)
+LOCAL_MODULE_TAGS      := optional
+LOCAL_CFLAGS           := -DLOG_TAG=\"$(TARGET_BOARD_PLATFORM).gralloc\" \
+                          -DDEBUG_CALC_FPS
+LOCAL_SRC_FILES :=  gpu.cpp gralloc.cpp framebuffer.cpp mapper.cpp
 
-LOCAL_C_INCLUDES += hardware/qcom/display/libgenlock
-LOCAL_C_INCLUDES += hardware/qcom/display/libqcomui
-LOCAL_ADDITIONAL_DEPENDENCIES +=
-LOCAL_SRC_FILES :=  framebuffer.cpp \
-                    gpu.cpp         \
-                    gralloc.cpp     \
-                    mapper.cpp
+ifeq ($(TARGET_USES_POST_PROCESSING),true)
+    LOCAL_CFLAGS     += -DUSES_POST_PROCESSING
+    LOCAL_C_INCLUDES += $(TARGET_OUT_HEADERS)/pp/inc
+endif
 
-LOCAL_MODULE := gralloc.$(TARGET_BOARD_PLATFORM)
-LOCAL_MODULE_TAGS := optional
-LOCAL_CFLAGS:= -DLOG_TAG=\"$(TARGET_BOARD_PLATFORM).gralloc\" -DHOST -DDEBUG_CALC_FPS
-
-ifeq ($(call is-board-platform,msm7627_surf msm7627_6x),true)
-    LOCAL_CFLAGS += -DTARGET_MSM7x27
+ifeq ($(TARGET_USES_MDP3), true)
+    LOCAL_CFLAGS += -DUSE_MDP3
 endif
 
 ifeq ($(TARGET_HAVE_HDMI_OUT),true)
     LOCAL_CFLAGS += -DHDMI_DUAL_DISPLAY
-    LOCAL_C_INCLUDES += hardware/qcom/display/liboverlay
     LOCAL_SHARED_LIBRARIES += liboverlay
 endif
-
-ifeq ($(TARGET_USES_SF_BYPASS),true)
-    LOCAL_CFLAGS += -DSF_BYPASS
-endif
-
-ifeq ($(TARGET_GRALLOC_USES_ASHMEM),true)
-    LOCAL_CFLAGS += -DUSE_ASHMEM
-endif
-
 include $(BUILD_SHARED_LIBRARY)
 
 #MemAlloc Library
 include $(CLEAR_VARS)
 LOCAL_PRELINK_MODULE := false
 LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)
-LOCAL_C_INCLUDES += hardware/qcom/display/libqcomui
-LOCAL_ADDITIONAL_DEPENDENCIES +=
+LOCAL_C_INCLUDES := hardware/qcom/display/libqcomui
 LOCAL_SHARED_LIBRARIES := liblog libcutils libutils
-LOCAL_SRC_FILES :=  ionalloc.cpp \
-                    alloc_controller.cpp
+LOCAL_SRC_FILES :=  ionalloc.cpp alloc_controller.cpp
 LOCAL_CFLAGS:= -DLOG_TAG=\"memalloc\"
-
-ifeq ($(TARGET_USES_ION),true)
-    LOCAL_CFLAGS += -DUSE_ION
-endif
-
+LOCAL_CFLAGS += -DUSE_ION
 LOCAL_MODULE := libmemalloc
 LOCAL_MODULE_TAGS := optional
 include $(BUILD_SHARED_LIBRARY)
diff --git a/libgralloc/alloc_controller.cpp b/libgralloc/alloc_controller.cpp
index 47cdc68..1356b2f 100644
--- a/libgralloc/alloc_controller.cpp
+++ b/libgralloc/alloc_controller.cpp
@@ -34,24 +34,26 @@
 #include "alloc_controller.h"
 #include "memalloc.h"
 #include "ionalloc.h"
+#include "pmemalloc.h"
 #include "ashmemalloc.h"
 #include "gr.h"
+#include "qcomutils/comptype.h"
 
 using namespace gralloc;
 using android::sp;
 
-const int GRALLOC_HEAP_MASK = GRALLOC_USAGE_PRIVATE_ADSP_HEAP      |
-                              GRALLOC_USAGE_PRIVATE_UI_CONTIG_HEAP |
-                              GRALLOC_USAGE_PRIVATE_SMI_HEAP       |
-                              GRALLOC_USAGE_PRIVATE_SYSTEM_HEAP    |
-                              GRALLOC_USAGE_PRIVATE_IOMMU_HEAP     |
-                              GRALLOC_USAGE_PRIVATE_MM_HEAP        |
-                              GRALLOC_USAGE_PRIVATE_WRITEBACK_HEAP |
-                              GRALLOC_USAGE_PRIVATE_CAMERA_HEAP;
+const int GRALLOC_HEAP_MASK  =  GRALLOC_USAGE_PRIVATE_ADSP_HEAP      |
+                                GRALLOC_USAGE_PRIVATE_UI_CONTIG_HEAP |
+                                GRALLOC_USAGE_PRIVATE_SMI_HEAP       |
+                                GRALLOC_USAGE_PRIVATE_SYSTEM_HEAP    |
+                                GRALLOC_USAGE_PRIVATE_IOMMU_HEAP     |
+                                GRALLOC_USAGE_PRIVATE_MM_HEAP        |
+                                GRALLOC_USAGE_PRIVATE_WRITEBACK_HEAP |
+                                GRALLOC_USAGE_PRIVATE_CAMERA_HEAP;
 
 
 //Common functions
-static bool canFallback(int compositionType, int usage, bool triedSystem)
+static bool canFallback(int usage, bool triedSystem)
 {
     // Fallback to system heap when alloc fails unless
     // 1. Composition type is MDP
@@ -60,11 +62,12 @@
     // 4. The heap type is protected
     // 5. The buffer is meant for external display only
 
-    if(compositionType == MDP_COMPOSITION)
+    if(QCCompositionType::getInstance().getCompositionType() & COMPOSITION_TYPE_MDP)
         return false;
     if(triedSystem)
         return false;
-    if(usage & (GRALLOC_HEAP_MASK | GRALLOC_USAGE_PROTECTED))
+    if(usage & (GRALLOC_HEAP_MASK | GRALLOC_USAGE_PROTECTED |
+                GRALLOC_USAGE_PRIVATE_CP_BUFFER))
         return false;
     if(usage & (GRALLOC_HEAP_MASK | GRALLOC_USAGE_EXTERNAL_ONLY))
         return false;
@@ -107,13 +110,15 @@
 }
 
 int IonController::allocate(alloc_data& data, int usage,
-        int compositionType)
+                            int compositionType)
 {
     int ionFlags = 0;
     int ret;
     bool noncontig = false;
 
     data.uncached = useUncached(usage);
+    data.allocType = 0;
+
     if(usage & GRALLOC_USAGE_PRIVATE_UI_CONTIG_HEAP)
         ionFlags |= ION_HEAP(ION_SF_HEAP_ID);
 
@@ -134,11 +139,13 @@
     if(usage & GRALLOC_USAGE_PRIVATE_CAMERA_HEAP)
         ionFlags |= ION_HEAP(ION_CAMERA_HEAP_ID);
 
-    if(usage & GRALLOC_USAGE_PROTECTED)
+    if(usage & GRALLOC_USAGE_PRIVATE_CP_BUFFER)
         ionFlags |= ION_SECURE;
 
     if(usage & GRALLOC_USAGE_PRIVATE_DO_NOT_MAP)
-        data.allocType  =  private_handle_t::PRIV_FLAGS_NOT_MAPPED;
+        data.allocType  |=  private_handle_t::PRIV_FLAGS_NOT_MAPPED;
+    else
+        data.allocType  &=  ~(private_handle_t::PRIV_FLAGS_NOT_MAPPED);
 
     // if no flags are set, default to
     // SF + IOMMU heaps, so that bypass can work
@@ -149,9 +156,9 @@
 
     data.flags = ionFlags;
     ret = mIonAlloc->alloc_buffer(data);
+
     // Fallback
-    if(ret < 0 && canFallback(compositionType,
-                              usage,
+    if(ret < 0 && canFallback(usage,
                               (ionFlags & ION_SYSTEM_HEAP_ID)))
     {
         ALOGW("Falling back to system heap");
@@ -161,7 +168,7 @@
     }
 
     if(ret >= 0 ) {
-        data.allocType = private_handle_t::PRIV_FLAGS_USES_ION;
+        data.allocType |= private_handle_t::PRIV_FLAGS_USES_ION;
         if(noncontig)
             data.allocType |= private_handle_t::PRIV_FLAGS_NONCONTIGUOUS_MEM;
         if(ionFlags & ION_SECURE)
@@ -183,14 +190,14 @@
     return memalloc;
 }
 
-#if 0
 //-------------- PmemKernelController-----------------------//
-
+//XXX: Remove - we're not using pmem anymore
+#if 0
 PmemKernelController::PmemKernelController()
 {
-     mPmemAdspAlloc = new PmemKernelAlloc(DEVICE_PMEM_ADSP);
-     // XXX: Right now, there is no need to maintain an instance
-     // of the SMI allocator as we need it only in a few cases
+    mPmemAdspAlloc = new PmemKernelAlloc(DEVICE_PMEM_ADSP);
+    // XXX: Right now, there is no need to maintain an instance
+    // of the SMI allocator as we need it only in a few cases
 }
 
 PmemKernelController::~PmemKernelController()
@@ -198,7 +205,7 @@
 }
 
 int PmemKernelController::allocate(alloc_data& data, int usage,
-        int compositionType)
+                                   int compositionType)
 {
     int ret = 0;
     bool adspFallback = false;
@@ -258,12 +265,13 @@
 }
 
 int PmemAshmemController::allocate(alloc_data& data, int usage,
-        int compositionType)
+                                   int compositionType)
 {
     int ret = 0;
+    data.allocType = 0;
 
     // Make buffers cacheable by default
-        data.uncached = false;
+    data.uncached = false;
 
     // Override if we explicitly need uncached buffers
     if (usage & GRALLOC_USAGE_PRIVATE_UNCACHED)
@@ -298,7 +306,7 @@
     // Fallback
     if(ret >= 0 ) {
         data.allocType = private_handle_t::PRIV_FLAGS_USES_PMEM;
-    } else if(ret < 0 && canFallback(compositionType, usage, false)) {
+    } else if(ret < 0 && canFallback(usage, false)) {
         ALOGW("Falling back to ashmem");
         ret = mAshmemAlloc->alloc_buffer(data);
         if(ret >= 0) {
@@ -327,9 +335,8 @@
     return memalloc;
 }
 #endif
-
 size_t getBufferSizeAndDimensions(int width, int height, int format,
-                        int& alignedw, int &alignedh)
+                                  int& alignedw, int &alignedh)
 {
     size_t size;
 
@@ -376,16 +383,25 @@
             if (HAL_PIXEL_FORMAT_NV12_ENCODEABLE == format) {
                 // The encoder requires a 2K aligned chroma offset.
                 size = ALIGN(alignedw*alignedh, 2048) +
-                       (ALIGN(alignedw/2, 16) * (alignedh/2))*2;
+                    (ALIGN(alignedw/2, 16) * (alignedh/2))*2;
             } else {
                 size = alignedw*alignedh +
                     (ALIGN(alignedw/2, 16) * (alignedh/2))*2;
             }
             size = ALIGN(size, 4096);
             break;
-
+        case HAL_PIXEL_FORMAT_YCbCr_422_SP:
+        case HAL_PIXEL_FORMAT_YCrCb_422_SP:
+            if(width & 1) {
+                ALOGE("width is odd for the YUV422_SP format");
+                return -EINVAL;
+            }
+            alignedw = ALIGN(width, 16);
+            alignedh = height;
+            size = ALIGN(alignedw * alignedh * 2, 4096);
+            break;
         default:
-            ALOGE("unrecognized pixel format: %d", format);
+            ALOGE("unrecognized pixel format: 0x%x", format);
             return -EINVAL;
     }
 
@@ -397,31 +413,31 @@
 // to free the buffer using the free_buffer function
 int alloc_buffer(private_handle_t **pHnd, int w, int h, int format, int usage)
 {
-     alloc_data data;
-     int alignedw, alignedh;
-     android::sp<gralloc::IAllocController> sAlloc =
-         gralloc::IAllocController::getInstance(false);
-     data.base = 0;
-     data.fd = -1;
-     data.offset = 0;
-     data.size = getBufferSizeAndDimensions(w, h, format, alignedw, alignedh);
-     data.align = getpagesize();
-     data.uncached = useUncached(usage);
-     int allocFlags = usage;
+    alloc_data data;
+    int alignedw, alignedh;
+    android::sp<gralloc::IAllocController> sAlloc =
+        gralloc::IAllocController::getInstance(false);
+    data.base = 0;
+    data.fd = -1;
+    data.offset = 0;
+    data.size = getBufferSizeAndDimensions(w, h, format, alignedw, alignedh);
+    data.align = getpagesize();
+    data.uncached = useUncached(usage);
+    int allocFlags = usage;
 
-     int err = sAlloc->allocate(data, allocFlags, 0);
-     if (0 != err) {
-         ALOGE("%s: allocate failed", __FUNCTION__);
-         return -ENOMEM;
-     }
+    int err = sAlloc->allocate(data, allocFlags, 0);
+    if (0 != err) {
+        ALOGE("%s: allocate failed", __FUNCTION__);
+        return -ENOMEM;
+    }
 
-     private_handle_t* hnd = new private_handle_t(data.fd, data.size,
-                             data.allocType, 0, format, alignedw, alignedh);
-     hnd->base = (int) data.base;
-     hnd->offset = data.offset;
-     hnd->gpuaddr = 0;
-     *pHnd = hnd;
-     return 0;
+    private_handle_t* hnd = new private_handle_t(data.fd, data.size,
+                                                 data.allocType, 0, format, alignedw, alignedh);
+    hnd->base = (int) data.base;
+    hnd->offset = data.offset;
+    hnd->gpuaddr = 0;
+    *pHnd = hnd;
+    return 0;
 }
 
 void free_buffer(private_handle_t *hnd)
diff --git a/libgralloc/alloc_controller.h b/libgralloc/alloc_controller.h
index 6c907d1..134ad40 100644
--- a/libgralloc/alloc_controller.h
+++ b/libgralloc/alloc_controller.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
+ * Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -33,82 +33,82 @@
 
 namespace gralloc {
 
-    struct alloc_data;
-    class IMemAlloc;
-    class IonAlloc;
+struct alloc_data;
+class IMemAlloc;
+class IonAlloc;
 
-    class IAllocController : public android::RefBase {
+class IAllocController : public android::RefBase {
 
-        public:
-            /* Allocate using a suitable method
-             * Returns the type of buffer allocated
-             */
-            virtual int allocate(alloc_data& data, int usage,
-                    int compositionType) = 0;
+    public:
+    /* Allocate using a suitable method
+     * Returns the type of buffer allocated
+     */
+    virtual int allocate(alloc_data& data, int usage,
+                         int compositionType) = 0;
 
-            virtual android::sp<IMemAlloc> getAllocator(int flags) = 0;
+    virtual android::sp<IMemAlloc> getAllocator(int flags) = 0;
 
-            virtual ~IAllocController() {};
+    virtual ~IAllocController() {};
 
-            static android::sp<IAllocController> getInstance(bool useMasterHeap);
+    static android::sp<IAllocController> getInstance(bool useMasterHeap);
 
-        private:
-            static android::sp<IAllocController> sController;
+    private:
+    static android::sp<IAllocController> sController;
 
-    };
+};
 
-    class IonController : public IAllocController {
+class IonController : public IAllocController {
 
-        public:
-            virtual int allocate(alloc_data& data, int usage,
-                    int compositionType);
+    public:
+    virtual int allocate(alloc_data& data, int usage,
+                         int compositionType);
 
-            virtual android::sp<IMemAlloc> getAllocator(int flags);
+    virtual android::sp<IMemAlloc> getAllocator(int flags);
 
-            IonController();
+    IonController();
 
-        private:
-            android::sp<IonAlloc> mIonAlloc;
+    private:
+    android::sp<IonAlloc> mIonAlloc;
 
-    };
+};
 
-    class PmemKernelController : public IAllocController {
+class PmemKernelController : public IAllocController {
 
-        public:
-            virtual int allocate(alloc_data& data, int usage,
-                    int compositionType);
+    public:
+    virtual int allocate(alloc_data& data, int usage,
+                         int compositionType);
 
-            virtual android::sp<IMemAlloc> getAllocator(int flags);
+    virtual android::sp<IMemAlloc> getAllocator(int flags);
 
-            PmemKernelController ();
+    PmemKernelController ();
 
-            ~PmemKernelController ();
+    ~PmemKernelController ();
 
-        private:
-            android::sp<IMemAlloc> mPmemAdspAlloc;
+    private:
+    android::sp<IMemAlloc> mPmemAdspAlloc;
 
-    };
+};
 
-    // Main pmem controller - this should only
-    // be used within gralloc
-    class PmemAshmemController : public IAllocController {
+// Main pmem controller - this should only
+// be used within gralloc
+class PmemAshmemController : public IAllocController {
 
-        public:
-            virtual int allocate(alloc_data& data, int usage,
-                    int compositionType);
+    public:
+    virtual int allocate(alloc_data& data, int usage,
+                         int compositionType);
 
-            virtual android::sp<IMemAlloc> getAllocator(int flags);
+    virtual android::sp<IMemAlloc> getAllocator(int flags);
 
-            PmemAshmemController();
+    PmemAshmemController();
 
-            ~PmemAshmemController();
+    ~PmemAshmemController();
 
-        private:
-            android::sp<IMemAlloc> mPmemUserspaceAlloc;
-            android::sp<IMemAlloc> mAshmemAlloc;
-            android::sp<IAllocController> mPmemKernelCtrl;
+    private:
+    android::sp<IMemAlloc> mPmemUserspaceAlloc;
+    android::sp<IMemAlloc> mAshmemAlloc;
+    android::sp<IAllocController> mPmemKernelCtrl;
 
-    };
+};
 
 } //end namespace gralloc
 #endif // GRALLOC_ALLOCCONTROLLER_H
diff --git a/libgralloc/ashmemalloc.cpp b/libgralloc/ashmemalloc.cpp
index 8397e21..b659d90 100644
--- a/libgralloc/ashmemalloc.cpp
+++ b/libgralloc/ashmemalloc.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
+ * Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -53,14 +53,14 @@
     } else {
         if (ashmem_set_prot_region(fd, prot) < 0) {
             ALOGE("ashmem_set_prot_region(fd=%d, prot=%x) failed (%s)",
-                 fd, prot, strerror(errno));
+                  fd, prot, strerror(errno));
             close(fd);
             err = -errno;
         } else {
             base = mmap(0, data.size, prot, MAP_SHARED|MAP_POPULATE|MAP_LOCKED, fd, 0);
             if (base == MAP_FAILED) {
                 ALOGE("alloc mmap(fd=%d, size=%d, prot=%x) failed (%s)",
-                     fd, data.size, prot, strerror(errno));
+                      fd, data.size, prot, strerror(errno));
                 close(fd);
                 err = -errno;
             } else {
@@ -74,7 +74,7 @@
         data.offset = offset;
         clean_buffer(base, data.size, offset, fd);
         ALOGD("ashmem: Allocated buffer base:%p size:%d fd:%d",
-                                base, data.size, fd);
+              base, data.size, fd);
 
     }
     return err;
@@ -84,7 +84,7 @@
 int AshmemAlloc::free_buffer(void* base, size_t size, int offset, int fd)
 {
     ALOGD("ashmem: Freeing buffer base:%p size:%d fd:%d",
-                            base, size, fd);
+          base, size, fd);
     int err = 0;
 
     if(!base) {
@@ -102,15 +102,15 @@
     void *base = 0;
 
     base = mmap(0, size, PROT_READ| PROT_WRITE,
-            MAP_SHARED|MAP_POPULATE, fd, 0);
+                MAP_SHARED|MAP_POPULATE, fd, 0);
     *pBase = base;
     if(base == MAP_FAILED) {
         ALOGE("ashmem: Failed to map memory in the client: %s",
-                                strerror(errno));
+              strerror(errno));
         err = -errno;
     } else {
         ALOGD("ashmem: Mapped buffer base:%p size:%d fd:%d",
-                 base, size, fd);
+              base, size, fd);
     }
     return err;
 }
@@ -121,7 +121,7 @@
     int err = munmap(base, size);
     if(err) {
         ALOGE("ashmem: Failed to unmap memory at %p: %s",
-                                base, strerror(errno));
+              base, strerror(errno));
     }
     return err;
 
diff --git a/libgralloc/ashmemalloc.h b/libgralloc/ashmemalloc.h
index 051dcd1..50daf04 100644
--- a/libgralloc/ashmemalloc.h
+++ b/libgralloc/ashmemalloc.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
+ * Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -34,23 +34,23 @@
 #include <linux/ion.h>
 
 namespace gralloc {
-    class AshmemAlloc : public IMemAlloc  {
+class AshmemAlloc : public IMemAlloc  {
 
-        public:
-            virtual int alloc_buffer(alloc_data& data);
+    public:
+    virtual int alloc_buffer(alloc_data& data);
 
-            virtual int free_buffer(void *base, size_t size,
-                    int offset, int fd);
+    virtual int free_buffer(void *base, size_t size,
+                            int offset, int fd);
 
-            virtual int map_buffer(void **pBase, size_t size,
-                    int offset, int fd);
+    virtual int map_buffer(void **pBase, size_t size,
+                           int offset, int fd);
 
-            virtual int unmap_buffer(void *base, size_t size,
-                    int offset);
+    virtual int unmap_buffer(void *base, size_t size,
+                             int offset);
 
-            virtual int clean_buffer(void*base, size_t size,
-                    int offset, int fd);
+    virtual int clean_buffer(void*base, size_t size,
+                             int offset, int fd);
 
-    };
+};
 }
 #endif /* GRALLOC_ASHMEMALLOC_H */
diff --git a/libgralloc/fb_priv.h b/libgralloc/fb_priv.h
new file mode 100644
index 0000000..677d1c1
--- /dev/null
+++ b/libgralloc/fb_priv.h
@@ -0,0 +1,181 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ * Copyright (c) 2012, Code Aurora Forum. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef FB_PRIV_H
+#define FB_PRIV_H
+#include <linux/fb.h>
+
+#define NUM_FRAMEBUFFERS_MIN  2
+//XXX: Enable triple framebuffers
+#define NUM_FRAMEBUFFERS_MAX  2
+
+#define NO_SURFACEFLINGER_SWAPINTERVAL
+#define COLOR_FORMAT(x) (x & 0xFFF) // Max range for colorFormats is 0 - FFF
+
+#ifdef __cplusplus
+template <class T>
+struct Node
+{
+    T data;
+    Node<T> *next;
+};
+
+template <class T>
+class Queue
+{
+    public:
+    Queue(): front(NULL), back(NULL), len(0) {dummy = new T;}
+    ~Queue()
+    {
+        clear();
+        delete dummy;
+    }
+    void push(const T& item)   //add an item to the back of the queue
+    {
+        if(len != 0) {         //if the queue is not empty
+            back->next = new Node<T>; //create a new node
+            back = back->next; //set the new node as the back node
+            back->data = item;
+            back->next = NULL;
+        } else {
+            back = new Node<T>;
+            back->data = item;
+            back->next = NULL;
+            front = back;
+        }
+        len++;
+    }
+    void pop()                 //remove the first item from the queue
+    {
+        if (isEmpty())
+            return;            //if the queue is empty, no node to dequeue
+        T item = front->data;
+        Node<T> *tmp = front;
+        front = front->next;
+        delete tmp;
+        if(front == NULL)      //if the queue is empty, update the back pointer
+            back = NULL;
+        len--;
+        return;
+    }
+    T& getHeadValue() const    //return the value of the first item in the queue
+    {                          //without modification to the structure
+        if (isEmpty()) {
+            ALOGE("Error can't get head of empty queue");
+            return *dummy;
+        }
+        return front->data;
+    }
+
+    bool isEmpty() const       //returns true if no elements are in the queue
+    {
+        return (front == NULL);
+    }
+
+    size_t size() const        //returns the amount of elements in the queue
+    {
+        return len;
+    }
+
+    private:
+    Node<T> *front;
+    Node<T> *back;
+    size_t len;
+    void clear()
+    {
+        while (!isEmpty())
+            pop();
+    }
+    T *dummy;
+};
+#endif
+
+enum hdmi_mirroring_state {
+    HDMI_NO_MIRRORING,
+    HDMI_UI_MIRRORING,
+};
+
+struct private_handle_t;
+
+struct qbuf_t {
+    buffer_handle_t buf;
+    int  idx;
+};
+
+enum buf_state {
+    SUB,
+    REF,
+    AVL
+};
+
+enum {
+    // flag to indicate we'll post this buffer
+    PRIV_USAGE_LOCKED_FOR_POST = 0x80000000,
+    PRIV_MIN_SWAP_INTERVAL = 0,
+    PRIV_MAX_SWAP_INTERVAL = 1,
+};
+
+
+struct avail_t {
+    pthread_mutex_t lock;
+    pthread_cond_t cond;
+    bool is_avail;
+    buf_state state;
+};
+
+struct private_module_t {
+    gralloc_module_t base;
+
+    struct private_handle_t* framebuffer;
+    uint32_t fbFormat;
+    uint32_t flags;
+    uint32_t numBuffers;
+    uint32_t bufferMask;
+    pthread_mutex_t lock;
+    buffer_handle_t currentBuffer;
+
+    struct fb_var_screeninfo info;
+    struct fb_fix_screeninfo finfo;
+    float xdpi;
+    float ydpi;
+    float fps;
+    uint32_t swapInterval;
+    Queue<struct qbuf_t> disp; // non-empty when buffer is ready for display
+    int currentIdx;
+    struct avail_t avail[NUM_FRAMEBUFFERS_MAX];
+    pthread_mutex_t qlock;
+    pthread_cond_t qpost;
+#if defined(__cplusplus) && defined(HDMI_DUAL_DISPLAY)
+    int orientation;
+    int videoOverlay; // VIDEO_OVERLAY - 2D or 3D
+    int secureVideoOverlay; // VideoOverlay is secure
+    uint32_t currentOffset;
+    int enableHDMIOutput; // holds the type of external display
+    bool trueMirrorSupport;
+    bool exitHDMIUILoop;
+    float actionsafeWidthRatio;
+    float actionsafeHeightRatio;
+    bool hdmiStateChanged;
+    hdmi_mirroring_state hdmiMirroringState;
+    pthread_mutex_t overlayLock;
+    pthread_cond_t overlayPost;
+#endif
+};
+
+
+
+#endif /* FB_PRIV_H */
diff --git a/libgralloc/framebuffer.cpp b/libgralloc/framebuffer.cpp
index b6b4a8f..4935785 100644
--- a/libgralloc/framebuffer.cpp
+++ b/libgralloc/framebuffer.cpp
@@ -1,6 +1,6 @@
 /*
  * Copyright (C) 2008 The Android Open Source Project
-* Copyright (c) 2010-2012 Code Aurora Forum. All rights reserved.
+ * Copyright (c) 2010-2012 Code Aurora Forum. All rights reserved.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -17,15 +17,11 @@
 
 #include <sys/mman.h>
 
-#include <dlfcn.h>
-
-#include <cutils/ashmem.h>
 #include <cutils/log.h>
 #include <cutils/properties.h>
-#include <utils/Timers.h>
+#include <dlfcn.h>
 
 #include <hardware/hardware.h>
-#include <hardware/gralloc.h>
 
 #include <fcntl.h>
 #include <errno.h>
@@ -33,9 +29,6 @@
 #include <string.h>
 #include <stdlib.h>
 #include <pthread.h>
-#include <utils/Timers.h>
-
-#include <cutils/log.h>
 #include <cutils/atomic.h>
 
 #include <linux/fb.h>
@@ -44,18 +37,15 @@
 #include <GLES/gl.h>
 
 #include "gralloc_priv.h"
+#include "fb_priv.h"
 #include "gr.h"
-#ifdef NO_SURFACEFLINGER_SWAPINTERVAL
 #include <cutils/properties.h>
-#endif
+#include <qcomutils/profiler.h>
 
-#include <qcom_ui.h>
+#include "overlay.h"
+namespace ovutils = overlay::utils;
 
-#define FB_DEBUG 0
-
-#if defined(HDMI_DUAL_DISPLAY)
 #define EVEN_OUT(x) if (x & 0x0001) {x--;}
-using overlay::Overlay;
 /** min of int a, b */
 static inline int min(int a, int b) {
     return (a<b) ? a : b;
@@ -64,50 +54,31 @@
 static inline int max(int a, int b) {
     return (a>b) ? a : b;
 }
-#endif
 
 char framebufferStateName[] = {'S', 'R', 'A'};
 
-/*****************************************************************************/
-
-enum {
-    MDDI_PANEL = '1',
-    EBI2_PANEL = '2',
-    LCDC_PANEL = '3',
-    EXT_MDDI_PANEL = '4',
-    TV_PANEL = '5'
-};
-
 enum {
     PAGE_FLIP = 0x00000001,
-    LOCKED = 0x00000002
+    LOCKED    = 0x00000002
 };
 
 struct fb_context_t {
     framebuffer_device_t  device;
 };
 
-static int neworientation;
-
-/*****************************************************************************/
-
-static void
-msm_copy_buffer(buffer_handle_t handle, int fd,
-                int width, int height, int format,
-                int x, int y, int w, int h);
 
 static int fb_setSwapInterval(struct framebuffer_device_t* dev,
-            int interval)
+                              int interval)
 {
     char pval[PROPERTY_VALUE_MAX];
-    property_get("debug.gr.swapinterval", pval, "-1");
+    property_get("debug.egl.swapinterval", pval, "-1");
     int property_interval = atoi(pval);
     if (property_interval >= 0)
         interval = property_interval;
 
     fb_context_t* ctx = (fb_context_t*)dev;
     private_module_t* m = reinterpret_cast<private_module_t*>(
-            dev->common.module);
+        dev->common.module);
     if (interval < dev->minSwapInterval || interval > dev->maxSwapInterval)
         return -EINVAL;
 
@@ -116,13 +87,13 @@
 }
 
 static int fb_setUpdateRect(struct framebuffer_device_t* dev,
-        int l, int t, int w, int h)
+                            int l, int t, int w, int h)
 {
     if (((w|h) <= 0) || ((l|t)<0))
         return -EINVAL;
     fb_context_t* ctx = (fb_context_t*)dev;
     private_module_t* m = reinterpret_cast<private_module_t*>(
-            dev->common.module);
+        dev->common.module);
     m->info.reserved[0] = 0x54445055; // "UPDT";
     m->info.reserved[1] = (uint16_t)l | ((uint32_t)t << 16);
     m->info.reserved[2] = (uint16_t)(l+w) | ((uint32_t)(t+h) << 16);
@@ -150,7 +121,7 @@
 
         // post buf out to display synchronously
         private_handle_t const* hnd = reinterpret_cast<private_handle_t const*>
-                                                (nxtBuf.buf);
+            (nxtBuf.buf);
         const size_t offset = hnd->base - m->framebuffer->base;
         m->info.activate = FB_ACTIVATE_VBL;
         m->info.yoffset = offset / m->finfo.line_length;
@@ -173,28 +144,30 @@
             int nxtAvail = ((nxtBuf.idx + 1) % m->numBuffers);
             pthread_mutex_lock(&(m->avail[nxtBuf.idx].lock));
             m->avail[nxtBuf.idx].is_avail = true;
-            m->avail[nxtBuf.idx].state = REF;
-            pthread_cond_broadcast(&(m->avail[nxtBuf.idx].cond));
+            m->avail[nxtBuf.idx].state = SUB;
+            pthread_cond_signal(&(m->avail[nxtBuf.idx].cond));
             pthread_mutex_unlock(&(m->avail[nxtBuf.idx].lock));
         } else {
+#if 0 //XXX: Triple FB
             pthread_mutex_lock(&(m->avail[nxtBuf.idx].lock));
             if (m->avail[nxtBuf.idx].state != SUB) {
                 ALOGE_IF(m->swapInterval != 0, "[%d] state %c, expected %c", nxtBuf.idx,
-                    framebufferStateName[m->avail[nxtBuf.idx].state],
-                    framebufferStateName[SUB]);
+                         framebufferStateName[m->avail[nxtBuf.idx].state],
+                         framebufferStateName[SUB]);
             }
+
             m->avail[nxtBuf.idx].state = REF;
             pthread_mutex_unlock(&(m->avail[nxtBuf.idx].lock));
-
-            pthread_mutex_lock(&(m->avail[cur_buf].lock));
-            m->avail[cur_buf].is_avail = true;
             if (m->avail[cur_buf].state != REF) {
                 ALOGE_IF(m->swapInterval != 0, "[%d] state %c, expected %c", cur_buf,
-                    framebufferStateName[m->avail[cur_buf].state],
-                    framebufferStateName[REF]);
+                         framebufferStateName[m->avail[cur_buf].state],
+                         framebufferStateName[SUB]);
             }
             m->avail[cur_buf].state = AVL;
-            pthread_cond_broadcast(&(m->avail[cur_buf].cond));
+#endif
+            pthread_mutex_lock(&(m->avail[cur_buf].lock));
+            m->avail[cur_buf].is_avail = true;
+            pthread_cond_signal(&(m->avail[cur_buf].cond));
             pthread_mutex_unlock(&(m->avail[cur_buf].lock));
         }
         cur_buf = nxtBuf.idx;
@@ -205,14 +178,19 @@
 #if defined(HDMI_DUAL_DISPLAY)
 static int closeHDMIChannel(private_module_t* m)
 {
+    // XXX - when enabling HDMI
+#if 0
     Overlay* pTemp = m->pobjOverlay;
     if(pTemp != NULL)
         pTemp->closeChannel();
+#endif
     return 0;
 }
 
+// XXX - Complete when enabling HDMI
+#if 0
 static void getSecondaryDisplayDestinationInfo(private_module_t* m, overlay_rect&
-                                rect, int& orientation)
+                                               rect, int& orientation)
 {
     Overlay* pTemp = m->pobjOverlay;
     int width = pTemp->getFBWidth();
@@ -224,10 +202,10 @@
     switch(rot) {
         // ROT_0
         case 0:
-        // ROT_180
+            // ROT_180
         case HAL_TRANSFORM_ROT_180:
             pTemp->getAspectRatioPosition(fbwidth, fbheight,
-                                                   &rect);
+                                          &rect);
             if(rot ==  HAL_TRANSFORM_ROT_180)
                 orientation = HAL_TRANSFORM_ROT_180;
             else
@@ -242,7 +220,7 @@
             //Width and height will be swapped as there
             //is rotation
             pTemp->getAspectRatioPosition(fbheight, fbwidth,
-                    &rect);
+                                          &rect);
 
             if(rot == HAL_TRANSFORM_ROT_90)
                 orientation = HAL_TRANSFORM_ROT_270;
@@ -252,82 +230,175 @@
     }
     return;
 }
+#endif
+
+/* Determine overlay state based on whether hardware supports true UI
+   mirroring and whether video is playing or not */
+static ovutils::eOverlayState getOverlayState(struct private_module_t* module)
+{
+    overlay2::Overlay& ov = *(Overlay::getInstance());
+
+    // Default to existing state
+    ovutils::eOverlayState state = ov.getState();
+
+    // Sanity check
+    if (!module) {
+        ALOGE("%s: NULL module", __FUNCTION__);
+        return state;
+    }
+
+    // Check if video is playing or not
+    if (module->videoOverlay) {
+        // Video is playing, check if hardware supports true UI mirroring
+        if (module->trueMirrorSupport) {
+            // True UI mirroring is supported by hardware
+            if (ov.getState() == ovutils::OV_2D_VIDEO_ON_PANEL) {
+                // Currently playing 2D video
+                state = ovutils::OV_2D_TRUE_UI_MIRROR;
+            } else if (ov.getState() == ovutils::OV_3D_VIDEO_ON_2D_PANEL) {
+                // Currently playing M3D video
+                // FIXME: Support M3D true UI mirroring
+                state = ovutils::OV_3D_VIDEO_ON_2D_PANEL_2D_TV;
+            }
+        } else {
+            // True UI mirroring is not supported by hardware
+            if (ov.getState() == ovutils::OV_2D_VIDEO_ON_PANEL) {
+                // Currently playing 2D video
+                state = ovutils::OV_2D_VIDEO_ON_PANEL_TV;
+            } else if (ov.getState() == ovutils::OV_3D_VIDEO_ON_2D_PANEL) {
+                // Currently playing M3D video
+                state = ovutils::OV_3D_VIDEO_ON_2D_PANEL_2D_TV;
+            }
+        }
+    } else {
+        // Video is not playing, true UI mirroring support is irrelevant
+        state = ovutils::OV_UI_MIRROR;
+    }
+
+    return state;
+}
+
+/* Set overlay state */
+static void setOverlayState(ovutils::eOverlayState state)
+{
+    overlay2::Overlay& ov = *(Overlay::getInstance());
+    ov.setState(state);
+}
 
 static void *hdmi_ui_loop(void *ptr)
 {
-    private_module_t* m = reinterpret_cast<private_module_t*>(
-            ptr);
+    private_module_t* m = reinterpret_cast<private_module_t*>(ptr);
     while (1) {
         pthread_mutex_lock(&m->overlayLock);
         while(!(m->hdmiStateChanged))
             pthread_cond_wait(&(m->overlayPost), &(m->overlayLock));
+
         m->hdmiStateChanged = false;
         if (m->exitHDMIUILoop) {
             pthread_mutex_unlock(&m->overlayLock);
             return NULL;
         }
-        bool waitForVsync = true;
-        int flags = WAIT_FOR_VSYNC;
-        if (m->pobjOverlay) {
-            Overlay* pTemp = m->pobjOverlay;
-            if (m->hdmiMirroringState == HDMI_NO_MIRRORING)
-                closeHDMIChannel(m);
-            else if(m->hdmiMirroringState == HDMI_UI_MIRRORING) {
-                if (!pTemp->isChannelUP()) {
-                   int alignedW = ALIGN(m->info.xres, 32);
 
-                   private_handle_t const* hnd =
-                      reinterpret_cast<private_handle_t const*>(m->framebuffer);
-                   overlay_buffer_info info;
-                   info.width = alignedW;
-                   info.height = hnd->height;
-                   info.format = hnd->format;
-                   info.size = hnd->size;
+        // No need to mirror UI if HDMI is not on
+        if (!m->enableHDMIOutput) {
+            ALOGE_IF(FB_DEBUG, "%s: hdmi not ON", __FUNCTION__);
+            pthread_mutex_unlock(&m->overlayLock);
+            continue;
+        }
 
-                   if (m->trueMirrorSupport)
-                       flags &= ~WAIT_FOR_VSYNC;
-                   // start the overlay Channel for mirroring
-                   // m->enableHDMIOutput corresponds to the fbnum
-                   if (pTemp->startChannel(info, m->enableHDMIOutput,
-                                           false, true, 0, VG0_PIPE, flags)) {
-                        pTemp->setFd(m->framebuffer->fd);
-                        pTemp->setCrop(0, 0, m->info.xres, m->info.yres);
-                   } else
-                       closeHDMIChannel(m);
-                }
+        overlay2::OverlayMgr* ovMgr =
+            overlay2::OverlayMgrSingleton::getOverlayMgr();
+        overlay2::Overlay& ov = ovMgr->ov();
 
-                if (pTemp->isChannelUP()) {
-                    overlay_rect destRect;
-                    int rot = 0;
-                    int currOrientation = 0;
-                    getSecondaryDisplayDestinationInfo(m, destRect, rot);
-                    pTemp->getOrientation(currOrientation);
-                    if(rot != currOrientation) {
-                        pTemp->setTransform(rot);
-                    }
-                    EVEN_OUT(destRect.x);
-                    EVEN_OUT(destRect.y);
-                    EVEN_OUT(destRect.w);
-                    EVEN_OUT(destRect.h);
-                    int currentX = 0, currentY = 0;
-                    uint32_t currentW = 0, currentH = 0;
-                    if (pTemp->getPosition(currentX, currentY, currentW, currentH)) {
-                        if ((currentX != destRect.x) || (currentY != destRect.y) ||
-                                (currentW != destRect.w) || (currentH != destRect.h)) {
-                            pTemp->setPosition(destRect.x, destRect.y, destRect.w,
-                                                                    destRect.h);
-                        }
-                    }
-                    if (m->trueMirrorSupport) {
-                        // if video is started the UI channel should be NO_WAIT.
-                        flags = !m->videoOverlay ? WAIT_FOR_VSYNC : 0;
-                        pTemp->updateOverlayFlags(flags);
-                    }
-                    pTemp->queueBuffer(m->currentOffset);
-                }
+        // Set overlay state
+        ovutils::eOverlayState state = getOverlayState(m);
+        setOverlayState(state);
+
+        // Determine the RGB pipe for UI depending on the state
+        ovutils::eDest dest = ovutils::OV_PIPE_ALL;
+        if (state == ovutils::OV_2D_TRUE_UI_MIRROR) {
+            // True UI mirroring state: external RGB pipe is OV_PIPE2
+            dest = ovutils::OV_PIPE2;
+        } else if (state == ovutils::OV_UI_MIRROR) {
+            // UI-only mirroring state: external RGB pipe is OV_PIPE0
+            dest = ovutils::OV_PIPE0;
+        } else {
+            // No UI in this case
+            pthread_mutex_unlock(&m->overlayLock);
+            continue;
+        }
+
+        if (m->hdmiMirroringState == HDMI_UI_MIRRORING) {
+            int alignedW = ALIGN(m->info.xres, 32);
+
+            private_handle_t const* hnd =
+                reinterpret_cast<private_handle_t const*>(m->framebuffer);
+            unsigned int width = alignedW;
+            unsigned int height = hnd->height;
+            unsigned int format = hnd->format;
+            unsigned int size = hnd->size/m->numBuffers;
+
+            ovutils::eMdpFlags mdpFlags = ovutils::OV_MDP_FLAGS_NONE;
+            // External display connected during secure video playback
+            // Open secure UI session
+            // NOTE: when external display is already connected and then secure
+            // playback is started, we dont have to do anything
+            if (m->secureVideoOverlay) {
+                ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_SECURE_OVERLAY_SESSION);
             }
-            else
-                closeHDMIChannel(m);
+
+            ovutils::Whf whf(width, height, format, size);
+            ovutils::PipeArgs parg(mdpFlags,
+                                   ovutils::OVERLAY_TRANSFORM_0,
+                                   whf,
+                                   ovutils::WAIT,
+                                   ovutils::ZORDER_0,
+                                   ovutils::IS_FG_OFF,
+                                   ovutils::ROT_FLAG_ENABLED);
+            ovutils::PipeArgs pargs[ovutils::MAX_PIPES] = { parg, parg, parg };
+            bool ret = ov.setSource(pargs, dest);
+            if (!ret) {
+                ALOGE("%s setSource failed", __FUNCTION__);
+            }
+
+            // we need to communicate m->orientation that will get some
+            // modifications within setParameter func.
+            // FIXME that is ugly.
+            const ovutils::Params prms (ovutils::OVERLAY_TRANSFORM_UI,
+                                        m->orientation);
+            ov.setParameter(prms, dest);
+            if (!ret) {
+                ALOGE("%s setParameter failed transform", __FUNCTION__);
+            }
+
+            // x,y,w,h
+            ovutils::Dim dcrop(0, 0, m->info.xres, m->info.yres);
+            ov.setMemoryId(m->framebuffer->fd, dest);
+            ret = ov.setCrop(dcrop, dest);
+            if (!ret) {
+                ALOGE("%s setCrop failed", __FUNCTION__);
+            }
+
+            ovutils::Dim pdim (m->info.xres,
+                               m->info.yres,
+                               0,
+                               0,
+                               m->orientation);
+            ret = ov.setPosition(pdim, dest);
+            if (!ret) {
+                ALOGE("%s setPosition failed", __FUNCTION__);
+            }
+
+            if (!ov.commit(dest)) {
+                ALOGE("%s commit fails", __FUNCTION__);
+            }
+
+            ret = ov.queueBuffer(m->currentOffset, dest);
+            if (!ret) {
+                ALOGE("%s queueBuffer failed", __FUNCTION__);
+            }
+        } else {
+            setOverlayState(ovutils::OV_CLOSED);
         }
         pthread_mutex_unlock(&m->overlayLock);
     }
@@ -336,20 +407,30 @@
 
 static int fb_videoOverlayStarted(struct framebuffer_device_t* dev, int started)
 {
+    ALOGE_IF(FB_DEBUG, "%s started=%d", __FUNCTION__, started);
     private_module_t* m = reinterpret_cast<private_module_t*>(
-            dev->common.module);
+        dev->common.module);
     pthread_mutex_lock(&m->overlayLock);
-    Overlay* pTemp = m->pobjOverlay;
     if(started != m->videoOverlay) {
         m->videoOverlay = started;
+        m->hdmiStateChanged = true;
         if (!m->trueMirrorSupport) {
-            m->hdmiStateChanged = true;
-            if (started && pTemp) {
+            if (started) {
                 m->hdmiMirroringState = HDMI_NO_MIRRORING;
-                closeHDMIChannel(m);
+                ovutils::eOverlayState state = getOverlayState(m);
+                setOverlayState(state);
             } else if (m->enableHDMIOutput)
                 m->hdmiMirroringState = HDMI_UI_MIRRORING;
-            pthread_cond_signal(&(m->overlayPost));
+        } else {
+            if (m->videoOverlay == VIDEO_3D_OVERLAY_STARTED) {
+                ALOGE_IF(FB_DEBUG, "3D Video Started, stop mirroring!");
+                m->hdmiMirroringState = HDMI_NO_MIRRORING;
+                ovutils::eOverlayState state = getOverlayState(m);
+                setOverlayState(state);
+            }
+            else if (m->enableHDMIOutput) {
+                m->hdmiMirroringState = HDMI_UI_MIRRORING;
+            }
         }
     }
     pthread_mutex_unlock(&m->overlayLock);
@@ -358,14 +439,13 @@
 
 static int fb_enableHDMIOutput(struct framebuffer_device_t* dev, int externaltype)
 {
+    ALOGE_IF(FB_DEBUG, "%s externaltype=%d", __FUNCTION__, externaltype);
     private_module_t* m = reinterpret_cast<private_module_t*>(
-            dev->common.module);
+        dev->common.module);
     pthread_mutex_lock(&m->overlayLock);
-    Overlay* pTemp = m->pobjOverlay;
     //Check if true mirroring can be supported
-    m->trueMirrorSupport = FrameBufferInfo::getInstance()->canSupportTrueMirroring();
+    m->trueMirrorSupport = ovutils::FrameBufferInfo::getInstance()->supportTrueMirroring();
     m->enableHDMIOutput = externaltype;
-    ALOGE("In fb_enableHDMIOutput: externaltype = %d", m->enableHDMIOutput);
     if(externaltype) {
         if (m->trueMirrorSupport) {
             m->hdmiMirroringState = HDMI_UI_MIRRORING;
@@ -373,9 +453,11 @@
             if(!m->videoOverlay)
                 m->hdmiMirroringState = HDMI_UI_MIRRORING;
         }
-    } else if (!externaltype && pTemp) {
+    } else if (!externaltype) {
+        // Either HDMI is disconnected or suspend occurred
         m->hdmiMirroringState = HDMI_NO_MIRRORING;
-        closeHDMIChannel(m);
+        ovutils::eOverlayState state = getOverlayState(m);
+        setOverlayState(state);
     }
     m->hdmiStateChanged = true;
     pthread_cond_signal(&(m->overlayPost));
@@ -383,58 +465,132 @@
     return 0;
 }
 
-
-static int fb_setActionSafeWidthRatio(struct framebuffer_device_t* dev, float asWidthRatio)
-{
-    private_module_t* m = reinterpret_cast<private_module_t*>(
-            dev->common.module);
-    pthread_mutex_lock(&m->overlayLock);
-    m->actionsafeWidthRatio = asWidthRatio;
-    pthread_mutex_unlock(&m->overlayLock);
-    return 0;
-}
-
-static int fb_setActionSafeHeightRatio(struct framebuffer_device_t* dev, float asHeightRatio)
-{
-    private_module_t* m = reinterpret_cast<private_module_t*>(
-                    dev->common.module);
-    pthread_mutex_lock(&m->overlayLock);
-    m->actionsafeHeightRatio = asHeightRatio;
-    pthread_mutex_unlock(&m->overlayLock);
-    return 0;
-}
-
 static int fb_orientationChanged(struct framebuffer_device_t* dev, int orientation)
 {
     private_module_t* m = reinterpret_cast<private_module_t*>(
-            dev->common.module);
+        dev->common.module);
     pthread_mutex_lock(&m->overlayLock);
     neworientation = orientation;
     pthread_mutex_unlock(&m->overlayLock);
     return 0;
 }
+
+static int handle_open_secure_start(private_module_t* m) {
+    pthread_mutex_lock(&m->overlayLock);
+    m->hdmiMirroringState = HDMI_NO_MIRRORING;
+    m->secureVideoOverlay = true;
+    pthread_mutex_unlock(&m->overlayLock);
+    return 0;
+}
+
+static int handle_open_secure_end(private_module_t* m) {
+    pthread_mutex_lock(&m->overlayLock);
+    if (m->enableHDMIOutput) {
+        if (m->trueMirrorSupport) {
+            m->hdmiMirroringState = HDMI_UI_MIRRORING;
+        } else if(!m->videoOverlay) {
+            m->hdmiMirroringState = HDMI_UI_MIRRORING;
+        }
+        m->hdmiStateChanged = true;
+        pthread_cond_signal(&(m->overlayPost));
+    }
+    pthread_mutex_unlock(&m->overlayLock);
+    return 0;
+}
+
+static int handle_close_secure_start(private_module_t* m) {
+    pthread_mutex_lock(&m->overlayLock);
+    m->hdmiMirroringState = HDMI_NO_MIRRORING;
+    m->secureVideoOverlay = false;
+    pthread_mutex_unlock(&m->overlayLock);
+    return 0;
+}
+
+static int handle_close_secure_end(private_module_t* m) {
+    pthread_mutex_lock(&m->overlayLock);
+    if (m->enableHDMIOutput) {
+        if (m->trueMirrorSupport) {
+            m->hdmiMirroringState = HDMI_UI_MIRRORING;
+        } else if(!m->videoOverlay) {
+            m->hdmiMirroringState = HDMI_UI_MIRRORING;
+        }
+        m->hdmiStateChanged = true;
+        pthread_cond_signal(&(m->overlayPost));
+    }
+    pthread_mutex_unlock(&m->overlayLock);
+    return 0;
+}
 #endif
 
+
+
+/* fb_perform - used to add custom event and handle them in fb HAL
+ * Used for external display related functions as of now
+ */
+static int fb_perform(struct framebuffer_device_t* dev, int event, int value)
+{
+    private_module_t* m = reinterpret_cast<private_module_t*>(
+        dev->common.module);
+    switch(event) {
+#if defined(HDMI_DUAL_DISPLAY)
+        case EVENT_EXTERNAL_DISPLAY:
+            fb_enableHDMIOutput(dev, value);
+            break;
+        case EVENT_VIDEO_OVERLAY:
+            fb_videoOverlayStarted(dev, value);
+            break;
+        case EVENT_ORIENTATION_CHANGE:
+            fb_orientationChanged(dev, value);
+            break;
+        case EVENT_OVERLAY_STATE_CHANGE:
+            if (value == OVERLAY_STATE_CHANGE_START) {
+                // When state change starts, get a lock on overlay
+                pthread_mutex_lock(&m->overlayLock);
+            } else if (value == OVERLAY_STATE_CHANGE_END) {
+                // When state change is complete, unlock overlay
+                pthread_mutex_unlock(&m->overlayLock);
+            }
+            break;
+        case EVENT_OPEN_SECURE_START:
+            handle_open_secure_start(m);
+            break;
+        case EVENT_OPEN_SECURE_END:
+            handle_open_secure_end(m);
+            break;
+        case EVENT_CLOSE_SECURE_START:
+            handle_close_secure_start(m);
+            break;
+        case EVENT_CLOSE_SECURE_END:
+            handle_close_secure_end(m);
+            break;
+#endif
+        default:
+            ALOGE("In %s: UNKNOWN Event = %d!!!", __FUNCTION__, event);
+            break;
+    }
+    return 0;
+}
+
+
 static int fb_post(struct framebuffer_device_t* dev, buffer_handle_t buffer)
 {
     if (private_handle_t::validate(buffer) < 0)
         return -EINVAL;
 
-    int nxtIdx, futureIdx = -1;
+    int nxtIdx;//, futureIdx = -1;
     bool reuse;
     struct qbuf_t qb;
     fb_context_t* ctx = (fb_context_t*)dev;
 
     private_handle_t const* hnd = reinterpret_cast<private_handle_t const*>(buffer);
     private_module_t* m = reinterpret_cast<private_module_t*>(
-            dev->common.module);
+        dev->common.module);
 
     if (hnd->flags & private_handle_t::PRIV_FLAGS_FRAMEBUFFER) {
 
         reuse = false;
         nxtIdx = (m->currentIdx + 1) % m->numBuffers;
-        futureIdx = (nxtIdx + 1) % m->numBuffers;
-
+        //futureIdx = (nxtIdx + 1) % m->numBuffers;
         if (m->swapInterval == 0) {
             // if SwapInterval = 0 and no buffers available then reuse
             // current buf for next rendering so don't post new buffer
@@ -450,24 +606,25 @@
         if(!reuse){
             // unlock previous ("current") Buffer and lock the new buffer
             m->base.lock(&m->base, buffer,
-                    private_module_t::PRIV_USAGE_LOCKED_FOR_POST,
-                    0,0, m->info.xres, m->info.yres, NULL);
+                         PRIV_USAGE_LOCKED_FOR_POST,
+                         0,0, m->info.xres, m->info.yres, NULL);
 
             // post/queue the new buffer
             pthread_mutex_lock(&(m->avail[nxtIdx].lock));
-            if (m->avail[nxtIdx].is_avail != true) {
-                ALOGE_IF(m->swapInterval != 0, "Found %d buf to be not avail", nxtIdx);
-            }
-
             m->avail[nxtIdx].is_avail = false;
+#if 0 //XXX: Triple FB
+            if (m->avail[nxtIdx].is_avail != true) {
+               ALOGE_IF(m->swapInterval != 0, "Found %d buf to be not avail", nxtIdx);
+            }
 
             if (m->avail[nxtIdx].state != AVL) {
                 ALOGD("[%d] state %c, expected %c", nxtIdx,
-                    framebufferStateName[m->avail[nxtIdx].state],
-                    framebufferStateName[AVL]);
+                      framebufferStateName[m->avail[nxtIdx].state],
+                      framebufferStateName[AVL]);
             }
 
             m->avail[nxtIdx].state = SUB;
+#endif
             pthread_mutex_unlock(&(m->avail[nxtIdx].lock));
 
             qb.idx = nxtIdx;
@@ -486,40 +643,12 @@
             if (m->currentBuffer)
                 m->base.unlock(&m->base, m->currentBuffer);
             m->base.lock(&m->base, buffer,
-                         private_module_t::PRIV_USAGE_LOCKED_FOR_POST,
+                         PRIV_USAGE_LOCKED_FOR_POST,
                          0,0, m->info.xres, m->info.yres, NULL);
             m->currentBuffer = buffer;
         }
 
-    } else {
-        void* fb_vaddr;
-        void* buffer_vaddr;
-        m->base.lock(&m->base, m->framebuffer,
-                GRALLOC_USAGE_SW_WRITE_RARELY,
-                0, 0, m->info.xres, m->info.yres,
-                &fb_vaddr);
-
-        m->base.lock(&m->base, buffer,
-                GRALLOC_USAGE_SW_READ_RARELY,
-                0, 0, m->info.xres, m->info.yres,
-                &buffer_vaddr);
-
-        //memcpy(fb_vaddr, buffer_vaddr, m->finfo.line_length * m->info.yres);
-
-        msm_copy_buffer(
-                m->framebuffer, m->framebuffer->fd,
-                m->info.xres, m->info.yres, m->fbFormat,
-                m->info.xoffset, m->info.yoffset,
-                m->info.width, m->info.height);
-
-        m->base.unlock(&m->base, buffer);
-        m->base.unlock(&m->base, m->framebuffer);
     }
-
-    ALOGD_IF(FB_DEBUG, "Framebuffer state: [0] = %c [1] = %c [2] = %c",
-        framebufferStateName[m->avail[0].state],
-        framebufferStateName[m->avail[1].state],
-        framebufferStateName[m->avail[2].state]);
     return 0;
 }
 
@@ -534,7 +663,7 @@
 static int fb_lockBuffer(struct framebuffer_device_t* dev, int index)
 {
     private_module_t* m = reinterpret_cast<private_module_t*>(
-            dev->common.module);
+        dev->common.module);
 
     // Return immediately if the buffer is available
     if ((m->avail[index].state == AVL) || (m->swapInterval == 0))
@@ -543,15 +672,13 @@
     pthread_mutex_lock(&(m->avail[index].lock));
     while (m->avail[index].state != AVL) {
         pthread_cond_wait(&(m->avail[index].cond),
-                         &(m->avail[index].lock));
+                          &(m->avail[index].lock));
     }
     pthread_mutex_unlock(&(m->avail[index].lock));
 
     return 0;
 }
 
-/*****************************************************************************/
-
 int mapFrameBufferLocked(struct private_module_t* module)
 {
     // already initialized...
@@ -559,9 +686,9 @@
         return 0;
     }
     char const * const device_template[] = {
-            "/dev/graphics/fb%u",
-            "/dev/fb%u",
-            0 };
+        "/dev/graphics/fb%u",
+        "/dev/fb%u",
+        0 };
 
     int fd = -1;
     int i=0;
@@ -592,11 +719,11 @@
     info.activate = FB_ACTIVATE_NOW;
 
     /* Interpretation of offset for color fields: All offsets are from the right,
-    * inside a "pixel" value, which is exactly 'bits_per_pixel' wide (means: you
-    * can use the offset as right argument to <<). A pixel afterwards is a bit
-    * stream and is written to video memory as that unmodified. This implies
-    * big-endian byte order if bits_per_pixel is greater than 8.
-    */
+     * inside a "pixel" value, which is exactly 'bits_per_pixel' wide (means: you
+     * can use the offset as right argument to <<). A pixel afterwards is a bit
+     * stream and is written to video memory as that unmodified. This implies
+     * big-endian byte order if bits_per_pixel is greater than 8.
+     */
 
     if(info.bits_per_pixel == 32) {
         /*
@@ -617,7 +744,8 @@
          * RGBA instead of RGBX. */
         if (property_get("debug.sf.hw", property, NULL) > 0 && atoi(property) == 0)
             module->fbFormat = HAL_PIXEL_FORMAT_RGBX_8888;
-        else if(property_get("debug.composition.type", property, NULL) > 0 && (strncmp(property, "mdp", 3) == 0))
+        else if(property_get("debug.composition.type", property, NULL) > 0 &&
+                (strncmp(property, "mdp", 3) == 0))
             module->fbFormat = HAL_PIXEL_FORMAT_RGBX_8888;
         else
             module->fbFormat = HAL_PIXEL_FORMAT_RGBA_8888;
@@ -641,7 +769,7 @@
     int  size = roundUpToPageSize(info.yres * info.xres * (info.bits_per_pixel/8));
 
     /*
-     * Request NUM_BUFFERS screens (at lest 2 for page flipping)
+     * Request NUM_BUFFERS screens (at least 2 for page flipping)
      */
     int numberOfBuffers = (int)(finfo.smem_len/size);
     ALOGV("num supported framebuffers in kernel = %d", numberOfBuffers);
@@ -673,7 +801,7 @@
         info.yres_virtual = size / line_length;
         flags &= ~PAGE_FLIP;
         ALOGW("page flipping not supported (yres_virtual=%d, requested=%d)",
-                info.yres_virtual, info.yres*2);
+              info.yres_virtual, info.yres*2);
     }
 
     if (ioctl(fd, FBIOGET_VSCREENINFO, &info) == -1)
@@ -691,35 +819,35 @@
     //The reserved[4] field is used to store FPS by the driver.
     float fps  = info.reserved[4];
 
-    ALOGI(   "using (fd=%d)\n"
-            "id           = %s\n"
-            "xres         = %d px\n"
-            "yres         = %d px\n"
-            "xres_virtual = %d px\n"
-            "yres_virtual = %d px\n"
-            "bpp          = %d\n"
-            "r            = %2u:%u\n"
-            "g            = %2u:%u\n"
-            "b            = %2u:%u\n",
-            fd,
-            finfo.id,
-            info.xres,
-            info.yres,
-            info.xres_virtual,
-            info.yres_virtual,
-            info.bits_per_pixel,
-            info.red.offset, info.red.length,
-            info.green.offset, info.green.length,
-            info.blue.offset, info.blue.length
-    );
+    ALOGI("using (fd=%d)\n"
+          "id           = %s\n"
+          "xres         = %d px\n"
+          "yres         = %d px\n"
+          "xres_virtual = %d px\n"
+          "yres_virtual = %d px\n"
+          "bpp          = %d\n"
+          "r            = %2u:%u\n"
+          "g            = %2u:%u\n"
+          "b            = %2u:%u\n",
+          fd,
+          finfo.id,
+          info.xres,
+          info.yres,
+          info.xres_virtual,
+          info.yres_virtual,
+          info.bits_per_pixel,
+          info.red.offset, info.red.length,
+          info.green.offset, info.green.length,
+          info.blue.offset, info.blue.length
+         );
 
-    ALOGI(   "width        = %d mm (%f dpi)\n"
-            "height       = %d mm (%f dpi)\n"
-            "refresh rate = %.2f Hz\n",
-            info.width,  xdpi,
-            info.height, ydpi,
-            fps
-    );
+    ALOGI("width        = %d mm (%f dpi)\n"
+          "height       = %d mm (%f dpi)\n"
+          "refresh rate = %.2f Hz\n",
+          info.width,  xdpi,
+          info.height, ydpi,
+          fps
+         );
 
 
     if (ioctl(fd, FBIOGET_FSCREENINFO, &finfo) == -1)
@@ -739,12 +867,12 @@
     char pval[PROPERTY_VALUE_MAX];
     property_get("debug.gr.swapinterval", pval, "1");
     module->swapInterval = atoi(pval);
-    if (module->swapInterval < private_module_t::PRIV_MIN_SWAP_INTERVAL ||
-        module->swapInterval > private_module_t::PRIV_MAX_SWAP_INTERVAL) {
+    if (module->swapInterval < PRIV_MIN_SWAP_INTERVAL ||
+        module->swapInterval > PRIV_MAX_SWAP_INTERVAL) {
         module->swapInterval = 1;
         ALOGW("Out of range (%d to %d) value for debug.gr.swapinterval, using 1",
-             private_module_t::PRIV_MIN_SWAP_INTERVAL,
-             private_module_t::PRIV_MAX_SWAP_INTERVAL);
+              PRIV_MIN_SWAP_INTERVAL,
+              PRIV_MAX_SWAP_INTERVAL);
     }
 
 #else
@@ -765,9 +893,9 @@
     }
 
     /* create display update thread */
-    pthread_t thread1;
-    if (pthread_create(&thread1, NULL, &disp_loop, (void *) module)) {
-         return -errno;
+    pthread_t disp_thread;
+    if (pthread_create(&disp_thread, NULL, &disp_loop, (void *) module)) {
+        return -errno;
     }
 
     /*
@@ -778,10 +906,12 @@
     module->numBuffers = info.yres_virtual / info.yres;
     module->bufferMask = 0;
     //adreno needs page aligned offsets. Align the fbsize to pagesize.
-    size_t fbSize = roundUpToPageSize(finfo.line_length * info.yres) * module->numBuffers;
+    size_t fbSize = roundUpToPageSize(finfo.line_length * info.yres)*
+                    module->numBuffers;
     module->framebuffer = new private_handle_t(fd, fbSize,
-                            private_handle_t::PRIV_FLAGS_USES_PMEM, BUFFER_TYPE_UI,
-                            module->fbFormat, info.xres, info.yres);
+                                               private_handle_t::PRIV_FLAGS_USES_PMEM,
+                                               BUFFER_TYPE_UI,
+                                               module->fbFormat, info.xres, info.yres);
     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));
@@ -794,7 +924,6 @@
     /* Overlay for HDMI*/
     pthread_mutex_init(&(module->overlayLock), NULL);
     pthread_cond_init(&(module->overlayPost), NULL);
-    module->pobjOverlay = new Overlay();
     module->currentOffset = 0;
     module->exitHDMIUILoop = false;
     module->hdmiStateChanged = false;
@@ -822,7 +951,7 @@
     fb_context_t* ctx = (fb_context_t*)dev;
 #if defined(HDMI_DUAL_DISPLAY)
     private_module_t* m = reinterpret_cast<private_module_t*>(
-            ctx->device.common.module);
+        ctx->device.common.module);
     pthread_mutex_lock(&m->overlayLock);
     m->exitHDMIUILoop = true;
     pthread_cond_signal(&(m->overlayPost));
@@ -835,7 +964,7 @@
 }
 
 int fb_device_open(hw_module_t const* module, const char* name,
-        hw_device_t** device)
+                   hw_device_t** device)
 {
     int status = -EINVAL;
     if (!strcmp(name, GRALLOC_HARDWARE_FB0)) {
@@ -849,22 +978,14 @@
         memset(dev, 0, sizeof(*dev));
 
         /* initialize the procs */
-        dev->device.common.tag = HARDWARE_DEVICE_TAG;
-        dev->device.common.version = 0;
-        dev->device.common.module = const_cast<hw_module_t*>(module);
-        dev->device.common.close = fb_close;
+        dev->device.common.tag      = HARDWARE_DEVICE_TAG;
+        dev->device.common.version  = 0;
+        dev->device.common.module   = const_cast<hw_module_t*>(module);
+        dev->device.common.close    = fb_close;
         dev->device.setSwapInterval = fb_setSwapInterval;
         dev->device.post            = fb_post;
-        dev->device.setUpdateRect = 0;
+        dev->device.setUpdateRect   = 0;
         dev->device.compositionComplete = fb_compositionComplete;
-        //dev->device.lockBuffer = fb_lockBuffer;
-#if defined(HDMI_DUAL_DISPLAY)
-        dev->device.orientationChanged = fb_orientationChanged;
-        dev->device.videoOverlayStarted = fb_videoOverlayStarted;
-        dev->device.enableHDMIOutput = fb_enableHDMIOutput;
-        dev->device.setActionSafeWidthRatio = fb_setActionSafeWidthRatio;
-        dev->device.setActionSafeHeightRatio = fb_setActionSafeHeightRatio;
-#endif
 
         private_module_t* m = (private_module_t*)module;
         status = mapFrameBuffer(m);
@@ -878,11 +999,10 @@
             const_cast<float&>(dev->device.xdpi) = m->xdpi;
             const_cast<float&>(dev->device.ydpi) = m->ydpi;
             const_cast<float&>(dev->device.fps) = m->fps;
-            const_cast<int&>(dev->device.minSwapInterval) = private_module_t::PRIV_MIN_SWAP_INTERVAL;
-            const_cast<int&>(dev->device.maxSwapInterval) = private_module_t::PRIV_MAX_SWAP_INTERVAL;
-            //const_cast<int&>(dev->device.numFramebuffers) = m->numBuffers;
+            const_cast<int&>(dev->device.minSwapInterval) = PRIV_MIN_SWAP_INTERVAL;
+            const_cast<int&>(dev->device.maxSwapInterval) = PRIV_MAX_SWAP_INTERVAL;
             if (m->finfo.reserved[0] == 0x5444 &&
-                    m->finfo.reserved[1] == 0x5055) {
+                m->finfo.reserved[1] == 0x5055) {
                 dev->device.setUpdateRect = fb_setUpdateRect;
                 ALOGD("UPDATE_ON_DEMAND supported");
             }
@@ -895,43 +1015,3 @@
     }
     return status;
 }
-
-/* Copy a pmem buffer to the framebuffer */
-
-static void
-msm_copy_buffer(buffer_handle_t handle, int fd,
-                int width, int height, int format,
-                int x, int y, int w, int h)
-{
-    struct {
-        unsigned int count;
-        mdp_blit_req req;
-    } blit;
-    private_handle_t *priv = (private_handle_t*) handle;
-
-    memset(&blit, 0, sizeof(blit));
-    blit.count = 1;
-
-    blit.req.flags = 0;
-    blit.req.alpha = 0xff;
-    blit.req.transp_mask = 0xffffffff;
-
-    blit.req.src.width = width;
-    blit.req.src.height = height;
-    blit.req.src.offset = 0;
-    blit.req.src.memory_id = priv->fd;
-
-    blit.req.dst.width = width;
-    blit.req.dst.height = height;
-    blit.req.dst.offset = 0;
-    blit.req.dst.memory_id = fd;
-    blit.req.dst.format = format;
-
-    blit.req.src_rect.x = blit.req.dst_rect.x = x;
-    blit.req.src_rect.y = blit.req.dst_rect.y = y;
-    blit.req.src_rect.w = blit.req.dst_rect.w = w;
-    blit.req.src_rect.h = blit.req.dst_rect.h = h;
-
-    if (ioctl(fd, MSMFB_BLIT, &blit))
-        ALOGE("MSMFB_BLIT failed = %d", -errno);
-}
diff --git a/libgralloc/gpu.cpp b/libgralloc/gpu.cpp
old mode 100755
new mode 100644
index 77ad174..0ec8d73
--- a/libgralloc/gpu.cpp
+++ b/libgralloc/gpu.cpp
@@ -32,34 +32,12 @@
 using android::sp;
 
 gpu_context_t::gpu_context_t(const private_module_t* module,
-        sp<IAllocController> alloc_ctrl ) :
+                             sp<IAllocController> alloc_ctrl ) :
     mAllocCtrl(alloc_ctrl)
 {
     // Zero out the alloc_device_t
     memset(static_cast<alloc_device_t*>(this), 0, sizeof(alloc_device_t));
 
-    char property[PROPERTY_VALUE_MAX];
-    if (property_get("debug.sf.hw", property, NULL) > 0) {
-        if(atoi(property) == 0) {
-            //debug.sf.hw = 0
-            compositionType = CPU_COMPOSITION;
-        } else { //debug.sf.hw = 1
-            // Get the composition type
-            property_get("debug.composition.type", property, NULL);
-            if (property == NULL) {
-                compositionType = GPU_COMPOSITION;
-            } else if ((strncmp(property, "mdp", 3)) == 0) {
-                compositionType = MDP_COMPOSITION;
-            } else if ((strncmp(property, "c2d", 3)) == 0) {
-                compositionType = C2D_COMPOSITION;
-            } else {
-                compositionType = GPU_COMPOSITION;
-            }
-        }
-    } else { //debug.sf.hw is not set. Use cpu composition
-        compositionType = CPU_COMPOSITION;
-    }
-
     // Initialize the procs
     common.tag     = HARDWARE_DEVICE_TAG;
     common.version = 0;
@@ -74,7 +52,7 @@
 }
 
 int gpu_context_t::gralloc_alloc_framebuffer_locked(size_t size, int usage,
-        buffer_handle_t* pHandle)
+                                                    buffer_handle_t* pHandle)
 {
     private_module_t* m = reinterpret_cast<private_module_t*>(common.module);
 
@@ -136,7 +114,7 @@
 
 
 int gpu_context_t::gralloc_alloc_framebuffer(size_t size, int usage,
-        buffer_handle_t* pHandle)
+                                             buffer_handle_t* pHandle)
 {
     private_module_t* m = reinterpret_cast<private_module_t*>(common.module);
     pthread_mutex_lock(&m->lock);
@@ -162,7 +140,7 @@
     else
         data.align = getpagesize();
     data.pHandle = (unsigned int) pHandle;
-    err = mAllocCtrl->allocate(data, usage, compositionType);
+    err = mAllocCtrl->allocate(data, usage, 0);
 
     if (usage & GRALLOC_USAGE_PRIVATE_UNSYNCHRONIZED) {
         flags |= private_handle_t::PRIV_FLAGS_UNSYNCHRONIZED;
@@ -179,7 +157,8 @@
     if (err == 0) {
         flags |= data.allocType;
         private_handle_t* hnd = new private_handle_t(data.fd, size, flags,
-                bufferType, format, width, height);
+                                                     bufferType, format, width,
+                                                     height);
 
         hnd->offset = data.offset;
         hnd->base = int(data.base) + data.offset;
@@ -217,7 +196,8 @@
 }
 
 int gpu_context_t::alloc_impl(int w, int h, int format, int usage,
-        buffer_handle_t* pHandle, int* pStride, size_t bufferSize) {
+                              buffer_handle_t* pHandle, int* pStride,
+                              size_t bufferSize) {
     if (!pHandle || !pStride)
         return -EINVAL;
 
@@ -234,8 +214,9 @@
     // All buffers marked as protected or for external
     // display need to go to overlay
     if ((usage & GRALLOC_USAGE_EXTERNAL_DISP) ||
-        (usage & GRALLOC_USAGE_PROTECTED)) {
-            bufferType = BUFFER_TYPE_VIDEO;
+        (usage & GRALLOC_USAGE_PROTECTED) ||
+        (usage & GRALLOC_USAGE_PRIVATE_CP_BUFFER)) {
+        bufferType = BUFFER_TYPE_VIDEO;
     }
     int err;
     if (usage & GRALLOC_USAGE_HW_FB) {
@@ -268,12 +249,12 @@
         int index = (hnd->base - m->framebuffer->base) / bufferSize;
         m->bufferMask &= ~(1<<index);
     } else {
+        terminateBuffer(&m->base, const_cast<private_handle_t*>(hnd));
         sp<IMemAlloc> memalloc = mAllocCtrl->getAllocator(hnd->flags);
         int err = memalloc->free_buffer((void*)hnd->base, (size_t) hnd->size,
-                hnd->offset, hnd->fd);
+                                        hnd->offset, hnd->fd);
         if(err)
             return err;
-        terminateBuffer(&m->base, const_cast<private_handle_t*>(hnd));
     }
 
     // Release the genlock
@@ -287,7 +268,8 @@
 }
 
 int gpu_context_t::gralloc_alloc(alloc_device_t* dev, int w, int h, int format,
-        int usage, buffer_handle_t* pHandle, int* pStride)
+                                 int usage, buffer_handle_t* pHandle,
+                                 int* pStride)
 {
     if (!dev) {
         return -EINVAL;
@@ -295,8 +277,10 @@
     gpu_context_t* gpu = reinterpret_cast<gpu_context_t*>(dev);
     return gpu->alloc_impl(w, h, format, usage, pHandle, pStride, 0);
 }
-int gpu_context_t::gralloc_alloc_size(alloc_device_t* dev, int w, int h, int format,
-        int usage, buffer_handle_t* pHandle, int* pStride, int bufferSize)
+int gpu_context_t::gralloc_alloc_size(alloc_device_t* dev, int w, int h,
+                                      int format, int usage,
+                                      buffer_handle_t* pHandle, int* pStride,
+                                      int bufferSize)
 {
     if (!dev) {
         return -EINVAL;
@@ -307,7 +291,7 @@
 
 
 int gpu_context_t::gralloc_free(alloc_device_t* dev,
-        buffer_handle_t handle)
+                                buffer_handle_t handle)
 {
     if (private_handle_t::validate(handle) < 0)
         return -EINVAL;
diff --git a/libgralloc/gpu.h b/libgralloc/gpu.h
index 301c411..487f4d1 100644
--- a/libgralloc/gpu.h
+++ b/libgralloc/gpu.h
@@ -1,6 +1,6 @@
 /*
  * Copyright (C) 2008 The Android Open Source Project
- * Copyright (c) 2011 Code Aurora Forum. All rights reserved.
+ * Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -28,54 +28,51 @@
 #include <utils/RefBase.h>
 
 #include "gralloc_priv.h"
+#include <fb_priv.h>
 
 namespace gralloc {
-    class IAllocController;
-    class gpu_context_t : public alloc_device_t {
-        public:
-            gpu_context_t(const private_module_t* module,
-                          android::sp<IAllocController>alloc_ctrl);
+class IAllocController;
+class gpu_context_t : public alloc_device_t {
+    public:
+    gpu_context_t(const private_module_t* module,
+                  android::sp<IAllocController>alloc_ctrl);
 
-            int gralloc_alloc_framebuffer_locked(size_t size, int usage,
-                                                 buffer_handle_t* pHandle);
+    int gralloc_alloc_framebuffer_locked(size_t size, int usage,
+                                         buffer_handle_t* pHandle);
 
-            int gralloc_alloc_framebuffer(size_t size, int usage,
-                                          buffer_handle_t* pHandle);
+    int gralloc_alloc_framebuffer(size_t size, int usage,
+                                  buffer_handle_t* pHandle);
 
-            int gralloc_alloc_buffer(size_t size, int usage,
-                                     buffer_handle_t* pHandle,
-                                     int bufferType, int format,
-                                     int width, int height);
+    int gralloc_alloc_buffer(size_t size, int usage,
+                             buffer_handle_t* pHandle,
+                             int bufferType, int format,
+                             int width, int height);
 
-            int free_impl(private_handle_t const* hnd);
+    int free_impl(private_handle_t const* hnd);
 
-            int alloc_impl(int w, int h, int format, int usage,
-                           buffer_handle_t* pHandle, int* pStride,
-                           size_t bufferSize = 0);
+    int alloc_impl(int w, int h, int format, int usage,
+                   buffer_handle_t* pHandle, int* pStride,
+                   size_t bufferSize = 0);
 
-            static int gralloc_alloc(alloc_device_t* dev, int w, int h,
-                                     int format, int usage,
-                                     buffer_handle_t* pHandle,
-                                     int* pStride);
+    static int gralloc_alloc(alloc_device_t* dev, int w, int h,
+                             int format, int usage,
+                             buffer_handle_t* pHandle,
+                             int* pStride);
 
-            static int gralloc_free(alloc_device_t* dev, buffer_handle_t handle);
+    static int gralloc_free(alloc_device_t* dev, buffer_handle_t handle);
 
-            static int gralloc_alloc_size(alloc_device_t* dev,
-                                          int w, int h, int format,
-                                          int usage, buffer_handle_t* pHandle,
-                                          int* pStride, int bufferSize);
+    static int gralloc_alloc_size(alloc_device_t* dev,
+                                  int w, int h, int format,
+                                  int usage, buffer_handle_t* pHandle,
+                                  int* pStride, int bufferSize);
 
-            static int gralloc_close(struct hw_device_t *dev);
+    static int gralloc_close(struct hw_device_t *dev);
 
-            int get_composition_type() const { return compositionType; }
-
-
-        private:
-            android::sp<IAllocController> mAllocCtrl;
-            int compositionType;
-            void getGrallocInformationFromFormat(int inputFormat,
-                                                 int *colorFormat,
-                                                 int *bufferType);
-    };
+    private:
+    android::sp<IAllocController> mAllocCtrl;
+    void getGrallocInformationFromFormat(int inputFormat,
+                                         int *colorFormat,
+                                         int *bufferType);
+};
 }
 #endif  // GRALLOC_GPU_H
diff --git a/libgralloc/gr.h b/libgralloc/gr.h
index cc36d9a..b330da9 100644
--- a/libgralloc/gr.h
+++ b/libgralloc/gr.h
@@ -1,6 +1,6 @@
 /*
  * Copyright (C) 2008 The Android Open Source Project
- * Copyright (c) 2011 Code Aurora Forum. All rights reserved.
+ * Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -51,11 +51,11 @@
 int mapFrameBufferLocked(struct private_module_t* module);
 int terminateBuffer(gralloc_module_t const* module, private_handle_t* hnd);
 size_t getBufferSizeAndDimensions(int width, int height, int format,
-                        int& alignedw, int &alignedh);
+                                  int& alignedw, int &alignedh);
 
 int decideBufferHandlingMechanism(int format, const char *compositionUsed,
-                                   int hasBlitEngine, int *needConversion,
-                                   int *useBufferDirectly);
+                                  int hasBlitEngine, int *needConversion,
+                                  int *useBufferDirectly);
 
 // Allocate buffer from width, height, format into a private_handle_t
 // It is the responsibility of the caller to free the buffer
@@ -66,10 +66,10 @@
 
 class Locker {
     pthread_mutex_t mutex;
-public:
+    public:
     class Autolock {
         Locker& locker;
-    public:
+        public:
         inline Autolock(Locker& locker) : locker(locker) {  locker.lock(); }
         inline ~Autolock() { locker.unlock(); }
     };
diff --git a/libgralloc/gralloc.cpp b/libgralloc/gralloc.cpp
index a98baf8..cf57fee 100644
--- a/libgralloc/gralloc.cpp
+++ b/libgralloc/gralloc.cpp
@@ -1,6 +1,6 @@
 /*
  * Copyright (C) 2008, The Android Open Source Project
- * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
+ * Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -36,71 +36,71 @@
 using android::sp;
 
 int fb_device_open(const hw_module_t* module, const char* name,
-        hw_device_t** device);
+                   hw_device_t** device);
 
 static int gralloc_device_open(const hw_module_t* module, const char* name,
-        hw_device_t** device);
+                               hw_device_t** device);
 
 extern int gralloc_lock(gralloc_module_t const* module,
-        buffer_handle_t handle, int usage,
-        int l, int t, int w, int h,
-        void** vaddr);
+                        buffer_handle_t handle, int usage,
+                        int l, int t, int w, int h,
+                        void** vaddr);
 
 extern int gralloc_unlock(gralloc_module_t const* module,
-        buffer_handle_t handle);
+                          buffer_handle_t handle);
 
 extern int gralloc_register_buffer(gralloc_module_t const* module,
-        buffer_handle_t handle);
+                                   buffer_handle_t handle);
 
 extern int gralloc_unregister_buffer(gralloc_module_t const* module,
-        buffer_handle_t handle);
+                                     buffer_handle_t handle);
 
 extern int gralloc_perform(struct gralloc_module_t const* module,
-        int operation, ... );
+                           int operation, ... );
 
 // HAL module methods
 static struct hw_module_methods_t gralloc_module_methods = {
-    open: gralloc_device_open
+open: gralloc_device_open
 };
 
 // HAL module initialize
 struct private_module_t HAL_MODULE_INFO_SYM = {
-    base: {
-        common: {
-            tag: HARDWARE_MODULE_TAG,
-            version_major: 1,
-            version_minor: 0,
-            id: GRALLOC_HARDWARE_MODULE_ID,
-            name: "Graphics Memory Allocator Module",
-            author: "The Android Open Source Project",
-            methods: &gralloc_module_methods,
-            dso: 0,
-            reserved: {0},
-        },
-        registerBuffer: gralloc_register_buffer,
-        unregisterBuffer: gralloc_unregister_buffer,
-        lock: gralloc_lock,
-        unlock: gralloc_unlock,
-        perform: gralloc_perform,
-        reserved_proc: {0},
-    },
-    framebuffer: 0,
-    fbFormat: 0,
-    flags: 0,
-    numBuffers: 0,
-    bufferMask: 0,
-    lock: PTHREAD_MUTEX_INITIALIZER,
-    currentBuffer: 0,
+base: {
+    common: {
+        tag: HARDWARE_MODULE_TAG,
+             version_major: 1,
+             version_minor: 0,
+             id: GRALLOC_HARDWARE_MODULE_ID,
+             name: "Graphics Memory Allocator Module",
+             author: "The Android Open Source Project",
+             methods: &gralloc_module_methods,
+             dso: 0,
+             reserved: {0},
+            },
+    registerBuffer: gralloc_register_buffer,
+    unregisterBuffer: gralloc_unregister_buffer,
+    lock: gralloc_lock,
+    unlock: gralloc_unlock,
+    perform: gralloc_perform,
+    reserved_proc: {0},
+      },
+framebuffer: 0,
+fbFormat: 0,
+flags: 0,
+numBuffers: 0,
+bufferMask: 0,
+lock: PTHREAD_MUTEX_INITIALIZER,
+currentBuffer: 0,
 };
 
 // Open Gralloc device
 int gralloc_device_open(const hw_module_t* module, const char* name,
-        hw_device_t** device)
+                        hw_device_t** device)
 {
     int status = -EINVAL;
     if (!strcmp(name, GRALLOC_HARDWARE_GPU0)) {
         const private_module_t* m = reinterpret_cast<const private_module_t*>(
-                module);
+            module);
         gpu_context_t *dev;
         sp<IAllocController> alloc_ctrl = IAllocController::getInstance(true);
         dev = new gpu_context_t(m, alloc_ctrl);
diff --git a/libgralloc/gralloc_priv.h b/libgralloc/gralloc_priv.h
index 0679621..846a611 100644
--- a/libgralloc/gralloc_priv.h
+++ b/libgralloc/gralloc_priv.h
@@ -28,13 +28,6 @@
 
 #include <cutils/native_handle.h>
 
-#include <linux/fb.h>
-
-#if defined(__cplusplus) && defined(HDMI_DUAL_DISPLAY)
-#include "overlayLib.h"
-using namespace overlay;
-#endif
-
 #include <cutils/log.h>
 
 enum {
@@ -87,6 +80,14 @@
      * other EXTERNAL_ONLY buffers are available. Used during suspend.
      */
     GRALLOC_USAGE_EXTERNAL_BLOCK          =       0x00020000,
+
+    /* Use this flag to request content protected buffers. Please note
+     * that this flag is different from the GRALLOC_USAGE_PROTECTED flag
+     * which can be used for buffers that are not secured for DRM
+     * but still need to be protected from screen captures
+     * 0x00040000 is reserved and these values are subject to change.
+     */
+    GRALLOC_USAGE_PRIVATE_CP_BUFFER       =       0x00080000,
 };
 
 enum {
@@ -96,107 +97,12 @@
 };
 
 
-enum {
-    GPU_COMPOSITION,
-    C2D_COMPOSITION,
-    MDP_COMPOSITION,
-    CPU_COMPOSITION,
-};
-
-/* numbers of max buffers for page flipping */
-#define NUM_FRAMEBUFFERS_MIN 2
-#define NUM_FRAMEBUFFERS_MAX 3
-
-/* number of default bufers for page flipping */
-#define NUM_DEF_FRAME_BUFFERS 2
-#define NO_SURFACEFLINGER_SWAPINTERVAL
 #define INTERLACE_MASK 0x80
 #define S3D_FORMAT_MASK 0xFF000
-#define COLOR_FORMAT(x) (x & 0xFFF) // Max range for colorFormats is 0 - FFF
 #define DEVICE_PMEM "/dev/pmem"
 #define DEVICE_PMEM_ADSP "/dev/pmem_adsp"
 #define DEVICE_PMEM_SMIPOOL "/dev/pmem_smipool"
 /*****************************************************************************/
-#ifdef __cplusplus
-
-//XXX: Remove framebuffer specific classes and defines to a different header
-template <class T>
-struct Node
-{
-    T data;
-    Node<T> *next;
-};
-
-template <class T>
-class Queue
-{
-public:
-    Queue(): front(NULL), back(NULL), len(0) {dummy = new T;}
-    ~Queue()
-    {
-        clear();
-        delete dummy;
-    }
-    void push(const T& item)   //add an item to the back of the queue
-    {
-        if(len != 0) {         //if the queue is not empty
-            back->next = new Node<T>; //create a new node
-            back = back->next; //set the new node as the back node
-            back->data = item;
-            back->next = NULL;
-        } else {
-            back = new Node<T>;
-            back->data = item;
-            back->next = NULL;
-            front = back;
-       }
-       len++;
-    }
-    void pop()                 //remove the first item from the queue
-    {
-        if (isEmpty())
-            return;            //if the queue is empty, no node to dequeue
-        T item = front->data;
-        Node<T> *tmp = front;
-        front = front->next;
-        delete tmp;
-        if(front == NULL)      //if the queue is empty, update the back pointer
-            back = NULL;
-        len--;
-        return;
-    }
-    T& getHeadValue() const    //return the value of the first item in the queue
-    {                          //without modification to the structure
-        if (isEmpty()) {
-            ALOGE("Error can't get head of empty queue");
-            return *dummy;
-        }
-        return front->data;
-    }
-
-    bool isEmpty() const       //returns true if no elements are in the queue
-    {
-        return (front == NULL);
-    }
-
-    size_t size() const        //returns the amount of elements in the queue
-    {
-        return len;
-    }
-
-private:
-    Node<T> *front;
-    Node<T> *back;
-    size_t len;
-    void clear()
-    {
-        while (!isEmpty())
-            pop();
-    }
-    T *dummy;
-};
-#endif
-
 enum {
     /* OEM specific HAL formats */
     HAL_PIXEL_FORMAT_NV12_ENCODEABLE  = 0x102,
@@ -206,6 +112,8 @@
     HAL_PIXEL_FORMAT_YCrCb_422_SP           = 0x10B,
     HAL_PIXEL_FORMAT_R_8                    = 0x10D,
     HAL_PIXEL_FORMAT_RG_88                  = 0x10E,
+    HAL_PIXEL_FORMAT_YCbCr_444_SP           = 0x10F,
+    HAL_PIXEL_FORMAT_YCrCb_444_SP           = 0x110,
     HAL_PIXEL_FORMAT_INTERLACE              = 0x180,
 
 };
@@ -224,89 +132,8 @@
 };
 
 enum {
-	BUFFER_TYPE_UI = 0,
-	BUFFER_TYPE_VIDEO
-};
-
-#if defined(HDMI_DUAL_DISPLAY)
-enum hdmi_mirroring_state {
-    HDMI_NO_MIRRORING,
-    HDMI_UI_MIRRORING,
-    HDMI_ORIGINAL_RESOLUTION_MIRRORING
-};
-#endif
-/*****************************************************************************/
-
-struct private_module_t;
-struct private_handle_t;
-struct PmemAllocator;
-
-struct qbuf_t {
-    buffer_handle_t buf;
-    int  idx;
-};
-
-enum buf_state {
-    SUB,
-    REF,
-    AVL
-};
-
-struct avail_t {
-    pthread_mutex_t lock;
-    pthread_cond_t cond;
-#ifdef __cplusplus
-    bool is_avail;
-    buf_state state;
-#endif
-};
-
-struct private_module_t {
-    gralloc_module_t base;
-
-    struct private_handle_t* framebuffer;
-    uint32_t fbFormat;
-    uint32_t flags;
-    uint32_t numBuffers;
-    uint32_t bufferMask;
-    pthread_mutex_t lock;
-    buffer_handle_t currentBuffer;
-
-    struct fb_var_screeninfo info;
-    struct fb_fix_screeninfo finfo;
-    float xdpi;
-    float ydpi;
-    float fps;
-    int swapInterval;
-#ifdef __cplusplus
-    Queue<struct qbuf_t> disp; // non-empty when buffer is ready for display
-#endif
-    int currentIdx;
-    struct avail_t avail[NUM_FRAMEBUFFERS_MAX];
-    pthread_mutex_t qlock;
-    pthread_cond_t qpost;
-
-    enum {
-        // flag to indicate we'll post this buffer
-        PRIV_USAGE_LOCKED_FOR_POST = 0x80000000,
-        PRIV_MIN_SWAP_INTERVAL = 0,
-        PRIV_MAX_SWAP_INTERVAL = 1,
-    };
-#if defined(__cplusplus) && defined(HDMI_DUAL_DISPLAY)
-    Overlay* pobjOverlay;
-    int orientation;
-    bool videoOverlay;
-    uint32_t currentOffset;
-    int enableHDMIOutput; // holds the type of external display
-    bool trueMirrorSupport;
-    bool exitHDMIUILoop;
-    float actionsafeWidthRatio;
-    float actionsafeHeightRatio;
-    bool hdmiStateChanged;
-    hdmi_mirroring_state hdmiMirroringState;
-    pthread_mutex_t overlayLock;
-    pthread_cond_t overlayPost;
-#endif
+    BUFFER_TYPE_UI = 0,
+    BUFFER_TYPE_VIDEO
 };
 
 /*****************************************************************************/
@@ -314,87 +141,114 @@
 #ifdef __cplusplus
 struct private_handle_t : public native_handle {
 #else
-struct private_handle_t {
-    native_handle_t nativeHandle;
+    struct private_handle_t {
+        native_handle_t nativeHandle;
 #endif
-    enum {
-        PRIV_FLAGS_FRAMEBUFFER    = 0x00000001,
-        PRIV_FLAGS_USES_PMEM      = 0x00000002,
-        PRIV_FLAGS_USES_PMEM_ADSP = 0x00000004,
-        PRIV_FLAGS_USES_ION       = 0x00000008,
-        PRIV_FLAGS_USES_ASHMEM    = 0x00000010,
-        PRIV_FLAGS_NEEDS_FLUSH    = 0x00000020,
-        PRIV_FLAGS_DO_NOT_FLUSH   = 0x00000040,
-        PRIV_FLAGS_SW_LOCK        = 0x00000080,
-        PRIV_FLAGS_NONCONTIGUOUS_MEM = 0x00000100,
-        PRIV_FLAGS_HWC_LOCK       = 0x00000200, // Set by HWC when storing the handle
-        PRIV_FLAGS_SECURE_BUFFER  = 0x00000400,
-        PRIV_FLAGS_UNSYNCHRONIZED = 0x00000800, // For explicit synchronization
-        PRIV_FLAGS_NOT_MAPPED     = 0x00001000, // Not mapped in userspace
-        PRIV_FLAGS_EXTERNAL_ONLY  = 0x00002000, // Display on external only
-        PRIV_FLAGS_EXTERNAL_BLOCK = 0x00004000, // Display only this buffer on external
-    };
+        enum {
+            PRIV_FLAGS_FRAMEBUFFER        = 0x00000001,
+            PRIV_FLAGS_USES_PMEM          = 0x00000002,
+            PRIV_FLAGS_USES_PMEM_ADSP     = 0x00000004,
+            PRIV_FLAGS_USES_ION           = 0x00000008,
+            PRIV_FLAGS_USES_ASHMEM        = 0x00000010,
+            PRIV_FLAGS_NEEDS_FLUSH        = 0x00000020,
+            PRIV_FLAGS_DO_NOT_FLUSH       = 0x00000040,
+            PRIV_FLAGS_SW_LOCK            = 0x00000080,
+            PRIV_FLAGS_NONCONTIGUOUS_MEM  = 0x00000100,
+            // Set by HWC when storing the handle
+            PRIV_FLAGS_HWC_LOCK           = 0x00000200,
+            PRIV_FLAGS_SECURE_BUFFER      = 0x00000400,
+            // For explicit synchronization
+            PRIV_FLAGS_UNSYNCHRONIZED     = 0x00000800,
+            // Not mapped in userspace
+            PRIV_FLAGS_NOT_MAPPED         = 0x00001000,
+            // Display on external only
+            PRIV_FLAGS_EXTERNAL_ONLY      = 0x00002000,
+            // Display only this buffer on external
+            PRIV_FLAGS_EXTERNAL_BLOCK     = 0x00004000,
+        };
 
-    // file-descriptors
-    int     fd;
-    int     genlockHandle; // genlock handle to be dup'd by the binder
-    // ints
-    int     magic;
-    int     flags;
-    int     size;
-    int     offset;
-    int     bufferType;
-
-    // FIXME: the attributes below should be out-of-line
-    int     base;
-    int     gpuaddr; // The gpu address mapped into the mmu. If using ashmem, set to 0 They don't care
-    int     pid;
-    int     format;
-    int     width;
-    int     height;
-    int     genlockPrivFd; // local fd of the genlock device.
+        // file-descriptors
+        int     fd;
+        // genlock handle to be dup'd by the binder
+        int     genlockHandle;
+        // ints
+        int     magic;
+        int     flags;
+        int     size;
+        int     offset;
+        int     bufferType;
+        int     base;
+        // The gpu address mapped into the mmu.
+        // If using ashmem, set to 0, they don't care
+        int     gpuaddr;
+        int     pid;
+        int     format;
+        int     width;
+        int     height;
+        // local fd of the genlock device.
+        int     genlockPrivFd;
 
 #ifdef __cplusplus
-    static const int sNumInts = 12;
-    static const int sNumFds = 2;
-    static const int sMagic = 'gmsm';
+        static const int sNumInts = 12;
+        static const int sNumFds = 2;
+        static const int sMagic = 'gmsm';
 
-    private_handle_t(int fd, int size, int flags, int bufferType, int format, int width, int height) :
-        fd(fd), genlockHandle(-1), magic(sMagic), flags(flags), size(size), offset(0),
-        bufferType(bufferType), base(0), gpuaddr(0), pid(getpid()), format(format),
-        width(width), height(height), genlockPrivFd(-1)
-    {
-        version = sizeof(native_handle);
-        numInts = sNumInts;
-        numFds = sNumFds;
-    }
-    ~private_handle_t() {
-        magic = 0;
-    }
+        private_handle_t(int fd, int size, int flags, int bufferType,
+                         int format,int width, int height) :
+            fd(fd), genlockHandle(-1), magic(sMagic),
+            flags(flags), size(size), offset(0),
+            bufferType(bufferType), base(0), gpuaddr(0),
+            pid(getpid()), format(format),
+            width(width), height(height), genlockPrivFd(-1)
+        {
+            version = sizeof(native_handle);
+            numInts = sNumInts;
+            numFds = sNumFds;
+        }
+        ~private_handle_t() {
+            magic = 0;
+        }
 
-    bool usesPhysicallyContiguousMemory() {
-        return (flags & PRIV_FLAGS_USES_PMEM) != 0;
-    }
+        bool usesPhysicallyContiguousMemory() {
+            return (flags & PRIV_FLAGS_USES_PMEM) != 0;
+        }
 
-    static int validate(const native_handle* h) {
-        const private_handle_t* hnd = (const private_handle_t*)h;
-        if (!h || h->version != sizeof(native_handle) ||
+        static int validate(const native_handle* h) {
+            const private_handle_t* hnd = (const private_handle_t*)h;
+            if (!h || h->version != sizeof(native_handle) ||
                 h->numInts != sNumInts || h->numFds != sNumFds ||
                 hnd->magic != sMagic)
-        {
-            ALOGE("invalid gralloc handle (at %p)", h);
-            return -EINVAL;
+            {
+                ALOGD("Invalid gralloc handle (at %p): "
+                      "ver(%d/%d) ints(%d/%d) fds(%d/%d) magic(%c%c%c%c/%c%c%c%c)",
+                      h,
+                      h ? h->version : -1, sizeof(native_handle),
+                      h ? h->numInts : -1, sNumInts,
+                      h ? h->numFds : -1, sNumFds,
+                      hnd ? (((hnd->magic >> 24) & 0xFF)?
+                             ((hnd->magic >> 24) & 0xFF) : '-') : '?',
+                      hnd ? (((hnd->magic >> 16) & 0xFF)?
+                             ((hnd->magic >> 16) & 0xFF) : '-') : '?',
+                      hnd ? (((hnd->magic >> 8) & 0xFF)?
+                             ((hnd->magic >> 8) & 0xFF) : '-') : '?',
+                      hnd ? (((hnd->magic >> 0) & 0xFF)?
+                             ((hnd->magic >> 0) & 0xFF) : '-') : '?',
+                      (sMagic >> 24) & 0xFF,
+                      (sMagic >> 16) & 0xFF,
+                      (sMagic >> 8) & 0xFF,
+                      (sMagic >> 0) & 0xFF);
+                return -EINVAL;
+            }
+            return 0;
         }
-        return 0;
-    }
 
-    static private_handle_t* dynamicCast(const native_handle* in) {
-        if (validate(in) == 0) {
-            return (private_handle_t*) in;
+        static private_handle_t* dynamicCast(const native_handle* in) {
+            if (validate(in) == 0) {
+                return (private_handle_t*) in;
+            }
+            return NULL;
         }
-        return NULL;
-    }
 #endif
-};
+    };
 
 #endif /* GRALLOC_PRIV_H_ */
diff --git a/libgralloc/ionalloc.cpp b/libgralloc/ionalloc.cpp
index 9ff0a5e..7c8fbf4 100644
--- a/libgralloc/ionalloc.cpp
+++ b/libgralloc/ionalloc.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
+ * Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -48,7 +48,7 @@
 
     if(mIonFd < 0 ) {
         ALOGE("%s: Failed to open ion device - %s",
-                __FUNCTION__, strerror(errno));
+              __FUNCTION__, strerror(errno));
         mIonFd = FD_INIT;
         return -errno;
     }
@@ -64,6 +64,7 @@
 
 int IonAlloc::alloc_buffer(alloc_data& data)
 {
+    Locker::Autolock _l(mLock);
     int err = 0;
     int ionSyncFd = FD_INIT;
     int iFd = FD_INIT;
@@ -84,12 +85,11 @@
     if(data.uncached) {
         // Use the sync FD to alloc and map
         // when we need uncached memory
-        // FIX: О–DSYNC defined to open uncached - add that in kernel
-	//ionSyncFd = open(ION_DEVICE, O_RDONLY|O_DSYNC);
-        ionSyncFd = open(ION_DEVICE, O_RDONLY);
+        // XXX: Change O_SYNC to O_DSYNC when available in bionic
+        ionSyncFd = open(ION_DEVICE, O_RDONLY|O_SYNC);
         if(ionSyncFd < 0) {
             ALOGE("%s: Failed to open ion device - %s",
-                    __FUNCTION__, strerror(errno));
+                  __FUNCTION__, strerror(errno));
             return -errno;
         }
         iFd = ionSyncFd;
@@ -111,7 +111,7 @@
     if(ioctl(iFd, ION_IOC_MAP, &fd_data)) {
         err = -errno;
         ALOGE("%s: ION_IOC_MAP failed with error - %s",
-                __FUNCTION__, strerror(errno));
+              __FUNCTION__, strerror(errno));
         ioctl(mIonFd, ION_IOC_FREE, &handle_data);
         if(ionSyncFd >= 0)
             close(ionSyncFd);
@@ -119,15 +119,15 @@
         return err;
     }
 
-    //if(!(data.flags & ION_SECURE) &&
-    if(!(data.allocType & private_handle_t::PRIV_FLAGS_NOT_MAPPED)) {
+    if(!(data.flags & ION_SECURE) &&
+       !(data.allocType & private_handle_t::PRIV_FLAGS_NOT_MAPPED)) {
 
         base = mmap(0, ionAllocData.len, PROT_READ|PROT_WRITE,
-                                MAP_SHARED, fd_data.fd, 0);
+                    MAP_SHARED, fd_data.fd, 0);
         if(base == MAP_FAILED) {
             err = -errno;
             ALOGE("%s: Failed to map the allocated memory: %s",
-                                    __FUNCTION__, strerror(errno));
+                  __FUNCTION__, strerror(errno));
             ioctl(mIonFd, ION_IOC_FREE, &handle_data);
             ionSyncFd = FD_INIT;
             return err;
@@ -146,15 +146,16 @@
     data.fd = fd_data.fd;
     ioctl(mIonFd, ION_IOC_FREE, &handle_data);
     ALOGD("ion: Allocated buffer base:%p size:%d fd:%d",
-                            data.base, ionAllocData.len, data.fd);
+          data.base, ionAllocData.len, data.fd);
     return 0;
 }
 
 
 int IonAlloc::free_buffer(void* base, size_t size, int offset, int fd)
 {
+    Locker::Autolock _l(mLock);
     ALOGD("ion: Freeing buffer base:%p size:%d fd:%d",
-            base, size, fd);
+          base, size, fd);
     int err = 0;
     err = open_device();
     if (err)
@@ -177,15 +178,15 @@
         return err;
 
     base = mmap(0, size, PROT_READ| PROT_WRITE,
-            MAP_SHARED, fd, 0);
+                MAP_SHARED, fd, 0);
     *pBase = base;
     if(base == MAP_FAILED) {
         err = -errno;
         ALOGD("ion: Failed to map memory in the client: %s",
-                                strerror(errno));
+              strerror(errno));
     } else {
         ALOGD("ion: Mapped buffer base:%p size:%d offset:%d fd:%d",
-                                base, size, offset, fd);
+              base, size, offset, fd);
     }
     return err;
 }
@@ -197,7 +198,7 @@
     if(munmap(base, size)) {
         err = -errno;
         ALOGE("ion: Failed to unmap memory at %p : %s",
-                 base, strerror(errno));
+              base, strerror(errno));
     }
     return err;
 
@@ -218,7 +219,7 @@
     if (ioctl(mIonFd, ION_IOC_IMPORT, &fd_data)) {
         err = -errno;
         ALOGE("%s: ION_IOC_IMPORT failed with error - %s",
-                __FUNCTION__, strerror(errno));
+              __FUNCTION__, strerror(errno));
         return err;
     }
 
@@ -230,7 +231,7 @@
     if(ioctl(mIonFd, ION_IOC_CLEAN_INV_CACHES, &flush_data)) {
         err = -errno;
         ALOGE("%s: ION_IOC_CLEAN_INV_CACHES failed with error - %s",
-                __FUNCTION__, strerror(errno));
+              __FUNCTION__, strerror(errno));
         ioctl(mIonFd, ION_IOC_FREE, &handle_data);
         return err;
     }
diff --git a/libgralloc/ionalloc.h b/libgralloc/ionalloc.h
index be26cd7..083f106 100644
--- a/libgralloc/ionalloc.h
+++ b/libgralloc/ionalloc.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
+ * Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -31,39 +31,44 @@
 #define GRALLOC_IONALLOC_H
 
 #include "memalloc.h"
+#include "gr.h"
+//#include <linux/ion.h>
+//XXX: Move to bionic
 #include "ion_msm.h"
 
 namespace gralloc {
 
-    class IonAlloc : public IMemAlloc  {
+class IonAlloc : public IMemAlloc  {
 
-        public:
-            virtual int alloc_buffer(alloc_data& data);
+    public:
+    virtual int alloc_buffer(alloc_data& data);
 
-            virtual int free_buffer(void *base, size_t size,
-                    int offset, int fd);
+    virtual int free_buffer(void *base, size_t size,
+                            int offset, int fd);
 
-            virtual int map_buffer(void **pBase, size_t size,
-                    int offset, int fd);
+    virtual int map_buffer(void **pBase, size_t size,
+                           int offset, int fd);
 
-            virtual int unmap_buffer(void *base, size_t size,
-                    int offset);
+    virtual int unmap_buffer(void *base, size_t size,
+                             int offset);
 
-            virtual int clean_buffer(void*base, size_t size,
-                    int offset, int fd);
+    virtual int clean_buffer(void*base, size_t size,
+                             int offset, int fd);
 
-            IonAlloc() { mIonFd = FD_INIT; }
+    IonAlloc() { mIonFd = FD_INIT; }
 
-            ~IonAlloc() { close_device(); }
+    ~IonAlloc() { close_device(); }
 
-        private:
-            int mIonFd;
+    private:
+    int mIonFd;
 
-            int open_device();
+    int open_device();
 
-            void close_device();
+    void close_device();
 
-    };
+    mutable Locker mLock;
+
+};
 
 }
 
diff --git a/libgralloc/mapper.cpp b/libgralloc/mapper.cpp
old mode 100755
new mode 100644
index c7ee7d4..4249f3f
--- a/libgralloc/mapper.cpp
+++ b/libgralloc/mapper.cpp
@@ -1,6 +1,6 @@
 /*
  * Copyright (C) 2008 The Android Open Source Project
- * Copyright (c) 2011 Code Aurora Forum. All rights reserved.
+ * Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -58,8 +58,8 @@
 }
 
 static int gralloc_map(gralloc_module_t const* module,
-        buffer_handle_t handle,
-        void** vaddr)
+                       buffer_handle_t handle,
+                       void** vaddr)
 {
     private_handle_t* hnd = (private_handle_t*)handle;
     void *mappedAddress;
@@ -68,22 +68,22 @@
         size_t size = hnd->size;
         sp<IMemAlloc> memalloc = getAllocator(hnd->flags) ;
         int err = memalloc->map_buffer(&mappedAddress, size,
-                hnd->offset, hnd->fd);
+                                       hnd->offset, hnd->fd);
         if(err) {
             ALOGE("Could not mmap handle %p, fd=%d (%s)",
-                    handle, hnd->fd, strerror(errno));
+                  handle, hnd->fd, strerror(errno));
             hnd->base = 0;
             return -errno;
         }
 
         if (mappedAddress == MAP_FAILED) {
             ALOGE("Could not mmap handle %p, fd=%d (%s)",
-                    handle, hnd->fd, strerror(errno));
+                  handle, hnd->fd, strerror(errno));
             hnd->base = 0;
             return -errno;
         }
         hnd->base = intptr_t(mappedAddress) + hnd->offset;
-        //ALOGD("gralloc_map() succeeded fd=%d, off=%d, size=%d, vaddr=%p",
+        //LOGD("gralloc_map() succeeded fd=%d, off=%d, size=%d, vaddr=%p",
         //        hnd->fd, hnd->offset, hnd->size, mappedAddress);
     }
     *vaddr = (void*)hnd->base;
@@ -91,7 +91,7 @@
 }
 
 static int gralloc_unmap(gralloc_module_t const* module,
-        buffer_handle_t handle)
+                         buffer_handle_t handle)
 {
     private_handle_t* hnd = (private_handle_t*)handle;
     if (!(hnd->flags & private_handle_t::PRIV_FLAGS_FRAMEBUFFER)) {
@@ -116,7 +116,7 @@
 /*****************************************************************************/
 
 int gralloc_register_buffer(gralloc_module_t const* module,
-        buffer_handle_t handle)
+                            buffer_handle_t handle)
 {
     if (private_handle_t::validate(handle) < 0)
         return -EINVAL;
@@ -164,7 +164,7 @@
 }
 
 int gralloc_unregister_buffer(gralloc_module_t const* module,
-        buffer_handle_t handle)
+                              buffer_handle_t handle)
 {
     if (private_handle_t::validate(handle) < 0)
         return -EINVAL;
@@ -195,7 +195,7 @@
 }
 
 int terminateBuffer(gralloc_module_t const* module,
-        private_handle_t* hnd)
+                    private_handle_t* hnd)
 {
     /*
      * If the buffer has been mapped during a lock operation, it's time
@@ -215,7 +215,8 @@
                 gralloc_unmap(module, hnd);
             }
         } else {
-            ALOGE("terminateBuffer: unmapping a non pmem/ashmem buffer flags = 0x%x", hnd->flags);
+            ALOGE("terminateBuffer: unmapping a non pmem/ashmem buffer flags = 0x%x",
+                  hnd->flags);
             gralloc_unmap(module, hnd);
         }
     }
@@ -224,9 +225,9 @@
 }
 
 int gralloc_lock(gralloc_module_t const* module,
-        buffer_handle_t handle, int usage,
-        int l, int t, int w, int h,
-        void** vaddr)
+                 buffer_handle_t handle, int usage,
+                 int l, int t, int w, int h,
+                 void** vaddr)
 {
     if (private_handle_t::validate(handle) < 0)
         return -EINVAL;
@@ -254,10 +255,10 @@
 
         int timeout = GENLOCK_MAX_TIMEOUT;
         if (GENLOCK_NO_ERROR != genlock_lock_buffer((native_handle_t *)handle,
-                                                   (genlock_lock_type)lockType,
-                                                   timeout)) {
+                                                    (genlock_lock_type)lockType,
+                                                    timeout)) {
             ALOGE("%s: genlock_lock_buffer (lockType=0x%x) failed", __FUNCTION__,
-                lockType);
+                  lockType);
             return -EINVAL;
         } else {
             // Mark this buffer as locked for SW read/write operation.
@@ -274,7 +275,7 @@
 }
 
 int gralloc_unlock(gralloc_module_t const* module,
-        buffer_handle_t handle)
+                   buffer_handle_t handle)
 {
     if (private_handle_t::validate(handle) < 0)
         return -EINVAL;
@@ -285,9 +286,9 @@
         int err;
         sp<IMemAlloc> memalloc = getAllocator(hnd->flags) ;
         err = memalloc->clean_buffer((void*)hnd->base,
-                hnd->size, hnd->offset, hnd->fd);
+                                     hnd->size, hnd->offset, hnd->fd);
         ALOGE_IF(err < 0, "cannot flush handle %p (offs=%x len=%x, flags = 0x%x) err=%s\n",
-                hnd, hnd->offset, hnd->size, hnd->flags, strerror(errno));
+                 hnd, hnd->offset, hnd->size, hnd->flags, strerror(errno));
         hnd->flags &= ~private_handle_t::PRIV_FLAGS_NEEDS_FLUSH;
     }
 
@@ -305,7 +306,7 @@
 /*****************************************************************************/
 
 int gralloc_perform(struct gralloc_module_t const* module,
-        int operation, ... )
+                    int operation, ... )
 {
     int res = -EINVAL;
     va_list args;
@@ -324,12 +325,12 @@
                 native_handle_t** handle = va_arg(args, native_handle_t**);
                 int memoryFlags = va_arg(args, int);
                 private_handle_t* hnd = (private_handle_t*)native_handle_create(
-                        private_handle_t::sNumFds, private_handle_t::sNumInts);
+                    private_handle_t::sNumFds, private_handle_t::sNumInts);
                 hnd->magic = private_handle_t::sMagic;
                 hnd->fd = fd;
                 unsigned int contigFlags = GRALLOC_USAGE_PRIVATE_ADSP_HEAP |
-                                  GRALLOC_USAGE_PRIVATE_UI_CONTIG_HEAP |
-                                  GRALLOC_USAGE_PRIVATE_SMI_HEAP;
+                    GRALLOC_USAGE_PRIVATE_UI_CONTIG_HEAP |
+                    GRALLOC_USAGE_PRIVATE_SMI_HEAP;
 
                 if (memoryFlags & contigFlags) {
                     // check if the buffer is a pmem buffer
@@ -338,7 +339,7 @@
                         hnd->flags =  private_handle_t::PRIV_FLAGS_USES_ION;
                     else
                         hnd->flags =  private_handle_t::PRIV_FLAGS_USES_PMEM |
-                                      private_handle_t::PRIV_FLAGS_DO_NOT_FLUSH;
+                            private_handle_t::PRIV_FLAGS_DO_NOT_FLUSH;
                 } else {
                     if (memoryFlags & GRALLOC_USAGE_PRIVATE_ION)
                         hnd->flags =  private_handle_t::PRIV_FLAGS_USES_ION;
diff --git a/libgralloc/memalloc.h b/libgralloc/memalloc.h
index 13a54e7..349078d 100644
--- a/libgralloc/memalloc.h
+++ b/libgralloc/memalloc.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
+ * Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -35,50 +35,50 @@
 
 namespace gralloc {
 
-    struct alloc_data {
-        void           *base;
-        int            fd;
-        int            offset;
-        size_t         size;
-        size_t         align;
-        unsigned int   pHandle;
-        bool           uncached;
-        unsigned int   flags;
-        int            allocType;
+struct alloc_data {
+    void           *base;
+    int            fd;
+    int            offset;
+    size_t         size;
+    size_t         align;
+    unsigned int   pHandle;
+    bool           uncached;
+    unsigned int   flags;
+    int            allocType;
+};
+
+class IMemAlloc : public android::RefBase {
+
+    public:
+    // Allocate buffer - fill in the alloc_data
+    // structure and pass it in. Mapped address
+    // and fd are returned in the alloc_data struct
+    virtual int alloc_buffer(alloc_data& data) = 0;
+
+    // Free buffer
+    virtual int free_buffer(void *base, size_t size,
+                            int offset, int fd) = 0;
+
+    // Map buffer
+    virtual int map_buffer(void **pBase, size_t size,
+                           int offset, int fd) = 0;
+
+    // Unmap buffer
+    virtual int unmap_buffer(void *base, size_t size,
+                             int offset) = 0;
+
+    // Clean and invalidate
+    virtual int clean_buffer(void *base, size_t size,
+                             int offset, int fd) = 0;
+
+    // Destructor
+    virtual ~IMemAlloc() {};
+
+    enum {
+        FD_INIT = -1,
     };
 
-    class IMemAlloc : public android::RefBase {
-
-        public:
-            // Allocate buffer - fill in the alloc_data
-            // structure and pass it in. Mapped address
-            // and fd are returned in the alloc_data struct
-            virtual int alloc_buffer(alloc_data& data) = 0;
-
-            // Free buffer
-            virtual int free_buffer(void *base, size_t size,
-                    int offset, int fd) = 0;
-
-            // Map buffer
-            virtual int map_buffer(void **pBase, size_t size,
-                    int offset, int fd) = 0;
-
-            // Unmap buffer
-            virtual int unmap_buffer(void *base, size_t size,
-                    int offset) = 0;
-
-            // Clean and invalidate
-            virtual int clean_buffer(void *base, size_t size,
-                    int offset, int fd) = 0;
-
-            // Destructor
-            virtual ~IMemAlloc() {};
-
-            enum {
-                FD_INIT = -1,
-            };
-
-    };
+};
 
 } // end gralloc namespace
 #endif // GRALLOC_MEMALLOC_H
diff --git a/libgralloc/pmem_bestfit_alloc.cpp b/libgralloc/pmem_bestfit_alloc.cpp
index e3875e9..3b91dec 100644
--- a/libgralloc/pmem_bestfit_alloc.cpp
+++ b/libgralloc/pmem_bestfit_alloc.cpp
@@ -1,6 +1,6 @@
 /*
  * Copyright (C) 2009 The Android Open Source Project
- * Copyright (c) 2011 Code Aurora Forum. All rights reserved.
+ * Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -24,12 +24,12 @@
 const int SimpleBestFitAllocator::kMemoryAlign = 32;
 
 SimpleBestFitAllocator::SimpleBestFitAllocator()
-    : mHeapSize(0)
+: mHeapSize(0)
 {
 }
 
 SimpleBestFitAllocator::SimpleBestFitAllocator(size_t size)
-    : mHeapSize(0)
+: mHeapSize(0)
 {
     setSize(size);
 }
@@ -113,13 +113,13 @@
                 mList.insertBefore(free_chunk, split);
             }
 
-            LOGE_IF(((free_chunk->start*kMemoryAlign)&(pagesize-1)),
-                    "page is not aligned!!!");
+            ALOGE_IF(((free_chunk->start*kMemoryAlign)&(pagesize-1)),
+                     "page is not aligned!!!");
 
             const ssize_t tail_free = free_size - (size+extra);
             if (tail_free > 0) {
                 chunk_t* split = new chunk_t(
-                        free_chunk->start + free_chunk->size, tail_free);
+                    free_chunk->start + free_chunk->size, tail_free);
                 mList.insertAfter(free_chunk, split);
             }
         }
@@ -128,33 +128,33 @@
     // we are out of PMEM. Print pmem stats
     // check if there is any leak or fragmentation
 
-    LOGD (" Out of PMEM. Dumping PMEM stats for debugging");
-    LOGD (" ------------- PRINT PMEM STATS --------------");
+    ALOGD (" Out of PMEM. Dumping PMEM stats for debugging");
+    ALOGD (" ------------- PRINT PMEM STATS --------------");
 
     cur = mList.head();
     static uint32_t node_count;
     static uint64_t allocated, free_space;
 
     while (cur) {
-      LOGD (" Node %d -> Start Address : %u Size %u Free info %d",\
-              node_count++, cur->start, cur->size, cur->free);
+        ALOGD (" Node %d -> Start Address : %u Size %u Free info %d",\
+               node_count++, cur->start, cur->size, cur->free);
 
-      // if cur-> free is 1 , the node is free
-      // calculate the total allocated and total free stats also
+        // if cur-> free is 1 , the node is free
+        // calculate the total allocated and total free stats also
 
-      if (cur->free)
-         free_space += cur->size;
-      else
-         allocated += cur->size;
-      // read next node
-      cur = cur->next;
+        if (cur->free)
+            free_space += cur->size;
+        else
+            allocated += cur->size;
+        // read next node
+        cur = cur->next;
     }
-    LOGD (" Total Allocated: %l Total Free: %l", allocated, free_space );
+    ALOGD (" Total Allocated: %l Total Free: %l", allocated, free_space );
 
     node_count = 0;
     allocated = 0;
     free_space = 0;
-    LOGD ("----------------------------------------------");
+    ALOGD ("----------------------------------------------");
     return -ENOMEM;
 }
 
@@ -164,9 +164,9 @@
     chunk_t* cur = mList.head();
     while (cur) {
         if (cur->start == start) {
-            LOG_FATAL_IF(cur->free,
-                "block at offset 0x%08lX of size 0x%08lX already freed",
-                cur->start*kMemoryAlign, cur->size*kMemoryAlign);
+            ALOG_FATAL_IF(cur->free,
+                          "block at offset 0x%08lX of size 0x%08lX already freed",
+                          cur->start*kMemoryAlign, cur->size*kMemoryAlign);
 
             // merge freed blocks together
             chunk_t* freed = cur;
@@ -183,9 +183,9 @@
                 cur = n;
             } while (cur && cur->free);
 
-            LOG_FATAL_IF(!freed->free,
-                "freed block at offset 0x%08lX of size 0x%08lX is not free!",
-                freed->start * kMemoryAlign, freed->size * kMemoryAlign);
+            ALOG_FATAL_IF(!freed->free,
+                          "freed block at offset 0x%08lX of size 0x%08lX is not free!",
+                          freed->start * kMemoryAlign, freed->size * kMemoryAlign);
 
             return freed;
         }
diff --git a/libgralloc/pmem_bestfit_alloc.h b/libgralloc/pmem_bestfit_alloc.h
index 2ea8452..4346ec3 100644
--- a/libgralloc/pmem_bestfit_alloc.h
+++ b/libgralloc/pmem_bestfit_alloc.h
@@ -1,6 +1,6 @@
 /*
  * Copyright (C) 2009 The Android Open Source Project
- * Copyright (c) 2011 Code Aurora Forum. All rights reserved.
+ * Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -36,8 +36,8 @@
     NODE*  mFirst;
     NODE*  mLast;
 
-public:
-                LinkedList() : mFirst(0), mLast(0) { }
+ public:
+    LinkedList() : mFirst(0), mLast(0) { }
     bool        isEmpty() const { return mFirst == 0; }
     NODE const* head() const { return mFirst; }
     NODE*       head() { return mFirst; }
@@ -53,11 +53,11 @@
     }
 
     void insertBefore(NODE* node, NODE* newNode) {
-         newNode->prev = node->prev;
-         newNode->next = node;
-         if (node->prev == 0)   mFirst = newNode;
-         else                   node->prev->next = newNode;
-         node->prev = newNode;
+        newNode->prev = node->prev;
+        newNode->next = node;
+        if (node->prev == 0)   mFirst = newNode;
+        else                   node->prev->next = newNode;
+        node->prev = newNode;
     }
 
     void insertHead(NODE* newNode) {
@@ -94,36 +94,36 @@
 
 class SimpleBestFitAllocator : public gralloc::PmemUserspaceAlloc::Allocator
 {
-public:
+ public:
 
-    SimpleBestFitAllocator();
-    SimpleBestFitAllocator(size_t size);
-    virtual ~SimpleBestFitAllocator();
+  SimpleBestFitAllocator();
+  SimpleBestFitAllocator(size_t size);
+  virtual ~SimpleBestFitAllocator();
 
-    virtual ssize_t setSize(size_t size);
+  virtual ssize_t setSize(size_t size);
 
-    virtual ssize_t allocate(size_t size, uint32_t flags = 0);
-    virtual ssize_t deallocate(size_t offset);
-    virtual size_t  size() const;
+  virtual ssize_t allocate(size_t size, uint32_t flags = 0);
+  virtual ssize_t deallocate(size_t offset);
+  virtual size_t  size() const;
 
-private:
-    struct chunk_t {
-        chunk_t(size_t start, size_t size)
-            : start(start), size(size), free(1), prev(0), next(0) {
-        }
-        size_t              start;
-        size_t              size : 28;
-        int                 free : 4;
-        mutable chunk_t*    prev;
-        mutable chunk_t*    next;
-    };
+ private:
+  struct chunk_t {
+      chunk_t(size_t start, size_t size)
+          : start(start), size(size), free(1), prev(0), next(0) {
+          }
+      size_t              start;
+      size_t              size : 28;
+      int                 free : 4;
+      mutable chunk_t*    prev;
+      mutable chunk_t*    next;
+  };
 
-    ssize_t  alloc(size_t size, uint32_t flags);
-    chunk_t* dealloc(size_t start);
+  ssize_t  alloc(size_t size, uint32_t flags);
+  chunk_t* dealloc(size_t start);
 
-    static const int    kMemoryAlign;
-    mutable Locker      mLock;
-    LinkedList<chunk_t> mList;
-    size_t              mHeapSize;
+  static const int    kMemoryAlign;
+  mutable Locker      mLock;
+  LinkedList<chunk_t> mList;
+  size_t              mHeapSize;
 };
 #endif /* GRALLOC_ALLOCATOR_H_ */
diff --git a/libgralloc/pmemalloc.cpp b/libgralloc/pmemalloc.cpp
index ccbf127..2286fb0 100644
--- a/libgralloc/pmemalloc.cpp
+++ b/libgralloc/pmemalloc.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
+ * Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -126,17 +126,17 @@
         ALOGD("%s: Total pmem size: %d", __FUNCTION__, size);
         if (err < 0) {
             ALOGE("%s: PMEM_GET_TOTAL_SIZE failed (%d), limp mode", mPmemDev,
-                    err);
+                  err);
             size = 8<<20;   // 8 MiB
         }
         mAllocator->setSize(size);
 
         void* base = mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd,
-                0);
+                          0);
         if (base == MAP_FAILED) {
             err = -errno;
             ALOGE("%s: Failed to map pmem master fd: %s", mPmemDev,
-                    strerror(errno));
+                  strerror(errno));
             base = 0;
             close(fd);
             fd = -1;
@@ -147,7 +147,7 @@
     } else {
         err = -errno;
         ALOGE("%s: Failed to open pmem device: %s", mPmemDev,
-                strerror(errno));
+              strerror(errno));
     }
     return err;
 }
@@ -203,13 +203,13 @@
 
             if (err < 0) {
                 ALOGE("%s: Failed to initialize pmem sub-heap: %d", mPmemDev,
-                        err);
+                      err);
                 close(fd);
                 mAllocator->deallocate(offset);
                 fd = -1;
             } else {
                 ALOGD("%s: Allocated buffer base:%p size:%d offset:%d fd:%d",
-                        mPmemDev, base, size, offset, fd);
+                      mPmemDev, base, size, offset, fd);
                 memset((char*)base + offset, 0, size);
                 //Clean cache before flushing to ensure pmem is properly flushed
                 err = clean_buffer((void*)((intptr_t) base + offset), size, offset, fd);
@@ -230,12 +230,12 @@
 int PmemUserspaceAlloc::free_buffer(void* base, size_t size, int offset, int fd)
 {
     ALOGD("%s: Freeing buffer base:%p size:%d offset:%d fd:%d",
-            mPmemDev, base, size, offset, fd);
+          mPmemDev, base, size, offset, fd);
     int err = 0;
     if (fd >= 0) {
         int err = unmapSubRegion(fd, offset, size);
         ALOGE_IF(err<0, "PMEM_UNMAP failed (%s), fd=%d, sub.offset=%u, "
-                "sub.size=%u", strerror(errno), fd, offset, size);
+                 "sub.size=%u", strerror(errno), fd, offset, size);
         if (err == 0) {
             // we can't deallocate the memory in case of UNMAP failure
             // because it would give that process access to someone else's
@@ -252,15 +252,15 @@
     int err = 0;
     size += offset;
     void *base = mmap(0, size, PROT_READ| PROT_WRITE,
-            MAP_SHARED, fd, 0);
+                      MAP_SHARED, fd, 0);
     *pBase = base;
     if(base == MAP_FAILED) {
         err = -errno;
         ALOGE("%s: Failed to map buffer size:%d offset:%d fd:%d Error: %s",
-                mPmemDev, size, offset, fd, strerror(errno));
+              mPmemDev, size, offset, fd, strerror(errno));
     } else {
         ALOGD("%s: Mapped buffer base:%p size:%d offset:%d fd:%d",
-                mPmemDev, base, size, offset, fd);
+              mPmemDev, base, size, offset, fd);
     }
     return err;
 
@@ -273,16 +273,15 @@
     base = (void*)(intptr_t(base) - offset);
     size += offset;
     ALOGD("%s: Unmapping buffer base:%p size:%d offset:%d",
-            mPmemDev , base, size, offset);
+          mPmemDev , base, size, offset);
     if (munmap(base, size) < 0) {
-
         err = -errno;
         ALOGE("%s: Failed to unmap memory at %p :%s",
-                   mPmemDev, base, strerror(errno));
+              mPmemDev, base, strerror(errno));
 
     }
 
-   return err;
+    return err;
 }
 
 int PmemUserspaceAlloc::clean_buffer(void *base, size_t size, int offset, int fd)
@@ -327,7 +326,7 @@
     if (base == MAP_FAILED) {
         err = -errno;
         ALOGE("%s: failed to map pmem fd: %s", mPmemDev,
-                strerror(errno));
+              strerror(errno));
         close(fd);
         return err;
     }
@@ -337,7 +336,7 @@
     data.offset = 0;
     data.fd = fd;
     ALOGD("%s: Allocated buffer base:%p size:%d fd:%d",
-                            mPmemDev, base, size, fd);
+          mPmemDev, base, size, fd);
     return 0;
 
 }
@@ -345,7 +344,7 @@
 int PmemKernelAlloc::free_buffer(void* base, size_t size, int offset, int fd)
 {
     ALOGD("%s: Freeing buffer base:%p size:%d fd:%d",
-            mPmemDev, base, size, fd);
+          mPmemDev, base, size, fd);
 
     int err =  unmap_buffer(base, size, offset);
     close(fd);
@@ -356,15 +355,15 @@
 {
     int err = 0;
     void *base = mmap(0, size, PROT_READ| PROT_WRITE,
-            MAP_SHARED, fd, 0);
+                      MAP_SHARED, fd, 0);
     *pBase = base;
     if(base == MAP_FAILED) {
         err = -errno;
         ALOGE("%s: Failed to map memory in the client: %s",
-                mPmemDev, strerror(errno));
+              mPmemDev, strerror(errno));
     } else {
         ALOGD("%s: Mapped buffer base:%p size:%d, fd:%d",
-                                mPmemDev, base, size, fd);
+              mPmemDev, base, size, fd);
     }
     return err;
 
@@ -376,7 +375,7 @@
     if (munmap(base, size)) {
         err = -errno;
         ALOGW("%s: Error unmapping memory at %p: %s",
-                                mPmemDev, base, strerror(err));
+              mPmemDev, base, strerror(err));
     }
     return err;
 
diff --git a/libgralloc/pmemalloc.h b/libgralloc/pmemalloc.h
index 4aed0b1..82794ec 100644
--- a/libgralloc/pmemalloc.h
+++ b/libgralloc/pmemalloc.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
+ * Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -35,72 +35,72 @@
 #include "memalloc.h"
 
 namespace gralloc {
-    class PmemUserspaceAlloc : public IMemAlloc  {
+class PmemUserspaceAlloc : public IMemAlloc  {
 
+    public:
+    class Allocator: public android::RefBase {
         public:
-            class Allocator: public android::RefBase {
-                public:
-                    virtual ~Allocator() {};
-                    virtual ssize_t setSize(size_t size) = 0;
-                    virtual size_t  size() const = 0;
-                    virtual ssize_t allocate(size_t size, uint32_t flags = 0) = 0;
-                    virtual ssize_t deallocate(size_t offset) = 0;
-            };
-
-            virtual int alloc_buffer(alloc_data& data);
-
-            virtual int free_buffer(void *base, size_t size,
-                    int offset, int fd);
-
-            virtual int map_buffer(void **pBase, size_t size,
-                    int offset, int fd);
-
-            virtual int unmap_buffer(void *base, size_t size,
-                    int offset);
-
-            virtual int clean_buffer(void*base, size_t size,
-                    int offset, int fd);
-
-            PmemUserspaceAlloc();
-
-            ~PmemUserspaceAlloc();
-
-        private:
-            int mMasterFd;
-            void* mMasterBase;
-            const char* mPmemDev;
-            android::sp<Allocator> mAllocator;
-            pthread_mutex_t mLock;
-            int init_pmem_area();
-            int init_pmem_area_locked();
-
+        virtual ~Allocator() {};
+        virtual ssize_t setSize(size_t size) = 0;
+        virtual size_t  size() const = 0;
+        virtual ssize_t allocate(size_t size, uint32_t flags = 0) = 0;
+        virtual ssize_t deallocate(size_t offset) = 0;
     };
 
-    class PmemKernelAlloc : public IMemAlloc  {
+    virtual int alloc_buffer(alloc_data& data);
 
-        public:
-            virtual int alloc_buffer(alloc_data& data);
+    virtual int free_buffer(void *base, size_t size,
+                            int offset, int fd);
 
-            virtual int free_buffer(void *base, size_t size,
-                    int offset, int fd);
+    virtual int map_buffer(void **pBase, size_t size,
+                           int offset, int fd);
 
-            virtual int map_buffer(void **pBase, size_t size,
-                    int offset, int fd);
+    virtual int unmap_buffer(void *base, size_t size,
+                             int offset);
 
-            virtual int unmap_buffer(void *base, size_t size,
-                    int offset);
+    virtual int clean_buffer(void*base, size_t size,
+                             int offset, int fd);
 
-            virtual int clean_buffer(void*base, size_t size,
-                    int offset, int fd);
+    PmemUserspaceAlloc();
 
-            PmemKernelAlloc(const char* device);
+    ~PmemUserspaceAlloc();
 
-            ~PmemKernelAlloc();
-        private:
-            const char* mPmemDev;
+    private:
+    int mMasterFd;
+    void* mMasterBase;
+    const char* mPmemDev;
+    android::sp<Allocator> mAllocator;
+    pthread_mutex_t mLock;
+    int init_pmem_area();
+    int init_pmem_area_locked();
+
+};
+
+class PmemKernelAlloc : public IMemAlloc  {
+
+    public:
+    virtual int alloc_buffer(alloc_data& data);
+
+    virtual int free_buffer(void *base, size_t size,
+                            int offset, int fd);
+
+    virtual int map_buffer(void **pBase, size_t size,
+                           int offset, int fd);
+
+    virtual int unmap_buffer(void *base, size_t size,
+                             int offset);
+
+    virtual int clean_buffer(void*base, size_t size,
+                             int offset, int fd);
+
+    PmemKernelAlloc(const char* device);
+
+    ~PmemKernelAlloc();
+    private:
+    const char* mPmemDev;
 
 
-    };
+};
 
 }
 #endif /* GRALLOC_PMEMALLOC_H */