hwcomposer : Use sysfs to read vysnc information

* Read sysfs entries to get vsync timestamp from kernel.
* External display continues to use uevents for hotplug events
* A new thread, vsyncThread is created to read and send vsync
  timestamps to HAL.
* Disable H/W VSYNC for MDP 5.x targets until kernel changes are
  complete.
* Synchronization is needed to make sure read() is not called
by hwcVsyncThread when VSYNC is disabled.

Change-Id: Iab0a94a3cfce9142b8867859f2a7d9bcaecb0996
Acked-by:  Neti Ravi Kumar <ravineti@codeaurora.org>
diff --git a/libhwcomposer/Android.mk b/libhwcomposer/Android.mk
index 8697b5a..25946ff 100644
--- a/libhwcomposer/Android.mk
+++ b/libhwcomposer/Android.mk
@@ -15,6 +15,7 @@
                                  hwc_video.cpp    \
                                  hwc_utils.cpp    \
                                  hwc_uevents.cpp  \
+                                 hwc_vsync.cpp    \
                                  hwc_mdpcomp.cpp  \
                                  hwc_uimirror.cpp \
 
diff --git a/libhwcomposer/hwc.cpp b/libhwcomposer/hwc.cpp
index 4a8d24d..f8f7f13 100644
--- a/libhwcomposer/hwc.cpp
+++ b/libhwcomposer/hwc.cpp
@@ -31,6 +31,7 @@
 #include "external.h"
 #include "hwc_mdpcomp.h"
 
+#define VSYNC_DEBUG 0
 using namespace qhwc;
 
 static int hwc_device_open(const struct hw_module_t* module,
@@ -68,8 +69,10 @@
     }
     ctx->proc = procs;
 
-    // don't start listening for events until we can do something with them
+    // Now that we have the functions needed, kick off
+    // the uevent & vsync threads
     init_uevent_thread(ctx);
+    init_vsync_thread(ctx);
 }
 
 //Helper
@@ -148,18 +151,38 @@
                              int event, int enabled)
 {
     int ret = 0;
+    static int prev_value;
+
     hwc_context_t* ctx = (hwc_context_t*)(dev);
     private_module_t* m = reinterpret_cast<private_module_t*>(
                 ctx->mFbDev->common.module);
     switch(event) {
         case HWC_EVENT_VSYNC:
             if(ioctl(ctx->dpyAttr[dpy].fd, MSMFB_OVERLAY_VSYNC_CTRL,
-                    &enabled) < 0) {
+                     &enabled) < 0) {
                 ALOGE("%s: vsync control failed. Dpy=%d, enabled=%d : %s",
-                        __FUNCTION__, dpy, enabled, strerror(errno));
+                      __FUNCTION__, dpy, enabled, strerror(errno));
+
                 ret = -errno;
             }
-            break;
+            /* vsync state change logic */
+            if (enabled == 1) {
+                //unblock vsync thread
+                pthread_mutex_lock(&ctx->vstate.lock);
+                ctx->vstate.enable = true;
+                pthread_cond_signal(&ctx->vstate.cond);
+                pthread_mutex_unlock(&ctx->vstate.lock);
+            } else if (enabled == 0 && ctx->vstate.enable) {
+                //vsync thread will block
+                pthread_mutex_lock(&ctx->vstate.lock);
+                ctx->vstate.enable = false;
+                pthread_mutex_unlock(&ctx->vstate.lock);
+            }
+            ALOGD_IF (VSYNC_DEBUG, "VSYNC state changed from %s to %s",
+              (prev_value)?"ENABLED":"DISABLED", (enabled)?"ENABLED":"DISABLED");
+            prev_value = enabled;
+            /* vsync state change logic - end*/
+           break;
         default:
             ret = -EINVAL;
     }
diff --git a/libhwcomposer/hwc_uevents.cpp b/libhwcomposer/hwc_uevents.cpp
index 3df0e25..ef43f62 100644
--- a/libhwcomposer/hwc_uevents.cpp
+++ b/libhwcomposer/hwc_uevents.cpp
@@ -21,6 +21,7 @@
 #include <hardware_legacy/uevent.h>
 #include <utils/Log.h>
 #include <sys/resource.h>
+#include <sys/prctl.h>
 #include <string.h>
 #include <stdlib.h>
 #include "hwc_utils.h"
@@ -28,8 +29,6 @@
 
 namespace qhwc {
 
-const char* MSMFB_DEVICE_FB0 = "change@/devices/virtual/graphics/fb0";
-const char* MSMFB_DEVICE_FB1 = "change@/devices/virtual/graphics/fb1";
 const char* MSMFB_HDMI_NODE = "fb1";
 
 static void handle_uevent(hwc_context_t* ctx, const char* udata, int len)
@@ -38,65 +37,38 @@
     char* hdmi;
     int64_t timestamp = 0;
     const char *str = udata;
-    int display = HWC_DISPLAY_PRIMARY;
 
     if(!strcasestr(str, "@/devices/virtual/graphics/fb")) {
         ALOGD_IF(UEVENT_DEBUG, "%s: Not Ext Disp Event ", __FUNCTION__);
         return;
     }
-
-    //Check if its primary vsync
-    vsync = !strncmp(str, MSMFB_DEVICE_FB0, strlen(MSMFB_DEVICE_FB0));
-    //If not primary vsync, see if its an external vsync
-    if(isExternalActive(ctx) && !vsync) {
-        vsync = !strncmp(str, MSMFB_DEVICE_FB1, strlen(MSMFB_DEVICE_FB1));
-        display = HWC_DISPLAY_EXTERNAL;
-    }
-
     hdmi = strcasestr(str, MSMFB_HDMI_NODE);
-
-    if(vsync) {
-        str += strlen(str) + 1;
-        while(*str) {
-            if (!strncmp(str, "VSYNC=", strlen("VSYNC="))) {
-                timestamp = strtoull(str + strlen("VSYNC="), NULL, 0);
-                //XXX: Handle vsync from multiple displays
-                ctx->proc->vsync(ctx->proc, display, timestamp);
-            }
-            str += strlen(str) + 1;
-            if(str - udata >= len)
-                break;
-        }
-        return;
-    }
-
-    if(hdmi) {
-        // parse HDMI events
-        // The event will be of the form:
-        // change@/devices/virtual/graphics/fb1 ACTION=change
-        // DEVPATH=/devices/virtual/graphics/fb1
-        // SUBSYSTEM=graphics HDCP_STATE=FAIL MAJOR=29
-        // for now just parsing onlin/offline info is enough
+    // parse HDMI events
+    // The event will be of the form:
+    // change@/devices/virtual/graphics/fb1 ACTION=change
+    // DEVPATH=/devices/virtual/graphics/fb1
+    // SUBSYSTEM=graphics HDCP_STATE=FAIL MAJOR=29
+    // for now just parsing onlin/offline info is enough
+    if (hdmi) {
         str = udata;
         int connected = 0;
         if(!(strncmp(str,"online@",strlen("online@")))) {
             connected = 1;
-            ctx->mExtDisplay->setExternalDisplay(connected);
+            ctx->mExtDisplay->setExternalDisplay(connected);;
         } else if(!(strncmp(str,"offline@",strlen("offline@")))) {
             connected = 0;
-            ctx->mExtDisplay->setExternalDisplay(connected);
+            ctx->mExtDisplay->setExternalDisplay(connected);;
         }
     }
-
 }
 
 static void *uevent_loop(void *param)
 {
     int len = 0;
-    static char udata[4096];
-    memset(udata, 0, sizeof(udata));
+    static char udata[PAGE_SIZE];
     hwc_context_t * ctx = reinterpret_cast<hwc_context_t *>(param);
-
+    char thread_name[64] = "hwcUeventThread";
+    prctl(PR_SET_NAME, (unsigned long) &thread_name, 0, 0, 0);
     setpriority(PRIO_PROCESS, 0, HAL_PRIORITY_URGENT_DISPLAY);
     uevent_init();
 
diff --git a/libhwcomposer/hwc_utils.cpp b/libhwcomposer/hwc_utils.cpp
index a4c7e3c..e198de3 100644
--- a/libhwcomposer/hwc_utils.cpp
+++ b/libhwcomposer/hwc_utils.cpp
@@ -59,6 +59,10 @@
     ctx->mExtDisplay = new ExternalDisplay(ctx);
     MDPComp::init(ctx);
 
+    pthread_mutex_init(&(ctx->vstate.lock), NULL);
+    pthread_cond_init(&(ctx->vstate.cond), NULL);
+    ctx->vstate.enable = false;
+
     ALOGI("Initializing Qualcomm Hardware Composer");
     ALOGI("MDP version: %d", ctx->mMDP.version);
 }
@@ -81,6 +85,10 @@
         delete ctx->mExtDisplay;
         ctx->mExtDisplay = NULL;
     }
+
+    pthread_mutex_destroy(&(ctx->vstate.lock));
+    pthread_cond_destroy(&(ctx->vstate.cond));
+
 }
 
 void dumpLayer(hwc_layer_1_t const* l)
diff --git a/libhwcomposer/hwc_utils.h b/libhwcomposer/hwc_utils.h
index 07318bd..0bde003 100644
--- a/libhwcomposer/hwc_utils.h
+++ b/libhwcomposer/hwc_utils.h
@@ -131,9 +131,11 @@
 
 // Initialize uevent thread
 void init_uevent_thread(hwc_context_t* ctx);
+// Initialize vsync thread
+void init_vsync_thread(hwc_context_t* ctx);
 
 inline void getLayerResolution(const hwc_layer_1_t* layer,
-                                         int& width, int& height)
+                               int& width, int& height)
 {
     hwc_rect_t displayFrame  = layer->displayFrame;
     width = displayFrame.right - displayFrame.left;
@@ -151,6 +153,12 @@
 
 }; //qhwc namespace
 
+struct vsync_state {
+    pthread_mutex_t lock;
+    pthread_cond_t  cond;
+    bool enable;
+};
+
 // -----------------------------------------------------------------------------
 // HWC context
 // This structure contains overall state
@@ -186,6 +194,9 @@
 
     //Lock to prevent set from being called while blanking
     mutable Locker mBlankLock;
+    //Vsync
+    struct vsync_state vstate;
+
 };
 
 #endif //HWC_UTILS_H
diff --git a/libhwcomposer/hwc_vsync.cpp b/libhwcomposer/hwc_vsync.cpp
new file mode 100644
index 0000000..cea00f4
--- /dev/null
+++ b/libhwcomposer/hwc_vsync.cpp
@@ -0,0 +1,112 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ * Copyright (C) 2012, Code Aurora Forum. All rights reserved.
+ *
+ * Not a Contribution, Apache license notifications and license are
+ * retained for attribution purposes only.
+
+ * 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.
+ */
+
+// WARNING : Excessive logging, if VSYNC_DEBUG enabled
+#define VSYNC_DEBUG 0
+
+#include <utils/Log.h>
+#include <fcntl.h>
+#include <sys/resource.h>
+#include <sys/prctl.h>
+#include "hwc_utils.h"
+#include "string.h"
+#include "external.h"
+
+
+namespace qhwc {
+
+static void *vsync_loop(void *param)
+{
+    const char* vsync_timestamp_fb0 = "/sys/class/graphics/fb0/vsync_event";
+    const char* vsync_timestamp_fb1 = "/sys/class/graphics/fb1/vsync_event";
+    int display = HWC_DISPLAY_PRIMARY;
+
+    hwc_context_t * ctx = reinterpret_cast<hwc_context_t *>(param);
+
+    char thread_name[64] = "hwcVsyncThread";
+    prctl(PR_SET_NAME, (unsigned long) &thread_name, 0, 0, 0);
+    setpriority(PRIO_PROCESS, 0, HAL_PRIORITY_URGENT_DISPLAY +
+                android::PRIORITY_MORE_FAVORABLE);
+
+    static char vdata[PAGE_SIZE];
+
+    uint64_t cur_timestamp=0;
+    int32_t len = -1, fd_timestamp = -1;
+    bool fb1_vsync = false;
+
+    /* Currently read vsync timestamp from drivers
+       e.g. VSYNC=41800875994
+    */
+
+    do {
+        pthread_mutex_lock(&ctx->vstate.lock);
+        if(ctx->vstate.enable == false) {
+          pthread_cond_wait(&ctx->vstate.cond, &ctx->vstate.lock);
+        }
+        pthread_mutex_unlock(&ctx->vstate.lock);
+
+
+       // try to open timestamp sysfs
+        fd_timestamp = open(vsync_timestamp_fb0, O_RDONLY);
+       if (fd_timestamp < 0) {
+           ALOGE ("FATAL:%s:not able to open file:%s, %s",  __FUNCTION__,
+                 (fb1_vsync) ? vsync_timestamp_fb1 : vsync_timestamp_fb0,
+                                                         strerror(errno));
+           return NULL;
+       }
+       // Open success - read now
+       len = read(fd_timestamp, vdata, PAGE_SIZE);
+       if (len < 0){
+           ALOGE ("FATAL:%s:not able to read file:%s, %s", __FUNCTION__,
+                  vsync_timestamp_fb0, strerror(errno));
+           fd_timestamp = -1;
+           return NULL;
+       }
+
+      // extract timestamp
+      const char *str = vdata;
+      if (!strncmp(str, "VSYNC=", strlen("VSYNC="))) {
+          cur_timestamp = strtoull(str + strlen("VSYNC="), NULL, 0);
+      } else {
+        ALOGE ("FATAL:%s:timestamp data not in correct format",
+                                                 __FUNCTION__);
+      }
+      // send timestamp to HAL
+      ALOGD_IF (VSYNC_DEBUG, "%s: timestamp %llu sent to HWC for %s",
+            __FUNCTION__, cur_timestamp, "fb0");
+      ctx->proc->vsync(ctx->proc, display, cur_timestamp);
+
+      // close open fds
+      close (fd_timestamp);
+
+      // reset fd
+      fd_timestamp = -1;
+
+    } while (true);
+}
+
+void init_vsync_thread(hwc_context_t* ctx)
+{
+    pthread_t vsync_thread;
+    ALOGI("Initializing VSYNC Thread");
+    pthread_create(&vsync_thread, NULL, vsync_loop, (void*) ctx);
+}
+
+}; //namespace