am eafa266c: (-s ours) DO NOT MERGE

* commit 'eafa266c88c496aa539f46407fbdab137b86d2c7':
  DO NOT MERGE
diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_BSD_APL2
similarity index 100%
rename from MODULE_LICENSE_APACHE2
rename to MODULE_LICENSE_BSD_APL2
diff --git a/camera/ANativeWindowDisplayAdapter.cpp b/camera/ANativeWindowDisplayAdapter.cpp
index 3f13b52..e4a70ae 100644
--- a/camera/ANativeWindowDisplayAdapter.cpp
+++ b/camera/ANativeWindowDisplayAdapter.cpp
@@ -177,8 +177,8 @@
     mFailedDQs = 0;
 
     mPaused = false;
-    mXOff = 0;
-    mYOff = 0;
+    mXOff = -1;
+    mYOff = -1;
     mFirstInit = false;
 
     mFD = -1;
@@ -269,6 +269,10 @@
         return BAD_VALUE;
     }
 
+    if ( window == mANativeWindow ) {
+        return ALREADY_EXISTS;
+    }
+
     ///Destroy the existing window object, if it exists
     destroy();
 
@@ -454,8 +458,8 @@
         mDisplayEnabled = false;
 
         ///Reset the offset values
-        mXOff = 0;
-        mYOff = 0;
+        mXOff = -1;
+        mYOff = -1;
 
         ///Reset the frame width and height values
         mFrameWidth =0;
@@ -536,7 +540,7 @@
     // Set gralloc usage bits for window.
     err = mANativeWindow->set_usage(mANativeWindow, CAMHAL_GRALLOC_USAGE);
     if (err != 0) {
-        LOGE("native_window_set_usage failed: %s (%d)", strerror(-err), -err);
+        ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), -err);
 
         if ( ENODEV == err ) {
             CAMHAL_LOGEA("Preview surface abandoned!");
@@ -550,7 +554,7 @@
     ///Set the number of buffers needed for camera preview
     err = mANativeWindow->set_buffer_count(mANativeWindow, numBufs);
     if (err != 0) {
-        LOGE("native_window_set_buffer_count failed: %s (%d)", strerror(-err), -err);
+        ALOGE("native_window_set_buffer_count failed: %s (%d)", strerror(-err), -err);
 
         if ( ENODEV == err ) {
             CAMHAL_LOGEA("Preview surface abandoned!");
@@ -571,7 +575,7 @@
             /*toOMXPixFormat(format)*/HAL_PIXEL_FORMAT_TI_NV12);  // Gralloc only supports NV12 alloc!
 
     if (err != 0) {
-        LOGE("native_window_set_buffers_geometry failed: %s (%d)", strerror(-err), -err);
+        ALOGE("native_window_set_buffers_geometry failed: %s (%d)", strerror(-err), -err);
 
         if ( ENODEV == err ) {
             CAMHAL_LOGEA("Preview surface abandoned!");
@@ -826,7 +830,7 @@
              }
          }
      else
-         LOGE("mANativeWindow is NULL");
+         ALOGE("mANativeWindow is NULL");
 
      ///Clear the frames with camera adapter map
      mFramesWithCameraAdapterMap.clear();
@@ -1095,7 +1099,7 @@
         mapper.unlock((buffer_handle_t) mGrallocHandleMap[i]);
         ret = mANativeWindow->enqueue_buffer(mANativeWindow, mBufferHandleMap[i]);
         if (ret != 0) {
-            LOGE("Surface::queueBuffer returned error %d", ret);
+            ALOGE("Surface::queueBuffer returned error %d", ret);
         }
 
         mFramesWithCameraAdapterMap.removeItem((int) dispFrame.mBuffer);
@@ -1137,7 +1141,7 @@
         // cancel buffer and dequeue another one
         ret = mANativeWindow->cancel_buffer(mANativeWindow, mBufferHandleMap[i]);
         if (ret != 0) {
-            LOGE("Surface::queueBuffer returned error %d", ret);
+            ALOGE("Surface::queueBuffer returned error %d", ret);
         }
 
         mFramesWithCameraAdapterMap.removeItem((int) dispFrame.mBuffer);
diff --git a/camera/Android.mk b/camera/Android.mk
index a84d0f9..1d7e048 100644
--- a/camera/Android.mk
+++ b/camera/Android.mk
@@ -59,13 +59,11 @@
     $(LOCAL_PATH)/inc/OMXCameraAdapter \
     $(LOCAL_PATH)/../libtiutils \
     hardware/ti/omap4xxx/tiler \
-    hardware/ti/omap4xxx/ion \
-    frameworks/base/include/ui \
-    frameworks/base/include/utils \
     hardware/ti/omap4xxx/domx/omx_core/inc \
     hardware/ti/omap4xxx/domx/mm_osal/inc \
     frameworks/base/include/media/stagefright \
-    frameworks/base/include/media/stagefright/openmax \
+    frameworks/native/include/media/hardware \
+    frameworks/native/include/media/openmax \
     external/jpeg \
     external/jhead
 
diff --git a/camera/AppCallbackNotifier.cpp b/camera/AppCallbackNotifier.cpp
index bfdd671..aa41141 100644
--- a/camera/AppCallbackNotifier.cpp
+++ b/camera/AppCallbackNotifier.cpp
@@ -38,12 +38,24 @@
                                         CameraFrame::FrameType type,
                                         void* cookie1,
                                         void* cookie2,
-                                        void* cookie3)
+                                        void* cookie3,
+                                        bool canceled)
 {
-    if (cookie1) {
+    if (cookie1 && !canceled) {
         AppCallbackNotifier* cb = (AppCallbackNotifier*) cookie1;
         cb->EncoderDoneCb(main_jpeg, thumb_jpeg, type, cookie2, cookie3);
     }
+
+    if (main_jpeg) {
+        free(main_jpeg);
+    }
+
+    if (thumb_jpeg) {
+       if (((Encoder_libjpeg::params *) thumb_jpeg)->dst) {
+           free(((Encoder_libjpeg::params *) thumb_jpeg)->dst);
+       }
+       free(thumb_jpeg);
+    }
 }
 
 /*--------------------NotificationHandler Class STARTS here-----------------------------*/
@@ -129,30 +141,17 @@
 
  exit:
 
-    if (main_jpeg) {
-        free(main_jpeg);
-    }
-
-    if (thumb_jpeg) {
-       if (((Encoder_libjpeg::params *) thumb_jpeg)->dst) {
-           free(((Encoder_libjpeg::params *) thumb_jpeg)->dst);
-       }
-       free(thumb_jpeg);
-    }
-
-    if (encoded_mem) {
-        encoded_mem->release(encoded_mem);
-    }
-
     if (picture) {
         picture->release(picture);
     }
 
-    if (cookie2) {
-        delete (ExifElementsTable*) cookie2;
-    }
-
     if (mNotifierState == AppCallbackNotifier::NOTIFIER_STARTED) {
+        if (encoded_mem) {
+            encoded_mem->release(encoded_mem);
+        }
+        if (cookie2) {
+            delete (ExifElementsTable*) cookie2;
+        }
         encoder = gEncoderQueue.valueFor(src);
         if (encoder.get()) {
             gEncoderQueue.removeItem(src);
@@ -285,7 +284,8 @@
         CAMHAL_LOGDA("Notification Thread received message from Camera HAL");
         shouldLive = processMessage();
         if(!shouldLive) {
-                CAMHAL_LOGDA("Notification Thread exiting.");
+          CAMHAL_LOGDA("Notification Thread exiting.");
+          return shouldLive;
         }
     }
 
@@ -311,8 +311,12 @@
     TIUTILS::Message msg;
     LOG_FUNCTION_NAME;
     {
-    Mutex::Autolock lock(mLock);
-    mEventQ.get(&msg);
+        Mutex::Autolock lock(mLock);
+        if(!mEventQ.isEmpty()) {
+            mEventQ.get(&msg);
+        } else {
+            return;
+        }
     }
     bool ret = true;
     CameraHalEvent *evt = NULL;
@@ -353,23 +357,36 @@
 
                 case CameraHalEvent::EVENT_FOCUS_LOCKED:
                 case CameraHalEvent::EVENT_FOCUS_ERROR:
-
                     focusEvtData = &evt->mEventData->focusEvent;
-                    if ( ( focusEvtData->focusLocked ) &&
-                          ( NULL != mCameraHal ) &&
-                          ( NULL != mNotifyCb ) &&
-                          ( mCameraHal->msgTypeEnabled(CAMERA_MSG_FOCUS) ) )
+                    if ( ( focusEvtData->focusStatus == CameraHalEvent::FOCUS_STATUS_SUCCESS ) &&
+                         ( NULL != mCameraHal ) &&
+                         ( NULL != mNotifyCb ) &&
+                         ( mCameraHal->msgTypeEnabled(CAMERA_MSG_FOCUS) ) )
                         {
+                         mCameraHal->disableMsgType(CAMERA_MSG_FOCUS);
                          mNotifyCb(CAMERA_MSG_FOCUS, true, 0, mCallbackCookie);
-                         mCameraHal->disableMsgType(CAMERA_MSG_FOCUS);
                         }
-                    else if ( focusEvtData->focusError &&
-                                ( NULL != mCameraHal ) &&
-                                ( NULL != mNotifyCb ) &&
-                                ( mCameraHal->msgTypeEnabled(CAMERA_MSG_FOCUS) ) )
+                    else if ( ( focusEvtData->focusStatus == CameraHalEvent::FOCUS_STATUS_FAIL ) &&
+                              ( NULL != mCameraHal ) &&
+                              ( NULL != mNotifyCb ) &&
+                              ( mCameraHal->msgTypeEnabled(CAMERA_MSG_FOCUS) ) )
                         {
-                         mNotifyCb(CAMERA_MSG_FOCUS, false, 0, mCallbackCookie);
                          mCameraHal->disableMsgType(CAMERA_MSG_FOCUS);
+                         mNotifyCb(CAMERA_MSG_FOCUS, false, 0, mCallbackCookie);
+                        }
+                    else if ( ( focusEvtData->focusStatus == CameraHalEvent::FOCUS_STATUS_PENDING ) &&
+                              ( NULL != mCameraHal ) &&
+                              ( NULL != mNotifyCb ) &&
+                              ( mCameraHal->msgTypeEnabled(CAMERA_MSG_FOCUS_MOVE) ) )
+                        {
+                         mNotifyCb(CAMERA_MSG_FOCUS_MOVE, true, 0, mCallbackCookie);
+                        }
+                    else if ( ( focusEvtData->focusStatus == CameraHalEvent::FOCUS_STATUS_DONE ) &&
+                              ( NULL != mCameraHal ) &&
+                              ( NULL != mNotifyCb ) &&
+                              ( mCameraHal->msgTypeEnabled(CAMERA_MSG_FOCUS_MOVE) ) )
+                        {
+                         mNotifyCb(CAMERA_MSG_FOCUS_MOVE, false, 0, mCallbackCookie);
                         }
 
                     break;
@@ -1206,7 +1223,7 @@
       {
         case NotificationThread::NOTIFIER_EXIT:
           {
-            CAMHAL_LOGI("Received NOTIFIER_EXIT command from Camera HAL");
+            CAMHAL_LOGDA("Received NOTIFIER_EXIT command from Camera HAL");
             mNotifierState = AppCallbackNotifier::NOTIFIER_EXITED;
             ret = false;
             break;
@@ -1664,7 +1681,7 @@
 
 status_t AppCallbackNotifier::disableMsgType(int32_t msgType)
 {
-    if(!mCameraHal->msgTypeEnabled(CAMERA_MSG_PREVIEW_FRAME | CAMERA_MSG_POSTVIEW_FRAME)) {
+    if( msgType & (CAMERA_MSG_PREVIEW_FRAME | CAMERA_MSG_POSTVIEW_FRAME) ) {
         mFrameProvider->disableFrameNotification(CameraFrame::PREVIEW_FRAME_SYNC);
     }
 
@@ -1732,9 +1749,20 @@
 
     while(!gEncoderQueue.isEmpty()) {
         sp<Encoder_libjpeg> encoder = gEncoderQueue.valueAt(0);
+        camera_memory_t* encoded_mem = NULL;
+        ExifElementsTable* exif = NULL;
+
         if(encoder.get()) {
             encoder->cancel();
-            encoder->join();
+
+            encoder->getCookies(NULL, (void**) &encoded_mem, (void**) &exif);
+            if (encoded_mem) {
+                encoded_mem->release(encoded_mem);
+            }
+            if (exif) {
+                delete exif;
+            }
+
             encoder.clear();
         }
         gEncoderQueue.removeItemsAt(0);
diff --git a/camera/BaseCameraAdapter.cpp b/camera/BaseCameraAdapter.cpp
index 882e4df..bb7a5b8 100644
--- a/camera/BaseCameraAdapter.cpp
+++ b/camera/BaseCameraAdapter.cpp
@@ -258,8 +258,6 @@
     size_t subscriberCount = 0;
     int refCount = -1;
 
-    Mutex::Autolock lock(mReturnFrameLock);
-
     if ( NULL == frameBuf )
         {
         CAMHAL_LOGEA("Invalid frameBuf");
@@ -268,6 +266,7 @@
 
     if ( NO_ERROR == res)
         {
+        Mutex::Autolock lock(mReturnFrameLock);
 
         refCount = getFrameRefCount(frameBuf,  frameType);
 
@@ -314,8 +313,8 @@
 #ifdef DEBUG_LOG
             if(mBuffersWithDucati.indexOfKey((int)frameBuf)>=0)
                 {
-                LOGE("Buffer already with Ducati!! 0x%x", frameBuf);
-                for(int i=0;i<mBuffersWithDucati.size();i++) LOGE("0x%x", mBuffersWithDucati.keyAt(i));
+                ALOGE("Buffer already with Ducati!! 0x%x", frameBuf);
+                for(int i=0;i<mBuffersWithDucati.size();i++) ALOGE("0x%x", mBuffersWithDucati.keyAt(i));
                 }
             mBuffersWithDucati.add((int)frameBuf,1);
 #endif
@@ -985,7 +984,7 @@
     return ret;
 }
 
-status_t BaseCameraAdapter::notifyFocusSubscribers(bool status)
+status_t BaseCameraAdapter::notifyFocusSubscribers(CameraHalEvent::FocusStatus status)
 {
     event_callback eventCb;
     CameraHalEvent focusEvent;
@@ -999,10 +998,12 @@
     }
 
 #if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS
-
-     //dump the AF latency
-     CameraHal::PPM("Focus finished in: ", &mStartFocus);
-
+     if (status == CameraHalEvent::FOCUS_STATUS_PENDING) {
+        gettimeofday(&mStartFocus, NULL);
+     } else {
+        //dump the AF latency
+        CameraHal::PPM("Focus finished in: ", &mStartFocus);
+    }
 #endif
 
     focusEvent.mEventData = new CameraHalEvent::CameraHalEventData();
@@ -1011,8 +1012,7 @@
     }
 
     focusEvent.mEventType = CameraHalEvent::EVENT_FOCUS_LOCKED;
-    focusEvent.mEventData->focusEvent.focusLocked = status;
-    focusEvent.mEventData->focusEvent.focusError = !status;
+    focusEvent.mEventData->focusEvent.focusStatus = status;
 
     for (unsigned int i = 0 ; i < mFocusSubscribers.size(); i++ )
         {
@@ -1054,7 +1054,7 @@
         shutterEvent.mCookie = ( void * ) mShutterSubscribers.keyAt(i);
         eventCb = ( event_callback ) mShutterSubscribers.valueAt(i);
 
-        CAMHAL_LOGEA("Sending shutter callback");
+        CAMHAL_LOGDA("Sending shutter callback");
 
         eventCb ( &shutterEvent );
     }
@@ -1518,7 +1518,7 @@
 
     LOG_FUNCTION_NAME;
 
-    notifyFocusSubscribers(false);
+    notifyFocusSubscribers(CameraHalEvent::FOCUS_STATUS_FAIL);
 
     LOG_FUNCTION_NAME_EXIT;
 
@@ -1696,6 +1696,12 @@
                     mNextState = INTIALIZED_STATE;
                     break;
 
+                case CAMERA_CANCEL_AUTOFOCUS:
+                case CAMERA_STOP_BRACKET_CAPTURE:
+                case CAMERA_STOP_IMAGE_CAPTURE:
+                    ret = INVALID_OPERATION;
+                    break;
+
                 default:
                     CAMHAL_LOGEB("Adapter state switch INTIALIZED_STATE Invalid Op! event = 0x%x",
                                  operation);
@@ -1717,6 +1723,12 @@
                     mNextState = PREVIEW_STATE;
                     break;
 
+                case CAMERA_STOP_PREVIEW:
+                    CAMHAL_LOGDB("Adapter state switch LOADED_PREVIEW_STATE->INTIALIZED_STATE event = 0x%x",
+                                 operation);
+                    mNextState = INTIALIZED_STATE;
+                    break;
+
                 //These events don't change the current state
                 case CAMERA_QUERY_BUFFER_SIZE_IMAGE_CAPTURE:
                 case CAMERA_QUERY_BUFFER_SIZE_PREVIEW_DATA:
diff --git a/camera/CameraHal.cpp b/camera/CameraHal.cpp
index c7ba87f..db73443 100644
--- a/camera/CameraHal.cpp
+++ b/camera/CameraHal.cpp
@@ -131,9 +131,7 @@
 
     // ignoring enable focus message from camera service
     // we will enable internally in autoFocus call
-    if (msgType & CAMERA_MSG_FOCUS) {
-        msgType &= ~CAMERA_MSG_FOCUS;
-    }
+    msgType &= ~(CAMERA_MSG_FOCUS | CAMERA_MSG_FOCUS_MOVE);
 
     {
     Mutex::Autolock lock(mLock);
@@ -249,19 +247,14 @@
     int w_orig, h_orig;
     int framerate,minframerate;
     int maxFPS, minFPS;
-    int error;
-    int base;
     const char *valstr = NULL;
-    const char *prevFormat;
-    char *af_coord;
-    TIUTILS::Message msg;
+    int varint = 0;
     status_t ret = NO_ERROR;
+    CameraParameters oldParams = mParameters;
     // Needed for KEY_RECORDING_HINT
     bool restartPreviewRequired = false;
     bool updateRequired = false;
-    CameraParameters oldParams(mParameters.flatten());
     bool videoMode = false;
-    char range[MAX_PROP_VALUE_LENGTH];
 
     {
         Mutex::Autolock lock(mLock);
@@ -277,17 +270,19 @@
                     mParameters.setPreviewFormat(valstr);
                 } else {
                     CAMHAL_LOGEB("Invalid preview format.Supported: %s",  mCameraProperties->get(CameraProperties::SUPPORTED_PREVIEW_FORMATS));
-                    return -EINVAL;
+                    return BAD_VALUE;
                 }
             }
 
-            if ((valstr = params.get(TICameraParameters::KEY_VNF)) != NULL) {
-                if ( (params.getInt(TICameraParameters::KEY_VNF)==0) || (params.getInt(TICameraParameters::KEY_VNF)==1) ) {
-                    CAMHAL_LOGDB("VNF set %s", params.get(TICameraParameters::KEY_VNF));
-                    mParameters.set(TICameraParameters::KEY_VNF, valstr);
+            varint = params.getInt(TICameraParameters::KEY_VNF);
+            valstr = params.get(TICameraParameters::KEY_VNF);
+            if ( valstr != NULL ) {
+                if ( ( varint == 0 ) || ( varint == 1 ) ) {
+                    CAMHAL_LOGDB("VNF set %s", valstr);
+                    mParameters.set(TICameraParameters::KEY_VNF, varint);
                 } else {
                     CAMHAL_LOGEB("ERROR: Invalid VNF: %s", valstr);
-                    ret = -EINVAL;
+                    return BAD_VALUE;
                 }
             }
 
@@ -296,35 +291,37 @@
                 // vstab then return an error
                 if (strcmp(mCameraProperties->get(CameraProperties::VSTAB_SUPPORTED),
                            CameraParameters::TRUE) == 0) {
-                    CAMHAL_LOGDB("VSTAB %s",
-                                  params.get(CameraParameters::KEY_VIDEO_STABILIZATION));
-                    mParameters.set(CameraParameters::KEY_VIDEO_STABILIZATION,
-                                    params.get(CameraParameters::KEY_VIDEO_STABILIZATION));
+                    CAMHAL_LOGDB("VSTAB %s",valstr);
+                    mParameters.set(CameraParameters::KEY_VIDEO_STABILIZATION, valstr);
                 } else if (strcmp(valstr, CameraParameters::TRUE) == 0) {
                     CAMHAL_LOGEB("ERROR: Invalid VSTAB: %s", valstr);
-                    ret = -EINVAL;
+                    return BAD_VALUE;
                 } else {
                     mParameters.set(CameraParameters::KEY_VIDEO_STABILIZATION,
                                     CameraParameters::FALSE);
                 }
             }
 
+
+
             if( (valstr = params.get(TICameraParameters::KEY_CAP_MODE)) != NULL)
                 {
-                CAMHAL_LOGDB("Capture mode set %s", params.get(TICameraParameters::KEY_CAP_MODE));
+                CAMHAL_LOGDB("Capture mode set %s", valstr);
                 mParameters.set(TICameraParameters::KEY_CAP_MODE, valstr);
                 }
 
             if ((valstr = params.get(TICameraParameters::KEY_IPP)) != NULL) {
                 if (isParameterValid(valstr,mCameraProperties->get(CameraProperties::SUPPORTED_IPP_MODES))) {
-                    CAMHAL_LOGDB("IPP mode set %s", params.get(TICameraParameters::KEY_IPP));
+                    CAMHAL_LOGDB("IPP mode set %s", valstr);
                     mParameters.set(TICameraParameters::KEY_IPP, valstr);
                 } else {
                     CAMHAL_LOGEB("ERROR: Invalid IPP mode: %s", valstr);
-                    ret = -EINVAL;
+                    return BAD_VALUE;
                 }
             }
 
+#ifdef OMAP_ENHANCEMENT
+
             if((valstr = params.get(TICameraParameters::KEY_S3D2D_PREVIEW)) != NULL)
                 {
                 CAMHAL_LOGDB("Stereo 3D->2D Preview mode is %s", params.get(TICameraParameters::KEY_S3D2D_PREVIEW));
@@ -336,18 +333,21 @@
                 CAMHAL_LOGDB("AutoConvergence mode is %s", params.get(TICameraParameters::KEY_AUTOCONVERGENCE));
                 mParameters.set(TICameraParameters::KEY_AUTOCONVERGENCE, valstr);
                 }
+#endif
 
             }
 
             params.getPreviewSize(&w, &h);
             if (w == -1 && h == -1) {
                 CAMHAL_LOGEA("Unable to get preview size");
-                return -EINVAL;
+                return BAD_VALUE;
               }
 
             int oldWidth, oldHeight;
             mParameters.getPreviewSize(&oldWidth, &oldHeight);
 
+#ifdef OMAP_ENHANCEMENT
+
             int orientation =0;
             if((valstr = params.get(TICameraParameters::KEY_SENSOR_ORIENTATION)) != NULL)
                 {
@@ -361,7 +361,7 @@
               if ( !isResolutionValid(h,w, mCameraProperties->get(CameraProperties::SUPPORTED_PREVIEW_SIZES)))
                {
                 CAMHAL_LOGEB("Invalid preview resolution %d x %d", w, h);
-                return -EINVAL;
+                return BAD_VALUE;
                }
               else
               {
@@ -375,7 +375,7 @@
             if ( !isResolutionValid(w, h, mCameraProperties->get(CameraProperties::SUPPORTED_PREVIEW_SIZES)))
                 {
                 CAMHAL_LOGEB("Invalid preview resolution %d x %d", w, h);
-                return -EINVAL;
+                return BAD_VALUE;
                 }
             else
                 {
@@ -383,12 +383,23 @@
                 }
            }
 
-            if ( ( oldWidth != w ) || ( oldHeight != h ) )
-                {
-                restartPreviewRequired |= true;
-                }
 
-            CAMHAL_LOGDB("PreviewResolution by App %d x %d", w, h);
+#else
+
+        if ( !isResolutionValid(w, h, mCameraProperties->get(CameraProperties::SUPPORTED_PREVIEW_SIZES))) {
+            CAMHAL_LOGEB("Invalid preview resolution %d x %d", w, h);
+            return BAD_VALUE;
+        } else {
+            mParameters.setPreviewSize(w, h);
+        }
+
+#endif
+
+        if ( ( oldWidth != w ) || ( oldHeight != h ) ) {
+            restartPreviewRequired |= true;
+        }
+
+        CAMHAL_LOGDB("PreviewResolution by App %d x %d", w, h);
 
         // Handle RECORDING_HINT to Set/Reset Video Mode Parameters
         valstr = params.get(CameraParameters::KEY_RECORDING_HINT);
@@ -429,7 +440,7 @@
             else
                 {
                 CAMHAL_LOGEA("Invalid RECORDING_HINT");
-                return -EINVAL;
+                return BAD_VALUE;
                 }
             }
         else
@@ -446,7 +457,7 @@
 
         if ((valstr = params.get(CameraParameters::KEY_FOCUS_MODE)) != NULL) {
             if (isParameterValid(valstr, mCameraProperties->get(CameraProperties::SUPPORTED_FOCUS_MODES))) {
-                CAMHAL_LOGDB("Focus mode set %s", params.get(CameraParameters::KEY_FOCUS_MODE));
+                CAMHAL_LOGDB("Focus mode set %s", valstr);
 
                 // we need to take a decision on the capture mode based on whether CAF picture or
                 // video is chosen so the behavior of each is consistent to the application
@@ -459,40 +470,44 @@
                 mParameters.set(CameraParameters::KEY_FOCUS_MODE, valstr);
              } else {
                 CAMHAL_LOGEB("ERROR: Invalid FOCUS mode = %s", valstr);
-                ret = -EINVAL;
+                return BAD_VALUE;
              }
         }
 
         ///Below parameters can be changed when the preview is running
         if ( (valstr = params.getPictureFormat()) != NULL ) {
-            if (isParameterValid(params.getPictureFormat(),mCameraProperties->get(CameraProperties::SUPPORTED_PICTURE_FORMATS))) {
+            if (isParameterValid(valstr, mCameraProperties->get(CameraProperties::SUPPORTED_PICTURE_FORMATS))) {
                 mParameters.setPictureFormat(valstr);
             } else {
                 CAMHAL_LOGEB("ERROR: Invalid picture format: %s",valstr);
-                ret = -EINVAL;
+                return BAD_VALUE;
             }
-            }
+        }
 
         params.getPictureSize(&w, &h);
         if ( isResolutionValid(w, h, mCameraProperties->get(CameraProperties::SUPPORTED_PICTURE_SIZES))) {
             mParameters.setPictureSize(w, h);
         } else {
             CAMHAL_LOGEB("ERROR: Invalid picture resolution %dx%d", w, h);
-            ret = -EINVAL;
+            return BAD_VALUE;
         }
 
         CAMHAL_LOGDB("Picture Size by App %d x %d", w, h);
 
+#ifdef OMAP_ENHANCEMENT
+
         if ((valstr = params.get(TICameraParameters::KEY_BURST)) != NULL) {
             if (params.getInt(TICameraParameters::KEY_BURST) >=0) {
-                CAMHAL_LOGDB("Burst set %s", params.get(TICameraParameters::KEY_BURST));
+                CAMHAL_LOGDB("Burst set %s", valstr);
                 mParameters.set(TICameraParameters::KEY_BURST, valstr);
             } else {
                 CAMHAL_LOGEB("ERROR: Invalid Burst value: %s",valstr);
-                ret = -EINVAL;
+                return BAD_VALUE;
             }
         }
 
+#endif
+
         framerate = params.getPreviewFrameRate();
         valstr = params.get(CameraParameters::KEY_PREVIEW_FPS_RANGE);
         CAMHAL_LOGDB("FRAMERATE %d", framerate);
@@ -510,7 +525,7 @@
                                       mCameraProperties->get(CameraProperties::SUPPORTED_PREVIEW_FRAME_RATES)))
         {
             CAMHAL_LOGEA("Invalid frame rate range or frame rate");
-            return -EINVAL;
+            return BAD_VALUE;
         }
 
         // Variable framerate ranges have higher priority over
@@ -527,7 +542,7 @@
             if ( ( 0 > minFPS ) || ( 0 > maxFPS ) )
               {
                 CAMHAL_LOGEA("ERROR: FPS Range is negative!");
-                return -EINVAL;
+                return BAD_VALUE;
               }
 
             framerate = maxFPS /CameraHal::VFR_SCALE;
@@ -570,13 +585,13 @@
         if ( ( 0 == minFPS ) || ( 0 == maxFPS ) )
           {
             CAMHAL_LOGEA("ERROR: FPS Range is invalid!");
-            ret = -EINVAL;
+            return BAD_VALUE;
           }
 
         if ( maxFPS < minFPS )
           {
             CAMHAL_LOGEA("ERROR: Max FPS is smaller than Min FPS!");
-            ret = -EINVAL;
+            return BAD_VALUE;
           }
         CAMHAL_LOGDB("SET FRAMERATE %d", framerate);
         mParameters.setPreviewFrameRate(framerate);
@@ -598,6 +613,8 @@
             mParameters.set(TICameraParameters::KEY_GLBCE, valstr);
             }
 
+#ifdef OMAP_ENHANCEMENT
+
         ///Update the current parameter set
         if( (valstr = params.get(TICameraParameters::KEY_AUTOCONVERGENCE)) != NULL)
             {
@@ -617,27 +634,31 @@
                 mParameters.set(TICameraParameters::KEY_EXPOSURE_MODE, valstr);
             } else {
                 CAMHAL_LOGEB("ERROR: Invalid Exposure  = %s", valstr);
-                ret = -EINVAL;
+                return BAD_VALUE;
             }
         }
 
+#endif
+
         if ((valstr = params.get(CameraParameters::KEY_WHITE_BALANCE)) != NULL) {
            if ( isParameterValid(valstr, mCameraProperties->get(CameraProperties::SUPPORTED_WHITE_BALANCE))) {
                CAMHAL_LOGDB("White balance set %s", valstr);
                mParameters.set(CameraParameters::KEY_WHITE_BALANCE, valstr);
             } else {
                CAMHAL_LOGEB("ERROR: Invalid white balance  = %s", valstr);
-               ret = -EINVAL;
+               return BAD_VALUE;
             }
         }
 
+#ifdef OMAP_ENHANCEMENT
+
         if ((valstr = params.get(TICameraParameters::KEY_CONTRAST)) != NULL) {
             if (params.getInt(TICameraParameters::KEY_CONTRAST) >= 0 ) {
                 CAMHAL_LOGDB("Contrast set %s", valstr);
                 mParameters.set(TICameraParameters::KEY_CONTRAST, valstr);
             } else {
                 CAMHAL_LOGEB("ERROR: Invalid Contrast  = %s", valstr);
-                ret = -EINVAL;
+                return BAD_VALUE;
             }
         }
 
@@ -647,7 +668,7 @@
                 mParameters.set(TICameraParameters::KEY_SHARPNESS, valstr);
             } else {
                 CAMHAL_LOGEB("ERROR: Invalid Sharpness = %s", valstr);
-                ret = -EINVAL;
+                return BAD_VALUE;
             }
         }
 
@@ -657,7 +678,7 @@
                 mParameters.set(TICameraParameters::KEY_SATURATION, valstr);
              } else {
                 CAMHAL_LOGEB("ERROR: Invalid Saturation = %s", valstr);
-                ret = -EINVAL;
+                return BAD_VALUE;
             }
         }
 
@@ -667,36 +688,44 @@
                 mParameters.set(TICameraParameters::KEY_BRIGHTNESS, valstr);
             } else {
                 CAMHAL_LOGEB("ERROR: Invalid Brightness = %s", valstr);
-                ret = -EINVAL;
+                return BAD_VALUE;
             }
          }
 
+#endif
+
         if ((valstr = params.get(CameraParameters::KEY_ANTIBANDING)) != NULL) {
             if (isParameterValid(valstr, mCameraProperties->get(CameraProperties::SUPPORTED_ANTIBANDING))) {
                 CAMHAL_LOGDB("Antibanding set %s", valstr);
                 mParameters.set(CameraParameters::KEY_ANTIBANDING, valstr);
              } else {
                 CAMHAL_LOGEB("ERROR: Invalid Antibanding = %s", valstr);
-                ret = -EINVAL;
+                return BAD_VALUE;
              }
          }
 
+#ifdef OMAP_ENHANCEMENT
+
         if ((valstr = params.get(TICameraParameters::KEY_ISO)) != NULL) {
             if (isParameterValid(valstr, mCameraProperties->get(CameraProperties::SUPPORTED_ISO_VALUES))) {
                 CAMHAL_LOGDB("ISO set %s", valstr);
                 mParameters.set(TICameraParameters::KEY_ISO, valstr);
             } else {
                 CAMHAL_LOGEB("ERROR: Invalid ISO = %s", valstr);
-                ret = -EINVAL;
+                return BAD_VALUE;
             }
         }
 
+#endif
+
         if( (valstr = params.get(CameraParameters::KEY_FOCUS_AREAS)) != NULL )
             {
-            CAMHAL_LOGI("Focus areas position set %s", params.get(CameraParameters::KEY_FOCUS_AREAS));
+            CAMHAL_LOGDB("Focus areas position set %s",valstr);
             mParameters.set(CameraParameters::KEY_FOCUS_AREAS, valstr);
             }
 
+#ifdef OMAP_ENHANCEMENT
+
         if( (valstr = params.get(TICameraParameters::KEY_MEASUREMENT_ENABLE)) != NULL )
             {
             CAMHAL_LOGDB("Measurements set to %s", params.get(TICameraParameters::KEY_MEASUREMENT_ENABLE));
@@ -717,9 +746,11 @@
 
             }
 
+#endif
+
         if( (valstr = params.get(CameraParameters::KEY_EXPOSURE_COMPENSATION)) != NULL)
             {
-            CAMHAL_LOGDB("Exposure compensation set %s", params.get(CameraParameters::KEY_EXPOSURE_COMPENSATION));
+            CAMHAL_LOGDB("Exposure compensation set %s", valstr);
             mParameters.set(CameraParameters::KEY_EXPOSURE_COMPENSATION, valstr);
             }
 
@@ -732,7 +763,7 @@
                 mParameters.set(CameraParameters::KEY_SCENE_MODE, valstr);
             } else {
                 CAMHAL_LOGEB("ERROR: Invalid Scene mode = %s", valstr);
-                ret = -EINVAL;
+                return BAD_VALUE;
             }
         }
 
@@ -742,7 +773,7 @@
                 mParameters.set(CameraParameters::KEY_FLASH_MODE, valstr);
             } else {
                 CAMHAL_LOGEB("ERROR: Invalid Flash mode = %s", valstr);
-                ret = -EINVAL;
+                return BAD_VALUE;
             }
         }
 
@@ -752,48 +783,48 @@
                 mParameters.set(CameraParameters::KEY_EFFECT, valstr);
              } else {
                 CAMHAL_LOGEB("ERROR: Invalid Effect = %s", valstr);
-                ret = -EINVAL;
+                return BAD_VALUE;
              }
         }
 
-        if(( (valstr = params.get(CameraParameters::KEY_ROTATION)) != NULL)
-            && (params.getInt(CameraParameters::KEY_ROTATION) >=0))
+        varint = params.getInt(CameraParameters::KEY_ROTATION);
+        if( varint >=0 )
             {
-            CAMHAL_LOGDB("Rotation set %s", params.get(CameraParameters::KEY_ROTATION));
-            mParameters.set(CameraParameters::KEY_ROTATION, valstr);
+            CAMHAL_LOGDB("Rotation set %d", varint);
+            mParameters.set(CameraParameters::KEY_ROTATION, varint);
             }
 
-        if(( (valstr = params.get(CameraParameters::KEY_JPEG_QUALITY)) != NULL)
-            && (params.getInt(CameraParameters::KEY_JPEG_QUALITY) >=0))
+        varint = params.getInt(CameraParameters::KEY_JPEG_QUALITY);
+        if( varint >= 0 )
             {
-            CAMHAL_LOGDB("Jpeg quality set %s", params.get(CameraParameters::KEY_JPEG_QUALITY));
-            mParameters.set(CameraParameters::KEY_JPEG_QUALITY, valstr);
+            CAMHAL_LOGDB("Jpeg quality set %d", varint);
+            mParameters.set(CameraParameters::KEY_JPEG_QUALITY, varint);
             }
 
-        if(( (valstr = params.get(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH)) != NULL)
-            && (params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH) >=0))
+        varint = params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH);
+        if( varint >=0 )
             {
-            CAMHAL_LOGDB("Thumbnail width set %s", params.get(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH));
-            mParameters.set(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH, valstr);
+            CAMHAL_LOGDB("Thumbnail width set %d", varint);
+            mParameters.set(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH, varint);
             }
 
-        if(( (valstr = params.get(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT)) != NULL)
-            && (params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT) >=0))
+        varint = params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT);
+        if( varint >=0 )
             {
-            CAMHAL_LOGDB("Thumbnail width set %s", params.get(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT));
-            mParameters.set(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT, valstr);
+            CAMHAL_LOGDB("Thumbnail width set %d", varint);
+            mParameters.set(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT, varint);
             }
 
-        if(( (valstr = params.get(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY)) != NULL )
-            && (params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY) >=0))
+        varint = params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY);
+        if( varint >=0 )
             {
-            CAMHAL_LOGDB("Thumbnail quality set %s", params.get(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY));
-            mParameters.set(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY, valstr);
+            CAMHAL_LOGDB("Thumbnail quality set %d", varint);
+            mParameters.set(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY, varint);
             }
 
         if( (valstr = params.get(CameraParameters::KEY_GPS_LATITUDE)) != NULL )
             {
-            CAMHAL_LOGDB("GPS latitude set %s", params.get(CameraParameters::KEY_GPS_LATITUDE));
+            CAMHAL_LOGDB("GPS latitude set %s", valstr);
             mParameters.set(CameraParameters::KEY_GPS_LATITUDE, valstr);
             }else{
                 mParameters.remove(CameraParameters::KEY_GPS_LATITUDE);
@@ -801,7 +832,7 @@
 
         if( (valstr = params.get(CameraParameters::KEY_GPS_LONGITUDE)) != NULL )
             {
-            CAMHAL_LOGDB("GPS longitude set %s", params.get(CameraParameters::KEY_GPS_LONGITUDE));
+            CAMHAL_LOGDB("GPS longitude set %s", valstr);
             mParameters.set(CameraParameters::KEY_GPS_LONGITUDE, valstr);
             }else{
                 mParameters.remove(CameraParameters::KEY_GPS_LONGITUDE);
@@ -809,7 +840,7 @@
 
         if( (valstr = params.get(CameraParameters::KEY_GPS_ALTITUDE)) != NULL )
             {
-            CAMHAL_LOGDB("GPS altitude set %s", params.get(CameraParameters::KEY_GPS_ALTITUDE));
+            CAMHAL_LOGDB("GPS altitude set %s", valstr);
             mParameters.set(CameraParameters::KEY_GPS_ALTITUDE, valstr);
             }else{
                 mParameters.remove(CameraParameters::KEY_GPS_ALTITUDE);
@@ -817,7 +848,7 @@
 
         if( (valstr = params.get(CameraParameters::KEY_GPS_TIMESTAMP)) != NULL )
             {
-            CAMHAL_LOGDB("GPS timestamp set %s", params.get(CameraParameters::KEY_GPS_TIMESTAMP));
+            CAMHAL_LOGDB("GPS timestamp set %s", valstr);
             mParameters.set(CameraParameters::KEY_GPS_TIMESTAMP, valstr);
             }else{
                 mParameters.remove(CameraParameters::KEY_GPS_TIMESTAMP);
@@ -825,7 +856,7 @@
 
         if( (valstr = params.get(TICameraParameters::KEY_GPS_DATESTAMP)) != NULL )
             {
-            CAMHAL_LOGDB("GPS datestamp set %s", params.get(TICameraParameters::KEY_GPS_DATESTAMP));
+            CAMHAL_LOGDB("GPS datestamp set %s", valstr);
             mParameters.set(TICameraParameters::KEY_GPS_DATESTAMP, valstr);
             }else{
                 mParameters.remove(TICameraParameters::KEY_GPS_DATESTAMP);
@@ -833,7 +864,7 @@
 
         if( (valstr = params.get(CameraParameters::KEY_GPS_PROCESSING_METHOD)) != NULL )
             {
-            CAMHAL_LOGDB("GPS processing method set %s", params.get(CameraParameters::KEY_GPS_PROCESSING_METHOD));
+            CAMHAL_LOGDB("GPS processing method set %s", valstr);
             mParameters.set(CameraParameters::KEY_GPS_PROCESSING_METHOD, valstr);
             }else{
                 mParameters.remove(CameraParameters::KEY_GPS_PROCESSING_METHOD);
@@ -841,7 +872,7 @@
 
         if( (valstr = params.get(TICameraParameters::KEY_GPS_MAPDATUM )) != NULL )
             {
-            CAMHAL_LOGDB("GPS MAPDATUM set %s", params.get(TICameraParameters::KEY_GPS_MAPDATUM));
+            CAMHAL_LOGDB("GPS MAPDATUM set %s", valstr);
             mParameters.set(TICameraParameters::KEY_GPS_MAPDATUM, valstr);
             }else{
                 mParameters.remove(TICameraParameters::KEY_GPS_MAPDATUM);
@@ -849,7 +880,7 @@
 
         if( (valstr = params.get(TICameraParameters::KEY_GPS_VERSION)) != NULL )
             {
-            CAMHAL_LOGDB("GPS MAPDATUM set %s", params.get(TICameraParameters::KEY_GPS_VERSION));
+            CAMHAL_LOGDB("GPS MAPDATUM set %s", valstr);
             mParameters.set(TICameraParameters::KEY_GPS_VERSION, valstr);
             }else{
                 mParameters.remove(TICameraParameters::KEY_GPS_VERSION);
@@ -857,16 +888,18 @@
 
         if( (valstr = params.get(TICameraParameters::KEY_EXIF_MODEL)) != NULL )
             {
-            CAMHAL_LOGDB("EXIF Model set %s", params.get(TICameraParameters::KEY_EXIF_MODEL));
+            CAMHAL_LOGDB("EXIF Model set %s", valstr);
             mParameters.set(TICameraParameters::KEY_EXIF_MODEL, valstr);
             }
 
         if( (valstr = params.get(TICameraParameters::KEY_EXIF_MAKE)) != NULL )
             {
-            CAMHAL_LOGDB("EXIF Make set %s", params.get(TICameraParameters::KEY_EXIF_MAKE));
+            CAMHAL_LOGDB("EXIF Make set %s", valstr);
             mParameters.set(TICameraParameters::KEY_EXIF_MAKE, valstr);
             }
 
+#ifdef OMAP_ENHANCEMENT
+
         if( (valstr = params.get(TICameraParameters::KEY_EXP_BRACKETING_RANGE)) != NULL )
             {
             CAMHAL_LOGDB("Exposure Bracketing set %s", params.get(TICameraParameters::KEY_EXP_BRACKETING_RANGE));
@@ -877,9 +910,12 @@
             mParameters.remove(TICameraParameters::KEY_EXP_BRACKETING_RANGE);
             }
 
-        if ((valstr = params.get(CameraParameters::KEY_ZOOM)) != NULL ) {
-            if ((params.getInt(CameraParameters::KEY_ZOOM) >= 0 ) &&
-                (params.getInt(CameraParameters::KEY_ZOOM) <= mMaxZoomSupported )) {
+#endif
+
+        valstr = params.get(CameraParameters::KEY_ZOOM);
+        varint = params.getInt(CameraParameters::KEY_ZOOM);
+        if ( valstr != NULL ) {
+            if ( ( varint >= 0 ) && ( varint <= mMaxZoomSupported ) ) {
                 CAMHAL_LOGDB("Zoom set %s", valstr);
                 doesSetParameterNeedUpdate(valstr,
                                            mParameters.get(CameraParameters::KEY_ZOOM),
@@ -887,13 +923,13 @@
                 mParameters.set(CameraParameters::KEY_ZOOM, valstr);
              } else {
                 CAMHAL_LOGEB("ERROR: Invalid Zoom: %s", valstr);
-                ret = -EINVAL;
+                return BAD_VALUE;
             }
         }
 
         if( (valstr = params.get(CameraParameters::KEY_AUTO_EXPOSURE_LOCK)) != NULL )
           {
-            CAMHAL_LOGDB("Auto Exposure Lock set %s", params.get(CameraParameters::KEY_AUTO_EXPOSURE_LOCK));
+            CAMHAL_LOGDB("Auto Exposure Lock set %s", valstr);
             doesSetParameterNeedUpdate(valstr,
                                        mParameters.get(CameraParameters::KEY_AUTO_EXPOSURE_LOCK),
                                        updateRequired);
@@ -902,7 +938,7 @@
 
         if( (valstr = params.get(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK)) != NULL )
           {
-            CAMHAL_LOGDB("Auto WhiteBalance Lock set %s", params.get(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK));
+            CAMHAL_LOGDB("Auto WhiteBalance Lock set %s", valstr);
             doesSetParameterNeedUpdate(valstr,
                                        mParameters.get(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK),
                                        updateRequired);
@@ -910,20 +946,20 @@
           }
         if( (valstr = params.get(CameraParameters::KEY_METERING_AREAS)) != NULL )
             {
-            CAMHAL_LOGI("Metering areas position set %s", params.get(CameraParameters::KEY_METERING_AREAS));
+            CAMHAL_LOGDB("Metering areas position set %s", valstr);
             mParameters.set(CameraParameters::KEY_METERING_AREAS, valstr);
             }
 
-        CameraParameters adapterParams = mParameters;
-
         // Only send parameters to adapter if preview is already
         // enabled or doesSetParameterNeedUpdate says so. Initial setParameters to camera adapter,
         // will be called in startPreview()
         // TODO(XXX): Need to identify other parameters that need update from camera adapter
         if ( (NULL != mCameraAdapter) && (mPreviewEnabled || updateRequired) ) {
-            ret |= mCameraAdapter->setParameters(adapterParams);
+            ret |= mCameraAdapter->setParameters(mParameters);
         }
 
+#ifdef OMAP_ENHANCEMENT
+
         if( NULL != params.get(TICameraParameters::KEY_TEMP_BRACKETING_RANGE_POS) )
             {
             int posBracketRange = params.getInt(TICameraParameters::KEY_TEMP_BRACKETING_RANGE_POS);
@@ -1001,11 +1037,13 @@
             mParameters.set(TICameraParameters::KEY_SHUTTER_ENABLE, valstr);
             }
 
+#endif
+
     }
 
     //On fail restore old parameters
     if ( NO_ERROR != ret ) {
-        mParameters.unflatten(oldParams.flatten());
+        mParameters = oldParams;
     }
 
     // Restart Preview if needed by KEY_RECODING_HINT only if preview is already running.
@@ -1431,7 +1469,7 @@
 
     ///If we don't have the preview callback enabled and display adapter,
     if(!mSetPreviewWindowCalled || (mDisplayAdapter.get() == NULL)){
-      CAMHAL_LOGI("Preview not started. Preview in progress flag set");
+      CAMHAL_LOGDA("Preview not started. Preview in progress flag set");
       mPreviewStartInProgress = true;
       ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_SWITCH_TO_EXECUTING);
       if ( NO_ERROR != ret ){
@@ -1660,13 +1698,13 @@
         if(mDisplayAdapter.get() != NULL)
         {
             ///NULL window passed, destroy the display adapter if present
-            CAMHAL_LOGI("NULL window passed, destroying display adapter");
+            CAMHAL_LOGDA("NULL window passed, destroying display adapter");
             mDisplayAdapter.clear();
             ///@remarks If there was a window previously existing, we usually expect another valid window to be passed by the client
             ///@remarks so, we will wait until it passes a valid window to begin the preview again
             mSetPreviewWindowCalled = false;
         }
-        CAMHAL_LOGI("NULL ANativeWindow passed to setPreviewWindow");
+        CAMHAL_LOGDA("NULL ANativeWindow passed to setPreviewWindow");
         return NO_ERROR;
     }else if(mDisplayAdapter.get() == NULL)
     {
@@ -1713,12 +1751,15 @@
             // Start the preview since the window is now available
             ret = startPreview();
         }
-    }else
-    {
-        /* If mDisplayAdpater is already created. No need to do anything.
-         * We get a surface handle directly now, so we can reconfigure surface
-         * itself in DisplayAdapter if dimensions have changed
-         */
+    } else {
+        // Update the display adapter with the new window that is passed from CameraService
+        ret = mDisplayAdapter->setPreviewWindow(window);
+        if ( (NO_ERROR == ret) && previewEnabled() ) {
+            restartPreview();
+        } else if (ret == ALREADY_EXISTS) {
+            // ALREADY_EXISTS should be treated as a noop in this case
+            ret = NO_ERROR;
+        }
     }
     LOG_FUNCTION_NAME_EXIT;
 
@@ -1900,6 +1941,7 @@
 bool CameraHal::setVideoModeParameters(const CameraParameters& params)
 {
     const char *valstr = NULL;
+    const char *valstrRemote = NULL;
     bool restartPreviewRequired = false;
     status_t ret = NO_ERROR;
 
@@ -1918,19 +1960,19 @@
     // Check if CAPTURE_MODE is VIDEO_MODE, since VSTAB & VNF work only in VIDEO_MODE.
     valstr = mParameters.get(TICameraParameters::KEY_CAP_MODE);
     if (strcmp(valstr, (const char *) TICameraParameters::VIDEO_MODE) == 0) {
+       valstrRemote = params.get(CameraParameters::KEY_VIDEO_STABILIZATION);
        // set VSTAB. restart is required if vstab value has changed
-       if (params.get(CameraParameters::KEY_VIDEO_STABILIZATION) != NULL) {
+       if ( valstrRemote != NULL) {
             // make sure we support vstab
             if (strcmp(mCameraProperties->get(CameraProperties::VSTAB_SUPPORTED),
                        CameraParameters::TRUE) == 0) {
                 valstr = mParameters.get(CameraParameters::KEY_VIDEO_STABILIZATION);
                 // vstab value has changed
                 if ((valstr != NULL) &&
-                     strcmp(valstr, params.get(CameraParameters::KEY_VIDEO_STABILIZATION)) != 0) {
+                     strcmp(valstr, valstrRemote) != 0) {
                     restartPreviewRequired = true;
                 }
-                mParameters.set(CameraParameters::KEY_VIDEO_STABILIZATION,
-                                params.get(CameraParameters::KEY_VIDEO_STABILIZATION));
+                mParameters.set(CameraParameters::KEY_VIDEO_STABILIZATION, valstrRemote);
             }
         } else if (mParameters.get(CameraParameters::KEY_VIDEO_STABILIZATION)) {
             // vstab was configured but now unset
@@ -1939,16 +1981,17 @@
         }
 
         // Set VNF
-        if (params.get(TICameraParameters::KEY_VNF) == NULL) {
+        valstrRemote = params.get(TICameraParameters::KEY_VNF);
+        if ( valstrRemote == NULL) {
             CAMHAL_LOGDA("Enable VNF");
             mParameters.set(TICameraParameters::KEY_VNF, "1");
             restartPreviewRequired = true;
         } else {
             valstr = mParameters.get(TICameraParameters::KEY_VNF);
-            if (valstr && strcmp(valstr, params.get(TICameraParameters::KEY_VNF)) != 0) {
+            if (valstr && strcmp(valstr, valstrRemote) != 0) {
                 restartPreviewRequired = true;
             }
-            mParameters.set(TICameraParameters::KEY_VNF, params.get(TICameraParameters::KEY_VNF));
+            mParameters.set(TICameraParameters::KEY_VNF, valstrRemote);
         }
 
         // For VSTAB alone for 1080p resolution, padded width goes > 2048, which cannot be rendered by GPU.
@@ -2675,15 +2718,35 @@
     if ( ( NO_ERROR == ret ) && ( NULL == mCameraAdapter ) )
         {
         CAMHAL_LOGEA("No CameraAdapter instance");
-        ret = -EINVAL;
+        return -EINVAL;
         }
 
+    ///////////////////////////////////////////////////////
+    // Following commands do NOT need preview to be started
+    ///////////////////////////////////////////////////////
+    switch(cmd) {
+        case CAMERA_CMD_ENABLE_FOCUS_MOVE_MSG:
+            bool enable = static_cast<bool>(arg1);
+            Mutex::Autolock lock(mLock);
+            if (enable) {
+                mMsgEnabled |= CAMERA_MSG_FOCUS_MOVE;
+            } else {
+                mMsgEnabled &= ~CAMERA_MSG_FOCUS_MOVE;
+            }
+            return NO_ERROR;
+        break;
+    }
+
     if ( ( NO_ERROR == ret ) && ( !previewEnabled() ))
         {
         CAMHAL_LOGEA("Preview is not running");
         ret = -EINVAL;
         }
 
+    ///////////////////////////////////////////////////////
+    // Following commands NEED preview to be started
+    ///////////////////////////////////////////////////////
+
     if ( NO_ERROR == ret )
         {
         switch(cmd)
diff --git a/camera/CameraHalCommon.cpp b/camera/CameraHalCommon.cpp
index 6d4ea2c..7e81a09 100644
--- a/camera/CameraHalCommon.cpp
+++ b/camera/CameraHalCommon.cpp
@@ -46,7 +46,7 @@
     ppm.tv_sec = ppm.tv_sec * 1000000;
     ppm.tv_sec = ppm.tv_sec + ppm.tv_usec - ppm_start.tv_usec;
 
-    LOGD("PPM: %s :%ld.%ld ms", str, ( ppm.tv_sec /1000 ), ( ppm.tv_sec % 1000 ));
+    ALOGD("PPM: %s :%ld.%ld ms", str, ( ppm.tv_sec /1000 ), ( ppm.tv_sec % 1000 ));
 }
 
 #elif PPM_INSTRUMENTATION_ABS
@@ -76,7 +76,7 @@
     absolute *= 1000;
     absolute += ppm.tv_usec /1000;
 
-    LOGD("PPM: %s :%llu.%llu ms : %llu ms", str, ( elapsed /1000 ), ( elapsed % 1000 ), absolute);
+    ALOGD("PPM: %s :%llu.%llu ms : %llu ms", str, ( elapsed /1000 ), ( elapsed % 1000 ), absolute);
 }
 
 #endif
@@ -109,7 +109,7 @@
     ppm.tv_sec = ppm.tv_sec * 1000000;
     ppm.tv_sec = ppm.tv_sec + ppm.tv_usec - ppm_first->tv_usec;
 
-    LOGD("PPM: %s :%ld.%ld ms :  %llu ms", temp_str, ( ppm.tv_sec /1000 ), ( ppm.tv_sec % 1000 ), absolute);
+    ALOGD("PPM: %s :%ld.%ld ms :  %llu ms", temp_str, ( ppm.tv_sec /1000 ), ( ppm.tv_sec % 1000 ), absolute);
 
     va_end(args);
 }
diff --git a/camera/CameraHalUtilClasses.cpp b/camera/CameraHalUtilClasses.cpp
index 3074bc4..073c2b8 100644
--- a/camera/CameraHalUtilClasses.cpp
+++ b/camera/CameraHalUtilClasses.cpp
@@ -1,362 +1,362 @@
-/*

- * Copyright (C) Texas Instruments - http://www.ti.com/

- *

- * 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.

- */

-

-/**

-* @file CameraHalUtilClasses.cpp

-*

-* This file maps the CameraHardwareInterface to the Camera interfaces on OMAP4 (mainly OMX).

-*

-*/

-

-#define LOG_TAG "CameraHAL"

-

-

-#include "CameraHal.h"

-

-namespace android {

-

-/*--------------------FrameProvider Class STARTS here-----------------------------*/

-

-int FrameProvider::enableFrameNotification(int32_t frameTypes)

-{

-    LOG_FUNCTION_NAME;

-    status_t ret = NO_ERROR;

-

-    ///Enable the frame notification to CameraAdapter (which implements FrameNotifier interface)

-    mFrameNotifier->enableMsgType(frameTypes<<MessageNotifier::FRAME_BIT_FIELD_POSITION

-                                    , mFrameCallback

-                                    , NULL

-                                    , mCookie

-                                    );

-

-    LOG_FUNCTION_NAME_EXIT;

-    return ret;

-}

-

-int FrameProvider::disableFrameNotification(int32_t frameTypes)

-{

-    LOG_FUNCTION_NAME;

-    status_t ret = NO_ERROR;

-

-    mFrameNotifier->disableMsgType(frameTypes<<MessageNotifier::FRAME_BIT_FIELD_POSITION

-                                    , mCookie

-                                    );

-

-    LOG_FUNCTION_NAME_EXIT;

-    return ret;

-}

-

-int FrameProvider::returnFrame(void *frameBuf, CameraFrame::FrameType frameType)

-{

-    status_t ret = NO_ERROR;

-

-    mFrameNotifier->returnFrame(frameBuf, frameType);

-

-    return ret;

-}

-

-void FrameProvider::addFramePointers(void *frameBuf, void *buf)

-{

-  mFrameNotifier->addFramePointers(frameBuf, buf);

-  return;

-}

-

-void FrameProvider::removeFramePointers()

-{

-  mFrameNotifier->removeFramePointers();

-  return;

-}

-

-/*--------------------FrameProvider Class ENDS here-----------------------------*/

-

-/*--------------------EventProvider Class STARTS here-----------------------------*/

-

-int EventProvider::enableEventNotification(int32_t frameTypes)

-{

-    LOG_FUNCTION_NAME;

-    status_t ret = NO_ERROR;

-

-    ///Enable the frame notification to CameraAdapter (which implements FrameNotifier interface)

-    mEventNotifier->enableMsgType(frameTypes<<MessageNotifier::EVENT_BIT_FIELD_POSITION

-                                    , NULL

-                                    , mEventCallback

-                                    , mCookie

-                                    );

-

-    LOG_FUNCTION_NAME_EXIT;

-    return ret;

-}

-

-int EventProvider::disableEventNotification(int32_t frameTypes)

-{

-    LOG_FUNCTION_NAME;

-    status_t ret = NO_ERROR;

-

-    mEventNotifier->disableMsgType(frameTypes<<MessageNotifier::FRAME_BIT_FIELD_POSITION

-                                    , mCookie

-                                    );

-

-    LOG_FUNCTION_NAME_EXIT;

-    return ret;

-}

-

-/*--------------------EventProvider Class ENDS here-----------------------------*/

-

-/*--------------------CameraArea Class STARTS here-----------------------------*/

-

-status_t CameraArea::transfrom(size_t width,

-                               size_t height,

-                               size_t &top,

-                               size_t &left,

-                               size_t &areaWidth,

-                               size_t &areaHeight)

-{

-    status_t ret = NO_ERROR;

-    size_t hRange, vRange;

-    double hScale, vScale;

-

-    LOG_FUNCTION_NAME

-

-    hRange = CameraArea::RIGHT - CameraArea::LEFT;

-    vRange = CameraArea::BOTTOM - CameraArea::TOP;

-    hScale = ( double ) width / ( double ) hRange;

-    vScale = ( double ) height / ( double ) vRange;

-

-    top = ( mTop + vRange / 2 ) * vScale;

-    left = ( mLeft + hRange / 2 ) * hScale;

-    areaHeight = ( mBottom + vRange / 2 ) * vScale;

-    areaHeight -= top;

-    areaWidth = ( mRight + hRange / 2) * hScale;

-    areaWidth -= left;

-

-    LOG_FUNCTION_NAME_EXIT

-

-    return ret;

-}

-

-status_t CameraArea::checkArea(ssize_t top,

-                               ssize_t left,

-                               ssize_t bottom,

-                               ssize_t right,

-                               ssize_t weight)

-{

-

-    //Handles the invalid regin corner case.

-    if ( ( 0 == top ) && ( 0 == left ) && ( 0 == bottom ) && ( 0 == right ) && ( 0 == weight ) ) {

-        return NO_ERROR;

-    }

-

-    if ( ( CameraArea::WEIGHT_MIN > weight ) ||  ( CameraArea::WEIGHT_MAX < weight ) ) {

-        CAMHAL_LOGEB("Camera area weight is invalid %d", weight);

-        return -EINVAL;

-    }

-

-    if ( ( CameraArea::TOP > top ) || ( CameraArea::BOTTOM < top ) ) {

-        CAMHAL_LOGEB("Camera area top coordinate is invalid %d", top );

-        return -EINVAL;

-    }

-

-    if ( ( CameraArea::TOP > bottom ) || ( CameraArea::BOTTOM < bottom ) ) {

-        CAMHAL_LOGEB("Camera area bottom coordinate is invalid %d", bottom );

-        return -EINVAL;

-    }

-

-    if ( ( CameraArea::LEFT > left ) || ( CameraArea::RIGHT < left ) ) {

-        CAMHAL_LOGEB("Camera area left coordinate is invalid %d", left );

-        return -EINVAL;

-    }

-

-    if ( ( CameraArea::LEFT > right ) || ( CameraArea::RIGHT < right ) ) {

-        CAMHAL_LOGEB("Camera area right coordinate is invalid %d", right );

-        return -EINVAL;

-    }

-

-    if ( left >= right ) {

-        CAMHAL_LOGEA("Camera area left larger than right");

-        return -EINVAL;

-    }

-

-    if ( top >= bottom ) {

-        CAMHAL_LOGEA("Camera area top larger than bottom");

-        return -EINVAL;

-    }

-

-    return NO_ERROR;

-}

-

-status_t CameraArea::parseAreas(const char *area,

-                                size_t areaLength,

-                                Vector< sp<CameraArea> > &areas)

-{

-    status_t ret = NO_ERROR;

-    char *ctx;

-    char *pArea = NULL;

-    char *pStart = NULL;

-    char *pEnd = NULL;

-    const char *startToken = "(";

-    const char endToken = ')';

-    const char sep = ',';

-    ssize_t top, left, bottom, right, weight;

-    char *tmpBuffer = NULL;

-    sp<CameraArea> currentArea;

-

-    LOG_FUNCTION_NAME

-

-    if ( ( NULL == area ) ||

-         ( 0 >= areaLength ) )

-        {

-        return -EINVAL;

-        }

-

-    tmpBuffer = ( char * ) malloc(areaLength);

-    if ( NULL == tmpBuffer )

-        {

-        return -ENOMEM;

-        }

-

-    memcpy(tmpBuffer, area, areaLength);

-

-    pArea = strtok_r(tmpBuffer, startToken, &ctx);

-

-    do

-        {

-

-        pStart = pArea;

-        if ( NULL == pStart )

-            {

-            CAMHAL_LOGEA("Parsing of the left area coordinate failed!");

-            ret = -EINVAL;

-            break;

-            }

-        else

-            {

-            left = static_cast<ssize_t>(strtol(pStart, &pEnd, 10));

-            }

-

-        if ( sep != *pEnd )

-            {

-            CAMHAL_LOGEA("Parsing of the top area coordinate failed!");

-            ret = -EINVAL;

-            break;

-            }

-        else

-            {

-            top = static_cast<ssize_t>(strtol(pEnd+1, &pEnd, 10));

-            }

-

-        if ( sep != *pEnd )

-            {

-            CAMHAL_LOGEA("Parsing of the right area coordinate failed!");

-            ret = -EINVAL;

-            break;

-            }

-        else

-            {

-            right = static_cast<ssize_t>(strtol(pEnd+1, &pEnd, 10));

-            }

-

-        if ( sep != *pEnd )

-            {

-            CAMHAL_LOGEA("Parsing of the bottom area coordinate failed!");

-            ret = -EINVAL;

-            break;

-            }

-        else

-            {

-            bottom = static_cast<ssize_t>(strtol(pEnd+1, &pEnd, 10));

-            }

-

-        if ( sep != *pEnd )

-            {

-            CAMHAL_LOGEA("Parsing of the weight area coordinate failed!");

-            ret = -EINVAL;

-            break;

-            }

-        else

-            {

-            weight = static_cast<ssize_t>(strtol(pEnd+1, &pEnd, 10));

-            }

-

-        if ( endToken != *pEnd )

-            {

-            CAMHAL_LOGEA("Malformed area!");

-            ret = -EINVAL;

-            break;

-            }

-

-        ret = checkArea(top, left, bottom, right, weight);

-        if ( NO_ERROR != ret ) {

-            break;

-        }

-

-        currentArea = new CameraArea(top, left, bottom, right, weight);

-        CAMHAL_LOGDB("Area parsed [%dx%d, %dx%d] %d",

-                     ( int ) top,

-                     ( int ) left,

-                     ( int ) bottom,

-                     ( int ) right,

-                     ( int ) weight);

-        if ( NULL != currentArea.get() )

-            {

-            areas.add(currentArea);

-            }

-        else

-            {

-            ret = -ENOMEM;

-            break;

-            }

-

-        pArea = strtok_r(NULL, startToken, &ctx);

-

-        }

-    while ( NULL != pArea );

-

-    if ( NULL != tmpBuffer )

-        {

-        free(tmpBuffer);

-        }

-

-    LOG_FUNCTION_NAME_EXIT

-

-    return ret;

-}

-

-bool CameraArea::areAreasDifferent(Vector< sp<CameraArea> > &area1,

-                                    Vector< sp<CameraArea> > &area2) {

-    if (area1.size() != area2.size()) {

-        return true;

-    }

-

-    // not going to care about sorting order for now

-    for (int i = 0; i < area1.size(); i++) {

-        if (!area1.itemAt(i)->compare(area2.itemAt(i))) {

-            return true;

-        }

-    }

-

-    return false;

-}

-

-bool CameraArea::compare(const sp<CameraArea> &area) {

-    return ((mTop == area->mTop) && (mLeft == area->mLeft) &&

-            (mBottom == area->mBottom) && (mRight == area->mRight) &&

-            (mWeight == area->mWeight));

-}

-

-

-/*--------------------CameraArea Class ENDS here-----------------------------*/

-

-};

+/*
+ * Copyright (C) Texas Instruments - http://www.ti.com/
+ *
+ * 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.
+ */
+
+/**
+* @file CameraHalUtilClasses.cpp
+*
+* This file maps the CameraHardwareInterface to the Camera interfaces on OMAP4 (mainly OMX).
+*
+*/
+
+#define LOG_TAG "CameraHAL"
+
+
+#include "CameraHal.h"
+
+namespace android {
+
+/*--------------------FrameProvider Class STARTS here-----------------------------*/
+
+int FrameProvider::enableFrameNotification(int32_t frameTypes)
+{
+    LOG_FUNCTION_NAME;
+    status_t ret = NO_ERROR;
+
+    ///Enable the frame notification to CameraAdapter (which implements FrameNotifier interface)
+    mFrameNotifier->enableMsgType(frameTypes<<MessageNotifier::FRAME_BIT_FIELD_POSITION
+                                    , mFrameCallback
+                                    , NULL
+                                    , mCookie
+                                    );
+
+    LOG_FUNCTION_NAME_EXIT;
+    return ret;
+}
+
+int FrameProvider::disableFrameNotification(int32_t frameTypes)
+{
+    LOG_FUNCTION_NAME;
+    status_t ret = NO_ERROR;
+
+    mFrameNotifier->disableMsgType(frameTypes<<MessageNotifier::FRAME_BIT_FIELD_POSITION
+                                    , mCookie
+                                    );
+
+    LOG_FUNCTION_NAME_EXIT;
+    return ret;
+}
+
+int FrameProvider::returnFrame(void *frameBuf, CameraFrame::FrameType frameType)
+{
+    status_t ret = NO_ERROR;
+
+    mFrameNotifier->returnFrame(frameBuf, frameType);
+
+    return ret;
+}
+
+void FrameProvider::addFramePointers(void *frameBuf, void *buf)
+{
+  mFrameNotifier->addFramePointers(frameBuf, buf);
+  return;
+}
+
+void FrameProvider::removeFramePointers()
+{
+  mFrameNotifier->removeFramePointers();
+  return;
+}
+
+/*--------------------FrameProvider Class ENDS here-----------------------------*/
+
+/*--------------------EventProvider Class STARTS here-----------------------------*/
+
+int EventProvider::enableEventNotification(int32_t frameTypes)
+{
+    LOG_FUNCTION_NAME;
+    status_t ret = NO_ERROR;
+
+    ///Enable the frame notification to CameraAdapter (which implements FrameNotifier interface)
+    mEventNotifier->enableMsgType(frameTypes<<MessageNotifier::EVENT_BIT_FIELD_POSITION
+                                    , NULL
+                                    , mEventCallback
+                                    , mCookie
+                                    );
+
+    LOG_FUNCTION_NAME_EXIT;
+    return ret;
+}
+
+int EventProvider::disableEventNotification(int32_t frameTypes)
+{
+    LOG_FUNCTION_NAME;
+    status_t ret = NO_ERROR;
+
+    mEventNotifier->disableMsgType(frameTypes<<MessageNotifier::FRAME_BIT_FIELD_POSITION
+                                    , mCookie
+                                    );
+
+    LOG_FUNCTION_NAME_EXIT;
+    return ret;
+}
+
+/*--------------------EventProvider Class ENDS here-----------------------------*/
+
+/*--------------------CameraArea Class STARTS here-----------------------------*/
+
+status_t CameraArea::transfrom(size_t width,
+                               size_t height,
+                               size_t &top,
+                               size_t &left,
+                               size_t &areaWidth,
+                               size_t &areaHeight)
+{
+    status_t ret = NO_ERROR;
+    size_t hRange, vRange;
+    double hScale, vScale;
+
+    LOG_FUNCTION_NAME
+
+    hRange = CameraArea::RIGHT - CameraArea::LEFT;
+    vRange = CameraArea::BOTTOM - CameraArea::TOP;
+    hScale = ( double ) width / ( double ) hRange;
+    vScale = ( double ) height / ( double ) vRange;
+
+    top = ( mTop + vRange / 2 ) * vScale;
+    left = ( mLeft + hRange / 2 ) * hScale;
+    areaHeight = ( mBottom + vRange / 2 ) * vScale;
+    areaHeight -= top;
+    areaWidth = ( mRight + hRange / 2) * hScale;
+    areaWidth -= left;
+
+    LOG_FUNCTION_NAME_EXIT
+
+    return ret;
+}
+
+status_t CameraArea::checkArea(ssize_t top,
+                               ssize_t left,
+                               ssize_t bottom,
+                               ssize_t right,
+                               ssize_t weight)
+{
+
+    //Handles the invalid regin corner case.
+    if ( ( 0 == top ) && ( 0 == left ) && ( 0 == bottom ) && ( 0 == right ) && ( 0 == weight ) ) {
+        return NO_ERROR;
+    }
+
+    if ( ( CameraArea::WEIGHT_MIN > weight ) ||  ( CameraArea::WEIGHT_MAX < weight ) ) {
+        CAMHAL_LOGEB("Camera area weight is invalid %d", weight);
+        return -EINVAL;
+    }
+
+    if ( ( CameraArea::TOP > top ) || ( CameraArea::BOTTOM < top ) ) {
+        CAMHAL_LOGEB("Camera area top coordinate is invalid %d", top );
+        return -EINVAL;
+    }
+
+    if ( ( CameraArea::TOP > bottom ) || ( CameraArea::BOTTOM < bottom ) ) {
+        CAMHAL_LOGEB("Camera area bottom coordinate is invalid %d", bottom );
+        return -EINVAL;
+    }
+
+    if ( ( CameraArea::LEFT > left ) || ( CameraArea::RIGHT < left ) ) {
+        CAMHAL_LOGEB("Camera area left coordinate is invalid %d", left );
+        return -EINVAL;
+    }
+
+    if ( ( CameraArea::LEFT > right ) || ( CameraArea::RIGHT < right ) ) {
+        CAMHAL_LOGEB("Camera area right coordinate is invalid %d", right );
+        return -EINVAL;
+    }
+
+    if ( left >= right ) {
+        CAMHAL_LOGEA("Camera area left larger than right");
+        return -EINVAL;
+    }
+
+    if ( top >= bottom ) {
+        CAMHAL_LOGEA("Camera area top larger than bottom");
+        return -EINVAL;
+    }
+
+    return NO_ERROR;
+}
+
+status_t CameraArea::parseAreas(const char *area,
+                                size_t areaLength,
+                                Vector< sp<CameraArea> > &areas)
+{
+    status_t ret = NO_ERROR;
+    char *ctx;
+    char *pArea = NULL;
+    char *pStart = NULL;
+    char *pEnd = NULL;
+    const char *startToken = "(";
+    const char endToken = ')';
+    const char sep = ',';
+    ssize_t top, left, bottom, right, weight;
+    char *tmpBuffer = NULL;
+    sp<CameraArea> currentArea;
+
+    LOG_FUNCTION_NAME
+
+    if ( ( NULL == area ) ||
+         ( 0 >= areaLength ) )
+        {
+        return -EINVAL;
+        }
+
+    tmpBuffer = ( char * ) malloc(areaLength);
+    if ( NULL == tmpBuffer )
+        {
+        return -ENOMEM;
+        }
+
+    memcpy(tmpBuffer, area, areaLength);
+
+    pArea = strtok_r(tmpBuffer, startToken, &ctx);
+
+    do
+        {
+
+        pStart = pArea;
+        if ( NULL == pStart )
+            {
+            CAMHAL_LOGEA("Parsing of the left area coordinate failed!");
+            ret = -EINVAL;
+            break;
+            }
+        else
+            {
+            left = static_cast<ssize_t>(strtol(pStart, &pEnd, 10));
+            }
+
+        if ( sep != *pEnd )
+            {
+            CAMHAL_LOGEA("Parsing of the top area coordinate failed!");
+            ret = -EINVAL;
+            break;
+            }
+        else
+            {
+            top = static_cast<ssize_t>(strtol(pEnd+1, &pEnd, 10));
+            }
+
+        if ( sep != *pEnd )
+            {
+            CAMHAL_LOGEA("Parsing of the right area coordinate failed!");
+            ret = -EINVAL;
+            break;
+            }
+        else
+            {
+            right = static_cast<ssize_t>(strtol(pEnd+1, &pEnd, 10));
+            }
+
+        if ( sep != *pEnd )
+            {
+            CAMHAL_LOGEA("Parsing of the bottom area coordinate failed!");
+            ret = -EINVAL;
+            break;
+            }
+        else
+            {
+            bottom = static_cast<ssize_t>(strtol(pEnd+1, &pEnd, 10));
+            }
+
+        if ( sep != *pEnd )
+            {
+            CAMHAL_LOGEA("Parsing of the weight area coordinate failed!");
+            ret = -EINVAL;
+            break;
+            }
+        else
+            {
+            weight = static_cast<ssize_t>(strtol(pEnd+1, &pEnd, 10));
+            }
+
+        if ( endToken != *pEnd )
+            {
+            CAMHAL_LOGEA("Malformed area!");
+            ret = -EINVAL;
+            break;
+            }
+
+        ret = checkArea(top, left, bottom, right, weight);
+        if ( NO_ERROR != ret ) {
+            break;
+        }
+
+        currentArea = new CameraArea(top, left, bottom, right, weight);
+        CAMHAL_LOGDB("Area parsed [%dx%d, %dx%d] %d",
+                     ( int ) top,
+                     ( int ) left,
+                     ( int ) bottom,
+                     ( int ) right,
+                     ( int ) weight);
+        if ( NULL != currentArea.get() )
+            {
+            areas.add(currentArea);
+            }
+        else
+            {
+            ret = -ENOMEM;
+            break;
+            }
+
+        pArea = strtok_r(NULL, startToken, &ctx);
+
+        }
+    while ( NULL != pArea );
+
+    if ( NULL != tmpBuffer )
+        {
+        free(tmpBuffer);
+        }
+
+    LOG_FUNCTION_NAME_EXIT
+
+    return ret;
+}
+
+bool CameraArea::areAreasDifferent(Vector< sp<CameraArea> > &area1,
+                                    Vector< sp<CameraArea> > &area2) {
+    if (area1.size() != area2.size()) {
+        return true;
+    }
+
+    // not going to care about sorting order for now
+    for (int i = 0; i < area1.size(); i++) {
+        if (!area1.itemAt(i)->compare(area2.itemAt(i))) {
+            return true;
+        }
+    }
+
+    return false;
+}
+
+bool CameraArea::compare(const sp<CameraArea> &area) {
+    return ((mTop == area->mTop) && (mLeft == area->mLeft) &&
+            (mBottom == area->mBottom) && (mRight == area->mRight) &&
+            (mWeight == area->mWeight));
+}
+
+
+/*--------------------CameraArea Class ENDS here-----------------------------*/
+
+};
diff --git a/camera/CameraHal_Module.cpp b/camera/CameraHal_Module.cpp
index 511cbc2..cb4e804 100644
--- a/camera/CameraHal_Module.cpp
+++ b/camera/CameraHal_Module.cpp
@@ -78,7 +78,7 @@
     int rv = -EINVAL;
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return rv;
@@ -99,7 +99,7 @@
 {
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return;
@@ -113,7 +113,7 @@
 {
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return;
@@ -127,7 +127,7 @@
 {
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return;
@@ -141,7 +141,7 @@
 {
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return 0;
@@ -156,7 +156,7 @@
     int rv = -EINVAL;
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return rv;
@@ -172,7 +172,7 @@
 {
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return;
@@ -187,7 +187,7 @@
     int rv = -EINVAL;
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return rv;
@@ -203,7 +203,7 @@
     int rv = -EINVAL;
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return rv;
@@ -221,7 +221,7 @@
     int rv = -EINVAL;
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return rv;
@@ -236,7 +236,7 @@
 {
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return;
@@ -251,7 +251,7 @@
     int rv = -EINVAL;
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return rv;
@@ -267,7 +267,7 @@
 {
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return;
@@ -282,7 +282,7 @@
     int rv = -EINVAL;
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return rv;
@@ -298,7 +298,7 @@
     int rv = -EINVAL;
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return rv;
@@ -314,7 +314,7 @@
     int rv = -EINVAL;
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return rv;
@@ -330,7 +330,7 @@
     int rv = -EINVAL;
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return rv;
@@ -346,7 +346,7 @@
     int rv = -EINVAL;
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return rv;
@@ -362,7 +362,7 @@
     char* param = NULL;
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return NULL;
@@ -378,7 +378,7 @@
 {
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return;
@@ -394,7 +394,7 @@
     int rv = -EINVAL;
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return rv;
@@ -409,7 +409,7 @@
 {
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     if(!device)
         return;
@@ -440,7 +440,7 @@
     int ret = 0;
     ti_camera_device_t* ti_dev = NULL;
 
-    LOGV("%s", __FUNCTION__);
+    ALOGV("%s", __FUNCTION__);
 
     android::Mutex::Autolock lock(gCameraHalDeviceLock);
 
@@ -501,7 +501,7 @@
 
         if(cameraid > num_cameras)
         {
-            LOGE("camera service provided cameraid out of bounds, "
+            ALOGE("camera service provided cameraid out of bounds, "
                     "cameraid = %d, num supported = %d",
                     cameraid, num_cameras);
             rv = -EINVAL;
@@ -510,7 +510,7 @@
 
         if(gCamerasOpen >= MAX_SIMUL_CAMERAS_SUPPORTED)
         {
-            LOGE("maximum number of cameras already open");
+            ALOGE("maximum number of cameras already open");
             rv = -ENOMEM;
             goto fail;
         }
@@ -518,7 +518,7 @@
         camera_device = (ti_camera_device_t*)malloc(sizeof(*camera_device));
         if(!camera_device)
         {
-            LOGE("camera_device allocation fail");
+            ALOGE("camera_device allocation fail");
             rv = -ENOMEM;
             goto fail;
         }
@@ -526,7 +526,7 @@
         camera_ops = (camera_device_ops_t*)malloc(sizeof(*camera_ops));
         if(!camera_ops)
         {
-            LOGE("camera_ops allocation fail");
+            ALOGE("camera_ops allocation fail");
             rv = -ENOMEM;
             goto fail;
         }
@@ -572,7 +572,7 @@
 
         if(gCameraProperties.getProperties(cameraid, &properties) < 0)
         {
-            LOGE("Couldn't get camera properties");
+            ALOGE("Couldn't get camera properties");
             rv = -ENOMEM;
             goto fail;
         }
@@ -581,14 +581,14 @@
 
         if(!camera)
         {
-            LOGE("Couldn't create instance of CameraHal class");
+            ALOGE("Couldn't create instance of CameraHal class");
             rv = -ENOMEM;
             goto fail;
         }
 
         if(properties && (camera->initialize(properties) != android::NO_ERROR))
         {
-            LOGE("Couldn't initialize camera instance");
+            ALOGE("Couldn't initialize camera instance");
             rv = -ENODEV;
             goto fail;
         }
@@ -656,7 +656,7 @@
     //Get camera properties for camera index
     if(gCameraProperties.getProperties(camera_id, &properties) < 0)
     {
-        LOGE("Couldn't get camera properties");
+        ALOGE("Couldn't get camera properties");
         rv = -EINVAL;
         goto end;
     }
diff --git a/camera/CameraProperties.cpp b/camera/CameraProperties.cpp
index 0e83fc9..5d3ff20 100644
--- a/camera/CameraProperties.cpp
+++ b/camera/CameraProperties.cpp
@@ -100,13 +100,13 @@
     mCamerasSupported = CameraAdapter_Capabilities(mCameraProps, mCamerasSupported, MAX_CAMERAS_SUPPORTED);
 
     if((int)mCamerasSupported < 0) {
-        LOGE("error while getting capabilities");
+        ALOGE("error while getting capabilities");
         ret = UNKNOWN_ERROR;
     } else if (mCamerasSupported > MAX_CAMERAS_SUPPORTED) {
-        LOGE("returned too many adapaters");
+        ALOGE("returned too many adapaters");
         ret = UNKNOWN_ERROR;
     } else {
-        LOGE("num_cameras = %d", mCamerasSupported);
+        ALOGE("num_cameras = %d", mCamerasSupported);
 
         for (unsigned int i = 0; i < mCamerasSupported; i++) {
             mCameraProps[i].set(CAMERA_SENSOR_INDEX, i);
@@ -114,7 +114,7 @@
         }
     }
 
-    LOGV("mCamerasSupported = %d", mCamerasSupported);
+    ALOGV("mCamerasSupported = %d", mCamerasSupported);
     LOG_FUNCTION_NAME_EXIT;
     return ret;
 }
diff --git a/camera/Encoder_libjpeg.cpp b/camera/Encoder_libjpeg.cpp
index 7a6054f..d50b2ea 100644
--- a/camera/Encoder_libjpeg.cpp
+++ b/camera/Encoder_libjpeg.cpp
@@ -44,6 +44,7 @@
 }
 
 #define ARRAY_SIZE(array) (sizeof((array)) / sizeof((array)[0]))
+#define MIN(x,y) ((x < y) ? x : y)
 
 namespace android {
 struct string_pair {
@@ -266,7 +267,7 @@
     ResetJpgfile();
     if (ReadJpegSectionsFromBuffer(jpeg, jpeg_size, read_mode)) {
         jpeg_opened = true;
-        create_EXIF(table, exif_tag_count, gps_tag_count);
+        create_EXIF(table, exif_tag_count, gps_tag_count, has_datetime_tag);
     }
 }
 
@@ -305,7 +306,7 @@
 }
 
 status_t ExifElementsTable::insertElement(const char* tag, const char* value) {
-    int value_length = 0;
+    unsigned int value_length = 0;
     status_t ret = NO_ERROR;
 
     if (!value || !tag) {
@@ -331,6 +332,10 @@
         table[position].GpsTag = FALSE;
         table[position].Tag = TagNameToValue(tag);
         exif_tag_count++;
+
+        if (strcmp(tag, TAG_DATETIME) == 0) {
+            has_datetime_tag = true;
+        }
     }
 
     table[position].DataLength = 0;
diff --git a/camera/MemoryManager.cpp b/camera/MemoryManager.cpp
index 55675d9..b1dbbcf 100644
--- a/camera/MemoryManager.cpp
+++ b/camera/MemoryManager.cpp
@@ -1,167 +1,173 @@
-/*

- * Copyright (C) Texas Instruments - http://www.ti.com/

- *

- * Licensed under the Apache License, Version 2.0 (the "License");

- * you may not use this file except in compliance with the License.

- * You may obtain a copy of the License at

- *

- *      http://www.apache.org/licenses/LICENSE-2.0

- *

- * Unless required by applicable law or agreed to in writing, software

- * distributed under the License is distributed on an "AS IS" BASIS,

- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

- * See the License for the specific language governing permissions and

- * limitations under the License.

- */

-

-

-

-#define LOG_TAG "CameraHAL"

-

-

-#include "CameraHal.h"

-#include "TICameraParameters.h"

-

-extern "C" {

-

-#include <ion.h>
+/*
+ * Copyright (C) Texas Instruments - http://www.ti.com/
+ *
+ * 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.
+ */
 
-//#include <timm_osal_interfaces.h>

-//#include <timm_osal_trace.h>

-

-

-};

-

-namespace android {

-

-///@todo Move these constants to a common header file, preferably in tiler.h

-#define STRIDE_8BIT (4 * 1024)

-#define STRIDE_16BIT (4 * 1024)

-

-#define ALLOCATION_2D 2

-

-///Utility Macro Declarations

-

-/*--------------------MemoryManager Class STARTS here-----------------------------*/

-void* MemoryManager::allocateBuffer(int width, int height, const char* format, int &bytes, int numBufs)

-{

-    LOG_FUNCTION_NAME;

 
-    if(mIonFd == 0)
+
+#define LOG_TAG "CameraHAL"
+
+
+#include "CameraHal.h"
+#include "TICameraParameters.h"
+
+extern "C" {
+
+#include <ion/ion.h>
+
+//#include <timm_osal_interfaces.h>
+//#include <timm_osal_trace.h>
+
+
+};
+
+namespace android {
+
+///@todo Move these constants to a common header file, preferably in tiler.h
+#define STRIDE_8BIT (4 * 1024)
+#define STRIDE_16BIT (4 * 1024)
+
+#define ALLOCATION_2D 2
+
+///Utility Macro Declarations
+
+/*--------------------MemoryManager Class STARTS here-----------------------------*/
+void* MemoryManager::allocateBuffer(int width, int height, const char* format, int &bytes, int numBufs)
+{
+    LOG_FUNCTION_NAME;
+
+    if(mIonFd < 0)
         {
         mIonFd = ion_open();
-        if(mIonFd == 0)
+        if(mIonFd < 0)
             {
             CAMHAL_LOGEA("ion_open failed!!!");
             return NULL;
             }
         }
 
-    ///We allocate numBufs+1 because the last entry will be marked NULL to indicate end of array, which is used when freeing

-    ///the buffers

-    const uint numArrayEntriesC = (uint)(numBufs+1);

-

-    ///Allocate a buffer array

-    uint32_t *bufsArr = new uint32_t [numArrayEntriesC];

-    if(!bufsArr)

-        {

-        CAMHAL_LOGEB("Allocation failed when creating buffers array of %d uint32_t elements", numArrayEntriesC);

-        LOG_FUNCTION_NAME_EXIT;

-        return NULL;

-        }

-

-    ///Initialize the array with zeros - this will help us while freeing the array in case of error

-    ///If a value of an array element is NULL, it means we didnt allocate it

-    memset(bufsArr, 0, sizeof(*bufsArr) * numArrayEntriesC);

-

+    ///We allocate numBufs+1 because the last entry will be marked NULL to indicate end of array, which is used when freeing
+    ///the buffers
+    const uint numArrayEntriesC = (uint)(numBufs+1);
+
+    ///Allocate a buffer array
+    uint32_t *bufsArr = new uint32_t [numArrayEntriesC];
+    if(!bufsArr)
+        {
+        CAMHAL_LOGEB("Allocation failed when creating buffers array of %d uint32_t elements", numArrayEntriesC);
+        goto error;
+        }
+
+    ///Initialize the array with zeros - this will help us while freeing the array in case of error
+    ///If a value of an array element is NULL, it means we didnt allocate it
+    memset(bufsArr, 0, sizeof(*bufsArr) * numArrayEntriesC);
+
     //2D Allocations are not supported currently
     if(bytes != 0)
-        {

+        {
         struct ion_handle *handle;
         int mmap_fd;
 
-        ///1D buffers

-        for (int i = 0; i < numBufs; i++)

-            {

+        ///1D buffers
+        for (int i = 0; i < numBufs; i++)
+            {
             int ret = ion_alloc(mIonFd, bytes, 0, 1 << ION_HEAP_TYPE_CARVEOUT, &handle);
             if(ret < 0)
-                {

+                {
                 CAMHAL_LOGEB("ion_alloc resulted in error %d", ret);
-                goto error;

-                }

+                goto error;
+                }
 
             CAMHAL_LOGDB("Before mapping, handle = %x, nSize = %d", handle, bytes);
             if ((ret = ion_map(mIonFd, handle, bytes, PROT_READ | PROT_WRITE, MAP_SHARED, 0,
                           (unsigned char**)&bufsArr[i], &mmap_fd)) < 0)
-                {

+                {
                 CAMHAL_LOGEB("Userspace mapping of ION buffers returned error %d", ret);
                 ion_free(mIonFd, handle);
                 goto error;
-                }

+                }
 
             mIonHandleMap.add(bufsArr[i], (unsigned int)handle);
             mIonFdMap.add(bufsArr[i], (unsigned int) mmap_fd);
             mIonBufLength.add(bufsArr[i], (unsigned int) bytes);
-            }

-

-        }

+            }
+
+        }
     else // If bytes is not zero, then it is a 2-D tiler buffer request
-        {

-        }

-

-        LOG_FUNCTION_NAME_EXIT;

-

-        return (void*)bufsArr;

-

+        {
+        }
+
+        LOG_FUNCTION_NAME_EXIT;
+
+        return (void*)bufsArr;
+
 error:
-    LOGE("Freeing buffers already allocated after error occurred");
-    freeBuffer(bufsArr);
-

+    ALOGE("Freeing buffers already allocated after error occurred");
+    if(bufsArr)
+        freeBuffer(bufsArr);
+
     if ( NULL != mErrorNotifier.get() )
         {
         mErrorNotifier->errorNotify(-ENOMEM);
         }
-

+
+    if (mIonFd >= 0)
+    {
+        ion_close(mIonFd);
+        mIonFd = -1;
+    }
+
     LOG_FUNCTION_NAME_EXIT;
     return NULL;
-}

-

-//TODO: Get needed data to map tiler buffers

-//Return dummy data for now

-uint32_t * MemoryManager::getOffsets()

-{

-    LOG_FUNCTION_NAME;

-

-    LOG_FUNCTION_NAME_EXIT;

-

-    return NULL;

-}

-

-int MemoryManager::getFd()

-{

-    LOG_FUNCTION_NAME;

-

-    LOG_FUNCTION_NAME_EXIT;

-

-    return -1;

-}

-

-int MemoryManager::freeBuffer(void* buf)

-{

-    status_t ret = NO_ERROR;

-    LOG_FUNCTION_NAME;

-

-    uint32_t *bufEntry = (uint32_t*)buf;

-

-    if(!bufEntry)

-        {

-        CAMHAL_LOGEA("NULL pointer passed to freebuffer");

-        LOG_FUNCTION_NAME_EXIT;

-        return BAD_VALUE;

-        }

-

-    while(*bufEntry)

-        {

+}
+
+//TODO: Get needed data to map tiler buffers
+//Return dummy data for now
+uint32_t * MemoryManager::getOffsets()
+{
+    LOG_FUNCTION_NAME;
+
+    LOG_FUNCTION_NAME_EXIT;
+
+    return NULL;
+}
+
+int MemoryManager::getFd()
+{
+    LOG_FUNCTION_NAME;
+
+    LOG_FUNCTION_NAME_EXIT;
+
+    return -1;
+}
+
+int MemoryManager::freeBuffer(void* buf)
+{
+    status_t ret = NO_ERROR;
+    LOG_FUNCTION_NAME;
+
+    uint32_t *bufEntry = (uint32_t*)buf;
+
+    if(!bufEntry)
+        {
+        CAMHAL_LOGEA("NULL pointer passed to freebuffer");
+        LOG_FUNCTION_NAME_EXIT;
+        return BAD_VALUE;
+        }
+
+    while(*bufEntry)
+        {
         unsigned int ptr = (unsigned int) *bufEntry++;
         if(mIonBufLength.valueFor(ptr))
             {
@@ -176,47 +182,47 @@
             {
             CAMHAL_LOGEA("Not a valid Memory Manager buffer");
             }
-        }

-

-    ///@todo Check if this way of deleting array is correct, else use malloc/free

-    uint32_t * bufArr = (uint32_t*)buf;

-    delete [] bufArr;

-

+        }
+
+    ///@todo Check if this way of deleting array is correct, else use malloc/free
+    uint32_t * bufArr = (uint32_t*)buf;
+    delete [] bufArr;
+
     if(mIonBufLength.size() == 0)
         {
-        if(mIonFd)
+        if(mIonFd >= 0)
             {
             ion_close(mIonFd);
-            mIonFd = 0;
+            mIonFd = -1;
             }
         }
-    LOG_FUNCTION_NAME_EXIT;

-    return ret;

-}

-

-status_t MemoryManager::setErrorHandler(ErrorNotifier *errorNotifier)

-{

-    status_t ret = NO_ERROR;

-

-    LOG_FUNCTION_NAME;

-

-    if ( NULL == errorNotifier )

-        {

-        CAMHAL_LOGEA("Invalid Error Notifier reference");

-        ret = -EINVAL;

-        }

-

-    if ( NO_ERROR == ret )

-        {

-        mErrorNotifier = errorNotifier;

-        }

-

-    LOG_FUNCTION_NAME_EXIT;

-

-    return ret;

-}

-

-};

-

-

-/*--------------------MemoryManager Class ENDS here-----------------------------*/

+    LOG_FUNCTION_NAME_EXIT;
+    return ret;
+}
+
+status_t MemoryManager::setErrorHandler(ErrorNotifier *errorNotifier)
+{
+    status_t ret = NO_ERROR;
+
+    LOG_FUNCTION_NAME;
+
+    if ( NULL == errorNotifier )
+        {
+        CAMHAL_LOGEA("Invalid Error Notifier reference");
+        ret = -EINVAL;
+        }
+
+    if ( NO_ERROR == ret )
+        {
+        mErrorNotifier = errorNotifier;
+        }
+
+    LOG_FUNCTION_NAME_EXIT;
+
+    return ret;
+}
+
+};
+
+
+/*--------------------MemoryManager Class ENDS here-----------------------------*/
diff --git a/camera/NV12_resize.c b/camera/NV12_resize.c
index 03c049e..7f92fb2 100644
--- a/camera/NV12_resize.c
+++ b/camera/NV12_resize.c
@@ -31,7 +31,7 @@
  mmUint16 dummy                         /* Transparent pixel value              */
  )
 {
-  LOGV("VT_resizeFrame_Video_opt2_lp+");
+  ALOGV("VT_resizeFrame_Video_opt2_lp+");
 
   mmUint16 row,col;
   mmUint32 resizeFactorX;
@@ -55,19 +55,19 @@
 	{
 		if(i_img_ptr->uHeight == o_img_ptr->uHeight)
 			{
-				LOGV("************************f(i_img_ptr->uHeight == o_img_ptr->uHeight) are same *********************\n");
-				LOGV("************************(i_img_ptr->width == %d" , i_img_ptr->uWidth );
-				LOGV("************************(i_img_ptr->uHeight == %d" , i_img_ptr->uHeight );
-				LOGV("************************(o_img_ptr->width == %d" ,o_img_ptr->uWidth );
-				LOGV("************************(o_img_ptr->uHeight == %d" , o_img_ptr->uHeight );
+				ALOGV("************************f(i_img_ptr->uHeight == o_img_ptr->uHeight) are same *********************\n");
+				ALOGV("************************(i_img_ptr->width == %d" , i_img_ptr->uWidth );
+				ALOGV("************************(i_img_ptr->uHeight == %d" , i_img_ptr->uHeight );
+				ALOGV("************************(o_img_ptr->width == %d" ,o_img_ptr->uWidth );
+				ALOGV("************************(o_img_ptr->uHeight == %d" , o_img_ptr->uHeight );
 			}
 	}
 
   if (!i_img_ptr || !i_img_ptr->imgPtr ||
     !o_img_ptr || !o_img_ptr->imgPtr)
   {
-	LOGE("Image Point NULL");
-	LOGV("VT_resizeFrame_Video_opt2_lp-");
+	ALOGE("Image Point NULL");
+	ALOGV("VT_resizeFrame_Video_opt2_lp-");
 	return FALSE;
   }
 
@@ -95,8 +95,8 @@
   /* make sure valid input size */
   if (idx < 1 || idy < 1 || i_img_ptr->uStride < 1)
 	{
-	LOGE("idx or idy less then 1 idx = %d idy = %d stride = %d", idx, idy, i_img_ptr->uStride);
-	LOGV("VT_resizeFrame_Video_opt2_lp-");
+	ALOGE("idx or idy less then 1 idx = %d idy = %d stride = %d", idx, idy, i_img_ptr->uStride);
+	ALOGV("VT_resizeFrame_Video_opt2_lp-");
 	return FALSE;
 	}
 
@@ -297,11 +297,11 @@
   }
   else
   {
-	LOGE("eFormat not supported");
-	LOGV("VT_resizeFrame_Video_opt2_lp-");
+	ALOGE("eFormat not supported");
+	ALOGV("VT_resizeFrame_Video_opt2_lp-");
 	return FALSE;
   }
-  LOGV("success");
-  LOGV("VT_resizeFrame_Video_opt2_lp-");
+  ALOGV("success");
+  ALOGV("VT_resizeFrame_Video_opt2_lp-");
   return TRUE;
 }
diff --git a/camera/OMXCameraAdapter/OMX3A.cpp b/camera/OMXCameraAdapter/OMX3A.cpp
index ef02e49..4cb4607 100644
--- a/camera/OMXCameraAdapter/OMX3A.cpp
+++ b/camera/OMXCameraAdapter/OMX3A.cpp
@@ -75,6 +75,7 @@
     status_t ret = NO_ERROR;
     int mode = 0;
     const char *str = NULL;
+    int varint = 0;
     BaseCameraAdapter::AdapterState nextState;
     BaseCameraAdapter::getNextState(nextState);
 
@@ -111,6 +112,8 @@
         CAMHAL_LOGVB("SceneMode %d", mParameters3A.SceneMode);
     }
 
+#ifdef OMAP_ENHANCEMENT
+
     str = params.get(TICameraParameters::KEY_EXPOSURE_MODE);
     mode = getLUTvalue_HALtoOMX( str, ExpLUT);
     if ( ( str != NULL ) && ( mParameters3A.Exposure != mode ))
@@ -123,6 +126,8 @@
             }
         }
 
+#endif
+
     str = params.get(CameraParameters::KEY_WHITE_BALANCE);
     mode = getLUTvalue_HALtoOMX( str, WBalLUT);
     if (mFirstTimeInit || ((str != NULL) && (mode != mParameters3A.WhiteBallance)))
@@ -135,54 +140,58 @@
             }
         }
 
-    if ( 0 <= params.getInt(TICameraParameters::KEY_CONTRAST) )
+#ifdef OMAP_ENHANCEMENT
+
+    varint = params.getInt(TICameraParameters::KEY_CONTRAST);
+    if ( 0 <= varint )
         {
         if ( mFirstTimeInit ||
-             ( (mParameters3A.Contrast  + CONTRAST_OFFSET) !=
-                     params.getInt(TICameraParameters::KEY_CONTRAST)) )
+             ( (mParameters3A.Contrast  + CONTRAST_OFFSET) != varint ) )
             {
-            mParameters3A.Contrast = params.getInt(TICameraParameters::KEY_CONTRAST) - CONTRAST_OFFSET;
+            mParameters3A.Contrast = varint - CONTRAST_OFFSET;
             CAMHAL_LOGDB("Contrast %d", mParameters3A.Contrast);
             mPending3Asettings |= SetContrast;
             }
         }
 
-    if ( 0 <= params.getInt(TICameraParameters::KEY_SHARPNESS) )
+    varint = params.getInt(TICameraParameters::KEY_SHARPNESS);
+    if ( 0 <= varint )
         {
         if ( mFirstTimeInit ||
-             ((mParameters3A.Sharpness + SHARPNESS_OFFSET) !=
-                     params.getInt(TICameraParameters::KEY_SHARPNESS)))
+             ((mParameters3A.Sharpness + SHARPNESS_OFFSET) != varint ))
             {
-            mParameters3A.Sharpness = params.getInt(TICameraParameters::KEY_SHARPNESS) - SHARPNESS_OFFSET;
+            mParameters3A.Sharpness = varint - SHARPNESS_OFFSET;
             CAMHAL_LOGDB("Sharpness %d", mParameters3A.Sharpness);
             mPending3Asettings |= SetSharpness;
             }
         }
 
-    if ( 0 <= params.getInt(TICameraParameters::KEY_SATURATION) )
+    varint = params.getInt(TICameraParameters::KEY_SATURATION);
+    if ( 0 <= varint )
         {
         if ( mFirstTimeInit ||
-             ((mParameters3A.Saturation + SATURATION_OFFSET) !=
-                     params.getInt(TICameraParameters::KEY_SATURATION)) )
+             ((mParameters3A.Saturation + SATURATION_OFFSET) != varint ) )
             {
-            mParameters3A.Saturation = params.getInt(TICameraParameters::KEY_SATURATION) - SATURATION_OFFSET;
+            mParameters3A.Saturation = varint - SATURATION_OFFSET;
             CAMHAL_LOGDB("Saturation %d", mParameters3A.Saturation);
             mPending3Asettings |= SetSaturation;
             }
         }
 
-    if ( 0 <= params.getInt(TICameraParameters::KEY_BRIGHTNESS) )
+    varint = params.getInt(TICameraParameters::KEY_BRIGHTNESS);
+    if ( 0 <= varint )
         {
         if ( mFirstTimeInit ||
-             (( mParameters3A.Brightness !=
-                     ( unsigned int ) params.getInt(TICameraParameters::KEY_BRIGHTNESS))) )
+             (( mParameters3A.Brightness != varint )) )
             {
-            mParameters3A.Brightness = (unsigned)params.getInt(TICameraParameters::KEY_BRIGHTNESS);
+            mParameters3A.Brightness = (unsigned) varint;
             CAMHAL_LOGDB("Brightness %d", mParameters3A.Brightness);
             mPending3Asettings |= SetBrightness;
             }
         }
 
+#endif
+
     str = params.get(CameraParameters::KEY_ANTIBANDING);
     mode = getLUTvalue_HALtoOMX(str,FlickerLUT);
     if ( mFirstTimeInit || ( ( str != NULL ) && ( mParameters3A.Flicker != mode ) ))
@@ -195,6 +204,8 @@
             }
         }
 
+#ifdef OMAP_ENHANCEMENT
+
     str = params.get(TICameraParameters::KEY_ISO);
     mode = getLUTvalue_HALtoOMX(str, IsoLUT);
     CAMHAL_LOGVB("ISO mode arrived in HAL : %s", str);
@@ -208,6 +219,8 @@
             }
         }
 
+#endif
+
     str = params.get(CameraParameters::KEY_FOCUS_MODE);
     mode = getLUTvalue_HALtoOMX(str, FocusLUT);
     if ( (mFirstTimeInit || ((str != NULL) && (mParameters3A.Focus != mode))))
@@ -225,15 +238,14 @@
         }
 
     str = params.get(CameraParameters::KEY_EXPOSURE_COMPENSATION);
+    varint = params.getInt(CameraParameters::KEY_EXPOSURE_COMPENSATION);
     if ( mFirstTimeInit ||
           (( str != NULL ) &&
-                  (mParameters3A.EVCompensation !=
-                          params.getInt(CameraParameters::KEY_EXPOSURE_COMPENSATION))))
+                  (mParameters3A.EVCompensation != varint )))
         {
-        CAMHAL_LOGDB("Setting EV Compensation to %d",
-                     params.getInt(CameraParameters::KEY_EXPOSURE_COMPENSATION));
+        CAMHAL_LOGDB("Setting EV Compensation to %d", varint);
 
-        mParameters3A.EVCompensation = params.getInt(CameraParameters::KEY_EXPOSURE_COMPENSATION);
+        mParameters3A.EVCompensation = varint;
         mPending3Asettings |= SetEVCompensation;
         }
 
@@ -273,7 +285,7 @@
         OMX_BOOL lock = OMX_FALSE;
         mUserSetExpLock = OMX_FALSE;
         str = params.get(CameraParameters::KEY_AUTO_EXPOSURE_LOCK);
-        if ( (strcmp(str, "true")) == 0)
+        if (str && ((strcmp(str, "true")) == 0))
           {
             CAMHAL_LOGVA("Locking Exposure");
             lock = OMX_TRUE;
@@ -298,7 +310,7 @@
         OMX_BOOL lock = OMX_FALSE;
         mUserSetWbLock = OMX_FALSE;
         str = params.get(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK);
-        if ( (strcmp(str, "true")) == 0)
+        if (str && ((strcmp(str, "true")) == 0))
           {
             CAMHAL_LOGVA("Locking WhiteBalance");
             lock = OMX_TRUE;
@@ -384,59 +396,26 @@
     return NULL;
 }
 
-status_t OMXCameraAdapter::apply3ADefaults(Gen3A_settings &Gen3A)
+status_t OMXCameraAdapter::init3AParams(Gen3A_settings &Gen3A)
 {
-    status_t ret = NO_ERROR;
-
     LOG_FUNCTION_NAME;
 
     Gen3A.Effect = getLUTvalue_HALtoOMX(OMXCameraAdapter::DEFAULT_EFFECT, EffLUT);
-    ret |= setEffect(Gen3A);
-
     Gen3A.FlashMode = getLUTvalue_HALtoOMX(OMXCameraAdapter::DEFAULT_FLASH_MODE, FlashLUT);
-    ret |= setFlashMode(Gen3A);
-
     Gen3A.SceneMode = getLUTvalue_HALtoOMX(OMXCameraAdapter::DEFAULT_SCENE_MODE, SceneLUT);
-    ret |= setScene(Gen3A);
-
     Gen3A.EVCompensation = atoi(OMXCameraAdapter::DEFAULT_EV_COMPENSATION);
-    ret |= setEVCompensation(Gen3A);
-
     Gen3A.Focus = getLUTvalue_HALtoOMX(OMXCameraAdapter::DEFAULT_FOCUS_MODE, FocusLUT);
-    ret |= setFocusMode(Gen3A);
-
     Gen3A.ISO = getLUTvalue_HALtoOMX(OMXCameraAdapter::DEFAULT_ISO_MODE, IsoLUT);
-    ret |= setISO(Gen3A);
-
     Gen3A.Flicker = getLUTvalue_HALtoOMX(OMXCameraAdapter::DEFAULT_ANTIBANDING, FlickerLUT);
-    ret |= setFlicker(Gen3A);
-
     Gen3A.Brightness = atoi(OMXCameraAdapter::DEFAULT_BRIGHTNESS);
-    ret |= setBrightness(Gen3A);
-
     Gen3A.Saturation = atoi(OMXCameraAdapter::DEFAULT_SATURATION) - SATURATION_OFFSET;
-    ret |= setSaturation(Gen3A);
-
     Gen3A.Sharpness = atoi(OMXCameraAdapter::DEFAULT_SHARPNESS) - SHARPNESS_OFFSET;
-    ret |= setSharpness(Gen3A);
-
     Gen3A.Contrast = atoi(OMXCameraAdapter::DEFAULT_CONTRAST) - CONTRAST_OFFSET;
-    ret |= setContrast(Gen3A);
-
     Gen3A.WhiteBallance = getLUTvalue_HALtoOMX(OMXCameraAdapter::DEFAULT_WB, WBalLUT);
-    ret |= setWBMode(Gen3A);
-
     Gen3A.Exposure = getLUTvalue_HALtoOMX(OMXCameraAdapter::DEFAULT_EXPOSURE_MODE, ExpLUT);
-    ret |= setExposureMode(Gen3A);
-
     Gen3A.ExposureLock = OMX_FALSE;
-    ret |= setExposureLock(Gen3A);
-
     Gen3A.FocusLock = OMX_FALSE;
-    ret |= setFocusLock(Gen3A);
-
     Gen3A.WhiteBalanceLock = OMX_FALSE;
-    ret |= setWhiteBalanceLock(Gen3A);
 
     LOG_FUNCTION_NAME_EXIT;
 
@@ -492,7 +471,7 @@
     char value[PROPERTY_VALUE_MAX];
     if (property_get("camera.flash_off", value, NULL) &&
         (!strcasecmp(value, "true") || !strcasecmp(value, "1"))) {
-        LOGW("flash is disabled for testing purpose");
+        ALOGW("flash is disabled for testing purpose");
         return true;
     }
 
diff --git a/camera/OMXCameraAdapter/OMXAlgo.cpp b/camera/OMXCameraAdapter/OMXAlgo.cpp
index 5924dde..ff68cc9 100644
--- a/camera/OMXCameraAdapter/OMXAlgo.cpp
+++ b/camera/OMXCameraAdapter/OMXAlgo.cpp
@@ -247,6 +247,8 @@
         mOMXStateSwitch = true;
         }
 
+#ifdef OMAP_ENHANCEMENT
+
     //Set Auto Convergence Mode
     valstr = params.get((const char *) TICameraParameters::KEY_AUTOCONVERGENCE);
     if ( valstr != NULL )
@@ -277,6 +279,8 @@
         CAMHAL_LOGVB("AutoConvergenceMode %s, value = %d", valstr, (int) manualconvergence);
         }
 
+#endif
+
     LOG_FUNCTION_NAME_EXIT;
 
     return ret;
diff --git a/camera/OMXCameraAdapter/OMXCameraAdapter.cpp b/camera/OMXCameraAdapter/OMXCameraAdapter.cpp
index aa32ede..a41327c 100755
--- a/camera/OMXCameraAdapter/OMXCameraAdapter.cpp
+++ b/camera/OMXCameraAdapter/OMXCameraAdapter.cpp
@@ -78,12 +78,6 @@
         return NO_INIT;
         }
 
-    if (mComponentState != OMX_StateLoaded && mComponentState != OMX_StateInvalid) {
-       CAMHAL_LOGEB("Error mComponentState %d is invalid!", mComponentState);
-       LOG_FUNCTION_NAME_EXIT;
-       return NO_INIT;
-    }
-
     ///Update the preview and image capture port indexes
     mCameraAdapterParameters.mPrevPortIndex = OMX_CAMERA_PORT_VIDEO_OUT_PREVIEW;
     // temp changed in order to build OMX_CAMERA_PORT_VIDEO_OUT_IMAGE;
@@ -94,9 +88,10 @@
 
     eError = OMX_Init();
     if (eError != OMX_ErrorNone) {
-      CAMHAL_LOGEB("Error OMX_Init -0x%x", eError);
-      return eError;
+        CAMHAL_LOGEB("OMX_Init() failed, error: 0x%x", eError);
+        return ErrorUtils::omxToAndroidError(eError);
     }
+    mOmxInitialized = true;
 
     ///Get the handle to the OMX Component
     eError = OMXCameraAdapter::OMXCameraGetHandle(&mCameraAdapterParameters.mHandleComp, (OMX_PTR)this);
@@ -105,6 +100,8 @@
     }
     GOTO_EXIT_IF((eError != OMX_ErrorNone), eError);
 
+    mComponentState = OMX_StateLoaded;
+
     CAMHAL_LOGVB("OMX_GetHandle -0x%x sensor_index = %lu", eError, mSensorIndex);
     eError = OMX_SendCommand(mCameraAdapterParameters.mHandleComp,
                                   OMX_CommandPortDisable,
@@ -176,7 +173,6 @@
     mRecording = false;
     mWaitingForSnapshot = false;
     mSnapshotCount = 0;
-    mComponentState = OMX_StateLoaded;
 
     mCapMode = HIGH_QUALITY;
     mIPP = IPP_NULL;
@@ -281,14 +277,15 @@
     mMeasurementEnabled = false;
     mFaceDetectionRunning = false;
     mFaceDetectionPaused = false;
+    mFDSwitchAlgoPriority = false;
 
     memset(&mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mImagePortIndex], 0, sizeof(OMXCameraPortParameters));
     memset(&mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mPrevPortIndex], 0, sizeof(OMXCameraPortParameters));
 
     //Initialize 3A defaults
-    ret = apply3ADefaults(mParameters3A);
+    ret = init3AParams(mParameters3A);
     if ( NO_ERROR != ret ) {
-        CAMHAL_LOGEA("Couldn't apply 3A defaults!");
+        CAMHAL_LOGEA("Couldn't init 3A params!");
         goto EXIT;
     }
 
@@ -541,6 +538,8 @@
         mOMXStateSwitch = true;
         }
 
+#ifdef OMAP_ENHANCEMENT
+
     if ( (valstr = params.get(TICameraParameters::KEY_MEASUREMENT_ENABLE)) != NULL )
         {
         if (strcmp(valstr, (const char *) TICameraParameters::MEASUREMENT_ENABLE) == 0)
@@ -562,6 +561,8 @@
         mMeasurementEnabled = false;
         }
 
+#endif
+
     ret |= setParametersCapture(params, state);
 
     ret |= setParameters3A(params, state);
@@ -594,7 +595,7 @@
     sprintf(fn, "/preview%03d.yuv", counter);
     fd = open(fn, O_CREAT | O_WRONLY | O_SYNC | O_TRUNC, 0777);
     if(fd < 0) {
-        LOGE("Unable to open file %s: %s", fn, strerror(fd));
+        ALOGE("Unable to open file %s: %s", fn, strerror(fd));
         return;
     }
 
@@ -682,6 +683,8 @@
                    mParameters.get(CameraParameters::KEY_FOCUS_DISTANCES));
         }
 
+#ifdef OMAP_ENHANCEMENT
+
     OMX_INIT_STRUCT_PTR (&exp, OMX_CONFIG_EXPOSUREVALUETYPE);
     exp.nPortIndex = OMX_ALL;
 
@@ -697,6 +700,8 @@
         CAMHAL_LOGEB("OMX error 0x%x, while retrieving current ISO value", eError);
         }
 
+#endif
+
     {
     Mutex::Autolock lock(mZoomLock);
     //Immediate zoom should not be avaialable while smooth zoom is running
@@ -750,7 +755,6 @@
         params.set(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK, valstr);
       }
 
-
     LOG_FUNCTION_NAME_EXIT;
 }
 
@@ -1743,6 +1747,8 @@
     ///If there is any failure, we reach here.
     ///Here, we do any resource freeing and convert from OMX error code to Camera Hal error code
 EXIT:
+    mStateSwitchLock.unlock();
+
     CAMHAL_LOGEB("Exiting function %s because of ret %d eError=%x", __FUNCTION__, ret, eError);
     performCleanupAfterError();
     CAMHAL_LOGEB("Exiting function %s because of ret %d eError=%x", __FUNCTION__, ret, eError);
@@ -1758,15 +1764,14 @@
     OMX_ERRORTYPE eError = OMX_ErrorNone;
     OMXCameraPortParameters *mPreviewData = NULL;
     OMXCameraPortParameters *measurementData = NULL;
-    OMX_CONFIG_EXTRADATATYPE extraDataControl;
 
     LOG_FUNCTION_NAME;
 
     if( 0 != mStartPreviewSem.Count() )
         {
         CAMHAL_LOGEB("Error mStartPreviewSem semaphore count %d", mStartPreviewSem.Count());
-        LOG_FUNCTION_NAME_EXIT;
-        return NO_INIT;
+        ret = NO_INIT;
+        goto EXIT;
         }
 
     mPreviewData = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mPrevPortIndex];
@@ -1870,15 +1875,7 @@
     // whether the preview frame is a snapshot
     if ( OMX_ErrorNone == eError)
         {
-        OMX_INIT_STRUCT_PTR (&extraDataControl, OMX_CONFIG_EXTRADATATYPE);
-        extraDataControl.nPortIndex = OMX_ALL;
-        extraDataControl.eExtraDataType = OMX_AncillaryData;
-        extraDataControl.bEnable = OMX_TRUE;
-
-        eError =  OMX_SetConfig(mCameraAdapterParameters.mHandleComp,
-                               ( OMX_INDEXTYPE ) OMX_IndexConfigOtherExtraDataControl,
-                               &extraDataControl);
-        GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
+        ret =  setExtraData(true, OMX_ALL, OMX_AncillaryData);
         }
 
 
@@ -1935,6 +1932,14 @@
     mCaptureData = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mImagePortIndex];
     measurementData = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mMeasurementPortIndex];
 
+   if (mAdapterState == LOADED_PREVIEW_STATE) {
+       // Something happened in CameraHal between UseBuffers and startPreview
+       // this means that state switch is still locked..so we need to unlock else
+       // deadlock will occur on the next start preview
+       mStateSwitchLock.unlock();
+       return NO_ERROR;
+   }
+
     if ( mComponentState != OMX_StateExecuting )
         {
         CAMHAL_LOGEA("Calling StopPreview() when not in EXECUTING state");
@@ -2707,6 +2712,7 @@
 {
     Mutex::Autolock lock(mEventLock);
     TIUTILS::Message *msg;
+    bool eventSignalled = false;
 
     LOG_FUNCTION_NAME;
 
@@ -2730,6 +2736,7 @@
                     //Signal the semaphore provided
                     sem->Signal();
                     free(msg);
+                    eventSignalled = true;
                     break;
                     }
                 }
@@ -2740,6 +2747,19 @@
         CAMHAL_LOGDA("Event queue empty!!!");
         }
 
+    // Special handling for any unregistered events
+    if (!eventSignalled) {
+        // Handling for focus callback
+        if ((nData2 == OMX_IndexConfigCommonFocusStatus) &&
+            (eEvent == (OMX_EVENTTYPE) OMX_EventIndexSettingChanged)) {
+                TIUTILS::Message msg;
+                msg.command = OMXCallbackHandler::CAMERA_FOCUS_STATUS;
+                msg.arg1 = NULL;
+                msg.arg2 = NULL;
+                mOMXCallbackHandler->put(&msg);
+        }
+    }
+
     LOG_FUNCTION_NAME_EXIT;
 
     return OMX_ErrorNone;
@@ -2867,7 +2887,7 @@
         mFps = ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
         mLastFpsTime = now;
         mLastFrameCount = mFrameCount;
-        LOGD("Camera %d Frames, %f FPS", mFrameCount, mFps);
+        ALOGD("Camera %d Frames, %f FPS", mFrameCount, mFps);
     }
     // XXX: mFPS has the value we want
 }
@@ -2919,7 +2939,7 @@
     CameraFrame cameraFrame;
     OMX_TI_PLATFORMPRIVATE *platformPrivate;
     OMX_OTHER_EXTRADATATYPE *extraData;
-    OMX_TI_ANCILLARYDATATYPE *ancillaryData;
+    OMX_TI_ANCILLARYDATATYPE *ancillaryData = NULL;
     bool snapshotFrame = false;
 
     res1 = res2 = NO_ERROR;
@@ -2952,7 +2972,6 @@
             }
 
         recalculateFPS();
-
             {
             Mutex::Autolock lock(mFaceDetectionLock);
             if ( mFaceDetectionRunning && !mFaceDetectionPaused ) {
@@ -2961,12 +2980,18 @@
                     notifyFaceSubscribers(fdResult);
                     fdResult.clear();
                 }
-            }
-            }
+                if ( mFDSwitchAlgoPriority ) {
 
-        if ( (nextState & CAPTURE_ACTIVE) )
-            {
-            mPending3Asettings |= SetFocus;
+                    //Disable region priority and enable face priority for AF
+                    setAlgoPriority(REGION_PRIORITY, FOCUS_ALGO, false);
+                    setAlgoPriority(FACE_PRIORITY, FOCUS_ALGO , true);
+
+                    //Disable Region priority and enable Face priority
+                    setAlgoPriority(REGION_PRIORITY, EXPOSURE_ALGO, false);
+                    setAlgoPriority(FACE_PRIORITY, EXPOSURE_ALGO, true);
+                    mFDSwitchAlgoPriority = false;
+                }
+            }
             }
 
         ///Prepare the frames to be sent - initialize CameraFrame object and reference count
@@ -2978,6 +3003,16 @@
             {
             typeOfFrame = CameraFrame::SNAPSHOT_FRAME;
             mask = (unsigned int)CameraFrame::SNAPSHOT_FRAME;
+
+            // video snapshot gets ancillary data and wb info from last snapshot frame
+            mCaptureAncillaryData = ancillaryData;
+            mWhiteBalanceData = NULL;
+            extraData = getExtradata((OMX_OTHER_EXTRADATATYPE*) platformPrivate->pMetaDataBuffer,
+                                     (OMX_EXTRADATATYPE) OMX_WhiteBalance);
+            if ( NULL != extraData )
+                {
+                mWhiteBalanceData = (OMX_TI_WHITEBALANCERESULTTYPE*) extraData->data;
+                }
             }
         else
             {
@@ -2991,7 +3026,7 @@
             mFramesWithEncoder++;
             }
 
-        //LOGV("FBD pBuffer = 0x%x", pBuffHeader->pBuffer);
+        //ALOGV("FBD pBuffer = 0x%x", pBuffHeader->pBuffer);
 
         if( mWaitingForSnapshot )
           {
@@ -3012,8 +3047,8 @@
 #ifdef DEBUG_LOG
         if(mBuffersWithDucati.indexOfKey((int)pBuffHeader->pBuffer)<0)
             {
-            LOGE("Buffer was never with Ducati!! 0x%x", pBuffHeader->pBuffer);
-            for(int i=0;i<mBuffersWithDucati.size();i++) LOGE("0x%x", mBuffersWithDucati.keyAt(i));
+            ALOGE("Buffer was never with Ducati!! 0x%x", pBuffHeader->pBuffer);
+            for(int i=0;i<mBuffersWithDucati.size();i++) ALOGE("0x%x", mBuffersWithDucati.keyAt(i));
             }
         mBuffersWithDucati.removeItem((int)pBuffHeader->pBuffer);
 #endif
@@ -3026,10 +3061,13 @@
         // On the fly update to 3A settings not working
         // Do not update 3A here if we are in the middle of a capture
         // or in the middle of transitioning to it
-        if( mPending3Asettings && ((nextState & CAPTURE_ACTIVE) == 0))
+        if( mPending3Asettings &&
+                ( (nextState & CAPTURE_ACTIVE) == 0 ) &&
+                ( (state & CAPTURE_ACTIVE) == 0 ) )
             {
             apply3Asettings(mParameters3A);
             }
+
         }
     else if( pBuffHeader->nOutputPortIndex == OMX_CAMERA_PORT_VIDEO_OUT_MEASUREMENT )
         {
@@ -3064,7 +3102,7 @@
             // populate exif data and pass to subscribers via quirk
             // subscriber is in charge of freeing exif data
             ExifElementsTable* exif = new ExifElementsTable();
-            setupEXIF_libjpeg(exif);
+            setupEXIF_libjpeg(exif, mCaptureAncillaryData, mWhiteBalanceData);
             cameraFrame.mQuirks |= CameraFrame::HAS_EXIF_DATA;
             cameraFrame.mCookie2 = (void*) exif;
             }
@@ -3368,6 +3406,11 @@
                                                                      ( OMX_BUFFERHEADERTYPE *) msg.arg2);
                 break;
             }
+            case OMXCallbackHandler::CAMERA_FOCUS_STATUS:
+            {
+                mCameraAdapter->handleFocusCallback();
+                break;
+            }
             case CommandHandler::COMMAND_EXIT:
             {
                 CAMHAL_LOGDA("Exiting OMX callback handler");
@@ -3381,6 +3424,41 @@
     return false;
 }
 
+status_t OMXCameraAdapter::setExtraData(bool enable, OMX_U32 nPortIndex, OMX_EXT_EXTRADATATYPE eType) {
+    status_t ret = NO_ERROR;
+    OMX_ERRORTYPE eError = OMX_ErrorNone;
+    OMX_CONFIG_EXTRADATATYPE extraDataControl;
+
+    LOG_FUNCTION_NAME;
+
+    if ( ( OMX_StateInvalid == mComponentState ) ||
+         ( NULL == mCameraAdapterParameters.mHandleComp ) ) {
+        CAMHAL_LOGEA("OMX component is in invalid state");
+        return -EINVAL;
+    }
+
+    OMX_INIT_STRUCT_PTR (&extraDataControl, OMX_CONFIG_EXTRADATATYPE);
+
+    extraDataControl.nPortIndex = nPortIndex;
+    extraDataControl.eExtraDataType = eType;
+    extraDataControl.eCameraView = OMX_2D;
+
+    if (enable) {
+        extraDataControl.bEnable = OMX_TRUE;
+    } else {
+        extraDataControl.bEnable = OMX_FALSE;
+    }
+
+    eError =  OMX_SetConfig(mCameraAdapterParameters.mHandleComp,
+                           (OMX_INDEXTYPE) OMX_IndexConfigOtherExtraDataControl,
+                            &extraDataControl);
+
+    LOG_FUNCTION_NAME_EXIT;
+
+    return (ret | ErrorUtils::omxToAndroidError(eError));
+}
+
+
 OMX_OTHER_EXTRADATATYPE *OMXCameraAdapter::getExtradata(OMX_OTHER_EXTRADATATYPE *extraData, OMX_EXTRADATATYPE type)
 {
   if ( NULL != extraData )
@@ -3398,17 +3476,18 @@
   return NULL;
 }
 
-OMXCameraAdapter::OMXCameraAdapter(size_t sensor_index): mComponentState (OMX_StateLoaded)
+OMXCameraAdapter::OMXCameraAdapter(size_t sensor_index)
 {
     LOG_FUNCTION_NAME;
 
+    mOmxInitialized = false;
+    mComponentState = OMX_StateInvalid;
     mSensorIndex = sensor_index;
     mPictureRotation = 0;
     // Initial values
     mTimeSourceDelta = 0;
     onlyOnce = true;
 
-    mDoAFSem.Create(0);
     mInitSem.Create(0);
     mFlushSem.Create(0);
     mUsePreviewDataSem.Create(0);
@@ -3441,22 +3520,22 @@
 
     Mutex::Autolock lock(gAdapterLock);
 
-    //Return to OMX Loaded state
-    switchToLoaded();
+    if ( mOmxInitialized ) {
+        // return to OMX Loaded state
+        switchToLoaded();
 
-    ///De-init the OMX
-    if( (mComponentState==OMX_StateLoaded) || (mComponentState==OMX_StateInvalid))
-        {
-        ///Free the handle for the Camera component
-        if(mCameraAdapterParameters.mHandleComp)
-            {
-            OMX_FreeHandle(mCameraAdapterParameters.mHandleComp);
-             mCameraAdapterParameters.mHandleComp = NULL;
+        // deinit the OMX
+        if ( mComponentState == OMX_StateLoaded || mComponentState == OMX_StateInvalid ) {
+            // free the handle for the Camera component
+            if ( mCameraAdapterParameters.mHandleComp ) {
+                OMX_FreeHandle(mCameraAdapterParameters.mHandleComp);
+                mCameraAdapterParameters.mHandleComp = NULL;
             }
-
-        OMX_Deinit();
         }
 
+        OMX_Deinit();
+        mOmxInitialized = false;
+    }
 
     //Remove any unhandled events
     if ( !mEventSignalQ.isEmpty() )
@@ -3526,28 +3605,30 @@
 {
     OMX_ERRORTYPE eError = OMX_ErrorUndefined;
 
-    int retries = 5;
-    while(eError!=OMX_ErrorNone && --retries>=0) {
+    for ( int i = 0; i < 5; ++i ) {
+        if ( i > 0 ) {
+            // sleep for 100 ms before next attempt
+            usleep(100000);
+        }
 
-      // Setup key parameters to send to Ducati during init
-      OMX_CALLBACKTYPE oCallbacks;
+        // setup key parameters to send to Ducati during init
+        OMX_CALLBACKTYPE oCallbacks;
 
-      // Initialize the callback handles
-      oCallbacks.EventHandler    = android::OMXCameraAdapterEventHandler;
-      oCallbacks.EmptyBufferDone = android::OMXCameraAdapterEmptyBufferDone;
-      oCallbacks.FillBufferDone  = android::OMXCameraAdapterFillBufferDone;
+        // initialize the callback handles
+        oCallbacks.EventHandler    = android::OMXCameraAdapterEventHandler;
+        oCallbacks.EmptyBufferDone = android::OMXCameraAdapterEmptyBufferDone;
+        oCallbacks.FillBufferDone  = android::OMXCameraAdapterFillBufferDone;
 
-      // Get Handle
-      eError = OMX_GetHandle(handle, (OMX_STRING)"OMX.TI.DUCATI1.VIDEO.CAMERA", pAppData, &oCallbacks);
-      if (eError != OMX_ErrorNone) {
-        CAMHAL_LOGEB("OMX_GetHandle -0x%x", eError);
-        //Sleep for 100 mS
-        usleep(100000);
-      } else {
-        break;
-      }
+        // get handle
+        eError = OMX_GetHandle(handle, (OMX_STRING)"OMX.TI.DUCATI1.VIDEO.CAMERA", pAppData, &oCallbacks);
+        if ( eError == OMX_ErrorNone ) {
+            return OMX_ErrorNone;
+        }
+
+        CAMHAL_LOGEB("OMX_GetHandle() failed, error: 0x%x", eError);
     }
 
+    *handle = 0;
     return eError;
 }
 
diff --git a/camera/OMXCameraAdapter/OMXCapture.cpp b/camera/OMXCameraAdapter/OMXCapture.cpp
index 77fdb05..93a0dae 100644
--- a/camera/OMXCameraAdapter/OMXCapture.cpp
+++ b/camera/OMXCameraAdapter/OMXCapture.cpp
@@ -40,6 +40,7 @@
     int w, h;
     OMX_COLOR_FORMATTYPE pixFormat;
     const char *valstr = NULL;
+    int varint = 0;
 
     LOG_FUNCTION_NAME;
 
@@ -142,6 +143,8 @@
         cap->mColorFormat = pixFormat;
         }
 
+#ifdef OMAP_ENHANCEMENT
+
     str = params.get(TICameraParameters::KEY_EXP_BRACKETING_RANGE);
     if ( NULL != str ) {
         parseExpRange(str, mExposureBracketingValues, EXP_BRACKET_RANGE, mExposureBracketingValidEntries);
@@ -151,12 +154,15 @@
         mExposureBracketingValidEntries = 0;
     }
 
-    if ( params.getInt(CameraParameters::KEY_ROTATION) != -1 )
+#endif
+
+    varint = params.getInt(CameraParameters::KEY_ROTATION);
+    if ( varint != -1 )
         {
-        if (params.getInt(CameraParameters::KEY_ROTATION) != mPictureRotation) {
+        if ( ( unsigned int )  varint != mPictureRotation) {
             mPendingCaptureSettings |= SetRotation;
         }
-        mPictureRotation = params.getInt(CameraParameters::KEY_ROTATION);
+        mPictureRotation = varint;
         }
     else
         {
@@ -166,11 +172,14 @@
 
     CAMHAL_LOGVB("Picture Rotation set %d", mPictureRotation);
 
+#ifdef OMAP_ENHANCEMENT
+
     // Read Sensor Orientation and set it based on perating mode
 
-     if (( params.getInt(TICameraParameters::KEY_SENSOR_ORIENTATION) != -1 ) && (mCapMode == OMXCameraAdapter::VIDEO_MODE))
+     varint = params.getInt(TICameraParameters::KEY_SENSOR_ORIENTATION);
+     if (( varint != -1 ) && (mCapMode == OMXCameraAdapter::VIDEO_MODE))
         {
-         mSensorOrientation = params.getInt(TICameraParameters::KEY_SENSOR_ORIENTATION);
+         mSensorOrientation = varint;
          if (mSensorOrientation == 270 ||mSensorOrientation==90)
              {
              CAMHAL_LOGEA(" Orientation is 270/90. So setting counter rotation  to Ducati");
@@ -185,12 +194,13 @@
 
      CAMHAL_LOGVB("Sensor Orientation  set : %d", mSensorOrientation);
 
-    if ( params.getInt(TICameraParameters::KEY_BURST)  >= 1 )
+    varint = params.getInt(TICameraParameters::KEY_BURST);
+    if ( varint >= 1 )
         {
-        if (params.getInt(TICameraParameters::KEY_BURST) != mBurstFrames) {
+        if (varint != mBurstFrames) {
             mPendingCaptureSettings |= SetExpBracket;
         }
-        mBurstFrames = params.getInt(TICameraParameters::KEY_BURST);
+        mBurstFrames = varint;
         }
     else
         {
@@ -200,13 +210,16 @@
 
     CAMHAL_LOGVB("Burst Frames set %d", mBurstFrames);
 
-    if ( ( params.getInt(CameraParameters::KEY_JPEG_QUALITY)  >= MIN_JPEG_QUALITY ) &&
-         ( params.getInt(CameraParameters::KEY_JPEG_QUALITY)  <= MAX_JPEG_QUALITY ) )
+#endif
+
+    varint = params.getInt(CameraParameters::KEY_JPEG_QUALITY);
+    if ( ( varint >= MIN_JPEG_QUALITY ) &&
+         ( varint  <= MAX_JPEG_QUALITY ) )
         {
-        if (params.getInt(CameraParameters::KEY_JPEG_QUALITY) != mPictureQuality) {
+        if ( ( unsigned int ) varint != mPictureQuality) {
             mPendingCaptureSettings |= SetQuality;
         }
-        mPictureQuality = params.getInt(CameraParameters::KEY_JPEG_QUALITY);
+        mPictureQuality = varint;
         }
     else
         {
@@ -216,12 +229,13 @@
 
     CAMHAL_LOGVB("Picture Quality set %d", mPictureQuality);
 
-    if ( params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH)  >= 0 )
+    varint = params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH);
+    if ( varint >= 0 )
         {
-        if (params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH) != mThumbWidth) {
+        if ( ( unsigned int ) varint != mThumbWidth) {
             mPendingCaptureSettings |= SetThumb;
         }
-        mThumbWidth = params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH);
+        mThumbWidth = varint;
         }
     else
         {
@@ -232,12 +246,13 @@
 
     CAMHAL_LOGVB("Picture Thumb width set %d", mThumbWidth);
 
-    if ( params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT)  >= 0 )
+    varint = params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT);
+    if ( varint >= 0 )
         {
-        if (params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT) != mThumbHeight) {
+        if ( ( unsigned int ) varint != mThumbHeight) {
             mPendingCaptureSettings |= SetThumb;
         }
-        mThumbHeight = params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT);
+        mThumbHeight = varint;
         }
     else
         {
@@ -248,13 +263,14 @@
 
     CAMHAL_LOGVB("Picture Thumb height set %d", mThumbHeight);
 
-    if ( ( params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY)  >= MIN_JPEG_QUALITY ) &&
-         ( params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY)  <= MAX_JPEG_QUALITY ) )
+    varint = params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY);
+    if ( ( varint >= MIN_JPEG_QUALITY ) &&
+         ( varint <= MAX_JPEG_QUALITY ) )
         {
-        if (params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY) != mThumbQuality) {
+        if ( ( unsigned int ) varint != mThumbQuality) {
             mPendingCaptureSettings |= SetThumb;
         }
-        mThumbQuality = params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY);
+        mThumbQuality = varint;
         }
     else
         {
@@ -775,6 +791,12 @@
         }
     }
 
+    // need to enable wb data for video snapshot to fill in exif data
+    if ((ret == NO_ERROR) && (mCapMode == VIDEO_MODE)) {
+        // video snapshot uses wb data from snapshot frame
+        ret = setExtraData(true, mCameraAdapterParameters.mPrevPortIndex, OMX_WhiteBalance);
+    }
+
     //OMX shutter callback events are only available in hq mode
     if ( (HIGH_QUALITY == mCapMode) || (HIGH_QUALITY_ZSL== mCapMode))
         {
@@ -866,6 +888,7 @@
 
 EXIT:
     CAMHAL_LOGEB("Exiting function %s because of ret %d eError=%x", __FUNCTION__, ret, eError);
+    setExtraData(false, mCameraAdapterParameters.mPrevPortIndex, OMX_WhiteBalance);
     mWaitingForSnapshot = false;
     mCaptureSignalled = false;
     performCleanupAfterError();
@@ -945,6 +968,13 @@
             goto EXIT;
         }
     }
+
+    // had to enable wb data for video snapshot to fill in exif data
+    // now that we are done...disable
+    if ((ret == NO_ERROR) && (mCapMode == VIDEO_MODE)) {
+        ret = setExtraData(false, mCameraAdapterParameters.mPrevPortIndex, OMX_WhiteBalance);
+    }
+
     CAMHAL_LOGDB("Capture set - 0x%x", eError);
 
     mCaptureSignalled = true; //set this to true if we exited because of timeout
diff --git a/camera/OMXCameraAdapter/OMXExif.cpp b/camera/OMXCameraAdapter/OMXExif.cpp
old mode 100755
new mode 100644
index 4c5e555..70fb3db
--- a/camera/OMXCameraAdapter/OMXExif.cpp
+++ b/camera/OMXCameraAdapter/OMXExif.cpp
@@ -497,7 +497,9 @@
     return ret;
 }
 
-status_t OMXCameraAdapter::setupEXIF_libjpeg(ExifElementsTable* exifTable)
+status_t OMXCameraAdapter::setupEXIF_libjpeg(ExifElementsTable* exifTable,
+                                             OMX_TI_ANCILLARYDATATYPE* pAncillaryData,
+                                             OMX_TI_WHITEBALANCERESULTTYPE* pWhiteBalanceData)
 {
     status_t ret = NO_ERROR;
     OMX_ERRORTYPE eError = OMX_ErrorNone;
@@ -544,7 +546,6 @@
                      pTime->tm_hour,
                      pTime->tm_min,
                      pTime->tm_sec );
-
             ret = exifTable->insertElement(TAG_DATETIME, temp_value);
         }
      }
@@ -658,6 +659,129 @@
         }
     }
 
+    // fill in short and ushort tags
+    if (NO_ERROR == ret) {
+        char temp_value[2];
+        temp_value[1] = '\0';
+
+        // AWB
+        if (mParameters3A.WhiteBallance == OMX_WhiteBalControlAuto) {
+            temp_value[0] = '0';
+        } else {
+            temp_value[0] = '1';
+        }
+        exifTable->insertElement(TAG_WHITEBALANCE, temp_value);
+
+        // MeteringMode
+        // TODO(XXX): only supporting this metering mode at the moment, may change in future
+        temp_value[0] = '2';
+        exifTable->insertElement(TAG_METERING_MODE, temp_value);
+
+        // ExposureProgram
+        // TODO(XXX): only supporting this exposure program at the moment, may change in future
+        temp_value[0] = '3';
+        exifTable->insertElement(TAG_EXPOSURE_PROGRAM, temp_value);
+
+        // ColorSpace
+        temp_value[0] = '1';
+        exifTable->insertElement(TAG_COLOR_SPACE, temp_value);
+
+        temp_value[0] = '2';
+        exifTable->insertElement(TAG_SENSING_METHOD, temp_value);
+
+        temp_value[0] = '1';
+        exifTable->insertElement(TAG_CUSTOM_RENDERED, temp_value);
+    }
+
+    if (pAncillaryData && (NO_ERROR == ret)) {
+        unsigned int numerator = 0, denominator = 0;
+        char temp_value[256];
+        unsigned int temp_num = 0;
+
+        // DigitalZoomRatio
+        snprintf(temp_value,
+                 sizeof(temp_value)/sizeof(char),
+                 "%u/%u",
+                 pAncillaryData->nDigitalZoomFactor, 1024);
+        exifTable->insertElement(TAG_DIGITALZOOMRATIO, temp_value);
+
+        // ExposureTime
+        snprintf(temp_value,
+                 sizeof(temp_value)/sizeof(char),
+                 "%u/%u",
+                 pAncillaryData->nExposureTime, 1000000);
+        exifTable->insertElement(TAG_EXPOSURETIME, temp_value);
+
+        // ApertureValue and FNumber
+        snprintf(temp_value,
+                 sizeof(temp_value)/sizeof(char),
+                 "%u/%u",
+                 pAncillaryData->nApertureValue, 100);
+        exifTable->insertElement(TAG_FNUMBER, temp_value);
+        exifTable->insertElement(TAG_APERTURE, temp_value);
+
+        // ISO
+        snprintf(temp_value,
+                 sizeof(temp_value)/sizeof(char),
+                 "%u,0,0",
+                 pAncillaryData->nCurrentISO);
+        exifTable->insertElement(TAG_ISO_EQUIVALENT, temp_value);
+
+        // ShutterSpeed
+        snprintf(temp_value,
+                 sizeof(temp_value)/sizeof(char),
+                 "%f",
+                 log(pAncillaryData->nExposureTime) / log(2));
+        ExifElementsTable::stringToRational(temp_value, &numerator, &denominator);
+        snprintf(temp_value, sizeof(temp_value)/sizeof(char), "%u/%u", numerator, denominator);
+        exifTable->insertElement(TAG_SHUTTERSPEED, temp_value);
+
+        // Flash
+        if (mParameters3A.FlashMode == OMX_IMAGE_FlashControlAuto) {
+            if(pAncillaryData->nFlashStatus) temp_num = 0x19; // Flash fired, auto mode
+            else temp_num = 0x18; // Flash did not fire, auto mode
+        } else if (mParameters3A.FlashMode == OMX_IMAGE_FlashControlOn) {
+            if(pAncillaryData->nFlashStatus) temp_num = 0x9; // Flash fired, compulsory flash mode
+            else temp_num = 0x10; // Flash did not fire, compulsory flash mode
+        } else if(pAncillaryData->nFlashStatus) {
+            temp_num = 0x1; // Flash fired
+        } else {
+            temp_num = 0x0; // Flash did not fire
+        }
+        snprintf(temp_value,
+                 sizeof(temp_value)/sizeof(char),
+                 "%u", temp_num);
+        exifTable->insertElement(TAG_FLASH, temp_value);
+
+        if (pWhiteBalanceData) {
+            unsigned int lightsource = 0;
+            unsigned int colourtemp = pWhiteBalanceData->nColorTemperature;
+            bool flash_fired = (temp_num & 0x1); // value from flash above
+
+            // stole this from framework/tools_library/src/tools_sys_exif_tags.c
+            if( colourtemp <= 3200 ) {
+                lightsource = 3; // Tungsten
+            } else if( colourtemp > 3200 && colourtemp <= 4800 ) {
+                lightsource = 2; // Fluorescent
+            } else if( colourtemp > 4800 && colourtemp <= 5500 ) {
+                lightsource = 1; // Daylight
+            } else if( colourtemp > 5500 && colourtemp <= 6500 ) {
+                lightsource = 9; // Fine weather
+            } else if( colourtemp > 6500 ) {
+                lightsource = 10; // Cloudy weather
+            }
+
+            if(flash_fired) {
+                lightsource = 4; // Flash
+            }
+
+            snprintf(temp_value,
+                    sizeof(temp_value)/sizeof(char),
+                    "%u", lightsource);
+            exifTable->insertElement(TAG_LIGHT_SOURCE, temp_value);
+        }
+    }
+
     LOG_FUNCTION_NAME_EXIT;
 
     return ret;
@@ -675,7 +799,7 @@
 
     if ( coord == 0 ) {
 
-        LOGE("Invalid GPS coordinate");
+        ALOGE("Invalid GPS coordinate");
 
         return -EINVAL;
     }
diff --git a/camera/OMXCameraAdapter/OMXFD.cpp b/camera/OMXCameraAdapter/OMXFD.cpp
index 38c7a6e..26bbd87 100644
--- a/camera/OMXCameraAdapter/OMXFD.cpp
+++ b/camera/OMXCameraAdapter/OMXFD.cpp
@@ -62,16 +62,9 @@
         goto out;
     }
 
-    if ( mFaceDetectionRunning )
-        {
-        //Disable region priority and enable face priority for AF
-        setAlgoPriority(REGION_PRIORITY, FOCUS_ALGO, false);
-        setAlgoPriority(FACE_PRIORITY, FOCUS_ALGO , true);
-
-        //Disable Region priority and enable Face priority
-        setAlgoPriority(REGION_PRIORITY, EXPOSURE_ALGO, false);
-        setAlgoPriority(FACE_PRIORITY, EXPOSURE_ALGO, true);
-        }
+    if ( mFaceDetectionRunning ) {
+        mFDSwitchAlgoPriority = true;
+    }
 
     // Note: White balance will not be face prioritized, since
     // the algorithm needs full frame statistics, and not face
@@ -125,7 +118,6 @@
 {
     status_t ret = NO_ERROR;
     OMX_ERRORTYPE eError = OMX_ErrorNone;
-    OMX_CONFIG_EXTRADATATYPE extraDataControl;
     OMX_CONFIG_OBJDETECTIONTYPE objDetection;
 
     LOG_FUNCTION_NAME;
@@ -170,27 +162,11 @@
 
     if ( NO_ERROR == ret )
         {
-        OMX_INIT_STRUCT_PTR (&extraDataControl, OMX_CONFIG_EXTRADATATYPE);
-        extraDataControl.nPortIndex = mCameraAdapterParameters.mPrevPortIndex;
-        extraDataControl.eExtraDataType = OMX_FaceDetection;
-        extraDataControl.eCameraView = OMX_2D;
-        if  ( enable )
-            {
-            extraDataControl.bEnable = OMX_TRUE;
-            }
-        else
-            {
-            extraDataControl.bEnable = OMX_FALSE;
-            }
+        ret = setExtraData(enable, mCameraAdapterParameters.mPrevPortIndex, OMX_FaceDetection);
 
-        eError =  OMX_SetConfig(mCameraAdapterParameters.mHandleComp,
-                                ( OMX_INDEXTYPE ) OMX_IndexConfigOtherExtraDataControl,
-                                &extraDataControl);
-        if ( OMX_ErrorNone != eError )
+        if ( NO_ERROR != ret )
             {
-            CAMHAL_LOGEB("Error while configuring face detection extra data 0x%x",
-                         eError);
-            ret = -1;
+            CAMHAL_LOGEA("Error while configuring face detection extra data");
             }
         else
             {
@@ -245,19 +221,19 @@
                          platformPrivate->pMetaDataBuffer,
                          platformPrivate->nMetaDataSize);
         } else {
-            CAMHAL_LOGEB("OMX_TI_PLATFORMPRIVATE size mismatch: expected = %d, received = %d",
+            CAMHAL_LOGDB("OMX_TI_PLATFORMPRIVATE size mismatch: expected = %d, received = %d",
                          ( unsigned int ) sizeof(OMX_TI_PLATFORMPRIVATE),
                          ( unsigned int ) platformPrivate->nSize);
-            ret = -EINVAL;
+            return -EINVAL;
         }
     }  else {
-        CAMHAL_LOGEA("Invalid OMX_TI_PLATFORMPRIVATE");
+        CAMHAL_LOGDA("Invalid OMX_TI_PLATFORMPRIVATE");
         return-EINVAL;
     }
 
 
     if ( 0 >= platformPrivate->nMetaDataSize ) {
-        CAMHAL_LOGEB("OMX_TI_PLATFORMPRIVATE nMetaDataSize is size is %d",
+        CAMHAL_LOGDB("OMX_TI_PLATFORMPRIVATE nMetaDataSize is size is %d",
                      ( unsigned int ) platformPrivate->nMetaDataSize);
         return -EINVAL;
     }
@@ -274,7 +250,7 @@
                      extraData->nPortIndex,
                      extraData->nVersion);
     } else {
-        CAMHAL_LOGEA("Invalid OMX_OTHER_EXTRADATATYPE");
+        CAMHAL_LOGDA("Invalid OMX_OTHER_EXTRADATATYPE");
         return -EINVAL;
     }
 
@@ -289,7 +265,7 @@
                          faceData->nPortIndex,
                          faceData->nVersion);
         } else {
-            CAMHAL_LOGEB("OMX_FACEDETECTIONTYPE size mismatch: expected = %d, received = %d",
+            CAMHAL_LOGDB("OMX_FACEDETECTIONTYPE size mismatch: expected = %d, received = %d",
                          ( unsigned int ) sizeof(OMX_FACEDETECTIONTYPE),
                          ( unsigned int ) faceData->nSize);
             return -EINVAL;
diff --git a/camera/OMXCameraAdapter/OMXFocus.cpp b/camera/OMXCameraAdapter/OMXFocus.cpp
index d9d4df4..50e2c21 100644
--- a/camera/OMXCameraAdapter/OMXFocus.cpp
+++ b/camera/OMXCameraAdapter/OMXFocus.cpp
@@ -84,7 +84,7 @@
     OMX_IMAGE_CONFIG_FOCUSCONTROLTYPE focusControl;
     OMX_PARAM_FOCUSSTATUSTYPE focusStatus;
     OMX_CONFIG_BOOLEANTYPE bOMX;
-    int timeout = 0;
+    nsecs_t timeout = 0;
 
     LOG_FUNCTION_NAME;
 
@@ -102,17 +102,14 @@
         return NO_ERROR;
         }
 
-    if ( 0 != mDoAFSem.Count() )
-        {
-        CAMHAL_LOGEB("Error mDoAFSem semaphore count %d", mDoAFSem.Count());
-        return NO_INIT;
-        }
 
     if( ((AF_ACTIVE & getState()) != AF_ACTIVE) && ((AF_ACTIVE & getNextState()) != AF_ACTIVE) ) {
        CAMHAL_LOGDA("Auto focus got canceled before doAutoFocus could be called");
        return NO_ERROR;
     }
 
+    OMX_INIT_STRUCT_PTR (&focusStatus, OMX_PARAM_FOCUSSTATUSTYPE);
+
     // If the app calls autoFocus, the camera will stop sending face callbacks.
     pauseFaceDetection(true);
 
@@ -141,8 +138,7 @@
     } else if ( mParameters3A.Focus == OMX_IMAGE_FocusControlAuto ) {
         // In case we have CAF running we should first check the AF status.
         // If it has managed to lock, then do as usual and return status
-        // immediately. If lock is not available, then switch temporarily
-        // to 'autolock' and do normal AF.
+        // immediately.
         ret = checkFocus(&focusStatus);
         if ( NO_ERROR != ret ) {
             CAMHAL_LOGEB("Focus status check failed 0x%x!", ret);
@@ -165,12 +161,6 @@
                                (OMX_INDEXTYPE)OMX_TI_IndexConfigAutofocusEnable,
                                &bOMX);
 
-        ret = RegisterForEvent(mCameraAdapterParameters.mHandleComp,
-                                    (OMX_EVENTTYPE) OMX_EventIndexSettingChanged,
-                                    OMX_ALL,
-                                    OMX_IndexConfigCommonFocusStatus,
-                                    mDoAFSem);
-
         // force AF, Ducati will take care of whether CAF
         // or AF will be performed, depending on light conditions
         if ( focusControl.eFocusControl == OMX_IMAGE_FocusControlAuto
@@ -194,31 +184,30 @@
         }
 
         // configure focus timeout based on capture mode
-        timeout = (mCapMode == VIDEO_MODE) ? AF_VIDEO_CALLBACK_TIMEOUT : AF_IMAGE_CALLBACK_TIMEOUT;
+        timeout = (mCapMode == VIDEO_MODE) ?
+                        ( ( nsecs_t ) AF_VIDEO_CALLBACK_TIMEOUT * 1000 ) :
+                        ( ( nsecs_t ) AF_IMAGE_CALLBACK_TIMEOUT * 1000 );
 
-        ret = mDoAFSem.WaitTimeout(timeout);
+            {
+            Mutex::Autolock lock(mDoAFMutex);
+            ret = mDoAFCond.waitRelative(mDoAFMutex, timeout);
+            }
+
         //If somethiing bad happened while we wait
         if (mComponentState == OMX_StateInvalid) {
           CAMHAL_LOGEA("Invalid State after Auto Focus Exitting!!!");
-          return EINVAL;
+          return -EINVAL;
         }
 
-        if( ret != NO_ERROR) {
-            //Disable auto focus callback from Ducati
-            setFocusCallback(false);
+        if(ret != NO_ERROR) {
             CAMHAL_LOGEA("Autofocus callback timeout expired");
-            RemoveEvent(mCameraAdapterParameters.mHandleComp,
-                                        (OMX_EVENTTYPE) OMX_EventIndexSettingChanged,
-                                        OMX_ALL,
-                                        OMX_IndexConfigCommonFocusStatus,
-                                        NULL );
-            returnFocusStatus(true);
+            ret = returnFocusStatus(true);
         } else {
             ret = returnFocusStatus(false);
         }
     } else { // Focus mode in continuous
         if ( NO_ERROR == ret ) {
-            ret = returnFocusStatus(false);
+            ret = returnFocusStatus(true);
             mPending3Asettings |= SetFocus;
         }
     }
@@ -230,7 +219,6 @@
 
 status_t OMXCameraAdapter::stopAutoFocus()
 {
-    status_t ret = NO_ERROR;
     OMX_ERRORTYPE eError = OMX_ErrorNone;
     OMX_IMAGE_CONFIG_FOCUSCONTROLTYPE focusControl;
 
@@ -254,24 +242,29 @@
         return NO_ERROR;
     }
 
-    if ( NO_ERROR == ret )
-        {
-        OMX_INIT_STRUCT_PTR (&focusControl, OMX_IMAGE_CONFIG_FOCUSCONTROLTYPE);
-        focusControl.eFocusControl = OMX_IMAGE_FocusControlOff;
+    OMX_INIT_STRUCT_PTR (&focusControl, OMX_IMAGE_CONFIG_FOCUSCONTROLTYPE);
+    focusControl.eFocusControl = OMX_IMAGE_FocusControlOff;
 
-        eError =  OMX_SetConfig(mCameraAdapterParameters.mHandleComp,
-                                OMX_IndexConfigFocusControl,
-                                &focusControl);
-        if ( OMX_ErrorNone != eError )
-            {
-            CAMHAL_LOGEB("Error while stopping focus 0x%x", eError);
-            return ErrorUtils::omxToAndroidError(eError);
-            }
-        }
+    eError =  OMX_SetConfig(mCameraAdapterParameters.mHandleComp,
+                            OMX_IndexConfigFocusControl,
+                            &focusControl);
+    if ( OMX_ErrorNone != eError )
+        {
+        CAMHAL_LOGEB("Error while stopping focus 0x%x", eError);
+        return ErrorUtils::omxToAndroidError(eError);
+    } else {
+        // This is a WA. Usually the OMX Camera component should
+        // generate AF status change OMX event fairly quickly
+        // ( after one preview frame ) and this notification should
+        // actually come from 'handleFocusCallback()'.
+        Mutex::Autolock lock(mDoAFMutex);
+        mDoAFCond.broadcast();
+    }
+
 
     LOG_FUNCTION_NAME_EXIT;
 
-    return ret;
+    return NO_ERROR;
 }
 
 status_t OMXCameraAdapter::getFocusMode(OMX_IMAGE_CONFIG_FOCUSCONTROLTYPE &focusMode)
@@ -319,19 +312,12 @@
          ( focusMode.eFocusControl != ( OMX_IMAGE_FOCUSCONTROLTYPE )
                  OMX_IMAGE_FocusControlAutoInfinity ) ) {
         stopAutoFocus();
-        //Signal a dummy AF event so that in case the callback from ducati
-        //does come then it doesnt crash after
-        //exiting this function since eventSem will go out of scope.
-        ret |= SignalEvent(mCameraAdapterParameters.mHandleComp,
-                                    (OMX_EVENTTYPE) OMX_EventIndexSettingChanged,
-                                    OMX_ALL,
-                                    OMX_IndexConfigCommonFocusStatus,
-                                    NULL );
     } else if (focusMode.eFocusControl == OMX_IMAGE_FocusControlAuto) {
+       // This re-enabling of CAF doesn't seem to
+       // be needed any more.
        // re-apply CAF after unlocking and canceling
-       mPending3Asettings |= SetFocus;
+       // mPending3Asettings |= SetFocus;
     }
-
     // If the apps call #cancelAutoFocus()}, the face callbacks will also resume.
     pauseFaceDetection(false);
 
@@ -401,7 +387,7 @@
 {
     status_t ret = NO_ERROR;
     OMX_PARAM_FOCUSSTATUSTYPE eFocusStatus;
-    bool focusStatus = false;
+    CameraHalEvent::FocusStatus focusStatus = CameraHalEvent::FOCUS_STATUS_FAIL;
     BaseCameraAdapter::AdapterState state, nextState;
     BaseCameraAdapter::getState(state);
     BaseCameraAdapter::getNextState(nextState);
@@ -436,7 +422,7 @@
 
         if ( timeoutReached )
             {
-            focusStatus = false;
+            focusStatus = CameraHalEvent::FOCUS_STATUS_FAIL;
             }
         else
             {
@@ -444,15 +430,16 @@
                 {
                     case OMX_FocusStatusReached:
                         {
-                        focusStatus = true;
+                        focusStatus = CameraHalEvent::FOCUS_STATUS_SUCCESS;
                         break;
                         }
-                    case OMX_FocusStatusOff:
+                    case OMX_FocusStatusOff: // AF got canceled
+                        return NO_ERROR;
                     case OMX_FocusStatusUnableToReach:
                     case OMX_FocusStatusRequest:
                     default:
                         {
-                        focusStatus = false;
+                        focusStatus = CameraHalEvent::FOCUS_STATUS_FAIL;
                         break;
                         }
                 }
@@ -462,9 +449,9 @@
             } else {
                 CAMHAL_LOGDA("Focus locked. Applied focus locks successfully");
             }
-
             stopAutoFocus();
             }
+
         //Query current focus distance after AF is complete
         updateFocusDistances(mParameters);
        }
@@ -520,7 +507,6 @@
     if ( NO_ERROR == ret )
         {
         OMX_INIT_STRUCT_PTR (eFocusStatus, OMX_PARAM_FOCUSSTATUSTYPE);
-
         eError = OMX_GetConfig(mCameraAdapterParameters.mHandleComp,
                                OMX_IndexConfigCommonFocusStatus,
                                eFocusStatus);
@@ -800,4 +786,54 @@
     return ret;
 }
 
+void OMXCameraAdapter::handleFocusCallback() {
+    OMX_PARAM_FOCUSSTATUSTYPE eFocusStatus;
+    CameraHalEvent::FocusStatus focusStatus = CameraHalEvent::FOCUS_STATUS_FAIL;
+    status_t ret = NO_ERROR;
+    BaseCameraAdapter::AdapterState nextState;
+    BaseCameraAdapter::getNextState(nextState);
+
+    OMX_INIT_STRUCT(eFocusStatus, OMX_PARAM_FOCUSSTATUSTYPE);
+
+    ret = checkFocus(&eFocusStatus);
+
+    if (NO_ERROR != ret) {
+        CAMHAL_LOGEA("Focus status check failed!");
+        // signal and unblock doAutoFocus
+        if (AF_ACTIVE & nextState) {
+            Mutex::Autolock lock(mDoAFMutex);
+            mDoAFCond.broadcast();
+        }
+        return;
+    }
+
+    if ( ( eFocusStatus.eFocusStatus != OMX_FocusStatusRequest ) &&
+         ( eFocusStatus.eFocusStatus != OMX_FocusStatusOff ) ) {
+        // signal doAutoFocus when a end of scan message comes
+        // ignore start of scan
+        Mutex::Autolock lock(mDoAFMutex);
+        mDoAFCond.broadcast();
+    }
+
+    if (mParameters3A.Focus != (OMX_IMAGE_FOCUSCONTROLTYPE) OMX_IMAGE_FocusControlAuto) {
+       CAMHAL_LOGDA("unregistered focus callback when not in CAF or doAutoFocus... not handling");
+       return;
+    }
+
+    // Handling for CAF Callbacks
+    switch (eFocusStatus.eFocusStatus) {
+        case OMX_FocusStatusRequest:
+            focusStatus = CameraHalEvent::FOCUS_STATUS_PENDING;
+            break;
+        case OMX_FocusStatusReached:
+        case OMX_FocusStatusOff:
+        case OMX_FocusStatusUnableToReach:
+        default:
+            focusStatus = CameraHalEvent::FOCUS_STATUS_DONE;
+            break;
+    }
+
+    notifyFocusSubscribers(focusStatus);
+}
+
 };
diff --git a/camera/V4LCameraAdapter/V4LCameraAdapter.cpp b/camera/V4LCameraAdapter/V4LCameraAdapter.cpp
index 3fb3380..c365023 100644
--- a/camera/V4LCameraAdapter/V4LCameraAdapter.cpp
+++ b/camera/V4LCameraAdapter/V4LCameraAdapter.cpp
@@ -438,7 +438,7 @@
         mFps = ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
         mLastFpsTime = now;
         mLastFrameCount = mFrameCount;
-        LOGD("Camera %d Frames, %f FPS", mFrameCount, mFps);
+        ALOGD("Camera %d Frames, %f FPS", mFrameCount, mFps);
     }
     // XXX: mFPS has the value we want
 }
diff --git a/camera/inc/ANativeWindowDisplayAdapter.h b/camera/inc/ANativeWindowDisplayAdapter.h
index e4698d0..9cdf45a 100644
--- a/camera/inc/ANativeWindowDisplayAdapter.h
+++ b/camera/inc/ANativeWindowDisplayAdapter.h
@@ -1,189 +1,188 @@
-/*

- * Copyright (C) Texas Instruments - http://www.ti.com/

- *

- * 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.

- */

-

-

-

-#include "CameraHal.h"

-#include <ui/egl/android_natives.h>

-#include <ui/GraphicBufferMapper.h>

-#include <hal_public.h>

-

-//temporarily define format here

-#define HAL_PIXEL_FORMAT_TI_NV12 0x100

-

-namespace android {

-

-/**

- * Display handler class - This class basically handles the buffer posting to display

- */

-

-class ANativeWindowDisplayAdapter : public DisplayAdapter

-{

-public:

-

-    typedef struct

-        {

-        void *mBuffer;

-        void *mUser;

-        int mOffset;

-        int mWidth;

-        int mHeight;

-        int mWidthStride;

-        int mHeightStride;

-        int mLength;

-        CameraFrame::FrameType mType;

-        } DisplayFrame;

-

-    enum DisplayStates

-        {

-        DISPLAY_INIT = 0,

-        DISPLAY_STARTED,

-        DISPLAY_STOPPED,

-        DISPLAY_EXITED

-        };

-

-public:

-

-    ANativeWindowDisplayAdapter();

-    virtual ~ANativeWindowDisplayAdapter();

-

-    ///Initializes the display adapter creates any resources required

-    virtual status_t initialize();

-

-    virtual int setPreviewWindow(struct preview_stream_ops *window);

-    virtual int setFrameProvider(FrameNotifier *frameProvider);

-    virtual int setErrorHandler(ErrorNotifier *errorNotifier);

-    virtual int enableDisplay(int width, int height, struct timeval *refTime = NULL, S3DParameters *s3dParams = NULL);

-    virtual int disableDisplay(bool cancel_buffer = true);

-    virtual status_t pauseDisplay(bool pause);

-

-#if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS

-

-    //Used for shot to snapshot measurement

-    virtual status_t setSnapshotTimeRef(struct timeval *refTime = NULL);

-

-#endif

-

-    virtual int useBuffers(void* bufArr, int num);

-    virtual bool supportsExternalBuffering();

-

-    //Implementation of inherited interfaces

-    virtual void* allocateBuffer(int width, int height, const char* format, int &bytes, int numBufs);

-    virtual uint32_t * getOffsets() ;

-    virtual int getFd() ;

-    virtual int freeBuffer(void* buf);

-

-    virtual int maxQueueableBuffers(unsigned int& queueable);

-

-    ///Class specific functions

-    static void frameCallbackRelay(CameraFrame* caFrame);

-    void frameCallback(CameraFrame* caFrame);

-

-    void displayThread();

-

-    private:

-    void destroy();

-    bool processHalMsg();

-    status_t PostFrame(ANativeWindowDisplayAdapter::DisplayFrame &dispFrame);

-    bool handleFrameReturn();

-    status_t returnBuffersToWindow();

-

-public:

-

-    static const int DISPLAY_TIMEOUT;

-    static const int FAILED_DQS_TO_SUSPEND;

-

-    class DisplayThread : public Thread

-        {

-        ANativeWindowDisplayAdapter* mDisplayAdapter;

-        TIUTILS::MessageQueue mDisplayThreadQ;

-

-        public:

-            DisplayThread(ANativeWindowDisplayAdapter* da)

-            : Thread(false), mDisplayAdapter(da) { }

-

-        ///Returns a reference to the display message Q for display adapter to post messages

-            TIUTILS::MessageQueue& msgQ()

-                {

-                return mDisplayThreadQ;

-                }

-

-            virtual bool threadLoop()

-                {

-                mDisplayAdapter->displayThread();

-                return false;

-                }

-

-            enum DisplayThreadCommands

-                {

-                DISPLAY_START,

-                DISPLAY_STOP,

-                DISPLAY_FRAME,

-                DISPLAY_EXIT

-                };

-        };

-

-    //friend declarations

-friend class DisplayThread;

-

-private:

-    int postBuffer(void* displayBuf);

-

-private:

-    bool mFirstInit;

-    bool mSuspend;

-    int mFailedDQs;

-    bool mPaused; //Pause state

-    preview_stream_ops_t*  mANativeWindow;

-    sp<DisplayThread> mDisplayThread;

-    FrameProvider *mFrameProvider; ///Pointer to the frame provider interface

-    TIUTILS::MessageQueue mDisplayQ;

-    unsigned int mDisplayState;

-    ///@todo Have a common class for these members

-    mutable Mutex mLock;

-    bool mDisplayEnabled;

-    int mBufferCount;

-    buffer_handle_t** mBufferHandleMap;

-    IMG_native_handle_t** mGrallocHandleMap;

-    uint32_t* mOffsetsMap;

-    int mFD;

-    KeyedVector<int, int> mFramesWithCameraAdapterMap;

-    sp<ErrorNotifier> mErrorNotifier;

-

-    uint32_t mFrameWidth;

-    uint32_t mFrameHeight;

-    uint32_t mPreviewWidth;

-    uint32_t mPreviewHeight;

-

-    uint32_t mXOff;

-    uint32_t mYOff;

-

-    const char *mPixelFormat;

-

-#if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS

-    //Used for calculating standby to first shot

-    struct timeval mStandbyToShot;

-    bool mMeasureStandby;

-    //Used for shot to snapshot/shot calculation

-    struct timeval mStartCapture;

-    bool mShotToShot;

-

-#endif

-

-};

-

-};

-

+/*
+ * Copyright (C) Texas Instruments - http://www.ti.com/
+ *
+ * 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.
+ */
+
+
+
+#include "CameraHal.h"
+#include <ui/GraphicBufferMapper.h>
+#include <hal_public.h>
+
+//temporarily define format here
+#define HAL_PIXEL_FORMAT_TI_NV12 0x100
+
+namespace android {
+
+/**
+ * Display handler class - This class basically handles the buffer posting to display
+ */
+
+class ANativeWindowDisplayAdapter : public DisplayAdapter
+{
+public:
+
+    typedef struct
+        {
+        void *mBuffer;
+        void *mUser;
+        int mOffset;
+        int mWidth;
+        int mHeight;
+        int mWidthStride;
+        int mHeightStride;
+        int mLength;
+        CameraFrame::FrameType mType;
+        } DisplayFrame;
+
+    enum DisplayStates
+        {
+        DISPLAY_INIT = 0,
+        DISPLAY_STARTED,
+        DISPLAY_STOPPED,
+        DISPLAY_EXITED
+        };
+
+public:
+
+    ANativeWindowDisplayAdapter();
+    virtual ~ANativeWindowDisplayAdapter();
+
+    ///Initializes the display adapter creates any resources required
+    virtual status_t initialize();
+
+    virtual int setPreviewWindow(struct preview_stream_ops *window);
+    virtual int setFrameProvider(FrameNotifier *frameProvider);
+    virtual int setErrorHandler(ErrorNotifier *errorNotifier);
+    virtual int enableDisplay(int width, int height, struct timeval *refTime = NULL, S3DParameters *s3dParams = NULL);
+    virtual int disableDisplay(bool cancel_buffer = true);
+    virtual status_t pauseDisplay(bool pause);
+
+#if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS
+
+    //Used for shot to snapshot measurement
+    virtual status_t setSnapshotTimeRef(struct timeval *refTime = NULL);
+
+#endif
+
+    virtual int useBuffers(void* bufArr, int num);
+    virtual bool supportsExternalBuffering();
+
+    //Implementation of inherited interfaces
+    virtual void* allocateBuffer(int width, int height, const char* format, int &bytes, int numBufs);
+    virtual uint32_t * getOffsets() ;
+    virtual int getFd() ;
+    virtual int freeBuffer(void* buf);
+
+    virtual int maxQueueableBuffers(unsigned int& queueable);
+
+    ///Class specific functions
+    static void frameCallbackRelay(CameraFrame* caFrame);
+    void frameCallback(CameraFrame* caFrame);
+
+    void displayThread();
+
+    private:
+    void destroy();
+    bool processHalMsg();
+    status_t PostFrame(ANativeWindowDisplayAdapter::DisplayFrame &dispFrame);
+    bool handleFrameReturn();
+    status_t returnBuffersToWindow();
+
+public:
+
+    static const int DISPLAY_TIMEOUT;
+    static const int FAILED_DQS_TO_SUSPEND;
+
+    class DisplayThread : public Thread
+        {
+        ANativeWindowDisplayAdapter* mDisplayAdapter;
+        TIUTILS::MessageQueue mDisplayThreadQ;
+
+        public:
+            DisplayThread(ANativeWindowDisplayAdapter* da)
+            : Thread(false), mDisplayAdapter(da) { }
+
+        ///Returns a reference to the display message Q for display adapter to post messages
+            TIUTILS::MessageQueue& msgQ()
+                {
+                return mDisplayThreadQ;
+                }
+
+            virtual bool threadLoop()
+                {
+                mDisplayAdapter->displayThread();
+                return false;
+                }
+
+            enum DisplayThreadCommands
+                {
+                DISPLAY_START,
+                DISPLAY_STOP,
+                DISPLAY_FRAME,
+                DISPLAY_EXIT
+                };
+        };
+
+    //friend declarations
+friend class DisplayThread;
+
+private:
+    int postBuffer(void* displayBuf);
+
+private:
+    bool mFirstInit;
+    bool mSuspend;
+    int mFailedDQs;
+    bool mPaused; //Pause state
+    preview_stream_ops_t*  mANativeWindow;
+    sp<DisplayThread> mDisplayThread;
+    FrameProvider *mFrameProvider; ///Pointer to the frame provider interface
+    TIUTILS::MessageQueue mDisplayQ;
+    unsigned int mDisplayState;
+    ///@todo Have a common class for these members
+    mutable Mutex mLock;
+    bool mDisplayEnabled;
+    int mBufferCount;
+    buffer_handle_t** mBufferHandleMap;
+    IMG_native_handle_t** mGrallocHandleMap;
+    uint32_t* mOffsetsMap;
+    int mFD;
+    KeyedVector<int, int> mFramesWithCameraAdapterMap;
+    sp<ErrorNotifier> mErrorNotifier;
+
+    uint32_t mFrameWidth;
+    uint32_t mFrameHeight;
+    uint32_t mPreviewWidth;
+    uint32_t mPreviewHeight;
+
+    uint32_t mXOff;
+    uint32_t mYOff;
+
+    const char *mPixelFormat;
+
+#if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS
+    //Used for calculating standby to first shot
+    struct timeval mStandbyToShot;
+    bool mMeasureStandby;
+    //Used for shot to snapshot/shot calculation
+    struct timeval mStartCapture;
+    bool mShotToShot;
+
+#endif
+
+};
+
+};
+
diff --git a/camera/inc/BaseCameraAdapter.h b/camera/inc/BaseCameraAdapter.h
index d778491..bc38e00 100644
--- a/camera/inc/BaseCameraAdapter.h
+++ b/camera/inc/BaseCameraAdapter.h
@@ -145,7 +145,7 @@
 
     // ---------------------Interface ends-----------------------------------
 
-    status_t notifyFocusSubscribers(bool status);
+    status_t notifyFocusSubscribers(CameraHalEvent::FocusStatus status);
     status_t notifyShutterSubscribers();
     status_t notifyZoomSubscribers(int zoomIdx, bool targetReached);
     status_t notifyFaceSubscribers(sp<CameraFDResult> &faces);
diff --git a/camera/inc/CameraHal.h b/camera/inc/CameraHal.h
index e34f4df..8b8392a 100644
--- a/camera/inc/CameraHal.h
+++ b/camera/inc/CameraHal.h
@@ -77,7 +77,7 @@
 #define LOCK_BUFFER_TRIES 5
 #define HAL_PIXEL_FORMAT_NV12 0x100
 
-#define CAMHAL_LOGI LOGI
+#define CAMHAL_LOGI ALOGI
 
 //Uncomment to enable more verbose/debug logs
 //#define DEBUG_LOG
@@ -90,8 +90,8 @@
 #define CAMHAL_LOGVA(str)
 #define CAMHAL_LOGVB(str, ...)
 
-#define CAMHAL_LOGEA LOGE
-#define CAMHAL_LOGEB LOGE
+#define CAMHAL_LOGEA ALOGE
+#define CAMHAL_LOGEB ALOGE
 
 #undef LOG_FUNCTION_NAME
 #undef LOG_FUNCTION_NAME_EXIT
@@ -331,6 +331,13 @@
         ALL_EVENTS = 0xFFFF ///Maximum of 16 event types supported
     };
 
+    enum FocusStatus {
+        FOCUS_STATUS_SUCCESS = 0x1,
+        FOCUS_STATUS_FAIL = 0x2,
+        FOCUS_STATUS_PENDING = 0x4,
+        FOCUS_STATUS_DONE = 0x8,
+    };
+
     ///Class declarations
     ///@remarks Add a new class for a new event type added above
 
@@ -341,8 +348,7 @@
 
     ///Focus event specific data
     typedef struct FocusEventData_t {
-        bool focusLocked;
-        bool focusError;
+        FocusStatus focusStatus;
         int currentFocusValue;
     } FocusEventData;
 
@@ -678,7 +684,7 @@
 class MemoryManager : public BufferProvider, public virtual RefBase
 {
 public:
-    MemoryManager():mIonFd(0){ }
+    MemoryManager():mIonFd(-1){ }
 
     ///Initializes the memory manager creates any resources required
     status_t initialize() { return NO_ERROR; }
diff --git a/camera/inc/CameraProperties.h b/camera/inc/CameraProperties.h
index a220af7..6f05877 100644
--- a/camera/inc/CameraProperties.h
+++ b/camera/inc/CameraProperties.h
@@ -1,198 +1,198 @@
-/*

- * Copyright (C) Texas Instruments - http://www.ti.com/

- *

- * 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 CAMERA_PROPERTIES_H

-#define CAMERA_PROPERTIES_H

-

-#include <utils/KeyedVector.h>

-#include <utils/String8.h>

-#include <stdio.h>

-#include <dirent.h>

-#include <errno.h>

-#include <stdio.h>

-#include <string.h>

-#include <ctype.h>

-#include "cutils/properties.h"

-

-namespace android {

-

-#define MAX_CAMERAS_SUPPORTED 2

-#define MAX_SIMUL_CAMERAS_SUPPORTED 1

-#define MAX_PROP_NAME_LENGTH 50

-#define MAX_PROP_VALUE_LENGTH 2048

-

-#define EXIF_MAKE_DEFAULT "default_make"

-#define EXIF_MODEL_DEFAULT "default_model"

-

-// Class that handles the Camera Properties

-class CameraProperties

-{

-public:

-    static const char INVALID[];

-    static const char CAMERA_NAME[];

-    static const char CAMERA_SENSOR_INDEX[];

-    static const char ORIENTATION_INDEX[];

-    static const char FACING_INDEX[];

-    static const char S3D_SUPPORTED[];

-    static const char SUPPORTED_PREVIEW_SIZES[];

-    static const char SUPPORTED_PREVIEW_FORMATS[];

-    static const char SUPPORTED_PREVIEW_FRAME_RATES[];

-    static const char SUPPORTED_PICTURE_SIZES[];

-    static const char SUPPORTED_PICTURE_FORMATS[];

-    static const char SUPPORTED_THUMBNAIL_SIZES[];

-    static const char SUPPORTED_WHITE_BALANCE[];

-    static const char SUPPORTED_EFFECTS[];

-    static const char SUPPORTED_ANTIBANDING[];

-    static const char SUPPORTED_EXPOSURE_MODES[];

-    static const char SUPPORTED_EV_MIN[];

-    static const char SUPPORTED_EV_MAX[];

-    static const char SUPPORTED_EV_STEP[];

-    static const char SUPPORTED_ISO_VALUES[];

-    static const char SUPPORTED_SCENE_MODES[];

-    static const char SUPPORTED_FLASH_MODES[];

-    static const char SUPPORTED_FOCUS_MODES[];

-    static const char REQUIRED_PREVIEW_BUFS[];

-    static const char REQUIRED_IMAGE_BUFS[];

-    static const char SUPPORTED_ZOOM_RATIOS[];

-    static const char SUPPORTED_ZOOM_STAGES[];

-    static const char SUPPORTED_IPP_MODES[];

-    static const char SMOOTH_ZOOM_SUPPORTED[];

-    static const char ZOOM_SUPPORTED[];

-    static const char PREVIEW_SIZE[];

-    static const char PREVIEW_FORMAT[];

-    static const char PREVIEW_FRAME_RATE[];

-    static const char ZOOM[];

-    static const char PICTURE_SIZE[];

-    static const char PICTURE_FORMAT[];

-    static const char JPEG_THUMBNAIL_SIZE[];

-    static const char WHITEBALANCE[];

-    static const char EFFECT[];

-    static const char ANTIBANDING[];

-    static const char EXPOSURE_MODE[];

-    static const char EV_COMPENSATION[];

-    static const char ISO_MODE[];

-    static const char FOCUS_MODE[];

-    static const char SCENE_MODE[];

-    static const char FLASH_MODE[];

-    static const char JPEG_QUALITY[];

-    static const char BRIGHTNESS[];

-    static const char SATURATION[];

-    static const char SHARPNESS[];

-    static const char CONTRAST[];

-    static const char IPP[];

-    static const char GBCE[];

-    static const char AUTOCONVERGENCE[];

-    static const char AUTOCONVERGENCE_MODE[];

-    static const char MANUALCONVERGENCE_VALUES[];

-    static const char SENSOR_ORIENTATION[];

-    static const char SENSOR_ORIENTATION_VALUES[];

-    static const char REVISION[];

-    static const char FOCAL_LENGTH[];

-    static const char HOR_ANGLE[];

-    static const char VER_ANGLE[];

-    static const char EXIF_MAKE[];

-    static const char EXIF_MODEL[];

-    static const char JPEG_THUMBNAIL_QUALITY[];

-    static const char MAX_FOCUS_AREAS[];

-    static const char MAX_FD_HW_FACES[];

-    static const char MAX_FD_SW_FACES[];

-

-    static const char PARAMS_DELIMITER [];

-

-    static const char S3D2D_PREVIEW[];

-    static const char S3D2D_PREVIEW_MODES[];

-    static const char VSTAB[];

-    static const char VSTAB_SUPPORTED[];

-    static const char FRAMERATE_RANGE[];

-    static const char FRAMERATE_RANGE_IMAGE[];

-    static const char FRAMERATE_RANGE_VIDEO[];

-    static const char FRAMERATE_RANGE_SUPPORTED[];

-

-    static const char DEFAULT_VALUE[];

-

-    static const char AUTO_EXPOSURE_LOCK[];

-    static const char AUTO_EXPOSURE_LOCK_SUPPORTED[];

-    static const char AUTO_WHITEBALANCE_LOCK[];

-    static const char AUTO_WHITEBALANCE_LOCK_SUPPORTED[];

-    static const char MAX_NUM_METERING_AREAS[];

-    static const char METERING_AREAS[];

-    static const char MAX_NUM_FOCUS_AREAS[];

-

-    static const char VIDEO_SNAPSHOT_SUPPORTED[];

-

-    static const char VIDEO_SIZE[];

-    static const char SUPPORTED_VIDEO_SIZES[];

-    static const char PREFERRED_PREVIEW_SIZE_FOR_VIDEO[];

-

-    CameraProperties();

-    ~CameraProperties();

-

-    // container class passed around for accessing properties

-    class Properties

-    {

-        public:

-            Properties()

-            {

-                mProperties = new DefaultKeyedVector<String8, String8>(String8(DEFAULT_VALUE));

-                char property[PROPERTY_VALUE_MAX];

-                property_get("ro.product.manufacturer", property, EXIF_MAKE_DEFAULT);

-                property[0] = toupper(property[0]);

-                set(EXIF_MAKE, property);

-                property_get("ro.product.model", property, EXIF_MODEL_DEFAULT);

-                property[0] = toupper(property[0]);

-                set(EXIF_MODEL, property);

-            }

-            ~Properties()

-            {

-                delete mProperties;

-            }

-            ssize_t set(const char *prop, const char *value);

-            ssize_t set(const char *prop, int value);

-            const char* get(const char * prop);

-            void dump();

-

-        protected:

-            const char* keyAt(unsigned int);

-            const char* valueAt(unsigned int);

-

-        private:

-            DefaultKeyedVector<String8, String8>* mProperties;

-

-    };

-

-    ///Initializes the CameraProperties class

-    status_t initialize();

-    status_t loadProperties();

-    int camerasSupported();

-    int getProperties(int cameraIndex, Properties** properties);

-

-private:

-

-    uint32_t mCamerasSupported;

-    int mInitialized;

-    mutable Mutex mLock;

-

-    Properties mCameraProps[MAX_CAMERAS_SUPPORTED];

-

-};

-

-};

-

-#endif //CAMERA_PROPERTIES_H

-

+/*
+ * Copyright (C) Texas Instruments - http://www.ti.com/
+ *
+ * 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 CAMERA_PROPERTIES_H
+#define CAMERA_PROPERTIES_H
+
+#include <utils/KeyedVector.h>
+#include <utils/String8.h>
+#include <stdio.h>
+#include <dirent.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+#include <ctype.h>
+#include "cutils/properties.h"
+
+namespace android {
+
+#define MAX_CAMERAS_SUPPORTED 2
+#define MAX_SIMUL_CAMERAS_SUPPORTED 1
+#define MAX_PROP_NAME_LENGTH 50
+#define MAX_PROP_VALUE_LENGTH 2048
+
+#define EXIF_MAKE_DEFAULT "default_make"
+#define EXIF_MODEL_DEFAULT "default_model"
+
+// Class that handles the Camera Properties
+class CameraProperties
+{
+public:
+    static const char INVALID[];
+    static const char CAMERA_NAME[];
+    static const char CAMERA_SENSOR_INDEX[];
+    static const char ORIENTATION_INDEX[];
+    static const char FACING_INDEX[];
+    static const char S3D_SUPPORTED[];
+    static const char SUPPORTED_PREVIEW_SIZES[];
+    static const char SUPPORTED_PREVIEW_FORMATS[];
+    static const char SUPPORTED_PREVIEW_FRAME_RATES[];
+    static const char SUPPORTED_PICTURE_SIZES[];
+    static const char SUPPORTED_PICTURE_FORMATS[];
+    static const char SUPPORTED_THUMBNAIL_SIZES[];
+    static const char SUPPORTED_WHITE_BALANCE[];
+    static const char SUPPORTED_EFFECTS[];
+    static const char SUPPORTED_ANTIBANDING[];
+    static const char SUPPORTED_EXPOSURE_MODES[];
+    static const char SUPPORTED_EV_MIN[];
+    static const char SUPPORTED_EV_MAX[];
+    static const char SUPPORTED_EV_STEP[];
+    static const char SUPPORTED_ISO_VALUES[];
+    static const char SUPPORTED_SCENE_MODES[];
+    static const char SUPPORTED_FLASH_MODES[];
+    static const char SUPPORTED_FOCUS_MODES[];
+    static const char REQUIRED_PREVIEW_BUFS[];
+    static const char REQUIRED_IMAGE_BUFS[];
+    static const char SUPPORTED_ZOOM_RATIOS[];
+    static const char SUPPORTED_ZOOM_STAGES[];
+    static const char SUPPORTED_IPP_MODES[];
+    static const char SMOOTH_ZOOM_SUPPORTED[];
+    static const char ZOOM_SUPPORTED[];
+    static const char PREVIEW_SIZE[];
+    static const char PREVIEW_FORMAT[];
+    static const char PREVIEW_FRAME_RATE[];
+    static const char ZOOM[];
+    static const char PICTURE_SIZE[];
+    static const char PICTURE_FORMAT[];
+    static const char JPEG_THUMBNAIL_SIZE[];
+    static const char WHITEBALANCE[];
+    static const char EFFECT[];
+    static const char ANTIBANDING[];
+    static const char EXPOSURE_MODE[];
+    static const char EV_COMPENSATION[];
+    static const char ISO_MODE[];
+    static const char FOCUS_MODE[];
+    static const char SCENE_MODE[];
+    static const char FLASH_MODE[];
+    static const char JPEG_QUALITY[];
+    static const char BRIGHTNESS[];
+    static const char SATURATION[];
+    static const char SHARPNESS[];
+    static const char CONTRAST[];
+    static const char IPP[];
+    static const char GBCE[];
+    static const char AUTOCONVERGENCE[];
+    static const char AUTOCONVERGENCE_MODE[];
+    static const char MANUALCONVERGENCE_VALUES[];
+    static const char SENSOR_ORIENTATION[];
+    static const char SENSOR_ORIENTATION_VALUES[];
+    static const char REVISION[];
+    static const char FOCAL_LENGTH[];
+    static const char HOR_ANGLE[];
+    static const char VER_ANGLE[];
+    static const char EXIF_MAKE[];
+    static const char EXIF_MODEL[];
+    static const char JPEG_THUMBNAIL_QUALITY[];
+    static const char MAX_FOCUS_AREAS[];
+    static const char MAX_FD_HW_FACES[];
+    static const char MAX_FD_SW_FACES[];
+
+    static const char PARAMS_DELIMITER [];
+
+    static const char S3D2D_PREVIEW[];
+    static const char S3D2D_PREVIEW_MODES[];
+    static const char VSTAB[];
+    static const char VSTAB_SUPPORTED[];
+    static const char FRAMERATE_RANGE[];
+    static const char FRAMERATE_RANGE_IMAGE[];
+    static const char FRAMERATE_RANGE_VIDEO[];
+    static const char FRAMERATE_RANGE_SUPPORTED[];
+
+    static const char DEFAULT_VALUE[];
+
+    static const char AUTO_EXPOSURE_LOCK[];
+    static const char AUTO_EXPOSURE_LOCK_SUPPORTED[];
+    static const char AUTO_WHITEBALANCE_LOCK[];
+    static const char AUTO_WHITEBALANCE_LOCK_SUPPORTED[];
+    static const char MAX_NUM_METERING_AREAS[];
+    static const char METERING_AREAS[];
+    static const char MAX_NUM_FOCUS_AREAS[];
+
+    static const char VIDEO_SNAPSHOT_SUPPORTED[];
+
+    static const char VIDEO_SIZE[];
+    static const char SUPPORTED_VIDEO_SIZES[];
+    static const char PREFERRED_PREVIEW_SIZE_FOR_VIDEO[];
+
+    CameraProperties();
+    ~CameraProperties();
+
+    // container class passed around for accessing properties
+    class Properties
+    {
+        public:
+            Properties()
+            {
+                mProperties = new DefaultKeyedVector<String8, String8>(String8(DEFAULT_VALUE));
+                char property[PROPERTY_VALUE_MAX];
+                property_get("ro.product.manufacturer", property, EXIF_MAKE_DEFAULT);
+                property[0] = toupper(property[0]);
+                set(EXIF_MAKE, property);
+                property_get("ro.product.model", property, EXIF_MODEL_DEFAULT);
+                property[0] = toupper(property[0]);
+                set(EXIF_MODEL, property);
+            }
+            ~Properties()
+            {
+                delete mProperties;
+            }
+            ssize_t set(const char *prop, const char *value);
+            ssize_t set(const char *prop, int value);
+            const char* get(const char * prop);
+            void dump();
+
+        protected:
+            const char* keyAt(unsigned int);
+            const char* valueAt(unsigned int);
+
+        private:
+            DefaultKeyedVector<String8, String8>* mProperties;
+
+    };
+
+    ///Initializes the CameraProperties class
+    status_t initialize();
+    status_t loadProperties();
+    int camerasSupported();
+    int getProperties(int cameraIndex, Properties** properties);
+
+private:
+
+    uint32_t mCamerasSupported;
+    int mInitialized;
+    mutable Mutex mLock;
+
+    Properties mCameraProps[MAX_CAMERAS_SUPPORTED];
+
+};
+
+};
+
+#endif //CAMERA_PROPERTIES_H
+
diff --git a/camera/inc/Encoder_libjpeg.h b/camera/inc/Encoder_libjpeg.h
old mode 100755
new mode 100644
index fef873f..727dd92
--- a/camera/inc/Encoder_libjpeg.h
+++ b/camera/inc/Encoder_libjpeg.h
@@ -30,6 +30,9 @@
 extern "C" {
 #include "jhead.h"
 }
+
+#define CANCEL_TIMEOUT 3000000 // 3 seconds
+
 namespace android {
 /**
  * libjpeg encoder class - uses libjpeg to encode yuv
@@ -41,8 +44,10 @@
                                             CameraFrame::FrameType type,
                                             void* cookie1,
                                             void* cookie2,
-                                            void* cookie3);
+                                            void* cookie3,
+                                            bool canceled);
 
+// these have to match strings defined in external/jhead/exif.c
 static const char TAG_MODEL[] = "Model";
 static const char TAG_MAKE[] = "Make";
 static const char TAG_FOCALLENGTH[] = "FocalLength";
@@ -61,12 +66,27 @@
 static const char TAG_GPS_TIMESTAMP[] = "GPSTimeStamp";
 static const char TAG_GPS_DATESTAMP[] = "GPSDateStamp";
 static const char TAG_ORIENTATION[] = "Orientation";
+static const char TAG_FLASH[] = "Flash";
+static const char TAG_DIGITALZOOMRATIO[] = "DigitalZoomRatio";
+static const char TAG_EXPOSURETIME[] = "ExposureTime";
+static const char TAG_APERTURE[] = "ApertureValue";
+static const char TAG_ISO_EQUIVALENT[] = "ISOSpeedRatings";
+static const char TAG_WHITEBALANCE[] = "WhiteBalance";
+static const char TAG_LIGHT_SOURCE[] = "LightSource";
+static const char TAG_METERING_MODE[] = "MeteringMode";
+static const char TAG_EXPOSURE_PROGRAM[] = "ExposureProgram";
+static const char TAG_COLOR_SPACE[] = "ColorSpace";
+static const char TAG_CPRS_BITS_PER_PIXEL[] = "CompressedBitsPerPixel";
+static const char TAG_FNUMBER[] = "FNumber";
+static const char TAG_SHUTTERSPEED[] = "ShutterSpeedValue";
+static const char TAG_SENSING_METHOD[] = "SensingMethod";
+static const char TAG_CUSTOM_RENDERED[] = "CustomRendered";
 
 class ExifElementsTable {
     public:
         ExifElementsTable() :
            gps_tag_count(0), exif_tag_count(0), position(0),
-           jpeg_opened(false) { }
+           jpeg_opened(false), has_datetime_tag(false) { }
         ~ExifElementsTable();
 
         status_t insertElement(const char* tag, const char* value);
@@ -82,6 +102,7 @@
         unsigned int exif_tag_count;
         unsigned int position;
         bool jpeg_opened;
+        bool has_datetime_tag;
 };
 
 class Encoder_libjpeg : public Thread {
@@ -115,6 +136,7 @@
               mCancelEncoding(false), mCookie1(cookie1), mCookie2(cookie2), mCookie3(cookie3),
               mType(type), mThumb(NULL) {
             this->incStrong(this);
+            mCancelSem.Create(0);
         }
 
         ~Encoder_libjpeg() {
@@ -133,6 +155,9 @@
             // encode our main image
             size = encode(mMainInput);
 
+            // signal cancel semaphore incase somebody is waiting
+            mCancelSem.Signal();
+
             // check if it is main jpeg thread
             if(mThumb.get()) {
                 // wait until tn jpeg thread exits.
@@ -142,7 +167,7 @@
             }
 
             if(mCb) {
-                mCb(mMainInput, mThumbnailInput, mType, mCookie1, mCookie2, mCookie3);
+                mCb(mMainInput, mThumbnailInput, mType, mCookie1, mCookie2, mCookie3, mCancelEncoding);
             }
 
             // encoder thread runs, self-destructs, and then exits
@@ -151,10 +176,17 @@
         }
 
         void cancel() {
+           mCancelEncoding = true;
            if (mThumb.get()) {
                mThumb->cancel();
+               mCancelSem.WaitTimeout(CANCEL_TIMEOUT);
            }
-           mCancelEncoding = true;
+        }
+
+        void getCookies(void **cookie1, void **cookie2, void **cookie3) {
+            if (cookie1) *cookie1 = mCookie1;
+            if (cookie2) *cookie2 = mCookie2;
+            if (cookie3) *cookie3 = mCookie3;
         }
 
     private:
@@ -167,6 +199,7 @@
         void* mCookie3;
         CameraFrame::FrameType mType;
         sp<Encoder_libjpeg> mThumb;
+        Semaphore mCancelSem;
 
         size_t encode(params*);
 };
diff --git a/camera/inc/OMXCameraAdapter/OMXCameraAdapter.h b/camera/inc/OMXCameraAdapter/OMXCameraAdapter.h
index 463032a..0fdc770 100644
--- a/camera/inc/OMXCameraAdapter/OMXCameraAdapter.h
+++ b/camera/inc/OMXCameraAdapter/OMXCameraAdapter.h
@@ -446,7 +446,8 @@
                                BaseCameraAdapter::AdapterState state);
     status_t convertGPSCoord(double coord, int &deg, int &min, int &sec, int &secDivisor);
     status_t setupEXIF();
-    status_t setupEXIF_libjpeg(ExifElementsTable*);
+    status_t setupEXIF_libjpeg(ExifElementsTable*, OMX_TI_ANCILLARYDATATYPE*,
+                               OMX_TI_WHITEBALANCERESULTTYPE*);
 
     //Focus functionality
     status_t doAutoFocus();
@@ -454,6 +455,7 @@
     status_t checkFocus(OMX_PARAM_FOCUSSTATUSTYPE *eFocusStatus);
     status_t returnFocusStatus(bool timeoutReached);
     status_t getFocusMode(OMX_IMAGE_CONFIG_FOCUSCONTROLTYPE &focusMode);
+    void handleFocusCallback();
 
 
     //Focus distances
@@ -634,12 +636,13 @@
     status_t sendCallBacks(CameraFrame frame, OMX_IN OMX_BUFFERHEADERTYPE *pBuffHeader, unsigned int mask, OMXCameraPortParameters *port);
 
     status_t apply3Asettings( Gen3A_settings& Gen3A );
-    status_t apply3ADefaults(Gen3A_settings &Gen3A);
+    status_t init3AParams(Gen3A_settings &Gen3A);
 
     // AutoConvergence
     status_t setAutoConvergence(OMX_TI_AUTOCONVERGENCEMODETYPE pACMode, OMX_S32 pManualConverence);
     status_t getAutoConvergence(OMX_TI_AUTOCONVERGENCEMODETYPE *pACMode, OMX_S32 *pManualConverence);
 
+    status_t setExtraData(bool enable, OMX_U32, OMX_EXT_EXTRADATATYPE);
     OMX_OTHER_EXTRADATATYPE *getExtradata(OMX_OTHER_EXTRADATATYPE *extraData, OMX_EXTRADATATYPE type);
 
     class CommandHandler : public Thread {
@@ -668,7 +671,7 @@
                 COMMAND_EXIT = -1,
                 CAMERA_START_IMAGE_CAPTURE = 0,
                 CAMERA_PERFORM_AUTOFOCUS = 1,
-                CAMERA_SWITCH_TO_EXECUTING
+                CAMERA_SWITCH_TO_EXECUTING,
             };
 
         private:
@@ -706,6 +709,7 @@
         enum {
             COMMAND_EXIT = -1,
             CAMERA_FILL_BUFFER_DONE,
+            CAMERA_FOCUS_STATUS,
         };
 
     private:
@@ -817,6 +821,7 @@
     //Face detection status
     bool mFaceDetectionRunning;
     bool mFaceDetectionPaused;
+    bool mFDSwitchAlgoPriority;
 
     camera_face_t  faceDetectionLastOutput [MAX_NUM_FACES_SUPPORTED];
     int faceDetectionNumFacesLastOutput;
@@ -873,6 +878,8 @@
     int mSnapshotCount;
     bool mCaptureConfigured;
     unsigned int mPendingCaptureSettings;
+    OMX_TI_ANCILLARYDATATYPE* mCaptureAncillaryData;
+    OMX_TI_WHITEBALANCERESULTTYPE* mWhiteBalanceData;
 
     //Temporal bracketing management data
     mutable Mutex mBracketingLock;
@@ -883,11 +890,11 @@
     int mBracketingRange;
 
     CameraParameters mParameters;
+    bool mOmxInitialized;
     OMXCameraAdapterComponentContext mCameraAdapterParameters;
     bool mFirstTimeInit;
 
     ///Semaphores used internally
-    Semaphore mDoAFSem;
     Semaphore mInitSem;
     Semaphore mFlushSem;
     Semaphore mUsePreviewDataSem;
@@ -926,6 +933,9 @@
     Mutex mFrameCountMutex;
     Condition mFirstFrameCondition;
 
+    Mutex mDoAFMutex;
+    Condition mDoAFCond;
+
     size_t mSensorIndex;
     CodingMode mCodingMode;
 
diff --git a/camera/inc/TICameraParameters.h b/camera/inc/TICameraParameters.h
index 633e5b6..4701cae 100644
--- a/camera/inc/TICameraParameters.h
+++ b/camera/inc/TICameraParameters.h
@@ -1,242 +1,242 @@
-/*

- * Copyright (C) Texas Instruments - http://www.ti.com/

- *

- * 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 TI_CAMERA_PARAMETERS_H

-#define TI_CAMERA_PARAMETERS_H

-

-#include <utils/KeyedVector.h>

-#include <utils/String8.h>

-

-namespace android {

-

-///TI Specific Camera Parameters

-class TICameraParameters

-{

-public:

-

-// Supported Camera indexes

-// Example value: "0,1,2,3", where 0-primary, 1-secondary1, 2-secondary2, 3-sterocamera

-static const  char KEY_SUPPORTED_CAMERAS[];

-// Select logical Camera index

-static const char KEY_CAMERA[];

-static const char KEY_CAMERA_NAME[];

-static const  char KEY_S3D_SUPPORTED[];

-static const char  KEY_BURST[];

-static const  char KEY_CAP_MODE[];

-static const  char KEY_VNF[];

-static const  char KEY_SATURATION[];

-static const  char KEY_BRIGHTNESS[];

-static const  char KEY_EXPOSURE_MODE[];

-static const  char KEY_SUPPORTED_EXPOSURE[];

-static const  char KEY_CONTRAST[];

-static const  char KEY_SHARPNESS[];

-static const  char KEY_ISO[];

-static const  char KEY_SUPPORTED_ISO_VALUES[];

-static const  char KEY_SUPPORTED_IPP[];

-static const  char KEY_IPP[];

-static const  char KEY_MAN_EXPOSURE[];

-static const  char KEY_METERING_MODE[];

-static const  char KEY_PADDED_WIDTH[];

-static const  char KEY_PADDED_HEIGHT[];

-static const char  KEY_EXP_BRACKETING_RANGE[];

-static const char  KEY_TEMP_BRACKETING[];

-static const char  KEY_TEMP_BRACKETING_RANGE_POS[];

-static const char  KEY_TEMP_BRACKETING_RANGE_NEG[];

-static const char  KEY_SHUTTER_ENABLE[];

-static const char  KEY_MEASUREMENT_ENABLE[];

-static const char  KEY_INITIAL_VALUES[];

-static const char  KEY_GBCE[];

-static const char  KEY_GLBCE[];

-static const char  KEY_MINFRAMERATE[];

-static const char  KEY_MAXFRAMERATE[];

-

-// TI recording hint to notify camera adapters of possible recording

-static const char  KEY_RECORDING_HINT[];

-static const char  KEY_AUTO_FOCUS_LOCK[];

-static const char  KEY_CURRENT_ISO[];

-

-static const char KEY_SENSOR_ORIENTATION[];

-static const char KEY_SENSOR_ORIENTATION_VALUES[];

-

-//TI extensions for zoom

-static const char ZOOM_SUPPORTED[];

-static const char ZOOM_UNSUPPORTED[];

-

-//TI extensions for camera capabilies

-static const char INITIAL_VALUES_TRUE[];

-static const char INITIAL_VALUES_FALSE[];

-

-//TI extensions for enabling/disabling measurements

-static const char MEASUREMENT_ENABLE[];

-static const char MEASUREMENT_DISABLE[];

-

-//  TI extensions to add values for ManualConvergence and AutoConvergence mode

-static const char KEY_AUTOCONVERGENCE[];

-static const char KEY_AUTOCONVERGENCE_MODE[];

-static const char KEY_MANUALCONVERGENCE_VALUES[];

-

-//TI extensions for enabling/disabling GLBCE

-static const char GLBCE_ENABLE[];

-static const char GLBCE_DISABLE[];

-

-//TI extensions for enabling/disabling GBCE

-static const char GBCE_ENABLE[];

-static const char GBCE_DISABLE[];

-

-// TI extensions to add Min frame rate Values

-static const char VIDEO_MINFRAMERATE_5[];

-static const char VIDEO_MINFRAMERATE_10[];

-static const char VIDEO_MINFRAMERATE_15[];

-static const char VIDEO_MINFRAMERATE_20[];

-static const char VIDEO_MINFRAMERATE_24[];

-static const char VIDEO_MINFRAMERATE_25[];

-static const char VIDEO_MINFRAMERATE_30[];

-static const char VIDEO_MINFRAMERATE_33[];

-

-//  TI extensions for Manual Gain and Manual Exposure

-static const char KEY_MANUAL_EXPOSURE_LEFT[];

-static const char KEY_MANUAL_EXPOSURE_RIGHT[];

-static const char KEY_MANUAL_EXPOSURE_MODES[];

-static const char KEY_MANUAL_GAIN_EV_RIGHT[];

-static const char KEY_MANUAL_GAIN_EV_LEFT[];

-static const char KEY_MANUAL_GAIN_ISO_RIGHT[];

-static const char KEY_MANUAL_GAIN_ISO_LEFT[];

-static const char KEY_MANUAL_GAIN_MODES[];

-

-//TI extensions for setting EXIF tags

-static const char KEY_EXIF_MODEL[];

-static const char KEY_EXIF_MAKE[];

-

-//TI extensions for additional GPS data

-static const char  KEY_GPS_MAPDATUM[];

-static const char  KEY_GPS_VERSION[];

-static const char  KEY_GPS_DATESTAMP[];

-

-//TI extensions for enabling/disabling shutter sound

-static const char SHUTTER_ENABLE[];

-static const char SHUTTER_DISABLE[];

-

-//TI extensions for Temporal bracketing

-static const char BRACKET_ENABLE[];

-static const char BRACKET_DISABLE[];

-

-//TI extensions to Image post-processing

-static const char IPP_LDCNSF[];

-static const char IPP_LDC[];

-static const char IPP_NSF[];

-static const char IPP_NONE[];

-

-//TI extensions to camera mode

-static const char HIGH_PERFORMANCE_MODE[];

-static const char HIGH_QUALITY_MODE[];

-static const char HIGH_QUALITY_ZSL_MODE[];

-static const char VIDEO_MODE[];

-

-

-// TI extensions to standard android pixel formats

-static const char PIXEL_FORMAT_RAW[];

-static const char PIXEL_FORMAT_JPS[];

-static const char PIXEL_FORMAT_MPO[];

-static const char PIXEL_FORMAT_RAW_JPEG[];

-static const char PIXEL_FORMAT_RAW_MPO[];

-

-// TI extensions to standard android scene mode settings

-static const  char SCENE_MODE_SPORT[];

-static const  char SCENE_MODE_CLOSEUP[];

-static const  char SCENE_MODE_AQUA[];

-static const  char SCENE_MODE_SNOWBEACH[];

-static const  char SCENE_MODE_MOOD[];

-static const  char SCENE_MODE_NIGHT_INDOOR[];

-static const  char SCENE_MODE_DOCUMENT[];

-static const  char SCENE_MODE_BARCODE[];

-static const  char SCENE_MODE_VIDEO_SUPER_NIGHT[];

-static const  char SCENE_MODE_VIDEO_CINE[];

-static const  char SCENE_MODE_VIDEO_OLD_FILM[];

-

-// TI extensions to standard android white balance settings.

-static const  char WHITE_BALANCE_TUNGSTEN[];

-static const  char WHITE_BALANCE_HORIZON[];

-static const  char WHITE_BALANCE_SUNSET[];

-static const  char WHITE_BALANCE_FACE[];

-

-// TI extensions to add exposure preset modes to android api

-static const  char EXPOSURE_MODE_OFF[];

-static const  char EXPOSURE_MODE_AUTO[];

-static const  char EXPOSURE_MODE_NIGHT[];

-static const  char EXPOSURE_MODE_BACKLIGHT[];

-static const  char EXPOSURE_MODE_SPOTLIGHT[];

-static const  char EXPOSURE_MODE_SPORTS[];

-static const  char EXPOSURE_MODE_SNOW[];

-static const  char EXPOSURE_MODE_BEACH[];

-static const  char EXPOSURE_MODE_APERTURE[];

-static const  char EXPOSURE_MODE_SMALL_APERTURE[];

-static const  char EXPOSURE_MODE_FACE[];

-

-// TI extensions to standard android focus presets.

-static const  char FOCUS_MODE_PORTRAIT[];

-static const  char FOCUS_MODE_EXTENDED[];

-static const char  FOCUS_MODE_FACE[];

-

-// TI extensions to add iso values

-static const char ISO_MODE_AUTO[];

-static const char ISO_MODE_100[];

-static const char ISO_MODE_200[];

-static const char ISO_MODE_400[];

-static const char ISO_MODE_800[];

-static const char ISO_MODE_1000[];

-static const char ISO_MODE_1200[];

-static const char ISO_MODE_1600[];

-

-//  TI extensions to add  values for effect settings.

-static const char EFFECT_NATURAL[];

-static const char EFFECT_VIVID[];

-static const char EFFECT_COLOR_SWAP[];

-static const char EFFECT_BLACKWHITE[];

-

-static const char KEY_S3D2D_PREVIEW[];

-static const char KEY_S3D2D_PREVIEW_MODE[];

-

-//  TI extensions to add values for AutoConvergence settings.

-static const char AUTOCONVERGENCE_MODE_DISABLE[];

-static const char AUTOCONVERGENCE_MODE_FRAME[];

-static const char AUTOCONVERGENCE_MODE_CENTER[];

-static const char AUTOCONVERGENCE_MODE_FFT[];

-static const char AUTOCONVERGENCE_MODE_MANUAL[];

-

-

-//TI extensions for flash mode settings

-static const char FLASH_MODE_FILL_IN[];

-

-//TI extensions to add sensor orientation parameters

-static const char ORIENTATION_SENSOR_NONE[];

-static const char ORIENTATION_SENSOR_90[];

-static const char ORIENTATION_SENSOR_180[];

-static const char ORIENTATION_SENSOR_270[];

-

-

-//TI values for camera direction

-static const char FACING_FRONT[];

-static const char FACING_BACK[];

-

-};

-

-};

-

-#endif

-

+/*
+ * Copyright (C) Texas Instruments - http://www.ti.com/
+ *
+ * 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 TI_CAMERA_PARAMETERS_H
+#define TI_CAMERA_PARAMETERS_H
+
+#include <utils/KeyedVector.h>
+#include <utils/String8.h>
+
+namespace android {
+
+///TI Specific Camera Parameters
+class TICameraParameters
+{
+public:
+
+// Supported Camera indexes
+// Example value: "0,1,2,3", where 0-primary, 1-secondary1, 2-secondary2, 3-sterocamera
+static const  char KEY_SUPPORTED_CAMERAS[];
+// Select logical Camera index
+static const char KEY_CAMERA[];
+static const char KEY_CAMERA_NAME[];
+static const  char KEY_S3D_SUPPORTED[];
+static const char  KEY_BURST[];
+static const  char KEY_CAP_MODE[];
+static const  char KEY_VNF[];
+static const  char KEY_SATURATION[];
+static const  char KEY_BRIGHTNESS[];
+static const  char KEY_EXPOSURE_MODE[];
+static const  char KEY_SUPPORTED_EXPOSURE[];
+static const  char KEY_CONTRAST[];
+static const  char KEY_SHARPNESS[];
+static const  char KEY_ISO[];
+static const  char KEY_SUPPORTED_ISO_VALUES[];
+static const  char KEY_SUPPORTED_IPP[];
+static const  char KEY_IPP[];
+static const  char KEY_MAN_EXPOSURE[];
+static const  char KEY_METERING_MODE[];
+static const  char KEY_PADDED_WIDTH[];
+static const  char KEY_PADDED_HEIGHT[];
+static const char  KEY_EXP_BRACKETING_RANGE[];
+static const char  KEY_TEMP_BRACKETING[];
+static const char  KEY_TEMP_BRACKETING_RANGE_POS[];
+static const char  KEY_TEMP_BRACKETING_RANGE_NEG[];
+static const char  KEY_SHUTTER_ENABLE[];
+static const char  KEY_MEASUREMENT_ENABLE[];
+static const char  KEY_INITIAL_VALUES[];
+static const char  KEY_GBCE[];
+static const char  KEY_GLBCE[];
+static const char  KEY_MINFRAMERATE[];
+static const char  KEY_MAXFRAMERATE[];
+
+// TI recording hint to notify camera adapters of possible recording
+static const char  KEY_RECORDING_HINT[];
+static const char  KEY_AUTO_FOCUS_LOCK[];
+static const char  KEY_CURRENT_ISO[];
+
+static const char KEY_SENSOR_ORIENTATION[];
+static const char KEY_SENSOR_ORIENTATION_VALUES[];
+
+//TI extensions for zoom
+static const char ZOOM_SUPPORTED[];
+static const char ZOOM_UNSUPPORTED[];
+
+//TI extensions for camera capabilies
+static const char INITIAL_VALUES_TRUE[];
+static const char INITIAL_VALUES_FALSE[];
+
+//TI extensions for enabling/disabling measurements
+static const char MEASUREMENT_ENABLE[];
+static const char MEASUREMENT_DISABLE[];
+
+//  TI extensions to add values for ManualConvergence and AutoConvergence mode
+static const char KEY_AUTOCONVERGENCE[];
+static const char KEY_AUTOCONVERGENCE_MODE[];
+static const char KEY_MANUALCONVERGENCE_VALUES[];
+
+//TI extensions for enabling/disabling GLBCE
+static const char GLBCE_ENABLE[];
+static const char GLBCE_DISABLE[];
+
+//TI extensions for enabling/disabling GBCE
+static const char GBCE_ENABLE[];
+static const char GBCE_DISABLE[];
+
+// TI extensions to add Min frame rate Values
+static const char VIDEO_MINFRAMERATE_5[];
+static const char VIDEO_MINFRAMERATE_10[];
+static const char VIDEO_MINFRAMERATE_15[];
+static const char VIDEO_MINFRAMERATE_20[];
+static const char VIDEO_MINFRAMERATE_24[];
+static const char VIDEO_MINFRAMERATE_25[];
+static const char VIDEO_MINFRAMERATE_30[];
+static const char VIDEO_MINFRAMERATE_33[];
+
+//  TI extensions for Manual Gain and Manual Exposure
+static const char KEY_MANUAL_EXPOSURE_LEFT[];
+static const char KEY_MANUAL_EXPOSURE_RIGHT[];
+static const char KEY_MANUAL_EXPOSURE_MODES[];
+static const char KEY_MANUAL_GAIN_EV_RIGHT[];
+static const char KEY_MANUAL_GAIN_EV_LEFT[];
+static const char KEY_MANUAL_GAIN_ISO_RIGHT[];
+static const char KEY_MANUAL_GAIN_ISO_LEFT[];
+static const char KEY_MANUAL_GAIN_MODES[];
+
+//TI extensions for setting EXIF tags
+static const char KEY_EXIF_MODEL[];
+static const char KEY_EXIF_MAKE[];
+
+//TI extensions for additional GPS data
+static const char  KEY_GPS_MAPDATUM[];
+static const char  KEY_GPS_VERSION[];
+static const char  KEY_GPS_DATESTAMP[];
+
+//TI extensions for enabling/disabling shutter sound
+static const char SHUTTER_ENABLE[];
+static const char SHUTTER_DISABLE[];
+
+//TI extensions for Temporal bracketing
+static const char BRACKET_ENABLE[];
+static const char BRACKET_DISABLE[];
+
+//TI extensions to Image post-processing
+static const char IPP_LDCNSF[];
+static const char IPP_LDC[];
+static const char IPP_NSF[];
+static const char IPP_NONE[];
+
+//TI extensions to camera mode
+static const char HIGH_PERFORMANCE_MODE[];
+static const char HIGH_QUALITY_MODE[];
+static const char HIGH_QUALITY_ZSL_MODE[];
+static const char VIDEO_MODE[];
+
+
+// TI extensions to standard android pixel formats
+static const char PIXEL_FORMAT_RAW[];
+static const char PIXEL_FORMAT_JPS[];
+static const char PIXEL_FORMAT_MPO[];
+static const char PIXEL_FORMAT_RAW_JPEG[];
+static const char PIXEL_FORMAT_RAW_MPO[];
+
+// TI extensions to standard android scene mode settings
+static const  char SCENE_MODE_SPORT[];
+static const  char SCENE_MODE_CLOSEUP[];
+static const  char SCENE_MODE_AQUA[];
+static const  char SCENE_MODE_SNOWBEACH[];
+static const  char SCENE_MODE_MOOD[];
+static const  char SCENE_MODE_NIGHT_INDOOR[];
+static const  char SCENE_MODE_DOCUMENT[];
+static const  char SCENE_MODE_BARCODE[];
+static const  char SCENE_MODE_VIDEO_SUPER_NIGHT[];
+static const  char SCENE_MODE_VIDEO_CINE[];
+static const  char SCENE_MODE_VIDEO_OLD_FILM[];
+
+// TI extensions to standard android white balance settings.
+static const  char WHITE_BALANCE_TUNGSTEN[];
+static const  char WHITE_BALANCE_HORIZON[];
+static const  char WHITE_BALANCE_SUNSET[];
+static const  char WHITE_BALANCE_FACE[];
+
+// TI extensions to add exposure preset modes to android api
+static const  char EXPOSURE_MODE_OFF[];
+static const  char EXPOSURE_MODE_AUTO[];
+static const  char EXPOSURE_MODE_NIGHT[];
+static const  char EXPOSURE_MODE_BACKLIGHT[];
+static const  char EXPOSURE_MODE_SPOTLIGHT[];
+static const  char EXPOSURE_MODE_SPORTS[];
+static const  char EXPOSURE_MODE_SNOW[];
+static const  char EXPOSURE_MODE_BEACH[];
+static const  char EXPOSURE_MODE_APERTURE[];
+static const  char EXPOSURE_MODE_SMALL_APERTURE[];
+static const  char EXPOSURE_MODE_FACE[];
+
+// TI extensions to standard android focus presets.
+static const  char FOCUS_MODE_PORTRAIT[];
+static const  char FOCUS_MODE_EXTENDED[];
+static const char  FOCUS_MODE_FACE[];
+
+// TI extensions to add iso values
+static const char ISO_MODE_AUTO[];
+static const char ISO_MODE_100[];
+static const char ISO_MODE_200[];
+static const char ISO_MODE_400[];
+static const char ISO_MODE_800[];
+static const char ISO_MODE_1000[];
+static const char ISO_MODE_1200[];
+static const char ISO_MODE_1600[];
+
+//  TI extensions to add  values for effect settings.
+static const char EFFECT_NATURAL[];
+static const char EFFECT_VIVID[];
+static const char EFFECT_COLOR_SWAP[];
+static const char EFFECT_BLACKWHITE[];
+
+static const char KEY_S3D2D_PREVIEW[];
+static const char KEY_S3D2D_PREVIEW_MODE[];
+
+//  TI extensions to add values for AutoConvergence settings.
+static const char AUTOCONVERGENCE_MODE_DISABLE[];
+static const char AUTOCONVERGENCE_MODE_FRAME[];
+static const char AUTOCONVERGENCE_MODE_CENTER[];
+static const char AUTOCONVERGENCE_MODE_FFT[];
+static const char AUTOCONVERGENCE_MODE_MANUAL[];
+
+
+//TI extensions for flash mode settings
+static const char FLASH_MODE_FILL_IN[];
+
+//TI extensions to add sensor orientation parameters
+static const char ORIENTATION_SENSOR_NONE[];
+static const char ORIENTATION_SENSOR_90[];
+static const char ORIENTATION_SENSOR_180[];
+static const char ORIENTATION_SENSOR_270[];
+
+
+//TI values for camera direction
+static const char FACING_FRONT[];
+static const char FACING_BACK[];
+
+};
+
+};
+
+#endif
+
diff --git a/domx/domx/omx_proxy_common/src/omx_proxy_common.c b/domx/domx/omx_proxy_common/src/omx_proxy_common.c
index 3014bf1..60507c6 100644
--- a/domx/domx/omx_proxy_common/src/omx_proxy_common.c
+++ b/domx/domx/omx_proxy_common/src/omx_proxy_common.c
@@ -75,7 +75,7 @@
 
 #ifdef USE_ION
 #include <unistd.h>
-#include <ion.h>
+#include <ion/ion.h>
 #include <sys/ioctl.h>
 #include <sys/mman.h>
 #include <sys/eventfd.h>
diff --git a/domx/mm_osal/src/timm_osal_trace.c b/domx/mm_osal/src/timm_osal_trace.c
index 874deb7..e9aae1b 100755
--- a/domx/mm_osal/src/timm_osal_trace.c
+++ b/domx/mm_osal/src/timm_osal_trace.c
@@ -109,12 +109,12 @@
 #ifdef _Android
 
 #if ( TIMM_OSAL_DEBUG_TRACE_DETAIL > 1 )
-		LOGD("%s:%d\t%s()\t", simplify_path(loc->file), loc->line,
+		ALOGD("%s:%d\t%s()\t", simplify_path(loc->file), loc->line,
 		    loc->function);
 #endif
 		char string[1000];
 		vsprintf(string, fmt, ap);
-		LOGD("%s",string);
+		ALOGD("%s",string);
 
 #else
 
diff --git a/domx/omx_core/src/OMX_Core_Wrapper.c b/domx/omx_core/src/OMX_Core_Wrapper.c
index d049ee0..8d61dd4 100755
--- a/domx/omx_core/src/OMX_Core_Wrapper.c
+++ b/domx/omx_core/src/OMX_Core_Wrapper.c
@@ -58,12 +58,12 @@
 OMX_BOOL TIOMXConfigParserRedirect(OMX_PTR aInputParameters,
     OMX_PTR aOutputParameters)
 {
-	LOGV("OMXConfigParserRedirect +\n");
+	ALOGV("OMXConfigParserRedirect +\n");
 	OMX_BOOL Status = OMX_FALSE;
 
 	Status = TIOMXConfigParser(aInputParameters, aOutputParameters);
 
-	LOGV("OMXConfigParserRedirect -\n");
+	ALOGV("OMXConfigParserRedirect -\n");
 	return Status;
 }
 #endif
@@ -92,14 +92,14 @@
 
 OMX_API OMX_ERRORTYPE TIOMX_Init(void)
 {
-	LOGV("TIOMX_Init\n");
+	ALOGV("TIOMX_Init\n");
 
 	return OMX_Init();
 }
 
 OMX_API OMX_ERRORTYPE TIOMX_Deinit(void)
 {
-	LOGV("TIOMX_Deinit\n");
+	ALOGV("TIOMX_Deinit\n");
 
 	return OMX_Deinit();
 }
@@ -108,7 +108,7 @@
     cComponentName, OMX_IN OMX_U32 nNameLength, OMX_IN OMX_U32 nIndex)
 {
 
-	LOGV("TIOMX_ComponentNameEnum\n");
+	ALOGV("TIOMX_ComponentNameEnum\n");
 
 	return OMX_ComponentNameEnum(cComponentName, nNameLength, nIndex);
 }
@@ -118,14 +118,14 @@
     OMX_IN OMX_PTR pAppData, OMX_IN OMX_CALLBACKTYPE * pCallBacks)
 {
 
-	LOGV("TIOMX_GetHandle\n");
+	ALOGV("TIOMX_GetHandle\n");
 
 	return OMX_GetHandle(pHandle, cComponentName, pAppData, pCallBacks);
 }
 
 OMX_API OMX_ERRORTYPE TIOMX_FreeHandle(OMX_IN OMX_HANDLETYPE hComponent)
 {
-	LOGV("TIOMX_FreeHandle\n");
+	ALOGV("TIOMX_FreeHandle\n");
 
 	return OMX_FreeHandle(hComponent);
 }
@@ -134,7 +134,7 @@
     OMX_INOUT OMX_U32 * pNumComps, OMX_INOUT OMX_U8 ** compNames)
 {
 
-	LOGV("TIOMX_GetComponentsOfRole\n");
+	ALOGV("TIOMX_GetComponentsOfRole\n");
 
 	return OMX_GetComponentsOfRole(role, pNumComps, compNames);
 }
@@ -143,7 +143,7 @@
     OMX_INOUT OMX_U32 * pNumRoles, OMX_OUT OMX_U8 ** roles)
 {
 
-	LOGV("TIOMX_GetRolesOfComponent\n");
+	ALOGV("TIOMX_GetRolesOfComponent\n");
 
 	return OMX_GetRolesOfComponent(compName, pNumRoles, roles);
 }
@@ -153,7 +153,7 @@
     OMX_IN OMX_HANDLETYPE hInput, OMX_IN OMX_U32 nPortInput)
 {
 
-	LOGV("TIOMX_SetupTunnel\n");
+	ALOGV("TIOMX_SetupTunnel\n");
 
 	return OMX_SetupTunnel(hOutput, nPortOutput, hInput, nPortInput);
 }
@@ -162,7 +162,7 @@
     OMX_IN OMX_STRING szURI)
 {
 
-	LOGV("TIOMX_GetContentPipe\n");
+	ALOGV("TIOMX_GetContentPipe\n");
 
 	//return OMX_GetContentPipe(
 	//      hPipe,
diff --git a/domx/omx_proxy_component/Android.mk b/domx/omx_proxy_component/Android.mk
index 4ebd727..58eb424 100644
--- a/domx/omx_proxy_component/Android.mk
+++ b/domx/omx_proxy_component/Android.mk
@@ -70,7 +70,6 @@
 	$(LOCAL_PATH)/../omx_core/inc \
 	$(LOCAL_PATH)/../mm_osal/inc \
 	$(LOCAL_PATH)/../domx \
-	$(HARDWARE_TI_OMAP4_BASE)/ion/ \
 	$(LOCAL_PATH)/../domx/omx_rpc/inc
 
 LOCAL_SHARED_LIBRARIES := \
@@ -105,6 +104,7 @@
 	$(LOCAL_PATH)/../../hwc \
 	$(HARDWARE_TI_OMAP4_BASE)/camera/inc \
 	frameworks/base/include/media/stagefright \
+	frameworks/native/include/media/hardware
 
 LOCAL_SHARED_LIBRARIES := \
 	libmm_osal \
@@ -140,6 +140,7 @@
 	$(LOCAL_PATH)/../../hwc \
 	$(HARDWARE_TI_OMAP4_BASE)/camera/inc \
 	frameworks/base/include/media/stagefright \
+	frameworks/native/include/media/hardware
 
 LOCAL_SHARED_LIBRARIES := \
 	libmm_osal \
diff --git a/domx/omx_proxy_component/omx_camera/src/omx_proxy_camera.c b/domx/omx_proxy_component/omx_camera/src/omx_proxy_camera.c
index 729c190..50ac002 100755
--- a/domx/omx_proxy_component/omx_camera/src/omx_proxy_camera.c
+++ b/domx/omx_proxy_component/omx_camera/src/omx_proxy_camera.c
@@ -74,7 +74,7 @@
 
 #ifdef USE_ION
 #include <unistd.h>
-#include <ion.h>
+#include <ion/ion.h>
 #include <sys/ioctl.h>
 #include <sys/mman.h>
 #include <sys/eventfd.h>
diff --git a/hwc/hwc.c b/hwc/hwc.c
index e97208b..b5b80ec 100644
--- a/hwc/hwc.c
+++ b/hwc/hwc.c
@@ -22,7 +22,9 @@
 #include <poll.h>
 #include <sys/ioctl.h>
 #include <linux/fb.h>
+#include <linux/omapfb.h>
 #include <sys/mman.h>
+#include <sys/resource.h>
 
 #include <cutils/properties.h>
 #include <cutils/log.h>
@@ -30,15 +32,12 @@
 #include <hardware/hardware.h>
 #include <hardware/hwcomposer.h>
 #include <EGL/egl.h>
-#include <utils/Timers.h>
 #include <hardware_legacy/uevent.h>
 #include <png.h>
 
-#define ASPECT_RATIO_TOLERANCE 0.02f
+#include <system/graphics.h>
 
-#ifndef FBIO_WAITFORVSYNC
-#define FBIO_WAITFORVSYNC       _IOW('F', 0x20, __u32)
-#endif
+#define ASPECT_RATIO_TOLERANCE 0.02f
 
 #define min(a, b) ( { typeof(a) __a = (a), __b = (b); __a < __b ? __a : __b; } )
 #define max(a, b) ( { typeof(a) __a = (a), __b = (b); __a > __b ? __a : __b; } )
@@ -137,17 +136,11 @@
     int flags_rgb_order;
     int flags_nv12_only;
 
-    int on_tv;
     int force_sgx;
     omap4_hwc_ext_t ext;        /* external mirroring data */
     int idle;
     int ovls_blending;
 
-    float lcd_m[2][3];          /* internal transformation matrix */
-    float lcd_hdmi_m[2][3];          /* internal transformation matrix */
-    int lcd_rotation;
-    hwc_rect_t lcd_region;
-
     /* composition data */
     struct dsscomp_setup_dispc_data dsscomp_data;
     buffer_handle_t *buffers;
@@ -158,7 +151,6 @@
     int ext_ovls_wanted;        /* # of overlays that should be on external display for current composition */
     int last_ext_ovls;          /* # of overlays on external/internal display for last composition */
     int last_int_ovls;
-    int lcd_transform;
 };
 typedef struct omap4_hwc_device omap4_hwc_device_t;
 
@@ -179,7 +171,7 @@
 
 static void dump_layer(hwc_layer_t const* l)
 {
-    LOGD("\ttype=%d, flags=%08x, handle=%p, tr=%02x, blend=%04x, {%d,%d,%d,%d}, {%d,%d,%d,%d}",
+    ALOGD("\ttype=%d, flags=%08x, handle=%p, tr=%02x, blend=%04x, {%d,%d,%d,%d}, {%d,%d,%d,%d}",
          l->compositionType, l->flags, l->handle, l->transform, l->blending,
          l->sourceCrop.left,
          l->sourceCrop.top,
@@ -195,7 +187,7 @@
 {
     unsigned i;
 
-    LOGD("[%08x] set: %c%c%c %d ovls\n",
+    ALOGD("[%08x] set: %c%c%c %d ovls\n",
          d->sync_id,
          (d->mode & DSSCOMP_SETUP_MODE_APPLY) ? 'A' : '-',
          (d->mode & DSSCOMP_SETUP_MODE_DISPLAY) ? 'D' : '-',
@@ -204,7 +196,7 @@
 
     for (i = 0; i < d->num_mgrs; i++) {
         struct dss2_mgr_info *mi = &d->mgrs[i];
-        LOGD(" (dis%d alpha=%d col=%08x ilace=%d)\n",
+        ALOGD(" (dis%d alpha=%d col=%08x ilace=%d)\n",
              mi->ix,
              mi->alpha_blending, mi->default_color,
              mi->interlaced);
@@ -214,10 +206,10 @@
         struct dss2_ovl_info *oi = &d->ovls[i];
         struct dss2_ovl_cfg *c = &oi->cfg;
         if (c->zonly)
-            LOGD("ovl%d(%s z%d)\n",
+            ALOGD("ovl%d(%s z%d)\n",
                  c->ix, c->enabled ? "ON" : "off", c->zorder);
         else
-            LOGD("ovl%d(%s z%d %s%s *%d%% %d*%d:%d,%d+%d,%d rot%d%s => %d,%d+%d,%d %p/%p|%d)\n",
+            ALOGD("ovl%d(%s z%d %s%s *%d%% %d*%d:%d,%d+%d,%d rot%d%s => %d,%d+%d,%d %p/%p|%d)\n",
                  c->ix, c->enabled ? "ON" : "off", c->zorder, DSS_FMT(c->color_mode),
                  c->pre_mult_alpha ? " premult" : "",
                  (c->global_alpha * 100 + 128) / 255,
@@ -293,7 +285,7 @@
     }
     dump_printf(&log, "}%s\n", hwc_dev->use_sgx ? " swap" : "");
 
-    LOGD("%s", log.buf);
+    ALOGD("%s", log.buf);
 }
 
 static int sync_id = 0;
@@ -315,7 +307,7 @@
     }
 }
 
-static int scaled(hwc_layer_t *layer,omap4_hwc_device_t *hwc_dev)
+static int scaled(hwc_layer_t *layer)
 {
     int w = WIDTH(layer->sourceCrop);
     int h = HEIGHT(layer->sourceCrop);
@@ -323,7 +315,7 @@
     if (layer->transform & HWC_TRANSFORM_ROT_90)
         swap(w, h);
 
-    return (hwc_dev->fb_dis.timings.x_res != w || hwc_dev->fb_dis.timings.y_res != h);
+    return WIDTH(layer->displayFrame) != w || HEIGHT(layer->displayFrame) != h;
 }
 
 static int is_protected(hwc_layer_t *layer)
@@ -335,18 +327,6 @@
 
 #define is_BLENDED(layer) ((layer)->blending != HWC_BLENDING_NONE)
 
-static int is_RGB32(IMG_native_handle_t *handle)
-{
-    switch(handle->iFormat)
-    {
-    case HAL_PIXEL_FORMAT_BGRA_8888:
-    case HAL_PIXEL_FORMAT_BGRX_8888:
-        return 1;
-    default:
-        return 0;
-    }
-}
-
 static int is_RGB(IMG_native_handle_t *handle)
 {
     switch(handle->iFormat)
@@ -444,7 +424,7 @@
 
     default:
         /* Should have been filtered out */
-        LOGV("Unsupported pixel format");
+        ALOGV("Unsupported pixel format");
         return;
     }
 
@@ -707,56 +687,6 @@
         oc->mirror = !oc->mirror;
 }
 
-static void
-omap4_hwc_adjust_lcd_layer(omap4_hwc_device_t *hwc_dev, struct dss2_ovl_info *ovl)
-{
-    struct dss2_ovl_cfg *oc = &ovl->cfg;
-    float x, y, w, h;
-
-    /* crop to lcd region if mirroring */
-    if (crop_to_rect(&ovl->cfg, hwc_dev->lcd_region) != 0) {
-        ovl->cfg.enabled = 0;
-        return;
-    }
-
-    /* display position */
-    x = hwc_dev->lcd_m[0][0] * oc->win.x + hwc_dev->lcd_m[0][1] * oc->win.y + hwc_dev->lcd_m[0][2];
-    y = hwc_dev->lcd_m[1][0] * oc->win.x + hwc_dev->lcd_m[1][1] * oc->win.y + hwc_dev->lcd_m[1][2];
-    w = hwc_dev->lcd_m[0][0] * oc->win.w + hwc_dev->lcd_m[0][1] * oc->win.h;
-    h = hwc_dev->lcd_m[1][0] * oc->win.w + hwc_dev->lcd_m[1][1] * oc->win.h;
-    oc->win.x = m_round(w > 0 ? x : x + w);
-    oc->win.y = m_round(h > 0 ? y : y + h);
-    oc->win.w = m_round(w > 0 ? w : -w);
-    oc->win.h = m_round(h > 0 ? h : -h);
-
-    /* combining transformations: F^a*R^b*F^i*R^j = F^(a+b)*R^(j+b*(-1)^i), because F*R = R^(-1)*F */
-    oc->rotation += (oc->mirror ? -1 : 1) * hwc_dev->lcd_rotation;
-    oc->rotation &= 3;
-}
-static void
-omap4_hwc_adjust_lcd_layer_to_hdmi(omap4_hwc_device_t *hwc_dev, struct dss2_ovl_info *ovl)
-{
-    struct dss2_ovl_cfg *oc = &ovl->cfg;
-    float x, y, w, h;
-
-    if (!hwc_dev->ext.current.docking &&
-        crop_to_rect(&ovl->cfg, hwc_dev->ext.mirror_region) != 0) {
-        ovl->cfg.enabled = 0;
-        return;
-    }
-
-    /* display position */
-    x = hwc_dev->lcd_hdmi_m[0][0] * oc->win.x + hwc_dev->lcd_hdmi_m[0][1] * oc->win.y + hwc_dev->lcd_hdmi_m[0][2];
-    y = hwc_dev->lcd_hdmi_m[1][0] * oc->win.x + hwc_dev->lcd_hdmi_m[1][1] * oc->win.y + hwc_dev->lcd_hdmi_m[1][2];
-    w = hwc_dev->lcd_hdmi_m[0][0] * oc->win.w + hwc_dev->lcd_hdmi_m[0][1] * oc->win.h;
-    h = hwc_dev->lcd_hdmi_m[1][0] * oc->win.w + hwc_dev->lcd_hdmi_m[1][1] * oc->win.h;
-    oc->win.x = m_round(w > 0 ? x : x + w);
-    oc->win.y = m_round(h > 0 ? y : y + h);
-    oc->win.w = m_round(w > 0 ? w : -w);
-    oc->win.h = m_round(h > 0 ? h : -h);
-
-}
-
 static struct dsscomp_dispc_limitations {
     __u8 max_xdecim_2d;
     __u8 max_ydecim_2d;
@@ -794,6 +724,10 @@
 
     /* NOTE: no support for checking YUV422 layers that are tricky to scale */
 
+    /* FIXME: limit vertical downscale well below theoretical limit as we saw display artifacts */
+    if (dst_h < src_h / 4)
+        return 0;
+
     /* max downscale */
     if (dst_h < src_h / limits->max_downscale / (is_2d ? limits->max_ydecim_2d : limits->max_ydecim_1d))
         return 0;
@@ -898,12 +832,10 @@
 static int omap4_hwc_set_best_hdmi_mode(omap4_hwc_device_t *hwc_dev, __u32 xres, __u32 yres,
                                         float xpy)
 {
-    int dis_ix = hwc_dev->on_tv ? 0 : 1;
-
     struct _qdis {
         struct dsscomp_display_info dis;
         struct dsscomp_videomode modedb[32];
-    } d = { .dis = { .ix = dis_ix } };
+    } d = { .dis = { .ix = 1 } };
     omap4_hwc_ext_t *ext = &hwc_dev->ext;
 
     d.dis.modedb_len = sizeof(d.modedb) / sizeof(*d.modedb);
@@ -927,21 +859,6 @@
         ext->yres = 480;
     }
 
-    /*
-     * copy the xres/yres from the preferred mode
-     */
-    __u32 preferred_mode_xres = 0;
-    __u32 preferred_mode_yres = 0;
-    for (i = 0; i < d.dis.modedb_len; i++) {
-        if (d.modedb[i].flag & FB_FLAG_PREFERRED) {
-            preferred_mode_xres = d.modedb[i].xres;
-            preferred_mode_yres = d.modedb[i].yres;
-            LOGD("preferred mode %d: xres %u yres %u\n",
-                i, d.modedb[i].xres, d.modedb[i].yres);
-            break;
-        }
-    }
-
     __u32 ext_fb_xres, ext_fb_yres;
     for (i = 0; i < d.dis.modedb_len; i++) {
         __u32 score = 0;
@@ -950,10 +867,6 @@
         __u32 ext_width = d.dis.width_in_mm;
         __u32 ext_height = d.dis.height_in_mm;
 
-        /* reject it because the hw says it can't actually use this mode */
-        if ((d.modedb[i].flag & FB_FLAG_HW_CAPABLE) == 0)
-            continue;
-
         if (d.modedb[i].flag & FB_FLAG_RATIO_4_3) {
             ext_width = 4;
             ext_height = 3;
@@ -978,17 +891,7 @@
 
         /* prefer CEA modes */
         if (d.modedb[i].flag & (FB_FLAG_RATIO_4_3 | FB_FLAG_RATIO_16_9))
-            score += 1;
-
-        /* prefer modes that match the preferred mode's resolution */
-        if (d.modedb[i].xres == preferred_mode_xres &&
-            d.modedb[i].yres == preferred_mode_yres) {
-            score += 1;
-        }
-
-        /* prefer modes the kernel has hinted is the correct mode */
-        if (d.modedb[i].flag & FB_FLAG_PREFERRED)
-            score += 1;
+            score = 1;
 
         /* prefer the same mode as we use for mirroring to avoid mode change */
        score = (score << 1) | (i == ~ext->mirror_mode && ext->avoid_mode_change);
@@ -996,10 +899,9 @@
         score = add_scaling_score(score, xres, yres, 60, ext_fb_xres, ext_fb_yres,
                                   mode_xres, mode_yres, d.modedb[i].refresh ? : 1);
 
-        LOGD("#%d: %dx%d %dHz flag 0x%x vmode 0x%x", i, mode_xres, mode_yres,
-            d.modedb[i].refresh, d.modedb[i].flag, d.modedb[i].vmode);
+        ALOGD("#%d: %dx%d %dHz", i, mode_xres, mode_yres, d.modedb[i].refresh);
         if (debug)
-            LOGD("  score=0x%x adj.res=%dx%d", score, ext_fb_xres, ext_fb_yres);
+            ALOGD("  score=0x%x adj.res=%dx%d", score, ext_fb_xres, ext_fb_yres);
         if (best_score < score) {
             ext->width = ext_width;
             ext->height = ext_height;
@@ -1010,9 +912,9 @@
         }
     }
     if (~best) {
-        struct dsscomp_setup_display_data sdis = { .ix = dis_ix, };
+        struct dsscomp_setup_display_data sdis = { .ix = 1, };
         sdis.mode = d.dis.modedb[best];
-        LOGD("picking #%d", best);
+        ALOGD("picking #%d", best);
         /* only reconfigure on change */
         if (ext->last_mode != ~best)
             ioctl(hwc_dev->dsscomp_fd, DSSCIOC_SETUP_DISPLAY, &sdis);
@@ -1029,7 +931,7 @@
             !omap4_hwc_can_scale(xres, yres, ext_fb_xres, ext_fb_yres,
                                  1, &d.dis, &limits,
                                  d.dis.timings.pixel_clock)) {
-            LOGW("DSS scaler cannot support HDMI cloning");
+            ALOGW("DSS scaler cannot support HDMI cloning");
             return -1;
         }
     }
@@ -1071,7 +973,7 @@
             num->possible_overlay_layers++;
 
             /* NV12 layers can only be rendered on scaling overlays */
-            if (scaled(layer,hwc_dev) || is_NV12(handle))
+            if (scaled(layer) || is_NV12(handle))
                 num->scaled_layers++;
 
             if (is_BGR(handle))
@@ -1145,17 +1047,13 @@
     if (hwc_dev->ext_ovls && ext->current.enabled && !ext->current.docking)
         num->max_hw_overlays = hwc_dev->ext_ovls;
 
-    /*If FB is not same resolution as LCD dont use GFX pipe line*/
-    if (hwc_dev->lcd_transform)
-        num->max_hw_overlays -= 1;
-    else
-        num->max_scaling_overlays = num->max_hw_overlays - nonscaling_ovls;
+    num->max_scaling_overlays = num->max_hw_overlays - nonscaling_ovls;
 }
 
 static int can_dss_render_all(omap4_hwc_device_t *hwc_dev, struct counts *num)
 {
     omap4_hwc_ext_t *ext = &hwc_dev->ext;
-    int on_tv = hwc_dev->on_tv || (ext->on_tv && ext->current.enabled);
+    int on_tv = ext->on_tv && ext->current.enabled;
     int tform = ext->current.enabled && (ext->current.rotation || ext->current.hflip);
 
     return  !hwc_dev->force_sgx &&
@@ -1179,7 +1077,7 @@
     IMG_native_handle_t *handle = (IMG_native_handle_t *)layer->handle;
 
     omap4_hwc_ext_t *ext = &hwc_dev->ext;
-    int on_tv = hwc_dev->on_tv || (ext->on_tv && ext->current.enabled);
+    int on_tv = ext->on_tv && ext->current.enabled;
     int tform = ext->current.enabled && (ext->current.rotation || ext->current.hflip);
 
     return omap4_hwc_is_valid_layer(hwc_dev, layer, handle) &&
@@ -1206,7 +1104,7 @@
     struct dss2_ovl_info *o = &dsscomp->ovls[dsscomp->num_ovls];
 
     if (dsscomp->num_ovls >= MAX_HW_OVERLAYS) {
-        LOGE("**** cannot clone layer #%d. using all %d overlays.", ix, dsscomp->num_ovls);
+        ALOGE("**** cannot clone layer #%d. using all %d overlays.", ix, dsscomp->num_ovls);
         return -EBUSY;
     }
 
@@ -1221,9 +1119,6 @@
     /* use distinct z values (to simplify z-order checking) */
     o->cfg.zorder += hwc_dev->post2_layers;
 
-     if (hwc_dev->lcd_transform)
-         omap4_hwc_adjust_lcd_layer_to_hdmi(hwc_dev,o);
-
     omap4_hwc_adjust_ext_layer(&hwc_dev->ext, o);
     dsscomp->num_ovls++;
     return 0;
@@ -1253,7 +1148,7 @@
         yres != ext->last_yres_used ||
         xpy < ext->last_xpy * (1.f - ASPECT_RATIO_TOLERANCE) ||
         xpy * (1.f - ASPECT_RATIO_TOLERANCE) > ext->last_xpy) {
-        LOGD("set up HDMI for %d*%d\n", xres, yres);
+        ALOGD("set up HDMI for %d*%d\n", xres, yres);
         if (omap4_hwc_set_best_hdmi_mode(hwc_dev, xres, yres, xpy)) {
             ext->current.enabled = 0;
             return -ENODEV;
@@ -1284,16 +1179,6 @@
     return 0;
 }
 
-/* test if layer appears to be RGB32 (4 Bpp) and > 1280x720 */
-static int is_large_rgb32_layer(const hwc_layer_t *layer)
-{
-    IMG_native_handle_t *handle = (IMG_native_handle_t *)layer->handle;
-
-    return is_RGB32(handle) &&
-        (((layer->sourceCrop.right - layer->sourceCrop.left) > 1280) ||
-        ((layer->sourceCrop.bottom - layer->sourceCrop.top) > 720));
-}
-
 static int omap4_hwc_prepare(struct hwc_composer_device *dev, hwc_layer_list_t* list)
 {
     omap4_hwc_device_t *hwc_dev = (omap4_hwc_device_t *)dev;
@@ -1330,7 +1215,6 @@
     int fb_z = -1;
     int scaled_gfx = 0;
     int ix_docking = -1;
-    int big_layers = 0;
 
     /* set up if DSS layers */
     unsigned int mem_used = 0;
@@ -1347,9 +1231,7 @@
              (hwc_dev->ext.current.docking && hwc_dev->ext.current.enabled && dockable(layer))) &&
             mem_used + mem1d(handle) < MAX_TILER_SLOT &&
             /* can't have a transparent overlay in the middle of the framebuffer stack */
-            !(is_BLENDED(layer) && fb_z >= 0) &&
-            /* current hardware is unable to keep up with more than 1 'large' RGB32 layer */
-            !(is_large_rgb32_layer(layer) && big_layers > 0)) {
+            !(is_BLENDED(layer) && fb_z >= 0)) {
 
             /* render via DSS overlay */
             mem_used += mem1d(handle);
@@ -1378,8 +1260,8 @@
 
             /* ensure GFX layer is never scaled */
             if (dsscomp->num_ovls == 0) {
-                scaled_gfx = scaled(layer,hwc_dev) || is_NV12(handle);
-            } else if (scaled_gfx && !scaled(layer,hwc_dev) && !is_NV12(handle)) {
+                scaled_gfx = scaled(layer) || is_NV12(handle);
+            } else if (scaled_gfx && !scaled(layer) && !is_NV12(handle)) {
                 /* swap GFX layer with this one */
                 dsscomp->ovls[dsscomp->num_ovls].cfg.ix = 0;
                 dsscomp->ovls[0].cfg.ix = dsscomp->num_ovls;
@@ -1392,14 +1274,8 @@
                  display_area(&dsscomp->ovls[dsscomp->num_ovls]) > display_area(&dsscomp->ovls[ix_docking])))
                 ix_docking = dsscomp->num_ovls;
 
-            omap4_hwc_adjust_lcd_layer(hwc_dev, &dsscomp->ovls[dsscomp->num_ovls]);
             dsscomp->num_ovls++;
             z++;
-
-            /* record whether or not this was a 'big' RGB32 layer */
-            if (is_large_rgb32_layer(layer)) {
-                big_layers++;
-            }
         } else if (hwc_dev->use_sgx) {
             if (fb_z < 0) {
                 /* NOTE: we are not handling transparent cutout for now */
@@ -1421,7 +1297,7 @@
         /* assign a z-layer for fb */
         if (fb_z < 0) {
             if (num.composited_layers)
-                LOGV("**** should have assigned z-layer for fb");
+                ALOGE("**** should have assigned z-layer for fb");
             fb_z = z++;
         }
 
@@ -1434,11 +1310,6 @@
         dsscomp->ovls[0].cfg.pre_mult_alpha = 1;
         dsscomp->ovls[0].addressing = OMAP_DSS_BUFADDR_LAYER_IX;
         dsscomp->ovls[0].ba = 0;
-        if (hwc_dev->lcd_transform)
-            dsscomp->ovls[0].cfg.ix = num.max_hw_overlays;
-        else
-              dsscomp->ovls[0].cfg.ix = num.max_hw_overlays-1;
-        omap4_hwc_adjust_lcd_layer(hwc_dev, &dsscomp->ovls[0]);
     }
 
     /* mirror layers */
@@ -1447,10 +1318,8 @@
     omap4_hwc_ext_t *ext = &hwc_dev->ext;
     if (ext->current.enabled && hwc_dev->ext_ovls) {
         if (ext->current.docking && ix_docking >= 0) {
-            if (clone_external_layer(hwc_dev, ix_docking) == 0) {
+            if (clone_external_layer(hwc_dev, ix_docking) == 0)
                 dsscomp->ovls[dsscomp->num_ovls - 1].cfg.zorder = z++;
-                dsscomp->ovls[dsscomp->num_ovls - 1].cfg.ix = MAX_HW_OVERLAYS - dsscomp->num_ovls;
-            }
         } else if (ext->current.docking && ix_docking < 0 && ext->force_dock) {
             ix_docking = dsscomp->num_ovls;
             struct dss2_ovl_info *oi = &dsscomp->ovls[ix_docking];
@@ -1460,7 +1329,6 @@
             if (clone_external_layer(hwc_dev, ix_docking) == 0) {
                 oi->addressing = OMAP_DSS_BUFADDR_FB;
                 oi->ba = 0;
-                oi->cfg.ix = MAX_HW_OVERLAYS - dsscomp->num_ovls;
                 z++;
             }
         } else if (!ext->current.docking) {
@@ -1481,16 +1349,16 @@
     ext->last = ext->current;
 
     if (z != dsscomp->num_ovls || dsscomp->num_ovls > MAX_HW_OVERLAYS)
-        LOGE("**** used %d z-layers for %d overlays\n", z, dsscomp->num_ovls);
+        ALOGE("**** used %d z-layers for %d overlays\n", z, dsscomp->num_ovls);
 
     /* verify all z-orders and overlay indices are distinct */
     for (i = z = ix = 0; i < dsscomp->num_ovls; i++) {
         struct dss2_ovl_cfg *c = &dsscomp->ovls[i].cfg;
 
         if (z & (1 << c->zorder))
-            LOGE("**** used z-order #%d multiple times", c->zorder);
+            ALOGE("**** used z-order #%d multiple times", c->zorder);
         if (ix & (1 << c->ix))
-            LOGE("**** used ovl index #%d multiple times", c->ix);
+            ALOGE("**** used ovl index #%d multiple times", c->ix);
         z |= 1 << c->zorder;
         ix |= 1 << c->ix;
     }
@@ -1508,7 +1376,7 @@
     }
 
     if (debug) {
-        LOGD("prepare (%d) - %s (comp=%d, poss=%d/%d scaled, RGB=%d,BGR=%d,NV12=%d) (ext=%s%s%ddeg%s %dex/%dmx (last %dex,%din)\n",
+        ALOGD("prepare (%d) - %s (comp=%d, poss=%d/%d scaled, RGB=%d,BGR=%d,NV12=%d) (ext=%s%s%ddeg%s %dex/%dmx (last %dex,%din)\n",
              dsscomp->sync_id,
              hwc_dev->use_sgx ? "SGX+OVL" : "all-OVL",
              num.composited_layers,
@@ -1538,18 +1406,18 @@
         /* remove bootloader image from the screen as blank/unblank does not change the composition */
         ret = ioctl(hwc_dev->dsscomp_fd, DSSCIOC_SETUP_DISPC, &d);
         if (ret)
-            LOGW("failed to remove bootloader image");
+            ALOGW("failed to remove bootloader image");
 
         /* blank and unblank fd to make sure display is properly programmed on boot.
          * This is needed because the bootloader can not be trusted.
          */
         ret = ioctl(hwc_dev->fb_fd, FBIOBLANK, FB_BLANK_POWERDOWN);
         if (ret)
-            LOGW("failed to blank display");
+            ALOGW("failed to blank display");
 
         ret = ioctl(hwc_dev->fb_fd, FBIOBLANK, FB_BLANK_UNBLANK);
         if (ret)
-            LOGW("failed to blank display");
+            ALOGW("failed to blank display");
     }
 }
 
@@ -1563,11 +1431,7 @@
 
     pthread_mutex_lock(&hwc_dev->lock);
 
-    /* disable resetting the screen on the first boot for devices
-     * with hdmi as primary input.
-     */
-    if (!hwc_dev->on_tv)
-        omap4_hwc_reset_screen(hwc_dev);
+    omap4_hwc_reset_screen(hwc_dev);
 
     invalidate = hwc_dev->ext_ovls_wanted && !hwc_dev->ext_ovls;
 
@@ -1581,7 +1445,7 @@
 
         if (hwc_dev->use_sgx) {
             if (!eglSwapBuffers((EGLDisplay)dpy, (EGLSurface)sur)) {
-                LOGE("eglSwapBuffers error");
+                ALOGE("eglSwapBuffers error");
                 err = HWC_EGL_ERROR;
                 goto err_out;
             }
@@ -1598,20 +1462,11 @@
                                  hwc_dev->buffers,
                                  hwc_dev->post2_layers,
                                  dsscomp, sizeof(*dsscomp));
-
-        if (!hwc_dev->use_sgx) {
-            __u32 crt = 0;
-            int err2 = ioctl(hwc_dev->fb_fd, FBIO_WAITFORVSYNC, &crt);
-            if (err2) {
-                LOGE("failed to wait for vsync (%d)", errno);
-                err = err ? : -errno;
-            }
-        }
     }
     hwc_dev->last_ext_ovls = hwc_dev->ext_ovls;
     hwc_dev->last_int_ovls = hwc_dev->post2_layers;
     if (err)
-        LOGE("Post2 error");
+        ALOGE("Post2 error");
 
 err_out:
     pthread_mutex_unlock(&hwc_dev->lock);
@@ -1664,7 +1519,7 @@
 
     FILE *fd = fopen(path, "rb");
     if (!fd) {
-        LOGE("failed to open PNG file %s: (%d)", path, errno);
+        ALOGE("failed to open PNG file %s: (%d)", path, errno);
         return -EINVAL;
     }
 
@@ -1672,7 +1527,7 @@
     __u8 header[SIZE_PNG_HEADER];
     fread(header, 1, SIZE_PNG_HEADER, fd);
     if (png_sig_cmp(header, 0, SIZE_PNG_HEADER)) {
-        LOGE("%s is not a PNG file", path);
+        ALOGE("%s is not a PNG file", path);
         goto fail;
     }
 
@@ -1720,7 +1575,7 @@
         png_set_bgr(png_ptr);
         break;
     default:
-        LOGE("unsupported PNG color: %x", color_type);
+        ALOGE("unsupported PNG color: %x", color_type);
         goto fail_alloc;
     }
 
@@ -1730,14 +1585,14 @@
     const int bpp = 4;
     img->size = ALIGN(width * height * bpp, 4096);
     if (img->size > hwc_dev->img_mem_size) {
-        LOGE("image does not fit into framebuffer area (%d > %d)", img->size, hwc_dev->img_mem_size);
+        ALOGE("image does not fit into framebuffer area (%d > %d)", img->size, hwc_dev->img_mem_size);
         goto fail_alloc;
     }
     img->ptr = hwc_dev->img_mem_ptr;
 
     row_pointers = calloc(height, sizeof(*row_pointers));
     if (!row_pointers) {
-        LOGE("failed to allocate row pointers");
+        ALOGE("failed to allocate row pointers");
         goto fail_alloc;
     }
     __u32 i;
@@ -1760,7 +1615,7 @@
     free_png_image(hwc_dev, img);
     free(row_pointers);
     if (!png_ptr || !info_ptr)
-        LOGE("failed to allocate PNG structures");
+        ALOGE("failed to allocate PNG structures");
     png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
 fail:
     fclose(fd);
@@ -1809,78 +1664,14 @@
     return 0;
 
 err_out:
-    LOGE("Composer HAL failed to load compatible Graphics HAL");
+    ALOGE("Composer HAL failed to load compatible Graphics HAL");
     return err;
 }
-static void set_lcd_transform_matrix(omap4_hwc_device_t *hwc_dev)
-{
-/* create LCD translation matrix */
 
-     hwc_rect_t region = { .left = 0, .top = 0, .right = hwc_dev->fb_dev->base.width, .bottom = hwc_dev->fb_dev->base.height };
-    hwc_dev->fb_dis.ix = 0;/*Default display*/
-     int ret = ioctl(hwc_dev->dsscomp_fd, DSSCIOC_QUERY_DISPLAY, &hwc_dev->fb_dis);
-          if (ret) {
-               LOGE("failed to get display info (%d): %m", errno);
-          }
-
-     int lcd_w = hwc_dev->fb_dis.timings.x_res;
-     int lcd_h = hwc_dev->fb_dis.timings.y_res;
-     int orig_w = WIDTH(region);
-     int orig_h = HEIGHT(region);
-     hwc_dev->lcd_region = region;
-     hwc_dev->lcd_rotation = ((lcd_w > lcd_h) ^ (orig_w > orig_h)) ? 1 : 0;
-     hwc_dev->lcd_transform = ((lcd_w != orig_w)||(lcd_h != orig_h)) ? 1 : 0;
-
-     LOGI("transforming FB (%dx%d) => (%dx%d) rot%d", orig_w, orig_h, lcd_w, lcd_h, hwc_dev->lcd_rotation);
-
-     /* reorientation matrix is:
-        m = (center-from-target-center) * (scale-to-target) * (mirror) * (rotate) * (center-to-original-center) */
-
-     memcpy(hwc_dev->lcd_m, m_unit, sizeof(m_unit));
-     m_translate(hwc_dev->lcd_m, -(orig_w >> 1) - region.left, -(orig_h >> 1) - region.top);
-     m_rotate(hwc_dev->lcd_m, hwc_dev->lcd_rotation);
-     if (hwc_dev->lcd_rotation & 1)
-          swap(orig_w, orig_h);
-     m_scale(hwc_dev->lcd_m, orig_w, lcd_w, orig_h, lcd_h);
-     m_translate(hwc_dev->lcd_m, lcd_w >> 1, lcd_h >> 1);
-
-     /*create reverse LCD transformation*/
-     memcpy(hwc_dev->lcd_hdmi_m, m_unit, sizeof(m_unit));
-     m_translate(hwc_dev->lcd_hdmi_m, -(lcd_w >> 1) - 0, -(lcd_h >> 1) - 0);
-     m_rotate(hwc_dev->lcd_hdmi_m, hwc_dev->lcd_rotation);
-     if (hwc_dev->lcd_rotation & 1)
-          swap(lcd_w, lcd_h);
-     m_scale(hwc_dev->lcd_hdmi_m, lcd_w, orig_w, lcd_h, orig_h);
-     m_translate(hwc_dev->lcd_hdmi_m, (orig_w >> 1) - region.left,(orig_h >> 1) - region.top);
-    return;
-
-}
 static void handle_hotplug(omap4_hwc_device_t *hwc_dev)
 {
     omap4_hwc_ext_t *ext = &hwc_dev->ext;
     __u8 state = ext->hdmi_state;
-    /* Ignore external HDMI logic if the primary display is HDMI */
-    if (hwc_dev->on_tv) {
-        LOGI("Primary display is HDMI - skip clone/dock logic");
-
-        if (state) {
-            __u32 xres = WIDTH(ext->mirror_region);
-            __u32 yres = HEIGHT(ext->mirror_region);
-            if (omap4_hwc_set_best_hdmi_mode(hwc_dev, xres, yres, ext->lcd_xpy)) {
-                    LOGE("Failed to set HDMI mode");
-            }
-            set_lcd_transform_matrix(hwc_dev);
-            ioctl(hwc_dev->fb_fd, FBIOBLANK, FB_BLANK_UNBLANK);
-
-            if (hwc_dev->procs && hwc_dev->procs->invalidate) {
-                hwc_dev->procs->invalidate(hwc_dev->procs);
-            }
-        } else {
-            ext->last_mode = 0;
-        }
-
-        return;
-    }
 
     pthread_mutex_lock(&hwc_dev->lock);
     ext->dock.enabled = ext->mirror.enabled = 0;
@@ -1899,7 +1690,7 @@
         ext->dock.rotation = atoi(value) & EXT_ROTATION;
         ext->dock.hflip = (atoi(value) & EXT_HFLIP) > 0;
         ext->dock.docking = 1;
-        property_get("persist.hwc.mirroring.transform", value, hwc_dev->fb_dis.timings.y_res > hwc_dev->fb_dis.timings.x_res ? "3" : "0");
+        property_get("persist.hwc.mirroring.transform", value, hwc_dev->fb_dev->base.height > hwc_dev->fb_dev->base.width ? "3" : "0");
         ext->mirror.rotation = atoi(value) & EXT_ROTATION;
         ext->mirror.hflip = (atoi(value) & EXT_HFLIP) > 0;
         ext->mirror.docking = 0;
@@ -1929,7 +1720,7 @@
     } else {
         ext->last_mode = 0;
     }
-    LOGI("external display changed (state=%d, mirror={%s tform=%ddeg%s}, dock={%s tform=%ddeg%s%s}, tv=%d", state,
+    ALOGI("external display changed (state=%d, mirror={%s tform=%ddeg%s}, dock={%s tform=%ddeg%s%s}, tv=%d", state,
          ext->mirror.enabled ? "enabled" : "disabled",
          ext->mirror.rotation * 90,
          ext->mirror.hflip ? "+hflip" : "",
@@ -1945,26 +1736,48 @@
             hwc_dev->procs->invalidate(hwc_dev->procs);
 }
 
-static void handle_uevents(omap4_hwc_device_t *hwc_dev, const char *s)
+static void handle_uevents(omap4_hwc_device_t *hwc_dev, const char *buff, int len)
 {
-    int dock = !strcmp(s, "change@/devices/virtual/switch/dock");
-    if (!dock &&
-        strcmp(s, "change@/devices/virtual/switch/hdmi"))
-        return;
+    int dock;
+    int hdmi;
+    int vsync;
+    int state = 0;
+    uint64_t timestamp = 0;
+    const char *s = buff;
+
+    dock = !strcmp(s, "change@/devices/virtual/switch/dock");
+    hdmi = !strcmp(s, "change@/devices/virtual/switch/hdmi");
+    vsync = !strcmp(s, "change@/devices/platform/omapfb") ||
+        !strcmp(s, "change@/devices/virtual/switch/omapfb-vsync");
+
+    if (!dock && !vsync && !hdmi)
+       return;
 
     s += strlen(s) + 1;
 
     while(*s) {
-        if (!strncmp(s, "SWITCH_STATE=", strlen("SWITCH_STATE="))) {
-            int state = atoi(s + strlen("SWITCH_STATE="));
-            if (dock)
-                hwc_dev->ext.force_dock = state == 1;
-            else
-                hwc_dev->ext.hdmi_state = state == 1;
-            handle_hotplug(hwc_dev);
-        }
+        if (!strncmp(s, "SWITCH_STATE=", strlen("SWITCH_STATE=")))
+            state = atoi(s + strlen("SWITCH_STATE="));
+        else if (!strncmp(s, "SWITCH_TIME=", strlen("SWITCH_TIME=")))
+            timestamp = strtoull(s + strlen("SWITCH_TIME="), NULL, 0);
+        else if (!strncmp(s, "VSYNC=", strlen("VSYNC=")))
+            timestamp = strtoull(s + strlen("VSYNC="), NULL, 0);
 
         s += strlen(s) + 1;
+        if (s - buff >= len)
+            break;
+    }
+
+    if (vsync) {
+        if (hwc_dev->procs && hwc_dev->procs->vsync) {
+            hwc_dev->procs->vsync(hwc_dev->procs, 0, timestamp);
+        }
+    } else {
+        if (dock)
+            hwc_dev->ext.force_dock = state == 1;
+        else
+            hwc_dev->ext.hdmi_state = state == 1;
+        handle_hotplug(hwc_dev);
     }
 }
 
@@ -1977,6 +1790,8 @@
     int timeout;
     int err;
 
+    setpriority(PRIO_PROCESS, 0, HAL_PRIORITY_URGENT_DISPLAY);
+
     uevent_init();
 
     fds[0].fd = uevent_get_fd();
@@ -2013,7 +1828,7 @@
 
         if (err == -1) {
             if (errno != EINTR)
-                LOGE("event error: %m");
+                ALOGE("event error: %m");
             continue;
         }
 
@@ -2026,8 +1841,8 @@
 
         if (fds[0].revents & POLLIN) {
             /* keep last 2 zeroes to ensure double 0 termination */
-            uevent_next_event(uevent_desc, sizeof(uevent_desc) - 2);
-            handle_uevents(hwc_dev, uevent_desc);
+            int len = uevent_next_event(uevent_desc, sizeof(uevent_desc) - 2);
+            handle_uevents(hwc_dev, uevent_desc, len);
         }
     } while (1);
 
@@ -2042,6 +1857,53 @@
     hwc_dev->procs = (typeof(hwc_dev->procs)) procs;
 }
 
+static int omap4_hwc_query(struct hwc_composer_device* dev,
+        int what, int* value)
+{
+    omap4_hwc_device_t *hwc_dev = (omap4_hwc_device_t *) dev;
+
+    switch (what) {
+    case HWC_BACKGROUND_LAYER_SUPPORTED:
+        // we don't support the background layer yet
+        value[0] = 0;
+        break;
+    case HWC_VSYNC_PERIOD:
+        // vsync period in nanosecond
+        value[0] = 1000000000.0 / hwc_dev->fb_dev->base.fps;
+        break;
+    default:
+        // unsupported query
+        return -EINVAL;
+    }
+    return 0;
+}
+
+static int omap4_hwc_event_control(struct hwc_composer_device* dev,
+        int event, int enabled)
+{
+    omap4_hwc_device_t *hwc_dev = (omap4_hwc_device_t *) dev;
+
+    switch (event) {
+    case HWC_EVENT_VSYNC:
+    {
+        int val = !!enabled;
+        int err;
+
+        err = ioctl(hwc_dev->fb_fd, OMAPFB_ENABLEVSYNC, &val);
+        if (err < 0)
+            return -errno;
+
+        return 0;
+    }
+    default:
+        return -EINVAL;
+    }
+}
+
+struct hwc_methods omap4_hwc_methods = {
+    .eventControl = &omap4_hwc_event_control,
+};
+
 static int omap4_hwc_device_open(const hw_module_t* module, const char* name,
                 hw_device_t** device)
 {
@@ -2059,7 +1921,7 @@
             return err;
 
         if (!hwc_mod->fb_dev) {
-            LOGE("Framebuffer HAL not opened before HWC");
+            ALOGE("Framebuffer HAL not opened before HWC");
             return -EFAULT;
         }
         hwc_mod->fb_dev->bBypassPost = 1;
@@ -2072,33 +1934,42 @@
     memset(hwc_dev, 0, sizeof(*hwc_dev));
 
     hwc_dev->base.common.tag = HARDWARE_DEVICE_TAG;
-    hwc_dev->base.common.version = HWC_API_VERSION;
+    hwc_dev->base.common.version = HWC_DEVICE_API_VERSION_0_3;
     hwc_dev->base.common.module = (hw_module_t *)module;
     hwc_dev->base.common.close = omap4_hwc_device_close;
     hwc_dev->base.prepare = omap4_hwc_prepare;
     hwc_dev->base.set = omap4_hwc_set;
     hwc_dev->base.dump = omap4_hwc_dump;
     hwc_dev->base.registerProcs = omap4_hwc_registerProcs;
+    hwc_dev->base.query = omap4_hwc_query;
+    hwc_dev->base.methods = &omap4_hwc_methods;
     hwc_dev->fb_dev = hwc_mod->fb_dev;
     *device = &hwc_dev->base.common;
 
     hwc_dev->dsscomp_fd = open("/dev/dsscomp", O_RDWR);
     if (hwc_dev->dsscomp_fd < 0) {
-        LOGE("failed to open dsscomp (%d)", errno);
+        ALOGE("failed to open dsscomp (%d)", errno);
+        err = -errno;
+        goto done;
+    }
+
+    hwc_dev->hdmi_fb_fd = open("/dev/graphics/fb1", O_RDWR);
+    if (hwc_dev->hdmi_fb_fd < 0) {
+        ALOGE("failed to open hdmi fb (%d)", errno);
         err = -errno;
         goto done;
     }
 
     hwc_dev->fb_fd = open("/dev/graphics/fb0", O_RDWR);
     if (hwc_dev->fb_fd < 0) {
-        LOGE("failed to open fb (%d)", errno);
+        ALOGE("failed to open fb (%d)", errno);
         err = -errno;
         goto done;
     }
 
     struct fb_fix_screeninfo fix;
     if (ioctl(hwc_dev->fb_fd, FBIOGET_FSCREENINFO, &fix)) {
-        LOGE("failed to get fb info (%d)", errno);
+        ALOGE("failed to get fb info (%d)", errno);
         err = -errno;
         goto done;
     }
@@ -2106,7 +1977,7 @@
     hwc_dev->img_mem_size = fix.smem_len;
     hwc_dev->img_mem_ptr = mmap(NULL, fix.smem_len, PROT_WRITE, MAP_SHARED, hwc_dev->fb_fd, 0);
     if (hwc_dev->img_mem_ptr == MAP_FAILED) {
-        LOGE("failed to map fb memory");
+        ALOGE("failed to map fb memory");
         err = -errno;
         goto done;
     }
@@ -2119,41 +1990,27 @@
 
     int ret = ioctl(hwc_dev->dsscomp_fd, DSSCIOC_QUERY_DISPLAY, &hwc_dev->fb_dis);
     if (ret) {
-        LOGE("failed to get display info (%d): %m", errno);
+        ALOGE("failed to get display info (%d): %m", errno);
         err = -errno;
         goto done;
     }
     hwc_dev->ext.lcd_xpy = (float) hwc_dev->fb_dis.width_in_mm / hwc_dev->fb_dis.timings.x_res /
                             hwc_dev->fb_dis.height_in_mm       * hwc_dev->fb_dis.timings.y_res;
 
-     if (hwc_dev->fb_dis.channel == OMAP_DSS_CHANNEL_DIGIT) {
-        LOGI("Primary display is HDMI");
-        hwc_dev->on_tv = 1;
-    }
-     else {
-        hwc_dev->hdmi_fb_fd = open("/dev/graphics/fb1", O_RDWR);
-        if (hwc_dev->hdmi_fb_fd < 0) {
-            LOGE("failed to open hdmi fb (%d)", errno);
-            err = -errno;
-            goto done;
-        }
-    }
-     set_lcd_transform_matrix( hwc_dev );
-
     if (pipe(hwc_dev->pipe_fds) == -1) {
-            LOGE("failed to event pipe (%d): %m", errno);
+            ALOGE("failed to event pipe (%d): %m", errno);
             err = -errno;
             goto done;
     }
 
     if (pthread_mutex_init(&hwc_dev->lock, NULL)) {
-        LOGE("failed to create mutex (%d): %m", errno);
+        ALOGE("failed to create mutex (%d): %m", errno);
         err = -errno;
         goto done;
     }
     if (pthread_create(&hwc_dev->hdmi_thread, NULL, omap4_hwc_hdmi_thread, hwc_dev))
     {
-        LOGE("failed to create HDMI listening thread (%d): %m", errno);
+        ALOGE("failed to create HDMI listening thread (%d): %m", errno);
         err = -errno;
         goto done;
     }
@@ -2177,10 +2034,10 @@
                &hwc_dev->ext.mirror_region.right, &hwc_dev->ext.mirror_region.bottom) != 4 ||
         hwc_dev->ext.mirror_region.left >= hwc_dev->ext.mirror_region.right ||
         hwc_dev->ext.mirror_region.top >= hwc_dev->ext.mirror_region.bottom) {
-        struct hwc_rect fb_region = { .right = hwc_dev->fb_dis.timings.x_res, .bottom = hwc_dev->fb_dis.timings.y_res };
+        struct hwc_rect fb_region = { .right = hwc_dev->fb_dev->base.width, .bottom = hwc_dev->fb_dev->base.height };
         hwc_dev->ext.mirror_region = fb_region;
     }
-    LOGI("clone region is set to (%d,%d) to (%d,%d)",
+    ALOGI("clone region is set to (%d,%d) to (%d,%d)",
          hwc_dev->ext.mirror_region.left, hwc_dev->ext.mirror_region.top,
          hwc_dev->ext.mirror_region.right, hwc_dev->ext.mirror_region.bottom);
 
@@ -2201,7 +2058,7 @@
     }
     handle_hotplug(hwc_dev);
 
-    LOGI("omap4_hwc_device_open(rgb_order=%d nv12_only=%d)",
+    ALOGI("omap4_hwc_device_open(rgb_order=%d nv12_only=%d)",
         hwc_dev->flags_rgb_order, hwc_dev->flags_nv12_only);
 
 done:
@@ -2228,8 +2085,8 @@
     .base = {
         .common = {
             .tag =                  HARDWARE_MODULE_TAG,
-            .version_major =        1,
-            .version_minor =        0,
+            .module_api_version =   HWC_MODULE_API_VERSION_0_1,
+            .hal_api_version =      HARDWARE_HAL_API_VERSION,
             .id =                   HWC_HARDWARE_MODULE_ID,
             .name =                 "OMAP 44xx Hardware Composer HAL",
             .author =               "Texas Instruments",
diff --git a/ion/Android.mk b/ion/Android.mk
deleted file mode 100644
index c9bf668..0000000
--- a/ion/Android.mk
+++ /dev/null
@@ -1,20 +0,0 @@
-# only include if running on an omap4 platform
-ifeq ($(TARGET_BOARD_PLATFORM),omap4)
-
-LOCAL_PATH:= $(call my-dir)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := ion.c
-LOCAL_MODULE := libion
-LOCAL_MODULE_TAGS := optional
-LOCAL_SHARED_LIBRARIES := liblog
-include $(BUILD_HEAPTRACKED_SHARED_LIBRARY)
-
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := ion.c ion_test.c
-LOCAL_MODULE := iontest
-LOCAL_MODULE_TAGS := optional tests
-LOCAL_SHARED_LIBRARIES := liblog
-include $(BUILD_HEAPTRACKED_EXECUTABLE)
-
-endif
diff --git a/ion/ion.c b/ion/ion.c
deleted file mode 100644
index 9df344c..0000000
--- a/ion/ion.c
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- *  ion.c
- *
- * Memory Allocator functions for ion
- *
- *   Copyright 2011 Google, Inc
- *
- *  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.
- */
-#include <errno.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <sys/ioctl.h>
-#include <sys/mman.h>
-#include <sys/types.h>
-
-#define LOG_TAG "ion"
-#include <cutils/log.h>
-
-#include <linux/ion.h>
-#include <linux/omap_ion.h>
-#include "ion.h"
-
-int ion_open()
-{
-        int fd = open("/dev/ion", O_RDWR);
-        if (fd < 0)
-                LOGE("open /dev/ion failed!\n");
-        return fd;
-}
-
-int ion_close(int fd)
-{
-        return close(fd);
-}
-
-static int ion_ioctl(int fd, int req, void *arg)
-{
-        int ret = ioctl(fd, req, arg);
-        if (ret < 0) {
-                LOGE("ioctl %d failed with code %d: %s\n", req,
-                       ret, strerror(errno));
-                return -errno;
-        }
-        return ret;
-}
-
-int ion_alloc(int fd, size_t len, size_t align, unsigned int flags,
-              struct ion_handle **handle)
-{
-        int ret;
-        struct ion_allocation_data data = {
-                .len = len,
-                .align = align,
-                .flags = flags,
-        };
-
-        ret = ion_ioctl(fd, ION_IOC_ALLOC, &data);
-        if (ret < 0)
-                return ret;
-        *handle = data.handle;
-        return ret;
-}
-
-int ion_alloc_tiler(int fd, size_t w, size_t h, int fmt, unsigned int flags,
-            struct ion_handle **handle, size_t *stride)
-{
-        int ret;
-        struct omap_ion_tiler_alloc_data alloc_data = {
-                .w = w,
-                .h = h,
-                .fmt = fmt,
-                .flags = flags,
-        };
-
-        struct ion_custom_data custom_data = {
-                .cmd = OMAP_ION_TILER_ALLOC,
-                .arg = (unsigned long)(&alloc_data),
-        };
-
-        ret = ion_ioctl(fd, ION_IOC_CUSTOM, &custom_data);
-        if (ret < 0)
-                return ret;
-        *stride = alloc_data.stride;
-        *handle = alloc_data.handle;
-        return ret;
-}
-
-int ion_free(int fd, struct ion_handle *handle)
-{
-        struct ion_handle_data data = {
-                .handle = handle,
-        };
-        return ion_ioctl(fd, ION_IOC_FREE, &data);
-}
-
-int ion_map(int fd, struct ion_handle *handle, size_t length, int prot,
-            int flags, off_t offset, unsigned char **ptr, int *map_fd)
-{
-        struct ion_fd_data data = {
-                .handle = handle,
-        };
-        int ret = ion_ioctl(fd, ION_IOC_MAP, &data);
-        if (ret < 0)
-                return ret;
-        *map_fd = data.fd;
-        if (*map_fd < 0) {
-                LOGE("map ioctl returned negative fd\n");
-                return -EINVAL;
-        }
-        *ptr = mmap(NULL, length, prot, flags, *map_fd, offset);
-        if (*ptr == MAP_FAILED) {
-                LOGE("mmap failed: %s\n", strerror(errno));
-                return -errno;
-        }
-        return ret;
-}
-
-int ion_share(int fd, struct ion_handle *handle, int *share_fd)
-{
-        int map_fd;
-        struct ion_fd_data data = {
-                .handle = handle,
-        };
-        int ret = ion_ioctl(fd, ION_IOC_SHARE, &data);
-        if (ret < 0)
-                return ret;
-        *share_fd = data.fd;
-        if (*share_fd < 0) {
-                LOGE("map ioctl returned negative fd\n");
-                return -EINVAL;
-        }
-        return ret;
-}
-
-int ion_import(int fd, int share_fd, struct ion_handle **handle)
-{
-        struct ion_fd_data data = {
-                .fd = share_fd,
-        };
-        int ret = ion_ioctl(fd, ION_IOC_IMPORT, &data);
-        if (ret < 0)
-                return ret;
-        *handle = data.handle;
-        return ret;
-}
diff --git a/ion/ion.h b/ion/ion.h
deleted file mode 100644
index 871b9bc..0000000
--- a/ion/ion.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- *  ion.c
- *
- * Memory Allocator functions for ion
- *
- *   Copyright 2011 Google, Inc
- *
- *  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.
- */
-
-#include <linux/ion.h>
-#include <linux/omap_ion.h>
-
-int ion_open();
-int ion_close(int fd);
-int ion_alloc(int fd, size_t len, size_t align, unsigned int flags,
-              struct ion_handle **handle);
-int ion_alloc_tiler(int fd, size_t w, size_t h, int fmt, unsigned int flags,
-		    struct ion_handle **handle, size_t *stride);
-int ion_free(int fd, struct ion_handle *handle);
-int ion_map(int fd, struct ion_handle *handle, size_t length, int prot,
-            int flags, off_t offset, unsigned char **ptr, int *map_fd);
-int ion_share(int fd, struct ion_handle *handle, int *share_fd);
-int ion_import(int fd, int share_fd, struct ion_handle **handle);
-
diff --git a/ion/ion_test.c b/ion/ion_test.c
deleted file mode 100644
index 734caca..0000000
--- a/ion/ion_test.c
+++ /dev/null
@@ -1,321 +0,0 @@
-#include <errno.h>
-#include <fcntl.h>
-#include <getopt.h>
-#include <string.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <sys/mman.h>
-#include <sys/ioctl.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include "ion.h"
-#include <linux/ion.h>
-#include <linux/omap_ion.h>
-
-size_t len = 1024*1024, align = 0;
-int prot = PROT_READ | PROT_WRITE;
-int map_flags = MAP_SHARED;
-int alloc_flags = 0;
-int test = -1;
-size_t width = 1024*1024, height = 1024*1024;
-int fmt = TILER_PIXEL_FMT_32BIT;
-int tiler_test = 0;
-size_t stride;
-
-int _ion_alloc_test(int *fd, struct ion_handle **handle)
-{
-	int ret;
-
-	*fd = ion_open();
-	if (*fd < 0)
-		return *fd;
-
-	if (tiler_test)
-		ret = ion_alloc_tiler(*fd, width, height, fmt, alloc_flags,
-					  handle, &stride);
-	else
-		ret = ion_alloc(*fd, len, align, alloc_flags, handle);
-
-	if (ret)
-		printf("%s failed: %s\n", __func__, strerror(ret));
-	return ret;
-}
-
-void ion_alloc_test()
-{
-	int fd, ret;
-	struct ion_handle *handle;
-
-	if(_ion_alloc_test(&fd, &handle))
-			return;
-
-	ret = ion_free(fd, handle);
-	if (ret) {
-		printf("%s failed: %s %p\n", __func__, strerror(ret), handle);
-		return;
-	}
-	ion_close(fd);
-	printf("ion alloc test: passed\n");
-}
-
-void _ion_tiler_map_test(unsigned char *ptr)
-{
-	size_t row, col;
-
-	for (row = 0; row < height; row++)
-		for (col = 0; col < width; col++) {
-			int i = (row * stride) + col;
-			ptr[i] = (unsigned char)i;
-		}
-	for (row = 0; row < height; row++)
-		for (col = 0; col < width; col++) {
-			int i = (row * stride) + col;
-			if (ptr[i] != (unsigned char)i)
-				printf("%s failed wrote %d read %d from mapped "
-					   "memory\n", __func__, i, ptr[i]);
-		}
-}
-
-
-void ion_map_test()
-{
-	int fd, map_fd, ret;
-	size_t i;
-	struct ion_handle *handle;
-	unsigned char *ptr;
-
-	if(_ion_alloc_test(&fd, &handle))
-		return;
-
-	if (tiler_test)
-		len = height * stride;
-	ret = ion_map(fd, handle, len, prot, map_flags, 0, &ptr, &map_fd);
-	if (ret)
-		return;
-
-	if (tiler_test)
-		_ion_tiler_map_test(ptr);
-	else {
-		for (i = 0; i < len; i++) {
-			ptr[i] = (unsigned char)i;
-		}
-		for (i = 0; i < len; i++)
-			if (ptr[i] != (unsigned char)i)
-				printf("%s failed wrote %d read %d from mapped "
-					   "memory\n", __func__, i, ptr[i]);
-	}
-	/* clean up properly */
-	ret = ion_free(fd, handle);
-	ion_close(fd);
-	munmap(ptr, len);
-	close(map_fd);
-
-	_ion_alloc_test(&fd, &handle);
-	close(fd);
-
-#if 0
-	munmap(ptr, len);
-	close(map_fd);
-	ion_close(fd);
-
-	_ion_alloc_test(len, align, flags, &fd, &handle);
-	close(map_fd);
-	ret = ion_map(fd, handle, len, prot, flags, 0, &ptr, &map_fd);
-	/* don't clean up */
-#endif
-}
-
-void ion_share_test()
-
-{
-	struct ion_handle *handle;
-	int sd[2];
-	int num_fd = 1;
-	struct iovec count_vec = {
-		.iov_base = &num_fd,
-		.iov_len = sizeof num_fd,
-	};
-	char buf[CMSG_SPACE(sizeof(int))];
-	socketpair(AF_UNIX, SOCK_STREAM, 0, sd);
-	if (fork()) {
-		struct msghdr msg = {
-			.msg_control = buf,
-			.msg_controllen = sizeof buf,
-			.msg_iov = &count_vec,
-			.msg_iovlen = 1,
-		};
-
-		struct cmsghdr *cmsg;
-		int fd, share_fd, ret;
-		char *ptr;
-		/* parent */
-		if(_ion_alloc_test(&fd, &handle))
-			return;
-		ret = ion_share(fd, handle, &share_fd);
-		if (ret)
-			printf("share failed %s\n", strerror(errno));
-		ptr = mmap(NULL, len, prot, map_flags, share_fd, 0);
-		if (ptr == MAP_FAILED) {
-			return;
-		}
-		strcpy(ptr, "master");
-		cmsg = CMSG_FIRSTHDR(&msg);
-		cmsg->cmsg_level = SOL_SOCKET;
-		cmsg->cmsg_type = SCM_RIGHTS;
-		cmsg->cmsg_len = CMSG_LEN(sizeof(int));
-		*(int *)CMSG_DATA(cmsg) = share_fd;
-		/* send the fd */
-		printf("master? [%10s] should be [master]\n", ptr);
-		printf("master sending msg 1\n");
-		sendmsg(sd[0], &msg, 0);
-		if (recvmsg(sd[0], &msg, 0) < 0)
-			perror("master recv msg 2");
-		printf("master? [%10s] should be [child]\n", ptr);
-
-		/* send ping */
-		sendmsg(sd[0], &msg, 0);
-		printf("master->master? [%10s]\n", ptr);
-		if (recvmsg(sd[0], &msg, 0) < 0)
-			perror("master recv 1");
-	} else {
-		struct msghdr msg;
-		struct cmsghdr *cmsg;
-		char* ptr;
-		int fd, recv_fd;
-		char* child_buf[100];
-		/* child */
-		struct iovec count_vec = {
-			.iov_base = child_buf,
-			.iov_len = sizeof child_buf,
-		};
-
-		struct msghdr child_msg = {
-			.msg_control = buf,
-			.msg_controllen = sizeof buf,
-			.msg_iov = &count_vec,
-			.msg_iovlen = 1,
-		};
-
-		if (recvmsg(sd[1], &child_msg, 0) < 0)
-			perror("child recv msg 1");
-		cmsg = CMSG_FIRSTHDR(&child_msg);
-		if (cmsg == NULL) {
-			printf("no cmsg rcvd in child");
-			return;
-		}
-		recv_fd = *(int*)CMSG_DATA(cmsg);
-		if (recv_fd < 0) {
-			printf("could not get recv_fd from socket");
-			return;
-		}
-		printf("child %d\n", recv_fd);
-		fd = ion_open();
-		ptr = mmap(NULL, len, prot, map_flags, recv_fd, 0);
-		if (ptr == MAP_FAILED) {
-			return;
-		}
-		printf("child? [%10s] should be [master]\n", ptr);
-		strcpy(ptr, "child");
-		printf("child sending msg 2\n");
-		sendmsg(sd[1], &child_msg, 0);
-	}
-}
-
-int main(int argc, char* argv[]) {
-	int c;
-	enum tests {
-		ALLOC_TEST = 0, MAP_TEST, SHARE_TEST,
-	};
-
-	while (1) {
-		static struct option opts[] = {
-			{"alloc", no_argument, 0, 'a'},
-			{"alloc_flags", required_argument, 0, 'f'},
-			{"map", no_argument, 0, 'm'},
-			{"share", no_argument, 0, 's'},
-			{"len", required_argument, 0, 'l'},
-			{"align", required_argument, 0, 'g'},
-			{"map_flags", required_argument, 0, 'z'},
-			{"prot", required_argument, 0, 'p'},
-			{"alloc_tiler", no_argument, 0, 't'},
-			{"width", required_argument, 0, 'w'},
-			{"height", required_argument, 0, 'h'},
-			{"fmt", required_argument, 0, 'r'},
-		};
-		int i = 0;
-		c = getopt_long(argc, argv, "af:h:l:mr:stw:", opts, &i);
-		if (c == -1)
-			break;
-
-		switch (c) {
-		case 'l':
-			len = atol(optarg);
-			break;
-		case 'g':
-			align = atol(optarg);
-			break;
-		case 'z':
-			map_flags = 0;
-			map_flags |= strstr(optarg, "PROT_EXEC") ?
-				PROT_EXEC : 0;
-			map_flags |= strstr(optarg, "PROT_READ") ?
-				PROT_READ: 0;
-			map_flags |= strstr(optarg, "PROT_WRITE") ?
-				PROT_WRITE: 0;
-			map_flags |= strstr(optarg, "PROT_NONE") ?
-				PROT_NONE: 0;
-			break;
-		case 'p':
-			prot = 0;
-			prot |= strstr(optarg, "MAP_PRIVATE") ?
-				MAP_PRIVATE	 : 0;
-			prot |= strstr(optarg, "MAP_SHARED") ?
-				MAP_PRIVATE	 : 0;
-			break;
-		case 'f':
-			alloc_flags = atol(optarg);
-			break;
-		case 'a':
-			test = ALLOC_TEST;
-			break;
-		case 'm':
-			test = MAP_TEST;
-			break;
-		case 'r':
-			fmt = atol(optarg);
-			break;
-		case 's':
-			test = SHARE_TEST;
-			break;
-		case 'w':
-			width = atol(optarg);
-			break;
-		case 'h':
-			height = atol(optarg);
-			break;
-		case 't':
-			tiler_test = 1;
-			break;
-		}
-	}
-	printf("test %d, len %u, width %u, height %u fmt %u align %u, "
-		   "map_flags %d, prot %d, alloc_flags %d\n", test, len, width,
-		   height, fmt, align, map_flags, prot, alloc_flags);
-	switch (test) {
-		case ALLOC_TEST:
-			ion_alloc_test();
-			break;
-		case MAP_TEST:
-			ion_map_test();
-			break;
-		case SHARE_TEST:
-			ion_share_test();
-			break;
-		default:
-			printf("must specify a test (alloc, map, share)\n");
-	}
-	return 0;
-}
diff --git a/kernel-headers/linux/omapfb.h b/kernel-headers/linux/omapfb.h
new file mode 100644
index 0000000..08ab25e
--- /dev/null
+++ b/kernel-headers/linux/omapfb.h
@@ -0,0 +1,231 @@
+/****************************************************************************
+ ****************************************************************************
+ ***
+ ***   This header was automatically generated from a Linux kernel header
+ ***   of the same name, to make information necessary for userspace to
+ ***   call into the kernel available to libc.  It contains only constants,
+ ***   structures, and macros generated from the original header, and thus,
+ ***   contains no copyrightable information.
+ ***
+ ***   To edit the content of this header, modify the corresponding
+ ***   source file (e.g. under external/kernel-headers/original/) then
+ ***   run bionic/libc/kernel/tools/update_all.py
+ ***
+ ***   Any manual change here will be lost the next time this script will
+ ***   be run. You've been warned!
+ ***
+ ****************************************************************************
+ ****************************************************************************/
+#ifndef __LINUX_OMAPFB_H__
+#define __LINUX_OMAPFB_H__
+#include <linux/fb.h>
+#include <linux/ioctl.h>
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#include <linux/types.h>
+#define OMAP_IOW(num, dtype) _IOW('O', num, dtype)
+#define OMAP_IOR(num, dtype) _IOR('O', num, dtype)
+#define OMAP_IOWR(num, dtype) _IOWR('O', num, dtype)
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define OMAP_IO(num) _IO('O', num)
+#define OMAPFB_MIRROR OMAP_IOW(31, int)
+#define OMAPFB_SYNC_GFX OMAP_IO(37)
+#define OMAPFB_VSYNC OMAP_IO(38)
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define OMAPFB_SET_UPDATE_MODE OMAP_IOW(40, int)
+#define OMAPFB_GET_CAPS OMAP_IOR(42, struct omapfb_caps)
+#define OMAPFB_GET_UPDATE_MODE OMAP_IOW(43, int)
+#define OMAPFB_LCD_TEST OMAP_IOW(45, int)
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define OMAPFB_CTRL_TEST OMAP_IOW(46, int)
+#define OMAPFB_UPDATE_WINDOW_OLD OMAP_IOW(47, struct omapfb_update_window_old)
+#define OMAPFB_SET_COLOR_KEY OMAP_IOW(50, struct omapfb_color_key)
+#define OMAPFB_GET_COLOR_KEY OMAP_IOW(51, struct omapfb_color_key)
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define OMAPFB_SETUP_PLANE OMAP_IOW(52, struct omapfb_plane_info)
+#define OMAPFB_QUERY_PLANE OMAP_IOW(53, struct omapfb_plane_info)
+#define OMAPFB_UPDATE_WINDOW OMAP_IOW(54, struct omapfb_update_window)
+#define OMAPFB_SETUP_MEM OMAP_IOW(55, struct omapfb_mem_info)
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define OMAPFB_QUERY_MEM OMAP_IOW(56, struct omapfb_mem_info)
+#define OMAPFB_WAITFORVSYNC OMAP_IO(57)
+#define OMAPFB_MEMORY_READ OMAP_IOR(58, struct omapfb_memory_read)
+#define OMAPFB_GET_OVERLAY_COLORMODE OMAP_IOR(59, struct omapfb_ovl_colormode)
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define OMAPFB_WAITFORGO OMAP_IO(60)
+#define OMAPFB_GET_VRAM_INFO OMAP_IOR(61, struct omapfb_vram_info)
+#define OMAPFB_SET_TEARSYNC OMAP_IOW(62, struct omapfb_tearsync_info)
+#define OMAPFB_GET_DISPLAY_INFO OMAP_IOR(63, struct omapfb_display_info)
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define OMAPFB_ENABLEVSYNC OMAP_IOW(64, int)
+#define OMAPFB_CAPS_GENERIC_MASK 0x00000fff
+#define OMAPFB_CAPS_LCDC_MASK 0x00fff000
+#define OMAPFB_CAPS_PANEL_MASK 0xff000000
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define OMAPFB_CAPS_MANUAL_UPDATE 0x00001000
+#define OMAPFB_CAPS_TEARSYNC 0x00002000
+#define OMAPFB_CAPS_PLANE_RELOCATE_MEM 0x00004000
+#define OMAPFB_CAPS_PLANE_SCALE 0x00008000
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define OMAPFB_CAPS_WINDOW_PIXEL_DOUBLE 0x00010000
+#define OMAPFB_CAPS_WINDOW_SCALE 0x00020000
+#define OMAPFB_CAPS_WINDOW_OVERLAY 0x00040000
+#define OMAPFB_CAPS_WINDOW_ROTATE 0x00080000
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define OMAPFB_CAPS_SET_BACKLIGHT 0x01000000
+#define OMAPFB_FORMAT_MASK 0x00ff
+#define OMAPFB_FORMAT_FLAG_DOUBLE 0x0100
+#define OMAPFB_FORMAT_FLAG_TEARSYNC 0x0200
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define OMAPFB_FORMAT_FLAG_FORCE_VSYNC 0x0400
+#define OMAPFB_FORMAT_FLAG_ENABLE_OVERLAY 0x0800
+#define OMAPFB_FORMAT_FLAG_DISABLE_OVERLAY 0x1000
+#define OMAPFB_MEMTYPE_SDRAM 0
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+#define OMAPFB_MEMTYPE_SRAM 1
+#define OMAPFB_MEMTYPE_MAX 1
+#define OMAPFB_MEM_IDX_ENABLED 0x80
+#define OMAPFB_MEM_IDX_MASK 0x7f
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+enum omapfb_color_format {
+ OMAPFB_COLOR_RGB565 = 0,
+ OMAPFB_COLOR_YUV422,
+ OMAPFB_COLOR_YUV420,
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ OMAPFB_COLOR_CLUT_8BPP,
+ OMAPFB_COLOR_CLUT_4BPP,
+ OMAPFB_COLOR_CLUT_2BPP,
+ OMAPFB_COLOR_CLUT_1BPP,
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ OMAPFB_COLOR_RGB444,
+ OMAPFB_COLOR_YUY422,
+ OMAPFB_COLOR_ARGB16,
+ OMAPFB_COLOR_RGB24U,
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ OMAPFB_COLOR_RGB24P,
+ OMAPFB_COLOR_ARGB32,
+ OMAPFB_COLOR_RGBA32,
+ OMAPFB_COLOR_RGBX32,
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+};
+struct omapfb_update_window {
+ __u32 x, y;
+ __u32 width, height;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ __u32 format;
+ __u32 out_x, out_y;
+ __u32 out_width, out_height;
+ __u32 reserved[8];
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+};
+struct omapfb_update_window_old {
+ __u32 x, y;
+ __u32 width, height;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ __u32 format;
+};
+enum omapfb_plane {
+ OMAPFB_PLANE_GFX = 0,
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ OMAPFB_PLANE_VID1,
+ OMAPFB_PLANE_VID2,
+};
+enum omapfb_channel_out {
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ OMAPFB_CHANNEL_OUT_LCD = 0,
+ OMAPFB_CHANNEL_OUT_DIGIT,
+};
+struct omapfb_plane_info {
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ __u32 pos_x;
+ __u32 pos_y;
+ __u8 enabled;
+ __u8 channel_out;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ __u8 mirror;
+ __u8 mem_idx;
+ __u32 out_width;
+ __u32 out_height;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ __u32 reserved2[12];
+};
+struct omapfb_mem_info {
+ __u32 size;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ __u8 type;
+ __u8 reserved[3];
+};
+struct omapfb_caps {
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ __u32 ctrl;
+ __u32 plane_color;
+ __u32 wnd_color;
+};
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+enum omapfb_color_key_type {
+ OMAPFB_COLOR_KEY_DISABLED = 0,
+ OMAPFB_COLOR_KEY_GFX_DST,
+ OMAPFB_COLOR_KEY_VID_SRC,
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+};
+struct omapfb_color_key {
+ __u8 channel_out;
+ __u32 background;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ __u32 trans_key;
+ __u8 key_type;
+};
+enum omapfb_update_mode {
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ OMAPFB_UPDATE_DISABLED = 0,
+ OMAPFB_AUTO_UPDATE,
+ OMAPFB_MANUAL_UPDATE
+};
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+struct omapfb_memory_read {
+ __u16 x;
+ __u16 y;
+ __u16 w;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ __u16 h;
+ size_t buffer_size;
+ void __user *buffer;
+};
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+struct omapfb_ovl_colormode {
+ __u8 overlay_idx;
+ __u8 mode_idx;
+ __u32 bits_per_pixel;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ __u32 nonstd;
+ struct fb_bitfield red;
+ struct fb_bitfield green;
+ struct fb_bitfield blue;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ struct fb_bitfield transp;
+};
+struct omapfb_vram_info {
+ __u32 total;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ __u32 free;
+ __u32 largest_free_block;
+ __u32 reserved[5];
+};
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+struct omapfb_tearsync_info {
+ __u8 enabled;
+ __u8 reserved1[3];
+ __u16 line;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ __u16 reserved2;
+};
+struct omapfb_display_info {
+ __u16 xres;
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+ __u16 yres;
+ __u32 width;
+ __u32 height;
+ __u32 reserved[5];
+/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
+};
+#endif
+
diff --git a/libI420colorconvert/Android.mk b/libI420colorconvert/Android.mk
index ec54d31..aa792ba 100644
--- a/libI420colorconvert/Android.mk
+++ b/libI420colorconvert/Android.mk
@@ -7,8 +7,8 @@
     ColorConvert.cpp
 
 LOCAL_C_INCLUDES:= \
-        $(TOP)/frameworks/base/include/media/stagefright/openmax \
-        $(TOP)/frameworks/media/libvideoeditor/include
+        $(TOP)/frameworks/native/include/media/openmax \
+        $(TOP)/frameworks/native/include/media/editor
 
 LOCAL_SHARED_LIBRARIES :=       \
 
diff --git a/libI420colorconvert/ColorConvert.cpp b/libI420colorconvert/ColorConvert.cpp
index 05194d2..7f9d93d 100644
--- a/libI420colorconvert/ColorConvert.cpp
+++ b/libI420colorconvert/ColorConvert.cpp
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-#include "II420ColorConverter.h"
+#include <II420ColorConverter.h>
 #include <OMX_IVCommon.h>
 #include <string.h>
 
diff --git a/libstagefrighthw/Android.mk b/libstagefrighthw/Android.mk
index c1757f2..cf18f69 100644
--- a/libstagefrighthw/Android.mk
+++ b/libstagefrighthw/Android.mk
@@ -7,7 +7,8 @@
     TIOMXPlugin.cpp
 
 LOCAL_C_INCLUDES:= \
-        $(TOP)/frameworks/base/include/media/stagefright/openmax
+        $(TOP)/frameworks/native/include/media/openmax \
+        $(TOP)/frameworks/native/include/media/hardware
 
 LOCAL_SHARED_LIBRARIES :=       \
         libbinder               \
diff --git a/libstagefrighthw/TIOMXPlugin.cpp b/libstagefrighthw/TIOMXPlugin.cpp
index 14c5e91..bd97b77 100644
--- a/libstagefrighthw/TIOMXPlugin.cpp
+++ b/libstagefrighthw/TIOMXPlugin.cpp
@@ -18,8 +18,7 @@
 
 #include <dlfcn.h>
 
-#include <media/stagefright/HardwareAPI.h>
-#include <media/stagefright/MediaDebug.h>
+#include <HardwareAPI.h>
 
 namespace android {
 
@@ -43,7 +42,7 @@
       mGetRolesOfComponentHandle(NULL) {
     if (mLibHandle != NULL) {
         mInit = (InitFunc)dlsym(mLibHandle, "TIOMX_Init");
-        mDeinit = (DeinitFunc)dlsym(mLibHandle, "TIOMX_DeInit");
+        mDeinit = (DeinitFunc)dlsym(mLibHandle, "TIOMX_Deinit");
 
         mComponentNameEnum =
             (ComponentNameEnumFunc)dlsym(mLibHandle, "TIOMX_ComponentNameEnum");
@@ -58,7 +57,7 @@
         (*mInit)();
     }
     else
-        LOGE("%s: failed to load %s", __func__, LIBOMX);
+        ALOGE("%s: failed to load %s", __func__, LIBOMX);
 }
 
 TIOMXPlugin::~TIOMXPlugin() {
@@ -99,7 +98,7 @@
         size_t size,
         OMX_U32 index) {
     if (mLibHandle == NULL) {
-	LOGE("mLibHandle is NULL!");
+	ALOGE("mLibHandle is NULL!");
         return OMX_ErrorUndefined;
     }
 
@@ -132,11 +131,11 @@
         err = (*mGetRolesOfComponentHandle)(
                 const_cast<OMX_STRING>(name), &numRoles, array);
 
-        CHECK_EQ(err, OMX_ErrorNone);
-
         for (OMX_U32 i = 0; i < numRoles; ++i) {
-            String8 s((const char *)array[i]);
-            roles->push(s);
+            if (err == OMX_ErrorNone) {
+                String8 s((const char *)array[i]);
+                roles->push(s);
+            }
 
             delete[] array[i];
             array[i] = NULL;
@@ -146,7 +145,7 @@
         array = NULL;
     }
 
-    return OMX_ErrorNone;
+    return err;
 }
 
 }  // namespace android
diff --git a/libstagefrighthw/TIOMXPlugin.h b/libstagefrighthw/TIOMXPlugin.h
index 668c5ef..7b2e982 100644
--- a/libstagefrighthw/TIOMXPlugin.h
+++ b/libstagefrighthw/TIOMXPlugin.h
@@ -18,7 +18,7 @@
 
 #define TI_OMX_PLUGIN_H_
 
-#include <media/stagefright/OMXPluginBase.h>
+#include <OMXPluginBase.h>
 
 namespace android {
 
diff --git a/libtiutils/Android.mk b/libtiutils/Android.mk
old mode 100755
new mode 100644
index 4b6a2b3..e15eba9
--- a/libtiutils/Android.mk
+++ b/libtiutils/Android.mk
@@ -19,7 +19,6 @@
     libcutils
 
 LOCAL_C_INCLUDES += \
-	frameworks/base/include/utils \
 	bionic/libc/include \
 	hardware/ti/omap4xxx/domx/omx_core/inc \
 	hardware/ti/omap4xxx/domx/mm_osal/inc
diff --git a/libtiutils/DebugUtils.h b/libtiutils/DebugUtils.h
index 54edfc7..f421252 100644
--- a/libtiutils/DebugUtils.h
+++ b/libtiutils/DebugUtils.h
@@ -20,14 +20,14 @@
 #define DEBUG_UTILS_H
 
 ///Defines for debug statements - Macro LOG_TAG needs to be defined in the respective files
-#define DBGUTILS_LOGVA(str)         LOGV("%s:%d %s - " str,__FILE__, __LINE__,__FUNCTION__);
-#define DBGUTILS_LOGVB(str,...)     LOGV("%s:%d %s - " str,__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__);
-#define DBGUTILS_LOGDA(str)         LOGD("%s:%d %s - " str,__FILE__, __LINE__,__FUNCTION__);
-#define DBGUTILS_LOGDB(str, ...)    LOGD("%s:%d %s - " str,__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__);
-#define DBGUTILS_LOGEA(str)         LOGE("%s:%d %s - " str,__FILE__, __LINE__, __FUNCTION__);
-#define DBGUTILS_LOGEB(str, ...)    LOGE("%s:%d %s - " str,__FILE__, __LINE__,__FUNCTION__, __VA_ARGS__);
-#define LOG_FUNCTION_NAME           LOGV("%d: %s() ENTER", __LINE__, __FUNCTION__);
-#define LOG_FUNCTION_NAME_EXIT      LOGV("%d: %s() EXIT", __LINE__, __FUNCTION__);
+#define DBGUTILS_LOGVA(str)         ALOGV("%s:%d %s - " str,__FILE__, __LINE__,__FUNCTION__);
+#define DBGUTILS_LOGVB(str,...)     ALOGV("%s:%d %s - " str,__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__);
+#define DBGUTILS_LOGDA(str)         ALOGD("%s:%d %s - " str,__FILE__, __LINE__,__FUNCTION__);
+#define DBGUTILS_LOGDB(str, ...)    ALOGD("%s:%d %s - " str,__FILE__, __LINE__, __FUNCTION__, __VA_ARGS__);
+#define DBGUTILS_LOGEA(str)         ALOGE("%s:%d %s - " str,__FILE__, __LINE__, __FUNCTION__);
+#define DBGUTILS_LOGEB(str, ...)    ALOGE("%s:%d %s - " str,__FILE__, __LINE__,__FUNCTION__, __VA_ARGS__);
+#define LOG_FUNCTION_NAME           ALOGV("%d: %s() ENTER", __LINE__, __FUNCTION__);
+#define LOG_FUNCTION_NAME_EXIT      ALOGV("%d: %s() EXIT", __LINE__, __FUNCTION__);
 
 
 
diff --git a/libtiutils/ErrorUtils.h b/libtiutils/ErrorUtils.h
index 24dd806..204ec97 100644
--- a/libtiutils/ErrorUtils.h
+++ b/libtiutils/ErrorUtils.h
@@ -18,7 +18,7 @@
 #define ERROR_UTILS_H
 
 ///Header file where all the android error codes are defined
-#include <Errors.h>
+#include <utils/Errors.h>
 
 ///Header file where all the OMX error codes are defined
 #include "OMX_Core.h"
diff --git a/libtiutils/MessageQueue.cpp b/libtiutils/MessageQueue.cpp
old mode 100755
new mode 100644
index 11f5407..e3647d4
--- a/libtiutils/MessageQueue.cpp
+++ b/libtiutils/MessageQueue.cpp
@@ -20,7 +20,7 @@
 #include <sys/types.h>
 #include <sys/poll.h>
 #include <unistd.h>
-#include <Errors.h>
+#include <utils/Errors.h>
 
 
 
diff --git a/libtiutils/MessageQueue.h b/libtiutils/MessageQueue.h
old mode 100755
new mode 100644
diff --git a/libtiutils/Semaphore.cpp b/libtiutils/Semaphore.cpp
index 41fa99c..37f3a89 100644
--- a/libtiutils/Semaphore.cpp
+++ b/libtiutils/Semaphore.cpp
@@ -1,232 +1,232 @@
-/*

- * Copyright (C) Texas Instruments - http://www.ti.com/

- *

- * 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.

- */

-

-

-

-#include "Semaphore.h"

-#include "ErrorUtils.h"

-#include <utils/Log.h>

-#include <time.h>

-

-namespace android {

-

-/**

-   @brief Constructor for the semaphore class

-

-   @param none

-   @return none

- */

-Semaphore::Semaphore()

-{

-    ///Initialize the semaphore to NULL

-    mSemaphore = NULL;

-}

-

-/**

-   @brief Destructor of the semaphore class

-

-   @param none

-   @return none

-

- */

-Semaphore::~Semaphore()

-{

-    Release();

-}

-

-/**

-   @brief: Releases semaphore

-

-   @param count >=0

-   @return NO_ERROR On Success

-   @return One of the android error codes based on semaphore de-initialization

- */

-

-status_t Semaphore::Release()

-{

-    int status = 0;

-

-    ///Destroy only if the semaphore has been created

-    if(mSemaphore)

-        {

-        status = sem_destroy(mSemaphore);

-

-        free(mSemaphore);

-

-        mSemaphore = NULL;

-        }

-

-    ///Initialize the semaphore and return the status

-    return ErrorUtils::posixToAndroidError(status);

-

-}

-

-/**

-   @brief Create the semaphore with initial count value

-

-   @param count >=0

-   @return NO_ERROR On Success

-   @return NO_MEMORY If unable to allocate memory for the semaphore

-   @return BAD_VALUE If an invalid count value is passed (<0)

-   @return One of the android error codes based on semaphore initialization

- */

-

-status_t Semaphore::Create(int count)

-{

-    status_t ret = NO_ERROR;

-

-    ///count cannot be less than zero

-    if(count<0)

-        {

-        return BAD_VALUE;

-        }

-

-    ret = Release();

-    if ( NO_ERROR != ret )

-        {

-        return ret;

-        }

-

-    ///allocate memory for the semaphore

-    mSemaphore = (sem_t*)malloc(sizeof(sem_t)) ;

-

-    ///if memory is unavailable, return error

-    if(!mSemaphore)

-        {

-        return NO_MEMORY;

-        }

-

-    ///Initialize the semaphore and return the status

-    return ErrorUtils::posixToAndroidError(sem_init(mSemaphore, 0x00, count));

-

-}

-

-/**

-   @brief Wait operation

-

-   @param none

-   @return BAD_VALUE if the semaphore is not initialized

-   @return NO_ERROR On success

-   @return One of the android error codes based on semaphore wait operation

- */

-status_t Semaphore::Wait()

-{

-    ///semaphore should have been created first

-    if(!mSemaphore)

-        {

-        return BAD_VALUE;

-        }

-

-    ///Wait and return the status after signalling

-    return ErrorUtils::posixToAndroidError(sem_wait(mSemaphore));

-

-

-}

-

-

-/**

-   @brief Signal operation

-

-   @param none

-     @return BAD_VALUE if the semaphore is not initialized

-     @return NO_ERROR On success

-     @return One of the android error codes based on semaphore signal operation

-   */

-

-status_t Semaphore::Signal()

-{

-    ///semaphore should have been created first

-    if(!mSemaphore)

-        {

-        return BAD_VALUE;

-        }

-

-    ///Post to the semaphore

-    return ErrorUtils::posixToAndroidError(sem_post(mSemaphore));

-

-}

-

-/**

-   @brief Current semaphore count

-

-   @param none

-   @return Current count value of the semaphore

- */

-int Semaphore::Count()

-{

-    int val;

-

-    ///semaphore should have been created first

-    if(!mSemaphore)

-        {

-        return BAD_VALUE;

-        }

-

-    ///get the value of the semaphore

-    sem_getvalue(mSemaphore, &val);

-

-    return val;

-}

-

-/**

-   @brief Wait operation with a timeout

-

-     @param timeoutMicroSecs The timeout period in micro seconds

-     @return BAD_VALUE if the semaphore is not initialized

-     @return NO_ERROR On success

-     @return One of the android error codes based on semaphore wait operation

-   */

-

-status_t Semaphore::WaitTimeout(int timeoutMicroSecs)

-{

-    status_t ret = NO_ERROR;

-

-    struct timespec timeSpec;

-    struct timeval currentTime;

-

-    ///semaphore should have been created first

-    if( NULL == mSemaphore)

-        {

-        ret = BAD_VALUE;

-        }

-

-    if ( NO_ERROR == ret )

-        {

-

-        ///setup the timeout values - timeout is specified in seconds and nanoseconds

-        gettimeofday(&currentTime, NULL);

-        timeSpec.tv_sec = currentTime.tv_sec;

-        timeSpec.tv_nsec = currentTime.tv_usec * 1000;

-        timeSpec.tv_sec += ( timeoutMicroSecs / 1000000 );

-        timeSpec.tv_nsec += ( timeoutMicroSecs % 1000000) * 1000;

-

-        ///Wait for the timeout or signal and return the result based on whichever event occurred first

-        ret = sem_timedwait(mSemaphore, &timeSpec);

-        }

-

-    if ( NO_ERROR != ret )

-      {

-        Signal();

-        Create(0);

-      }

-

-    return ret;

-}

-

-

-};

-

-

+/*
+ * Copyright (C) Texas Instruments - http://www.ti.com/
+ *
+ * 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.
+ */
+
+
+
+#include "Semaphore.h"
+#include "ErrorUtils.h"
+#include <utils/Log.h>
+#include <time.h>
+
+namespace android {
+
+/**
+   @brief Constructor for the semaphore class
+
+   @param none
+   @return none
+ */
+Semaphore::Semaphore()
+{
+    ///Initialize the semaphore to NULL
+    mSemaphore = NULL;
+}
+
+/**
+   @brief Destructor of the semaphore class
+
+   @param none
+   @return none
+
+ */
+Semaphore::~Semaphore()
+{
+    Release();
+}
+
+/**
+   @brief: Releases semaphore
+
+   @param count >=0
+   @return NO_ERROR On Success
+   @return One of the android error codes based on semaphore de-initialization
+ */
+
+status_t Semaphore::Release()
+{
+    int status = 0;
+
+    ///Destroy only if the semaphore has been created
+    if(mSemaphore)
+        {
+        status = sem_destroy(mSemaphore);
+
+        free(mSemaphore);
+
+        mSemaphore = NULL;
+        }
+
+    ///Initialize the semaphore and return the status
+    return ErrorUtils::posixToAndroidError(status);
+
+}
+
+/**
+   @brief Create the semaphore with initial count value
+
+   @param count >=0
+   @return NO_ERROR On Success
+   @return NO_MEMORY If unable to allocate memory for the semaphore
+   @return BAD_VALUE If an invalid count value is passed (<0)
+   @return One of the android error codes based on semaphore initialization
+ */
+
+status_t Semaphore::Create(int count)
+{
+    status_t ret = NO_ERROR;
+
+    ///count cannot be less than zero
+    if(count<0)
+        {
+        return BAD_VALUE;
+        }
+
+    ret = Release();
+    if ( NO_ERROR != ret )
+        {
+        return ret;
+        }
+
+    ///allocate memory for the semaphore
+    mSemaphore = (sem_t*)malloc(sizeof(sem_t)) ;
+
+    ///if memory is unavailable, return error
+    if(!mSemaphore)
+        {
+        return NO_MEMORY;
+        }
+
+    ///Initialize the semaphore and return the status
+    return ErrorUtils::posixToAndroidError(sem_init(mSemaphore, 0x00, count));
+
+}
+
+/**
+   @brief Wait operation
+
+   @param none
+   @return BAD_VALUE if the semaphore is not initialized
+   @return NO_ERROR On success
+   @return One of the android error codes based on semaphore wait operation
+ */
+status_t Semaphore::Wait()
+{
+    ///semaphore should have been created first
+    if(!mSemaphore)
+        {
+        return BAD_VALUE;
+        }
+
+    ///Wait and return the status after signalling
+    return ErrorUtils::posixToAndroidError(sem_wait(mSemaphore));
+
+
+}
+
+
+/**
+   @brief Signal operation
+
+   @param none
+     @return BAD_VALUE if the semaphore is not initialized
+     @return NO_ERROR On success
+     @return One of the android error codes based on semaphore signal operation
+   */
+
+status_t Semaphore::Signal()
+{
+    ///semaphore should have been created first
+    if(!mSemaphore)
+        {
+        return BAD_VALUE;
+        }
+
+    ///Post to the semaphore
+    return ErrorUtils::posixToAndroidError(sem_post(mSemaphore));
+
+}
+
+/**
+   @brief Current semaphore count
+
+   @param none
+   @return Current count value of the semaphore
+ */
+int Semaphore::Count()
+{
+    int val;
+
+    ///semaphore should have been created first
+    if(!mSemaphore)
+        {
+        return BAD_VALUE;
+        }
+
+    ///get the value of the semaphore
+    sem_getvalue(mSemaphore, &val);
+
+    return val;
+}
+
+/**
+   @brief Wait operation with a timeout
+
+     @param timeoutMicroSecs The timeout period in micro seconds
+     @return BAD_VALUE if the semaphore is not initialized
+     @return NO_ERROR On success
+     @return One of the android error codes based on semaphore wait operation
+   */
+
+status_t Semaphore::WaitTimeout(int timeoutMicroSecs)
+{
+    status_t ret = NO_ERROR;
+
+    struct timespec timeSpec;
+    struct timeval currentTime;
+
+    ///semaphore should have been created first
+    if( NULL == mSemaphore)
+        {
+        ret = BAD_VALUE;
+        }
+
+    if ( NO_ERROR == ret )
+        {
+
+        ///setup the timeout values - timeout is specified in seconds and nanoseconds
+        gettimeofday(&currentTime, NULL);
+        timeSpec.tv_sec = currentTime.tv_sec;
+        timeSpec.tv_nsec = currentTime.tv_usec * 1000;
+        timeSpec.tv_sec += ( timeoutMicroSecs / 1000000 );
+        timeSpec.tv_nsec += ( timeoutMicroSecs % 1000000) * 1000;
+
+        ///Wait for the timeout or signal and return the result based on whichever event occurred first
+        ret = sem_timedwait(mSemaphore, &timeSpec);
+        }
+
+    if ( NO_ERROR != ret )
+      {
+        Signal();
+        Create(0);
+      }
+
+    return ret;
+}
+
+
+};
+
+
diff --git a/libtiutils/Semaphore.h b/libtiutils/Semaphore.h
index 466e709..6990848 100644
--- a/libtiutils/Semaphore.h
+++ b/libtiutils/Semaphore.h
@@ -16,7 +16,7 @@
 
 
 
-#include <Errors.h>
+#include <utils/Errors.h>
 #include <semaphore.h>
 #include <stdio.h>
 #include <stdarg.h>
diff --git a/omap4.mk b/omap4.mk
index 0fc74f5..ec07ab3 100644
--- a/omap4.mk
+++ b/omap4.mk
@@ -33,5 +33,7 @@
 	libomxcameraadapter \
 	hwcomposer.omap4 \
 	smc_pa_ctrl \
-	tf_daemon
+	tf_daemon \
+	libtf_crypto_sst
 
+PRODUCT_VENDOR_KERNEL_HEADERS := hardware/ti/omap4xxx/kernel-headers
diff --git a/original-kernel-headers/linux/omapfb.h b/original-kernel-headers/linux/omapfb.h
new file mode 100644
index 0000000..80c5dc6
--- /dev/null
+++ b/original-kernel-headers/linux/omapfb.h
@@ -0,0 +1,274 @@
+/*
+ * File: include/linux/omapfb.h
+ *
+ * Framebuffer driver for TI OMAP boards
+ *
+ * Copyright (C) 2004 Nokia Corporation
+ * Author: Imre Deak <imre.deak@nokia.com>
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation; either version 2 of the License, or (at your
+ * option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+ */
+
+#ifndef __LINUX_OMAPFB_H__
+#define __LINUX_OMAPFB_H__
+
+#include <linux/fb.h>
+#include <linux/ioctl.h>
+#include <linux/types.h>
+
+/* IOCTL commands. */
+
+#define OMAP_IOW(num, dtype)	_IOW('O', num, dtype)
+#define OMAP_IOR(num, dtype)	_IOR('O', num, dtype)
+#define OMAP_IOWR(num, dtype)	_IOWR('O', num, dtype)
+#define OMAP_IO(num)		_IO('O', num)
+
+#define OMAPFB_MIRROR		OMAP_IOW(31, int)
+#define OMAPFB_SYNC_GFX		OMAP_IO(37)
+#define OMAPFB_VSYNC		OMAP_IO(38)
+#define OMAPFB_SET_UPDATE_MODE	OMAP_IOW(40, int)
+#define OMAPFB_GET_CAPS		OMAP_IOR(42, struct omapfb_caps)
+#define OMAPFB_GET_UPDATE_MODE	OMAP_IOW(43, int)
+#define OMAPFB_LCD_TEST		OMAP_IOW(45, int)
+#define OMAPFB_CTRL_TEST	OMAP_IOW(46, int)
+#define OMAPFB_UPDATE_WINDOW_OLD OMAP_IOW(47, struct omapfb_update_window_old)
+#define OMAPFB_SET_COLOR_KEY	OMAP_IOW(50, struct omapfb_color_key)
+#define OMAPFB_GET_COLOR_KEY	OMAP_IOW(51, struct omapfb_color_key)
+#define OMAPFB_SETUP_PLANE	OMAP_IOW(52, struct omapfb_plane_info)
+#define OMAPFB_QUERY_PLANE	OMAP_IOW(53, struct omapfb_plane_info)
+#define OMAPFB_UPDATE_WINDOW	OMAP_IOW(54, struct omapfb_update_window)
+#define OMAPFB_SETUP_MEM	OMAP_IOW(55, struct omapfb_mem_info)
+#define OMAPFB_QUERY_MEM	OMAP_IOW(56, struct omapfb_mem_info)
+#define OMAPFB_WAITFORVSYNC	OMAP_IO(57)
+#define OMAPFB_MEMORY_READ	OMAP_IOR(58, struct omapfb_memory_read)
+#define OMAPFB_GET_OVERLAY_COLORMODE OMAP_IOR(59, struct omapfb_ovl_colormode)
+#define OMAPFB_WAITFORGO	OMAP_IO(60)
+#define OMAPFB_GET_VRAM_INFO	OMAP_IOR(61, struct omapfb_vram_info)
+#define OMAPFB_SET_TEARSYNC	OMAP_IOW(62, struct omapfb_tearsync_info)
+#define OMAPFB_GET_DISPLAY_INFO	OMAP_IOR(63, struct omapfb_display_info)
+#define OMAPFB_ENABLEVSYNC	OMAP_IOW(64, int)
+
+#define OMAPFB_CAPS_GENERIC_MASK	0x00000fff
+#define OMAPFB_CAPS_LCDC_MASK		0x00fff000
+#define OMAPFB_CAPS_PANEL_MASK		0xff000000
+
+#define OMAPFB_CAPS_MANUAL_UPDATE	0x00001000
+#define OMAPFB_CAPS_TEARSYNC		0x00002000
+#define OMAPFB_CAPS_PLANE_RELOCATE_MEM	0x00004000
+#define OMAPFB_CAPS_PLANE_SCALE		0x00008000
+#define OMAPFB_CAPS_WINDOW_PIXEL_DOUBLE	0x00010000
+#define OMAPFB_CAPS_WINDOW_SCALE	0x00020000
+#define OMAPFB_CAPS_WINDOW_OVERLAY	0x00040000
+#define OMAPFB_CAPS_WINDOW_ROTATE	0x00080000
+#define OMAPFB_CAPS_SET_BACKLIGHT	0x01000000
+
+/* Values from DSP must map to lower 16-bits */
+#define OMAPFB_FORMAT_MASK		0x00ff
+#define OMAPFB_FORMAT_FLAG_DOUBLE	0x0100
+#define OMAPFB_FORMAT_FLAG_TEARSYNC	0x0200
+#define OMAPFB_FORMAT_FLAG_FORCE_VSYNC	0x0400
+#define OMAPFB_FORMAT_FLAG_ENABLE_OVERLAY	0x0800
+#define OMAPFB_FORMAT_FLAG_DISABLE_OVERLAY	0x1000
+
+#define OMAPFB_MEMTYPE_SDRAM		0
+#define OMAPFB_MEMTYPE_SRAM		1
+#define OMAPFB_MEMTYPE_MAX		1
+
+#define OMAPFB_MEM_IDX_ENABLED	0x80
+#define OMAPFB_MEM_IDX_MASK	0x7f
+
+enum omapfb_color_format {
+	OMAPFB_COLOR_RGB565 = 0,
+	OMAPFB_COLOR_YUV422,
+	OMAPFB_COLOR_YUV420,
+	OMAPFB_COLOR_CLUT_8BPP,
+	OMAPFB_COLOR_CLUT_4BPP,
+	OMAPFB_COLOR_CLUT_2BPP,
+	OMAPFB_COLOR_CLUT_1BPP,
+	OMAPFB_COLOR_RGB444,
+	OMAPFB_COLOR_YUY422,
+
+	OMAPFB_COLOR_ARGB16,
+	OMAPFB_COLOR_RGB24U,	/* RGB24, 32-bit container */
+	OMAPFB_COLOR_RGB24P,	/* RGB24, 24-bit container */
+	OMAPFB_COLOR_ARGB32,
+	OMAPFB_COLOR_RGBA32,
+	OMAPFB_COLOR_RGBX32,
+};
+
+struct omapfb_update_window {
+	__u32 x, y;
+	__u32 width, height;
+	__u32 format;
+	__u32 out_x, out_y;
+	__u32 out_width, out_height;
+	__u32 reserved[8];
+};
+
+struct omapfb_update_window_old {
+	__u32 x, y;
+	__u32 width, height;
+	__u32 format;
+};
+
+enum omapfb_plane {
+	OMAPFB_PLANE_GFX = 0,
+	OMAPFB_PLANE_VID1,
+	OMAPFB_PLANE_VID2,
+};
+
+enum omapfb_channel_out {
+	OMAPFB_CHANNEL_OUT_LCD = 0,
+	OMAPFB_CHANNEL_OUT_DIGIT,
+};
+
+struct omapfb_plane_info {
+	__u32 pos_x;
+	__u32 pos_y;
+	__u8  enabled;
+	__u8  channel_out;
+	__u8  mirror;
+	__u8  mem_idx;
+	__u32 out_width;
+	__u32 out_height;
+	__u32 reserved2[12];
+};
+
+struct omapfb_mem_info {
+	__u32 size;
+	__u8  type;
+	__u8  reserved[3];
+};
+
+struct omapfb_caps {
+	__u32 ctrl;
+	__u32 plane_color;
+	__u32 wnd_color;
+};
+
+enum omapfb_color_key_type {
+	OMAPFB_COLOR_KEY_DISABLED = 0,
+	OMAPFB_COLOR_KEY_GFX_DST,
+	OMAPFB_COLOR_KEY_VID_SRC,
+};
+
+struct omapfb_color_key {
+	__u8  channel_out;
+	__u32 background;
+	__u32 trans_key;
+	__u8  key_type;
+};
+
+enum omapfb_update_mode {
+	OMAPFB_UPDATE_DISABLED = 0,
+	OMAPFB_AUTO_UPDATE,
+	OMAPFB_MANUAL_UPDATE
+};
+
+struct omapfb_memory_read {
+	__u16 x;
+	__u16 y;
+	__u16 w;
+	__u16 h;
+	size_t buffer_size;
+	void __user *buffer;
+};
+
+struct omapfb_ovl_colormode {
+	__u8 overlay_idx;
+	__u8 mode_idx;
+	__u32 bits_per_pixel;
+	__u32 nonstd;
+	struct fb_bitfield red;
+	struct fb_bitfield green;
+	struct fb_bitfield blue;
+	struct fb_bitfield transp;
+};
+
+struct omapfb_vram_info {
+	__u32 total;
+	__u32 free;
+	__u32 largest_free_block;
+	__u32 reserved[5];
+};
+
+struct omapfb_tearsync_info {
+	__u8 enabled;
+	__u8 reserved1[3];
+	__u16 line;
+	__u16 reserved2;
+};
+
+struct omapfb_display_info {
+	__u16 xres;
+	__u16 yres;
+	__u32 width;	/* phys width of the display in micrometers */
+	__u32 height;	/* phys height of the display in micrometers */
+	__u32 reserved[5];
+};
+
+#ifdef __KERNEL__
+
+#include <plat/board.h>
+
+#ifdef CONFIG_ARCH_OMAP1
+#define OMAPFB_PLANE_NUM		1
+#else
+#define OMAPFB_PLANE_NUM		3
+#endif
+
+struct omapfb_mem_region {
+	u32		paddr;
+	void __iomem	*vaddr;
+	unsigned long	size;
+	u8		type;		/* OMAPFB_PLANE_MEM_* */
+	enum omapfb_color_format format;/* OMAPFB_COLOR_* */
+	unsigned	format_used:1;	/* Must be set when format is set.
+					 * Needed b/c of the badly chosen 0
+					 * base for OMAPFB_COLOR_* values
+					 */
+	unsigned	alloc:1;	/* allocated by the driver */
+	unsigned	map:1;		/* kernel mapped by the driver */
+};
+
+struct omapfb_mem_desc {
+	int				region_cnt;
+	struct omapfb_mem_region	region[OMAPFB_PLANE_NUM];
+};
+
+struct omapfb_platform_data {
+	struct omap_lcd_config		lcd;
+	struct omapfb_mem_desc		mem_desc;
+	void				*ctrl_platform_data;
+};
+
+/* in arch/arm/plat-omap/fb.c */
+extern void omapfb_set_platform_data(struct omapfb_platform_data *data);
+extern void omapfb_set_ctrl_platform_data(void *pdata);
+extern void omapfb_reserve_sdram_memblock(void);
+
+/* helper methods that may be used by other modules */
+enum omap_color_mode;
+struct omap_video_timings;
+int omapfb_mode_to_dss_mode(struct fb_var_screeninfo *var,
+			enum omap_color_mode *mode);
+void omapfb_fb2dss_timings(struct fb_videomode *fb_timings,
+			struct omap_video_timings *dss_timings);
+void omapfb_dss2fb_timings(struct omap_video_timings *dss_timings,
+			struct fb_videomode *fb_timings);
+
+#endif
+
+#endif /* __OMAPFB_H */
diff --git a/MODULE_LICENSE_APACHE2 b/security/MODULE_LICENSE_BSD_LIKE
similarity index 100%
copy from MODULE_LICENSE_APACHE2
copy to security/MODULE_LICENSE_BSD_LIKE
diff --git a/security/smc_pa_ctrl/s_version.h b/security/smc_pa_ctrl/s_version.h
index fb9e652..139c11f 100644
--- a/security/smc_pa_ctrl/s_version.h
+++ b/security/smc_pa_ctrl/s_version.h
@@ -59,15 +59,15 @@
 /*
  * This version number must be updated for each new release
  */
-#define S_VERSION_MAIN  "01.06"
-#define S_VERSION_RESOURCE 1,6,0,S_VERSION_BUILD
+#define S_VERSION_MAIN  "01.04"
+#define S_VERSION_RESOURCE 1,4,0,S_VERSION_BUILD
 
 /*
 * If this is a patch or engineering version use the following
 * defines to set the version number. Else set these values to 0.
 */
+#define S_VERSION_PATCH 11
 #define S_VERSION_ENG 0
-#define S_VERSION_PATCH 0
 
 #ifdef S_VERSION_BUILD
 /* TRICK: detect if S_VERSION is defined but empty */
@@ -106,8 +106,8 @@
 	S_VERSION_OS \
 	S_VERSION_PLATFORM \
 	S_VERSION_MAIN \
-	_S_VERSION_ENG \
 	_S_VERSION_PATCH \
+	_S_VERSION_ENG \
 	"."  __STRINGIFY2(S_VERSION_BUILD) " " \
 	S_VERSION_VARIANT
 
diff --git a/security/tee_client_api/Android.mk b/security/tee_client_api/Android.mk
index 8e7d8d5..bfd92f4 100644
--- a/security/tee_client_api/Android.mk
+++ b/security/tee_client_api/Android.mk
@@ -9,13 +9,13 @@
 LOCAL_SRC_FILES:= \
 	tee_client_api_linux_driver.c
 
+LOCAL_CFLAGS += -DLINUX
+LOCAL_CFLAGS += -D__ANDROID32__
+
 ifdef S_VERSION_BUILD
 LOCAL_CFLAGS += -DS_VERSION_BUILD=$(S_VERSION_BUILD)
 endif
 
-LOCAL_LDLIBS += -llog
-
-LOCAL_CFLAGS += -DLINUX
 LOCAL_CFLAGS += -I $(LOCAL_PATH)/../tf_sdk/include/
 
 LOCAL_MODULE:= libtee_client_api_driver
diff --git a/security/tee_client_api/s_version.h b/security/tee_client_api/s_version.h
index f712db2..d112ea0 100644
--- a/security/tee_client_api/s_version.h
+++ b/security/tee_client_api/s_version.h
@@ -58,15 +58,15 @@
 /*
  * This version number must be updated for each new release
  */
-#define S_VERSION_MAIN  "01.06"
-#define S_VERSION_RESOURCE 1,6,0,S_VERSION_BUILD
+#define S_VERSION_MAIN  "01.04"
+#define S_VERSION_RESOURCE 1,4,0,S_VERSION_BUILD
 
 /*
 * If this is a patch or engineering version use the following
 * defines to set the version number. Else set these values to 0.
 */
+#define S_VERSION_PATCH 11
 #define S_VERSION_ENG 0
-#define S_VERSION_PATCH 0
 
 #ifdef S_VERSION_BUILD
 /* TRICK: detect if S_VERSION is defined but empty */
@@ -105,8 +105,8 @@
 	S_VERSION_OS \
 	S_VERSION_PLATFORM \
 	S_VERSION_MAIN \
-	_S_VERSION_ENG \
 	_S_VERSION_PATCH \
+	_S_VERSION_ENG \
 	"."  __STRINGIFY2(S_VERSION_BUILD) " " \
 	S_VERSION_VARIANT
 
diff --git a/security/tee_client_api/schannel6_protocol.h b/security/tee_client_api/schannel6_protocol.h
index 81769be..66ed12c 100644
--- a/security/tee_client_api/schannel6_protocol.h
+++ b/security/tee_client_api/schannel6_protocol.h
@@ -34,6 +34,15 @@
 #include "s_type.h"
 
 /**
+ * This header file defines some structures needed for the secure channel
+ * protocol. See your Product Reference Manual for a specification of the
+ * SChannel protocol.
+ */
+// jroux to do : remove
+#undef SMC_PROTOCOL_VERSION
+#define SMC_PROTOCOL_VERSION 0x06000000
+
+/**
  * Time representation.
  */
 typedef uint64_t SCTIME;
@@ -97,15 +106,6 @@
  */
 #include "schannel6_logins.h"
 
-/*
- * Limits and sizes
- */
-
-/* Maximum number of L1 descriptors covered by a registered shared memory block.
-   Must be kept in synch with TF_MAX_COARSE_PAGES in tf_protocol.h
-   in the Linux kernel driver. */
-#define SCHANNEL6_MAX_DESCRIPTORS_PER_REGISTERED_SHARED_MEM 128
-
 /**
  * Command parameters.
  */
@@ -217,7 +217,7 @@
    uint32_t                      nBlockID;
    uint32_t                      nSharedMemSize;
    uint32_t                      nSharedMemStartOffset;
-   uint32_t                      nSharedMemDescriptors[SCHANNEL6_MAX_DESCRIPTORS_PER_REGISTERED_SHARED_MEM];
+   uint32_t                      nSharedMemDescriptors[8];
 
 }SCHANNEL6_REGISTER_SHARED_MEMORY_COMMAND;
 
diff --git a/security/tee_client_api/tee_client_api_linux_driver.c b/security/tee_client_api/tee_client_api_linux_driver.c
index 584eea2..08a8210 100644
--- a/security/tee_client_api/tee_client_api_linux_driver.c
+++ b/security/tee_client_api/tee_client_api_linux_driver.c
@@ -96,13 +96,6 @@
 #define TRACE_WARNING(...)
 #define TRACE_INFO(...)
 #else
-#if defined ANDROID
-#define LOG_TAG "TEE"
-#include <android/log.h>
-#define TRACE_INFO(format, ...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, format, __VA_ARGS__)
-#define TRACE_ERROR(format, ...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, format, __VA_ARGS__)
-#define TRACE_WARNING(format, ...) __android_log_print(TRACE_WARNING, LOG_TAG, format, __VA_ARGS__)
-#else
 static void TRACE_ERROR(const char* format, ...)
 {
    va_list ap;
@@ -132,7 +125,6 @@
    fprintf(stderr, "\n");
    va_end(ap);
 }
-#endif /* ANDROID */
 #endif /* NDEBUG */
 
 
@@ -792,7 +784,7 @@
        if (connectionData != NULL)
        {
            *(uint32_t*)sCommand.sOpenClientSession.sLoginData = *(uint32_t*)connectionData;
-           sCommand.sHeader.nMessageSize += 1;
+           sCommand.sHeader.nMessageSize += sizeof(uint32_t);
        }
    }
    sCommand.sOpenClientSession.nCancellationID    = (uint32_t)operation; // used for TEEC_RequestCancellation
diff --git a/security/tf_crypto_sst/Android.mk b/security/tf_crypto_sst/Android.mk
new file mode 100644
index 0000000..6d3a9d8
--- /dev/null
+++ b/security/tf_crypto_sst/Android.mk
@@ -0,0 +1,32 @@
+ifeq ($(TARGET_BOARD_PLATFORM),omap4)
+
+LOCAL_PATH := $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_PRELINK_MODULE := false
+LOCAL_ARM_MODE := arm
+
+LOCAL_SRC_FILES := \
+	lib_object.c \
+	lib_mutex_linux.c \
+	sst_stub.c \
+	mtc.c \
+	pkcs11_global.c \
+	pkcs11_object.c \
+	pkcs11_session.c
+
+LOCAL_CFLAGS += -DLINUX
+LOCAL_CFLAGS += -D__ANDROID32__
+
+ifdef S_VERSION_BUILD
+LOCAL_CFLAGS += -DS_VERSION_BUILD=$(S_VERSION_BUILD)
+endif
+
+LOCAL_CFLAGS += -I $(LOCAL_PATH)/../tf_sdk/include/
+
+LOCAL_MODULE:= libtf_crypto_sst
+LOCAL_STATIC_LIBRARIES := libtee_client_api_driver
+LOCAL_MODULE_TAGS := optional
+
+include $(BUILD_SHARED_LIBRARY)
+endif
diff --git a/security/tf_crypto_sst/lib_mutex.h b/security/tf_crypto_sst/lib_mutex.h
new file mode 100644
index 0000000..6f4bed1
--- /dev/null
+++ b/security/tf_crypto_sst/lib_mutex.h
@@ -0,0 +1,97 @@
+/**
+ * Copyright(c) 2011 Trusted Logic.   All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *  * Neither the name Trusted Logic nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __LIB_MUTEX_H__
+#define __LIB_MUTEX_H__
+
+/**
+ * This libray defines a type of simple non-recursive mutex that can
+ * be statically initialized. The interface is very similar to pthread
+ * mutexes.
+ **/
+
+#ifdef WIN32
+
+#include <windows.h>
+#include "s_type.h"
+
+/* Windows API: use a critical section with a state describing
+   whether it has been initialized or not or is being initialized.
+   We use interlocked operations on the state to synchronize between
+   multiple threads competing to initialize the critical section */
+typedef struct
+{
+   volatile uint32_t nInitState;
+   CRITICAL_SECTION sCriticalSection;
+}
+LIB_MUTEX;
+
+#define LIB_MUTEX_WIN32_STATE_UNINITIALIZED 0
+#define LIB_MUTEX_WIN32_STATE_INITIALIZING  1
+#define LIB_MUTEX_WIN32_STATE_INITIALIZED   2
+
+#define LIB_MUTEX_INITIALIZER { 0 }
+
+#endif  /* WIN32 */
+
+#ifdef LINUX
+
+#include <pthread.h>
+#include "s_type.h"
+
+/* Linux: directly use a pthread mutex. */
+typedef pthread_mutex_t LIB_MUTEX;
+#define LIB_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER
+
+#endif /* LINUX */
+
+/**
+ * Initialize a mutex. Note that thie function cannot fail. If there
+ * is not enough resource to initialize the mutex, the implementation
+ * resort to active-wait
+ **/
+void libMutexInit(LIB_MUTEX* pMutex);
+
+/**
+ * Lock the mutex
+ */
+void libMutexLock(LIB_MUTEX* pMutex);
+
+/**
+ * Unlock the mutex
+ */
+void libMutexUnlock(LIB_MUTEX* pMutex);
+
+/**
+ * Destroy the mutex
+ */
+void libMutexDestroy(LIB_MUTEX* pMutex);
+
+#endif /* __LIB_MUTEX_H__ */
diff --git a/security/tf_sdk/include/ssdi_smc_ext.h b/security/tf_crypto_sst/lib_mutex_linux.c
similarity index 74%
rename from security/tf_sdk/include/ssdi_smc_ext.h
rename to security/tf_crypto_sst/lib_mutex_linux.c
index d0cb1c7..da8c9e0 100644
--- a/security/tf_sdk/include/ssdi_smc_ext.h
+++ b/security/tf_crypto_sst/lib_mutex_linux.c
@@ -28,34 +28,29 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-/*
-* File            : ssdi_smc_ext.h
-*
-* Original-Author : Trusted Logic S.A.
-*
-* Created         : October 27, 2008
-*/
-
 /**
- * SSDI SMC Extensions specification header file.
- */
+ * Implementation of the mutex library over the Linux API
+ **/
+#include <pthread.h>
+#include "lib_mutex.h"
 
-#ifndef __SSDI_SMC_EXT_H__
-#define __SSDI_SMC_EXT_H__
-
-
-/* Cryptoki slotID constants */
-#define S_CRYPTOKI_KEYSTORE_HW_TOKEN               0x00007FFF
-
-
-#define CKMV_SMC_KEK_DERIVE                        0xC0000000
-
-
-typedef struct CKV_SMC_KEK_DERIVE_PARAMS
+void libMutexInit(LIB_MUTEX* pMutex)
 {
-   CK_ULONG Id;
-   CK_BYTE diversify[16];
-} CKV_SMC_KEK_DERIVE_PARAMS;
+   pthread_mutex_init(pMutex, NULL);
+   /* Error ignored. Is that OK? */
+}
 
+void libMutexLock(LIB_MUTEX* pMutex)
+{
+   pthread_mutex_lock(pMutex);
+}
 
-#endif /* __SSDI_SMC_EXT_H__ */
+void libMutexUnlock(LIB_MUTEX* pMutex)
+{
+   pthread_mutex_unlock(pMutex);
+}
+
+void libMutexDestroy(LIB_MUTEX* pMutex)
+{
+   pthread_mutex_destroy(pMutex);
+}
diff --git a/security/tf_crypto_sst/lib_object.c b/security/tf_crypto_sst/lib_object.c
new file mode 100644
index 0000000..a07a66f
--- /dev/null
+++ b/security/tf_crypto_sst/lib_object.c
@@ -0,0 +1,418 @@
+/**
+ * Copyright(c) 2011 Trusted Logic.   All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *  * Neither the name Trusted Logic nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** Simple implementation of lib_object using doubly-linked lists. This
+   implementation should outperform more sophisticated data structures
+   like blanced binary trees when the tables have fewer than 10 to 20
+   elements.  */
+
+#include <string.h>
+#include "s_type.h"
+
+#include "lib_object.h"
+
+/* Generic node */
+typedef struct LIB_OBJECT_NODE
+{
+   struct LIB_OBJECT_NODE* pPrevious;
+   struct LIB_OBJECT_NODE* pNext;
+   union
+   {
+      uint16_t nHandle;
+
+      S_STORAGE_NAME sStorageName;
+
+      struct
+      {
+         /* Public fields */
+         uint8_t  sFilename[64];
+         uint8_t  nFilenameLength;
+      }
+      f;
+   }
+   key;
+}
+LIB_OBJECT_NODE;
+
+typedef enum
+{
+   LIB_OBJECT_NODE_TYPE_HANDLE16,
+   LIB_OBJECT_NODE_TYPE_STORAGE_NAME,
+   LIB_OBJECT_NODE_TYPE_FILENAME,
+   LIB_OBJECT_NODE_TYPE_UNINDEXED
+}
+LIB_OBJECT_NODE_TYPE;
+
+/* -----------------------------------------------------------------------
+   Search functions
+   -----------------------------------------------------------------------*/
+static bool libObjectKeyEqualNode(
+   LIB_OBJECT_NODE* pNode,
+   uint32_t nKey1,
+   void* pKey2,
+   LIB_OBJECT_NODE_TYPE eNodeType)
+{
+   switch (eNodeType)
+   {
+   default:
+   case LIB_OBJECT_NODE_TYPE_HANDLE16:
+      return
+         nKey1 == pNode->key.nHandle;
+   case LIB_OBJECT_NODE_TYPE_STORAGE_NAME:
+      return
+         memcmp(
+            (S_STORAGE_NAME*)pKey2,
+            &pNode->key.sStorageName,
+            sizeof(S_STORAGE_NAME)) == 0;
+   case LIB_OBJECT_NODE_TYPE_FILENAME:
+   {
+      uint32_t nLength1 = nKey1;
+      uint32_t nLength2 = pNode->key.f.nFilenameLength;
+      return
+         nLength1 == nLength2
+         &&
+         memcmp(
+            pKey2,
+            &pNode->key.f.sFilename,
+            nLength1) == 0;
+   }
+   }
+}
+
+/* Polymorphic search function */
+static LIB_OBJECT_NODE* libObjectSearch(
+   LIB_OBJECT_NODE* pRoot,
+   uint32_t nKey1,
+   void* pKey2,
+   LIB_OBJECT_NODE_TYPE eNodeType)
+{
+   if (pRoot != NULL)
+   {
+      LIB_OBJECT_NODE* pNode = pRoot;
+      do
+      {
+         if (libObjectKeyEqualNode(pNode, nKey1, pKey2, eNodeType))
+         {
+            /* Match found */
+            return pNode;
+         }
+         pNode = pNode->pNext;
+      }
+      while (pNode != pRoot);
+   }
+   return NULL;
+}
+
+LIB_OBJECT_NODE_HANDLE16* libObjectHandle16Search(
+               LIB_OBJECT_TABLE_HANDLE16* pTable,
+               uint32_t nHandle)
+{
+   return (LIB_OBJECT_NODE_HANDLE16*)libObjectSearch(
+      (LIB_OBJECT_NODE*)pTable->pRoot, nHandle, NULL, LIB_OBJECT_NODE_TYPE_HANDLE16);
+}
+
+
+LIB_OBJECT_NODE_STORAGE_NAME* libObjectStorageNameSearch(
+               LIB_OBJECT_TABLE_STORAGE_NAME* pTable,
+               S_STORAGE_NAME* pStorageName)
+{
+   return (LIB_OBJECT_NODE_STORAGE_NAME*)libObjectSearch(
+      (LIB_OBJECT_NODE*)pTable->pRoot, 0, pStorageName, LIB_OBJECT_NODE_TYPE_STORAGE_NAME);
+}
+
+LIB_OBJECT_NODE_FILENAME* libObjectFilenameSearch(
+               LIB_OBJECT_TABLE_FILENAME* pTable,
+               uint8_t* pFilename,
+               uint32_t  nFilenameLength)
+{
+   return (LIB_OBJECT_NODE_FILENAME*)libObjectSearch(
+      (LIB_OBJECT_NODE*)pTable->pRoot, nFilenameLength, pFilename, LIB_OBJECT_NODE_TYPE_FILENAME);
+}
+
+/* -----------------------------------------------------------------------
+   Add functions
+   -----------------------------------------------------------------------*/
+
+/* Polymorphic add function. Add the node at the end of the linked list */
+static bool libObjectAdd(
+   LIB_OBJECT_NODE** ppRoot,
+   LIB_OBJECT_NODE* pNew,
+   LIB_OBJECT_NODE_TYPE eNodeType)
+{
+   LIB_OBJECT_NODE* pRoot;
+   LIB_OBJECT_NODE* pLast;
+   if (*ppRoot == NULL)
+   {
+      *ppRoot = pNew;
+      pNew->pNext = pNew;
+      pNew->pPrevious = pNew;
+      if (eNodeType == LIB_OBJECT_NODE_TYPE_HANDLE16)
+      {
+         pNew->key.nHandle = 1;
+      }
+      return true;
+   }
+   else
+   {
+      pRoot = *ppRoot;
+      pLast = pRoot->pPrevious;
+      if (eNodeType == LIB_OBJECT_NODE_TYPE_HANDLE16)
+      {
+         if (pLast->key.nHandle == LIB_OBJECT_HANDLE16_MAX)
+         {
+            /* We cannot just assign last handle + 1 because it will
+               overflow. So, scan the whole list */
+            goto scan_list;
+         }
+         pNew->key.nHandle = pLast->key.nHandle + 1;
+      }
+      pLast->pNext = pNew;
+      pNew->pPrevious = pLast;
+      pNew->pNext = pRoot;
+      pRoot->pPrevious = pNew;
+      return true;
+   }
+scan_list:
+   {
+      LIB_OBJECT_NODE* pNode = pRoot;
+      uint32_t nFreeHandle = 1;
+      do
+      {
+         if (pNode->key.nHandle > nFreeHandle)
+         {
+            /* nMaxHandle+1 is not allocated. Insert pNew just before pNode */
+            pNew->key.nHandle = nFreeHandle;
+            pNew->pNext = pNode;
+            pNew->pPrevious = pNode->pPrevious;
+            pNode->pPrevious->pNext = pNew;
+            pNode->pPrevious = pNew;
+            if (pNode == pRoot)
+            {
+               /* Special case, pNew is the new root */
+               *ppRoot = pNew;
+            }
+            return true;
+         }
+         pNode = pNode->pNext;
+         nFreeHandle++;
+      }
+      while (pNode != pRoot);
+      /* No free handle */
+      return false;
+   }
+}
+
+bool libObjectHandle16Add(
+               LIB_OBJECT_TABLE_HANDLE16* pTable,
+               LIB_OBJECT_NODE_HANDLE16* pObject)
+{
+   return libObjectAdd(
+      (LIB_OBJECT_NODE**)&pTable->pRoot,
+      (LIB_OBJECT_NODE*)pObject,
+      LIB_OBJECT_NODE_TYPE_HANDLE16);
+}
+
+
+void libObjectStorageNameAdd(
+               LIB_OBJECT_TABLE_STORAGE_NAME* pTable,
+               LIB_OBJECT_NODE_STORAGE_NAME* pObject)
+{
+   libObjectAdd(
+      (LIB_OBJECT_NODE**)&pTable->pRoot,
+      (LIB_OBJECT_NODE*)pObject,
+      LIB_OBJECT_NODE_TYPE_STORAGE_NAME);
+}
+
+
+void libObjectFilenameAdd(
+               LIB_OBJECT_TABLE_FILENAME* pTable,
+               LIB_OBJECT_NODE_FILENAME* pObject)
+{
+   libObjectAdd(
+      (LIB_OBJECT_NODE**)&pTable->pRoot,
+      (LIB_OBJECT_NODE*)pObject,
+      LIB_OBJECT_NODE_TYPE_FILENAME);
+}
+
+
+void libObjectUnindexedAdd(
+         LIB_OBJECT_TABLE_UNINDEXED* pTable,
+         LIB_OBJECT_NODE_UNINDEXED* pObject)
+{
+   libObjectAdd(
+      (LIB_OBJECT_NODE**)&pTable->pRoot,
+      (LIB_OBJECT_NODE*)pObject,
+      LIB_OBJECT_NODE_TYPE_UNINDEXED);
+}
+
+
+/* -----------------------------------------------------------------------
+   Remove functions
+   -----------------------------------------------------------------------*/
+static void libObjectRemove(LIB_OBJECT_NODE** ppRoot, LIB_OBJECT_NODE* pObject)
+{
+   LIB_OBJECT_NODE* pPrevious = pObject->pPrevious;
+   LIB_OBJECT_NODE* pNext = pObject->pNext;
+
+   pPrevious->pNext = pNext;
+   pNext->pPrevious = pPrevious;
+
+   if (pPrevious == pObject)
+   {
+      /* Removed the last object in the table */
+      *ppRoot = NULL;
+   }
+   else if (pObject == *ppRoot)
+   {
+      /* Removed the first object in the list */
+      *ppRoot = pNext;
+   }
+}
+
+static LIB_OBJECT_NODE* libObjectRemoveOne(LIB_OBJECT_NODE** ppRoot)
+{
+   if (*ppRoot == NULL)
+   {
+      return NULL;
+   }
+   else
+   {
+      LIB_OBJECT_NODE* pObject = *ppRoot;
+      libObjectRemove(ppRoot, pObject);
+      return pObject;
+   }
+}
+
+void libObjectHandle16Remove(
+               LIB_OBJECT_TABLE_HANDLE16* pTable,
+               LIB_OBJECT_NODE_HANDLE16* pObject)
+{
+   libObjectRemove((LIB_OBJECT_NODE**)&pTable->pRoot, (LIB_OBJECT_NODE*)pObject);
+   pObject->nHandle = 0;
+}
+
+LIB_OBJECT_NODE_HANDLE16* libObjectHandle16RemoveOne(
+               LIB_OBJECT_TABLE_HANDLE16* pTable)
+{
+   LIB_OBJECT_NODE_HANDLE16* pObject = (LIB_OBJECT_NODE_HANDLE16*)libObjectRemoveOne((LIB_OBJECT_NODE**)&pTable->pRoot);
+   if (pObject != NULL)
+   {
+      pObject->nHandle = 0;
+   }
+   return pObject;
+}
+
+void libObjectStorageNameRemove(
+               LIB_OBJECT_TABLE_STORAGE_NAME* pTable,
+               LIB_OBJECT_NODE_STORAGE_NAME* pObject)
+{
+   libObjectRemove((LIB_OBJECT_NODE**)&pTable->pRoot, (LIB_OBJECT_NODE*)pObject);
+}
+
+LIB_OBJECT_NODE_STORAGE_NAME* libObjectStorageNameRemoveOne(
+               LIB_OBJECT_TABLE_STORAGE_NAME* pTable)
+{
+   return (LIB_OBJECT_NODE_STORAGE_NAME*)libObjectRemoveOne((LIB_OBJECT_NODE**)&pTable->pRoot);
+}
+
+void libObjectFilenameRemove(
+               LIB_OBJECT_TABLE_FILENAME* pTable,
+               LIB_OBJECT_NODE_FILENAME* pObject)
+{
+   libObjectRemove((LIB_OBJECT_NODE**)&pTable->pRoot, (LIB_OBJECT_NODE*)pObject);
+}
+
+LIB_OBJECT_NODE_FILENAME* libObjectFilenameRemoveOne(
+               LIB_OBJECT_TABLE_FILENAME* pTable)
+{
+   return (LIB_OBJECT_NODE_FILENAME*)libObjectRemoveOne((LIB_OBJECT_NODE**)&pTable->pRoot);
+}
+
+void libObjectUnindexedRemove(
+         LIB_OBJECT_TABLE_UNINDEXED* pTable,
+         LIB_OBJECT_NODE_UNINDEXED* pObject)
+{
+   libObjectRemove((LIB_OBJECT_NODE**)&pTable->pRoot, (LIB_OBJECT_NODE*)pObject);
+}
+
+LIB_OBJECT_NODE_UNINDEXED* libObjectUnindexedRemoveOne(LIB_OBJECT_TABLE_UNINDEXED* pTable)
+{
+   return (LIB_OBJECT_NODE_UNINDEXED*)libObjectRemoveOne((LIB_OBJECT_NODE**)&pTable->pRoot);
+}
+
+
+/* -----------------------------------------------------------------------
+   Get-next functions
+   -----------------------------------------------------------------------*/
+
+static LIB_OBJECT_NODE* libObjectNext(LIB_OBJECT_NODE* pRoot, LIB_OBJECT_NODE* pObject)
+{
+   if (pObject == NULL)
+   {
+      return pRoot;
+   }
+   else if (pObject == pRoot->pPrevious)
+   {
+      return NULL;
+   }
+   else
+   {
+      return pObject->pNext;
+   }
+}
+
+
+LIB_OBJECT_NODE_HANDLE16* libObjectHandle16Next(
+               LIB_OBJECT_TABLE_HANDLE16* pTable,
+               LIB_OBJECT_NODE_HANDLE16* pObject)
+{
+   return (LIB_OBJECT_NODE_HANDLE16*)libObjectNext((LIB_OBJECT_NODE*)pTable->pRoot, (LIB_OBJECT_NODE*)pObject);
+}
+
+LIB_OBJECT_NODE_STORAGE_NAME* libObjectStorageNameNext(
+               LIB_OBJECT_TABLE_STORAGE_NAME* pTable,
+               LIB_OBJECT_NODE_STORAGE_NAME* pObject)
+{
+   return (LIB_OBJECT_NODE_STORAGE_NAME*)libObjectNext((LIB_OBJECT_NODE*)pTable->pRoot, (LIB_OBJECT_NODE*)pObject);
+}
+
+LIB_OBJECT_NODE_FILENAME* libObjectFilenameNext(
+               LIB_OBJECT_TABLE_FILENAME* pTable,
+               LIB_OBJECT_NODE_FILENAME* pObject)
+{
+   return (LIB_OBJECT_NODE_FILENAME*)libObjectNext((LIB_OBJECT_NODE*)pTable->pRoot, (LIB_OBJECT_NODE*)pObject);
+}
+
+LIB_OBJECT_NODE_UNINDEXED* libObjectUnindexedNext(
+               LIB_OBJECT_TABLE_UNINDEXED* pTable,
+               LIB_OBJECT_NODE_UNINDEXED* pObject)
+{
+   return (LIB_OBJECT_NODE_UNINDEXED*)libObjectNext((LIB_OBJECT_NODE*)pTable->pRoot, (LIB_OBJECT_NODE*)pObject);
+}
diff --git a/security/tf_crypto_sst/lib_object.h b/security/tf_crypto_sst/lib_object.h
new file mode 100644
index 0000000..5abb834
--- /dev/null
+++ b/security/tf_crypto_sst/lib_object.h
@@ -0,0 +1,348 @@
+/**
+ * Copyright(c) 2011 Trusted Logic.   All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *  * Neither the name Trusted Logic nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef   __LIB_OBJECT_H__
+#define   __LIB_OBJECT_H__
+
+#include "s_type.h"
+
+typedef struct
+{
+   /* Type of storage: See S_STORAGE_TYPE_XXX */
+   uint32_t nStorageType;
+
+   /* Login type of the client: See S_LOGIN_XXX */
+   uint32_t nLoginType;
+
+   /* Identifier of the client (secure or non-secure client) */
+   S_UUID sClientUUID;
+}
+S_STORAGE_NAME;
+
+
+/**
+ * This library defines three types of objects and keys:
+ * - objects identified by a 16-bit handle
+ * - objects identified by a S_STORAGE_NAME
+ * - objects identified by a filename, which is a variable-size up-to-64 bytes byte array
+ * - unindexed objects
+ **/
+
+/* -------------------------------------------------------------------------
+   Useful macro to get a structure from a pointer to one of its fields.
+
+   Typical usage:
+   typedef struct
+   {
+      LIB_OBJECT_NODE_HANDLE16  sNodeInHandleTable;
+      LIB_OBJECT_NODE_UNINDEXED sNodeInList;
+   }
+   CONTEXT;
+
+   LIB_OBJECT_CONTAINER_OF(libObjectUnindexedNext(pList, pObject), CONTEXT, sNodeInList)
+
+
+   -------------------------------------------------------------------------*/
+#define LIB_OBJECT_CONTAINER_OF(ptr, type, member) (((type*)(((char*)(ptr)) - offsetof(type, member))))
+
+
+/* -------------------------------------------------------------------------
+   Table of objects indexed by 16-bit handles
+   -------------------------------------------------------------------------*/
+
+#define LIB_OBJECT_HANDLE16_MAX ((uint16_t)0xFFFF)
+
+/**
+ * NODE of an object in a table indexed by 16-bit handles
+ **/
+typedef struct
+{
+   /* Implementation-defined fields */
+   uint32_t _l[2];
+
+   /* Public field */
+   uint16_t   nHandle;
+}
+LIB_OBJECT_NODE_HANDLE16;
+
+/**
+ * A table of objects indexed by 16-bit handles
+ **/
+typedef struct
+{
+   LIB_OBJECT_NODE_HANDLE16* pRoot;
+}
+LIB_OBJECT_TABLE_HANDLE16;
+
+/**
+ * Add an object in a handle table. This function also
+ * assigns a new handle value to the object. The handle
+ * is guaranteed to be unique among all the objects
+ * in the table and non-zero.
+ *
+ * Returns false if the maximum number of handles has been reached
+ *    (i.e., there are already 65535 objects in the table)
+ **/
+bool libObjectHandle16Add(
+               LIB_OBJECT_TABLE_HANDLE16* pTable,
+               LIB_OBJECT_NODE_HANDLE16* pObject);
+
+/**
+ * Search an object by its handle. Return NULL if the
+ * object is not found
+ **/
+LIB_OBJECT_NODE_HANDLE16* libObjectHandle16Search(
+               LIB_OBJECT_TABLE_HANDLE16* pTable,
+               uint32_t nHandle);
+
+/**
+ * Remove an object from a handle table.
+ *
+ * The object must be part of the table
+ **/
+void libObjectHandle16Remove(
+               LIB_OBJECT_TABLE_HANDLE16* pTable,
+               LIB_OBJECT_NODE_HANDLE16* pObject);
+
+/**
+ * Remove one object from the table. This is useful when
+ * you want to destroy all the objects in the table.
+ *
+ * Returns NULL if the table is empty
+ **/
+LIB_OBJECT_NODE_HANDLE16* libObjectHandle16RemoveOne(
+               LIB_OBJECT_TABLE_HANDLE16* pTable);
+
+/**
+ * Get the object following pObject in the handle table.
+ * If pObject is NULL, return the first object in the list
+ * Return NULL if the object is the last in the table
+ **/
+LIB_OBJECT_NODE_HANDLE16* libObjectHandle16Next(
+               LIB_OBJECT_TABLE_HANDLE16* pTable,
+               LIB_OBJECT_NODE_HANDLE16* pObject);
+
+/* -------------------------------------------------------------------------
+   Table of objects indexed by storage name
+   -------------------------------------------------------------------------*/
+
+/**
+ * NODE of an object in a table indexed by storage name
+ **/
+typedef struct
+{
+   /* Implementation-defined fields */
+   uint32_t _l[2];
+
+   /* Public fields */
+   S_STORAGE_NAME sStorageName;
+}
+LIB_OBJECT_NODE_STORAGE_NAME;
+
+/**
+ * A table of objects indexed by storage name
+ **/
+typedef struct
+{
+   LIB_OBJECT_NODE_STORAGE_NAME* pRoot;
+}
+LIB_OBJECT_TABLE_STORAGE_NAME;
+
+/**
+ * Add an object in a storage name table.
+ *
+ * The object must not be part of the table yet. The caller
+ * must have set pObject->sStorageName with the storage name
+ **/
+void libObjectStorageNameAdd(
+               LIB_OBJECT_TABLE_STORAGE_NAME* pTable,
+               LIB_OBJECT_NODE_STORAGE_NAME* pObject);
+
+/**
+ * Search an object by its storage name. Return NULL if the
+ * object is not found
+ **/
+LIB_OBJECT_NODE_STORAGE_NAME* libObjectStorageNameSearch(
+               LIB_OBJECT_TABLE_STORAGE_NAME* pTable,
+               S_STORAGE_NAME* pStorageName);
+
+/**
+ * Remove an object from a storage name table.
+ *
+ * The object must be part of the table
+ **/
+void libObjectStorageNameRemove(
+               LIB_OBJECT_TABLE_STORAGE_NAME* pTable,
+               LIB_OBJECT_NODE_STORAGE_NAME* pObject);
+
+/**
+ * Remove one object from the table. This is useful when
+ * you want to destroy all the objects in the table
+ * Returns NULL if the table is empty
+ **/
+LIB_OBJECT_NODE_STORAGE_NAME* libObjectStorageNameRemoveOne(
+               LIB_OBJECT_TABLE_STORAGE_NAME* pTable);
+
+/**
+ * Get the object following pObject in the storage name table.
+ * If pObject is NULL, return the first object
+ * Return NULL if the object is the last in the table
+ **/
+LIB_OBJECT_NODE_STORAGE_NAME* libObjectStorageNameNext(
+               LIB_OBJECT_TABLE_STORAGE_NAME* pTable,
+               LIB_OBJECT_NODE_STORAGE_NAME* pObject);
+
+/* -------------------------------------------------------------------------
+   Table of objects indexed by filenames
+   -------------------------------------------------------------------------*/
+
+/**
+ * NODE of an object in a table indexed by filenames (varsize up-to-64 bytes)
+ **/
+typedef struct
+{
+   /* Implementation-defined fields */
+   uint32_t _l[2];
+
+   /* Public fields */
+   uint8_t  sFilename[64];
+   uint8_t  nFilenameLength;
+}
+LIB_OBJECT_NODE_FILENAME;
+
+/**
+ * A table of objects indexed by filenames
+ **/
+typedef struct
+{
+   LIB_OBJECT_NODE_FILENAME* pRoot;
+}
+LIB_OBJECT_TABLE_FILENAME;
+
+/**
+ * Add an object in a filename table.
+ *
+ * The object must not be part of the table yet. The caller
+ * must have set pObject->sFilename and pObject->nFilenameLength
+ * with the object filename
+ **/
+void libObjectFilenameAdd(
+               LIB_OBJECT_TABLE_FILENAME* pTable,
+               LIB_OBJECT_NODE_FILENAME* pObject);
+
+/**
+ * Search an object by its filename. Return NULL if the
+ * object is not found
+ **/
+LIB_OBJECT_NODE_FILENAME* libObjectFilenameSearch(
+               LIB_OBJECT_TABLE_FILENAME* pTable,
+               uint8_t* pFilename,
+               uint32_t  nFilenameLength);
+
+/**
+ * Remove an object from a filename table.
+ *
+ * The object must be part of the table
+ **/
+void libObjectFilenameRemove(
+               LIB_OBJECT_TABLE_FILENAME* pTable,
+               LIB_OBJECT_NODE_FILENAME* pObject);
+
+/**
+ * Remove one element from the table and return it. This is useful when
+ * you want to destroy all the objects in the table
+ * Returns NULL if the table is empty
+ **/
+LIB_OBJECT_NODE_FILENAME* libObjectFilenameRemoveOne(
+               LIB_OBJECT_TABLE_FILENAME* pTable);
+
+/**
+ * Get the object following pObject in the filename table.
+ * If pObject is NULL, return the first object
+ * Return NULL if the object is the last in the table
+ **/
+LIB_OBJECT_NODE_FILENAME* libObjectFilenameNext(
+               LIB_OBJECT_TABLE_FILENAME* pTable,
+               LIB_OBJECT_NODE_FILENAME* pObject);
+
+/* -------------------------------------------------------------------------
+   Unindexed table of objects
+   -------------------------------------------------------------------------*/
+/**
+ * NODE of an unindexed object
+ **/
+typedef struct
+{
+   /* Implementation-defined fields */
+   uint32_t _l[2];
+}
+LIB_OBJECT_NODE_UNINDEXED;
+
+/**
+ * A table of unindexed objects
+ **/
+typedef struct
+{
+   LIB_OBJECT_NODE_UNINDEXED* pRoot;
+}
+LIB_OBJECT_TABLE_UNINDEXED;
+
+
+/**
+ * Add an object in an unindexed table. The object must not be part of the table yet.
+ **/
+void libObjectUnindexedAdd(
+         LIB_OBJECT_TABLE_UNINDEXED* pTable,
+         LIB_OBJECT_NODE_UNINDEXED* pObject);
+
+/**
+ * Remove an object from an unindexed table. The object must be part of the table.
+ **/
+void libObjectUnindexedRemove(
+         LIB_OBJECT_TABLE_UNINDEXED* pTable,
+         LIB_OBJECT_NODE_UNINDEXED* pObject);
+
+/**
+ * Remove one object in the table. This is useful when you want to destroy all objects
+ * in the table.
+ * Returns NULL if the table is empty
+ **/
+LIB_OBJECT_NODE_UNINDEXED* libObjectUnindexedRemoveOne(LIB_OBJECT_TABLE_UNINDEXED* pTable);
+
+/**
+ * Get the object following pObject in the table.
+ * If pObject is NULL, return the first object
+ * Return NULL if the object is the last in the table
+ **/
+LIB_OBJECT_NODE_UNINDEXED* libObjectUnindexedNext(
+               LIB_OBJECT_TABLE_UNINDEXED* pTable,
+               LIB_OBJECT_NODE_UNINDEXED* pObject);
+
+#endif /* __LIB_OBJECT_H__ */
diff --git a/security/tf_crypto_sst/mtc.c b/security/tf_crypto_sst/mtc.c
new file mode 100644
index 0000000..2be4870
--- /dev/null
+++ b/security/tf_crypto_sst/mtc.c
@@ -0,0 +1,274 @@
+/**
+ * Copyright(c) 2011 Trusted Logic.   All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *  * Neither the name Trusted Logic nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define MTC_EXPORTS
+#include "mtc.h"
+
+/* Included for the TEE management */
+#include "pkcs11_internal.h"
+
+
+/*------------------------------------------------------------------------------
+   Defines
+------------------------------------------------------------------------------*/
+
+/**
+ * The magic word.
+ */
+#define MTC_SESSION_MAGIC  ( (uint32_t)0x4D544300 )   /* "MTC\0" */
+
+/**
+ * The MTC session context
+ */
+typedef struct
+{
+   /* Magic word, must be set to {MTC_SESSION_MAGIC}. */
+   uint32_t    nMagicWord;
+
+   /* MTC Identifier */
+   uint32_t nCounterIdentifier;
+
+   /* TEEC session and cryptoki session */
+   TEEC_Session sSession;
+   uint32_t     hCryptoSession;
+
+} MTC_SESSION_CONTEXT;
+
+
+static bool g_bMTCInitialized = false;
+
+
+/*------------------------------------------------------------------------------
+   Static functions
+------------------------------------------------------------------------------*/
+
+static S_RESULT static_getMonotonicCounter(S_HANDLE hCounter,
+                                           S_MONOTONIC_COUNTER_VALUE* psValue,
+                                           bool bIncrement)
+{
+   TEEC_Result          nError;
+   TEEC_Operation       sOperation;
+   MTC_SESSION_CONTEXT* pSession = NULL;
+   uint32_t             nCommandID;
+
+   if (!g_bMTCInitialized)
+   {
+      return S_ERROR_BAD_STATE;
+   }
+
+   pSession = (MTC_SESSION_CONTEXT *)hCounter;
+   if ((pSession == NULL) || (pSession->nMagicWord != MTC_SESSION_MAGIC))
+   {
+      return S_ERROR_BAD_PARAMETERS;
+   }
+
+   if (bIncrement)
+   {
+      nCommandID = SERVICE_SYSTEM_PKCS11_INCREMENT_MTC_COMMAND_ID;
+   }
+   else
+   {
+      nCommandID = SERVICE_SYSTEM_PKCS11_GET_MTC_COMMAND_ID;
+   }
+
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INOUT, TEEC_NONE, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].value.a = pSession->nCounterIdentifier;
+   sOperation.params[0].value.b = 0;
+   nError = TEEC_InvokeCommand(&pSession->sSession,
+                            (pSession->hCryptoSession << 16 ) |
+                              (nCommandID & 0x00007FFF),
+                            &sOperation,
+                            NULL);
+
+   psValue->nLow  = sOperation.params[0].value.a;
+   psValue->nHigh = sOperation.params[0].value.b;
+
+   return nError;
+}
+
+/*------------------------------------------------------------------------------
+   API
+------------------------------------------------------------------------------*/
+
+MTC_EXPORT S_RESULT SMonotonicCounterInit(void)
+{
+   TEEC_Result nTeeError;
+
+   stubMutexLock();
+   if (g_bMTCInitialized)
+   {
+      nTeeError = TEEC_SUCCESS;
+   }
+   else
+   {
+      nTeeError = stubInitializeContext();
+      if (nTeeError == TEEC_SUCCESS)
+      {
+         g_bMTCInitialized = true;
+      }
+   }
+   stubMutexUnlock();
+
+   return nTeeError;
+}
+
+MTC_EXPORT void SMonotonicCounterTerminate(void)
+{
+   stubMutexLock();
+   if (g_bMTCInitialized)
+   {
+      stubFinalizeContext();
+      g_bMTCInitialized = false;
+   }
+   stubMutexUnlock();
+}
+
+MTC_EXPORT S_RESULT SMonotonicCounterOpen(
+                 uint32_t nCounterIdentifier,
+                 OUT S_HANDLE* phCounter)
+{
+   TEEC_Result                nError;
+   TEEC_Operation             sOperation;
+   MTC_SESSION_CONTEXT*       pSession = NULL;
+   S_MONOTONIC_COUNTER_VALUE  nCounterValue;
+
+   if (phCounter == NULL)
+   {
+      return S_ERROR_BAD_PARAMETERS;
+   }
+
+   *phCounter = S_HANDLE_NULL;
+
+   if (!g_bMTCInitialized)
+   {
+      return S_ERROR_BAD_STATE;
+   }
+
+   if (nCounterIdentifier != S_MONOTONIC_COUNTER_GLOBAL)
+   {
+      return S_ERROR_ITEM_NOT_FOUND;
+   }
+
+   pSession = (MTC_SESSION_CONTEXT*)malloc(sizeof(MTC_SESSION_CONTEXT));
+   if (pSession == NULL)
+   {
+      return S_ERROR_OUT_OF_MEMORY;
+   }
+   memset(pSession, 0, sizeof(MTC_SESSION_CONTEXT));
+   pSession->nMagicWord = MTC_SESSION_MAGIC;
+
+   /* Open a TEE session with the system service */
+   nError = TEEC_OpenSession(&g_sContext,
+                             &pSession->sSession,
+                             &SERVICE_UUID,
+                             TEEC_LOGIN_PUBLIC,
+                             NULL,
+                             NULL, /* No operation parameters */
+                             NULL);
+   if (nError != TEEC_SUCCESS)
+   {
+      goto error;
+   }
+
+   /* Open a cryptoki session */
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INOUT, TEEC_NONE, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].value.a = CKV_TOKEN_SYSTEM_SHARED;
+   sOperation.params[0].value.b = CKF_RW_SESSION | CKF_SERIAL_SESSION;
+   nError = TEEC_InvokeCommand(&pSession->sSession,
+                               SERVICE_SYSTEM_PKCS11_C_OPEN_SESSION_COMMAND_ID & 0x00007FFF,
+                               &sOperation,
+                               NULL);
+   if (nError != TEEC_SUCCESS)
+   {
+      TEEC_CloseSession(&pSession->sSession);
+      goto error;
+   }
+
+   pSession->hCryptoSession = sOperation.params[0].value.a;
+   pSession->nCounterIdentifier = nCounterIdentifier;
+
+   nError = SMonotonicCounterGet((S_HANDLE)pSession, &nCounterValue);
+   if (nError != TEEC_SUCCESS)
+   {
+      SMonotonicCounterClose((S_HANDLE)pSession);
+      return nError;
+   }
+
+   *phCounter = (S_HANDLE)pSession;
+
+   return TEEC_SUCCESS;
+
+error:
+   free(pSession);
+   return nError;
+}
+
+MTC_EXPORT void SMonotonicCounterClose(S_HANDLE hCounter)
+{
+   MTC_SESSION_CONTEXT* pSession;
+
+   if (!g_bMTCInitialized)
+   {
+      return;
+   }
+
+   pSession = (MTC_SESSION_CONTEXT *)hCounter;
+   if ((pSession == NULL) || (pSession->nMagicWord != MTC_SESSION_MAGIC))
+   {
+      return;
+   }
+
+   (void)TEEC_InvokeCommand(&pSession->sSession,
+                            (pSession->hCryptoSession << 16 ) |
+                              (SERVICE_SYSTEM_PKCS11_C_CLOSE_SESSION_COMMAND_ID & 0x00007FFF),
+                            NULL, /* No operation parameters */
+                            NULL);
+
+   TEEC_CloseSession(&pSession->sSession);
+   free(pSession);
+}
+
+MTC_EXPORT S_RESULT SMonotonicCounterGet(
+                 S_HANDLE hCounter,
+                 S_MONOTONIC_COUNTER_VALUE* psCurrentValue)
+{
+   return static_getMonotonicCounter(hCounter, psCurrentValue, false);
+}
+
+MTC_EXPORT S_RESULT SMonotonicCounterIncrement(
+                 S_HANDLE hCounter,
+                 S_MONOTONIC_COUNTER_VALUE* psNewValue)
+{
+   return static_getMonotonicCounter(hCounter, psNewValue, true);
+}
diff --git a/security/tf_crypto_sst/pkcs11_global.c b/security/tf_crypto_sst/pkcs11_global.c
new file mode 100644
index 0000000..f7c491d
--- /dev/null
+++ b/security/tf_crypto_sst/pkcs11_global.c
@@ -0,0 +1,275 @@
+/**
+ * Copyright(c) 2011 Trusted Logic.   All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *  * Neither the name Trusted Logic nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Implementation Notes:
+ *
+ * This API is NOT thread-safe. Indeed this Cryptoki implementation
+ * only supports option 1 defined in PKCS#11, section 6.5.2:
+ * "The application can specify that it will not be accessing the library concurrently
+ * from multiple threads, and so the library need not worry about performing any type
+ * of locking for the sake of thread-safety."
+ */
+
+#include "pkcs11_internal.h"
+
+/* ------------------------------------------------------------------------
+    System Service UUID
+------------------------------------------------------------------------- */
+const TEEC_UUID SERVICE_UUID = SERVICE_SYSTEM_UUID;
+
+/* ------------------------------------------------------------------------
+    Definition of the global TEE Context
+------------------------------------------------------------------------- */
+TEEC_Context g_sContext;
+/* A mutex that protects the access to the global context and to the
+   g_bContextRefCounter flag */
+LIB_MUTEX g_sContextMutex = LIB_MUTEX_INITIALIZER;
+/* Whether the context has already been initialized or not */
+uint32_t  g_nContextRefCounter = 0;
+
+bool g_bCryptokiInitialized = false;
+
+/* ------------------------------------------------------------------------
+   Internal global TEE context management
+------------------------------------------------------------------------- */
+
+void stubMutexLock(void)
+{
+   libMutexLock(&g_sContextMutex);
+}
+
+void stubMutexUnlock(void)
+{
+   libMutexUnlock(&g_sContextMutex);
+}
+
+/* This API must be protected by stubMutexLock/Unlock */
+TEEC_Result stubInitializeContext(void)
+{
+   TEEC_Result nTeeError;
+
+   if (g_nContextRefCounter)
+   {
+      g_nContextRefCounter ++;
+      return TEEC_SUCCESS;
+   }
+
+   nTeeError = TEEC_InitializeContext(NULL, &g_sContext);
+   if (nTeeError == TEEC_SUCCESS)
+   {
+      g_nContextRefCounter = 1;
+   }
+
+   return nTeeError;
+}
+
+/* This API must be protected by stubMutexLock/Unlock */
+void stubFinalizeContext(void)
+{
+   if (g_nContextRefCounter > 0)
+   {
+      g_nContextRefCounter --;
+   }
+
+   if (g_nContextRefCounter == 0)
+   {
+      TEEC_FinalizeContext(&g_sContext);
+      memset(&g_sContext, 0, sizeof(TEEC_Context));
+   }
+}
+
+
+/* ------------------------------------------------------------------------
+                          Internal monitor management
+------------------------------------------------------------------------- */
+/**
+* Check that hSession is a valid primary session,
+* or a valid secondary session attached to a valid primary session.
+*
+* input:
+*   S_HANDLE hSession: the session handle to check
+* output:
+*   bool* pBoolIsPrimarySession: a boolean set to true if the session is primary,
+*             set to false if the session if the session is secondary
+*   returned boolean: set to true iff :
+*              - either hSession is a valid primary session
+*              - or hSession is a valid secondary session attached to a valid primary session
+**/
+bool ckInternalSessionIsOpenedEx(S_HANDLE hSession, bool* pBoolIsPrimarySession)
+{
+   PPKCS11_SESSION_CONTEXT_HEADER   pHeader = (PPKCS11_SESSION_CONTEXT_HEADER)hSession;
+   PPKCS11_PRIMARY_SESSION_CONTEXT  pSession = NULL;
+
+   if ((pHeader == NULL) || (pHeader->nMagicWord != PKCS11_SESSION_MAGIC))
+   {
+      return FALSE;
+   }
+   if (pHeader->nSessionTag == PKCS11_PRIMARY_SESSION_TAG) /* primary session */
+   {
+      pSession = (PPKCS11_PRIMARY_SESSION_CONTEXT)pHeader;
+
+      *pBoolIsPrimarySession = true;
+
+      /* check that primary session is valid */
+      return (pSession->hCryptoSession != CK_INVALID_HANDLE);
+   }
+   else if (pHeader->nSessionTag == PKCS11_SECONDARY_SESSION_TAG) /*secondary session */
+   {
+      PPKCS11_SECONDARY_SESSION_CONTEXT pSecSession = (PPKCS11_SECONDARY_SESSION_CONTEXT)pHeader;
+
+      *pBoolIsPrimarySession = false;
+
+      /* check that primary session is still valid */
+      pSession = pSecSession->pPrimarySession;
+      if (  (pSession == NULL) ||
+            (pSession->sHeader.nMagicWord != PKCS11_SESSION_MAGIC) ||
+            (pSession->sHeader.nSessionTag != PKCS11_PRIMARY_SESSION_TAG))
+      {
+         return FALSE;
+      }
+
+      if (pSession->hCryptoSession == CK_INVALID_HANDLE)
+      {
+         return FALSE;
+      }
+
+      /* check that secondary session is valid */
+      return (pSecSession->hSecondaryCryptoSession != CK_INVALID_HANDLE);
+   }
+   else
+   {
+     return FALSE;
+   }
+}
+
+/* ------------------------------------------------------------------------
+                          Internal error management
+------------------------------------------------------------------------- */
+
+CK_RV ckInternalTeeErrorToCKError(TEEC_Result nError)
+{
+   switch (nError)
+   {
+      case TEEC_SUCCESS:
+         return CKR_OK;
+
+      case TEEC_ERROR_BAD_PARAMETERS:
+      case TEEC_ERROR_BAD_FORMAT:
+         return CKR_ARGUMENTS_BAD;
+      case TEEC_ERROR_OUT_OF_MEMORY:
+         return CKR_HOST_MEMORY;
+      case TEEC_ERROR_ACCESS_DENIED:
+         return CKR_TOKEN_NOT_PRESENT;
+      default:
+         return CKR_DEVICE_ERROR;
+   }
+}
+
+/* ------------------------------------------------------------------------
+                          Public Functions
+------------------------------------------------------------------------- */
+CK_RV PKCS11_EXPORT C_Initialize(CK_VOID_PTR pInitArgs)
+{
+   CK_RV       nErrorCode;
+   TEEC_Result nTeeError;
+
+   if (pInitArgs != NULL_PTR)
+   {
+      return CKR_ARGUMENTS_BAD;
+   }
+
+   stubMutexLock();
+   if (g_bCryptokiInitialized)
+   {
+      nErrorCode = CKR_CRYPTOKI_ALREADY_INITIALIZED;
+   }
+   else
+   {
+      nTeeError = stubInitializeContext();
+      if (nTeeError == TEEC_SUCCESS)
+      {
+         g_bCryptokiInitialized = true;
+      }
+      nErrorCode = ckInternalTeeErrorToCKError(nTeeError);
+   }
+   stubMutexUnlock();
+
+   return nErrorCode;
+}
+
+CK_RV PKCS11_EXPORT C_Finalize(CK_VOID_PTR pReserved)
+{
+   CK_RV nErrorCode;
+
+   if (pReserved != NULL_PTR)
+   {
+      return CKR_ARGUMENTS_BAD;
+   }
+
+   stubMutexLock();
+   if (g_bCryptokiInitialized)
+   {
+      stubFinalizeContext();
+      g_bCryptokiInitialized = false;
+      nErrorCode = CKR_OK;
+   }
+   else
+   {
+      nErrorCode = CKR_CRYPTOKI_NOT_INITIALIZED;
+   }
+   stubMutexUnlock();
+
+   return nErrorCode;
+}
+
+static const CK_INFO sImplementationInfo =
+{
+   {2, 20},         /* cryptokiVersion, spec 2.20 */
+   "Trusted Logic", /* manufacturerID */
+   0,               /* flags */
+   "PKCS#11",       /* libraryDescription */
+   {3, 0}           /* libraryVersion */
+};
+
+CK_RV PKCS11_EXPORT C_GetInfo(CK_INFO_PTR pInfo)
+{
+   if (!g_bCryptokiInitialized)
+   {
+      return CKR_CRYPTOKI_NOT_INITIALIZED;
+   }
+   if (pInfo == NULL_PTR)
+   {
+      return CKR_ARGUMENTS_BAD;
+   }
+
+   memcpy(pInfo, &sImplementationInfo, sizeof(CK_INFO));
+   return CKR_OK;
+}
diff --git a/security/tf_crypto_sst/pkcs11_internal.h b/security/tf_crypto_sst/pkcs11_internal.h
new file mode 100644
index 0000000..14ecf83
--- /dev/null
+++ b/security/tf_crypto_sst/pkcs11_internal.h
@@ -0,0 +1,137 @@
+/**
+ * Copyright(c) 2011 Trusted Logic.   All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *  * Neither the name Trusted Logic nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __PKCS11_INTERNAL_H__
+#define __PKCS11_INTERNAL_H__
+
+#define CRYPTOKI_EXPORTS
+#include "cryptoki.h"
+#include "service_system_protocol.h"
+
+#include "lib_object.h"
+#include "lib_mutex.h"
+#include "tee_client_api.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+
+/**
+ * The magic word.
+ */
+#define PKCS11_SESSION_MAGIC  ( (uint32_t)0x45EF683B )
+
+/**
+ * Computes required size to fit in a 4-bytes aligned buffer (at the end)
+ * If the size is a multiple of 4, just returns the size
+ * Otherwise, return the size so that the (end of the buffer)+1 is 4-bytes aligned.
+ */
+#define PKCS11_GET_SIZE_WITH_ALIGNMENT(a)  (uint32_t)(((uint32_t)a+3) & ~3)
+
+
+/**
+ * The System Service UUID used by the library
+ */
+extern const TEEC_UUID SERVICE_UUID;
+
+/**
+ * g_sContext: the global TEEC context used by the library
+ */
+extern TEEC_Context  g_sContext;
+
+void stubMutexLock(void);
+void stubMutexUnlock(void);
+TEEC_Result stubInitializeContext(void);
+void stubFinalizeContext(void);
+
+/** Whether the cryptoki library is initialized or not */
+extern bool g_bCryptokiInitialized;
+
+CK_RV ckInternalTeeErrorToCKError(TEEC_Result nError);
+
+#define PKCS11_PRIMARY_SESSION_TAG    1
+#define PKCS11_SECONDARY_SESSION_TAG  2
+
+typedef struct
+{
+   /*
+    * Magic word, must be set to {PKCS11_SESSION_MAGIC}.
+    */
+   uint32_t    nMagicWord;
+
+   /* nSessionTag must be set to {PKCS11_PRIMARY_SESSION_TAG} for primary session
+   *                          to {PKCS11_SECONDARY_SESSION_TAG} for secondary session */
+   uint32_t    nSessionTag;
+
+}PKCS11_SESSION_CONTEXT_HEADER, * PPKCS11_SESSION_CONTEXT_HEADER;
+
+/**
+ * The PKCS11 Primary session context
+ */
+typedef struct
+{
+   /* sHeader must be the first field of this structure */
+   PKCS11_SESSION_CONTEXT_HEADER sHeader;
+
+   /* TEEC session used for this cryptoki primary session.
+      Each primary session has its own TEEC session */
+   TEEC_Session sSession;
+   uint32_t     hCryptoSession;
+
+   /* Mutex to protect the table of secondary sessions */
+   LIB_MUTEX sSecondarySessionTableMutex;
+
+   /* Table of secondary sessions */
+   LIB_OBJECT_TABLE_HANDLE16 sSecondarySessionTable;
+
+} PKCS11_PRIMARY_SESSION_CONTEXT, * PPKCS11_PRIMARY_SESSION_CONTEXT;
+
+/**
+ * The PKCS11 Secondary session context
+ */
+typedef struct
+{
+   /* sHeader must be the first field of this structure */
+   PKCS11_SESSION_CONTEXT_HEADER sHeader;
+
+   /* Secondary session handle as returned by pkcs11 */
+   uint32_t       hSecondaryCryptoSession;
+
+   /* A node of the table of secondary sessions */
+   LIB_OBJECT_NODE_HANDLE16 sSecondarySessionNode;
+
+   /* pointer to the primary session */
+   PKCS11_PRIMARY_SESSION_CONTEXT* pPrimarySession;
+
+} PKCS11_SECONDARY_SESSION_CONTEXT, *PPKCS11_SECONDARY_SESSION_CONTEXT;
+
+bool ckInternalSessionIsOpenedEx(S_HANDLE hSession, bool* pBoolIsPrimarySession);
+
+#endif /* __PKCS11_INTERNAL_H__ */
diff --git a/security/tf_crypto_sst/pkcs11_object.c b/security/tf_crypto_sst/pkcs11_object.c
new file mode 100644
index 0000000..53caadc
--- /dev/null
+++ b/security/tf_crypto_sst/pkcs11_object.c
@@ -0,0 +1,1637 @@
+/**
+ * Copyright(c) 2011 Trusted Logic.   All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *  * Neither the name Trusted Logic nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "pkcs11_internal.h"
+
+/* ------------------------------------------------------------------------
+Internal Functions
+------------------------------------------------------------------------- */
+/**
+* Checks the following pre-conditions:
+* - cryptoki is initialized,
+* - hSession is valid (primary and/or secondary),
+* - the user is logged in.
+*
+* And updates handle values:
+*  IN/OUT : phSession
+*           IN  = Cryptoki external handle
+*           OUT = TFAPI handle = primary cryptoki session handle
+*  OUT    : phSecSession16Msb
+*           OUT = 0 for a primary session or
+*                 the secondary cryptoki session handle in the 16 MSB bits
+*/
+static CK_RV static_checkPreConditionsAndUpdateHandles(
+         CK_SESSION_HANDLE*   phSession,
+         uint32_t*            phCommandIDAndSession,
+         PPKCS11_PRIMARY_SESSION_CONTEXT* ppSession)
+{
+   bool  bIsPrimarySession;
+
+   /* Check Cryptoki is initialized */
+   if (!g_bCryptokiInitialized)
+   {
+      return CKR_CRYPTOKI_NOT_INITIALIZED;
+   }
+
+   if (phSession == NULL)
+   {
+      return CKR_SESSION_HANDLE_INVALID;
+   }
+
+   /* Check that the session is valid */
+   if (!ckInternalSessionIsOpenedEx(*phSession, &bIsPrimarySession))
+   {
+      return CKR_SESSION_HANDLE_INVALID;
+   }
+   /* previous check is fine, then update session handles */
+   if (bIsPrimarySession)
+   {
+      PPKCS11_PRIMARY_SESSION_CONTEXT pSession =
+         (PPKCS11_PRIMARY_SESSION_CONTEXT)(*phSession);
+
+      *phSession = pSession->hCryptoSession;
+      *phCommandIDAndSession = (pSession->hCryptoSession<<16)|(*phCommandIDAndSession&0x00007FFF);
+      *ppSession = pSession;
+   }
+   else
+   {
+      PPKCS11_SECONDARY_SESSION_CONTEXT pSecSession =
+         (PPKCS11_SECONDARY_SESSION_CONTEXT)(*phSession);
+
+      *phSession = pSecSession->pPrimarySession->hCryptoSession;
+      *phCommandIDAndSession = (pSecSession->hSecondaryCryptoSession<<16)|(1<<15)|(*phCommandIDAndSession&0x00007FFF);
+      *ppSession = pSecSession->pPrimarySession;
+   }
+
+   return CKR_OK;
+}
+
+/******************************************/
+/* The buffer must be freed by the caller */
+/******************************************/
+static CK_RV static_encodeTwoTemplates(
+   uint8_t**         ppBuffer,
+   uint32_t *        pBufferSize,
+   const uint32_t    nParamIndex,
+   CK_ATTRIBUTE*     pTemplate1,
+   CK_ULONG          ulCount1,
+   CK_ATTRIBUTE*     pTemplate2,
+   CK_ULONG          ulCount2)
+{
+   INPUT_TEMPLATE_ITEM  sItem;
+
+   uint32_t i;
+   uint32_t nDataOffset    = 0;
+   uint32_t nBufferIndex   = 0;
+   uint32_t nBufferSize    = 0;
+   uint8_t* pBuffer = NULL;
+   CK_RV    nErrorCode = CKR_OK;
+
+   if (ulCount1 == 0)
+   {
+      /* Nothing to do */
+      return CKR_OK;
+   }
+   if (pTemplate1 == NULL)
+   {
+      /* Nothing to do */
+      return CKR_OK;
+   }
+
+   /* First compute the total required buffer size that
+    * will contain the full templates (for the template 1 AND 2)
+    */
+   nBufferSize =  4 +                                    /* Nb Attributes */
+                  sizeof(INPUT_TEMPLATE_ITEM)*ulCount1;  /* The attributes items */
+   if (pTemplate2 != NULL)
+   {
+      nBufferSize += 4 +                                    /* Nb Attributes */
+                     sizeof(INPUT_TEMPLATE_ITEM)*ulCount2;  /* The attributes items */
+   }
+
+   /* First data (attribute values) on either template 1 or 2 will just be after the last item */
+   nDataOffset = nBufferSize;
+
+   for (i = 0; i < ulCount1; i++)
+   {
+      /* Each value will be aligned on 4 bytes.
+         This computation includes the spare bytes. */
+      nBufferSize += PKCS11_GET_SIZE_WITH_ALIGNMENT(pTemplate1[i].ulValueLen);
+   }
+   if (pTemplate2 != NULL)
+   {
+      for (i = 0; i < ulCount2; i++)
+      {
+         /* Each value will be aligned on 4 bytes.
+            This computation includes the spare bytes. */
+         nBufferSize += PKCS11_GET_SIZE_WITH_ALIGNMENT(pTemplate2[i].ulValueLen);
+      }
+   }
+
+   pBuffer = (uint8_t*)malloc(nBufferSize);
+   if (pBuffer == NULL)
+   {
+      /* Not enough memory */
+      return CKR_DEVICE_MEMORY;
+   }
+
+   memset(pBuffer, 0, nBufferSize);
+
+   /*
+    * First template
+    */
+   *(uint32_t*)(pBuffer + nBufferIndex) = ulCount1;
+   nBufferIndex += 4;
+   for (i = 0; i < ulCount1; i++)
+   {
+      sItem.attributeType     = (uint32_t)pTemplate1[i].type;
+      /* dataOffset = 0 means NULL buffer */
+      sItem.dataOffset        = ((pTemplate1[i].pValue == NULL) ? 0 : nDataOffset);
+      sItem.dataParamIndex    = nParamIndex; /* The parameter where we store the data (0 to 3) */
+      sItem.dataValueLen      = (uint32_t)pTemplate1[i].ulValueLen;
+      /* Copy the item */
+      memcpy(pBuffer + nBufferIndex, &sItem, sizeof(INPUT_TEMPLATE_ITEM));
+      nBufferIndex += sizeof(INPUT_TEMPLATE_ITEM);
+      if (pTemplate1[i].pValue != NULL)
+      {
+         /* Copy the data */
+         memcpy(pBuffer + nDataOffset, (uint8_t*)pTemplate1[i].pValue, (uint32_t)pTemplate1[i].ulValueLen);
+         /* Next data will be stored just after the previous one but aligned on 4 bytes */
+         nDataOffset += PKCS11_GET_SIZE_WITH_ALIGNMENT(pTemplate1[i].ulValueLen);
+         if ((nDataOffset & 0xC0000000) != 0)
+         {
+            /* We whould never go in this case, that means the dataOffset will not be able to store the offset correctly */
+            nErrorCode = CKR_DEVICE_ERROR;
+            goto error;
+         }
+      }
+   }
+
+   /*
+    * Second template
+    */
+   if (pTemplate2 != NULL)
+   {
+      *(uint32_t*)(pBuffer + nBufferIndex) = ulCount2;
+      nBufferIndex += 4;
+      for (i = 0; i < ulCount2; i++)
+      {
+         sItem.attributeType     = (uint32_t)pTemplate2[i].type;
+         /* dataOffset = 0 means NULL buffer */
+         sItem.dataOffset        = ((pTemplate2[i].pValue == NULL) ? 0 : nDataOffset);
+         sItem.dataParamIndex    = nParamIndex; /* The parameter where we store the data (0..3) */
+         sItem.dataValueLen      = (uint32_t)pTemplate2[i].ulValueLen;
+         /* Copy the item */
+         memcpy(pBuffer + nBufferIndex, &sItem, sizeof(INPUT_TEMPLATE_ITEM));
+         nBufferIndex += sizeof(INPUT_TEMPLATE_ITEM);
+         if (pTemplate2[i].pValue != NULL)
+         {
+            /* Copy the data */
+            memcpy(pBuffer + nDataOffset, (uint8_t*)pTemplate2[i].pValue, (uint32_t)pTemplate2[i].ulValueLen);
+            /* Next data will be stored just after the previous one but aligned on 4 bytes */
+            nDataOffset += PKCS11_GET_SIZE_WITH_ALIGNMENT(pTemplate2[i].ulValueLen);
+            if ((nDataOffset & 0xC0000000) != 0)
+            {
+               /* We whould never go in this case, that means the dataOffset will not be able to store the offset correctly */
+               nErrorCode = CKR_DEVICE_ERROR;
+               goto error;
+            }
+         }
+      }
+   }
+
+   *ppBuffer      = pBuffer;
+   *pBufferSize   = nBufferSize;
+
+   return CKR_OK;
+
+error:
+   free(pBuffer);
+   return nErrorCode;
+}
+
+/******************************************/
+/* The buffer must be freed by the caller */
+/******************************************/
+static CK_RV static_encodeTemplate(
+   uint8_t**         ppBuffer,
+   uint32_t*         pBufferSize,
+   const uint32_t    nParamIndex,
+   CK_ATTRIBUTE*     pTemplate,
+   CK_ULONG          ulCount)
+{
+   return static_encodeTwoTemplates(ppBuffer, pBufferSize, nParamIndex, pTemplate, ulCount, NULL, 0);
+}
+/* ----------------------------------------------------------------------- */
+
+static CK_RV static_C_CallInit(
+   uint32_t            nCommandID,
+   CK_SESSION_HANDLE   hSession,
+   const CK_MECHANISM* pMechanism,
+   CK_OBJECT_HANDLE    hKey)
+{
+   TEEC_Result    teeErr;
+   uint32_t       nErrorOrigin;
+   TEEC_Operation sOperation;
+   CK_RV          nErrorCode = CKR_OK;
+   uint32_t       nCommandIDAndSession = nCommandID;
+   uint32_t       nParamType2 = TEEC_NONE;
+   PPKCS11_PRIMARY_SESSION_CONTEXT pSession;
+
+   nErrorCode = static_checkPreConditionsAndUpdateHandles(&hSession, &nCommandIDAndSession, &pSession);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+   if (pMechanism == NULL)
+   {
+      return CKR_ARGUMENTS_BAD;
+   }
+
+   memset(&sOperation, 0, sizeof(TEEC_Operation));
+   sOperation.params[0].value.a = (uint32_t)pMechanism->mechanism;
+   if (nCommandID != SERVICE_SYSTEM_PKCS11_C_DIGESTINIT_COMMAND_ID)
+   {
+      sOperation.params[0].value.b = (uint32_t)hKey;
+
+   }
+   sOperation.params[1].tmpref.buffer = (uint8_t*)pMechanism->pParameter;
+   sOperation.params[1].tmpref.size   = (uint32_t)pMechanism->ulParameterLen;
+
+   /* Specific case of RSA OAEP */
+   if (((nCommandID == SERVICE_SYSTEM_PKCS11_C_ENCRYPTINIT_COMMAND_ID)
+      ||(nCommandID == SERVICE_SYSTEM_PKCS11_C_DECRYPTINIT_COMMAND_ID))
+      && (pMechanism->mechanism == CKM_RSA_PKCS_OAEP)
+      && (pMechanism->pParameter != NULL))
+   {
+      /* Add the source buffer of the RSA OAEP mechanism parameters */
+      nParamType2 = TEEC_MEMREF_TEMP_INPUT;
+      sOperation.params[2].tmpref.buffer = (uint8_t*)((CK_RSA_PKCS_OAEP_PARAMS_PTR)(pMechanism->pParameter))->pSourceData;
+      sOperation.params[2].tmpref.size   = (uint32_t) ((CK_RSA_PKCS_OAEP_PARAMS_PTR)(pMechanism->pParameter))->ulSourceDataLen;
+   }
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INPUT, TEEC_MEMREF_TEMP_INPUT, nParamType2, TEEC_NONE);
+   teeErr = TEEC_InvokeCommand(   &pSession->sSession,
+                                  nCommandIDAndSession,        /* commandID */
+                                  &sOperation,                 /* IN OUT operation */
+                                  &nErrorOrigin                /* OUT returnOrigin, optional */
+                                 );
+   nErrorCode = (nErrorOrigin == TEEC_ORIGIN_TRUSTED_APP ?
+                  teeErr :
+                  ckInternalTeeErrorToCKError(teeErr));
+
+   return nErrorCode;
+}
+
+/* ----------------------------------------------------------------------- */
+/**
+* If bSend, the pData buffer is sent to the service.
+* If bResult, a buffer is received, the convention described in
+* PKCS11 Section 11.2 applies for pResult and pulResultLen.
+* Specific function used for single operation
+*/
+static CK_RV static_C_CallForSingle(
+   uint32_t             nCommandID,
+   CK_SESSION_HANDLE    hSession,
+   const CK_BYTE*       pData,
+   CK_ULONG             ulDataLen,
+   CK_BYTE*             pResult,
+   CK_ULONG*            pulResultLen,
+   bool                 bSend,
+   bool                 bReceive)
+{
+   TEEC_Result       teeErr;
+   uint32_t          nErrorOrigin;
+   TEEC_Operation    sOperation;
+   CK_RV             nErrorCode = CKR_OK;
+   uint32_t          nCommandIDAndSession = nCommandID;
+   uint32_t          nParamType0 = TEEC_NONE;
+   uint32_t          nParamType1 = TEEC_NONE;
+   PPKCS11_PRIMARY_SESSION_CONTEXT pSession;
+
+   nErrorCode = static_checkPreConditionsAndUpdateHandles(&hSession, &nCommandIDAndSession, &pSession);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   memset(&sOperation, 0, sizeof(TEEC_Operation));
+
+   if (bSend)
+   {
+      nParamType0 = TEEC_MEMREF_TEMP_INPUT;
+      sOperation.params[0].tmpref.buffer = (uint8_t*)pData;
+      sOperation.params[0].tmpref.size   = (uint32_t)ulDataLen;
+   }
+
+   if (bReceive)
+   {
+      if (pulResultLen == NULL)
+      {
+         /* The P11 API Spec states that, in this case, the operation must be
+            aborted and the error code CKR_ARGUMENTS_BAD must be returned. We
+            achieve this result by sending an invalid parameter type */
+         nParamType1 = TEEC_NONE;
+      }
+      else if (pResult == NULL)
+      {
+         /* If pResult is NULL, the caller only wants the buffer length.
+            Send a NULL output memref */
+         nParamType1 = TEEC_MEMREF_TEMP_OUTPUT;
+         sOperation.params[1].tmpref.buffer = (uint8_t*)NULL;
+      }
+      else
+      {
+         /* send the result buffer information */
+         nParamType1 = TEEC_MEMREF_TEMP_OUTPUT;
+         sOperation.params[1].tmpref.buffer = (uint8_t*)pResult;
+         sOperation.params[1].tmpref.size   = (uint32_t)*pulResultLen;
+      }
+   }
+
+   sOperation.paramTypes = TEEC_PARAM_TYPES(nParamType0, nParamType1, TEEC_NONE, TEEC_NONE);
+   teeErr = TEEC_InvokeCommand(&pSession->sSession,
+                               nCommandIDAndSession,     /* commandID */
+                               &sOperation,              /* IN OUT operation */
+                               &nErrorOrigin             /* OUT returnOrigin, optional */
+                              );
+   if (teeErr != TEEC_SUCCESS)
+   {
+      nErrorCode = (nErrorOrigin == TEEC_ORIGIN_TRUSTED_APP ?
+                     teeErr :
+                     ckInternalTeeErrorToCKError(teeErr));
+      goto end;
+   }
+
+   /* Success */
+   nErrorCode = CKR_OK;
+
+ end:
+   if (bReceive)
+   {
+      if ((nErrorCode == CKR_OK) || (nErrorCode == CKR_BUFFER_TOO_SMALL))
+      {
+         /* The service has returned the actual result */
+         /* The data is already in pResult, we get the returned length */
+         *pulResultLen = sOperation.params[1].tmpref.size;
+      }
+   }
+
+   return nErrorCode;
+}
+
+/* ----------------------------------------------------------------------- */
+/**
+* If bSend, the pData buffer is sent to the service.
+* If bResult, a buffer is received, the convention described in
+* PKCS11 Section 11.2 applies for pResult and pulResultLen.
+* Specific function only used for update operations
+*/
+static CK_RV static_C_CallUpdate(
+   uint32_t             nCommandID,
+   CK_SESSION_HANDLE    hSession,
+   const CK_BYTE*       pData,
+   CK_ULONG             ulDataLen,
+   CK_BYTE*             pResult,
+   CK_ULONG*            pulResultLen,
+   bool                 bSend,
+   bool                 bReceive)
+{
+   TEEC_Result       teeErr;
+   uint32_t          nErrorOrigin;
+   TEEC_Operation    sOperation;
+   CK_RV             nErrorCode = CKR_OK;
+   uint32_t          nResultLen = 0;
+   uint32_t          nCommandIDAndSession = nCommandID;
+   uint32_t          nParamType0 = TEEC_NONE;
+   uint32_t          nParamType1 = TEEC_NONE;
+   PPKCS11_PRIMARY_SESSION_CONTEXT pSession;
+
+   nErrorCode = static_checkPreConditionsAndUpdateHandles(&hSession, &nCommandIDAndSession, &pSession);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   if (pulResultLen != NULL)
+   {
+      nResultLen = *pulResultLen;
+   }
+
+   memset(&sOperation, 0, sizeof(TEEC_Operation));
+
+   if (bSend)
+   {
+      nParamType0 = TEEC_MEMREF_TEMP_INPUT;
+      sOperation.params[0].tmpref.buffer = (void*)pData;
+      sOperation.params[0].tmpref.size   = ulDataLen;
+   }
+
+   if (bReceive)
+   {
+      if (pulResultLen == NULL)
+      {
+         /* The P11 API Spec states that, in this case, the operation must be
+            aborted and the error code CKR_ARGUMENTS_BAD must be returned. We
+            achieve this result by setting an invalid parameter type */
+         nParamType1 = TEEC_NONE;
+      }
+      else if (pResult == NULL)
+      {
+         /* If pResult is NULL, the caller only wants the output buffer length.
+            Pass a NULL output ref */
+         nParamType1 = TEEC_MEMREF_TEMP_OUTPUT;
+         sOperation.params[1].tmpref.buffer = NULL;
+      }
+      else
+      {
+         /* send the result buffer information */
+         nParamType1 = TEEC_MEMREF_TEMP_OUTPUT;
+         sOperation.params[1].tmpref.buffer = pResult;
+         sOperation.params[1].tmpref.size   = (uint32_t)*pulResultLen;
+      }
+   }
+
+   sOperation.paramTypes = TEEC_PARAM_TYPES(nParamType0, nParamType1, TEEC_NONE, TEEC_NONE);
+   teeErr = TEEC_InvokeCommand(   &pSession->sSession,
+                                  nCommandIDAndSession,        /* commandID */
+                                  &sOperation,                 /* IN OUT operation */
+                                  &nErrorOrigin                /* OUT returnOrigin, optional */
+                                 );
+   if (teeErr != TEEC_SUCCESS)
+   {
+      nErrorCode = (nErrorOrigin == TEEC_ORIGIN_TRUSTED_APP ?
+                     teeErr :
+                     ckInternalTeeErrorToCKError(teeErr));
+      goto end;
+   }
+
+   /* Success */
+   nErrorCode = CKR_OK;
+
+ end:
+   if (bReceive)
+   {
+      if ((nErrorCode == CKR_OK) || (nErrorCode == CKR_BUFFER_TOO_SMALL))
+      {
+         /* The service has returned the actual result */
+         /* The data is already in pResult, we get the returned length */
+         *pulResultLen = sOperation.params[1].tmpref.size;
+      }
+   }
+
+   return nErrorCode;
+}
+
+/* Splits the buffer pData in chunks of nChunkSize size
+ * and calls static_C_CallUpdate for each chunk
+ */
+static CK_RV static_C_CallSplitUpdate(
+                           uint32_t           nCommandID,
+                           CK_SESSION_HANDLE  hSession,
+                           const CK_BYTE*     pData,
+                           CK_ULONG           ulDataLen,
+                           CK_BYTE*           pResult,
+                           CK_ULONG*          pulResultLen,
+                           bool               bSend,
+                           bool               bReceive,
+                           uint32_t           nChunkSize)
+{
+   CK_RV nErrorCode;
+   CK_ULONG nPartDataLen;
+   CK_ULONG nPartResultLen = 0;
+   CK_ULONG ulResultLen = 0;
+   bool bIsSymOperation = false;
+
+   if (pulResultLen != NULL)
+   {
+      ulResultLen = *pulResultLen;
+      /* Check wether the operation is a symetrical or asymetrical */
+      if (*pulResultLen == ulDataLen)
+      {
+         bIsSymOperation = true;
+      }
+      *pulResultLen = 0;
+   }
+
+   while (ulDataLen > 0)
+   {
+      nPartDataLen = (ulDataLen <= nChunkSize ?
+                        ulDataLen : nChunkSize);
+      if (bIsSymOperation)
+      {
+         /* update the result only if it is a symetric operation */
+         nPartResultLen = (ulResultLen <= nChunkSize ?
+                               ulResultLen : nChunkSize);
+      }
+      else
+      {
+         nPartResultLen = ulResultLen;
+      }
+
+      nErrorCode =  static_C_CallUpdate(
+                                 nCommandID,
+                                 hSession,
+                                 pData,
+                                 nPartDataLen,
+                                 pResult,
+                                 &nPartResultLen,
+                                 bSend,
+                                 bReceive);
+      if (nErrorCode != CKR_OK)
+      {
+         return nErrorCode;
+      }
+
+      ulDataLen -= nPartDataLen;
+      pData += nPartDataLen;
+
+      if (pResult != NULL)
+      {
+         ulResultLen -= nPartResultLen;
+         pResult += nPartResultLen;
+      }
+
+      if ((pulResultLen != NULL) && (bIsSymOperation))
+      {
+         *pulResultLen += nPartResultLen;
+      }
+   }
+   return CKR_OK;
+}
+
+/* Decides whether to split or not the inout/output buffer into chunks
+*/
+static CK_RV static_C_Call_CallForUpdate(
+                           uint32_t           nCommandID,
+                           CK_SESSION_HANDLE  hSession,
+                           const CK_BYTE*     pData,
+                           CK_ULONG           ulDataLen,
+                           CK_BYTE*           pResult,
+                           CK_ULONG*          pulResultLen,
+                           bool               bSend,
+                           bool               bReceive)
+{
+   CK_RV                   nErrorCode;
+   uint32_t                nChunkSize;
+
+   TEEC_ImplementationLimits  limits;
+
+   if (!g_bCryptokiInitialized)
+   {
+      return CKR_CRYPTOKI_NOT_INITIALIZED;
+   }
+
+   TEEC_GetImplementationLimits(&limits);
+
+   /* We can split the buffer in chunks of fixed size.
+      No matter of the start address of the buffer,
+      a safe size would be TotalNumberOfPages - 1
+   */
+   nChunkSize = limits.tmprefMaxSize - limits.pageSize;
+
+   if (ulDataLen > nChunkSize)
+   {
+      /* inoutMaxSize = 0  means unlimited size */
+       nErrorCode = static_C_CallSplitUpdate(nCommandID,
+                                 hSession,
+                                 pData,
+                                 ulDataLen,
+                                 pResult,
+                                 pulResultLen,
+                                 bSend,
+                                 bReceive,
+                                 nChunkSize);
+   }
+   else
+   {
+      nErrorCode = static_C_CallUpdate(nCommandID,
+                                 hSession,
+                                 pData,
+                                 ulDataLen,
+                                 pResult,
+                                 pulResultLen,
+                                 bSend,
+                                 bReceive);
+   }
+   return nErrorCode;
+
+}
+
+/* ------------------------------------------------------------------------
+Public Functions
+------------------------------------------------------------------------- */
+
+CK_RV PKCS11_EXPORT C_CreateObject(
+   CK_SESSION_HANDLE    hSession,    /* the session's handle */
+   const CK_ATTRIBUTE*  pTemplate,   /* the object's template */
+   CK_ULONG             ulCount,     /* attributes in template */
+   CK_OBJECT_HANDLE*    phObject)    /* receives new object's handle. */
+{
+   TEEC_Result          teeErr;
+   uint32_t             nErrorOrigin;
+   TEEC_Operation       sOperation;
+   CK_RV                nErrorCode = CKR_OK;
+   PPKCS11_PRIMARY_SESSION_CONTEXT pSession;
+   uint32_t             nCommandIDAndSession = SERVICE_SYSTEM_PKCS11_C_CREATEOBJECT_COMMAND_ID;
+   uint8_t*             pBuffer = NULL;
+   uint32_t             nBufferSize = 0;
+
+   if ( pTemplate == NULL || phObject == NULL )
+   {
+      return CKR_ARGUMENTS_BAD;
+   }
+
+   nErrorCode = static_checkPreConditionsAndUpdateHandles(&hSession, &nCommandIDAndSession, &pSession);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   nErrorCode = static_encodeTemplate(&pBuffer, &nBufferSize, 0, (CK_ATTRIBUTE*)pTemplate, ulCount); /* Sets the template on the param 0 */
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   memset(&sOperation, 0, sizeof(TEEC_Operation));
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_MEMREF_TEMP_INPUT, TEEC_VALUE_OUTPUT, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].tmpref.buffer = pBuffer;
+   sOperation.params[0].tmpref.size   = nBufferSize;
+   teeErr = TEEC_InvokeCommand(   &pSession->sSession,
+                                  nCommandIDAndSession,        /* commandID */
+                                  &sOperation,                 /* IN OUT operation */
+                                  &nErrorOrigin                /* OUT returnOrigin, optional */
+                                 );
+   free(pBuffer);
+
+   if (teeErr != TEEC_SUCCESS)
+   {
+      nErrorCode = (nErrorOrigin == TEEC_ORIGIN_TRUSTED_APP ?
+                     teeErr :
+                     ckInternalTeeErrorToCKError(teeErr));
+      goto end;
+   }
+
+   *phObject = sOperation.params[1].value.a;
+
+   /* Success */
+   nErrorCode = CKR_OK;
+
+end:
+   return nErrorCode;
+}
+
+CK_RV PKCS11_EXPORT C_DestroyObject(
+   CK_SESSION_HANDLE hSession,  /* the session's handle */
+   CK_OBJECT_HANDLE  hObject)   /* the object's handle */
+{
+   TEEC_Result    teeErr;
+   uint32_t       nErrorOrigin;
+   TEEC_Operation sOperation;
+   CK_RV       nErrorCode = CKR_OK;
+   uint32_t    nCommandIDAndSession = SERVICE_SYSTEM_PKCS11_C_DESTROYOBJECT_COMMAND_ID;
+   PPKCS11_PRIMARY_SESSION_CONTEXT pSession;
+
+   nErrorCode = static_checkPreConditionsAndUpdateHandles(&hSession, &nCommandIDAndSession, &pSession);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   memset(&sOperation, 0, sizeof(TEEC_Operation));
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INPUT, TEEC_NONE, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].value.a = (uint32_t)hObject;
+   teeErr = TEEC_InvokeCommand(   &pSession->sSession,
+                                  nCommandIDAndSession,        /* commandID */
+                                  &sOperation,                 /* IN OUT operation */
+                                  &nErrorOrigin                /* OUT returnOrigin, optional */
+                                 );
+   nErrorCode = (nErrorOrigin == TEEC_ORIGIN_TRUSTED_APP ?
+                  teeErr :
+                  ckInternalTeeErrorToCKError(teeErr));
+   return nErrorCode;
+}
+
+CK_RV PKCS11_EXPORT C_GetAttributeValue(
+   CK_SESSION_HANDLE hSession,   /* the session's handle */
+   CK_OBJECT_HANDLE  hObject,    /* the object's handle */
+   CK_ATTRIBUTE*     pTemplate,  /* specifies attributes, gets values */
+   CK_ULONG          ulCount)    /* attributes in template */
+{
+   TEEC_Result       teeErr;
+   uint32_t          nErrorOrigin;
+   TEEC_Operation    sOperation;
+   CK_RV             nErrorCode = CKR_OK;
+   CK_RV             nFinalErrorCode = CKR_OK;
+   uint32_t          i = 0;
+   uint32_t          nCommandIDAndSession = SERVICE_SYSTEM_PKCS11_C_GETATTRIBUTEVALUE_COMMAND_ID;
+   PPKCS11_PRIMARY_SESSION_CONTEXT pSession;
+
+   nErrorCode = static_checkPreConditionsAndUpdateHandles(&hSession, &nCommandIDAndSession, &pSession);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   if (pTemplate == NULL)
+   {
+      return CKR_ARGUMENTS_BAD;
+   }
+
+   if (ulCount == 0)
+   {
+      return CKR_OK;
+   }
+
+   for (i = 0; i < ulCount; i++)
+   {
+      memset(&sOperation, 0, sizeof(TEEC_Operation));
+      sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INPUT, TEEC_MEMREF_TEMP_OUTPUT, TEEC_NONE, TEEC_NONE);
+      sOperation.params[0].value.a = (uint32_t)hObject;
+      sOperation.params[0].value.b = (uint32_t)pTemplate[i].type;
+      sOperation.params[1].tmpref.buffer = pTemplate[i].pValue;
+      sOperation.params[1].tmpref.size   = pTemplate[i].ulValueLen;
+      teeErr = TEEC_InvokeCommand(   &pSession->sSession,
+                                     nCommandIDAndSession,        /* commandID */
+                                     &sOperation,                 /* IN OUT operation */
+                                     &nErrorOrigin                /* OUT returnOrigin, optional */
+                                    );
+      nErrorCode = (nErrorOrigin == TEEC_ORIGIN_TRUSTED_APP ?
+                     teeErr :
+                     ckInternalTeeErrorToCKError(teeErr));
+      if (nErrorCode != CKR_OK)
+      {
+         if (  (nErrorCode == CKR_ATTRIBUTE_SENSITIVE) ||
+               (nErrorCode == CKR_ATTRIBUTE_TYPE_INVALID) ||
+               (nErrorCode == CKR_BUFFER_TOO_SMALL))
+         {
+            nFinalErrorCode = nErrorCode;
+         }
+         else
+         {
+            /* Not some of the special error codes: this is fatal */
+            return nErrorCode;
+         }
+      }
+
+      pTemplate[i].ulValueLen = sOperation.params[1].tmpref.size;
+   }
+
+   return nFinalErrorCode;
+}
+
+CK_RV PKCS11_EXPORT C_FindObjectsInit(
+   CK_SESSION_HANDLE    hSession,   /* the session's handle */
+   const CK_ATTRIBUTE*  pTemplate,  /* attribute values to match */
+   CK_ULONG             ulCount)    /* attributes in search template */
+{
+   TEEC_Result    teeErr;
+   uint32_t       nErrorOrigin;
+   TEEC_Operation sOperation;
+   CK_RV       nErrorCode = CKR_OK;
+   PPKCS11_PRIMARY_SESSION_CONTEXT pSession;
+   uint32_t    nCommandIDAndSession = SERVICE_SYSTEM_PKCS11_C_FINDOBJECTSINIT_COMMAND_ID;
+   uint8_t*    pBuffer     = NULL;
+   uint32_t    nBufferSize = 0;
+
+   nErrorCode = static_checkPreConditionsAndUpdateHandles(&hSession, &nCommandIDAndSession, &pSession);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   nErrorCode = static_encodeTemplate(&pBuffer, &nBufferSize, 0, (CK_ATTRIBUTE*)pTemplate, ulCount); /* Sets the template on the param 0 */
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   memset(&sOperation, 0, sizeof(TEEC_Operation));
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_MEMREF_TEMP_INPUT, TEEC_NONE, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].tmpref.buffer = pBuffer;
+   sOperation.params[0].tmpref.size   = nBufferSize;
+   teeErr = TEEC_InvokeCommand(   &pSession->sSession,
+                                  nCommandIDAndSession,        /* commandID */
+                                  &sOperation,                 /* IN OUT operation */
+                                  &nErrorOrigin                /* OUT returnOrigin, optional */
+                                 );
+   free(pBuffer);
+
+   nErrorCode = (nErrorOrigin == TEEC_ORIGIN_TRUSTED_APP ?
+                  teeErr :
+                  ckInternalTeeErrorToCKError(teeErr));
+   return nErrorCode;
+}
+
+
+CK_RV PKCS11_EXPORT C_FindObjects(
+   CK_SESSION_HANDLE hSession,          /* the session's handle */
+   CK_OBJECT_HANDLE* phObject,          /* receives object handle array */
+   CK_ULONG          ulMaxObjectCount,  /* max handles to be returned */
+   CK_ULONG*         pulObjectCount)    /* actual number returned */
+{
+   TEEC_Result       teeErr;
+   uint32_t          nErrorOrigin;
+   TEEC_Operation    sOperation;
+   CK_RV             nErrorCode = CKR_OK;
+   PPKCS11_PRIMARY_SESSION_CONTEXT pSession;
+   uint32_t          nCommandIDAndSession = SERVICE_SYSTEM_PKCS11_C_FINDOBJECTS_COMMAND_ID;
+
+   if ( (phObject == NULL) || (pulObjectCount == NULL))
+   {
+      return CKR_ARGUMENTS_BAD;
+   }
+
+   *pulObjectCount = 0;
+
+   nErrorCode = static_checkPreConditionsAndUpdateHandles(&hSession, &nCommandIDAndSession, &pSession);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   memset(&sOperation, 0, sizeof(TEEC_Operation));
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_MEMREF_TEMP_OUTPUT, TEEC_NONE, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].tmpref.buffer = (uint8_t*)phObject;
+   sOperation.params[0].tmpref.size   = (uint32_t)ulMaxObjectCount * sizeof(uint32_t);
+
+   teeErr = TEEC_InvokeCommand(   &pSession->sSession,
+                                  nCommandIDAndSession,        /* commandID */
+                                  &sOperation,                 /* IN OUT operation */
+                                  &nErrorOrigin                /* OUT returnOrigin, optional */
+                                 );
+
+   if (teeErr != TEEC_SUCCESS)
+   {
+      nErrorCode = (nErrorOrigin == TEEC_ORIGIN_TRUSTED_APP ?
+                     teeErr :
+                     ckInternalTeeErrorToCKError(teeErr));
+      return nErrorCode;
+   }
+
+   *pulObjectCount = sOperation.params[0].tmpref.size / sizeof(uint32_t);
+
+   return CKR_OK;
+}
+
+CK_RV PKCS11_EXPORT C_FindObjectsFinal(CK_SESSION_HANDLE hSession) /* the session's handle */
+{
+   TEEC_Result    teeErr;
+   uint32_t       nErrorOrigin;
+   TEEC_Operation sOperation;
+   CK_RV          nErrorCode = CKR_OK;
+   uint32_t       nCommandIDAndSession = SERVICE_SYSTEM_PKCS11_C_FINDOBJECTSFINAL_COMMAND_ID;
+   PPKCS11_PRIMARY_SESSION_CONTEXT pSession;
+
+   nErrorCode = static_checkPreConditionsAndUpdateHandles(&hSession, &nCommandIDAndSession, &pSession);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   memset(&sOperation, 0, sizeof(TEEC_Operation));
+   teeErr = TEEC_InvokeCommand(   &pSession->sSession,
+                                  nCommandIDAndSession,        /* commandID */
+                                  &sOperation,                 /* IN OUT operation */
+                                  &nErrorOrigin                /* OUT returnOrigin, optional */
+                                 );
+
+   nErrorCode = (nErrorOrigin == TEEC_ORIGIN_TRUSTED_APP ?
+                  teeErr :
+                  ckInternalTeeErrorToCKError(teeErr));
+   return nErrorCode;
+}
+
+
+CK_RV PKCS11_EXPORT C_DigestInit(
+   CK_SESSION_HANDLE   hSession,   /* the session's handle */
+   const CK_MECHANISM* pMechanism) /* the digesting mechanism */
+{
+   return static_C_CallInit(
+      SERVICE_SYSTEM_PKCS11_C_DIGESTINIT_COMMAND_ID,
+      hSession,
+      pMechanism,
+      CK_INVALID_HANDLE);
+}
+
+CK_RV PKCS11_EXPORT C_Digest(
+   CK_SESSION_HANDLE hSession,     /* the session's handle */
+   const CK_BYTE*    pData,        /* data to be digested */
+   CK_ULONG          ulDataLen,    /* bytes of data to be digested */
+   CK_BYTE*          pDigest,      /* receives the message digest */
+   CK_ULONG*         pulDigestLen) /* receives byte length of digest */
+{
+   return static_C_CallForSingle(
+      SERVICE_SYSTEM_PKCS11_C_DIGEST_COMMAND_ID,
+      hSession,
+      pData,
+      ulDataLen,
+      pDigest,
+      pulDigestLen,
+      TRUE,
+      TRUE);
+}
+
+CK_RV PKCS11_EXPORT C_DigestUpdate(
+   CK_SESSION_HANDLE hSession,  /* the session's handle */
+   const CK_BYTE*    pPart,     /* data to be digested */
+   CK_ULONG          ulPartLen) /* bytes of data to be digested */
+{
+   return static_C_Call_CallForUpdate(
+      SERVICE_SYSTEM_PKCS11_C_DIGESTUPDATE_COMMAND_ID,
+      hSession,
+      pPart,
+      ulPartLen,
+      NULL,
+      NULL,
+      TRUE,
+      FALSE);
+}
+
+CK_RV PKCS11_EXPORT C_DigestFinal(
+   CK_SESSION_HANDLE hSession,  /* the session's handle */
+   CK_BYTE*       pDigest,      /* receives the message digest */
+   CK_ULONG*      pulDigestLen) /* receives byte count of digest */
+{
+   return static_C_Call_CallForUpdate(
+      SERVICE_SYSTEM_PKCS11_C_DIGESTFINAL_COMMAND_ID,
+      hSession,
+      NULL,
+      0,
+      pDigest,
+      pulDigestLen,
+      FALSE,
+      TRUE);
+}
+
+
+CK_RV PKCS11_EXPORT C_SignInit(
+   CK_SESSION_HANDLE    hSession,    /* the session's handle */
+   const CK_MECHANISM*  pMechanism,  /* the signature mechanism */
+   CK_OBJECT_HANDLE     hKey)        /* handle of the signature key */
+{
+   return static_C_CallInit(
+      SERVICE_SYSTEM_PKCS11_C_SIGNINIT_COMMAND_ID,
+      hSession,
+      pMechanism,
+      hKey);
+}
+
+CK_RV PKCS11_EXPORT C_Sign(
+   CK_SESSION_HANDLE hSession,        /* the session's handle */
+   const CK_BYTE*    pData,           /* the data (digest) to be signed */
+   CK_ULONG          ulDataLen,       /* count of bytes to be signed */
+   CK_BYTE*          pSignature,      /* receives the signature */
+   CK_ULONG*         pulSignatureLen) /* receives byte count of signature */
+{
+   return static_C_CallForSingle(
+      SERVICE_SYSTEM_PKCS11_C_SIGN_COMMAND_ID,
+      hSession,
+      pData,
+      ulDataLen,
+      pSignature,
+      pulSignatureLen,
+      TRUE,
+      TRUE);
+}
+
+CK_RV PKCS11_EXPORT C_SignUpdate(
+   CK_SESSION_HANDLE hSession,  /* the session's handle */
+   const CK_BYTE*    pPart,     /* the data (digest) to be signed */
+   CK_ULONG          ulPartLen) /* count of bytes to be signed */
+{
+   return static_C_Call_CallForUpdate(
+      SERVICE_SYSTEM_PKCS11_C_SIGNUPDATE_COMMAND_ID,
+      hSession,
+      pPart,
+      ulPartLen,
+      NULL,
+      NULL,
+      TRUE,
+      FALSE);
+}
+
+CK_RV PKCS11_EXPORT C_SignFinal(
+   CK_SESSION_HANDLE hSession,     /* the session's handle */
+   CK_BYTE*       pSignature,      /* receives the signature */
+   CK_ULONG*      pulSignatureLen) /* receives byte count of signature */
+{
+   return static_C_Call_CallForUpdate(
+      SERVICE_SYSTEM_PKCS11_C_SIGNFINAL_COMMAND_ID,
+      hSession,
+      NULL,
+      0,
+      pSignature,
+      pulSignatureLen,
+      FALSE,
+      TRUE);
+}
+
+CK_RV PKCS11_EXPORT C_EncryptInit(
+   CK_SESSION_HANDLE   hSession,    /* the session's handle */
+   const CK_MECHANISM* pMechanism,  /* the encryption mechanism */
+   CK_OBJECT_HANDLE    hKey)        /* handle of encryption key */
+{
+   return static_C_CallInit(
+      SERVICE_SYSTEM_PKCS11_C_ENCRYPTINIT_COMMAND_ID,
+      hSession,
+      pMechanism,
+      hKey);
+}
+
+CK_RV PKCS11_EXPORT C_Encrypt(
+   CK_SESSION_HANDLE hSession,            /* the session's handle */
+   const CK_BYTE*    pData,               /* the plaintext data */
+   CK_ULONG          ulDataLen,           /* bytes of plaintext data */
+   CK_BYTE*          pEncryptedData,      /* receives encrypted data */
+   CK_ULONG*         pulEncryptedDataLen) /* receives encrypted byte count */
+{
+
+   return static_C_CallForSingle(
+      SERVICE_SYSTEM_PKCS11_C_ENCRYPT_COMMAND_ID,
+      hSession,
+      pData,
+      ulDataLen,
+      pEncryptedData,
+      pulEncryptedDataLen,
+      TRUE,
+      TRUE);
+}
+
+
+
+CK_RV PKCS11_EXPORT C_EncryptUpdate(
+   CK_SESSION_HANDLE hSession,           /* the session's handle */
+   const CK_BYTE*    pPart,              /* the plaintext data */
+   CK_ULONG          ulPartLen,          /* bytes of plaintext data */
+   CK_BYTE*          pEncryptedPart,     /* receives encrypted data */
+   CK_ULONG*         pulEncryptedPartLen)/* receives encrypted byte count */
+{
+   return static_C_Call_CallForUpdate(
+      SERVICE_SYSTEM_PKCS11_C_ENCRYPTUPDATE_COMMAND_ID,
+      hSession,
+      pPart,
+      ulPartLen,
+      pEncryptedPart,
+      pulEncryptedPartLen,
+      TRUE,
+      TRUE);
+}
+
+CK_RV PKCS11_EXPORT C_EncryptFinal(
+   CK_SESSION_HANDLE hSession,             /* the session's handle */
+   CK_BYTE*       pLastEncryptedPart,      /* receives encrypted last part */
+   CK_ULONG*      pulLastEncryptedPartLen) /* receives byte count */
+{
+   return static_C_Call_CallForUpdate(
+      SERVICE_SYSTEM_PKCS11_C_ENCRYPTFINAL_COMMAND_ID,
+      hSession,
+      NULL,
+      0,
+      pLastEncryptedPart,
+      pulLastEncryptedPartLen,
+      FALSE,
+      TRUE);
+}
+
+CK_RV PKCS11_EXPORT C_DecryptInit(
+   CK_SESSION_HANDLE   hSession,    /* the session's handle */
+   const CK_MECHANISM* pMechanism,  /* the decryption mechanism */
+   CK_OBJECT_HANDLE    hKey)        /* handle of the decryption key */
+{
+   return static_C_CallInit(
+      SERVICE_SYSTEM_PKCS11_C_DECRYPTINIT_COMMAND_ID,
+      hSession,
+      pMechanism,
+      hKey);
+}
+
+CK_RV PKCS11_EXPORT C_Decrypt(
+   CK_SESSION_HANDLE hSession,           /* the session's handle */
+   const CK_BYTE*    pEncryptedData,     /* input encrypted data */
+   CK_ULONG          ulEncryptedDataLen, /* count of bytes of input */
+   CK_BYTE*          pData,              /* receives decrypted output */
+   CK_ULONG*         pulDataLen)         /* receives decrypted byte count */
+{
+
+   return static_C_CallForSingle(
+      SERVICE_SYSTEM_PKCS11_C_DECRYPT_COMMAND_ID,
+      hSession,
+      pEncryptedData,
+      ulEncryptedDataLen,
+      pData,
+      pulDataLen,
+      TRUE,
+      TRUE);
+}
+
+CK_RV PKCS11_EXPORT C_DecryptUpdate(
+   CK_SESSION_HANDLE hSession,            /* the session's handle */
+   const CK_BYTE*    pEncryptedPart,      /* input encrypted data */
+   CK_ULONG          ulEncryptedPartLen,  /* count of bytes of input */
+   CK_BYTE*          pPart,               /* receives decrypted output */
+   CK_ULONG*         pulPartLen)          /* receives decrypted byte count */
+{
+   return static_C_Call_CallForUpdate(
+      SERVICE_SYSTEM_PKCS11_C_DECRYPTUPDATE_COMMAND_ID,
+      hSession,
+      pEncryptedPart,
+      ulEncryptedPartLen,
+      pPart,
+      pulPartLen,
+      TRUE,
+      TRUE);
+}
+
+CK_RV PKCS11_EXPORT C_DecryptFinal(
+   CK_SESSION_HANDLE hSession,    /* the session's handle */
+   CK_BYTE*       pLastPart,      /* receives decrypted output */
+   CK_ULONG*      pulLastPartLen) /* receives decrypted byte count */
+{
+   return static_C_Call_CallForUpdate(
+      SERVICE_SYSTEM_PKCS11_C_DECRYPTFINAL_COMMAND_ID,
+      hSession,
+      NULL,
+      0,
+      pLastPart,
+      pulLastPartLen,
+      FALSE,
+      TRUE);
+}
+
+
+CK_RV PKCS11_EXPORT C_GenerateKey(
+   CK_SESSION_HANDLE    hSession,    /* the session's handle */
+   const CK_MECHANISM*  pMechanism,  /* the key generation mechanism */
+   const CK_ATTRIBUTE*  pTemplate,   /* template for the new key */
+   CK_ULONG             ulCount,     /* number of attributes in template */
+   CK_OBJECT_HANDLE*    phKey)       /* receives handle of new key */
+{
+   TEEC_Result    teeErr;
+   uint32_t       nErrorOrigin;
+   TEEC_Operation sOperation;
+   CK_RV       nErrorCode = CKR_OK;
+   uint32_t    nCommandIDAndSession = SERVICE_SYSTEM_PKCS11_C_GENERATEKEY_COMMAND_ID;
+   uint8_t*    pBuffer     = NULL;
+   uint32_t    nBufferSize = 0;
+   PPKCS11_PRIMARY_SESSION_CONTEXT pSession;
+
+   if ((pMechanism == NULL) || (phKey == NULL) || (pTemplate == NULL))
+   {
+      return CKR_ARGUMENTS_BAD;
+   }
+
+   nErrorCode = static_checkPreConditionsAndUpdateHandles(&hSession, &nCommandIDAndSession, &pSession);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   nErrorCode = static_encodeTemplate(&pBuffer, &nBufferSize, 2, (CK_ATTRIBUTE*)pTemplate, ulCount);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   memset(&sOperation, 0, sizeof(TEEC_Operation));
+   sOperation.params[0].value.a = (uint32_t)pMechanism->mechanism;
+   sOperation.params[0].value.b = 0;
+   sOperation.params[1].tmpref.buffer = pMechanism->pParameter;
+   sOperation.params[1].tmpref.size = (uint32_t)pMechanism->ulParameterLen;
+   sOperation.params[2].tmpref.buffer = pBuffer;
+   sOperation.params[2].tmpref.size = nBufferSize;
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INOUT, TEEC_MEMREF_TEMP_INPUT, TEEC_MEMREF_TEMP_INPUT, TEEC_NONE);
+   teeErr = TEEC_InvokeCommand(   &pSession->sSession,
+                                  nCommandIDAndSession,        /* commandID */
+                                  &sOperation,                 /* IN OUT operation */
+                                  &nErrorOrigin                /* OUT returnOrigin, optional */
+                                 );
+   free(pBuffer);
+
+   if (teeErr != TEEC_SUCCESS)
+   {
+      nErrorCode = (nErrorOrigin == TEEC_ORIGIN_TRUSTED_APP ?
+                     teeErr :
+                     ckInternalTeeErrorToCKError(teeErr));
+      return nErrorCode;
+   }
+
+   *phKey = sOperation.params[0].value.a;
+
+   return CKR_OK;
+}
+
+CK_RV PKCS11_EXPORT C_GenerateKeyPair(
+   CK_SESSION_HANDLE    hSession,                    /* the session's handle */
+   const CK_MECHANISM*  pMechanism,                  /* the key gen. mech. */
+   const CK_ATTRIBUTE*  pPublicKeyTemplate,          /* pub. attr. template */
+   CK_ULONG             ulPublicKeyAttributeCount,   /* # of pub. attrs. */
+   const CK_ATTRIBUTE*  pPrivateKeyTemplate,         /* priv. attr. template */
+   CK_ULONG             ulPrivateKeyAttributeCount,  /* # of priv. attrs. */
+   CK_OBJECT_HANDLE*    phPublicKey,                 /* gets pub. key handle */
+   CK_OBJECT_HANDLE*    phPrivateKey)                /* gets priv. key handle */
+{
+   TEEC_Result    teeErr;
+   uint32_t       nErrorOrigin;
+   TEEC_Operation sOperation;
+   CK_RV       nErrorCode = CKR_OK;
+   uint32_t    nCommandIDAndSession = SERVICE_SYSTEM_PKCS11_C_GENERATEKEYPAIR_COMMAND_ID;
+   uint8_t*    pBuffer     = NULL;
+   uint32_t    nBufferSize = 0;
+   PPKCS11_PRIMARY_SESSION_CONTEXT pSession;
+
+   if (  (pMechanism == NULL) ||
+         (pPublicKeyTemplate == NULL) || (pPrivateKeyTemplate == NULL) ||
+         (phPublicKey== NULL) || (phPrivateKey== NULL))
+   {
+      return CKR_ARGUMENTS_BAD;
+   }
+
+   nErrorCode = static_checkPreConditionsAndUpdateHandles(&hSession, &nCommandIDAndSession, &pSession);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   nErrorCode = static_encodeTwoTemplates(&pBuffer, &nBufferSize, 2, (CK_ATTRIBUTE*)pPublicKeyTemplate, ulPublicKeyAttributeCount, (CK_ATTRIBUTE*)pPrivateKeyTemplate, ulPrivateKeyAttributeCount);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   memset(&sOperation, 0, sizeof(TEEC_Operation));
+   sOperation.params[0].value.a = (uint32_t)pMechanism->mechanism;
+   sOperation.params[0].value.b = 0;
+   sOperation.params[1].tmpref.buffer = (uint8_t*)pMechanism->pParameter;
+   sOperation.params[1].tmpref.size = (uint32_t)pMechanism->ulParameterLen;
+   sOperation.params[2].tmpref.buffer = pBuffer;
+   sOperation.params[2].tmpref.size = nBufferSize;
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INOUT, TEEC_MEMREF_TEMP_INPUT, TEEC_MEMREF_TEMP_INPUT, TEEC_NONE);
+   teeErr = TEEC_InvokeCommand(   &pSession->sSession,
+                                  nCommandIDAndSession,        /* commandID */
+                                  &sOperation,                 /* IN OUT operation */
+                                  &nErrorOrigin                /* OUT returnOrigin, optional */
+                                 );
+   free(pBuffer);
+
+   if (teeErr != TEEC_SUCCESS)
+   {
+      nErrorCode = (nErrorOrigin == TEEC_ORIGIN_TRUSTED_APP ?
+                     teeErr :
+                     ckInternalTeeErrorToCKError(teeErr));
+      return nErrorCode;
+   }
+
+   *phPublicKey  = sOperation.params[0].value.a;
+   *phPrivateKey = sOperation.params[0].value.b;
+
+   return CKR_OK;
+}
+
+CK_RV PKCS11_EXPORT C_DeriveKey(
+   CK_SESSION_HANDLE    hSession,          /* session's handle */
+   const CK_MECHANISM*  pMechanism,        /* key deriv. mech. */
+   CK_OBJECT_HANDLE     hBaseKey,          /* base key */
+   const CK_ATTRIBUTE*  pTemplate,         /* new key template */
+   CK_ULONG             ulAttributeCount,  /* template length */
+   CK_OBJECT_HANDLE*    phKey)             /* gets new handle */
+{
+   TEEC_Result    teeErr;
+   uint32_t       nErrorOrigin;
+   TEEC_Operation sOperation;
+   CK_RV       nErrorCode = CKR_OK;
+   uint32_t    nCommandIDAndSession = SERVICE_SYSTEM_PKCS11_C_DERIVEKEY_COMMAND_ID;
+   uint8_t*    pBuffer     = NULL;
+   uint32_t    nBufferSize = 0;
+   PPKCS11_PRIMARY_SESSION_CONTEXT pSession;
+
+   if ((pMechanism == NULL) || (pTemplate == NULL) || (phKey == NULL))
+   {
+      return CKR_ARGUMENTS_BAD;
+   }
+
+   nErrorCode = static_checkPreConditionsAndUpdateHandles(&hSession, &nCommandIDAndSession, &pSession);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   nErrorCode = static_encodeTemplate(&pBuffer, &nBufferSize, 2, (CK_ATTRIBUTE*)pTemplate, ulAttributeCount);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   memset(&sOperation, 0, sizeof(TEEC_Operation));
+   sOperation.params[0].value.a = (uint32_t)pMechanism->mechanism;
+   sOperation.params[0].value.b = (uint32_t)hBaseKey;
+   sOperation.params[1].tmpref.buffer = (uint8_t*)pMechanism->pParameter;
+   sOperation.params[1].tmpref.size = (uint32_t)pMechanism->ulParameterLen;
+   sOperation.params[2].tmpref.buffer = pBuffer;
+   sOperation.params[2].tmpref.size = nBufferSize;
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INOUT, TEEC_MEMREF_TEMP_INPUT, TEEC_MEMREF_TEMP_INPUT, TEEC_NONE);
+   teeErr = TEEC_InvokeCommand(   &pSession->sSession,
+                                  nCommandIDAndSession,        /* commandID */
+                                  &sOperation,                 /* IN OUT operation */
+                                  &nErrorOrigin                /* OUT returnOrigin, optional */
+                                 );
+   free(pBuffer);
+
+   if (teeErr != TEEC_SUCCESS)
+   {
+      nErrorCode = (nErrorOrigin == TEEC_ORIGIN_TRUSTED_APP ?
+                     teeErr :
+                     ckInternalTeeErrorToCKError(teeErr));
+      return nErrorCode;
+   }
+
+   *phKey = sOperation.params[0].value.a;
+
+   return CKR_OK;
+}
+
+CK_RV PKCS11_EXPORT C_SeedRandom(
+   CK_SESSION_HANDLE hSession,  /* the session's handle */
+   const CK_BYTE*    pSeed,     /* the seed material */
+   CK_ULONG          ulSeedLen) /* count of bytes of seed material */
+{
+   TEEC_Result    teeErr;
+   uint32_t       nErrorOrigin;
+   TEEC_Operation sOperation;
+   CK_RV       nErrorCode = CKR_OK;
+   uint32_t    nCommandIDAndSession = SERVICE_SYSTEM_PKCS11_C_SEEDRANDOM_COMMAND_ID;
+   PPKCS11_PRIMARY_SESSION_CONTEXT pSession;
+
+   nErrorCode = static_checkPreConditionsAndUpdateHandles(&hSession, &nCommandIDAndSession, &pSession);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+   memset(&sOperation, 0, sizeof(TEEC_Operation));
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_MEMREF_TEMP_INPUT, TEEC_NONE, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].tmpref.buffer = (uint8_t*)pSeed;
+   sOperation.params[0].tmpref.size   = (uint32_t)ulSeedLen;
+   teeErr = TEEC_InvokeCommand(   &pSession->sSession,
+                                  nCommandIDAndSession,        /* commandID */
+                                  &sOperation,                 /* IN OUT operation */
+                                  &nErrorOrigin                /* OUT returnOrigin, optional */
+                                 );
+
+   nErrorCode = (nErrorOrigin == TEEC_ORIGIN_TRUSTED_APP ?
+                  teeErr :
+                  ckInternalTeeErrorToCKError(teeErr));
+   return nErrorCode;
+}
+
+CK_RV PKCS11_EXPORT C_GenerateRandom(
+   CK_SESSION_HANDLE hSession,    /* the session's handle */
+   CK_BYTE*          pRandomData,  /* receives the random data */
+   CK_ULONG          ulRandomLen) /* number of bytes to be generated */
+{
+   TEEC_Result    teeErr;
+   uint32_t       nErrorOrigin;
+   TEEC_Operation sOperation;
+   CK_RV       nErrorCode = CKR_OK;
+   uint32_t    nCommandIDAndSession = SERVICE_SYSTEM_PKCS11_C_GENERATERANDOM_COMMAND_ID;
+   PPKCS11_PRIMARY_SESSION_CONTEXT pSession;
+
+   nErrorCode = static_checkPreConditionsAndUpdateHandles(&hSession, &nCommandIDAndSession, &pSession);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   do
+   {
+      CK_ULONG nArrayLength;
+      nArrayLength = 1024;
+      if (ulRandomLen < nArrayLength)
+      {
+         nArrayLength = ulRandomLen;
+      }
+      memset(&sOperation, 0, sizeof(TEEC_Operation));
+      sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_MEMREF_TEMP_OUTPUT, TEEC_NONE, TEEC_NONE, TEEC_NONE);
+      sOperation.params[0].tmpref.buffer = (uint8_t*)pRandomData;
+      sOperation.params[0].tmpref.size   = (uint32_t)nArrayLength;
+      teeErr = TEEC_InvokeCommand(   &pSession->sSession,
+                                     nCommandIDAndSession,        /* commandID */
+                                     &sOperation,                 /* IN OUT operation */
+                                     &nErrorOrigin                /* OUT returnOrigin, optional */
+                                    );
+      if (teeErr != TEEC_SUCCESS)
+      {
+         nErrorCode = (nErrorOrigin == TEEC_ORIGIN_TRUSTED_APP ?
+                        teeErr :
+                        ckInternalTeeErrorToCKError(teeErr));
+         return nErrorCode;
+      }
+
+      ulRandomLen -= nArrayLength;
+      pRandomData += nArrayLength;
+      if (ulRandomLen == 0)
+      {
+         break;
+      }
+   }
+   while(1);
+
+   return CKR_OK;
+}
+
+CK_RV PKCS11_EXPORT C_VerifyInit(
+   CK_SESSION_HANDLE   hSession,    /* the session's handle */
+   const CK_MECHANISM* pMechanism,  /* the verification mechanism */
+   CK_OBJECT_HANDLE    hKey)        /* handle of the verification key */
+{
+   return static_C_CallInit(
+      SERVICE_SYSTEM_PKCS11_C_VERIFYINIT_COMMAND_ID,
+      hSession,
+      pMechanism,
+      hKey);
+}
+
+CK_RV PKCS11_EXPORT C_Verify(
+   CK_SESSION_HANDLE hSession,       /* the session's handle */
+   const CK_BYTE*    pData,          /* plaintext data (digest) to compare */
+   CK_ULONG          ulDataLen,      /* length of data (digest) in bytes */
+   CK_BYTE*          pSignature,     /* the signature to be verified */
+   CK_ULONG          ulSignatureLen) /* count of bytes of signature */
+{
+   TEEC_Result    teeErr;
+   uint32_t       nErrorOrigin;
+   TEEC_Operation sOperation;
+   CK_RV       nErrorCode = CKR_OK;
+   uint32_t    nCommandIDAndSession = SERVICE_SYSTEM_PKCS11_C_VERIFY_COMMAND_ID;
+   PPKCS11_PRIMARY_SESSION_CONTEXT pSession;
+
+   nErrorCode = static_checkPreConditionsAndUpdateHandles(&hSession, &nCommandIDAndSession, &pSession);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   memset(&sOperation, 0, sizeof(TEEC_Operation));
+   sOperation.params[0].tmpref.buffer = (uint8_t*)pData;
+   sOperation.params[0].tmpref.size   = (uint32_t)ulDataLen;
+   sOperation.params[1].tmpref.buffer = (uint8_t*)pSignature;
+   sOperation.params[1].tmpref.size   = (uint32_t)ulSignatureLen;
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_MEMREF_TEMP_INPUT, TEEC_MEMREF_TEMP_INPUT, TEEC_NONE, TEEC_NONE);
+   teeErr = TEEC_InvokeCommand(   &pSession->sSession,
+                                  nCommandIDAndSession,        /* commandID */
+                                  &sOperation,                 /* IN OUT operation */
+                                  &nErrorOrigin                /* OUT returnOrigin, optional */
+                                 );
+   nErrorCode = (nErrorOrigin == TEEC_ORIGIN_TRUSTED_APP ?
+                  teeErr :
+                  ckInternalTeeErrorToCKError(teeErr));
+   return nErrorCode;
+}
+
+CK_RV PKCS11_EXPORT C_VerifyUpdate(
+   CK_SESSION_HANDLE hSession,  /* the session's handle */
+   const CK_BYTE*    pPart,     /* plaintext data (digest) to compare */
+   CK_ULONG          ulPartLen) /* length of data (digest) in bytes */
+{
+   return static_C_Call_CallForUpdate(
+      SERVICE_SYSTEM_PKCS11_C_VERIFYUPDATE_COMMAND_ID,
+      hSession,
+      pPart,
+      ulPartLen,
+      NULL,
+      NULL,
+      TRUE,
+      FALSE);
+}
+
+CK_RV PKCS11_EXPORT C_VerifyFinal(
+   CK_SESSION_HANDLE hSession,       /* the session's handle */
+   const CK_BYTE*    pSignature,     /* the signature to be verified */
+   CK_ULONG          ulSignatureLen) /* count of bytes of signature */
+{
+   return static_C_Call_CallForUpdate(
+      SERVICE_SYSTEM_PKCS11_C_VERIFYFINAL_COMMAND_ID,
+      hSession,
+      pSignature,
+      ulSignatureLen,
+      NULL,
+      NULL,
+      TRUE,
+      FALSE);
+}
+
+CK_RV PKCS11_EXPORT C_CloseObjectHandle(
+   CK_SESSION_HANDLE hSession,  /* the session's handle */
+   CK_OBJECT_HANDLE  hObject)   /* the object's handle */
+{
+   TEEC_Result    teeErr;
+   uint32_t       nErrorOrigin;
+   TEEC_Operation sOperation;
+   CK_RV       nErrorCode = CKR_OK;
+   uint32_t    nCommandIDAndSession = SERVICE_SYSTEM_PKCS11_C_CLOSEOBJECTHANDLE_COMMAND_ID;
+   PPKCS11_PRIMARY_SESSION_CONTEXT pSession;
+
+   nErrorCode = static_checkPreConditionsAndUpdateHandles(&hSession, &nCommandIDAndSession, &pSession);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+   memset(&sOperation, 0, sizeof(TEEC_Operation));
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INPUT, TEEC_NONE, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].value.a = (uint32_t)hObject;
+   sOperation.params[0].value.b = 0;
+   teeErr = TEEC_InvokeCommand(   &pSession->sSession,
+                                  nCommandIDAndSession,        /* commandID */
+                                  &sOperation,                 /* IN OUT operation */
+                                  &nErrorOrigin                /* OUT returnOrigin, optional */
+                                 );
+   nErrorCode = (nErrorOrigin == TEEC_ORIGIN_TRUSTED_APP ?
+                  teeErr :
+                  ckInternalTeeErrorToCKError(teeErr));
+   return nErrorCode;
+}
+
+CK_RV PKCS11_EXPORT C_CopyObject(
+         CK_SESSION_HANDLE    hSession,    /* the session's handle */
+         CK_OBJECT_HANDLE     hObject,     /* the source object's handle */
+   const CK_ATTRIBUTE*        pTemplate,   /* the template of the copied object */
+         CK_ULONG             ulCount,     /* the number of attributes of the template*/
+         CK_OBJECT_HANDLE*    phNewObject) /* the copied object's handle */
+{
+   TEEC_Result    teeErr;
+   uint32_t       nErrorOrigin;
+   TEEC_Operation sOperation;
+   CK_RV       nErrorCode = CKR_OK;
+   uint32_t    nCommandIDAndSession = SERVICE_SYSTEM_PKCS11_C_COPYOBJECT_COMMAND_ID;
+   uint8_t*    pBuffer     = NULL;
+   uint32_t    nBufferSize = 0;
+   PPKCS11_PRIMARY_SESSION_CONTEXT pSession;
+
+   if ((pTemplate == NULL) || (phNewObject == NULL))
+   {
+      return CKR_ARGUMENTS_BAD;
+   }
+
+   nErrorCode = static_checkPreConditionsAndUpdateHandles(&hSession, &nCommandIDAndSession, &pSession);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   nErrorCode = static_encodeTemplate(&pBuffer, &nBufferSize, 1, (CK_ATTRIBUTE*)pTemplate, ulCount);
+   if (nErrorCode != CKR_OK)
+   {
+      return nErrorCode;
+   }
+
+   memset(&sOperation, 0, sizeof(TEEC_Operation));
+   sOperation.params[0].value.a = (uint32_t)hObject;
+   sOperation.params[0].value.b = 0;
+   sOperation.params[1].tmpref.buffer = pBuffer;
+   sOperation.params[1].tmpref.size   = nBufferSize;
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INOUT, TEEC_MEMREF_TEMP_INPUT, TEEC_NONE, TEEC_NONE);
+   teeErr = TEEC_InvokeCommand(   &pSession->sSession,
+                                  nCommandIDAndSession,        /* commandID */
+                                  &sOperation,                 /* IN OUT operation */
+                                  &nErrorOrigin                /* OUT returnOrigin, optional */
+                                 );
+   free(pBuffer);
+
+   if (teeErr != TEEC_SUCCESS)
+   {
+      nErrorCode = (nErrorOrigin == TEEC_ORIGIN_TRUSTED_APP ?
+                     teeErr :
+                     ckInternalTeeErrorToCKError(teeErr));
+      return nErrorCode;
+   }
+
+   *phNewObject = sOperation.params[0].value.a;
+
+   return CKR_OK;
+}
diff --git a/security/tf_crypto_sst/pkcs11_session.c b/security/tf_crypto_sst/pkcs11_session.c
new file mode 100644
index 0000000..bc845c7
--- /dev/null
+++ b/security/tf_crypto_sst/pkcs11_session.c
@@ -0,0 +1,420 @@
+/**
+ * Copyright(c) 2011 Trusted Logic.   All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *  * Neither the name Trusted Logic nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Implementation Notes:
+ *
+ * The PKCS11 session handle is directly mapped on the
+ * Trusted Foundations Software session handle (S_HANDLE).
+ */
+
+#include "pkcs11_internal.h"
+
+
+/* ------------------------------------------------------------------------
+                          Public Functions
+------------------------------------------------------------------------- */
+
+
+CK_RV PKCS11_EXPORT C_OpenSession(CK_SLOT_ID              slotID,        /* the slot's ID */
+                                    CK_FLAGS              flags,         /* defined in CK_SESSION_INFO */
+                                    CK_VOID_PTR           pApplication,  /* pointer passed to callback */
+                                    CK_NOTIFY             Notify,        /* notification callback function */
+                                    CK_SESSION_HANDLE*    phSession)     /* receives new session handle */
+{
+   CK_RV                   nErrorCode = CKR_OK;
+   uint32_t                nErrorOrigin = TEEC_ORIGIN_API;
+   TEEC_Result             nTeeError;
+   TEEC_Operation          sOperation;
+   PPKCS11_PRIMARY_SESSION_CONTEXT   pSession = NULL;
+   PPKCS11_SECONDARY_SESSION_CONTEXT pSecondarySession = NULL;
+   uint32_t                nLoginType;
+   uint32_t                nLoginData = 0;
+   void*                   pLoginData = NULL;
+   bool                    bIsPrimarySession;
+   char*                   pSignatureFile = NULL;
+   uint32_t                nSignatureFileLen = 0;
+   uint8_t                 nParamType3 = TEEC_NONE;
+
+   /* Prevent the compiler from complaining about unused parameters */
+   do{(void)pApplication;}while(0);
+   do{(void)Notify;}while(0);
+
+   if (phSession == NULL)
+   {
+      return CKR_ARGUMENTS_BAD;
+   }
+
+      /* Check Cryptoki is initialized */
+   if (!g_bCryptokiInitialized)
+   {
+      return CKR_CRYPTOKI_NOT_INITIALIZED;
+   }
+
+   if ((flags & CKVF_OPEN_SUB_SESSION) == 0)
+   {
+      *phSession = CK_INVALID_HANDLE;
+
+      /*
+      * Allocate the session context
+      */
+      pSession = (PPKCS11_PRIMARY_SESSION_CONTEXT)malloc(sizeof(PKCS11_PRIMARY_SESSION_CONTEXT));
+      if (pSession == NULL)
+      {
+         return CKR_DEVICE_MEMORY;
+      }
+
+      pSession->sHeader.nMagicWord  = PKCS11_SESSION_MAGIC;
+      pSession->sHeader.nSessionTag = PKCS11_PRIMARY_SESSION_TAG;
+      memset(&pSession->sSession, 0, sizeof(TEEC_Session));
+      pSession->sSecondarySessionTable.pRoot = NULL_PTR;
+
+      /* The structure must be initialized first (in a portable manner)
+         to make it work on Win32 */
+      memset(&pSession->sSecondarySessionTableMutex, 0,
+               sizeof(pSession->sSecondarySessionTableMutex));
+      libMutexInit(&pSession->sSecondarySessionTableMutex);
+
+      switch (slotID)
+      {
+      case CKV_TOKEN_SYSTEM_SHARED:
+      case CKV_TOKEN_USER_SHARED:
+         nLoginType = TEEC_LOGIN_PUBLIC;
+         break;
+
+      case CKV_TOKEN_SYSTEM:
+      case CKV_TOKEN_USER:
+      default:
+         nLoginType = TEEC_LOGIN_AUTHENTICATION;
+         break;
+      }
+
+      /* Group tokens */
+      if ((slotID >= 0x00010000) && (slotID <= 0x0002FFFF))
+      {
+         nLoginType = TEEC_LOGIN_GROUP;
+
+         /* The 16 lower-order bits encode the group identifier */
+         nLoginData = (uint32_t)slotID & 0x0000FFFF;
+         pLoginData = (void*)&nLoginData;
+
+         /* Update the slotID for the system / PKCS11 service */
+         if ((slotID >= 0x00010000) && (slotID <= 0x0001FFFF))
+         {
+            /* System group token */
+            slotID = 3;       /* CKV_TOKEN_SYSTEM_GROUP */
+         }
+         else  /* ((slotID >= 0x00020000) && (slotID <= 0x0002FFFF)) */
+         {
+            /* User group token */
+            slotID = 0x4014;  /* CKV_TOKEN_USER_GROUP */
+         }
+      }
+
+retry:
+      memset(&sOperation, 0, sizeof(TEEC_Operation));
+
+      if (nLoginType == TEEC_LOGIN_AUTHENTICATION)
+      {
+          nTeeError = TEEC_ReadSignatureFile((void **)&pSignatureFile, &nSignatureFileLen);
+          if (nTeeError != TEEC_ERROR_ITEM_NOT_FOUND)
+          {
+              if (nTeeError != TEEC_SUCCESS)
+              {
+                  goto error;
+              }
+
+              sOperation.params[3].tmpref.buffer = pSignatureFile;
+              sOperation.params[3].tmpref.size   = nSignatureFileLen;
+              nParamType3 = TEEC_MEMREF_TEMP_INPUT;
+          }
+          else
+          {
+              /* No signature file found.
+              * Should use LOGIN_APPLICATION for now
+              * Can not use TEEC_LOGIN_AUTHENTICATION as this means that all .exe wil need a signature file
+              * - a bit annoying for when passing the tests
+              */
+              nLoginType = TEEC_LOGIN_USER_APPLICATION;
+          }
+      }
+
+      sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_NONE, TEEC_NONE, TEEC_NONE, nParamType3);
+      nTeeError = TEEC_OpenSession(&g_sContext,
+                                &pSession->sSession,        /* OUT session */
+                                &SERVICE_UUID,              /* destination UUID */
+                                nLoginType,                 /* connectionMethod */
+                                pLoginData,                 /* connectionData */
+                                &sOperation,                /* IN OUT operation */
+                                NULL                        /* OUT returnOrigin, optional */
+                                );
+      if (nTeeError != TEEC_SUCCESS)
+      {
+         /* No need of the returnOrigin as this is not specific to P11 */
+
+         if (  (nTeeError == TEEC_ERROR_NOT_SUPPORTED) &&
+               (nLoginType == TEEC_LOGIN_AUTHENTICATION))
+         {
+            /* We could not open a session with the login TEEC_LOGIN_AUTHENTICATION */
+            /* If it is not supported by the product, */
+            /* retry with fallback to TEEC_LOGIN_USER_APPLICATION */
+            nLoginType = TEEC_LOGIN_USER_APPLICATION;
+            goto retry;
+         }
+
+         /* The ERROR_ACCESS_DENIED, if returned, will be converted into CKR_TOKEN_NOT_PRESENT
+          * For the External Cryptographic API, this means that the authentication
+          * of the calling application fails.
+          */
+         goto error;
+      }
+
+      memset(&sOperation, 0, sizeof(TEEC_Operation));
+      sOperation.params[0].value.a = slotID;
+      sOperation.params[0].value.b = flags;  /* access flags */
+      sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INOUT, TEEC_NONE, TEEC_NONE, TEEC_NONE);
+      nTeeError = TEEC_InvokeCommand(&pSession->sSession,
+                                  SERVICE_SYSTEM_PKCS11_C_OPEN_SESSION_COMMAND_ID & 0x00007FFF,
+                                  &sOperation,              /* IN OUT operation */
+                                  &nErrorOrigin             /* OUT returnOrigin, optional */
+                                 );
+      if (nTeeError != TEEC_SUCCESS)
+      {
+         goto error;
+      }
+
+      *phSession = (CK_SESSION_HANDLE)pSession;
+      pSession->hCryptoSession = sOperation.params[0].value.a;
+
+      return CKR_OK;
+   }
+   else
+   {
+      bool bResult;
+
+      /* Check that {*phSession} is a valid primary session handle */
+      if ((!ckInternalSessionIsOpenedEx(*phSession, &bIsPrimarySession)) ||
+         (!bIsPrimarySession))
+      {
+         return CKR_SESSION_HANDLE_INVALID;
+      }
+
+      pSession = (PPKCS11_PRIMARY_SESSION_CONTEXT)(*phSession);
+
+      /* allocate the secondary session context */
+      pSecondarySession = (PKCS11_SECONDARY_SESSION_CONTEXT*)malloc(sizeof(PKCS11_SECONDARY_SESSION_CONTEXT));
+      if (pSecondarySession == NULL)
+      {
+         return CKR_DEVICE_MEMORY;
+      }
+      pSecondarySession->sHeader.nMagicWord  = PKCS11_SESSION_MAGIC;
+      pSecondarySession->sHeader.nSessionTag = PKCS11_SECONDARY_SESSION_TAG;
+      pSecondarySession->pPrimarySession = pSession;
+
+      libMutexLock(&pSession->sSecondarySessionTableMutex);
+      bResult = libObjectHandle16Add(&pSession->sSecondarySessionTable,
+                                    &pSecondarySession->sSecondarySessionNode);
+      libMutexUnlock(&pSession->sSecondarySessionTableMutex);
+      if (bResult == false)
+      {
+         free(pSecondarySession);
+         return CKR_DEVICE_MEMORY;
+      }
+
+      memset(&sOperation, 0, sizeof(TEEC_Operation));
+      sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INOUT, TEEC_NONE, TEEC_NONE, TEEC_NONE);
+      nTeeError = TEEC_InvokeCommand(&pSession->sSession,
+                                  (pSession->hCryptoSession << 16) |
+                                    (1 << 15) |
+                                    (SERVICE_SYSTEM_PKCS11_C_OPEN_SESSION_COMMAND_ID & 0x00007FFF),
+                                  &sOperation,                 /* IN OUT operation */
+                                  &nErrorOrigin                /* OUT returnOrigin, optional */
+                                 );
+      if (nTeeError != TEEC_SUCCESS)
+      {
+         goto error;
+      }
+
+      *phSession = (CK_SESSION_HANDLE)pSecondarySession;
+      pSecondarySession->hSecondaryCryptoSession = sOperation.params[0].value.a;
+
+      return CKR_OK;
+   }
+
+error:
+   nErrorCode = (nErrorOrigin == TEEC_ORIGIN_TRUSTED_APP ?
+                  nTeeError :
+                  ckInternalTeeErrorToCKError(nTeeError));
+
+   if ((flags & CKVF_OPEN_SUB_SESSION) == 0)
+   {
+      libMutexDestroy(&pSession->sSecondarySessionTableMutex);
+      free(pSession);
+   }
+   else
+   {
+      libMutexLock(&pSession->sSecondarySessionTableMutex);
+      libObjectHandle16Remove(&pSession->sSecondarySessionTable,&pSecondarySession->sSecondarySessionNode);
+      libMutexUnlock(&pSession->sSecondarySessionTableMutex);
+      free(pSecondarySession);
+   }
+
+   return nErrorCode;
+}
+
+CK_RV PKCS11_EXPORT C_CloseSession(CK_SESSION_HANDLE hSession) /* the session's handle */
+{
+   CK_RV                   nErrorCode = CKR_OK;
+   uint32_t                nErrorOrigin = TEEC_ORIGIN_API;
+   TEEC_Result             nTeeError;
+   TEEC_Operation          sOperation;
+   bool                    bIsPrimarySession;
+
+   /* Check Cryptoki is initialized */
+   if (!g_bCryptokiInitialized)
+   {
+      return CKR_CRYPTOKI_NOT_INITIALIZED;
+   }
+
+   if (!ckInternalSessionIsOpenedEx(hSession, &bIsPrimarySession))
+   {
+      return CKR_SESSION_HANDLE_INVALID;
+   }
+
+   if (bIsPrimarySession)
+   {
+      LIB_OBJECT_NODE_HANDLE16*           pObject;
+      PPKCS11_SECONDARY_SESSION_CONTEXT   pSecSession;
+      PPKCS11_PRIMARY_SESSION_CONTEXT     pSession = (PPKCS11_PRIMARY_SESSION_CONTEXT)hSession;
+
+      hSession = pSession->hCryptoSession;
+
+      memset(&sOperation, 0, sizeof(TEEC_Operation));
+      sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_NONE, TEEC_NONE, TEEC_NONE, TEEC_NONE);
+      nTeeError = TEEC_InvokeCommand(&pSession->sSession,
+                                  (pSession->hCryptoSession << 16 ) |
+                                    (SERVICE_SYSTEM_PKCS11_C_CLOSE_SESSION_COMMAND_ID & 0x00007FFF),
+                                  &sOperation,                 /* IN OUT operation */
+                                  &nErrorOrigin                /* OUT returnOrigin, optional */
+                                 );
+      if (nTeeError != TEEC_SUCCESS)
+      {
+         goto end;
+      }
+
+      TEEC_CloseSession(&pSession->sSession);
+      memset(&pSession->sSession, 0, sizeof(TEEC_Session));
+
+      /* Free all secondary session contexts */
+      libMutexLock(&pSession->sSecondarySessionTableMutex);
+      pObject = libObjectHandle16RemoveOne(&pSession->sSecondarySessionTable);
+      while (pObject != NULL)
+      {
+         /* find all secondary session contexts,
+            and release associated resources */
+
+         pSecSession = LIB_OBJECT_CONTAINER_OF(pObject, //ptr
+                                               PKCS11_SECONDARY_SESSION_CONTEXT,//type
+                                               sSecondarySessionNode);//member
+
+         /* free secondary session context */
+         free(pSecSession);
+
+         pObject = libObjectHandle16RemoveOne(&pSession->sSecondarySessionTable);
+      }
+      libMutexUnlock(&pSession->sSecondarySessionTableMutex);
+
+      libMutexDestroy(&pSession->sSecondarySessionTableMutex);
+
+      /* free primary session context */
+      free(pSession);
+   }
+   else
+   {
+      PPKCS11_SECONDARY_SESSION_CONTEXT pSecSession = (PPKCS11_SECONDARY_SESSION_CONTEXT)hSession;
+      PPKCS11_PRIMARY_SESSION_CONTEXT   pSession;
+
+      uint32_t nCommandID = ( (pSecSession->hSecondaryCryptoSession & 0xFFFF) << 16 ) |
+                              (1 << 15) |
+                              (SERVICE_SYSTEM_PKCS11_C_CLOSE_SESSION_COMMAND_ID & 0x00007FFF);
+
+      /* every pre-check are fine, then, update the local handles */
+      hSession = pSecSession->pPrimarySession->hCryptoSession;
+      pSession = (PPKCS11_PRIMARY_SESSION_CONTEXT)(pSecSession->pPrimarySession);
+
+      memset(&sOperation, 0, sizeof(TEEC_Operation));
+      sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_NONE, TEEC_NONE, TEEC_NONE, TEEC_NONE);
+      nTeeError = TEEC_InvokeCommand(&pSession->sSession,
+                                  nCommandID,
+                                  &sOperation,                 /* IN OUT operation */
+                                  &nErrorOrigin                /* OUT returnOrigin, optional */
+                                 );
+      if (nTeeError != TEEC_SUCCESS)
+      {
+         goto end;
+      }
+
+      /* remove the object from the table */
+      libMutexLock(&pSession->sSecondarySessionTableMutex);
+      libObjectHandle16Remove(&pSecSession->pPrimarySession->sSecondarySessionTable, &pSecSession->sSecondarySessionNode);
+      libMutexUnlock(&pSession->sSecondarySessionTableMutex);
+
+      /* free secondary session context */
+      free(pSecSession);
+   }
+
+end:
+   nErrorCode = (nErrorOrigin == TEEC_ORIGIN_TRUSTED_APP ?
+                  nTeeError :
+                  ckInternalTeeErrorToCKError(nTeeError));
+   return nErrorCode;
+}
+
+
+CK_RV PKCS11_EXPORT C_Login(CK_SESSION_HANDLE hSession,  /* the session's handle */
+                              CK_USER_TYPE      userType,  /* the user type */
+                              const CK_UTF8CHAR*   pPin,      /* the user's PIN */
+                              CK_ULONG          ulPinLen)  /* the length of the PIN */
+{
+   /* Prevent the compiler from complaining about unused variables */
+   do{(void)hSession;}while(0);
+   do{(void)userType;}while(0);
+   do{(void)pPin;}while(0);
+   do{(void)ulPinLen;}while(0);
+
+   return CKR_OK;
+}
+
+CK_RV PKCS11_EXPORT C_Logout(CK_SESSION_HANDLE hSession) /* the session's handle */
+{
+   do{(void)hSession;}while(0);
+
+   return CKR_OK;
+}
diff --git a/security/tf_crypto_sst/service_system_protocol.h b/security/tf_crypto_sst/service_system_protocol.h
new file mode 100644
index 0000000..560ec40
--- /dev/null
+++ b/security/tf_crypto_sst/service_system_protocol.h
@@ -0,0 +1,116 @@
+/**
+ * Copyright(c) 2011 Trusted Logic.   All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *  * Neither the name Trusted Logic nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __SERVICE_SYSTEM_PROTOCOL_H__
+#define __SERVICE_SYSTEM_PROTOCOL_H__
+
+#include "s_type.h"
+
+/* -----------------------------------------------------------------------------
+      UUID and Name
+----------------------------------------------------------------------------- */
+
+/** Service Identifier */
+/* {56304b83-5c4e-4428-b99e-605c96ae58d6} */
+#define SERVICE_SYSTEM_UUID   { 0x56304b83, 0x5c4e, 0x4428, { 0xb9, 0x9e, 0x60, 0x5c, 0x96, 0xae, 0x58, 0xd6 } }
+
+/** Generic type for error codes in the system service */
+#define SERVICE_SYSTEM_NAME_ASCII  "SYSTEM"
+
+
+/* -----------------------------------------------------------------------------
+                               SST Command identifiers
+----------------------------------------------------------------------------- */
+
+#define SERVICE_SYSTEM_SST_OPEN_COMMAND_ID                0x00000001
+#define SERVICE_SYSTEM_SST_CLOSE_COMMAND_ID               0x00000002
+#define SERVICE_SYSTEM_SST_READ_COMMAND_ID                0x00000003
+#define SERVICE_SYSTEM_SST_WRITE_COMMAND_ID               0x00000004
+#define SERVICE_SYSTEM_SST_SEEK_COMMAND_ID                0x00000005
+#define SERVICE_SYSTEM_SST_GET_OFFSET_AND_SIZE_COMMAND_ID 0x00000007
+#define SERVICE_SYSTEM_SST_GET_SIZE_COMMAND_ID            0x00000008
+#define SERVICE_SYSTEM_SST_CLOSE_DELETE_COMMAND_ID        0x00000009
+#define SERVICE_SYSTEM_SST_TRUNCATE_COMMAND_ID            0x0000000A
+#define SERVICE_SYSTEM_SST_ENUM_START_COMMAND_ID          0x0000000B
+#define SERVICE_SYSTEM_SST_ENUM_GETNEXT_COMMAND_ID        0x0000000C
+#define SERVICE_SYSTEM_SST_ENUM_CLOSE_COMMAND_ID          0x0000000D
+#define SERVICE_SYSTEM_SST_RENAME_COMMAND_ID              0x0000000E
+
+/* -----------------------------------------------------------------------------
+                      PKCS11/MTC Command identifiers
+----------------------------------------------------------------------------- */
+#define SERVICE_SYSTEM_PKCS11_C_CREATEOBJECT_COMMAND_ID      0x00000020
+#define SERVICE_SYSTEM_PKCS11_C_DESTROYOBJECT_COMMAND_ID     0x00000021
+#define SERVICE_SYSTEM_PKCS11_C_GETATTRIBUTEVALUE_COMMAND_ID 0x00000022
+#define SERVICE_SYSTEM_PKCS11_C_FINDOBJECTSINIT_COMMAND_ID   0x00000023
+#define SERVICE_SYSTEM_PKCS11_C_FINDOBJECTS_COMMAND_ID       0x00000024
+#define SERVICE_SYSTEM_PKCS11_C_FINDOBJECTSFINAL_COMMAND_ID  0x00000025
+#define SERVICE_SYSTEM_PKCS11_C_DIGESTINIT_COMMAND_ID        0x00000026
+#define SERVICE_SYSTEM_PKCS11_C_DIGEST_COMMAND_ID            0x00000027
+#define SERVICE_SYSTEM_PKCS11_C_DIGESTUPDATE_COMMAND_ID      0x00000028
+#define SERVICE_SYSTEM_PKCS11_C_DIGESTFINAL_COMMAND_ID       0x00000029
+#define SERVICE_SYSTEM_PKCS11_C_SIGNINIT_COMMAND_ID          0x0000002A
+#define SERVICE_SYSTEM_PKCS11_C_SIGN_COMMAND_ID              0x0000002B
+#define SERVICE_SYSTEM_PKCS11_C_SIGNUPDATE_COMMAND_ID        0x0000002C
+#define SERVICE_SYSTEM_PKCS11_C_SIGNFINAL_COMMAND_ID         0x0000002D
+#define SERVICE_SYSTEM_PKCS11_C_ENCRYPTINIT_COMMAND_ID       0x0000002E
+#define SERVICE_SYSTEM_PKCS11_C_ENCRYPT_COMMAND_ID           0x0000002F
+#define SERVICE_SYSTEM_PKCS11_C_ENCRYPTUPDATE_COMMAND_ID     0x00000030
+#define SERVICE_SYSTEM_PKCS11_C_ENCRYPTFINAL_COMMAND_ID      0x00000031
+#define SERVICE_SYSTEM_PKCS11_C_DECRYPTINIT_COMMAND_ID       0x00000032
+#define SERVICE_SYSTEM_PKCS11_C_DECRYPT_COMMAND_ID           0x00000033
+#define SERVICE_SYSTEM_PKCS11_C_DECRYPTUPDATE_COMMAND_ID     0x00000034
+#define SERVICE_SYSTEM_PKCS11_C_DECRYPTFINAL_COMMAND_ID      0x00000035
+#define SERVICE_SYSTEM_PKCS11_C_GENERATEKEY_COMMAND_ID       0x00000036
+#define SERVICE_SYSTEM_PKCS11_C_GENERATEKEYPAIR_COMMAND_ID   0x00000037
+#define SERVICE_SYSTEM_PKCS11_C_SEEDRANDOM_COMMAND_ID        0x00000038
+#define SERVICE_SYSTEM_PKCS11_C_GENERATERANDOM_COMMAND_ID    0x00000039
+#define SERVICE_SYSTEM_PKCS11_C_VERIFYINIT_COMMAND_ID        0x0000003A
+#define SERVICE_SYSTEM_PKCS11_C_VERIFY_COMMAND_ID            0x0000003B
+#define SERVICE_SYSTEM_PKCS11_C_VERIFYUPDATE_COMMAND_ID      0x0000003C
+#define SERVICE_SYSTEM_PKCS11_C_VERIFYFINAL_COMMAND_ID       0x0000003D
+#define SERVICE_SYSTEM_PKCS11_C_DERIVEKEY_COMMAND_ID         0x0000003E
+#define SERVICE_SYSTEM_PKCS11_C_ABORTOPERATION_COMMAND_ID    0x0000003F
+#define SERVICE_SYSTEM_PKCS11_C_COPYOBJECT_COMMAND_ID        0x00000040
+#define SERVICE_SYSTEM_PKCS11_C_CLOSEOBJECTHANDLE_COMMAND_ID 0x00000041
+#define SERVICE_SYSTEM_PKCS11_C_OPEN_SESSION_COMMAND_ID      0x00000042
+#define SERVICE_SYSTEM_PKCS11_C_CLOSE_SESSION_COMMAND_ID     0x00000043
+#define SERVICE_SYSTEM_PKCS11_INCREMENT_MTC_COMMAND_ID       0x00000044
+#define SERVICE_SYSTEM_PKCS11_GET_MTC_COMMAND_ID             0x00000045
+
+typedef struct
+{
+   uint32_t             attributeType;
+   uint32_t             dataOffset : 30;
+   uint32_t             dataParamIndex  : 2;
+   uint32_t             dataValueLen;
+} INPUT_TEMPLATE_ITEM;
+
+#endif /* __SERVICE_SYSTEM_PROTOCOL_H__ */
diff --git a/security/tf_crypto_sst/sst_stub.c b/security/tf_crypto_sst/sst_stub.c
new file mode 100644
index 0000000..e8a78bc
--- /dev/null
+++ b/security/tf_crypto_sst/sst_stub.c
@@ -0,0 +1,800 @@
+/**
+ * Copyright(c) 2011 Trusted Logic.   All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *  * Neither the name Trusted Logic nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifdef __ANDROID32__
+#include <stddef.h>
+#endif
+
+#include <stdlib.h>
+#include <string.h>
+
+#define SST_EXPORTS
+#define EXCLUDE_SERVICE_SYSTEM_SST_BASIC_TYPES
+#include "sst.h"
+
+/* Included for the TEE management */
+#include "pkcs11_internal.h"
+
+
+static TEEC_Session g_SSTSession;
+static bool g_bSSTInitialized = false;
+
+
+/* ------------------------------------------------------------------------
+            TEEC -> SST error code translation
+  ------------------------------------------------------------------------- */
+static SST_ERROR static_SSTConvertErrorCode(TEEC_Result nError)
+{
+   switch (nError)
+   {
+      case TEEC_SUCCESS:
+         return SST_SUCCESS;
+      case SST_ERROR_BAD_PARAMETERS:
+      case SST_ERROR_ACCESS_DENIED:
+      case SST_ERROR_ACCESS_CONFLICT:
+      case SST_ERROR_CORRUPTED:
+      case SST_ERROR_NO_SPACE:
+      case SST_ERROR_ITEM_NOT_FOUND:
+      case SST_ERROR_OUT_OF_MEMORY:
+      case SST_ERROR_OVERFLOW:
+         return nError;
+      default:
+         return SST_ERROR_GENERIC;
+   }
+}
+
+static TEEC_Session* static_SSTGetSession(void)
+{
+   if (g_bSSTInitialized)
+   {
+      return &g_SSTSession;
+   }
+
+   return NULL;
+}
+
+SST_ERROR SST_EXPORT_API SSTInit(void)
+{
+   TEEC_Result          nTeeError = TEEC_SUCCESS;
+   TEEC_Operation       sOperation;
+   uint8_t              nParamType3 = TEEC_NONE;
+   void*                pSignatureFile = NULL;
+   uint32_t             nSignatureFileLen = 0;
+   uint32_t             nLoginType;
+
+   stubMutexLock();
+   if (g_bSSTInitialized)
+   {
+      /* SST library already initialized */
+      nTeeError = TEEC_SUCCESS;
+      goto end;
+   }
+
+   nTeeError = stubInitializeContext();
+   if (nTeeError != TEEC_SUCCESS)
+   {
+      goto end;
+   }
+
+   /* Check if there is a signature file.
+    * If yes, send it in param3, otherwise use LOGIN_APPLICATION
+    */
+   nTeeError =  TEEC_ReadSignatureFile(&pSignatureFile, &nSignatureFileLen);
+   if (nTeeError == TEEC_ERROR_ITEM_NOT_FOUND)
+   {
+      nLoginType = TEEC_LOGIN_USER_APPLICATION;
+   }
+   else
+   {
+       if (nTeeError != TEEC_SUCCESS)
+       {
+           goto end;
+       }
+       sOperation.params[3].tmpref.buffer = pSignatureFile;
+       sOperation.params[3].tmpref.size   = nSignatureFileLen;
+       nParamType3 = TEEC_MEMREF_TEMP_INPUT;
+       nLoginType = TEEC_LOGIN_AUTHENTICATION;
+   }
+
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_NONE, TEEC_NONE, TEEC_NONE, nParamType3);
+   nTeeError = TEEC_OpenSession(&g_sContext,
+                             &g_SSTSession,              /* OUT session */
+                             &SERVICE_UUID,              /* destination UUID */
+                             nLoginType,                 /* connectionMethod */
+                             NULL,                       /* connectionData */
+                             &sOperation,                /* IN OUT operation */
+                             NULL                        /* OUT returnOrigin, optional */
+                             );
+   if (nTeeError != TEEC_SUCCESS)
+   {
+      goto end_finalize_context;
+   }
+
+   g_bSSTInitialized = true;
+   stubMutexUnlock();
+   return SST_SUCCESS;
+
+end_finalize_context:
+   stubFinalizeContext();
+end:
+   stubMutexUnlock();
+   return static_SSTConvertErrorCode(nTeeError);
+}
+
+SST_ERROR SST_EXPORT_API SSTTerminate(void)
+{
+   stubMutexLock();
+   if (g_bSSTInitialized)
+   {
+      TEEC_CloseSession(&g_SSTSession);
+      stubFinalizeContext();
+      g_bSSTInitialized = false;
+   }
+   /* else if not intialized => success too */
+   stubMutexUnlock();
+   return SST_SUCCESS;
+}
+
+
+/* ------------------------------------------------------------------------
+                           Other API Functions
+------------------------------------------------------------------------- */
+
+
+/* Check that the input filename is well-formed */
+static SST_ERROR static_SSTCheckFileName(const char* pName)
+{
+   uint32_t i;
+   char     c;
+
+   if (pName == NULL)
+   {
+      return SST_ERROR_BAD_PARAMETERS;
+   }
+
+   for (i = 0; i <= SST_MAX_FILENAME; i++)
+   {
+      c = pName[i];
+      if (c == 0)
+      {
+         /* End of the string */
+         return SST_SUCCESS;
+      }
+
+      if (c == '/' || c == '\\')
+      {
+         /* Invalid character */
+         return SST_ERROR_BAD_PARAMETERS;
+      }
+
+      if (c < 0x20 || c >= 0x7F)
+      {
+         /* Filename contains illegal characters */
+         return SST_ERROR_BAD_PARAMETERS;
+      }
+   }
+   /* Filename is too long. Zero terminator not found */
+   return SST_ERROR_BAD_PARAMETERS;
+}
+
+static SST_ERROR static_SSTCheckPattern(
+      const char* pFilenamePattern)
+{
+   uint32_t i;
+   if(pFilenamePattern == NULL)
+   {
+      return S_SUCCESS;
+   }
+
+   /**
+    * Check Forbidden characters.
+    */
+   for (i = 0; pFilenamePattern[i] != 0; i++)
+   {
+      if(pFilenamePattern[i] < 0x20 )
+      {
+         return S_ERROR_BAD_PARAMETERS;
+      }
+      else if(pFilenamePattern[i] == 0x2F ) /* '/' */
+      {
+         return S_ERROR_BAD_PARAMETERS;
+      }
+      else if(pFilenamePattern[i] == 0x5C ) /* '\' */
+      {
+         /**
+          * Must be directly followed by asterisk character or question-mark
+          * character.
+          */
+         if (! ((pFilenamePattern[i+1] == '*' ||
+                   pFilenamePattern[i+1] == '?')))
+         {
+            return S_ERROR_BAD_PARAMETERS;
+         }
+      }
+      else if(pFilenamePattern[i] >= 0x7F )
+      {
+         return S_ERROR_BAD_PARAMETERS;
+      }
+   }
+
+   return S_SUCCESS;
+}
+
+
+
+SST_ERROR SST_EXPORT_API SSTOpen(const char* pFilename,
+                                 uint32_t    nFlags,
+                                 uint32_t    nReserved,
+                                 SST_HANDLE* phFile)
+{
+   TEEC_Session*     pSession;
+   TEEC_Result       nError;
+   TEEC_Operation    sOperation;
+   uint32_t          nReturnOrigin;
+   SST_ERROR         nErrorCode = SST_SUCCESS;
+
+   if (phFile == NULL || nReserved != 0)
+   {
+      return SST_ERROR_BAD_PARAMETERS;
+   }
+
+   *phFile = SST_HANDLE_INVALID;
+
+   nErrorCode = static_SSTCheckFileName(pFilename);
+   if (nErrorCode != SST_SUCCESS)
+   {
+      return nErrorCode;
+   }
+
+   pSession = static_SSTGetSession();
+   if (pSession == NULL)
+   {
+      return SST_ERROR_GENERIC;
+   }
+
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INOUT, TEEC_MEMREF_TEMP_INPUT, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].value.a = 1;      /* Private storage */
+   sOperation.params[0].value.b = nFlags; /* Access flags */
+   sOperation.params[1].tmpref.buffer = (void*)pFilename;
+   sOperation.params[1].tmpref.size   = strlen(pFilename);
+   nError = TEEC_InvokeCommand(pSession,
+                               SERVICE_SYSTEM_SST_OPEN_COMMAND_ID,   /* commandID */
+                               &sOperation,                 /* IN OUT operation */
+                               &nReturnOrigin               /* OUT returnOrigin, optional */
+                              );
+   if (nError == TEEC_SUCCESS)
+   {
+      *phFile = (SST_HANDLE)sOperation.params[0].value.a;
+   }
+
+   return static_SSTConvertErrorCode(nError);
+}
+
+SST_ERROR SST_EXPORT_API SSTCloseHandle(SST_HANDLE  hFile)
+{
+   TEEC_Session*     pSession;
+   TEEC_Result        nError;
+   TEEC_Operation    sOperation;
+   uint32_t          nReturnOrigin;
+
+   if (hFile == S_HANDLE_NULL)
+   {
+      return SST_SUCCESS;
+   }
+
+   pSession = static_SSTGetSession();
+   if (pSession == NULL)
+   {
+      return SST_ERROR_GENERIC;
+   }
+
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INPUT, TEEC_NONE, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].value.a = hFile;
+   nError = TEEC_InvokeCommand(pSession,
+                               SERVICE_SYSTEM_SST_CLOSE_COMMAND_ID, /* commandID */
+                               &sOperation,                  /* IN OUT operation */
+                               &nReturnOrigin            /* OUT returnOrigin, optional */
+                              );
+
+   return static_SSTConvertErrorCode(nError);
+}
+
+SST_ERROR SST_EXPORT_API SSTWrite(SST_HANDLE       hFile,
+                                  const uint8_t*   pBuffer,
+                                  uint32_t         nSize)
+{
+   TEEC_Session*     pSession;
+   TEEC_Result       nError;
+   TEEC_Operation    sOperation;
+   uint32_t          nReturnOrigin;
+
+   if (pBuffer == NULL)
+   {
+      return SST_ERROR_BAD_PARAMETERS;
+   }
+
+   if (nSize == 0)
+   {
+      return SST_SUCCESS;
+   }
+
+   pSession = static_SSTGetSession();
+   if (pSession == NULL)
+   {
+      return SST_ERROR_GENERIC;
+   }
+
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INPUT, TEEC_MEMREF_TEMP_INPUT, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].value.a       = hFile;
+   sOperation.params[1].tmpref.buffer = (void*)pBuffer;
+   sOperation.params[1].tmpref.size   = nSize;
+
+   nError = TEEC_InvokeCommand(pSession,
+                               SERVICE_SYSTEM_SST_WRITE_COMMAND_ID, /* commandID */
+                               &sOperation,                  /* IN OUT operation */
+                               &nReturnOrigin            /* OUT returnOrigin, optional */
+                              );
+
+   return static_SSTConvertErrorCode(nError);
+}
+
+
+SST_ERROR SST_EXPORT_API SSTRead(SST_HANDLE   hFile,
+                                 uint8_t*     pBuffer,
+                                 uint32_t     nSize,
+                                 uint32_t*    pnCount)
+{
+   TEEC_Session*     pSession;
+   TEEC_Result       nError;
+   TEEC_Operation    sOperation;
+   uint32_t          nReturnOrigin;
+
+   if ((pBuffer == NULL) || (pnCount == NULL))
+   {
+      return SST_ERROR_BAD_PARAMETERS;
+   }
+   *pnCount = 0;
+
+   pSession = static_SSTGetSession();
+   if (pSession == NULL)
+   {
+      return SST_ERROR_GENERIC;
+   }
+
+   if (nSize == 0)
+   {
+      return SST_SUCCESS;
+   }
+
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INPUT, TEEC_MEMREF_TEMP_OUTPUT, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].value.a       = hFile;
+   sOperation.params[1].tmpref.buffer = pBuffer;
+   sOperation.params[1].tmpref.size   = nSize;
+
+   nError = TEEC_InvokeCommand(pSession,
+                               SERVICE_SYSTEM_SST_READ_COMMAND_ID, /* commandID */
+                               &sOperation,                  /* IN OUT operation */
+                               &nReturnOrigin            /* OUT returnOrigin, optional */
+                              );
+
+   *pnCount = sOperation.params[1].tmpref.size; /* The returned buffer size */
+   return static_SSTConvertErrorCode(nError);
+}
+
+SST_ERROR SST_EXPORT_API SSTSeek(SST_HANDLE   hFile,
+                                 int32_t     nOffset,
+                                 SST_WHENCE   whence)
+{
+   TEEC_Session*     pSession;
+   TEEC_Result       nError;
+   TEEC_Operation    sOperation;
+   uint32_t          nReturnOrigin;
+
+   switch(whence)
+   {
+   case SST_SEEK_SET:
+   case SST_SEEK_CUR:
+   case SST_SEEK_END:
+      break;
+   default:
+      return SST_ERROR_BAD_PARAMETERS;
+   }
+
+   pSession = static_SSTGetSession();
+   if (pSession == NULL)
+   {
+      return SST_ERROR_GENERIC;
+   }
+
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INPUT, TEEC_VALUE_INPUT, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].value.a = hFile;
+   sOperation.params[1].value.a = nOffset;
+   sOperation.params[1].value.b = (uint32_t)whence;
+
+   nError = TEEC_InvokeCommand(pSession,
+                               SERVICE_SYSTEM_SST_SEEK_COMMAND_ID, /* commandID */
+                               &sOperation,                  /* IN OUT operation */
+                               &nReturnOrigin            /* OUT returnOrigin, optional */
+                              );
+   return static_SSTConvertErrorCode(nError);
+
+}
+
+static SST_ERROR SSTGetOffsetAndSize(SST_HANDLE   hFile, uint32_t* pnOffset, uint32_t* pnSize)
+{
+   TEEC_Session*     pSession;
+   TEEC_Result       nError;
+   TEEC_Operation    sOperation;
+   uint32_t          nReturnOrigin;
+
+   pSession = static_SSTGetSession();
+   if (pSession == NULL)
+   {
+      return SST_ERROR_GENERIC;
+   }
+
+   if (pnOffset == NULL)
+   {
+      return SST_ERROR_BAD_PARAMETERS;
+   }
+
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INOUT, TEEC_NONE, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].value.a = (uint32_t)hFile;
+
+   nError = TEEC_InvokeCommand(pSession,
+                               SERVICE_SYSTEM_SST_GET_OFFSET_AND_SIZE_COMMAND_ID, /* commandID */
+                               &sOperation,                  /* IN OUT operation */
+                               &nReturnOrigin            /* OUT returnOrigin, optional */
+                              );
+
+   if (pnOffset != NULL)
+   {
+      *pnOffset = sOperation.params[0].value.a;
+   }
+   if (pnSize != NULL)
+   {
+      *pnSize = sOperation.params[0].value.b;
+   }
+   return static_SSTConvertErrorCode(nError);
+
+}
+
+SST_ERROR SST_EXPORT_API SSTTell(SST_HANDLE   hFile,
+                                 uint32_t*    pnPos)
+{
+   return SSTGetOffsetAndSize(hFile, pnPos, NULL);
+}
+
+SST_ERROR SST_EXPORT_API SSTGetSize(const char*  pFilename,
+                                    uint32_t*    pnSize)
+{
+   TEEC_Session*     pSession;
+   TEEC_Result       nError;
+   TEEC_Operation    sOperation;
+   uint32_t          nReturnOrigin;
+
+   if ((pFilename == NULL) || (pnSize == NULL))
+   {
+      return SST_ERROR_BAD_PARAMETERS;
+   }
+
+   nError = static_SSTCheckFileName(pFilename);
+   if (nError != SST_SUCCESS)
+   {
+      return nError;
+   }
+
+   pSession = static_SSTGetSession();
+   if (pSession == NULL)
+   {
+      return SST_ERROR_GENERIC;
+   }
+
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INOUT, TEEC_MEMREF_TEMP_INPUT, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].value.a = 1; /* private storage */
+   sOperation.params[0].value.b = 0;
+   sOperation.params[1].tmpref.buffer = (void*)pFilename;
+   sOperation.params[1].tmpref.size   = strlen(pFilename);
+
+   nError = TEEC_InvokeCommand(pSession,
+                               SERVICE_SYSTEM_SST_GET_SIZE_COMMAND_ID, /* commandID */
+                               &sOperation,                  /* IN OUT operation */
+                               &nReturnOrigin            /* OUT returnOrigin, optional */
+                              );
+
+   *pnSize = sOperation.params[0].value.a;
+   return static_SSTConvertErrorCode(nError);
+}
+
+
+SST_ERROR SST_EXPORT_API SSTEof( SST_HANDLE   hFile,
+                                 bool*        pbEof)
+{
+   uint32_t nOffset;
+   uint32_t nSize;
+   SST_ERROR nError;
+   if (pbEof == NULL)
+      return SST_ERROR_BAD_PARAMETERS;
+   nError = SSTGetOffsetAndSize(hFile, &nOffset, &nSize);
+   if (nError == SST_SUCCESS)
+   {
+      if (nOffset >= nSize)
+      {
+         *pbEof = true;
+      }
+      else
+      {
+         *pbEof = false;
+      }
+   }
+   return nError;
+}
+
+SST_ERROR SST_EXPORT_API SSTCloseAndDelete(SST_HANDLE  hFile)
+{
+   TEEC_Session*     pSession;
+   TEEC_Result       nError;
+   TEEC_Operation    sOperation;
+   uint32_t          nReturnOrigin;
+
+   pSession = static_SSTGetSession();
+   if (pSession == NULL)
+   {
+      return SST_ERROR_GENERIC;
+   }
+
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INPUT, TEEC_NONE, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].value.a = hFile;
+
+   nError = TEEC_InvokeCommand(pSession,
+                               SERVICE_SYSTEM_SST_CLOSE_DELETE_COMMAND_ID, /* commandID */
+                               &sOperation,                  /* IN OUT operation */
+                               &nReturnOrigin            /* OUT returnOrigin, optional */
+                              );
+   return static_SSTConvertErrorCode(nError);
+}
+
+SST_ERROR SST_EXPORT_API SSTTruncate(SST_HANDLE hFile, uint32_t nLength)
+{
+   TEEC_Session*     pSession;
+   TEEC_Result       nError;
+   TEEC_Operation    sOperation;
+   uint32_t          nReturnOrigin;
+
+   pSession = static_SSTGetSession();
+   if (pSession == NULL)
+   {
+      return SST_ERROR_GENERIC;
+   }
+
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INPUT, TEEC_NONE, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].value.a = hFile;
+   sOperation.params[0].value.b = nLength;
+
+   nError = TEEC_InvokeCommand(pSession,
+                               SERVICE_SYSTEM_SST_TRUNCATE_COMMAND_ID, /* commandID */
+                               &sOperation,                  /* IN OUT operation */
+                               &nReturnOrigin            /* OUT returnOrigin, optional */
+                              );
+   return static_SSTConvertErrorCode(nError);
+}
+
+SST_ERROR SST_EXPORT_API SSTRename(SST_HANDLE hFile,
+                                   const char* pNewFilename)
+{
+   TEEC_Session*     pSession;
+   TEEC_Result       nError;
+   TEEC_Operation    sOperation;
+   uint32_t          nReturnOrigin;
+
+   pSession = static_SSTGetSession();
+   if (pSession == NULL)
+   {
+      return SST_ERROR_GENERIC;
+   }
+
+   if (pNewFilename == NULL)
+   {
+      return SST_ERROR_BAD_PARAMETERS;
+   }
+
+   nError = static_SSTCheckFileName(pNewFilename);
+   if (nError != SST_SUCCESS)
+   {
+      return nError;
+   }
+
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INPUT, TEEC_MEMREF_TEMP_INPUT, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].value.a = hFile;
+   sOperation.params[1].tmpref.buffer = (void*)pNewFilename;
+   sOperation.params[1].tmpref.size   = strlen(pNewFilename);
+
+   nError = TEEC_InvokeCommand(pSession,
+                               SERVICE_SYSTEM_SST_RENAME_COMMAND_ID, /* commandID */
+                               &sOperation,                  /* IN OUT operation */
+                               &nReturnOrigin            /* OUT returnOrigin, optional */
+                              );
+      return static_SSTConvertErrorCode(nError);
+}
+
+SST_ERROR SST_EXPORT_API SSTEnumerationStart(const char* pFilenamePattern,
+                                             uint32_t  nReserved1,
+                                             uint32_t  nReserved2,
+                                             SST_HANDLE* phFileEnumeration)
+{
+   TEEC_Session*     pSession;
+   TEEC_Result       nError;
+   TEEC_Operation    sOperation;
+   uint32_t          nReturnOrigin;
+
+   if (nReserved1!=0 || nReserved2!=0)
+   {
+      return SST_ERROR_BAD_PARAMETERS;
+   }
+   if (phFileEnumeration==NULL)
+   {
+      return SST_ERROR_BAD_PARAMETERS;
+   }
+   *phFileEnumeration = SST_HANDLE_INVALID;
+
+   nError = static_SSTCheckPattern(pFilenamePattern);
+   if (nError != SST_SUCCESS)
+   {
+      return nError;
+   }
+
+   pSession = static_SSTGetSession();
+   if (pSession == NULL)
+   {
+      return SST_ERROR_GENERIC;
+   }
+
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INOUT, TEEC_MEMREF_TEMP_INPUT, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].value.a = 1;      /* Private storage */
+   sOperation.params[1].tmpref.buffer = (void*)pFilenamePattern;
+   if (pFilenamePattern != NULL)
+   {
+      sOperation.params[1].tmpref.size   = strlen(pFilenamePattern);
+   }
+   else
+   {
+      sOperation.params[1].tmpref.size   = 0;
+   }
+
+   nError = TEEC_InvokeCommand(pSession,
+                               SERVICE_SYSTEM_SST_ENUM_START_COMMAND_ID, /* commandID */
+                               &sOperation,                  /* IN OUT operation */
+                               &nReturnOrigin            /* OUT returnOrigin, optional */
+                              );
+
+   *phFileEnumeration = (SST_HANDLE)sOperation.params[0].value.a;
+   return static_SSTConvertErrorCode(nError);
+}
+
+SST_ERROR SST_EXPORT_API SSTEnumerationCloseHandle(SST_HANDLE hFileEnumeration)
+{
+   TEEC_Session*     pSession;
+   TEEC_Result       nError;
+   TEEC_Operation    sOperation;
+   uint32_t          nReturnOrigin;
+
+   pSession = static_SSTGetSession();
+   if (pSession == NULL)
+   {
+      return SST_ERROR_GENERIC;
+   }
+
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INPUT, TEEC_NONE, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].value.a = hFileEnumeration;
+
+   nError = TEEC_InvokeCommand(pSession,
+                               SERVICE_SYSTEM_SST_ENUM_CLOSE_COMMAND_ID, /* commandID */
+                               &sOperation,                  /* IN OUT operation */
+                               &nReturnOrigin                /* OUT returnOrigin, optional */
+                              );
+
+   return static_SSTConvertErrorCode(nError);
+}
+
+SST_ERROR SST_EXPORT_API SSTEnumerationGetNext(SST_HANDLE      hFileEnumeration,
+                                               SST_FILE_INFO**   ppFileInfo)
+
+{
+   TEEC_Session*     pSession;
+   TEEC_Result       nError;
+   TEEC_Operation    sOperation;
+   uint32_t          nReturnOrigin;
+   SST_FILE_INFO*    pInfo = NULL;
+   char              sFilename[SST_MAX_FILENAME];
+
+   if (ppFileInfo==NULL)
+   {
+      return SST_ERROR_BAD_PARAMETERS;
+   }
+
+   pSession = static_SSTGetSession();
+   if (pSession == NULL)
+   {
+      return SST_ERROR_GENERIC;
+   }
+
+   sOperation.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INOUT, TEEC_MEMREF_TEMP_OUTPUT, TEEC_NONE, TEEC_NONE);
+   sOperation.params[0].value.a = hFileEnumeration;
+   sOperation.params[1].tmpref.buffer = sFilename;
+   sOperation.params[1].tmpref.size   = SST_MAX_FILENAME;
+
+   nError = TEEC_InvokeCommand(pSession,
+                               SERVICE_SYSTEM_SST_ENUM_GETNEXT_COMMAND_ID, /* commandID */
+                               &sOperation,                  /* IN OUT operation */
+                               &nReturnOrigin            /* OUT returnOrigin, optional */
+                              );
+
+   if (nError == TEEC_SUCCESS)
+   {
+      if (sOperation.params[1].tmpref.size <= SST_MAX_FILENAME)
+      {
+         pInfo = (SST_FILE_INFO*)malloc(sizeof(SST_FILE_INFO));
+         if (pInfo == NULL)
+         {
+            return SST_ERROR_OUT_OF_MEMORY;
+         }
+         pInfo->pName = (char*)malloc(sOperation.params[1].tmpref.size+1);
+         if (pInfo->pName == NULL)
+         {
+            free(pInfo);
+            return SST_ERROR_OUT_OF_MEMORY;
+         }
+         memcpy(pInfo->pName, sFilename, sOperation.params[1].tmpref.size);
+         /* Add zero terminator */
+         pInfo->pName[sOperation.params[1].tmpref.size] = 0;
+         pInfo->nSize = sOperation.params[0].value.b;
+      }
+   }
+  *ppFileInfo = pInfo;
+   return static_SSTConvertErrorCode(nError);
+ }
+
+SST_ERROR SST_EXPORT_API SSTDestroyFileInfo(SST_FILE_INFO*   pFileInfo)
+{
+   TEEC_Session*  pSession;
+
+   pSession = static_SSTGetSession();
+   if (pSession == NULL)
+   {
+      return SST_ERROR_GENERIC;
+   }
+
+   if (pFileInfo != NULL)
+   {
+      free(pFileInfo->pName);
+      free(pFileInfo);
+   }
+   return SST_SUCCESS;
+}
diff --git a/security/tf_daemon/Android.mk b/security/tf_daemon/Android.mk
index dbfbb4a..eccba3d 100644
--- a/security/tf_daemon/Android.mk
+++ b/security/tf_daemon/Android.mk
@@ -13,8 +13,6 @@
 	smc_properties_parser.c \
 	lib_manifest2.c
 
-LOCAL_LDLIBS += -llog
-
 LOCAL_CFLAGS += -DLINUX
 LOCAL_CFLAGS += -D__ANDROID32__
 LOCAL_CFLAGS += -DSUPPORT_DELEGATION_EXTENSION
diff --git a/security/tf_daemon/delegation_client.c b/security/tf_daemon/delegation_client.c
index a2bff0b..54ee112 100644
--- a/security/tf_daemon/delegation_client.c
+++ b/security/tf_daemon/delegation_client.c
@@ -28,7 +28,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#if defined(ANDROID)
+#if defined(__ANDROID32__)
 #include <stddef.h>
 #endif
 #include <stdio.h>
@@ -43,12 +43,12 @@
 #include <sys/types.h>
 #include <fcntl.h>
 
-#if defined(LINUX) || defined(ANDROID)
+#if defined(LINUX) || defined(__ANDROID32__)
 #include <unistd.h>
 #include <sys/resource.h>
 
 
-#if defined(ANDROID)
+#if defined(__ANDROID32__)
 /* fdatasync does not exist on Android */
 #define fdatasync fsync
 #else
@@ -58,14 +58,14 @@
  * in some distributions
  */
 int fdatasync(int fd);
-#endif /* ANDROID */
+#endif /* __ANDROID32__ */
 #include <syslog.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <pthread.h>
 #include <semaphore.h>
 #define PATH_SEPARATOR '/'
-#endif /* LINUX || ANDROID */
+#endif /* LINUX || __ANDROID32__ */
 
 #ifdef WIN32
 #include <windows.h>
@@ -97,10 +97,6 @@
 #include "delegation_client_extension.h"
 #endif
 
-#ifdef TFSW_FDM_ANDROID
-#include <android/log.h>
-#endif
-
 /*----------------------------------------------------------------------------
  * Design notes
  * ============
@@ -113,7 +109,7 @@
 /*----------------------------------------------------------------------------
  * Defines and structures
  *----------------------------------------------------------------------------*/
-#define ECHANGE_BUFFER_INSTRUCTIONS_NB 1000
+#define ECHANGE_BUFFER_INSTRUCTIONS_NB 100
 
 #define DEFAULT_WORKSPACE_SIZE (128*1024)
 
@@ -128,21 +124,6 @@
    uint8_t                        sWorkspace[1/*g_nWorkspaceSize*/];
 } DELEGATION_EXCHANGE_BUFFER;
 
-#ifdef SUPPORT_RPMB_PARTITION
-typedef struct
-{
-   uint8_t pDummy[196];
-   uint8_t pMAC[32];
-   uint8_t pData[256];
-   uint8_t pNonce[16];
-   uint32_t nMC;
-   uint16_t nAddr;
-   uint16_t nBlockCount;
-   uint16_t nResult;
-   uint16_t nReqOrResp;
-} DELEGATION_RPMB_MESSAGE;
-#endif
-
 #define MD_VAR_NOT_USED(variable)  do{(void)(variable);}while(0);
 
 #define MD_INLINE __inline
@@ -160,7 +141,7 @@
    in release builds whereas logs are visible to the customer.
 
    -----------------------------------------------*/
-#if defined(LINUX) || (defined ANDROID)
+#if defined(LINUX) || (defined __ANDROID32__)
 
 static bool bDetached = false;
 
@@ -174,13 +155,9 @@
    }
    else
    {
-#ifdef TFSW_FDM_ANDROID
-	   __android_log_vprint(ANDROID_LOG_ERROR   , "TF Daemon", format, ap);
-#else
       fprintf(stderr, "ERROR: ");
       vfprintf(stderr, format, ap);
       fprintf(stderr, "\n");
-#endif
    }
    va_end(ap);
 }
@@ -195,13 +172,9 @@
    }
    else
    {
-#ifdef TFSW_FDM_ANDROID
-	   __android_log_vprint(ANDROID_LOG_WARN   , "TF Daemon", format, ap);
-#else
       fprintf(stderr, "WARNING: ");
       vfprintf(stderr, format, ap);
       fprintf(stderr, "\n");
-#endif
    }
    va_end(ap);
 }
@@ -215,12 +188,8 @@
    }
    else
    {
-#ifdef TFSW_FDM_ANDROID
-	   __android_log_vprint(ANDROID_LOG_INFO   , "TF Daemon", format, ap);
-#else
       vfprintf(stderr, format, ap);
       fprintf(stderr, "\n");
-#endif
    }
    va_end(ap);
 }
@@ -236,13 +205,9 @@
    }
    else
    {
-#ifdef TFSW_FDM_ANDROID
-	   __android_log_vprint(ANDROID_LOG_ERROR   , "TF Daemon", format, ap);
-#else
       fprintf(stderr, "TRACE: ERROR: ");
       vfprintf(stderr, format, ap);
       fprintf(stderr, "\n");
-#endif
    }
    va_end(ap);
 #else
@@ -261,13 +226,9 @@
    }
    else
    {
-#ifdef TFSW_FDM_ANDROID
-	   __android_log_vprint(ANDROID_LOG_WARN   , "TF Daemon", format, ap);
-#else
       fprintf(stderr, "TRACE: WARNING: ");
       vfprintf(stderr, format, ap);
       fprintf(stderr, "\n");
-#endif
    }
    va_end(ap);
 #else
@@ -286,13 +247,9 @@
    }
    else
    {
-#ifdef TFSW_FDM_ANDROID
-	   __android_log_vprint(ANDROID_LOG_INFO   , "TF Daemon", format, ap);
-#else
       fprintf(stderr, "TRACE: ");
       vfprintf(stderr, format, ap);
       fprintf(stderr, "\n");
-#endif
    }
    va_end(ap);
 #else
@@ -332,7 +289,7 @@
 }
 
 #else
-/* !defined(LINUX) || !defined(ANDROID) */
+/* !defined(LINUX) || !defined(__ANDROID32__) */
 
 static MD_INLINE void LogError(const char* format, ...)
 {
@@ -402,7 +359,7 @@
    MD_VAR_NOT_USED(format);
 #endif /* NDEBUG */
 }
-#endif /* defined(LINUX) || defined(ANDROID) */
+#endif /* defined(LINUX) || defined(__ANDROID32__) */
 
 /*----------------------------------------------------------------------------
  * Globals
@@ -526,7 +483,7 @@
    if (result == 0)
    {
       /* Storage dir exists. Check access rights */
-#if defined(LINUX) || (defined ANDROID)
+#if defined(LINUX) || (defined __ANDROID32__)
       if ((buf.st_mode & (S_IXUSR | S_IWUSR)) != (S_IXUSR | S_IWUSR))
       {
          LogError("storageDir '%s' does not have read-write access", directoryName);
@@ -572,7 +529,7 @@
    }
 
    /* Try to erase the file */
-#if defined(LINUX) || (defined ANDROID) || defined (__SYMBIAN32__)
+#if defined(LINUX) || (defined __ANDROID32__) || defined (__SYMBIAN32__)
    if (unlink(g_pPartitionNames[nPartitionID]) != 0)
 #endif
 #ifdef WIN32
@@ -729,46 +686,6 @@
    return S_SUCCESS;
 }
 
-#ifdef SUPPORT_RPMB_PARTITION
-static TEEC_Result rpmbRead(DELEGATION_RPMB_INSTRUCTION *pInstruction)
-{
-   DELEGATION_RPMB_MESSAGE* pMessages;
-   uint32_t nNbMsg, nIndex;
-
-   nNbMsg = g_nSectorSize >> 8;
-   pMessages = (DELEGATION_RPMB_MESSAGE*)malloc(nNbMsg * sizeof(DELEGATION_RPMB_MESSAGE));
-   if (pMessages == NULL)
-   {
-      return S_ERROR_OUT_OF_MEMORY;
-   }
-   memset(pMessages,0,nNbMsg * sizeof(DELEGATION_RPMB_MESSAGE));
-
-   for (nIndex=0;nIndex<nNbMsg;nIndex++)
-   {
-      memcpy(pMessages[nIndex].pNonce , pInstruction->pNonce, 16);
-      pMessages[nIndex].nAddr = pInstruction->nAddr;
-      pMessages[nIndex].nBlockCount = pInstruction->nBlockCount;
-      pMessages[nIndex].nReqOrResp = 0x0004;
-   }
-   memcpy(pMessages[nNbMsg-1].pMAC,pInstruction->nMAC,32);
-
-   /* TODO: send to the RPMB driver */
-
-   memcpy(pInstruction->pNonce,pMessages[0].pNonce , 16);
-   pInstruction->nAddr = pMessages[0].nAddr;
-   pInstruction->nBlockCount = pMessages[0].nBlockCount;
-   for (nIndex=0;nIndex<nNbMsg;nIndex++)
-   {
-      memcpy(g_pWorkspaceBuffer + pInstruction->nWorkspaceOffset[nIndex],pMessages[nIndex].pData,256);
-   }
-   memcpy(pInstruction->nMAC, pMessages[nNbMsg-1].pMAC,32);
-   pInstruction->nResult=pMessages[nNbMsg-1].nResult;
-
-   free(pMessages);
-
-   return S_SUCCESS;
-}
-#endif
 /**
  * This function executes the WRITE instruction.
  *
@@ -807,42 +724,7 @@
    return S_SUCCESS;
 }
 
-#ifdef SUPPORT_RPMB_PARTITION
-static TEEC_Result rpmbWrite(DELEGATION_RPMB_INSTRUCTION *pInstruction)
-{
-   DELEGATION_RPMB_MESSAGE* pMessages;
-   uint32_t nNbMsg, nIndex;
 
-   nNbMsg = g_nSectorSize >> 8;
-   pMessages = (DELEGATION_RPMB_MESSAGE*)malloc(nNbMsg * sizeof(DELEGATION_RPMB_MESSAGE));
-   if (pMessages == NULL)
-   {
-      return S_ERROR_OUT_OF_MEMORY;
-   }
-   memset(pMessages,0,nNbMsg * sizeof(DELEGATION_RPMB_MESSAGE));
-
-   for (nIndex=0;nIndex<nNbMsg;nIndex++)
-   {
-      memcpy(pMessages[nIndex].pData,g_pWorkspaceBuffer + pInstruction->nWorkspaceOffset[nIndex],256);
-      pMessages[nIndex].nMC = pInstruction->nMC;
-      pMessages[nIndex].nAddr = pInstruction->nAddr;
-      pMessages[nIndex].nBlockCount = pInstruction->nBlockCount;
-      pMessages[nIndex].nReqOrResp = 0x0003;
-   }
-   memcpy(pMessages[nNbMsg-1].pMAC,pInstruction->nMAC,32);
-
-   /* TODO: send to the RPMB driver */
-
-   pInstruction->nAddr = pMessages[0].nAddr;
-   pInstruction->nMC = pMessages[0].nMC;
-   memcpy(pInstruction->nMAC, pMessages[nNbMsg-1].pMAC,32);
-   pInstruction->nResult=pMessages[nNbMsg-1].nResult;
-
-   free(pMessages);
-
-   return S_SUCCESS;
-}
-#endif
 /**
  * This function executes the SET_SIZE instruction.
  *
@@ -892,7 +774,7 @@
    {
       int result = 0;
       /* Truncate the partition file */
-#if defined(LINUX) || (defined ANDROID)
+#if defined(LINUX) || (defined __ANDROID32__)
       result = ftruncate(fileno(pFile),nNewSectorCount * g_nSectorSize);
 #endif
 #if defined (__SYMBIAN32__)
@@ -937,7 +819,7 @@
    }
    /* Then synchronize the file descriptor with the file-system */
 
-#if defined(LINUX) || (defined ANDROID)
+#if defined(LINUX) || (defined __ANDROID32__)
    result=fdatasync(fileno(pFile));
 #endif
 #if defined (__SYMBIAN32__)
@@ -1126,13 +1008,6 @@
                {
                case DELEGATION_INSTRUCTION_PARTITION_CREATE:
                   nError = partitionCreate(nPartitionID);
-#ifdef SUPPORT_RPMB_PARTITION
-                  if (nPartitionID == RPMB_PARTITION_ID)
-                  {
-                     /* TODO: get the Write counter */
-                     pInstruction->sAuthRW.nMC = 0;
-                  }
-#endif
                   TRACE_INFO("INSTRUCTION: ID=0x%x pid=%d err=%d", (nInstructionID & 0x0F), nPartitionID, nError);
                   break;
                case DELEGATION_INSTRUCTION_PARTITION_OPEN:
@@ -1144,33 +1019,9 @@
                      {
                         g_pExchangeBuffer->sAdministrativeData.nPartitionOpenSizes[nPartitionID] = nPartitionSize;
                      }
-#ifdef SUPPORT_RPMB_PARTITION
-                     if (nPartitionID == RPMB_PARTITION_ID)
-                     {
-                        /* TODO: get the Write counter */
-                        pInstruction->sAuthRW.nMC = 0;
-                     }
-#endif
                      break;
                   }
                case DELEGATION_INSTRUCTION_PARTITION_READ:
-#ifdef SUPPORT_RPMB_PARTITION
-                  if (nPartitionID == RPMB_PARTITION_ID)
-                  {
-                     if (nInstructionsIndex + sizeof(DELEGATION_RPMB_INSTRUCTION)-sizeof(uint32_t) <= nInstructionsBufferSize)
-                     {
-                        nInstructionsIndex+=sizeof(DELEGATION_RPMB_INSTRUCTION)-sizeof(uint32_t);
-                     }
-                     else
-                     {
-                        goto instruction_parse_end;
-                     }
-                     nError = rpmbRead(&pInstruction->sAuthRW);
-                     TRACE_INFO("INSTRUCTION: ID=0x%x pid=%d err=%d", (nInstructionID & 0x0F), nPartitionID, nError);
-                     break;
-                  }
-                  else
-#endif
                   {
                      /* Parse parameters */
                      uint32_t nSectorID;
@@ -1190,23 +1041,6 @@
                      break;
                   }
                case DELEGATION_INSTRUCTION_PARTITION_WRITE:
-#ifdef SUPPORT_RPMB_PARTITION
-                  if (nPartitionID == RPMB_PARTITION_ID)
-                  {
-                     if (nInstructionsIndex + sizeof(DELEGATION_RPMB_INSTRUCTION)-sizeof(uint32_t) <= nInstructionsBufferSize)
-                     {
-                        nInstructionsIndex+=sizeof(DELEGATION_RPMB_INSTRUCTION)-sizeof(uint32_t);
-                     }
-                     else
-                     {
-                        goto instruction_parse_end;
-                     }
-                     nError = rpmbWrite(&pInstruction->sAuthRW);
-                     TRACE_INFO("INSTRUCTION: ID=0x%x pid=%d err=%d", (nInstructionID & 0x0F), nPartitionID, nError);
-                     break;
-                  }
-                  else
-#endif
                   {
                      /* Parse parameters */
                      uint32_t nSectorID;
@@ -1483,7 +1317,7 @@
     * Detach the daemon from the console
     */
 
-#if defined(LINUX) || (defined ANDROID)
+#if defined(LINUX) || (defined __ANDROID32__)
    {
       /*
        * Turns this application into a daemon => fork off parent process, setup logging, ...
diff --git a/security/tf_daemon/lib_uuid.h b/security/tf_daemon/lib_uuid.h
deleted file mode 100644
index acec4a0..0000000
--- a/security/tf_daemon/lib_uuid.h
+++ /dev/null
@@ -1,155 +0,0 @@
-/**
- * Copyright(c) 2011 Trusted Logic.   All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *  * Neither the name Trusted Logic nor the names of its
- *    contributors may be used to endorse or promote products derived
- *    from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef __LIB_UUID_H__
-#define __LIB_UUID_H__
-
-
-#include "s_type.h"
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-#if 0
-}  /* balance curly quotes */
-#endif
-
-/**
- * LIB_UUID is deprecated use S_UUID instead.
- * @deprecated
- */
-typedef S_UUID LIB_UUID;
-/**
- * LIB_UUID_STRING_SIZE is deprecated use UUID_STRING_SIZE instead.
- * @deprecated
- */
-#define LIB_UUID_STRING_SIZE  36
-
-/**
- * Defines the UUID string size in characters
- *
- * E.g. "f81d4fae-7dec-11d0-a765-00a0c91e6bf6"
- **/
-#define UUID_STRING_SIZE  36
-
-/**
- * Converts the string representation of an UUID to the binary representation as
- * a S_UUID type. The binary UUID structure must be provided by the caller.
- *
- * @param   pIdentifierString  The UTF-8 representation of the identifier. This
- *          string does not need to be zero terminated. The decoder reads only
- *          the {UUID_STRING_SIZE} first bytes.
- *
- * @param   pIdentifier  The identifer structure receiving the binary value of
- *          the identifier.
- *
- * @return  TRUE in case of success, FALSE if the string does not conform to the
- *          syntax of UUID as defined in RFC 4122
- *          (http://www.ietf.org/rfc/rfc4122.txt)
- **/
-bool libUUIDFromString(
-      IN  const uint8_t* pIdentifierString,
-      OUT S_UUID* pIdentifier);
-
-/**
- * Converts the binary representation of an UUID to the string representation.
- *
- * @param   pIdentifier  The identifer structure with the binary value of the
- *          identifier.
- *
- * @param   pIdentifierString  The buffer receiving the UTF-8 representation of
- *          the identifier. This string is not zero terminated. The encoder
- *          writes only the first {UUID_STRING_SIZE} bytes.
- *
- **/
-void libUUIDToString(
-      IN  const S_UUID* pIdentifier,
-      OUT uint8_t* pIdentifierString);
-
-/**
- * Generates an UUID from the specified MD5 hash value, as specified in section
- * 4.3, Algorithm for Creating a Name-Based UUID, of RFC 4122.
- *
- * This function assumes that the hash value is 128-bit long.
- *
- * @param pHashData A pointer to the first byte of the MD5 hash data. Only the
- * first 16 bytes of this hash data will be used to generate the UUID.
- *
- * @param pIdentifier A pointer to the placeholder receiving the generated
- * identifier.
- **/
-void libUUIDFromMD5Hash(
-      IN  const uint8_t* pHashData,
-      OUT S_UUID* pIdentifier);
-
-/**
- * Generates an UUID from the specified SHA-1 hash value, as specified in
- * section 4.3, Algorithm for Creating a Name-Based UUID, of RFC 4122.
- *
- * This function assumes that the hash value is 128-bit long.
- *
- * @param pHashData A pointer to the first byte of the SHA-1 hash data. Only the
- * first 16 bytes of this hash data will be used to generate the UUID.
- *
- * @param pIdentifier A pointer to the placeholder receiving the generated
- * identifier.
- **/
-void libUUIDFromSHA1Hash(
-      IN  const uint8_t* pHashData,
-      OUT S_UUID* pIdentifier);
-
-/**
- * Checks if an identifier is the nil identifier as specified in RFC 4122.
- *
- * @param   pIdentifier  The identifier to check.
- *
- * @return  TRUE if the identifier is the nil identifier, FALSE otherwise.
- **/
-bool libUUIDIsNil(
-      IN  const S_UUID* pIdentifier);
-
-/**
- * Sets an identifier to the nil value as specified in RFC 4122.
- *
- * @param   pIdentifier  The identifier to set to nil.
- **/
-void libUUIDSetToNil(
-      OUT S_UUID* pIdentifier);
-
-#if 0
-{  /* balance curly quotes */
-#endif
-#ifdef __cplusplus
-}  /* closes extern "C" */
-#endif
-
-
-#endif  /* !defined(__LIB_UUID_H__) */
diff --git a/security/tf_daemon/s_version.h b/security/tf_daemon/s_version.h
index f712db2..d112ea0 100644
--- a/security/tf_daemon/s_version.h
+++ b/security/tf_daemon/s_version.h
@@ -58,15 +58,15 @@
 /*
  * This version number must be updated for each new release
  */
-#define S_VERSION_MAIN  "01.06"
-#define S_VERSION_RESOURCE 1,6,0,S_VERSION_BUILD
+#define S_VERSION_MAIN  "01.04"
+#define S_VERSION_RESOURCE 1,4,0,S_VERSION_BUILD
 
 /*
 * If this is a patch or engineering version use the following
 * defines to set the version number. Else set these values to 0.
 */
+#define S_VERSION_PATCH 11
 #define S_VERSION_ENG 0
-#define S_VERSION_PATCH 0
 
 #ifdef S_VERSION_BUILD
 /* TRICK: detect if S_VERSION is defined but empty */
@@ -105,8 +105,8 @@
 	S_VERSION_OS \
 	S_VERSION_PLATFORM \
 	S_VERSION_MAIN \
-	_S_VERSION_ENG \
 	_S_VERSION_PATCH \
+	_S_VERSION_ENG \
 	"."  __STRINGIFY2(S_VERSION_BUILD) " " \
 	S_VERSION_VARIANT
 
diff --git a/security/tf_daemon/service_delegation_protocol.h b/security/tf_daemon/service_delegation_protocol.h
index bf831f8..22b291d 100644
--- a/security/tf_daemon/service_delegation_protocol.h
+++ b/security/tf_daemon/service_delegation_protocol.h
@@ -70,10 +70,6 @@
 #define DELEGATION_NOTIFY_TYPE_INFO                 0x000000E3
 #define DELEGATION_NOTIFY_TYPE_DEBUG                0x000000E4
 
-#ifdef SUPPORT_RPMB_PARTITION
-#define RPMB_PARTITION_ID                 14
-#endif
-
 typedef struct
 {
    uint32_t nInstructionID;
@@ -94,21 +90,6 @@
    uint32_t nWorkspaceOffset;
 } DELEGATION_RW_INSTRUCTION;
 
-#ifdef SUPPORT_RPMB_PARTITION
-typedef struct
-{
-   uint32_t nInstructionID;
-   uint8_t  nMAC[32];
-   uint32_t nWorkspaceOffset[16];
-   uint8_t  pNonce[16];
-   uint32_t nMC;
-   uint16_t nAddr;
-   uint16_t nBlockCount;
-   uint16_t nResult;
-   uint16_t nRequest;
-} DELEGATION_RPMB_INSTRUCTION;
-#endif
-
 typedef struct
 {
    uint32_t nInstructionID;
@@ -121,9 +102,6 @@
    DELEGATION_NOTIFY_INSTRUCTION     sNotify;
    DELEGATION_RW_INSTRUCTION         sReadWrite;
    DELEGATION_SET_SIZE_INSTRUCTION   sSetSize;
-#ifdef SUPPORT_RPMB_PARTITION
-   DELEGATION_RPMB_INSTRUCTION       sAuthRW;
-#endif
 } DELEGATION_INSTRUCTION;
 
 typedef struct
diff --git a/security/tf_daemon/smc_properties.c b/security/tf_daemon/smc_properties.c
index 48bfa8c..ce1e7e3 100644
--- a/security/tf_daemon/smc_properties.c
+++ b/security/tf_daemon/smc_properties.c
@@ -76,7 +76,7 @@
    STATE_BINARY
 } INTEGER_FORMAT;
 
-#if defined (LINUX) || defined(ANDROID)
+#if defined (LINUX) || defined(__ANDROID32__)
 #define SEPARATOR_CHAR '/'
 
 #elif defined (WIN32) || defined (__SYMBIAN32__) || defined (_WIN32_WCE)
@@ -151,7 +151,7 @@
          printf("Path %s doesn't point on a directory.\n", pDir);
          return false;
       }
-#if (!defined(__SYMBIAN32__)) && (!defined(_WIN32_WCE)) && (!defined(ANDROID))
+#if (!defined(__SYMBIAN32__)) && (!defined(_WIN32_WCE)) && (!defined(__ANDROID32__))
       // TODO : under Symbian, Android and WM, check access right of a directory failed? I don't know why...
        /* check read access */
        if ((buf.st_mode & S_IREAD) != S_IREAD)
diff --git a/security/tf_daemon/smc_properties_parser.c b/security/tf_daemon/smc_properties_parser.c
index 8d0d676..1f97224 100644
--- a/security/tf_daemon/smc_properties_parser.c
+++ b/security/tf_daemon/smc_properties_parser.c
@@ -42,7 +42,6 @@
 
 #include "smc_properties_parser.h"
 #include "lib_manifest2.h"
-#include "lib_uuid.h"
 #include "s_error.h"
 
 /* ---------------------------------------------------------------------------------
@@ -58,7 +57,7 @@
 #define GET_LAST_ERR  errno
 #endif
 
-#if defined (LINUX) || defined (__SYMBIAN32__) || defined (ANDROID)
+#if defined (LINUX) || defined (__SYMBIAN32__) || defined (__ANDROID32__)
 #define STRICMP strcasecmp
 #elif defined(_WIN32_WCE)
 #define STRICMP _stricmp
@@ -242,7 +241,7 @@
 
 
 static S_RESULT SMCPropYacc(uint8_t* pBuffer, uint32_t nBufferLength,
-                     CONF_FILE* pConfFile, SERVICE_SECTION* pService)
+                     CONF_FILE* pConfFile)
 {
    S_RESULT nError=S_SUCCESS;
    LIST *pPublicPropertyList=NULL;
@@ -265,15 +264,6 @@
    sParserContext.nManifestLength = nBufferLength;
    sParserContext.nType = LIB_MANIFEST2_TYPE_SOURCE_WITH_SECTIONS;
 
-   if (pService!=NULL)
-   {
-      pPublicPropertyList=&pService->sPublicPropertyList;
-      pPrivatePropertyList=&pService->sPrivatePropertyList;
-      /* read inside a service compiled manifest */
-      sParserContext.nType = LIB_MANIFEST2_TYPE_COMPILED;
-      sprintf(serviceManifestName, "%s(manifest)", pService->sNode.pName);
-      sParserContext.pManifestName = serviceManifestName;
-   }
    libManifest2InitContext(&sParserContext);
 
    while (true)
@@ -392,47 +382,6 @@
          }
          else
          {
-            if (strcmp(pProperty->sNode.pName,CONFIG_SERVICE_ID_PROPERTY_NAME) == 0)
-            {
-               if (pService!=NULL)
-               {
-                  pService->sNode.pName=malloc(nValueLength+1);
-                  if (pService->sNode.pName==NULL)
-                  {
-                     nError=S_ERROR_OUT_OF_MEMORY;
-                     goto error;
-                  }
-#if defined (LINUX) || defined (__SYMBIAN32__) || defined(ANDROID)
-                  {
-                     // put each char of the value in uppercase
-                     char* p=pProperty->pValue;
-                     while(*p)
-                     {
-                        *p=toupper(*p);
-                        p++;
-                     }
-                  }
-#else
-                  _strupr(pProperty->pValue);
-#endif
-                  memcpy(pService->sNode.pName,pProperty->pValue,nValueLength+1);
-
-                  if (!libUUIDFromString((const uint8_t*)pProperty->pValue,&pService->sUUID))
-                  {
-                     nError=S_ERROR_WRONG_SIGNATURE;
-                     goto error;
-                  }
-                  {
-                     S_UUID sNullUUID;
-                     memset(&sNullUUID,0,sizeof(S_UUID));
-                     if (!memcmp(&pService->sUUID,&sNullUUID,sizeof(S_UUID)))
-                     {
-                        nError=S_ERROR_WRONG_SIGNATURE;
-                        goto error;
-                     }
-                  }
-               }
-            }
             if ((nValueLength > strlen(CONFIG_PROPERTY_NAME)) &&
                 (memcmp(pProperty->sNode.pName, CONFIG_PROPERTY_NAME, strlen(CONFIG_PROPERTY_NAME)) == 0))
             {
@@ -462,10 +411,10 @@
          TRACE_ERROR("Configuration file: wrong service UUID: %s\n", pValueZ);
          break;
       case S_ERROR_OUT_OF_MEMORY:
-         TRACE_ERROR("Out of memory\n");
+	  TRACE_ERROR("Out of memory\n");
          break;
       case S_ERROR_ITEM_NOT_FOUND:
-         TRACE_ERROR("Configuration file: service \"%s\" not found\n", pNameZ);
+	  TRACE_ERROR("Configuration file: service \"%s\" not found\n", pNameZ);
          break;
       }
    }
@@ -595,7 +544,7 @@
       assert(0);
    }
 
-   nError=SMCPropYacc(pFile,nFileLength,pConfFile,NULL);
+   nError=SMCPropYacc(pFile,nFileLength,pConfFile);
 
    if(pConfigFilename != NULL)
    {
diff --git a/security/tf_sdk/include/s_type.h b/security/tf_sdk/include/s_type.h
index ae260cc..72f2a8a 100644
--- a/security/tf_sdk/include/s_type.h
+++ b/security/tf_sdk/include/s_type.h
@@ -35,7 +35,7 @@
 #define __S_TYPE_H__
 
 /* C99 integer types */
-#if (!defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L) &&(!defined(ANDROID))
+#if (!defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L) &&(!defined(__ANDROID32__))
 
 #include <limits.h>
 
diff --git a/security/tf_sdk/include/sddi.h b/security/tf_sdk/include/sddi.h
deleted file mode 100644
index 713e070..0000000
--- a/security/tf_sdk/include/sddi.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/**
- * Copyright(c) 2011 Trusted Logic.   All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *  * Neither the name Trusted Logic nor the names of its
- *    contributors may be used to endorse or promote products derived
- *    from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef __SDDI_H__
-#define __SDDI_H__
-
-#include "ssdi.h"
-
-#ifndef SDDI_EXPORT
-#if defined(WIN32) || defined(__ARMCC_VERSION)
-#ifdef SMODULE_IMPLEMENTATION
-#define SDDI_EXPORT __declspec(dllexport)
-#else
-#define SDDI_EXPORT __declspec(dllimport)
-#endif
-#elif defined(__GNUC__)
-#define SDDI_EXPORT __attribute__ ((visibility ("default")))
-#else
-#define SDDI_EXPORT
-#endif
-#endif   /* !SDDI_EXPORT */
-
-#ifndef SDRV_EXPORT
-#if defined(WIN32) || defined(_WIN32_WCE) || defined(__ARMCC_VERSION)
-#define SDRV_EXPORT __declspec(dllexport)
-#elif defined(__GNUC__)
-#define SDRV_EXPORT __attribute__ ((visibility ("default")))
-#else
-#define SDRV_EXPORT
-#endif
-#endif   /* !SDRV_EXPORT */
-
-#define S_CACHE_OPERATION_CLEAN                0x00000001
-#define S_CACHE_OPERATION_INVALIDATE           0x00000002
-#define S_CACHE_OPERATION_CLEAN_AND_INVALIDATE 0x00000003
-
-void SDDI_EXPORT *SMemGetVirtual(uint32_t nSegmentID);
-
-S_RESULT SDDI_EXPORT SMemGetPhysical(void* pVirtual, uint32_t* pnPhysical);
-
-S_RESULT SDDI_EXPORT SMemFlush(
-                   uint32_t  nSegmentID,
-                   uint32_t  nOperation);
-
-S_RESULT SDDI_EXPORT SMemFlushByAddress(
-                   void* pStartAddress,
-                   uint32_t nLength,
-                   uint32_t  nOperation);
-
-/*------------------------------------------------------------------------------
-         Driver Common Entry Points
-------------------------------------------------------------------------------*/
-
-S_RESULT SDRV_EXPORT SDrvCreate(uint32_t nParam0, uint32_t nParam1);
-
-void SDRV_EXPORT SDrvDestroy(void);
-
-#endif /* #ifndef __SDDI_H__ */
diff --git a/security/tf_sdk/include/smapi.h b/security/tf_sdk/include/smapi.h
deleted file mode 100644
index 2fc3e5e..0000000
--- a/security/tf_sdk/include/smapi.h
+++ /dev/null
@@ -1,366 +0,0 @@
-/**
- * Copyright(c) 2011 Trusted Logic.   All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *  * Neither the name Trusted Logic nor the names of its
- *    contributors may be used to endorse or promote products derived
- *    from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-/*
- * File            : smapi.h
- * Last-Author     : Trusted Logic S.A.
- * Created         : March 15, 2003
- */
-
-#ifndef __SMAPI_H__
-#define __SMAPI_H__
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-/*------------------------------------------------------------------------------
-   Includes
-------------------------------------------------------------------------------*/
-
-#include "s_type.h"
-#include "s_error.h"
-/*------------------------------------------------------------------------------
-   SMAPI Types
-------------------------------------------------------------------------------*/
-
-
-#ifdef SM_EXPORT_IMPLEMENTATION
-#define SM_EXPORT S_DLL_EXPORT
-#else
-#define SM_EXPORT S_DLL_IMPORT
-#endif
-
-typedef struct SM_PROPERTY
-{
-   wchar_t* pName;
-   wchar_t* pValue;
-} SM_PROPERTY;
-
-typedef struct SM_TIME_LIMIT
-{
-   uint32_t nHighTime;
-   uint32_t nLowTime;
-} SM_TIME_LIMIT;
-
-/*------------------------------------------------------------------------------
-   Constants
-------------------------------------------------------------------------------*/
-
-
-#define SM_API_VERSION  0x03000000
-
-#define SM_CONTROL_MODE_USER               ( (uint32_t)0x00000002 )
-#define SM_CONTROL_MODE_MANAGER            ( (uint32_t)0x00000008 )
-#define SM_CONTROL_MODE_EXCLUSIVE_MANAGER  ( (uint32_t)0x00000010 )
-
-#define SM_LOGIN_PUBLIC             ( (uint32_t)0x00000000 )
-#define SM_LOGIN_OS_IDENTIFICATION  ( (uint32_t)0x00000005 )
-#define SM_LOGIN_AUTHENTICATION                             ( (uint32_t)0x80000000 )
-#define SM_LOGIN_AUTHENTICATION_FALLBACK_OS_IDENTIFICATION  ( (uint32_t)0x80000001 )
-#define SM_LOGIN_PRIVILEGED  ( (uint32_t)0x80000002 )
-
-#define SM_MEMORY_ACCESS_CLIENT_WRITE_SERVICE_READ  ( (uint32_t)0x00000001 )
-#define SM_MEMORY_ACCESS_CLIENT_READ_SERVICE_WRITE  ( (uint32_t)0x00000002 )
-
-#define SMX_MEMORY_ACCESS_DIRECT                    ( (uint32_t)0x80000000 )
-#define SMX_MEMORY_ACCESS_DIRECT_FORCE              ( (uint32_t)0x40000000 )
-
-#define SM_INFINITE_TIMEOUT  ( (uint32_t)0xFFFFFFFF )
-
-#define SM_NULL_ELEMENT  ( (uint32_t)0xFFFFFFFF )
-
-/*------------------------------------------------------------------------------
-   Functions and Macros
-------------------------------------------------------------------------------*/
-
-SM_EXPORT SM_ERROR SMDeviceCreateContext(
-      const wchar_t* pDeviceName,
-      uint32_t       nReserved,
-      SM_HANDLE*     phDevice);
-
-SM_EXPORT SM_ERROR SMDeviceDeleteContext(
-      SM_HANDLE hDevice);
-
-SM_EXPORT void SMFree(
-      SM_HANDLE hElement,
-      void* pBuffer);
-
-SM_EXPORT SM_ERROR SMStubGetTimeLimit(
-      SM_HANDLE      hElement,
-      uint32_t       nTimeout,
-      SM_TIME_LIMIT* pTimeLimit);
-
-SM_EXPORT SM_ERROR SMStubPrepareOpenOperation(
-      SM_HANDLE            hDevice,
-      uint32_t             nLoginType,
-      const void*          pLoginInfo,
-      const SM_UUID*       pidService,
-      uint32_t             nControlMode,
-      const SM_TIME_LIMIT* pTimeLimit,
-      uint32_t             nReserved1,
-      uint32_t             nReserved2,
-      SM_HANDLE*           phClientSession,
-      SM_HANDLE*           phParameterEncoder,
-      SM_HANDLE*           phOperation);
-
-SM_EXPORT SM_ERROR SMStubPrepareInvokeOperation(
-      SM_HANDLE            hClientSession,
-      uint32_t             nCommandIdentifier,
-      const SM_TIME_LIMIT* pTimeLimit,
-      uint32_t             nReserved1,
-      uint32_t             nReserved2,
-      SM_HANDLE*           phParameterEncoder,
-      SM_HANDLE*           phOperation);
-
-SM_EXPORT SM_ERROR SMStubPrepareCloseOperation(
-      SM_HANDLE  hClientSession,
-      uint32_t   nReserved1,
-      uint32_t   nReserved2,
-      SM_HANDLE* phParameterEncoder,
-      SM_HANDLE* phOperation);
-
-SM_EXPORT SM_ERROR SMStubPerformOperation(
-      SM_HANDLE  hOperation,
-      uint32_t   nReserved,
-      SM_ERROR*  pnServiceErrorCode,
-      SM_HANDLE* phAnswerDecoder);
-
-SM_EXPORT SM_ERROR SMStubCancelOperation(
-      SM_HANDLE hOperation);
-
-SM_EXPORT SM_ERROR SMStubReleaseOperation(
-      SM_HANDLE hOperation);
-
-SM_EXPORT SM_ERROR SMStubAllocateSharedMemory(
-      SM_HANDLE  hClientSession,
-      uint32_t   nLength,
-      uint32_t   nFlags,
-      uint32_t   nReserved,
-      void**     ppBlock,
-      SM_HANDLE* phBlockHandle);
-
-SM_EXPORT SM_ERROR SMStubRegisterSharedMemory(
-      SM_HANDLE  hClientSession,
-      void*      pBuffer,
-      uint32_t   nBufferLength,
-      uint32_t   nFlags,
-      uint32_t   nReserved,
-      SM_HANDLE* phBlockHandle);
-
-SM_EXPORT SM_ERROR SMStubReleaseSharedMemory(
-      SM_HANDLE hBlockHandle);
-
-SM_EXPORT void SMStubEncoderWriteUint8(
-      SM_HANDLE hEncoder,
-      uint8_t   nValue);
-
-SM_EXPORT void SMStubEncoderWriteUint16(
-      SM_HANDLE hEncoder,
-      uint16_t  nValue);
-
-SM_EXPORT void SMStubEncoderWriteUint32(
-      SM_HANDLE hEncoder,
-      uint32_t  nValue);
-
-SM_EXPORT void SMStubEncoderWriteBoolean(
-      SM_HANDLE hEncoder,
-      bool      nValue);
-
-SM_EXPORT void SMStubEncoderWriteHandle(
-      SM_HANDLE hEncoder,
-      SM_HANDLE hValue);
-
-SM_EXPORT void SMStubEncoderWriteString(
-      SM_HANDLE      hEncoder,
-      const wchar_t* pValue);
-
-SM_EXPORT void SMStubEncoderWriteUint8Array(
-      SM_HANDLE      hEncoder,
-      uint32_t       nArrayLength,
-      const uint8_t* pnArray);
-
-SM_EXPORT void SMStubEncoderWriteUint16Array(
-      SM_HANDLE       hEncoder,
-      uint32_t        nArrayLength,
-      const uint16_t* pnArray);
-
-SM_EXPORT void SMStubEncoderWriteUint32Array(
-      SM_HANDLE       hEncoder,
-      uint32_t        nArrayLength,
-      const uint32_t* pnArray);
-
-SM_EXPORT void SMStubEncoderWriteHandleArray(
-      SM_HANDLE        hEncoder,
-      uint32_t         nArrayLength,
-      const SM_HANDLE* pnArray);
-
-SM_EXPORT void SMStubEncoderWriteMemoryReference(
-      SM_HANDLE hEncoder,
-      SM_HANDLE hBlock,
-      uint32_t  nOffset,
-      uint32_t  nLength,
-      uint32_t  nFlags);
-
-SM_EXPORT void SMStubEncoderOpenSequence(
-      SM_HANDLE hEncoder);
-
-SM_EXPORT void SMStubEncoderCloseSequence(
-      SM_HANDLE hEncoder);
-
-SM_EXPORT SM_ERROR SMStubDecoderGetError(
-      SM_HANDLE hDecoder);
-
-SM_EXPORT bool SMStubDecoderHasData(
-      SM_HANDLE hDecoder);
-
-SM_EXPORT uint8_t SMStubDecoderReadUint8(
-      SM_HANDLE hDecoder);
-
-SM_EXPORT uint16_t SMStubDecoderReadUint16(
-      SM_HANDLE hDecoder);
-
-SM_EXPORT uint32_t SMStubDecoderReadUint32(
-      SM_HANDLE hDecoder);
-
-SM_EXPORT bool SMStubDecoderReadBoolean(
-      SM_HANDLE hDecoder);
-
-SM_EXPORT SM_HANDLE SMStubDecoderReadHandle(
-      SM_HANDLE hDecoder);
-
-SM_EXPORT wchar_t* SMStubDecoderReadString(
-      SM_HANDLE hDecoder);
-
-SM_EXPORT uint8_t* SMStubDecoderReadUint8Array(
-      SM_HANDLE hDecoder,
-      uint32_t* pnArrayLength);
-
-SM_EXPORT uint16_t* SMStubDecoderReadUint16Array(
-      SM_HANDLE hDecoder,
-      uint32_t* pnArrayLength);
-
-SM_EXPORT uint32_t* SMStubDecoderReadUint32Array(
-      SM_HANDLE hDecoder,
-      uint32_t* pnArrayLength);
-
-SM_EXPORT SM_HANDLE* SMStubDecoderReadHandleArray(
-      SM_HANDLE hDecoder,
-      uint32_t* pnArrayLength);
-
-SM_EXPORT uint32_t SMStubDecoderReadArrayLength(
-      SM_HANDLE hDecoder);
-
-SM_EXPORT uint32_t SMStubDecoderCopyUint8Array(
-      SM_HANDLE hDecoder,
-      uint32_t  nIndex,
-      uint32_t  nMaxLength,
-      uint8_t*  pArray);
-
-SM_EXPORT uint32_t SMStubDecoderCopyUint16Array(
-      SM_HANDLE hDecoder,
-      uint32_t  nIndex,
-      uint32_t  nMaxLength,
-      uint16_t* pArray);
-
-SM_EXPORT uint32_t SMStubDecoderCopyUint32Array(
-      SM_HANDLE hDecoder,
-      uint32_t  nIndex,
-      uint32_t  nMaxLength,
-      uint32_t* pArray);
-
-SM_EXPORT uint32_t SMStubDecoderCopyHandleArray(
-      SM_HANDLE  hDecoder,
-      uint32_t   nIndex,
-      uint32_t   nMaxLength,
-      SM_HANDLE* pArray);
-
-SM_EXPORT void SMStubDecoderReadSequence(
-      SM_HANDLE  hDecoder,
-      SM_HANDLE* phSequenceDecoder);
-
-SM_EXPORT void SMStubDecoderSkip(
-      SM_HANDLE hDecoder);
-
-SM_EXPORT SM_ERROR SMManagerOpen(
-      SM_HANDLE   hDevice,
-      uint32_t    nLoginType,
-      const void* pLoginInfo,
-      uint32_t    nControlMode,
-      SM_HANDLE*  phServiceManager);
-
-SM_EXPORT SM_ERROR SMManagerClose(
-      SM_HANDLE hServiceManager);
-
-SM_EXPORT SM_ERROR SMManagerGetAllServices(
-      SM_HANDLE hServiceManager,
-      SM_UUID**  ppServiceIdentifierList,
-      uint32_t* pnListLength);
-
-SM_EXPORT SM_ERROR SMManagerGetServiceProperty(
-      SM_HANDLE      hServiceManager,
-      const SM_UUID* pidService,
-      wchar_t*       pPropertyName,
-      wchar_t**      ppPropertyValue);
-
-SM_EXPORT SM_ERROR SMManagerGetAllServiceProperties(
-      SM_HANDLE      hServiceManager,
-      const SM_UUID* pidService,
-      SM_PROPERTY**  ppProperties,
-      uint32_t*      pnPropertiesLength);
-
-SM_EXPORT SM_ERROR SMManagerDownloadService(
-      SM_HANDLE      hServiceManager,
-      const uint8_t* pServiceCode,
-      uint32_t       nServiceCodeSize,
-      SM_UUID*       pidService);
-
-SM_EXPORT SM_ERROR SMManagerRemoveService(
-      SM_HANDLE      hServiceManager,
-      const SM_UUID* pidService);
-
-SM_EXPORT SM_ERROR SMGetImplementationProperty(
-      SM_HANDLE       hDevice,
-      const wchar_t*  pPropertyName,
-      wchar_t**       ppPropertyValue);
-
-SM_EXPORT SM_ERROR SMGetAllImplementationProperties(
-      SM_HANDLE     hDevice,
-      SM_PROPERTY** ppProperties,
-      uint32_t*     pnPropertiesLength);
-
-#include "smapi_ex.h"
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __SMAPI_H__ */
diff --git a/security/tf_sdk/include/smapi_ex.h b/security/tf_sdk/include/smapi_ex.h
deleted file mode 100644
index 14444f7..0000000
--- a/security/tf_sdk/include/smapi_ex.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/**
- * Copyright(c) 2011 Trusted Logic.   All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *  * Neither the name Trusted Logic nor the names of its
- *    contributors may be used to endorse or promote products derived
- *    from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-/*
- * File            : smapi_ex.h
- * Last-Author     : Trusted Logic S.A.
- * Created         : April 23, 2007
- */
-
-#ifndef __SMAPI_EX_H__
-#define __SMAPI_EX_H__
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Appends the specified UUID value to the encoded data of the specified
- * encoder instance.
- *
- * Upon error, this function sets the error state of the encoder. No other state
- * is affected.
- *
- * This function does nothing if the error state of the encoder is set upon
- * entry.
- *
- * @param hEncoder The handle of the encoder instance.
- *
- * @param pUUID A pointer to the UUID value to encode.
- */
-SM_EXPORT void SMStubEncoderWriteUUID(
-      SM_HANDLE hEncoder,
-      const SM_UUID *pUUID);
-
-/**
- * Reads the UUID value at the current offset in the encoded data parsed by the
- * specified decoder instance.
- *
- * Upon return, the current offset of the decoder references the first item
- * following the decoded item.
- *
- * If the decoder error state is set upon entry, the function sets the UUID
- * placeholder to the nil UUID and does nothing more.
- *
- * @param hDecoder The handle of the decoder instance.
- *
- * @param pUUID A pointer to the placeholder to be set to the decoded UUID
- * value. This placeholder is set to the nil UUID upon failure.
- */
-SM_EXPORT void SMStubDecoderReadUUID(
-      SM_HANDLE hDecoder,
-      SM_UUID *pUUID);
-
-/**
- * Opens a sequence in the current decoder. The current decoder must point to a
- * sequence.
- *
- * After this function is called, the current decoder points to the first element
- * of the sequence.
- *
- * If the error state of the decoder is set upon entry, this function does nothing.
- *
- * Upon error, this function sets the error state of the current decoder.
- * In particular, if the decoder does not point to a sequence, the error state
- * is set to S_ERROR_BAD_FORMAT.
- *
- * @param hDecoder A handle of the decoder instance.
- *
- */
-SM_EXPORT void SMStubDecoderOpenSequence(
-      SM_HANDLE hDecoder);
-
-/**
- * Closes a sequence in the current decoder. At least one sequence must have been
- * opened using the function {SMStubDecoderOpenSequence}
- *
- * When this function returns, the current decoder points to the first element
- * following the current sequence.
- *
- * If the error state of the decoder is set upon entry, this function does nothing.
- *
- * Upon error, this function sets the error state of the current decoder.
- * In particular, if the decoder does not point within a sequence, the error state
- * is set to S_ERROR_ILLEGAL_STATE.
- *
- * @param hDecoder A handle of the decoder instance.
- *
- */
-SM_EXPORT void SMStubDecoderCloseSequence(
-      SM_HANDLE hDecoder);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __SMAPI_EX_H__ */
diff --git a/security/tf_sdk/include/ssdi.h b/security/tf_sdk/include/ssdi.h
deleted file mode 100644
index 256f62e..0000000
--- a/security/tf_sdk/include/ssdi.h
+++ /dev/null
@@ -1,529 +0,0 @@
-/**
- * Copyright(c) 2011 Trusted Logic.   All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *  * Neither the name Trusted Logic nor the names of its
- *    contributors may be used to endorse or promote products derived
- *    from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-/*
-* File            : ssdi.h
-*
-* Original-Author : Trusted Logic S.A.
-*
-* Created         : May 31, 2006
-*/
-
-/**
- * SSDI specification 3.0 header file.
- */
-
-#ifndef __SSDI_H__
-#define __SSDI_H__
-
-#include "s_type.h"
-#include "s_error.h"
-
-#ifndef SSDI_EXPORT
-#ifdef SMODULE_IMPLEMENTATION
-#define SSDI_EXPORT S_DLL_EXPORT
-#else
-#define SSDI_EXPORT S_DLL_IMPORT
-#endif
-#endif
-
-#ifndef SRVX_EXPORT
-#define SRVX_EXPORT S_DLL_EXPORT
-#endif
-
-/*------------------------------------------------------------------------------
-         SSDI Types
-------------------------------------------------------------------------------*/
-
-typedef struct S_PROPERTY
-{
-   char* pName;
-   char* pValue ;
-} S_PROPERTY;
-
-typedef struct S_TIME_LIMIT
-{
-   uint32_t nTime1;
-   uint32_t nTime2;
-} S_TIME_LIMIT;
-
-typedef struct S_CALENDAR
-{
-   int32_t nYear;
-   int32_t nMonth;
-   int32_t nDayOfWeek;
-   int32_t nDay;
-   int32_t nHour;
-   int32_t nMinute;
-   int32_t nSecond;
-} S_CALENDAR;
-
-typedef enum
-{
-   S_FILE_SEEK_SET = 0,
-   S_FILE_SEEK_CUR,
-   S_FILE_SEEK_END
-} S_WHENCE;
-
-typedef struct S_FILE_INFO
-{
-   char*    pName;
-   uint32_t nSize;
-   uint32_t nNameLength;
-}S_FILE_INFO;
-
-typedef struct
-{
-   void* pBuffer;
-   uint32_t nSize;
-}
-S_PARAM_MEMREF;
-
-typedef struct
-{
-   uint32_t a;
-   uint32_t b;
-}
-S_PARAM_VALUE;
-
-typedef union
-{
-   S_PARAM_MEMREF  memref;
-   S_PARAM_VALUE   value;
-}
-S_PARAM;
-
-
-/*------------------------------------------------------------------------------
-         Constants
-------------------------------------------------------------------------------*/
-#define S_TIMEOUT_INFINITE                         0xFFFFFFFF
-
-/* storage private to the service */
-#define S_FILE_STORAGE_PRIVATE                     0x00000001
-
-#ifdef SUPPORT_RPMB_PARTITION
-/* storage on rpmb */
-#define S_FILE_STORAGE_RPMB                        0x00000002
-#endif
-
-/* Cryptoki slotID constants */
-#define S_CRYPTOKI_KEYSTORE_PRIVATE                0x00000001
-#define S_CRYPTOKI_KEYSTORE_PRIVATE_USER           0x00004004
-
-/* SFile constants */
-#define S_FILE_FLAG_ACCESS_READ                    0x0001
-#define S_FILE_FLAG_ACCESS_WRITE                   0x0002
-#define S_FILE_FLAG_ACCESS_WRITE_META              0x0004
-
-#define S_FILE_FLAG_SHARE_READ                     0x0010
-#define S_FILE_FLAG_SHARE_WRITE                    0x0020
-
-#define S_FILE_FLAG_CREATE                         0x0200
-#define S_FILE_FLAG_EXCLUSIVE                      0x0400
-
-#define S_FILE_NAME_MAX                            0x40
-#define S_FILE_MAX_POSITION                        0xFFFFFFFF
-
-/* SDate constants */
-#define S_DATE_STATUS_NOT_SET                      0xFFFF5000
-#define S_DATE_STATUS_NEEDS_RESET                  0xFFFF5001
-#define S_DATE_STATUS_SET                          0x00000000
-
-/* Login types */
-#define S_LOGIN_PUBLIC                             0x00000000
-#define S_LOGIN_USER                               0x00000001
-#define S_LOGIN_GROUP                              0x00000002
-#define S_LOGIN_APPLICATION                        0x00000004
-#define S_LOGIN_APPLICATION_USER                   0x00000005
-#define S_LOGIN_APPLICATION_GROUP                  0x00000006
-#define S_LOGIN_AUTHENTICATION                     0x80000000
-#define S_LOGIN_PRIVILEGED                         0x80000002
-#define S_LOGIN_CLIENT_IS_SERVICE                  0xF0000000
-#define S_LOGIN_SYSTEM                             0xF0000001
-
-/* Parameter types */
-#define S_PARAM_TYPE_NONE          0x0
-#define S_PARAM_TYPE_VALUE_INPUT   0x1
-#define S_PARAM_TYPE_VALUE_OUTPUT  0x2
-#define S_PARAM_TYPE_VALUE_INOUT   0x3
-#define S_PARAM_TYPE_MEMREF_INPUT  0x5
-#define S_PARAM_TYPE_MEMREF_OUTPUT 0x6
-#define S_PARAM_TYPE_MEMREF_INOUT  0x7
-
-#define S_PARAM_TYPE_INPUT_FLAG    0x1
-#define S_PARAM_TYPE_OUTPUT_FLAG   0x2
-#define S_PARAM_TYPE_MEMREF_FLAG   0x4
-
-#define S_PARAM_TYPES(t0,t1,t2,t3)  ((t0) | ((t1) << 4) | ((t2) << 8) | ((t3) << 12))
-#define S_PARAM_TYPE_GET(t, i) (((t) >> (i*4)) & 0xF)
-
-#define S_ORIGIN_API         1
-#define S_ORIGIN_COMMS       2
-#define S_ORIGIN_TEE         3
-#define S_ORIGIN_TRUSTED_APP 4
-
-/*------------------------------------------------------------------------------
-         Implementation Functions
-------------------------------------------------------------------------------*/
-
-S_RESULT SSDI_EXPORT SImplementationGetAllProperties(
-                                 S_PROPERTY** ppProperties,
-                                 uint32_t* pnPropertiesCount);
-
-S_RESULT SSDI_EXPORT SImplementationGetProperty(const char* pName,
-                                                char** ppValue);
-
-S_RESULT SSDI_EXPORT SImplementationGetPropertyAsInt(const char* pName,
-                                                     uint32_t* pnValue);
-
-S_RESULT SSDI_EXPORT SImplementationGetPropertyAsBool(const char* pName,
-                                                      bool* pbValue);
-
-/*------------------------------------------------------------------------------
-         Service Functions
-------------------------------------------------------------------------------*/
-
-S_RESULT SSDI_EXPORT SServiceGetAllProperties(
-                                 OUT S_PROPERTY** ppProperties,
-                                 OUT uint32_t* pnPropertiesCount);
-
-S_RESULT SSDI_EXPORT SServiceGetProperty (
-                             IN const char* pName,
-                             OUT char** ppValue);
-
-S_RESULT SSDI_EXPORT SServiceGetPropertyAsInt (
-                                  IN const char* pName,
-                                  OUT uint32_t* pnValue);
-
-S_RESULT SSDI_EXPORT SServiceGetPropertyAsBool(
-                                  IN const char* pName,
-                                  OUT bool* pbValue);
-
-/*------------------------------------------------------------------------------
-         Instance Functions
-------------------------------------------------------------------------------*/
-
-void SSDI_EXPORT SInstanceSetData(
-                      void* pInstanceData);
-
-void SSDI_EXPORT *SInstanceGetData(void);
-
-/*------------------------------------------------------------------------------
-         Session Functions
-------------------------------------------------------------------------------*/
-
-void SSDI_EXPORT SSessionGetClientID(
-                         S_UUID* pClientID);
-
-S_RESULT SSDI_EXPORT SSessionGetAllClientProperties(
-                                    OUT uint32_t* pnPropertyCount,
-                                    OUT S_PROPERTY** ppPropertyArray);
-
-S_RESULT SSDI_EXPORT SSessionGetClientProperty(
-                                  IN const char* pName,
-                                  OUT char** ppValue);
-
-S_RESULT SSDI_EXPORT SSessionGetClientPropertyAsInt (
-                                        IN const char* pName,
-                                        OUT uint32_t* pnValue);
-
-S_RESULT SSDI_EXPORT SSessionGetClientPropertyAsBool (
-                                         IN const char* pName,
-                                         OUT bool* pnValue);
-
-/*------------------------------------------------------------------------------
-         Memory Management Functions
-------------------------------------------------------------------------------*/
-
-void SSDI_EXPORT *SMemAlloc(uint32_t size);
-
-void SSDI_EXPORT *SMemRealloc(void* ptr, uint32_t newSize);
-
-void SSDI_EXPORT SMemFree(void *ptr);
-
-void SSDI_EXPORT *SMemMove(void *dest, const void *src, uint32_t n);
-
-int32_t SSDI_EXPORT SMemCompare(const void *s1, const void *s2, uint32_t n);
-
-void SSDI_EXPORT *SMemFill(void *s, uint32_t c, uint32_t n);
-
-void SSDI_EXPORT *SMemAllocEx(uint32_t nPoolID, uint32_t nSize);
-
-S_RESULT SMemDup(void *src, uint32_t n, void **dest);
-
-/*------------------------------------------------------------------------------
-         Trace & Debug Functions
-------------------------------------------------------------------------------*/
-void SSDI_EXPORT _SLogTrace(
-               const char *message,
-               ... /* arguments */);
-void SSDI_EXPORT _SLogWarning(
-               const char *message,
-               ... /* arguments */);
-void SSDI_EXPORT _SLogError(
-               const char *message,
-               ... /* arguments */);
-
-#ifdef __SSDI_USE_TRACE_EX
-#include "ssdi_trace_ex.h"
-#else
-
-#ifndef SSDI_NO_TRACE
-
-#define SLogTrace _SLogTrace
-#define SLogWarning _SLogWarning
-#define SLogError _SLogError
-
-#else /* defined(SSDI_NO_TRACE) */
-
-/* Note that the following code depends on the compiler's supporting variadic macros */
-#define SLogTrace(...)   do ; while(false)
-#define SLogWarning(...) do ; while(false)
-#define SLogError(...)   do ; while(false)
-
-#endif /* !defined(SSDI_NO_TRACE) */
-
-#endif /* __SSDI_USE_TRACE_EX */
-
-void SSDI_EXPORT _SAssertionFailed(
-      const char* pFileName,
-      uint32_t nLine,
-      const char* pExpression);
-
-#ifdef SSDI_DEBUG
-#define SAssert(test)                                     \
-   do                                                       \
-   {                                                        \
-      if (!(test))                                          \
-      {                                                     \
-         _SAssertionFailed(__FILE__, __LINE__, #test);   \
-      }                                                     \
-   }                                                        \
-   while (0)
-#else /* !defined(SSDI_DEBUG) */
-#define SAssert(test)
-#endif /* defined(SSDI_DEBUG) */
-
-#define S_VAR_NOT_USED(variable) do{(void)(variable);}while(0);
-
-/*------------------------------------------------------------------------------
-         Time Utility
-------------------------------------------------------------------------------*/
-void SSDI_EXPORT STimeGetLimit(
-           uint32_t      nTimeout,
-       OUT S_TIME_LIMIT* pTimeLimit );
-
-
-/*------------------------------------------------------------------------------
-         Thread Functions
-------------------------------------------------------------------------------*/
-S_RESULT SSDI_EXPORT SThreadCreate(
-                      OUT S_HANDLE* phThread,
-                      uint32_t      stackSize,
-                      uint32_t     (*pEntryPoint)(void*),
-                      IN void*      pThreadArg);
-
-S_RESULT SSDI_EXPORT SThreadJoin(
-                    S_HANDLE        hThread,
-                    uint32_t*       pnExitCode,
-                    const S_TIME_LIMIT*   pTimeLimit);
-
-void SSDI_EXPORT SThreadYield(void);
-
-S_RESULT SSDI_EXPORT SThreadSleep(const S_TIME_LIMIT* pTimeLimit);
-
-void SSDI_EXPORT SThreadCancel(S_HANDLE hThread, uint32_t nReserved);
-
-bool SSDI_EXPORT SThreadIsCancelled (void* pReserved);
-
-void SSDI_EXPORT SThreadResetCancel(void);
-
-void SSDI_EXPORT SThreadMaskCancellation ( bool bMask );
-
-/*------------------------------------------------------------------------------
-         Semaphore Functions
-------------------------------------------------------------------------------*/
-
-S_RESULT SSDI_EXPORT SSemaphoreCreate (
-                          uint32_t  initialCount,
-                          S_HANDLE* phSemaphore);
-
-S_RESULT SSDI_EXPORT SSemaphoreAcquire(S_HANDLE hSemaphore, const S_TIME_LIMIT* pTimeLimit);
-
-void SSDI_EXPORT SSemaphoreRelease(S_HANDLE hSemaphore);
-
-/*------------------------------------------------------------------------------
-         File System Functions
-------------------------------------------------------------------------------*/
-
-S_RESULT SSDI_EXPORT SFileOpen(
-                  uint32_t  nStorageID,
-                  const char     *pFilename,
-                  uint32_t  nFlags,
-                  uint32_t  nReserved,
-                  S_HANDLE *phFile);
-
-S_RESULT SSDI_EXPORT SFileRead(S_HANDLE         hFile,
-                  uint8_t*         pBuffer,
-                  uint32_t         nSize,
-                  uint32_t*        pnCount);
-
-S_RESULT SSDI_EXPORT SFileWrite (S_HANDLE         hFile,
-                    const uint8_t*         pBuffer,
-                    uint32_t         nSize);
-
-S_RESULT SSDI_EXPORT SFileTruncate(S_HANDLE      hFile,
-                      uint32_t       nSize);
-
-S_RESULT SSDI_EXPORT SFileSeek(S_HANDLE     hFile,
-                  int32_t      nOffset,
-                  S_WHENCE     eWhence);
-
-uint32_t SSDI_EXPORT SFileTell(S_HANDLE        hFile);
-
-bool SSDI_EXPORT SFileEOF(S_HANDLE   hFile);
-
-S_RESULT SSDI_EXPORT SFileCloseAndDelete(S_HANDLE hFile);
-
-S_RESULT SSDI_EXPORT SFileRename(S_HANDLE hFile, const char* pNewFilename);
-
-S_RESULT SSDI_EXPORT SFileGetSize(uint32_t     nStorageID,
-                     const char*        pFilename,
-                     uint32_t*    pnFileSize);
-
-S_RESULT SSDI_EXPORT SFileEnumerationStart (
-                               uint32_t  nStorageID,
-                               const char*     pFilenamePattern,
-                               uint32_t  nReserved1,
-                               uint32_t  nReserved2,
-                               S_HANDLE* phFileEnumeration);
-
-S_RESULT SSDI_EXPORT SFileEnumerationGetNext (
-                                 S_HANDLE           hFileEnumeration,
-                                 OUT S_FILE_INFO**  ppFileInfo);
-
-/*------------------------------------------------------------------------------
-         Date Functions
-------------------------------------------------------------------------------*/
-
-S_RESULT SSDI_EXPORT SDateSet (
-           int32_t  nSeconds,
-           uint32_t nReserved);
-
-S_RESULT SSDI_EXPORT SDateGet(
-       OUT int32_t*  pnSeconds,
-       OUT uint32_t* pnDateStatus,
-       uint32_t      nReserved );
-
-int32_t SSDI_EXPORT SClockGet(void);
-
-S_RESULT SSDI_EXPORT SDateConvertSecondsToCalendar(
-        IN int32_t     nSeconds,
-        IN const S_CALENDAR* pOrigin,
-       OUT S_CALENDAR* pDate );
-
-S_RESULT SSDI_EXPORT SDateConvertCalendarToSeconds(
-        IN const S_CALENDAR* pOrigin,
-        IN const S_CALENDAR* pDate,
-       OUT int32_t*    pnSeconds);
-
-/*------------------------------------------------------------------------------
-         Handle Functions
-------------------------------------------------------------------------------*/
-void SSDI_EXPORT SHandleClose ( S_HANDLE hHandle);
-
-/*------------------------------------------------------------------------------
-         Crypto API
-------------------------------------------------------------------------------*/
-
-#define PKCS11_EXPORT SSDI_EXPORT
-
-#include "pkcs11.h"
-
-/*------------------------------------------------------------------------------
-         Cryptoki Update Shortcut
-------------------------------------------------------------------------------*/
-
-#define S_UPDATE_SHORTCUT_FLAG_AGGRESSIVE 0x00000001
-
-CK_RV SSDI_EXPORT CV_ActivateUpdateShortcut2(
-   CK_SESSION_HANDLE hCryptokiSession,
-   uint32_t nCommandID,
-   uint32_t nFlags,
-   uint32_t nReserved);
-
-void SSDI_EXPORT CV_DeactivateUpdateShortcut(
-  CK_SESSION_HANDLE hCryptokiSession);
-
-
-/*------------------------------------------------------------------------------
-         Panic Function
-------------------------------------------------------------------------------*/
-
-void SSDI_EXPORT SPanic(uint32_t nReserved);
-
-/*------------------------------------------------------------------------------
-         SXControl functions
-------------------------------------------------------------------------------*/
-S_RESULT SSDI_EXPORT SXControlOpenClientSession (
-           const S_UUID* pDestination,
-           S_TIME_LIMIT* pDeadline,
-           uint32_t nParamTypes,
-           S_PARAM pParams[4],
-           OUT S_HANDLE* phSessionHandle,
-           uint32_t* pnReturnOrigin);
-
-S_RESULT SSDI_EXPORT SXControlInvokeCommand (
-           S_HANDLE hSessionHandle,
-           S_TIME_LIMIT* pDeadline,
-           uint32_t nCommandID,
-           uint32_t nParamTypes,
-           S_PARAM pParams[4],
-           uint32_t* pnReturnOrigin);
-
-/*------------------------------------------------------------------------------
-         SRVX Entry Points
-------------------------------------------------------------------------------*/
-
-extern S_RESULT SRVX_EXPORT SRVXCreate(void);
-extern void     SRVX_EXPORT SRVXDestroy(void);
-extern S_RESULT SRVX_EXPORT SRVXOpenClientSession(uint32_t nParamTypes,
-                                           IN OUT S_PARAM pParams[4],
-                                           OUT void** ppSessionContext);
-extern S_RESULT SRVX_EXPORT SRVXInvokeCommand(IN OUT void* pSessionContext,
-                                       uint32_t nCommandID,
-                                       uint32_t nParamTypes,
-                                       IN OUT S_PARAM pParams[4]);
-extern void SRVX_EXPORT SRVXCloseClientSession(IN OUT void* pSessionContext);
-
-#include "ssdi_v2_compat.h"
-
-#endif /* __SSDI_H__ */
diff --git a/security/tf_sdk/include/ssdi_v2_compat.h b/security/tf_sdk/include/ssdi_v2_compat.h
deleted file mode 100644
index 06a3b0e..0000000
--- a/security/tf_sdk/include/ssdi_v2_compat.h
+++ /dev/null
@@ -1,308 +0,0 @@
-/**
- * Copyright(c) 2011 Trusted Logic.   All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *  * Neither the name Trusted Logic nor the names of its
- *    contributors may be used to endorse or promote products derived
- *    from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-/*
-* File            : ssdi_v2_compat.h
-*
-* Original-Author : Trusted Logic S.A.
-*
-* Created         : July 08, 2010
-*/
-
-/**
- * This header file contains the definitions for the legacy
- * SSDI-V2 types and functions
- */
-
-#ifndef __SSDI_V2_COMPAT_H__
-#define __SSDI_V2_COMPAT_H__
-
-#include "s_type.h"
-#include "s_error.h"
-#include "ssdi.h"
-
-/* SSPI entry points must not be exported.
-   SRVX entry points defined in the ssdi_v2_compat library are exported. */
-#define SSPI_EXPORT
-
-/*------------------------------------------------------------------------------
-         Constants
-------------------------------------------------------------------------------*/
-#define S_SHARED_MEMORY_ACCESS_READ                0x01
-#define S_SHARED_MEMORY_ACCESS_WRITE               0x02
-
-#define S_NULL_ELEMENT                             0xFFFFFFFF
-
-#define S_SHARED_MEMORY_ACCESS_READ                0x01
-#define S_SHARED_MEMORY_ACCESS_WRITE               0x02
-
-/* SControl constants */
-#define S_CONTROL_MODE_USER                        0x00000002
-#define S_CONTROL_MODE_MANAGER                     0x00000008
-#define S_CONTROL_MODE_EXCLUSIVE_MANAGER           0x00000010
-
-/* Shared memory access */
-#define S_MEMORY_ACCESS_CLIENT_WRITE_SERVICE_READ  0x00000001
-#define S_MEMORY_ACCESS_CLIENT_READ_SERVICE_WRITE  0x00000002
-
-/* Login types */
-#define S_LOGIN_OS_IDENTIFICATION                  S_LOGIN_APPLICATION_USER
-
-/*------------------------------------------------------------------------------
-         Decoder Functions
-------------------------------------------------------------------------------*/
-
-S_RESULT SDecoderGetError(S_HANDLE hDecoder);
-
-bool SDecoderHasData(S_HANDLE hDecoder);
-
-uint8_t SDecoderReadUint8(S_HANDLE hDecoder);
-
-uint16_t SDecoderReadUint16(S_HANDLE hDecoder);
-
-uint32_t SDecoderReadUint32(S_HANDLE hDecoder);
-
-char *SDecoderReadString(S_HANDLE hDecoder);
-
-bool SDecoderReadBoolean(S_HANDLE hDecoder);
-
-uint8_t *SDecoderReadUint8Array(
-                               S_HANDLE hDecoder,
-                               OUT uint32_t* pnArrayLength);
-
-uint16_t *SDecoderReadUint16Array(
-                                 S_HANDLE hDecoder,
-                                 OUT uint32_t* pnArrayLength);
-
-uint32_t *SDecoderReadUint32Array(
-                                 S_HANDLE hDecoder,
-                                 OUT uint32_t* pnArrayLength);
-
-uint32_t SDecoderReadArrayLength(S_HANDLE hDecoder);
-
-uint32_t SDecoderCopyUint8Array(
-                                IN  S_HANDLE hDecoder,
-                                IN  uint32_t nIndex,
-                                IN  uint32_t nMaxLength,
-                                OUT uint8_t* pArray);
-
-uint32_t SDecoderCopyUint16Array(
-                                 IN S_HANDLE hDecoder,
-                                 IN uint32_t nIndex,
-                                 IN uint32_t nMaxLength,
-                                 OUT uint16_t* pArray);
-
-uint32_t SDecoderCopyUint32Array(
-                                 IN S_HANDLE hDecoder,
-                                 IN uint32_t nIndex,
-                                 IN uint32_t nMaxLength,
-                                 OUT uint32_t* pArray);
-
-void SDecoderOpenSequence(S_HANDLE hDecoder);
-
-void SDecoderCloseSequence(S_HANDLE hDecoder);
-
-void SDecoderSkip(S_HANDLE hDecoder);
-
-uint8_t *SDecoderReadMemoryReference(
-                                     S_HANDLE hDecoder,
-                                     uint32_t nFlags,
-                                     OUT uint32_t* pnSize);
-void SDecoderReadUUID(
-                        IN  S_HANDLE hDecoder,
-                        OUT S_UUID*  pUUID);
-
-/*------------------------------------------------------------------------------
-         Encoder Functions
-------------------------------------------------------------------------------*/
-
-void SEncoderWriteUint8(
-                        IN S_HANDLE hEncoder,
-                        IN uint8_t value);
-
-void SEncoderWriteUint16(
-                         IN S_HANDLE hEncoder,
-                         IN   uint16_t value);
-
-void SEncoderWriteUint32(IN S_HANDLE hEncoder,
-                                     IN uint32_t value);
-
-void SEncoderWriteBoolean(IN S_HANDLE hEncoder,
-                                      IN  bool value);
-
-void SEncoderWriteString(IN S_HANDLE hEncoder,
-                                     IN const char* value);
-
-void SEncoderWriteUint8Array(IN S_HANDLE hEncoder,
-                                         IN  uint32_t nArrayLength,
-                                         IN const uint8_t* pnArray);
-
-void SEncoderWriteUint16Array(IN S_HANDLE hEncoder,
-                              IN uint32_t nArrayLength,
-                              IN const uint16_t* pnArray);
-
-void SEncoderWriteUint32Array(IN S_HANDLE hEncoder,
-                              IN uint32_t nArrayLength,
-                              IN const uint32_t* pnArray);
-
-void SEncoderWriteBooleanArray(IN S_HANDLE hEncoder,
-                               IN   uint32_t nArrayLength,
-                               IN const bool*    pnArray);
-
-void SEncoderWriteStringArray(IN S_HANDLE hEncoder,
-                             IN uint32_t nArrayLength,
-                             IN const char** pnArray);
-
-void SEncoderWriteMemoryReference(
-                              S_HANDLE hEncoder,
-                              S_HANDLE hBlock,
-                              uint32_t nOffset,
-                              uint32_t nLength,
-                              uint32_t nFlags);
-
-void SEncoderOpenSequence( S_HANDLE hEncoder );
-
-void SEncoderCloseSequence( S_HANDLE hEncoder );
-
-S_RESULT SEncoderGetError(S_HANDLE hEncoder);
-
-void SEncoderReset( S_HANDLE hEncoder );
-
-void SEncoderWriteUUID(
-                  IN S_HANDLE hEncoder,
-                  IN const S_UUID*  pUUID);
-
-/*------------------------------------------------------------------------------
-         Service Control Functions
-------------------------------------------------------------------------------*/
-
-S_RESULT SControlPrepareOpenOperation(
-        IN const S_UUID*       pIdService,
-           uint32_t      nControlMode,
-        IN const S_TIME_LIMIT* pTimeLimit,
-           uint32_t      nEncoderBufferSize,
-           uint32_t      nDecoderBufferSize,
-       OUT S_HANDLE*     phClientSession,
-       OUT S_HANDLE*     phParameterEncoder,
-       OUT S_HANDLE*     phOperation );
-
-S_RESULT SControlPrepareInvokeOperation(
-           S_HANDLE      hClientSession,
-           uint32_t      nCommandIdentifier,
-        IN const S_TIME_LIMIT* pTimeLimit,
-           uint32_t      nEncoderBufferSize,
-           uint32_t      nDecoderBufferSize,
-       OUT S_HANDLE*     phParameterEncoder,
-       OUT S_HANDLE*     phOperation );
-
-S_RESULT SControlPrepareCloseOperation(
-           S_HANDLE  hClientSession,
-           uint32_t  nEncoderBufferSize,
-           uint32_t  nDecoderBufferSize,
-       OUT S_HANDLE* phParameterEncoder,
-       OUT S_HANDLE* phOperation );
-
-S_RESULT SControlPerformOperation(
-           S_HANDLE  hOperation,
-           uint32_t  nReserved,
-       OUT S_RESULT* pnServiceErrorCode,
-       OUT S_HANDLE* phAnswerDecoder );
-
-S_RESULT SControlCancelOperation( S_HANDLE hOperation );
-
-S_RESULT SControlAllocateSharedMemory(
-           S_HANDLE  hClientSession,
-           uint32_t  nLength,
-           uint32_t  nFlags,
-           uint32_t  nReserved,
-       OUT void**    ppBlock,
-       OUT S_HANDLE* phBlockHandle);
-
-S_RESULT SControlRegisterSharedMemory(
-           S_HANDLE  hClientSession,
-        IN const void*     pBuffer,
-           uint32_t  nBufferLength,
-           uint32_t  nFlags,
-           uint32_t  nReserved,
-       OUT S_HANDLE* phBlockHandle );
-
-/*------------------------------------------------------------------------------
-         Service Manager Functions
-------------------------------------------------------------------------------*/
-
-S_RESULT SManagerOpen(
-                           uint32_t nControlMode,
-                           S_HANDLE* phServiceManager);
-
-S_RESULT SManagerGetAllServices(
-                           S_HANDLE hServiceManager,
-                           S_UUID** ppServiceIdentifierList,
-                           uint32_t* pnListLength);
-
-S_RESULT SManagerGetServiceProperty(
-                           S_HANDLE hServiceManager,
-                           const S_UUID* pidService,
-                           const char* pPropertyName,
-                           char** ppPropertyValue);
-
-S_RESULT SManagerGetAllServiceProperties(
-                           S_HANDLE hServiceManager,
-                           const S_UUID* pidService,
-                           S_PROPERTY** ppProperties,
-                           uint32_t* pnPropertiesLength);
-
-S_RESULT SManagerDownloadService(
-                           S_HANDLE hServiceManager,
-                           const uint8_t* pServiceCode,
-                           uint32_t nServiceCodeSize,
-                           S_UUID* pidService);
-
-S_RESULT SManagerRemoveService(
-                           S_HANDLE hServiceManager,
-                           const S_UUID* pidService);
-
-/*------------------------------------------------------------------------------
-         SSPI Entry Points
-------------------------------------------------------------------------------*/
-
-S_RESULT SSPICreate(void);
-void     SSPIDestroy(void);
-S_RESULT SSPIOpenClientSession(S_HANDLE hDecoder,
-                                           S_HANDLE hEncoder,
-                                           OUT void** ppSessionContext);
-S_RESULT SSPIInvokeCommand(IN OUT void* pSessionContext,
-                                       uint32_t nCommandID,
-                                       S_HANDLE hDecoder,
-                                       S_HANDLE hEncoder);
-S_RESULT SSPICloseClientSession(IN OUT void* pSessionContext,
-                                            uint32_t nCause,
-                                            S_HANDLE hDecoder,
-                                            S_HANDLE hEncoder);
-#endif /* __SSDI_V2_COMPAT_H__ */
diff --git a/test/CameraHal/Android.mk b/test/CameraHal/Android.mk
index c7da48a..9a31d85 100644
--- a/test/CameraHal/Android.mk
+++ b/test/CameraHal/Android.mk
@@ -13,6 +13,7 @@
 	libcutils \
 	libbinder \
 	libmedia \
+	libmedia_native \
 	libui \
 	libgui \
 	libcamera_client
diff --git a/test/CameraHal/camera_test.h b/test/CameraHal/camera_test.h
index ad750ff..df44833 100644
--- a/test/CameraHal/camera_test.h
+++ b/test/CameraHal/camera_test.h
@@ -1,9 +1,9 @@
 #ifndef CAMERA_TEST_H
 #define CAMERA_TEST_H
 
-#define PRINTOVER(arg...)     LOGD(#arg)
-#define LOG_FUNCTION_NAME         LOGD("%d: %s() ENTER", __LINE__, __FUNCTION__);
-#define LOG_FUNCTION_NAME_EXIT    LOGD("%d: %s() EXIT", __LINE__, __FUNCTION__);
+#define PRINTOVER(arg...)     ALOGD(#arg)
+#define LOG_FUNCTION_NAME         ALOGD("%d: %s() ENTER", __LINE__, __FUNCTION__);
+#define LOG_FUNCTION_NAME_EXIT    ALOGD("%d: %s() EXIT", __LINE__, __FUNCTION__);
 #define KEY_GBCE            "gbce"
 #define KEY_GLBCE           "glbce"
 #define KEY_CAMERA          "camera-index"
diff --git a/test/CameraHal/camera_test_menu.cpp b/test/CameraHal/camera_test_menu.cpp
index f8ef2b1..1430ea4 100644
--- a/test/CameraHal/camera_test_menu.cpp
+++ b/test/CameraHal/camera_test_menu.cpp
@@ -7,11 +7,8 @@
 #include <semaphore.h>
 #include <pthread.h>
 
-#include <surfaceflinger/Surface.h>
-#include <surfaceflinger/ISurface.h>
-#include <surfaceflinger/ISurfaceComposer.h>
-#include <surfaceflinger/ISurfaceComposerClient.h>
-#include <surfaceflinger/SurfaceComposerClient.h>
+#include <gui/Surface.h>
+#include <gui/SurfaceComposerClient.h>
 
 #include <camera/Camera.h>
 #include <camera/ICamera.h>
@@ -513,19 +510,19 @@
     sprintf(fn, "/sdcard/preview%03d.yuv", counter);
     fd = open(fn, O_CREAT | O_WRONLY | O_TRUNC, 0777);
     if(fd < 0) {
-        LOGE("Unable to open file %s: %s", fn, strerror(fd));
+        ALOGE("Unable to open file %s: %s", fn, strerror(fd));
         goto out;
     }
 
     size = mem->size();
     if (size <= 0) {
-        LOGE("IMemory object is of zero size");
+        ALOGE("IMemory object is of zero size");
         goto out;
     }
 
     buff = (unsigned char *)mem->pointer();
     if (!buff) {
-        LOGE("Buffer pointer is invalid");
+        ALOGE("Buffer pointer is invalid");
         goto out;
     }
 
@@ -603,19 +600,19 @@
     fd = open(fn, O_CREAT | O_WRONLY | O_TRUNC, 0777);
 
     if(fd < 0) {
-        LOGE("Unable to open file %s: %s", fn, strerror(fd));
+        ALOGE("Unable to open file %s: %s", fn, strerror(fd));
         goto out;
     }
 
     size = mem->size();
     if (size <= 0) {
-        LOGE("IMemory object is of zero size");
+        ALOGE("IMemory object is of zero size");
         goto out;
     }
 
     buff = (unsigned char *)mem->pointer();
     if (!buff) {
-        LOGE("Buffer pointer is invalid");
+        ALOGE("Buffer pointer is invalid");
         goto out;
     }
 
diff --git a/test/CameraHal/camera_test_script.cpp b/test/CameraHal/camera_test_script.cpp
index a0b8ade..afd88be 100644
--- a/test/CameraHal/camera_test_script.cpp
+++ b/test/CameraHal/camera_test_script.cpp
@@ -7,12 +7,6 @@
 #include <semaphore.h>
 #include <pthread.h>
 
-#include <surfaceflinger/Surface.h>
-#include <surfaceflinger/ISurface.h>
-#include <surfaceflinger/ISurfaceComposer.h>
-#include <surfaceflinger/ISurfaceComposerClient.h>
-#include <surfaceflinger/SurfaceComposerClient.h>
-
 #include <camera/Camera.h>
 #include <camera/ICamera.h>
 #include <media/mediarecorder.h>