qseecom:  Load and unload app on open/close

This fix is intended when using QSEOS_VERSION_13.
Targets that have not moved to latest QSEE, will run into
a failure when the qseecom daemon is run.   qseecom daemon
opens the qseecom device and registers the listeners.

In the old QSEE version 13, the app itself responds to these
request for registering the listeners.  So the app needs to have
loaded prior to issuing the register listeners request.

Change-Id: Ic1756aac2b8d8cc22b9b630053e77ba7f7a49c91
Signed-off-by: Mona Hossain <mhossain@codeaurora.org>
diff --git a/drivers/misc/qseecom.c b/drivers/misc/qseecom.c
index 495a986..ba00d5e 100644
--- a/drivers/misc/qseecom.c
+++ b/drivers/misc/qseecom.c
@@ -486,23 +486,6 @@
 	if (__copy_from_user(&req, (void __user *)argp, sizeof(req)))
 		return -EFAULT;
 
-	if (qseecom.qseos_version == QSEOS_VERSION_13) {
-		long pil_error;
-		mutex_lock(&pil_access_lock);
-		if (pil_ref_cnt == 0) {
-			pil = pil_get("tzapps");
-			if (IS_ERR(pil)) {
-				pr_err("Playready PIL image load failed\n");
-				pil_error = PTR_ERR(pil);
-				pil = NULL;
-				pr_debug("tzapps image load FAILED\n");
-				mutex_unlock(&pil_access_lock);
-				return pil_error;
-			}
-		}
-		pil_ref_cnt++;
-		mutex_unlock(&pil_access_lock);
-	}
 	/* Get the handle of the shared fd */
 	data->client.ihandle = ion_import_fd(qseecom.ion_clnt, req.ifd_data_fd);
 	if (IS_ERR_OR_NULL(data->client.ihandle)) {
@@ -789,11 +772,6 @@
 				break;
 			}
 		}
-		mutex_lock(&pil_access_lock);
-		if (pil_ref_cnt == 1)
-			pil_put(pil);
-		pil_ref_cnt--;
-		mutex_unlock(&pil_access_lock);
 	}
 	data->released = true;
 	return ret;
@@ -1330,6 +1308,23 @@
 	data->released = false;
 	init_waitqueue_head(&data->abort_wq);
 	atomic_set(&data->ioctl_count, 0);
+	if (qseecom.qseos_version == QSEOS_VERSION_13) {
+		int pil_error;
+		mutex_lock(&pil_access_lock);
+		if (pil_ref_cnt == 0) {
+			pil = pil_get("tzapps");
+			if (IS_ERR(pil)) {
+				pr_err("Playready PIL image load failed\n");
+				pil_error = PTR_ERR(pil);
+				pil = NULL;
+				pr_debug("tzapps image load FAILED\n");
+				mutex_unlock(&pil_access_lock);
+				return pil_error;
+			}
+		}
+		pil_ref_cnt++;
+		mutex_unlock(&pil_access_lock);
+	}
 	return ret;
 }
 
@@ -1349,6 +1344,13 @@
 			return ret;
 		}
 	}
+	if (qseecom.qseos_version == QSEOS_VERSION_13) {
+		mutex_lock(&pil_access_lock);
+		if (pil_ref_cnt == 1)
+			pil_put(pil);
+		pil_ref_cnt--;
+		mutex_unlock(&pil_access_lock);
+	}
 	kfree(data);
 	qsee_disable_clock_vote();