QCamera2: Release SM thread before closing all locks

 The state machine thread will begin to terminate
 after the QCamera2HardwareInterface mutexes are
 released. It is still possible for the state
 machine thread to try and acquire one of the locks
 before it is terminated, which can lead to a deadlock.
 To avoid this, the destructor of
 QCamera2HardwareInterface will first wait for the
 state machine thread to terminate and then release
 the locks.

Change-Id: Ie141c608ed49eda3bbbf1df39f29e5b280bff336
diff --git a/QCamera2/HAL/QCamera2HWI.cpp b/QCamera2/HAL/QCamera2HWI.cpp
index 97a4f40..eb8f6ab 100644
--- a/QCamera2/HAL/QCamera2HWI.cpp
+++ b/QCamera2/HAL/QCamera2HWI.cpp
@@ -1090,6 +1090,7 @@
     mDefferedWorkThread.exit();
 
     closeCamera();
+    m_stateMachine.releaseThread();
     pthread_mutex_destroy(&m_lock);
     pthread_cond_destroy(&m_cond);
     pthread_mutex_destroy(&m_evtLock);
diff --git a/QCamera2/HAL/QCameraStateMachine.cpp b/QCamera2/HAL/QCameraStateMachine.cpp
index 1936527..f803524 100644
--- a/QCamera2/HAL/QCameraStateMachine.cpp
+++ b/QCamera2/HAL/QCameraStateMachine.cpp
@@ -133,6 +133,20 @@
  *==========================================================================*/
 QCameraStateMachine::~QCameraStateMachine()
 {
+    cam_sem_destroy(&cmd_sem);
+}
+
+/*===========================================================================
+ * FUNCTION   : releaseThread
+ *
+ * DESCRIPTION: Sends an exit command and terminates the state machine thread
+ *
+ * PARAMETERS : none
+ *
+ * RETURN     : none
+ *==========================================================================*/
+void QCameraStateMachine::releaseThread()
+{
     if (cmd_pid != 0) {
         qcamera_sm_cmd_t *node =
             (qcamera_sm_cmd_t *)malloc(sizeof(qcamera_sm_cmd_t));
@@ -150,7 +164,6 @@
         }
         cmd_pid = 0;
     }
-    cam_sem_destroy(&cmd_sem);
 }
 
 /*===========================================================================
diff --git a/QCamera2/HAL/QCameraStateMachine.h b/QCamera2/HAL/QCameraStateMachine.h
index da21433..bc31be4 100644
--- a/QCamera2/HAL/QCameraStateMachine.h
+++ b/QCamera2/HAL/QCameraStateMachine.h
@@ -172,6 +172,7 @@
     bool isPreviewReady(); // check if preview is ready
     bool isCaptureRunning(); // check if image capture is running
     bool isNonZSLCaptureRunning(); // check if image capture is running in non ZSL mode
+    void releaseThread();
 
 private:
     typedef enum {