resolve merge conflicts of 3ceaacc to stage-aosp-master

Test: I solemnly swear I tested this conflict resolution.
Change-Id: Ic688982b8d16a7d42cafdf0d76eb6ec931322b1e
diff --git a/include/telephony/ril.h b/include/telephony/ril.h
index 9dfaaeb..bc21790 100644
--- a/include/telephony/ril.h
+++ b/include/telephony/ril.h
@@ -31,7 +31,7 @@
 extern "C" {
 #endif
 
-
+#ifndef SIM_COUNT
 #if defined(ANDROID_SIM_COUNT_2)
 #define SIM_COUNT 2
 #elif defined(ANDROID_SIM_COUNT_3)
@@ -45,6 +45,7 @@
 #ifndef ANDROID_MULTI_SIM
 #define SIM_COUNT 1
 #endif
+#endif
 
 /*
  * RIL version.
@@ -357,7 +358,17 @@
     PREF_NET_TYPE_LTE_GSM_WCDMA            = 9, /* LTE, GSM/WCDMA */
     PREF_NET_TYPE_LTE_CMDA_EVDO_GSM_WCDMA  = 10, /* LTE, CDMA, EvDo, GSM/WCDMA */
     PREF_NET_TYPE_LTE_ONLY                 = 11, /* LTE only */
-    PREF_NET_TYPE_LTE_WCDMA                = 12  /* LTE/WCDMA */
+    PREF_NET_TYPE_LTE_WCDMA                = 12,  /* LTE/WCDMA */
+    PREF_NET_TYPE_TD_SCDMA_ONLY            = 13, /* TD-SCDMA only */
+    PREF_NET_TYPE_TD_SCDMA_WCDMA           = 14, /* TD-SCDMA and WCDMA */
+    PREF_NET_TYPE_TD_SCDMA_LTE             = 15, /* TD-SCDMA and LTE */
+    PREF_NET_TYPE_TD_SCDMA_GSM             = 16, /* TD-SCDMA and GSM */
+    PREF_NET_TYPE_TD_SCDMA_GSM_LTE         = 17, /* TD-SCDMA,GSM and LTE */
+    PREF_NET_TYPE_TD_SCDMA_GSM_WCDMA       = 18, /* TD-SCDMA, GSM/WCDMA */
+    PREF_NET_TYPE_TD_SCDMA_WCDMA_LTE       = 19, /* TD-SCDMA, WCDMA and LTE */
+    PREF_NET_TYPE_TD_SCDMA_GSM_WCDMA_LTE   = 20, /* TD-SCDMA, GSM/WCDMA and LTE */
+    PREF_NET_TYPE_TD_SCDMA_GSM_WCDMA_CDMA_EVDO_AUTO  = 21, /* TD-SCDMA, GSM/WCDMA, CDMA and EvDo */
+    PREF_NET_TYPE_TD_SCDMA_LTE_CDMA_EVDO_GSM_WCDMA   = 22  /* TD-SCDMA, LTE, CDMA, EvDo GSM/WCDMA */
 } RIL_PreferredNetworkType;
 
 /* Source for cdma subscription */
@@ -1992,11 +2003,11 @@
 
 typedef enum {
     RIL_DST_POWER_SAVE_MODE,        // Device power save mode (provided by PowerManager)
-                                    // Non-zero value indicates the device is in power save mode.
+                                    // True indicates the device is in power save mode.
     RIL_DST_CHARGING_STATE,         // Device charging state (provided by BatteryManager)
-                                    // Non-zero value indicates the device is charging.
-    RIL_DST_LOW_DATA_EXPECTED       // Low data expected mode. Non-zero value indicates low data
-                                    // traffic is expected, for example, when the device is idle
+                                    // True indicates the device is charging.
+    RIL_DST_LOW_DATA_EXPECTED       // Low data expected mode. True indicates low data traffic
+                                    // is expected, for example, when the device is idle
                                     // (e.g. not doing tethering in the background). Note
                                     // this doesn't mean no data is expected.
 } RIL_DeviceStateType;
@@ -5381,7 +5392,7 @@
  * RIL_REQUEST_VOICE_RADIO_TECH
  *
  * Query the radio technology type (3GPP/3GPP2) used for voice. Query is valid only
- * when radio state is RADIO_STATE_ON
+ * when radio state is not RADIO_STATE_UNAVAILABLE
  *
  * "data" is NULL
  * "response" is int *
@@ -6928,40 +6939,40 @@
  */
 #define RIL_UNSOL_LCEDATA_RECV 1045
 
-/**
- * RIL_UNSOL_PCO_DATA
- *
- * Called when there is new Carrier PCO data received for a data call.  Ideally
- * only new data will be forwarded, though this is not required.  Multiple
- * boxes of carrier PCO data for a given call should result in a series of
- * RIL_UNSOL_PCO_DATA calls.
- *
- * "data" is the RIL_PCO_Data structure.
- *
- */
+ /**
+  * RIL_UNSOL_PCO_DATA
+  *
+  * Called when there is new Carrier PCO data received for a data call.  Ideally
+  * only new data will be forwarded, though this is not required.  Multiple
+  * boxes of carrier PCO data for a given call should result in a series of
+  * RIL_UNSOL_PCO_DATA calls.
+  *
+  * "data" is the RIL_PCO_Data structure.
+  *
+  */
 #define RIL_UNSOL_PCO_DATA 1046
 
-/**
- * RIL_UNSOL_MODEM_RESTART
- *
- * Called when there is a modem reset.
- *
- * "reason" is "const char *" containing the reason for the reset. It
- * could be a crash signature if the restart was due to a crash or some
- * string such as "user-initiated restart" or "AT command initiated
- * restart" that explains the cause of the modem restart.
- *
- * When modem restarts, one of the following radio state transitions will happen
- * 1) RADIO_STATE_ON->RADIO_STATE_UNAVAILABLE->RADIO_STATE_ON or
- * 2) RADIO_STATE_OFF->RADIO_STATE_UNAVAILABLE->RADIO_STATE_OFF
- * This message can be sent either just before the RADIO_STATE changes to RADIO_STATE_UNAVAILABLE
- * or just after but should never be sent after the RADIO_STATE changes from UNAVAILABLE to
- * AVAILABLE(RADIO_STATE_ON/RADIO_STATE_OFF) again.
- *
- * It should NOT be sent after the RADIO_STATE changes to AVAILABLE after the
- * modem restart as that could be interpreted as a second modem reset by the
- * framework.
- */
+ /**
+  * RIL_UNSOL_MODEM_RESTART
+  *
+  * Called when there is a modem reset.
+  *
+  * "reason" is "const char *" containing the reason for the reset. It
+  * could be a crash signature if the restart was due to a crash or some
+  * string such as "user-initiated restart" or "AT command initiated
+  * restart" that explains the cause of the modem restart.
+  *
+  * When modem restarts, one of the following radio state transitions will happen
+  * 1) RADIO_STATE_ON->RADIO_STATE_UNAVAILABLE->RADIO_STATE_ON or
+  * 2) RADIO_STATE_OFF->RADIO_STATE_UNAVAILABLE->RADIO_STATE_OFF
+  * This message can be sent either just before the RADIO_STATE changes to RADIO_STATE_UNAVAILABLE
+  * or just after but should never be sent after the RADIO_STATE changes from UNAVAILABLE to
+  * AVAILABLE(RADIO_STATE_ON/RADIO_STATE_OFF) again.
+  *
+  * It should NOT be sent after the RADIO_STATE changes to AVAILABLE after the
+  * modem restart as that could be interpreted as a second modem reset by the
+  * framework.
+  */
 #define RIL_UNSOL_MODEM_RESTART 1047
 
 /**
diff --git a/libril/Android.mk b/libril/Android.mk
index 06643d9..d4ed8f4 100644
--- a/libril/Android.mk
+++ b/libril/Android.mk
@@ -28,10 +28,10 @@
 LOCAL_STATIC_LIBRARIES := \
     libprotobuf-c-nano-enable_malloc \
 
-#LOCAL_CFLAGS := -DANDROID_MULTI_SIM -DDSDA_RILD1
 LOCAL_CFLAGS += -Wno-unused-parameter
 
 ifeq ($(SIM_COUNT), 2)
+    LOCAL_CFLAGS += -DANDROID_MULTI_SIM -DDSDA_RILD1
     LOCAL_CFLAGS += -DANDROID_SIM_COUNT_2
 endif
 
@@ -44,24 +44,3 @@
 
 include $(BUILD_SHARED_LIBRARY)
 
-
-# For RdoServD which needs a static library
-# =========================================
-ifneq ($(ANDROID_BIONIC_TRANSITION),)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES:= \
-    ril.cpp
-
-LOCAL_STATIC_LIBRARIES := \
-    libutils_static \
-    libcutils \
-    librilutils_static \
-    libprotobuf-c-nano-enable_malloc
-
-LOCAL_CFLAGS += -Wno-unused-parameter
-
-LOCAL_MODULE:= libril_static
-
-include $(BUILD_STATIC_LIBRARY)
-endif # ANDROID_BIONIC_TRANSITION
diff --git a/libril/RilSapSocket.cpp b/libril/RilSapSocket.cpp
index 92b7a7b..664e6a9 100644
--- a/libril/RilSapSocket.cpp
+++ b/libril/RilSapSocket.cpp
@@ -78,7 +78,9 @@
        const void *data,
        size_t datalen) {
     RilSapSocket *sap_socket = getSocketById(RIL_SOCKET_1);
-    sap_socket->onUnsolicitedResponse(unsolResponse, (void *)data, datalen);
+    if(sap_socket){
+        sap_socket->onUnsolicitedResponse(unsolResponse, (void *)data, datalen);
+    }
 }
 #endif
 
diff --git a/libril/ril.cpp b/libril/ril.cpp
index 1451a56..fa9d630 100644
--- a/libril/ril.cpp
+++ b/libril/ril.cpp
@@ -192,12 +192,8 @@
 
 #if defined(ANDROID_MULTI_SIM)
 #define RIL_UNSOL_RESPONSE(a, b, c, d) RIL_onUnsolicitedResponse((a), (b), (c), (d))
-#define CALL_ONREQUEST(a, b, c, d, e) s_callbacks.onRequest((a), (b), (c), (d), (e))
-#define CALL_ONSTATEREQUEST(a) s_callbacks.onStateRequest(a)
 #else
 #define RIL_UNSOL_RESPONSE(a, b, c, d) RIL_onUnsolicitedResponse((a), (b), (c))
-#define CALL_ONREQUEST(a, b, c, d, e) s_callbacks.onRequest((a), (b), (c), (d))
-#define CALL_ONSTATEREQUEST(a) s_callbacks.onStateRequest()
 #endif
 
 static UserCallbackInfo * internalRequestTimedCallback
@@ -959,7 +955,7 @@
         case RIL_E_SIM_FULL: return "E_SIM_FULL";
         case RIL_E_NETWORK_REJECT: return "E_NETWORK_REJECT";
         case RIL_E_OPERATION_NOT_ALLOWED: return "E_OPERATION_NOT_ALLOWED";
-        case RIL_E_EMPTY_RECORD: return "E_EMPTY_RECORD";
+        case RIL_E_EMPTY_RECORD: "E_EMPTY_RECORD";
         case RIL_E_INVALID_SMS_FORMAT: return "E_INVALID_SMS_FORMAT";
         case RIL_E_ENCODING_ERR: return "E_ENCODING_ERR";
         case RIL_E_INVALID_SMSC_ADDRESS: return "E_INVALID_SMSC_ADDRESS";
@@ -1219,13 +1215,13 @@
         case RIL_UNSOL_HARDWARE_CONFIG_CHANGED: return "UNSOL_HARDWARE_CONFIG_CHANGED";
         case RIL_UNSOL_DC_RT_INFO_CHANGED: return "UNSOL_DC_RT_INFO_CHANGED";
         case RIL_UNSOL_RADIO_CAPABILITY: return "UNSOL_RADIO_CAPABILITY";
+        case RIL_UNSOL_MODEM_RESTART: return "UNSOL_MODEM_RESTART";
+        case RIL_UNSOL_CARRIER_INFO_IMSI_ENCRYPTION: return "UNSOL_CARRIER_INFO_IMSI_ENCRYPTION";
         case RIL_UNSOL_ON_SS: return "UNSOL_ON_SS";
         case RIL_UNSOL_STK_CC_ALPHA_NOTIFY: return "UNSOL_STK_CC_ALPHA_NOTIFY";
         case RIL_UNSOL_LCEDATA_RECV: return "UNSOL_LCEDATA_RECV";
         case RIL_UNSOL_PCO_DATA: return "UNSOL_PCO_DATA";
-        case RIL_UNSOL_MODEM_RESTART: return "UNSOL_MODEM_RESTART";
-        case RIL_UNSOL_CARRIER_INFO_IMSI_ENCRYPTION: return "UNSOL_CARRIER_INFO_IMSI_ENCRYPTION";
-    default: return "<unknown request>";
+        default: return "<unknown request>";
     }
 }
 
@@ -1252,4 +1248,4 @@
     }
 }
 
-} /* namespace android */
\ No newline at end of file
+} /* namespace android */
diff --git a/libril/ril_service.cpp b/libril/ril_service.cpp
index 443225a..10ef3cb 100644
--- a/libril/ril_service.cpp
+++ b/libril/ril_service.cpp
@@ -52,6 +52,15 @@
 #define ATOI_NULL_HANDLED(x) (x ? atoi(x) : -1)
 #define ATOI_NULL_HANDLED_DEF(x, defaultVal) (x ? atoi(x) : defaultVal)
 
+#if defined(ANDROID_MULTI_SIM)
+#define CALL_ONREQUEST(a, b, c, d, e) \
+        s_vendorFunctions->onRequest((a), (b), (c), (d), ((RIL_SOCKET_ID)(e)))
+#define CALL_ONSTATEREQUEST(a) s_vendorFunctions->onStateRequest((RIL_SOCKET_ID)(a))
+#else
+#define CALL_ONREQUEST(a, b, c, d, e) s_vendorFunctions->onRequest((a), (b), (c), (d))
+#define CALL_ONSTATEREQUEST(a) s_vendorFunctions->onStateRequest()
+#endif
+
 RIL_RadioFunctions *s_vendorFunctions = NULL;
 static CommandInfo *s_commands;
 
@@ -516,7 +525,7 @@
     if (pRI == NULL) {
         return false;
     }
-    s_vendorFunctions->onRequest(request, NULL, 0, pRI);
+    CALL_ONREQUEST(request, NULL, 0, pRI, slotId);
     return true;
 }
 
@@ -531,7 +540,7 @@
         return false;
     }
 
-    s_vendorFunctions->onRequest(request, pString, sizeof(char *), pRI);
+    CALL_ONREQUEST(request, pString, sizeof(char *), pRI, slotId);
 
     memsetAndFreeStrings(1, pString);
     return true;
@@ -565,7 +574,7 @@
     }
     va_end(ap);
 
-    s_vendorFunctions->onRequest(request, pStrings, countStrings * sizeof(char *), pRI);
+    CALL_ONREQUEST(request, pStrings, countStrings * sizeof(char *), pRI, slotId);
 
     if (pStrings != NULL) {
         for (int i = 0 ; i < countStrings ; i++) {
@@ -605,7 +614,7 @@
         }
     }
 
-    s_vendorFunctions->onRequest(request, pStrings, countStrings * sizeof(char *), pRI);
+    CALL_ONREQUEST(request, pStrings, countStrings * sizeof(char *), pRI, slotId);
 
     if (pStrings != NULL) {
         for (int i = 0 ; i < countStrings ; i++) {
@@ -640,7 +649,7 @@
     }
     va_end(ap);
 
-    s_vendorFunctions->onRequest(request, pInts, countInts * sizeof(int), pRI);
+    CALL_ONREQUEST(request, pInts, countInts * sizeof(int), pRI, slotId);
 
     if (pInts != NULL) {
 #ifdef MEMSET_FREED
@@ -669,7 +678,7 @@
         return false;
     }
 
-    s_vendorFunctions->onRequest(request, &cf, sizeof(cf), pRI);
+    CALL_ONREQUEST(request, &cf, sizeof(cf), pRI, slotId);
 
     memsetAndFreeStrings(1, cf.number);
 
@@ -684,7 +693,7 @@
 
     const uint8_t *uData = rawBytes.data();
 
-    s_vendorFunctions->onRequest(request, (void *) uData, rawBytes.size(), pRI);
+    CALL_ONREQUEST(request, (void *) uData, rawBytes.size(), pRI, slotId);
 
     return true;
 }
@@ -708,7 +717,7 @@
         return false;
     }
 
-    s_vendorFunctions->onRequest(request, &apdu, sizeof(apdu), pRI);
+    CALL_ONREQUEST(request, &apdu, sizeof(apdu), pRI, slotId);
 
     memsetAndFreeStrings(1, apdu.data);
 
@@ -906,7 +915,7 @@
         dial.uusInfo = &uusInfo;
     }
 
-    s_vendorFunctions->onRequest(RIL_REQUEST_DIAL, &dial, sizeOfDial, pRI);
+    CALL_ONREQUEST(RIL_REQUEST_DIAL, &dial, sizeOfDial, pRI, mSlotId);
 
     memsetAndFreeStrings(2, dial.address, uusInfo.uusData);
 
@@ -1151,7 +1160,7 @@
         return Void();
     }
 
-    s_vendorFunctions->onRequest(RIL_REQUEST_SIM_IO, &rilIccIo, sizeof(rilIccIo), pRI);
+    CALL_ONREQUEST(RIL_REQUEST_SIM_IO, &rilIccIo, sizeof(rilIccIo), pRI, mSlotId);
 
     memsetAndFreeStrings(4, rilIccIo.path, rilIccIo.data, rilIccIo.pin2, rilIccIo.aidPtr);
 
@@ -1284,7 +1293,7 @@
     RLOGD("setBarringPassword: serial %d", serial);
 #endif
     dispatchStrings(serial, mSlotId, RIL_REQUEST_CHANGE_BARRING_PASSWORD,
-            2, oldPassword.c_str(), newPassword.c_str());
+            3, facility.c_str(), oldPassword.c_str(), newPassword.c_str());
     return Void();
 }
 
@@ -1492,7 +1501,7 @@
         return Void();
     }
 
-    s_vendorFunctions->onRequest(RIL_REQUEST_WRITE_SMS_TO_SIM, &args, sizeof(args), pRI);
+    CALL_ONREQUEST(RIL_REQUEST_WRITE_SMS_TO_SIM, &args, sizeof(args), pRI, mSlotId);
 
     memsetAndFreeStrings(2, args.smsc, args.pdu);
 
@@ -1711,7 +1720,7 @@
     RIL_CDMA_SMS_Message rcsm = {};
     constructCdmaSms(rcsm, sms);
 
-    s_vendorFunctions->onRequest(pRI->pCI->requestNumber, &rcsm, sizeof(rcsm), pRI);
+    CALL_ONREQUEST(pRI->pCI->requestNumber, &rcsm, sizeof(rcsm), pRI, mSlotId);
     return Void();
 }
 
@@ -1729,7 +1738,7 @@
     rcsa.uErrorClass = (RIL_CDMA_SMS_ErrorClass) smsAck.errorClass;
     rcsa.uSMSCauseCode = smsAck.smsCauseCode;
 
-    s_vendorFunctions->onRequest(pRI->pCI->requestNumber, &rcsa, sizeof(rcsa), pRI);
+    CALL_ONREQUEST(pRI->pCI->requestNumber, &rcsa, sizeof(rcsa), pRI, mSlotId);
     return Void();
 }
 
@@ -1766,8 +1775,8 @@
         gsmBci[i].selected = BOOL_TO_INT(configInfo[i].selected);
     }
 
-    s_vendorFunctions->onRequest(pRI->pCI->requestNumber, gsmBciPtrs,
-            num * sizeof(RIL_GSM_BroadcastSmsConfigInfo *), pRI);
+    CALL_ONREQUEST(pRI->pCI->requestNumber, gsmBciPtrs,
+            num * sizeof(RIL_GSM_BroadcastSmsConfigInfo *), pRI, mSlotId);
     return Void();
 }
 
@@ -1811,8 +1820,8 @@
         cdmaBci[i].selected = BOOL_TO_INT(configInfo[i].selected);
     }
 
-    s_vendorFunctions->onRequest(pRI->pCI->requestNumber, cdmaBciPtrs,
-            num * sizeof(RIL_CDMA_BroadcastSmsConfigInfo *), pRI);
+    CALL_ONREQUEST(pRI->pCI->requestNumber, cdmaBciPtrs,
+            num * sizeof(RIL_CDMA_BroadcastSmsConfigInfo *), pRI, mSlotId);
     return Void();
 }
 
@@ -1847,7 +1856,7 @@
     rcsw.status = (int) cdmaSms.status;
     constructCdmaSms(rcsw.message, cdmaSms.message);
 
-    s_vendorFunctions->onRequest(pRI->pCI->requestNumber, &rcsw, sizeof(rcsw), pRI);
+    CALL_ONREQUEST(pRI->pCI->requestNumber, &rcsw, sizeof(rcsw), pRI, mSlotId);
     return Void();
 }
 
@@ -1983,8 +1992,19 @@
     if (s_vendorFunctions->version <= 14) {
         RIL_InitialAttachApn iaa = {};
 
-        if (!copyHidlStringToRil(&iaa.apn, dataProfileInfo.apn, pRI)) {
-            return Void();
+        if (dataProfileInfo.apn.size() == 0) {
+            iaa.apn = (char *) calloc(1, sizeof(char));
+            if (iaa.apn == NULL) {
+                RLOGE("Memory allocation failed for request %s",
+                        requestToString(pRI->pCI->requestNumber));
+                sendErrorResponse(pRI, RIL_E_NO_MEMORY);
+                return Void();
+            }
+            iaa.apn[0] = '\0';
+        } else {
+            if (!copyHidlStringToRil(&iaa.apn, dataProfileInfo.apn, pRI)) {
+                return Void();
+            }
         }
 
         const hidl_string &protocol =
@@ -2004,15 +2024,27 @@
             return Void();
         }
 
-        s_vendorFunctions->onRequest(RIL_REQUEST_SET_INITIAL_ATTACH_APN, &iaa, sizeof(iaa), pRI);
+        CALL_ONREQUEST(RIL_REQUEST_SET_INITIAL_ATTACH_APN, &iaa, sizeof(iaa), pRI, mSlotId);
 
         memsetAndFreeStrings(4, iaa.apn, iaa.protocol, iaa.username, iaa.password);
     } else {
         RIL_InitialAttachApn_v15 iaa = {};
 
-        if (!copyHidlStringToRil(&iaa.apn, dataProfileInfo.apn, pRI)) {
-            return Void();
+        if (dataProfileInfo.apn.size() == 0) {
+            iaa.apn = (char *) calloc(1, sizeof(char));
+            if (iaa.apn == NULL) {
+                RLOGE("Memory allocation failed for request %s",
+                        requestToString(pRI->pCI->requestNumber));
+                sendErrorResponse(pRI, RIL_E_NO_MEMORY);
+                return Void();
+            }
+            iaa.apn[0] = '\0';
+        } else {
+            if (!copyHidlStringToRil(&iaa.apn, dataProfileInfo.apn, pRI)) {
+                return Void();
+            }
         }
+
         if (!copyHidlStringToRil(&iaa.protocol, dataProfileInfo.protocol, pRI)) {
             memsetAndFreeStrings(1, iaa.apn);
             return Void();
@@ -2048,7 +2080,7 @@
             return Void();
         }
 
-        s_vendorFunctions->onRequest(RIL_REQUEST_SET_INITIAL_ATTACH_APN, &iaa, sizeof(iaa), pRI);
+        CALL_ONREQUEST(RIL_REQUEST_SET_INITIAL_ATTACH_APN, &iaa, sizeof(iaa), pRI, mSlotId);
 
         memsetAndFreeStrings(6, iaa.apn, iaa.protocol, iaa.roamingProtocol, iaa.username,
                 iaa.password, iaa.mvnoMatchData);
@@ -2107,8 +2139,8 @@
     }
 
     rism.message.gsmMessage = pStrings;
-    s_vendorFunctions->onRequest(pRI->pCI->requestNumber, &rism, sizeof(RIL_RadioTechnologyFamily) +
-            sizeof(uint8_t) + sizeof(int32_t) + dataLen, pRI);
+    CALL_ONREQUEST(pRI->pCI->requestNumber, &rism, sizeof(RIL_RadioTechnologyFamily) +
+            sizeof(uint8_t) + sizeof(int32_t) + dataLen, pRI, pRI->socket_id);
 
     for (int i = 0 ; i < countStrings ; i++) {
         memsetAndFreeStrings(1, pStrings[i]);
@@ -2139,8 +2171,8 @@
 
     constructCdmaSms(rcsm, message.cdmaMessage[0]);
 
-    s_vendorFunctions->onRequest(pRI->pCI->requestNumber, &rism, sizeof(RIL_RadioTechnologyFamily) +
-            sizeof(uint8_t) + sizeof(int32_t) + sizeof(rcsm), pRI);
+    CALL_ONREQUEST(pRI->pCI->requestNumber, &rism, sizeof(RIL_RadioTechnologyFamily) +
+            sizeof(uint8_t) + sizeof(int32_t) + sizeof(rcsm), pRI, pRI->socket_id);
 
     return true;
 }
@@ -2196,7 +2228,7 @@
             return Void();
         }
 
-        s_vendorFunctions->onRequest(pRI->pCI->requestNumber, &params, sizeof(params), pRI);
+        CALL_ONREQUEST(pRI->pCI->requestNumber, &params, sizeof(params), pRI, mSlotId);
 
         memsetAndFreeStrings(1, params.aidPtr);
     }
@@ -2231,7 +2263,7 @@
     RIL_NV_ReadItem nvri = {};
     nvri.itemID = (RIL_NV_Item) itemId;
 
-    s_vendorFunctions->onRequest(pRI->pCI->requestNumber, &nvri, sizeof(nvri), pRI);
+    CALL_ONREQUEST(pRI->pCI->requestNumber, &nvri, sizeof(nvri), pRI, mSlotId);
     return Void();
 }
 
@@ -2252,7 +2284,7 @@
         return Void();
     }
 
-    s_vendorFunctions->onRequest(pRI->pCI->requestNumber, &nvwi, sizeof(nvwi), pRI);
+    CALL_ONREQUEST(pRI->pCI->requestNumber, &nvwi, sizeof(nvwi), pRI, mSlotId);
 
     memsetAndFreeStrings(1, nvwi.value);
     return Void();
@@ -2309,7 +2341,7 @@
     rilUiccSub.sub_type = (RIL_SubscriptionType) uiccSub.subType;
     rilUiccSub.act_status = (RIL_UiccSubActStatus) uiccSub.actStatus;
 
-    s_vendorFunctions->onRequest(pRI->pCI->requestNumber, &rilUiccSub, sizeof(rilUiccSub), pRI);
+    CALL_ONREQUEST(pRI->pCI->requestNumber, &rilUiccSub, sizeof(rilUiccSub), pRI, mSlotId);
     return Void();
 }
 
@@ -2353,7 +2385,7 @@
         return Void();
     }
 
-    s_vendorFunctions->onRequest(pRI->pCI->requestNumber, &pf, sizeof(pf), pRI);
+    CALL_ONREQUEST(pRI->pCI->requestNumber, &pf, sizeof(pf), pRI, mSlotId);
 
     memsetAndFreeStrings(2, pf.authData, pf.aid);
     return Void();
@@ -2464,8 +2496,8 @@
             dataProfiles[i].enabled = BOOL_TO_INT(profiles[i].enabled);
         }
 
-        s_vendorFunctions->onRequest(RIL_REQUEST_SET_DATA_PROFILE, dataProfilePtrs,
-                num * sizeof(RIL_DataProfileInfo *), pRI);
+        CALL_ONREQUEST(RIL_REQUEST_SET_DATA_PROFILE, dataProfilePtrs,
+                num * sizeof(RIL_DataProfileInfo *), pRI, mSlotId);
 
         freeSetDataProfileData(num, dataProfiles, dataProfilePtrs, 4,
                 &RIL_DataProfileInfo::apn, &RIL_DataProfileInfo::protocol,
@@ -2541,8 +2573,8 @@
             dataProfiles[i].mtu = profiles[i].mtu;
         }
 
-        s_vendorFunctions->onRequest(RIL_REQUEST_SET_DATA_PROFILE, dataProfilePtrs,
-                num * sizeof(RIL_DataProfileInfo_v15 *), pRI);
+        CALL_ONREQUEST(RIL_REQUEST_SET_DATA_PROFILE, dataProfilePtrs,
+                num * sizeof(RIL_DataProfileInfo_v15 *), pRI, mSlotId);
 
         freeSetDataProfileData(num, dataProfiles, dataProfilePtrs, 6,
                 &RIL_DataProfileInfo_v15::apn, &RIL_DataProfileInfo_v15::protocol,
@@ -2587,7 +2619,7 @@
     rilRc.status = (int) rc.status;
     strncpy(rilRc.logicalModemUuid, rc.logicalModemUuid.c_str(), MAX_UUID_LENGTH);
 
-    s_vendorFunctions->onRequest(pRI->pCI->requestNumber, &rilRc, sizeof(rilRc), pRI);
+    CALL_ONREQUEST(pRI->pCI->requestNumber, &rilRc, sizeof(rilRc), pRI, mSlotId);
 
     return Void();
 }
@@ -2679,7 +2711,7 @@
         excludedCarriers[i].match_data = carriers.excludedCarriers[i].matchData.c_str();
     }
 
-    s_vendorFunctions->onRequest(pRI->pCI->requestNumber, &cr, sizeof(RIL_CarrierRestrictions), pRI);
+    CALL_ONREQUEST(pRI->pCI->requestNumber, &cr, sizeof(RIL_CarrierRestrictions), pRI, mSlotId);
 
 #ifdef MEMSET_FREED
     memset(allowedCarriers, 0, cr.len_allowed_carriers * sizeof(RIL_Carrier));
@@ -2955,6 +2987,7 @@
         int ret = responseIntOrEmpty(responseInfo, serial, responseType, e, response, responseLen);
         Return<void> retStatus = radioService[slotId]->mRadioResponse->
                 supplyIccPinForAppResponse(responseInfo, ret);
+        RLOGE("supplyIccPinForAppResponse: amit ret %d", ret);
         radioService[slotId]->checkReturnStatus(retStatus);
     } else {
         RLOGE("supplyIccPinForAppResponse: radioService[%d]->mRadioResponse == NULL",
@@ -3102,7 +3135,8 @@
         populateResponseInfo(responseInfo, serial, responseType, e);
 
         hidl_vec<Call> calls;
-        if (response == NULL || (responseLen % sizeof(RIL_Call *)) != 0) {
+        if ((response == NULL && responseLen != 0)
+                || (responseLen % sizeof(RIL_Call *)) != 0) {
             RLOGE("getCurrentCallsResponse: Invalid response");
             if (e == RIL_E_SUCCESS) responseInfo.error = RadioError::INVALID_RESPONSE;
         } else {
@@ -3518,6 +3552,20 @@
     return -1;
 }
 
+int convertResponseHexStringEntryToInt(char **response, int index, int numStrings) {
+    const int hexBase = 16;
+    if ((response != NULL) &&  (numStrings > index) && (response[index] != NULL)) {
+        return strtol(response[index], NULL, hexBase);
+    }
+
+    return -1;
+}
+
+/* Fill Cell Identity info from Voice Registration State Response.
+ * This fucntion is applicable only for RIL Version < 15.
+ * Response is a  "char **".
+ * First and Second entries are in hex string format
+ * and rest are integers represented in ascii format. */
 void fillCellIdentityFromVoiceRegStateResponseString(CellIdentity &cellIdentity,
         int numStrings, char** response) {
 
@@ -3528,28 +3576,37 @@
     switch(rilCellIdentity.cellInfoType) {
 
         case RIL_CELL_INFO_TYPE_GSM: {
+            /* valid LAC are hexstrings in the range 0x0000 - 0xffff */
             rilCellIdentity.cellIdentityGsm.lac =
-                    convertResponseStringEntryToInt(response, 1, numStrings);
+                    convertResponseHexStringEntryToInt(response, 1, numStrings);
+
+            /* valid CID are hexstrings in the range 0x00000000 - 0xffffffff */
             rilCellIdentity.cellIdentityGsm.cid =
-                    convertResponseStringEntryToInt(response, 2, numStrings);
+                    convertResponseHexStringEntryToInt(response, 2, numStrings);
             break;
         }
 
         case RIL_CELL_INFO_TYPE_WCDMA: {
+            /* valid LAC are hexstrings in the range 0x0000 - 0xffff */
             rilCellIdentity.cellIdentityWcdma.lac =
-                    convertResponseStringEntryToInt(response, 1, numStrings);
+                    convertResponseHexStringEntryToInt(response, 1, numStrings);
+
+            /* valid CID are hexstrings in the range 0x00000000 - 0xffffffff */
             rilCellIdentity.cellIdentityWcdma.cid =
-                    convertResponseStringEntryToInt(response, 2, numStrings);
+                    convertResponseHexStringEntryToInt(response, 2, numStrings);
             rilCellIdentity.cellIdentityWcdma.psc =
                     convertResponseStringEntryToInt(response, 14, numStrings);
             break;
         }
 
         case RIL_CELL_INFO_TYPE_TD_SCDMA:{
+            /* valid LAC are hexstrings in the range 0x0000 - 0xffff */
             rilCellIdentity.cellIdentityTdscdma.lac =
-                    convertResponseStringEntryToInt(response, 1, numStrings);
+                    convertResponseHexStringEntryToInt(response, 1, numStrings);
+
+            /* valid CID are hexstrings in the range 0x00000000 - 0xffffffff */
             rilCellIdentity.cellIdentityTdscdma.cid =
-                    convertResponseStringEntryToInt(response, 2, numStrings);
+                    convertResponseHexStringEntryToInt(response, 2, numStrings);
             break;
         }
 
@@ -3569,10 +3626,13 @@
         }
 
         case RIL_CELL_INFO_TYPE_LTE:{
+            /* valid TAC are hexstrings in the range 0x0000 - 0xffff */
             rilCellIdentity.cellIdentityLte.tac =
-                    convertResponseStringEntryToInt(response, 1, numStrings);
+                    convertResponseHexStringEntryToInt(response, 1, numStrings);
+
+            /* valid CID are hexstrings in the range 0x00000000 - 0xffffffff */
             rilCellIdentity.cellIdentityLte.ci =
-                    convertResponseStringEntryToInt(response, 2, numStrings);
+                    convertResponseHexStringEntryToInt(response, 2, numStrings);
             break;
         }
 
@@ -3584,6 +3644,11 @@
     fillCellIdentityResponse(cellIdentity, rilCellIdentity);
 }
 
+/* Fill Cell Identity info from Data Registration State Response.
+ * This fucntion is applicable only for RIL Version < 15.
+ * Response is a  "char **".
+ * First and Second entries are in hex string format
+ * and rest are integers represented in ascii format. */
 void fillCellIdentityFromDataRegStateResponseString(CellIdentity &cellIdentity,
         int numStrings, char** response) {
 
@@ -3593,24 +3658,33 @@
     rilCellIdentity.cellInfoType = getCellInfoTypeRadioTechnology(response[3]);
     switch(rilCellIdentity.cellInfoType) {
         case RIL_CELL_INFO_TYPE_GSM: {
+            /* valid LAC are hexstrings in the range 0x0000 - 0xffff */
             rilCellIdentity.cellIdentityGsm.lac =
-                    convertResponseStringEntryToInt(response, 1, numStrings);
+                    convertResponseHexStringEntryToInt(response, 1, numStrings);
+
+            /* valid CID are hexstrings in the range 0x00000000 - 0xffffffff */
             rilCellIdentity.cellIdentityGsm.cid =
-                    convertResponseStringEntryToInt(response, 2, numStrings);
+                    convertResponseHexStringEntryToInt(response, 2, numStrings);
             break;
         }
         case RIL_CELL_INFO_TYPE_WCDMA: {
+            /* valid LAC are hexstrings in the range 0x0000 - 0xffff */
             rilCellIdentity.cellIdentityWcdma.lac =
-                    convertResponseStringEntryToInt(response, 1, numStrings);
+                    convertResponseHexStringEntryToInt(response, 1, numStrings);
+
+            /* valid CID are hexstrings in the range 0x00000000 - 0xffffffff */
             rilCellIdentity.cellIdentityWcdma.cid =
-                    convertResponseStringEntryToInt(response, 2, numStrings);
+                    convertResponseHexStringEntryToInt(response, 2, numStrings);
             break;
         }
         case RIL_CELL_INFO_TYPE_TD_SCDMA:{
+            /* valid LAC are hexstrings in the range 0x0000 - 0xffff */
             rilCellIdentity.cellIdentityTdscdma.lac =
-                    convertResponseStringEntryToInt(response, 1, numStrings);
+                    convertResponseHexStringEntryToInt(response, 1, numStrings);
+
+            /* valid CID are hexstrings in the range 0x00000000 - 0xffffffff */
             rilCellIdentity.cellIdentityTdscdma.cid =
-                    convertResponseStringEntryToInt(response, 2, numStrings);
+                    convertResponseHexStringEntryToInt(response, 2, numStrings);
             break;
         }
         case RIL_CELL_INFO_TYPE_LTE: {
@@ -3899,9 +3973,11 @@
         populateResponseInfo(responseInfo, serial, responseType, e);
 
         SetupDataCallResult result = {};
-        if (response == NULL || responseLen != sizeof(RIL_Data_Call_Response_v11)) {
-            RLOGE("setupDataCallResponse: Invalid response");
-            if (e == RIL_E_SUCCESS) responseInfo.error = RadioError::INVALID_RESPONSE;
+        if (response == NULL || (responseLen % sizeof(RIL_Data_Call_Response_v11)) != 0) {
+            if (response != NULL) {
+                RLOGE("setupDataCallResponse: Invalid response");
+                if (e == RIL_E_SUCCESS) responseInfo.error = RadioError::INVALID_RESPONSE;
+            }
             result.status = DataCallFailCause::ERROR_UNSPECIFIED;
             result.type = hidl_string();
             result.ifname = hidl_string();
@@ -4067,7 +4143,8 @@
         populateResponseInfo(responseInfo, serial, responseType, e);
         hidl_vec<CallForwardInfo> callForwardInfos;
 
-        if (response == NULL || responseLen % sizeof(RIL_CallForwardInfo *) != 0) {
+        if ((response == NULL && responseLen != 0)
+                || responseLen % sizeof(RIL_CallForwardInfo *) != 0) {
             RLOGE("getCallForwardStatusResponse Invalid response: NULL");
             if (e == RIL_E_SUCCESS) responseInfo.error = RadioError::INVALID_RESPONSE;
         } else {
@@ -4395,7 +4472,8 @@
         RadioResponseInfo responseInfo = {};
         populateResponseInfo(responseInfo, serial, responseType, e);
         hidl_vec<OperatorInfo> networks;
-        if (response == NULL || responseLen % (4 * sizeof(char *))!= 0) {
+        if ((response == NULL && responseLen != 0)
+                || responseLen % (4 * sizeof(char *))!= 0) {
             RLOGE("getAvailableNetworksResponse Invalid response: NULL");
             if (e == RIL_E_SUCCESS) responseInfo.error = RadioError::INVALID_RESPONSE;
         } else {
@@ -4589,7 +4667,8 @@
         populateResponseInfo(responseInfo, serial, responseType, e);
 
         hidl_vec<SetupDataCallResult> ret;
-        if (response == NULL || responseLen % sizeof(RIL_Data_Call_Response_v11) != 0) {
+        if ((response == NULL && responseLen != 0)
+                || responseLen % sizeof(RIL_Data_Call_Response_v11) != 0) {
             RLOGE("getDataCallListResponse: invalid response");
             if (e == RIL_E_SUCCESS) responseInfo.error = RadioError::INVALID_RESPONSE;
         } else {
@@ -4699,7 +4778,7 @@
         RadioResponseInfo responseInfo = {};
         populateResponseInfo(responseInfo, serial, responseType, e);
         hidl_vec<RadioBandMode> modes;
-        if (response == NULL || responseLen % sizeof(int) != 0) {
+        if ((response == NULL && responseLen != 0)|| responseLen % sizeof(int) != 0) {
             RLOGE("getAvailableBandModesResponse Invalid response: NULL");
             if (e == RIL_E_SUCCESS) responseInfo.error = RadioError::INVALID_RESPONSE;
         } else {
@@ -4866,7 +4945,8 @@
         populateResponseInfo(responseInfo, serial, responseType, e);
         hidl_vec<NeighboringCell> cells;
 
-        if (response == NULL || responseLen % sizeof(RIL_NeighboringCell *) != 0) {
+        if ((response == NULL && responseLen != 0)
+                || responseLen % sizeof(RIL_NeighboringCell *) != 0) {
             RLOGE("getNeighboringCidsResponse Invalid response: NULL");
             if (e == RIL_E_SUCCESS) responseInfo.error = RadioError::INVALID_RESPONSE;
         } else {
@@ -5169,7 +5249,8 @@
         populateResponseInfo(responseInfo, serial, responseType, e);
         hidl_vec<GsmBroadcastSmsConfigInfo> configs;
 
-        if (response == NULL || responseLen % sizeof(RIL_GSM_BroadcastSmsConfigInfo *) != 0) {
+        if ((response == NULL && responseLen != 0)
+                || responseLen % sizeof(RIL_GSM_BroadcastSmsConfigInfo *) != 0) {
             RLOGE("getGsmBroadcastConfigResponse Invalid response: NULL");
             if (e == RIL_E_SUCCESS) responseInfo.error = RadioError::INVALID_RESPONSE;
         } else {
@@ -5253,7 +5334,8 @@
         populateResponseInfo(responseInfo, serial, responseType, e);
         hidl_vec<CdmaBroadcastSmsConfigInfo> configs;
 
-        if (response == NULL || responseLen % sizeof(RIL_CDMA_BroadcastSmsConfigInfo *) != 0) {
+        if ((response == NULL && responseLen != 0)
+                || responseLen % sizeof(RIL_CDMA_BroadcastSmsConfigInfo *) != 0) {
             RLOGE("getCdmaBroadcastConfigResponse Invalid response: NULL");
             if (e == RIL_E_SUCCESS) responseInfo.error = RadioError::INVALID_RESPONSE;
         } else {
@@ -5674,7 +5756,8 @@
         populateResponseInfo(responseInfo, serial, responseType, e);
 
         hidl_vec<CellInfo> ret;
-        if (response == NULL || responseLen % sizeof(RIL_CellInfo_v12) != 0) {
+        if ((response == NULL && responseLen != 0)
+                || responseLen % sizeof(RIL_CellInfo_v12) != 0) {
             RLOGE("getCellInfoListResponse: Invalid response");
             if (e == RIL_E_SUCCESS) responseInfo.error = RadioError::INVALID_RESPONSE;
         } else {
@@ -5828,7 +5911,9 @@
         int numInts = responseLen / sizeof(int);
         if (response == NULL || responseLen % sizeof(int) != 0) {
             RLOGE("iccOpenLogicalChannelResponse Invalid response: NULL");
-            if (e == RIL_E_SUCCESS) responseInfo.error = RadioError::INVALID_RESPONSE;
+            if (response != NULL) {
+                if (e == RIL_E_SUCCESS) responseInfo.error = RadioError::INVALID_RESPONSE;
+            }
         } else {
             int *pInt = (int *) response;
             channelId = pInt[0];
@@ -6029,7 +6114,8 @@
         populateResponseInfo(responseInfo, serial, responseType, e);
 
         hidl_vec<HardwareConfig> result;
-        if (response == NULL || responseLen % sizeof(RIL_HardwareConfig) != 0) {
+        if ((response == NULL && responseLen != 0)
+                || responseLen % sizeof(RIL_HardwareConfig) != 0) {
             RLOGE("hardwareConfigChangedInd: invalid response");
             if (e == RIL_E_SUCCESS) responseInfo.error = RadioError::INVALID_RESPONSE;
         } else {
@@ -6568,7 +6654,7 @@
         populateResponseInfo(responseInfo, serial, responseType, e);
         hidl_vec<hidl_string> data;
 
-        if (response == NULL || responseLen % sizeof(char *) != 0) {
+        if ((response == NULL && responseLen != 0) || responseLen % sizeof(char *) != 0) {
             RLOGE("sendRequestStringsResponse Invalid response: NULL");
             if (e == RIL_E_SUCCESS) responseInfo.error = RadioError::INVALID_RESPONSE;
         } else {
@@ -6602,7 +6688,8 @@
                                  int indicationType, int token, RIL_Errno e, void *response,
                                  size_t responseLen) {
     if (radioService[slotId] != NULL && radioService[slotId]->mRadioIndication != NULL) {
-        RadioState radioState = (RadioState) s_vendorFunctions->onStateRequest();
+        RadioState radioState =
+                (RadioState) CALL_ONSTATEREQUEST(slotId);
         RLOGD("radioStateChangedInd: radioState %d", radioState);
         Return<void> retStatus = radioService[slotId]->mRadioIndication->radioStateChanged(
                 convertIntToRadioIndicationType(indicationType), radioState);
@@ -6915,7 +7002,8 @@
                                   int indicationType, int token, RIL_Errno e, void *response,
                                   size_t responseLen) {
     if (radioService[slotId] != NULL && radioService[slotId]->mRadioIndication != NULL) {
-        if (response == NULL || responseLen % sizeof(RIL_Data_Call_Response_v11) != 0) {
+        if ((response == NULL && responseLen != 0)
+                || responseLen % sizeof(RIL_Data_Call_Response_v11) != 0) {
             RLOGE("dataCallListChangedInd: invalid response");
             return 0;
         }
@@ -7798,7 +7886,7 @@
                            int indicationType, int token, RIL_Errno e, void *response,
                            size_t responseLen) {
     if (radioService[slotId] != NULL && radioService[slotId]->mRadioIndication != NULL) {
-        if (response == NULL || responseLen % sizeof(RIL_CellInfo_v12) != 0) {
+        if ((response == NULL && responseLen != 0) || responseLen % sizeof(RIL_CellInfo_v12) != 0) {
             RLOGE("cellInfoListInd: invalid response");
             return 0;
         }
@@ -7919,7 +8007,8 @@
                                     int indicationType, int token, RIL_Errno e, void *response,
                                     size_t responseLen) {
     if (radioService[slotId] != NULL && radioService[slotId]->mRadioIndication != NULL) {
-        if (response == NULL || responseLen % sizeof(RIL_HardwareConfig) != 0) {
+        if ((response == NULL && responseLen != 0)
+                || responseLen % sizeof(RIL_HardwareConfig) != 0) {
             RLOGE("hardwareConfigChangedInd: invalid response");
             return 0;
         }
diff --git a/reference-ril/atchannel.c b/reference-ril/atchannel.c
index 5dc3e3c..0041836 100644
--- a/reference-ril/atchannel.c
+++ b/reference-ril/atchannel.c
@@ -61,12 +61,17 @@
 #endif
 
 /*
- * for current pending command
- * these are protected by s_commandmutex
+ * There is one reader thread |s_tid_reader| and potentially multiple writer
+ * threads. |s_commandmutex| and |s_commandcond| are used to maintain the
+ * condition that the writer thread will not read from |sp_response| until the
+ * reader thread has signaled itself is finished, etc. |s_writeMutex| is used to
+ * prevent multiple writer threads from calling at_send_command_full_nolock
+ * function at the same time.
  */
 
 static pthread_mutex_t s_commandmutex = PTHREAD_MUTEX_INITIALIZER;
 static pthread_cond_t s_commandcond = PTHREAD_COND_INITIALIZER;
+static pthread_mutex_t s_writeMutex = PTHREAD_MUTEX_INITIALIZER;
 
 static ATCommandType s_type;
 static const char *s_responsePrefix = NULL;
@@ -736,12 +741,16 @@
                     long long timeoutMsec, ATResponse **pp_outResponse)
 {
     int err;
+    bool inEmulator;
 
     if (0 != pthread_equal(s_tid_reader, pthread_self())) {
         /* cannot be called from reader thread */
         return AT_ERROR_INVALID_THREAD;
     }
-
+    inEmulator = isInEmulator();
+    if (inEmulator) {
+        pthread_mutex_lock(&s_writeMutex);
+    }
     pthread_mutex_lock(&s_commandmutex);
 
     err = at_send_command_full_nolock(command, type,
@@ -749,6 +758,9 @@
                     timeoutMsec, pp_outResponse);
 
     pthread_mutex_unlock(&s_commandmutex);
+    if (inEmulator) {
+        pthread_mutex_unlock(&s_writeMutex);
+    }
 
     if (err == AT_ERROR_TIMEOUT && s_onTimeout != NULL) {
         s_onTimeout();
@@ -888,12 +900,16 @@
 {
     int i;
     int err = 0;
+    bool inEmulator;
 
     if (0 != pthread_equal(s_tid_reader, pthread_self())) {
         /* cannot be called from reader thread */
         return AT_ERROR_INVALID_THREAD;
     }
-
+    inEmulator = isInEmulator();
+    if (inEmulator) {
+        pthread_mutex_lock(&s_writeMutex);
+    }
     pthread_mutex_lock(&s_commandmutex);
 
     for (i = 0 ; i < HANDSHAKE_RETRY_COUNT ; i++) {
@@ -914,6 +930,9 @@
     }
 
     pthread_mutex_unlock(&s_commandmutex);
+    if (inEmulator) {
+        pthread_mutex_unlock(&s_writeMutex);
+    }
 
     return err;
 }
diff --git a/reference-ril/misc.c b/reference-ril/misc.c
index e4b8d72..c0e9b6e 100644
--- a/reference-ril/misc.c
+++ b/reference-ril/misc.c
@@ -14,7 +14,9 @@
 ** See the License for the specific language governing permissions and
 ** limitations under the License.
 */
+#include <sys/system_properties.h>
 
+#include "misc.h"
 /** returns 1 if line starts with prefix, 0 if it does not */
 int strStartsWith(const char *line, const char *prefix)
 {
@@ -27,3 +29,12 @@
     return *prefix == '\0';
 }
 
+// Returns true iff running this process in an emulator VM
+bool isInEmulator(void) {
+  static int inQemu = -1;
+  if (inQemu < 0) {
+      char propValue[PROP_VALUE_MAX];
+      inQemu = (__system_property_get("ro.kernel.qemu", propValue) != 0);
+  }
+  return inQemu == 1;
+}
diff --git a/reference-ril/misc.h b/reference-ril/misc.h
index 7044a07..9e65ab3 100644
--- a/reference-ril/misc.h
+++ b/reference-ril/misc.h
@@ -14,6 +14,9 @@
 ** See the License for the specific language governing permissions and
 ** limitations under the License.
 */
+#include <stdbool.h>
 
 /** returns 1 if line starts with prefix, 0 if it does not */
 int strStartsWith(const char *line, const char *prefix);
+/** Returns true iff running this process in an emulator VM */
+bool isInEmulator(void);
\ No newline at end of file
diff --git a/reference-ril/reference-ril.c b/reference-ril/reference-ril.c
index 16e379a..c20fb81 100644
--- a/reference-ril/reference-ril.c
+++ b/reference-ril/reference-ril.c
@@ -17,7 +17,6 @@
 
 #include <telephony/ril_cdma_sms.h>
 #include <telephony/librilutils.h>
-#include <stdbool.h>
 #include <stdio.h>
 #include <assert.h>
 #include <string.h>
@@ -26,6 +25,7 @@
 #include <sys/cdefs.h>
 #include <sys/types.h>
 #include <sys/stat.h>
+#include <inttypes.h>
 #include <fcntl.h>
 #include <pthread.h>
 #include <alloca.h>
@@ -35,8 +35,8 @@
 #include <getopt.h>
 #include <sys/socket.h>
 #include <cutils/sockets.h>
-#include <termios.h>
 #include <sys/system_properties.h>
+#include <termios.h>
 #include <system/qemu_pipe.h>
 
 #include "ril.h"
@@ -240,15 +240,6 @@
 static int s_expectAnswer = 0;
 #endif /* WORKAROUND_ERRONEOUS_ANSWER */
 
-// Returns true iff running this process in an emulator VM
-static bool isInEmulator(void) {
-    static int inQemu = -1;
-    if (inQemu < 0) {
-        char propValue[PROP_VALUE_MAX];
-        inQemu = (__system_property_get("ro.kernel.qemu", propValue) != 0);
-    }
-    return inQemu == 1;
-}
 
 static int s_cell_info_rate_ms = INT_MAX;
 static int s_mcc = 0;
@@ -340,6 +331,22 @@
     return -1;
 }
 
+static int parseSimResponseLine(char* line, RIL_SIM_IO_Response* response) {
+    int err;
+
+    err = at_tok_start(&line);
+    if (err < 0) return err;
+    err = at_tok_nextint(&line, &response->sw1);
+    if (err < 0) return err;
+    err = at_tok_nextint(&line, &response->sw2);
+    if (err < 0) return err;
+
+    if (at_tok_hasmore(&line)) {
+        err = at_tok_nextstr(&line, &response->simResponse);
+        if (err < 0) return err;
+    }
+    return 0;
+}
 
 /** do post-AT+CFUN=1 initialization */
 static void onRadioPowerOn()
@@ -543,23 +550,27 @@
         err = at_tok_nextstr(&line, &out);
         if (err < 0)
             goto error;
-        responses[i].type = alloca(strlen(out) + 1);
-        strcpy(responses[i].type, out);
+
+        int type_size = strlen(out) + 1;
+        responses[i].type = alloca(type_size);
+        strlcpy(responses[i].type, out, type_size);
 
         // APN ignored for v5
         err = at_tok_nextstr(&line, &out);
         if (err < 0)
             goto error;
 
-        responses[i].ifname = alloca(strlen(PPP_TTY_PATH) + 1);
-        strcpy(responses[i].ifname, PPP_TTY_PATH);
+        int ifname_size = strlen(PPP_TTY_PATH) + 1;
+        responses[i].ifname = alloca(ifname_size);
+        strlcpy(responses[i].ifname, PPP_TTY_PATH, ifname_size);
 
         err = at_tok_nextstr(&line, &out);
         if (err < 0)
             goto error;
 
-        responses[i].addresses = alloca(strlen(out) + 1);
-        strcpy(responses[i].addresses, out);
+        int addresses_size = strlen(out) + 1;
+        responses[i].addresses = alloca(addresses_size);
+        strlcpy(responses[i].addresses, out, addresses_size);
 
         if (isInEmulator()) {
             /* We are in the emulator - the dns servers are listed
@@ -1652,6 +1663,119 @@
     RIL_onRequestComplete(t, RIL_E_SMS_SEND_FAIL_RETRY, &response, sizeof(response));
 }
 
+static void requestSimOpenChannel(void *data, size_t datalen, RIL_Token t)
+{
+    ATResponse *p_response = NULL;
+    int32_t session_id;
+    int err;
+    char cmd[32];
+    char dummy;
+    char *line;
+
+    // Max length is 16 bytes according to 3GPP spec 27.007 section 8.45
+    if (data == NULL || datalen == 0 || datalen > 16) {
+        ALOGE("Invalid data passed to requestSimOpenChannel");
+        RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
+        return;
+    }
+
+    snprintf(cmd, sizeof(cmd), "AT+CCHO=%s", data);
+
+    err = at_send_command_numeric(cmd, &p_response);
+    if (err < 0 || p_response == NULL || p_response->success == 0) {
+        ALOGE("Error %d opening logical channel: %d",
+              err, p_response ? p_response->success : 0);
+        RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
+        at_response_free(p_response);
+        return;
+    }
+
+    // Ensure integer only by scanning for an extra char but expect one result
+    line = p_response->p_intermediates->line;
+    if (sscanf(line, "%" SCNd32 "%c", &session_id, &dummy) != 1) {
+        ALOGE("Invalid AT response, expected integer, was '%s'", line);
+        RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
+        return;
+    }
+
+    RIL_onRequestComplete(t, RIL_E_SUCCESS, &session_id, sizeof(&session_id));
+    at_response_free(p_response);
+}
+
+static void requestSimCloseChannel(void *data, size_t datalen, RIL_Token t)
+{
+    ATResponse *p_response = NULL;
+    int32_t session_id;
+    int err;
+    char cmd[32];
+
+    if (data == NULL || datalen != sizeof(session_id)) {
+        ALOGE("Invalid data passed to requestSimCloseChannel");
+        RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
+        return;
+    }
+    session_id = ((int32_t *)data)[0];
+    snprintf(cmd, sizeof(cmd), "AT+CCHC=%" PRId32, session_id);
+    err = at_send_command_singleline(cmd, "+CCHC", &p_response);
+
+    if (err < 0 || p_response == NULL || p_response->success == 0) {
+        ALOGE("Error %d closing logical channel %d: %d",
+              err, session_id, p_response ? p_response->success : 0);
+        RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
+        at_response_free(p_response);
+        return;
+    }
+
+    RIL_onRequestComplete(t, RIL_E_SUCCESS, NULL, 0);
+
+    at_response_free(p_response);
+}
+
+static void requestSimTransmitApduChannel(void *data,
+                                          size_t datalen,
+                                          RIL_Token t)
+{
+    ATResponse *p_response = NULL;
+    int err;
+    char *cmd;
+    char *line;
+    size_t cmd_size;
+    RIL_SIM_IO_Response sim_response;
+    RIL_SIM_APDU *apdu = (RIL_SIM_APDU *)data;
+
+    if (apdu == NULL || datalen != sizeof(RIL_SIM_APDU)) {
+        RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
+        return;
+    }
+
+    cmd_size = 10 + (apdu->data ? strlen(apdu->data) : 0);
+    asprintf(&cmd, "AT+CGLA=%d,%zu,%02x%02x%02x%02x%02x%s",
+             apdu->sessionid, cmd_size, apdu->cla, apdu->instruction,
+             apdu->p1, apdu->p2, apdu->p3, apdu->data ? apdu->data : "");
+
+    err = at_send_command_singleline(cmd, "+CGLA", &p_response);
+    free(cmd);
+    if (err < 0 || p_response == NULL || p_response->success == 0) {
+        ALOGE("Error %d transmitting APDU: %d",
+              err, p_response ? p_response->success : 0);
+        RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
+        at_response_free(p_response);
+        return;
+    }
+
+    line = p_response->p_intermediates->line;
+    err = parseSimResponseLine(line, &sim_response);
+
+    if (err == 0) {
+        RIL_onRequestComplete(t, RIL_E_SUCCESS,
+                              &sim_response, sizeof(sim_response));
+    } else {
+        ALOGE("Error %d parsing SIM response line: %s", err, line);
+        RIL_onRequestComplete(t, RIL_E_GENERIC_FAILURE, NULL, 0);
+    }
+    at_response_free(p_response);
+}
+
 static void requestSetupDataCall(void *data, size_t datalen, RIL_Token t)
 {
     const char *apn;
@@ -1830,18 +1954,9 @@
 
     line = p_response->p_intermediates->line;
 
-    err = at_tok_start(&line);
-    if (err < 0) goto error;
-
-    err = at_tok_nextint(&line, &(sr.sw1));
-    if (err < 0) goto error;
-
-    err = at_tok_nextint(&line, &(sr.sw2));
-    if (err < 0) goto error;
-
-    if (at_tok_hasmore(&line)) {
-        err = at_tok_nextstr(&line, &(sr.simResponse));
-        if (err < 0) goto error;
+    err = parseSimResponseLine(line, &sr);
+    if (err < 0) {
+        goto error;
     }
 
     RIL_onRequestComplete(t, RIL_E_SUCCESS, &sr, sizeof(sr));
@@ -2001,9 +2116,9 @@
  * RIL_onRequestComplete() may be called from any thread, before or after
  * this function returns.
  *
- * Will always be called from the same thread, so returning here implies
- * that the radio is ready to process another command (whether or not
- * the previous command has completed).
+ * Because onRequest function could be called from multiple different thread,
+ * we must ensure that the underlying at_send_command_* function
+ * is atomic.
  */
 static void
 onRequest (int request, void *data, size_t datalen, RIL_Token t)
@@ -2175,6 +2290,15 @@
         case RIL_REQUEST_IMS_SEND_SMS:
             requestImsSendSMS(data, datalen, t);
             break;
+        case RIL_REQUEST_SIM_OPEN_CHANNEL:
+            requestSimOpenChannel(data, datalen, t);
+            break;
+        case RIL_REQUEST_SIM_CLOSE_CHANNEL:
+            requestSimCloseChannel(data, datalen, t);
+            break;
+        case RIL_REQUEST_SIM_TRANSMIT_APDU_CHANNEL:
+            requestSimTransmitApduChannel(data, datalen, t);
+            break;
         case RIL_REQUEST_SETUP_DATA_CALL:
             requestSetupDataCall(data, datalen, t);
             break;
diff --git a/rild/Android.mk b/rild/Android.mk
index fe81d22..4f5802b 100644
--- a/rild/Android.mk
+++ b/rild/Android.mk
@@ -6,21 +6,20 @@
 LOCAL_SRC_FILES:= \
 	rild.c
 
-
 LOCAL_SHARED_LIBRARIES := \
-	liblog \
 	libcutils \
-	libril \
-	libdl
+	libdl \
+	liblog \
+	libril
 
-# temporary hack for broken vendor rils
+# Temporary hack for broken vendor RILs.
 LOCAL_WHOLE_STATIC_LIBRARIES := \
 	librilutils_static
 
 LOCAL_CFLAGS := -DRIL_SHLIB
-#LOCAL_CFLAGS += -DANDROID_MULTI_SIM
 
 ifeq ($(SIM_COUNT), 2)
+    LOCAL_CFLAGS += -DANDROID_MULTI_SIM
     LOCAL_CFLAGS += -DANDROID_SIM_COUNT_2
 endif
 
diff --git a/rild/rild.c b/rild/rild.c
index d324692..96bd2ff 100644
--- a/rild/rild.c
+++ b/rild/rild.c
@@ -40,7 +40,6 @@
 #define LIB_PATH_PROPERTY   "rild.libpath"
 #define LIB_ARGS_PROPERTY   "rild.libargs"
 #define MAX_LIB_ARGS        16
-#define MAX_CAP_NUM         (CAP_TO_INDEX(CAP_LAST_CAP) + 1)
 
 static void usage(const char *argv0) {
     fprintf(stderr, "Usage: %s -l <ril impl library> [-- <args for impl library>]\n", argv0);
@@ -98,54 +97,9 @@
     return count;
 }
 
-/*
- * switchUser - Switches UID to radio, preserving CAP_NET_ADMIN capabilities.
- * Our group, cache, was set by init.
- */
-void switchUser() {
-    char debuggable[PROP_VALUE_MAX];
-
-    prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
-    if (setresuid(AID_RADIO, AID_RADIO, AID_RADIO) == -1) {
-        RLOGE("setresuid failed: %s", strerror(errno));
-        exit(EXIT_FAILURE);
-    }
-
-    struct __user_cap_header_struct header;
-    memset(&header, 0, sizeof(header));
-    header.version = _LINUX_CAPABILITY_VERSION_3;
-    header.pid = 0;
-
-    struct __user_cap_data_struct data[MAX_CAP_NUM];
-    memset(&data, 0, sizeof(data));
-
-    data[CAP_TO_INDEX(CAP_NET_ADMIN)].effective |= CAP_TO_MASK(CAP_NET_ADMIN);
-    data[CAP_TO_INDEX(CAP_NET_ADMIN)].permitted |= CAP_TO_MASK(CAP_NET_ADMIN);
-
-    data[CAP_TO_INDEX(CAP_NET_RAW)].effective |= CAP_TO_MASK(CAP_NET_RAW);
-    data[CAP_TO_INDEX(CAP_NET_RAW)].permitted |= CAP_TO_MASK(CAP_NET_RAW);
-
-    data[CAP_TO_INDEX(CAP_BLOCK_SUSPEND)].effective |= CAP_TO_MASK(CAP_BLOCK_SUSPEND);
-    data[CAP_TO_INDEX(CAP_BLOCK_SUSPEND)].permitted |= CAP_TO_MASK(CAP_BLOCK_SUSPEND);
-
-    if (capset(&header, &data[0]) == -1) {
-        RLOGE("capset failed: %s", strerror(errno));
-        exit(EXIT_FAILURE);
-    }
-
-    /*
-     * Debuggable build only:
-     * Set DUMPABLE that was cleared by setuid() to have tombstone on RIL crash
-     */
-    property_get("ro.debuggable", debuggable, "0");
-    if (strcmp(debuggable, "1") == 0) {
-        prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
-    }
-}
-
 int main(int argc, char **argv) {
     // vendor ril lib path either passed in as -l parameter, or read from rild.libpath property
-    const char * rilLibPath = NULL;
+    const char *rilLibPath = NULL;
     // ril arguments either passed in as -- parameter, or read from rild.libargs property
     char **rilArgv;
     // handle for vendor ril lib
@@ -209,8 +163,6 @@
         }
     }
 
-    switchUser();
-
     dlHandle = dlopen(rilLibPath, RTLD_NOW);
 
     if (dlHandle == NULL) {
@@ -252,7 +204,7 @@
     }
 
     rilArgv[argc++] = "-c";
-    rilArgv[argc++] = clientId;
+    rilArgv[argc++] = (char*)clientId;
     RLOGD("RIL_Init argc = %d clientId = %s", argc, rilArgv[argc-1]);
 
     // Make sure there's a reasonable argv[0]
diff --git a/rild/rild.rc b/rild/rild.rc
index 2aa8c63..b27e1da 100644
--- a/rild/rild.rc
+++ b/rild/rild.rc
@@ -1,4 +1,5 @@
 service ril-daemon /vendor/bin/hw/rild
     class main
-    user root
+    user radio
     group radio cache inet misc audio log readproc wakelock
+    capabilities BLOCK_SUSPEND NET_ADMIN NET_RAW