Home | History | Annotate | Download | only in jni
      1 /*
      2  * Copyright (C) 2012 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #include <semaphore.h>
     18 #include <errno.h>
     19 #include "OverrideLog.h"
     20 #include "NfcJniUtil.h"
     21 #include "NfcAdaptation.h"
     22 #include "SyncEvent.h"
     23 #include "PeerToPeer.h"
     24 #include "RoutingManager.h"
     25 #include "NfcTag.h"
     26 #include "config.h"
     27 #include "PowerSwitch.h"
     28 #include "JavaClassConstants.h"
     29 #include "Pn544Interop.h"
     30 #include <ScopedLocalRef.h>
     31 #include <ScopedUtfChars.h>
     32 #include <ScopedPrimitiveArray.h>
     33 
     34 extern "C"
     35 {
     36     #include "nfa_api.h"
     37     #include "nfa_p2p_api.h"
     38     #include "rw_api.h"
     39     #include "nfa_ee_api.h"
     40     #include "nfc_brcm_defs.h"
     41     #include "ce_api.h"
     42 }
     43 
     44 extern const UINT8 nfca_version_string [];
     45 extern const UINT8 nfa_version_string [];
     46 extern tNFA_DM_DISC_FREQ_CFG* p_nfa_dm_rf_disc_freq_cfg; //defined in stack
     47 namespace android
     48 {
     49     extern bool gIsTagDeactivating;
     50     extern bool gIsSelectingRfInterface;
     51     extern void nativeNfcTag_doTransceiveStatus (tNFA_STATUS status, uint8_t * buf, uint32_t buflen);
     52     extern void nativeNfcTag_notifyRfTimeout ();
     53     extern void nativeNfcTag_doConnectStatus (jboolean is_connect_ok);
     54     extern void nativeNfcTag_doDeactivateStatus (int status);
     55     extern void nativeNfcTag_doWriteStatus (jboolean is_write_ok);
     56     extern void nativeNfcTag_doCheckNdefResult (tNFA_STATUS status, uint32_t max_size, uint32_t current_size, uint8_t flags);
     57     extern void nativeNfcTag_doMakeReadonlyResult (tNFA_STATUS status);
     58     extern void nativeNfcTag_doPresenceCheckResult (tNFA_STATUS status);
     59     extern void nativeNfcTag_formatStatus (bool is_ok);
     60     extern void nativeNfcTag_resetPresenceCheck ();
     61     extern void nativeNfcTag_doReadCompleted (tNFA_STATUS status);
     62     extern void nativeNfcTag_abortWaits ();
     63     extern void nativeLlcpConnectionlessSocket_abortWait ();
     64     extern void nativeNfcTag_registerNdefTypeHandler ();
     65     extern void nativeLlcpConnectionlessSocket_receiveData (uint8_t* data, uint32_t len, uint32_t remote_sap);
     66 }
     67 
     68 
     69 /*****************************************************************************
     70 **
     71 ** public variables and functions
     72 **
     73 *****************************************************************************/
     74 bool                        gActivated = false;
     75 SyncEvent                   gDeactivatedEvent;
     76 
     77 namespace android
     78 {
     79     jmethodID               gCachedNfcManagerNotifyNdefMessageListeners;
     80     jmethodID               gCachedNfcManagerNotifyTransactionListeners;
     81     jmethodID               gCachedNfcManagerNotifyLlcpLinkActivation;
     82     jmethodID               gCachedNfcManagerNotifyLlcpLinkDeactivated;
     83     jmethodID               gCachedNfcManagerNotifyLlcpFirstPacketReceived;
     84     jmethodID               gCachedNfcManagerNotifyHostEmuActivated;
     85     jmethodID               gCachedNfcManagerNotifyHostEmuData;
     86     jmethodID               gCachedNfcManagerNotifyHostEmuDeactivated;
     87     jmethodID               gCachedNfcManagerNotifyRfFieldActivated;
     88     jmethodID               gCachedNfcManagerNotifyRfFieldDeactivated;
     89     const char*             gNativeP2pDeviceClassName                 = "com/android/nfc/dhimpl/NativeP2pDevice";
     90     const char*             gNativeLlcpServiceSocketClassName         = "com/android/nfc/dhimpl/NativeLlcpServiceSocket";
     91     const char*             gNativeLlcpConnectionlessSocketClassName  = "com/android/nfc/dhimpl/NativeLlcpConnectionlessSocket";
     92     const char*             gNativeLlcpSocketClassName                = "com/android/nfc/dhimpl/NativeLlcpSocket";
     93     const char*             gNativeNfcTagClassName                    = "com/android/nfc/dhimpl/NativeNfcTag";
     94     const char*             gNativeNfcManagerClassName                = "com/android/nfc/dhimpl/NativeNfcManager";
     95     void                    doStartupConfig ();
     96     void                    startStopPolling (bool isStartPolling);
     97     void                    startRfDiscovery (bool isStart);
     98 }
     99 
    100 
    101 /*****************************************************************************
    102 **
    103 ** private variables and functions
    104 **
    105 *****************************************************************************/
    106 namespace android
    107 {
    108 static jint                 sLastError = ERROR_BUFFER_TOO_SMALL;
    109 static jmethodID            sCachedNfcManagerNotifySeApduReceived;
    110 static jmethodID            sCachedNfcManagerNotifySeMifareAccess;
    111 static jmethodID            sCachedNfcManagerNotifySeEmvCardRemoval;
    112 static jmethodID            sCachedNfcManagerNotifyTargetDeselected;
    113 static SyncEvent            sNfaEnableEvent;  //event for NFA_Enable()
    114 static SyncEvent            sNfaDisableEvent;  //event for NFA_Disable()
    115 static SyncEvent            sNfaEnableDisablePollingEvent;  //event for NFA_EnablePolling(), NFA_DisablePolling()
    116 static SyncEvent            sNfaSetConfigEvent;  // event for Set_Config....
    117 static SyncEvent            sNfaGetConfigEvent;  // event for Get_Config....
    118 static bool                 sIsNfaEnabled = false;
    119 static bool                 sDiscoveryEnabled = false;  //is polling or listening
    120 static bool                 sPollingEnabled = false;  //is polling for tag?
    121 static bool                 sIsDisabling = false;
    122 static bool                 sRfEnabled = false; // whether RF discovery is enabled
    123 static bool                 sSeRfActive = false;  // whether RF with SE is likely active
    124 static bool                 sReaderModeEnabled = false; // whether we're only reading tags, not allowing P2p/card emu
    125 static bool                 sP2pActive = false; // whether p2p was last active
    126 static bool                 sAbortConnlessWait = false;
    127 #define CONFIG_UPDATE_TECH_MASK     (1 << 1)
    128 #define DEFAULT_TECH_MASK           (NFA_TECHNOLOGY_MASK_A \
    129                                      | NFA_TECHNOLOGY_MASK_B \
    130                                      | NFA_TECHNOLOGY_MASK_F \
    131                                      | NFA_TECHNOLOGY_MASK_ISO15693 \
    132                                      | NFA_TECHNOLOGY_MASK_B_PRIME \
    133                                      | NFA_TECHNOLOGY_MASK_A_ACTIVE \
    134                                      | NFA_TECHNOLOGY_MASK_F_ACTIVE \
    135                                      | NFA_TECHNOLOGY_MASK_KOVIO)
    136 #define DEFAULT_DISCOVERY_DURATION       500
    137 #define READER_MODE_DISCOVERY_DURATION   200
    138 
    139 static void nfaConnectionCallback (UINT8 event, tNFA_CONN_EVT_DATA *eventData);
    140 static void nfaDeviceManagementCallback (UINT8 event, tNFA_DM_CBACK_DATA *eventData);
    141 static bool isPeerToPeer (tNFA_ACTIVATED& activated);
    142 static bool isListenMode(tNFA_ACTIVATED& activated);
    143 static void enableDisableLptd (bool enable);
    144 static tNFA_STATUS stopPolling_rfDiscoveryDisabled();
    145 static tNFA_STATUS startPolling_rfDiscoveryDisabled(tNFA_TECHNOLOGY_MASK tech_mask);
    146 
    147 static UINT16 sCurrentConfigLen;
    148 static UINT8 sConfig[256];
    149 
    150 /////////////////////////////////////////////////////////////
    151 /////////////////////////////////////////////////////////////
    152 
    153 
    154 /*******************************************************************************
    155 **
    156 ** Function:        getNative
    157 **
    158 ** Description:     Get native data
    159 **
    160 ** Returns:         Native data structure.
    161 **
    162 *******************************************************************************/
    163 nfc_jni_native_data *getNative (JNIEnv* e, jobject o)
    164 {
    165     static struct nfc_jni_native_data *sCachedNat = NULL;
    166     if (e)
    167     {
    168         sCachedNat = nfc_jni_get_nat(e, o);
    169     }
    170     return sCachedNat;
    171 }
    172 
    173 
    174 /*******************************************************************************
    175 **
    176 ** Function:        handleRfDiscoveryEvent
    177 **
    178 ** Description:     Handle RF-discovery events from the stack.
    179 **                  discoveredDevice: Discovered device.
    180 **
    181 ** Returns:         None
    182 **
    183 *******************************************************************************/
    184 static void handleRfDiscoveryEvent (tNFC_RESULT_DEVT* discoveredDevice)
    185 {
    186     if (discoveredDevice->more)
    187     {
    188         //there is more discovery notification coming
    189         return;
    190     }
    191 
    192     bool isP2p = NfcTag::getInstance ().isP2pDiscovered ();
    193     if (!sReaderModeEnabled && isP2p)
    194     {
    195         //select the peer that supports P2P
    196         NfcTag::getInstance ().selectP2p();
    197     }
    198     else
    199     {
    200         //select the first of multiple tags that is discovered
    201         NfcTag::getInstance ().selectFirstTag();
    202     }
    203 }
    204 
    205 
    206 /*******************************************************************************
    207 **
    208 ** Function:        nfaConnectionCallback
    209 **
    210 ** Description:     Receive connection-related events from stack.
    211 **                  connEvent: Event code.
    212 **                  eventData: Event data.
    213 **
    214 ** Returns:         None
    215 **
    216 *******************************************************************************/
    217 static void nfaConnectionCallback (UINT8 connEvent, tNFA_CONN_EVT_DATA* eventData)
    218 {
    219     tNFA_STATUS status = NFA_STATUS_FAILED;
    220     ALOGD("%s: event= %u", __FUNCTION__, connEvent);
    221 
    222     switch (connEvent)
    223     {
    224     case NFA_POLL_ENABLED_EVT: // whether polling successfully started
    225         {
    226             ALOGD("%s: NFA_POLL_ENABLED_EVT: status = %u", __FUNCTION__, eventData->status);
    227 
    228             SyncEventGuard guard (sNfaEnableDisablePollingEvent);
    229             sNfaEnableDisablePollingEvent.notifyOne ();
    230         }
    231         break;
    232 
    233     case NFA_POLL_DISABLED_EVT: // Listening/Polling stopped
    234         {
    235             ALOGD("%s: NFA_POLL_DISABLED_EVT: status = %u", __FUNCTION__, eventData->status);
    236 
    237             SyncEventGuard guard (sNfaEnableDisablePollingEvent);
    238             sNfaEnableDisablePollingEvent.notifyOne ();
    239         }
    240         break;
    241 
    242     case NFA_RF_DISCOVERY_STARTED_EVT: // RF Discovery started
    243         {
    244             ALOGD("%s: NFA_RF_DISCOVERY_STARTED_EVT: status = %u", __FUNCTION__, eventData->status);
    245 
    246             SyncEventGuard guard (sNfaEnableDisablePollingEvent);
    247             sNfaEnableDisablePollingEvent.notifyOne ();
    248         }
    249         break;
    250 
    251     case NFA_RF_DISCOVERY_STOPPED_EVT: // RF Discovery stopped event
    252         {
    253             ALOGD("%s: NFA_RF_DISCOVERY_STOPPED_EVT: status = %u", __FUNCTION__, eventData->status);
    254 
    255             SyncEventGuard guard (sNfaEnableDisablePollingEvent);
    256             sNfaEnableDisablePollingEvent.notifyOne ();
    257         }
    258         break;
    259 
    260     case NFA_DISC_RESULT_EVT: // NFC link/protocol discovery notificaiton
    261         status = eventData->disc_result.status;
    262         ALOGD("%s: NFA_DISC_RESULT_EVT: status = %d", __FUNCTION__, status);
    263         if (status != NFA_STATUS_OK)
    264         {
    265             ALOGE("%s: NFA_DISC_RESULT_EVT error: status = %d", __FUNCTION__, status);
    266         }
    267         else
    268         {
    269             NfcTag::getInstance().connectionEventHandler(connEvent, eventData);
    270             handleRfDiscoveryEvent(&eventData->disc_result.discovery_ntf);
    271         }
    272         break;
    273 
    274     case NFA_SELECT_RESULT_EVT: // NFC link/protocol discovery select response
    275         ALOGD("%s: NFA_SELECT_RESULT_EVT: status = %d, gIsSelectingRfInterface = %d, sIsDisabling=%d", __FUNCTION__, eventData->status, gIsSelectingRfInterface, sIsDisabling);
    276 
    277         if (sIsDisabling)
    278             break;
    279 
    280         if (eventData->status != NFA_STATUS_OK)
    281         {
    282             if (gIsSelectingRfInterface)
    283             {
    284                 nativeNfcTag_doConnectStatus(false);
    285             }
    286 
    287             ALOGE("%s: NFA_SELECT_RESULT_EVT error: status = %d", __FUNCTION__, eventData->status);
    288             NFA_Deactivate (FALSE);
    289         }
    290         break;
    291 
    292     case NFA_DEACTIVATE_FAIL_EVT:
    293         ALOGD("%s: NFA_DEACTIVATE_FAIL_EVT: status = %d", __FUNCTION__, eventData->status);
    294         break;
    295 
    296     case NFA_ACTIVATED_EVT: // NFC link/protocol activated
    297         ALOGD("%s: NFA_ACTIVATED_EVT: gIsSelectingRfInterface=%d, sIsDisabling=%d", __FUNCTION__, gIsSelectingRfInterface, sIsDisabling);
    298         NfcTag::getInstance().setActive(true);
    299         if (sIsDisabling || !sIsNfaEnabled)
    300             break;
    301         gActivated = true;
    302 
    303         NfcTag::getInstance().setActivationState ();
    304         if (gIsSelectingRfInterface)
    305         {
    306             nativeNfcTag_doConnectStatus(true);
    307             break;
    308         }
    309 
    310         nativeNfcTag_resetPresenceCheck();
    311         if (isPeerToPeer(eventData->activated))
    312         {
    313             if (sReaderModeEnabled)
    314             {
    315                 ALOGD("%s: ignoring peer target in reader mode.", __FUNCTION__);
    316                 NFA_Deactivate (FALSE);
    317                 break;
    318             }
    319             sP2pActive = true;
    320             ALOGD("%s: NFA_ACTIVATED_EVT; is p2p", __FUNCTION__);
    321             // Disable RF field events in case of p2p
    322             UINT8  nfa_disable_rf_events[] = { 0x00 };
    323             ALOGD ("%s: Disabling RF field events", __FUNCTION__);
    324             status = NFA_SetConfig(NCI_PARAM_ID_RF_FIELD_INFO, sizeof(nfa_disable_rf_events),
    325                     &nfa_disable_rf_events[0]);
    326             if (status == NFA_STATUS_OK) {
    327                 ALOGD ("%s: Disabled RF field events", __FUNCTION__);
    328             } else {
    329                 ALOGE ("%s: Failed to disable RF field events", __FUNCTION__);
    330             }
    331         }
    332         else if (pn544InteropIsBusy() == false)
    333         {
    334             NfcTag::getInstance().connectionEventHandler (connEvent, eventData);
    335 
    336             // We know it is not activating for P2P.  If it activated in
    337             // listen mode then it is likely for an SE transaction.
    338             // Send the RF Event.
    339             if (isListenMode(eventData->activated))
    340             {
    341                 sSeRfActive = true;
    342             }
    343         }
    344         break;
    345 
    346     case NFA_DEACTIVATED_EVT: // NFC link/protocol deactivated
    347         ALOGD("%s: NFA_DEACTIVATED_EVT   Type: %u, gIsTagDeactivating: %d", __FUNCTION__, eventData->deactivated.type,gIsTagDeactivating);
    348         NfcTag::getInstance().setDeactivationState (eventData->deactivated);
    349         if (eventData->deactivated.type != NFA_DEACTIVATE_TYPE_SLEEP)
    350         {
    351             {
    352                 SyncEventGuard g (gDeactivatedEvent);
    353                 gActivated = false; //guard this variable from multi-threaded access
    354                 gDeactivatedEvent.notifyOne ();
    355             }
    356             nativeNfcTag_resetPresenceCheck();
    357             NfcTag::getInstance().connectionEventHandler (connEvent, eventData);
    358             nativeNfcTag_abortWaits();
    359             NfcTag::getInstance().abort ();
    360         }
    361         else if (gIsTagDeactivating)
    362         {
    363             NfcTag::getInstance().setActive(false);
    364             nativeNfcTag_doDeactivateStatus(0);
    365         }
    366 
    367         // If RF is activated for what we think is a Secure Element transaction
    368         // and it is deactivated to either IDLE or DISCOVERY mode, notify w/event.
    369         if ((eventData->deactivated.type == NFA_DEACTIVATE_TYPE_IDLE)
    370                 || (eventData->deactivated.type == NFA_DEACTIVATE_TYPE_DISCOVERY))
    371         {
    372             if (sSeRfActive) {
    373                 sSeRfActive = false;
    374             } else if (sP2pActive) {
    375                 sP2pActive = false;
    376                 // Make sure RF field events are re-enabled
    377                 ALOGD("%s: NFA_DEACTIVATED_EVT; is p2p", __FUNCTION__);
    378                 // Disable RF field events in case of p2p
    379                 UINT8  nfa_enable_rf_events[] = { 0x01 };
    380 
    381                 if (!sIsDisabling && sIsNfaEnabled)
    382                 {
    383                     ALOGD ("%s: Enabling RF field events", __FUNCTION__);
    384                     status = NFA_SetConfig(NCI_PARAM_ID_RF_FIELD_INFO, sizeof(nfa_enable_rf_events),
    385                             &nfa_enable_rf_events[0]);
    386                     if (status == NFA_STATUS_OK) {
    387                         ALOGD ("%s: Enabled RF field events", __FUNCTION__);
    388                     } else {
    389                         ALOGE ("%s: Failed to enable RF field events", __FUNCTION__);
    390                     }
    391                 }
    392             }
    393         }
    394 
    395         break;
    396 
    397     case NFA_TLV_DETECT_EVT: // TLV Detection complete
    398         status = eventData->tlv_detect.status;
    399         ALOGD("%s: NFA_TLV_DETECT_EVT: status = %d, protocol = %d, num_tlvs = %d, num_bytes = %d",
    400              __FUNCTION__, status, eventData->tlv_detect.protocol,
    401              eventData->tlv_detect.num_tlvs, eventData->tlv_detect.num_bytes);
    402         if (status != NFA_STATUS_OK)
    403         {
    404             ALOGE("%s: NFA_TLV_DETECT_EVT error: status = %d", __FUNCTION__, status);
    405         }
    406         break;
    407 
    408     case NFA_NDEF_DETECT_EVT: // NDEF Detection complete;
    409         //if status is failure, it means the tag does not contain any or valid NDEF data;
    410         //pass the failure status to the NFC Service;
    411         status = eventData->ndef_detect.status;
    412         ALOGD("%s: NFA_NDEF_DETECT_EVT: status = 0x%X, protocol = %u, "
    413              "max_size = %lu, cur_size = %lu, flags = 0x%X", __FUNCTION__,
    414              status,
    415              eventData->ndef_detect.protocol, eventData->ndef_detect.max_size,
    416              eventData->ndef_detect.cur_size, eventData->ndef_detect.flags);
    417         NfcTag::getInstance().connectionEventHandler (connEvent, eventData);
    418         nativeNfcTag_doCheckNdefResult(status,
    419             eventData->ndef_detect.max_size, eventData->ndef_detect.cur_size,
    420             eventData->ndef_detect.flags);
    421         break;
    422 
    423     case NFA_DATA_EVT: // Data message received (for non-NDEF reads)
    424         ALOGD("%s: NFA_DATA_EVT: status = 0x%X, len = %d", __FUNCTION__, eventData->status, eventData->data.len);
    425         nativeNfcTag_doTransceiveStatus(eventData->status, eventData->data.p_data, eventData->data.len);
    426         break;
    427     case NFA_RW_INTF_ERROR_EVT:
    428         ALOGD("%s: NFC_RW_INTF_ERROR_EVT", __FUNCTION__);
    429         nativeNfcTag_notifyRfTimeout();
    430         nativeNfcTag_doReadCompleted (NFA_STATUS_TIMEOUT);
    431         break;
    432     case NFA_SELECT_CPLT_EVT: // Select completed
    433         status = eventData->status;
    434         ALOGD("%s: NFA_SELECT_CPLT_EVT: status = %d", __FUNCTION__, status);
    435         if (status != NFA_STATUS_OK)
    436         {
    437             ALOGE("%s: NFA_SELECT_CPLT_EVT error: status = %d", __FUNCTION__, status);
    438         }
    439         break;
    440 
    441     case NFA_READ_CPLT_EVT: // NDEF-read or tag-specific-read completed
    442         ALOGD("%s: NFA_READ_CPLT_EVT: status = 0x%X", __FUNCTION__, eventData->status);
    443         nativeNfcTag_doReadCompleted (eventData->status);
    444         NfcTag::getInstance().connectionEventHandler (connEvent, eventData);
    445         break;
    446 
    447     case NFA_WRITE_CPLT_EVT: // Write completed
    448         ALOGD("%s: NFA_WRITE_CPLT_EVT: status = %d", __FUNCTION__, eventData->status);
    449         nativeNfcTag_doWriteStatus (eventData->status == NFA_STATUS_OK);
    450         break;
    451 
    452     case NFA_SET_TAG_RO_EVT: // Tag set as Read only
    453         ALOGD("%s: NFA_SET_TAG_RO_EVT: status = %d", __FUNCTION__, eventData->status);
    454         nativeNfcTag_doMakeReadonlyResult(eventData->status);
    455         break;
    456 
    457     case NFA_CE_NDEF_WRITE_START_EVT: // NDEF write started
    458         ALOGD("%s: NFA_CE_NDEF_WRITE_START_EVT: status: %d", __FUNCTION__, eventData->status);
    459 
    460         if (eventData->status != NFA_STATUS_OK)
    461             ALOGE("%s: NFA_CE_NDEF_WRITE_START_EVT error: status = %d", __FUNCTION__, eventData->status);
    462         break;
    463 
    464     case NFA_CE_NDEF_WRITE_CPLT_EVT: // NDEF write completed
    465         ALOGD("%s: FA_CE_NDEF_WRITE_CPLT_EVT: len = %lu", __FUNCTION__, eventData->ndef_write_cplt.len);
    466         break;
    467 
    468     case NFA_LLCP_ACTIVATED_EVT: // LLCP link is activated
    469         ALOGD("%s: NFA_LLCP_ACTIVATED_EVT: is_initiator: %d  remote_wks: %d, remote_lsc: %d, remote_link_miu: %d, local_link_miu: %d",
    470              __FUNCTION__,
    471              eventData->llcp_activated.is_initiator,
    472              eventData->llcp_activated.remote_wks,
    473              eventData->llcp_activated.remote_lsc,
    474              eventData->llcp_activated.remote_link_miu,
    475              eventData->llcp_activated.local_link_miu);
    476 
    477         PeerToPeer::getInstance().llcpActivatedHandler (getNative(0, 0), eventData->llcp_activated);
    478         break;
    479 
    480     case NFA_LLCP_DEACTIVATED_EVT: // LLCP link is deactivated
    481         ALOGD("%s: NFA_LLCP_DEACTIVATED_EVT", __FUNCTION__);
    482         PeerToPeer::getInstance().llcpDeactivatedHandler (getNative(0, 0), eventData->llcp_deactivated);
    483         break;
    484     case NFA_LLCP_FIRST_PACKET_RECEIVED_EVT: // Received first packet over llcp
    485         ALOGD("%s: NFA_LLCP_FIRST_PACKET_RECEIVED_EVT", __FUNCTION__);
    486         PeerToPeer::getInstance().llcpFirstPacketHandler (getNative(0, 0));
    487         break;
    488     case NFA_PRESENCE_CHECK_EVT:
    489         ALOGD("%s: NFA_PRESENCE_CHECK_EVT", __FUNCTION__);
    490         nativeNfcTag_doPresenceCheckResult (eventData->status);
    491         break;
    492     case NFA_FORMAT_CPLT_EVT:
    493         ALOGD("%s: NFA_FORMAT_CPLT_EVT: status=0x%X", __FUNCTION__, eventData->status);
    494         nativeNfcTag_formatStatus (eventData->status == NFA_STATUS_OK);
    495         break;
    496 
    497     case NFA_I93_CMD_CPLT_EVT:
    498         ALOGD("%s: NFA_I93_CMD_CPLT_EVT: status=0x%X", __FUNCTION__, eventData->status);
    499         break;
    500 
    501     case NFA_CE_UICC_LISTEN_CONFIGURED_EVT :
    502         ALOGD("%s: NFA_CE_UICC_LISTEN_CONFIGURED_EVT : status=0x%X", __FUNCTION__, eventData->status);
    503         break;
    504 
    505     case NFA_SET_P2P_LISTEN_TECH_EVT:
    506         ALOGD("%s: NFA_SET_P2P_LISTEN_TECH_EVT", __FUNCTION__);
    507         PeerToPeer::getInstance().connectionEventHandler (connEvent, eventData);
    508         break;
    509 
    510     default:
    511         ALOGE("%s: unknown event ????", __FUNCTION__);
    512         break;
    513     }
    514 }
    515 
    516 
    517 /*******************************************************************************
    518 **
    519 ** Function:        nfcManager_initNativeStruc
    520 **
    521 ** Description:     Initialize variables.
    522 **                  e: JVM environment.
    523 **                  o: Java object.
    524 **
    525 ** Returns:         True if ok.
    526 **
    527 *******************************************************************************/
    528 static jboolean nfcManager_initNativeStruc (JNIEnv* e, jobject o)
    529 {
    530     ALOGD ("%s: enter", __FUNCTION__);
    531 
    532     nfc_jni_native_data* nat = (nfc_jni_native_data*)malloc(sizeof(struct nfc_jni_native_data));
    533     if (nat == NULL)
    534     {
    535         ALOGE ("%s: fail allocate native data", __FUNCTION__);
    536         return JNI_FALSE;
    537     }
    538 
    539     memset (nat, 0, sizeof(*nat));
    540     e->GetJavaVM(&(nat->vm));
    541     nat->env_version = e->GetVersion();
    542     nat->manager = e->NewGlobalRef(o);
    543 
    544     ScopedLocalRef<jclass> cls(e, e->GetObjectClass(o));
    545     jfieldID f = e->GetFieldID(cls.get(), "mNative", "J");
    546     e->SetLongField(o, f, (jlong)nat);
    547 
    548     /* Initialize native cached references */
    549     gCachedNfcManagerNotifyNdefMessageListeners = e->GetMethodID(cls.get(),
    550             "notifyNdefMessageListeners", "(Lcom/android/nfc/dhimpl/NativeNfcTag;)V");
    551     gCachedNfcManagerNotifyLlcpLinkActivation = e->GetMethodID(cls.get(),
    552             "notifyLlcpLinkActivation", "(Lcom/android/nfc/dhimpl/NativeP2pDevice;)V");
    553     gCachedNfcManagerNotifyLlcpLinkDeactivated = e->GetMethodID(cls.get(),
    554             "notifyLlcpLinkDeactivated", "(Lcom/android/nfc/dhimpl/NativeP2pDevice;)V");
    555     gCachedNfcManagerNotifyLlcpFirstPacketReceived = e->GetMethodID(cls.get(),
    556             "notifyLlcpLinkFirstPacketReceived", "(Lcom/android/nfc/dhimpl/NativeP2pDevice;)V");
    557 
    558     gCachedNfcManagerNotifyHostEmuActivated = e->GetMethodID(cls.get(),
    559             "notifyHostEmuActivated", "()V");
    560 
    561     gCachedNfcManagerNotifyHostEmuData = e->GetMethodID(cls.get(),
    562             "notifyHostEmuData", "([B)V");
    563 
    564     gCachedNfcManagerNotifyHostEmuDeactivated = e->GetMethodID(cls.get(),
    565             "notifyHostEmuDeactivated", "()V");
    566 
    567     gCachedNfcManagerNotifyRfFieldActivated = e->GetMethodID(cls.get(),
    568             "notifyRfFieldActivated", "()V");
    569     gCachedNfcManagerNotifyRfFieldDeactivated = e->GetMethodID(cls.get(),
    570             "notifyRfFieldDeactivated", "()V");
    571 
    572     if (nfc_jni_cache_object(e, gNativeNfcTagClassName, &(nat->cached_NfcTag)) == -1)
    573     {
    574         ALOGE ("%s: fail cache NativeNfcTag", __FUNCTION__);
    575         return JNI_FALSE;
    576     }
    577 
    578     if (nfc_jni_cache_object(e, gNativeP2pDeviceClassName, &(nat->cached_P2pDevice)) == -1)
    579     {
    580         ALOGE ("%s: fail cache NativeP2pDevice", __FUNCTION__);
    581         return JNI_FALSE;
    582     }
    583 
    584     ALOGD ("%s: exit", __FUNCTION__);
    585     return JNI_TRUE;
    586 }
    587 
    588 
    589 /*******************************************************************************
    590 **
    591 ** Function:        nfaDeviceManagementCallback
    592 **
    593 ** Description:     Receive device management events from stack.
    594 **                  dmEvent: Device-management event ID.
    595 **                  eventData: Data associated with event ID.
    596 **
    597 ** Returns:         None
    598 **
    599 *******************************************************************************/
    600 void nfaDeviceManagementCallback (UINT8 dmEvent, tNFA_DM_CBACK_DATA* eventData)
    601 {
    602     ALOGD ("%s: enter; event=0x%X", __FUNCTION__, dmEvent);
    603 
    604     switch (dmEvent)
    605     {
    606     case NFA_DM_ENABLE_EVT: /* Result of NFA_Enable */
    607         {
    608             SyncEventGuard guard (sNfaEnableEvent);
    609             ALOGD ("%s: NFA_DM_ENABLE_EVT; status=0x%X",
    610                     __FUNCTION__, eventData->status);
    611             sIsNfaEnabled = eventData->status == NFA_STATUS_OK;
    612             sIsDisabling = false;
    613             sNfaEnableEvent.notifyOne ();
    614         }
    615         break;
    616 
    617     case NFA_DM_DISABLE_EVT: /* Result of NFA_Disable */
    618         {
    619             SyncEventGuard guard (sNfaDisableEvent);
    620             ALOGD ("%s: NFA_DM_DISABLE_EVT", __FUNCTION__);
    621             sIsNfaEnabled = false;
    622             sIsDisabling = false;
    623             sNfaDisableEvent.notifyOne ();
    624         }
    625         break;
    626 
    627     case NFA_DM_SET_CONFIG_EVT: //result of NFA_SetConfig
    628         ALOGD ("%s: NFA_DM_SET_CONFIG_EVT", __FUNCTION__);
    629         {
    630             SyncEventGuard guard (sNfaSetConfigEvent);
    631             sNfaSetConfigEvent.notifyOne();
    632         }
    633         break;
    634 
    635     case NFA_DM_GET_CONFIG_EVT: /* Result of NFA_GetConfig */
    636         ALOGD ("%s: NFA_DM_GET_CONFIG_EVT", __FUNCTION__);
    637         {
    638             SyncEventGuard guard (sNfaGetConfigEvent);
    639             if (eventData->status == NFA_STATUS_OK &&
    640                     eventData->get_config.tlv_size <= sizeof(sConfig))
    641             {
    642                 sCurrentConfigLen = eventData->get_config.tlv_size;
    643                 memcpy(sConfig, eventData->get_config.param_tlvs, eventData->get_config.tlv_size);
    644             }
    645             else
    646             {
    647                 ALOGE("%s: NFA_DM_GET_CONFIG failed", __FUNCTION__);
    648                 sCurrentConfigLen = 0;
    649             }
    650             sNfaGetConfigEvent.notifyOne();
    651         }
    652         break;
    653 
    654     case NFA_DM_RF_FIELD_EVT:
    655         ALOGD ("%s: NFA_DM_RF_FIELD_EVT; status=0x%X; field status=%u", __FUNCTION__,
    656               eventData->rf_field.status, eventData->rf_field.rf_field_status);
    657         if (!sP2pActive && eventData->rf_field.status == NFA_STATUS_OK)
    658         {
    659             struct nfc_jni_native_data *nat = getNative(NULL, NULL);
    660             JNIEnv* e = NULL;
    661             ScopedAttach attach(nat->vm, &e);
    662             if (e == NULL)
    663             {
    664                 ALOGE ("jni env is null");
    665                 return;
    666             }
    667             if (eventData->rf_field.rf_field_status == NFA_DM_RF_FIELD_ON)
    668                 e->CallVoidMethod (nat->manager, android::gCachedNfcManagerNotifyRfFieldActivated);
    669             else
    670                 e->CallVoidMethod (nat->manager, android::gCachedNfcManagerNotifyRfFieldDeactivated);
    671         }
    672         break;
    673 
    674     case NFA_DM_NFCC_TRANSPORT_ERR_EVT:
    675     case NFA_DM_NFCC_TIMEOUT_EVT:
    676         {
    677             if (dmEvent == NFA_DM_NFCC_TIMEOUT_EVT)
    678                 ALOGE ("%s: NFA_DM_NFCC_TIMEOUT_EVT; abort", __FUNCTION__);
    679             else if (dmEvent == NFA_DM_NFCC_TRANSPORT_ERR_EVT)
    680                 ALOGE ("%s: NFA_DM_NFCC_TRANSPORT_ERR_EVT; abort", __FUNCTION__);
    681 
    682             nativeNfcTag_abortWaits();
    683             NfcTag::getInstance().abort ();
    684             sAbortConnlessWait = true;
    685             nativeLlcpConnectionlessSocket_abortWait();
    686             {
    687                 ALOGD ("%s: aborting  sNfaEnableDisablePollingEvent", __FUNCTION__);
    688                 SyncEventGuard guard (sNfaEnableDisablePollingEvent);
    689                 sNfaEnableDisablePollingEvent.notifyOne();
    690             }
    691             {
    692                 ALOGD ("%s: aborting  sNfaEnableEvent", __FUNCTION__);
    693                 SyncEventGuard guard (sNfaEnableEvent);
    694                 sNfaEnableEvent.notifyOne();
    695             }
    696             {
    697                 ALOGD ("%s: aborting  sNfaDisableEvent", __FUNCTION__);
    698                 SyncEventGuard guard (sNfaDisableEvent);
    699                 sNfaDisableEvent.notifyOne();
    700             }
    701             sDiscoveryEnabled = false;
    702             sPollingEnabled = false;
    703             PowerSwitch::getInstance ().abort ();
    704 
    705             if (!sIsDisabling && sIsNfaEnabled)
    706             {
    707                 NFA_Disable(FALSE);
    708                 sIsDisabling = true;
    709             }
    710             else
    711             {
    712                 sIsNfaEnabled = false;
    713                 sIsDisabling = false;
    714             }
    715             PowerSwitch::getInstance ().initialize (PowerSwitch::UNKNOWN_LEVEL);
    716             ALOGE ("%s: crash NFC service", __FUNCTION__);
    717             //////////////////////////////////////////////
    718             //crash the NFC service process so it can restart automatically
    719             abort ();
    720             //////////////////////////////////////////////
    721         }
    722         break;
    723 
    724     case NFA_DM_PWR_MODE_CHANGE_EVT:
    725         PowerSwitch::getInstance ().deviceManagementCallback (dmEvent, eventData);
    726         break;
    727 
    728     default:
    729         ALOGD ("%s: unhandled event", __FUNCTION__);
    730         break;
    731     }
    732 }
    733 
    734 /*******************************************************************************
    735 **
    736 ** Function:        nfcManager_sendRawFrame
    737 **
    738 ** Description:     Send a raw frame.
    739 **                  e: JVM environment.
    740 **                  o: Java object.
    741 **
    742 ** Returns:         True if ok.
    743 **
    744 *******************************************************************************/
    745 static jboolean nfcManager_sendRawFrame (JNIEnv* e, jobject, jbyteArray data)
    746 {
    747     ScopedByteArrayRO bytes(e, data);
    748     uint8_t* buf = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(&bytes[0]));
    749     size_t bufLen = bytes.size();
    750     tNFA_STATUS status = NFA_SendRawFrame (buf, bufLen, 0);
    751 
    752     return (status == NFA_STATUS_OK);
    753 }
    754 
    755 /*******************************************************************************
    756 **
    757 ** Function:        nfcManager_routeAid
    758 **
    759 ** Description:     Route an AID to an EE
    760 **                  e: JVM environment.
    761 **                  o: Java object.
    762 **
    763 ** Returns:         True if ok.
    764 **
    765 *******************************************************************************/
    766 static jboolean nfcManager_routeAid (JNIEnv* e, jobject, jbyteArray aid, jint route)
    767 {
    768     ScopedByteArrayRO bytes(e, aid);
    769     uint8_t* buf = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(&bytes[0]));
    770     size_t bufLen = bytes.size();
    771     bool result = RoutingManager::getInstance().addAidRouting(buf, bufLen, route);
    772     return result;
    773 }
    774 
    775 /*******************************************************************************
    776 **
    777 ** Function:        nfcManager_unrouteAid
    778 **
    779 ** Description:     Remove a AID routing
    780 **                  e: JVM environment.
    781 **                  o: Java object.
    782 **
    783 ** Returns:         True if ok.
    784 **
    785 *******************************************************************************/
    786 static jboolean nfcManager_unrouteAid (JNIEnv* e, jobject, jbyteArray aid)
    787 {
    788     ScopedByteArrayRO bytes(e, aid);
    789     uint8_t* buf = const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(&bytes[0]));
    790     size_t bufLen = bytes.size();
    791     bool result = RoutingManager::getInstance().removeAidRouting(buf, bufLen);
    792     return result;
    793 }
    794 
    795 /*******************************************************************************
    796 **
    797 ** Function:        nfcManager_commitRouting
    798 **
    799 ** Description:     Sends the AID routing table to the controller
    800 **                  e: JVM environment.
    801 **                  o: Java object.
    802 **
    803 ** Returns:         True if ok.
    804 **
    805 *******************************************************************************/
    806 static jboolean nfcManager_commitRouting (JNIEnv* e, jobject)
    807 {
    808     return RoutingManager::getInstance().commitRouting();
    809 }
    810 
    811 /*******************************************************************************
    812 **
    813 ** Function:        nfcManager_doInitialize
    814 **
    815 ** Description:     Turn on NFC.
    816 **                  e: JVM environment.
    817 **                  o: Java object.
    818 **
    819 ** Returns:         True if ok.
    820 **
    821 *******************************************************************************/
    822 static jboolean nfcManager_doInitialize (JNIEnv* e, jobject o)
    823 {
    824     ALOGD ("%s: enter; ver=%s nfa=%s NCI_VERSION=0x%02X",
    825         __FUNCTION__, nfca_version_string, nfa_version_string, NCI_VERSION);
    826     tNFA_STATUS stat = NFA_STATUS_OK;
    827 
    828     PowerSwitch & powerSwitch = PowerSwitch::getInstance ();
    829 
    830     if (sIsNfaEnabled)
    831     {
    832         ALOGD ("%s: already enabled", __FUNCTION__);
    833         goto TheEnd;
    834     }
    835 
    836     powerSwitch.initialize (PowerSwitch::FULL_POWER);
    837 
    838     {
    839         unsigned long num = 0;
    840 
    841         NfcAdaptation& theInstance = NfcAdaptation::GetInstance();
    842         theInstance.Initialize(); //start GKI, NCI task, NFC task
    843 
    844         {
    845             SyncEventGuard guard (sNfaEnableEvent);
    846             tHAL_NFC_ENTRY* halFuncEntries = theInstance.GetHalEntryFuncs ();
    847 
    848             NFA_Init (halFuncEntries);
    849 
    850             stat = NFA_Enable (nfaDeviceManagementCallback, nfaConnectionCallback);
    851             if (stat == NFA_STATUS_OK)
    852             {
    853                 num = initializeGlobalAppLogLevel ();
    854                 CE_SetTraceLevel (num);
    855                 LLCP_SetTraceLevel (num);
    856                 NFC_SetTraceLevel (num);
    857                 RW_SetTraceLevel (num);
    858                 NFA_SetTraceLevel (num);
    859                 NFA_P2pSetTraceLevel (num);
    860                 sNfaEnableEvent.wait(); //wait for NFA command to finish
    861             }
    862         }
    863 
    864         if (stat == NFA_STATUS_OK)
    865         {
    866             //sIsNfaEnabled indicates whether stack started successfully
    867             if (sIsNfaEnabled)
    868             {
    869                 RoutingManager::getInstance().initialize(getNative(e, o));
    870                 nativeNfcTag_registerNdefTypeHandler ();
    871                 NfcTag::getInstance().initialize (getNative(e, o));
    872                 PeerToPeer::getInstance().initialize ();
    873                 PeerToPeer::getInstance().handleNfcOnOff (true);
    874 
    875                 /////////////////////////////////////////////////////////////////////////////////
    876                 // Add extra configuration here (work-arounds, etc.)
    877 
    878                 struct nfc_jni_native_data *nat = getNative(e, o);
    879 
    880                 if ( nat )
    881                 {
    882                     if (GetNumValue(NAME_POLLING_TECH_MASK, &num, sizeof(num)))
    883                         nat->tech_mask = num;
    884                     else
    885                         nat->tech_mask = DEFAULT_TECH_MASK;
    886                     ALOGD ("%s: tag polling tech mask=0x%X", __FUNCTION__, nat->tech_mask);
    887                 }
    888 
    889                 // if this value exists, set polling interval.
    890                 if (GetNumValue(NAME_NFA_DM_DISC_DURATION_POLL, &num, sizeof(num)))
    891                     nat->discovery_duration = num;
    892                 else
    893                     nat->discovery_duration = DEFAULT_DISCOVERY_DURATION;
    894 
    895                 NFA_SetRfDiscoveryDuration(nat->discovery_duration);
    896 
    897                 // Do custom NFCA startup configuration.
    898                 doStartupConfig();
    899                 goto TheEnd;
    900             }
    901         }
    902 
    903         ALOGE ("%s: fail nfa enable; error=0x%X", __FUNCTION__, stat);
    904 
    905         if (sIsNfaEnabled)
    906             stat = NFA_Disable (FALSE /* ungraceful */);
    907 
    908         theInstance.Finalize();
    909     }
    910 
    911 TheEnd:
    912     if (sIsNfaEnabled)
    913         PowerSwitch::getInstance ().setLevel (PowerSwitch::LOW_POWER);
    914     ALOGD ("%s: exit", __FUNCTION__);
    915     return sIsNfaEnabled ? JNI_TRUE : JNI_FALSE;
    916 }
    917 
    918 
    919 /*******************************************************************************
    920 **
    921 ** Function:        nfcManager_enableDiscovery
    922 **
    923 ** Description:     Start polling and listening for devices.
    924 **                  e: JVM environment.
    925 **                  o: Java object.
    926 **                  technologies_mask: the bitmask of technologies for which to enable discovery
    927 **                  enable_lptd: whether to enable low power polling (default: false)
    928 **
    929 ** Returns:         None
    930 **
    931 *******************************************************************************/
    932 static void nfcManager_enableDiscovery (JNIEnv* e, jobject o, jint technologies_mask, \
    933     jboolean enable_lptd, jboolean reader_mode, jboolean enable_host_routing,
    934     jboolean restart)
    935 {
    936     tNFA_TECHNOLOGY_MASK tech_mask = DEFAULT_TECH_MASK;
    937     struct nfc_jni_native_data *nat = getNative(e, o);
    938 
    939     if (technologies_mask == -1 && nat)
    940         tech_mask = (tNFA_TECHNOLOGY_MASK)nat->tech_mask;
    941     else if (technologies_mask != -1)
    942         tech_mask = (tNFA_TECHNOLOGY_MASK) technologies_mask;
    943     ALOGD ("%s: enter; tech_mask = %02x", __FUNCTION__, tech_mask);
    944 
    945     if (sDiscoveryEnabled && !restart)
    946     {
    947         ALOGE ("%s: already discovering", __FUNCTION__);
    948         return;
    949     }
    950 
    951     tNFA_STATUS stat = NFA_STATUS_OK;
    952 
    953     PowerSwitch::getInstance ().setLevel (PowerSwitch::FULL_POWER);
    954 
    955     if (sRfEnabled) {
    956         // Stop RF discovery to reconfigure
    957         startRfDiscovery(false);
    958     }
    959 
    960     // Check polling configuration
    961     if (tech_mask != 0)
    962     {
    963         stopPolling_rfDiscoveryDisabled();
    964         enableDisableLptd(enable_lptd);
    965         startPolling_rfDiscoveryDisabled(tech_mask);
    966 
    967         // Start P2P listening if tag polling was enabled
    968         if (sPollingEnabled)
    969         {
    970             ALOGD ("%s: Enable p2pListening", __FUNCTION__);
    971             PeerToPeer::getInstance().enableP2pListening (!reader_mode);
    972 
    973             if (reader_mode && !sReaderModeEnabled)
    974             {
    975                 sReaderModeEnabled = true;
    976                 NFA_PauseP2p();
    977                 NFA_DisableListening();
    978                 NFA_SetRfDiscoveryDuration(READER_MODE_DISCOVERY_DURATION);
    979             }
    980             else if (sReaderModeEnabled)
    981             {
    982                 struct nfc_jni_native_data *nat = getNative(e, o);
    983                 sReaderModeEnabled = false;
    984                 NFA_ResumeP2p();
    985                 NFA_EnableListening();
    986                 NFA_SetRfDiscoveryDuration(nat->discovery_duration);
    987             }
    988         }
    989     }
    990     else
    991     {
    992         // No technologies configured, stop polling
    993         stopPolling_rfDiscoveryDisabled();
    994     }
    995 
    996     // Check listen configuration
    997     if (enable_host_routing)
    998     {
    999         RoutingManager::getInstance().enableRoutingToHost();
   1000         RoutingManager::getInstance().commitRouting();
   1001     }
   1002     else
   1003     {
   1004         RoutingManager::getInstance().disableRoutingToHost();
   1005         RoutingManager::getInstance().commitRouting();
   1006     }
   1007     // Actually start discovery.
   1008     startRfDiscovery (true);
   1009     sDiscoveryEnabled = true;
   1010 
   1011     PowerSwitch::getInstance ().setModeOn (PowerSwitch::DISCOVERY);
   1012 
   1013     ALOGD ("%s: exit", __FUNCTION__);
   1014 }
   1015 
   1016 
   1017 /*******************************************************************************
   1018 **
   1019 ** Function:        nfcManager_disableDiscovery
   1020 **
   1021 ** Description:     Stop polling and listening for devices.
   1022 **                  e: JVM environment.
   1023 **                  o: Java object.
   1024 **
   1025 ** Returns:         None
   1026 **
   1027 *******************************************************************************/
   1028 void nfcManager_disableDiscovery (JNIEnv* e, jobject o)
   1029 {
   1030     tNFA_STATUS status = NFA_STATUS_OK;
   1031     ALOGD ("%s: enter;", __FUNCTION__);
   1032 
   1033     pn544InteropAbortNow ();
   1034     if (sDiscoveryEnabled == false)
   1035     {
   1036         ALOGD ("%s: already disabled", __FUNCTION__);
   1037         goto TheEnd;
   1038     }
   1039 
   1040     // Stop RF Discovery.
   1041     startRfDiscovery (false);
   1042 
   1043     if (sPollingEnabled)
   1044         status = stopPolling_rfDiscoveryDisabled();
   1045 
   1046     PeerToPeer::getInstance().enableP2pListening (false);
   1047 
   1048     sDiscoveryEnabled = false;
   1049     //if nothing is active after this, then tell the controller to power down
   1050     if (! PowerSwitch::getInstance ().setModeOff (PowerSwitch::DISCOVERY))
   1051         PowerSwitch::getInstance ().setLevel (PowerSwitch::LOW_POWER);
   1052 TheEnd:
   1053     ALOGD ("%s: exit", __FUNCTION__);
   1054 }
   1055 
   1056 void enableDisableLptd (bool enable)
   1057 {
   1058     // This method is *NOT* thread-safe. Right now
   1059     // it is only called from the same thread so it's
   1060     // not an issue.
   1061     static bool sCheckedLptd = false;
   1062     static bool sHasLptd = false;
   1063 
   1064     tNFA_STATUS stat = NFA_STATUS_OK;
   1065     if (!sCheckedLptd)
   1066     {
   1067         sCheckedLptd = true;
   1068         SyncEventGuard guard (sNfaGetConfigEvent);
   1069         tNFA_PMID configParam[1] = {NCI_PARAM_ID_TAGSNIFF_CFG};
   1070         stat = NFA_GetConfig(1, configParam);
   1071         if (stat != NFA_STATUS_OK)
   1072         {
   1073             ALOGE("%s: NFA_GetConfig failed", __FUNCTION__);
   1074             return;
   1075         }
   1076         sNfaGetConfigEvent.wait ();
   1077         if (sCurrentConfigLen < 4 || sConfig[1] != NCI_PARAM_ID_TAGSNIFF_CFG) {
   1078             ALOGE("%s: Config TLV length %d returned is too short", __FUNCTION__,
   1079                     sCurrentConfigLen);
   1080             return;
   1081         }
   1082         if (sConfig[3] == 0) {
   1083             ALOGE("%s: LPTD is disabled, not enabling in current config", __FUNCTION__);
   1084             return;
   1085         }
   1086         sHasLptd = true;
   1087     }
   1088     // Bail if we checked and didn't find any LPTD config before
   1089     if (!sHasLptd) return;
   1090     UINT8 enable_byte = enable ? 0x01 : 0x00;
   1091 
   1092     SyncEventGuard guard(sNfaSetConfigEvent);
   1093 
   1094     stat = NFA_SetConfig(NCI_PARAM_ID_TAGSNIFF_CFG, 1, &enable_byte);
   1095     if (stat == NFA_STATUS_OK)
   1096         sNfaSetConfigEvent.wait ();
   1097     else
   1098         ALOGE("%s: Could not configure LPTD feature", __FUNCTION__);
   1099     return;
   1100 }
   1101 
   1102 
   1103 /*******************************************************************************
   1104 **
   1105 ** Function:        nfcManager_doCreateLlcpServiceSocket
   1106 **
   1107 ** Description:     Create a new LLCP server socket.
   1108 **                  e: JVM environment.
   1109 **                  o: Java object.
   1110 **                  nSap: Service access point.
   1111 **                  sn: Service name
   1112 **                  miu: Maximum information unit.
   1113 **                  rw: Receive window size.
   1114 **                  linearBufferLength: Max buffer size.
   1115 **
   1116 ** Returns:         NativeLlcpServiceSocket Java object.
   1117 **
   1118 *******************************************************************************/
   1119 static jobject nfcManager_doCreateLlcpServiceSocket (JNIEnv* e, jobject, jint nSap, jstring sn, jint miu, jint rw, jint linearBufferLength)
   1120 {
   1121     PeerToPeer::tJNI_HANDLE jniHandle = PeerToPeer::getInstance().getNewJniHandle ();
   1122 
   1123     ScopedUtfChars serviceName(e, sn);
   1124 
   1125     ALOGD ("%s: enter: sap=%i; name=%s; miu=%i; rw=%i; buffLen=%i", __FUNCTION__, nSap, serviceName.c_str(), miu, rw, linearBufferLength);
   1126 
   1127     /* Create new NativeLlcpServiceSocket object */
   1128     jobject serviceSocket = NULL;
   1129     if (nfc_jni_cache_object_local(e, gNativeLlcpServiceSocketClassName, &(serviceSocket)) == -1)
   1130     {
   1131         ALOGE ("%s: Llcp socket object creation error", __FUNCTION__);
   1132         return NULL;
   1133     }
   1134 
   1135     /* Get NativeLlcpServiceSocket class object */
   1136     ScopedLocalRef<jclass> clsNativeLlcpServiceSocket(e, e->GetObjectClass(serviceSocket));
   1137     if (e->ExceptionCheck())
   1138     {
   1139         e->ExceptionClear();
   1140         ALOGE("%s: Llcp Socket get object class error", __FUNCTION__);
   1141         return NULL;
   1142     }
   1143 
   1144     if (!PeerToPeer::getInstance().registerServer (jniHandle, serviceName.c_str()))
   1145     {
   1146         ALOGE("%s: RegisterServer error", __FUNCTION__);
   1147         return NULL;
   1148     }
   1149 
   1150     jfieldID f;
   1151 
   1152     /* Set socket handle to be the same as the NfaHandle*/
   1153     f = e->GetFieldID(clsNativeLlcpServiceSocket.get(), "mHandle", "I");
   1154     e->SetIntField(serviceSocket, f, (jint) jniHandle);
   1155     ALOGD ("%s: socket Handle = 0x%X", __FUNCTION__, jniHandle);
   1156 
   1157     /* Set socket linear buffer length */
   1158     f = e->GetFieldID(clsNativeLlcpServiceSocket.get(), "mLocalLinearBufferLength", "I");
   1159     e->SetIntField(serviceSocket, f,(jint)linearBufferLength);
   1160     ALOGD ("%s: buffer length = %d", __FUNCTION__, linearBufferLength);
   1161 
   1162     /* Set socket MIU */
   1163     f = e->GetFieldID(clsNativeLlcpServiceSocket.get(), "mLocalMiu", "I");
   1164     e->SetIntField(serviceSocket, f,(jint)miu);
   1165     ALOGD ("%s: MIU = %d", __FUNCTION__, miu);
   1166 
   1167     /* Set socket RW */
   1168     f = e->GetFieldID(clsNativeLlcpServiceSocket.get(), "mLocalRw", "I");
   1169     e->SetIntField(serviceSocket, f,(jint)rw);
   1170     ALOGD ("%s:  RW = %d", __FUNCTION__, rw);
   1171 
   1172     sLastError = 0;
   1173     ALOGD ("%s: exit", __FUNCTION__);
   1174     return serviceSocket;
   1175 }
   1176 
   1177 
   1178 /*******************************************************************************
   1179 **
   1180 ** Function:        nfcManager_doGetLastError
   1181 **
   1182 ** Description:     Get the last error code.
   1183 **                  e: JVM environment.
   1184 **                  o: Java object.
   1185 **
   1186 ** Returns:         Last error code.
   1187 **
   1188 *******************************************************************************/
   1189 static jint nfcManager_doGetLastError(JNIEnv*, jobject)
   1190 {
   1191     ALOGD ("%s: last error=%i", __FUNCTION__, sLastError);
   1192     return sLastError;
   1193 }
   1194 
   1195 
   1196 /*******************************************************************************
   1197 **
   1198 ** Function:        nfcManager_doDeinitialize
   1199 **
   1200 ** Description:     Turn off NFC.
   1201 **                  e: JVM environment.
   1202 **                  o: Java object.
   1203 **
   1204 ** Returns:         True if ok.
   1205 **
   1206 *******************************************************************************/
   1207 static jboolean nfcManager_doDeinitialize (JNIEnv*, jobject)
   1208 {
   1209     ALOGD ("%s: enter", __FUNCTION__);
   1210 
   1211     sIsDisabling = true;
   1212     pn544InteropAbortNow ();
   1213     RoutingManager::getInstance().onNfccShutdown();
   1214     PowerSwitch::getInstance ().initialize (PowerSwitch::UNKNOWN_LEVEL);
   1215 
   1216     if (sIsNfaEnabled)
   1217     {
   1218         SyncEventGuard guard (sNfaDisableEvent);
   1219         tNFA_STATUS stat = NFA_Disable (TRUE /* graceful */);
   1220         if (stat == NFA_STATUS_OK)
   1221         {
   1222             ALOGD ("%s: wait for completion", __FUNCTION__);
   1223             sNfaDisableEvent.wait (); //wait for NFA command to finish
   1224             PeerToPeer::getInstance ().handleNfcOnOff (false);
   1225         }
   1226         else
   1227         {
   1228             ALOGE ("%s: fail disable; error=0x%X", __FUNCTION__, stat);
   1229         }
   1230     }
   1231     nativeNfcTag_abortWaits();
   1232     NfcTag::getInstance().abort ();
   1233     sAbortConnlessWait = true;
   1234     nativeLlcpConnectionlessSocket_abortWait();
   1235     sIsNfaEnabled = false;
   1236     sDiscoveryEnabled = false;
   1237     sPollingEnabled = false;
   1238     sIsDisabling = false;
   1239     gActivated = false;
   1240 
   1241     {
   1242         //unblock NFA_EnablePolling() and NFA_DisablePolling()
   1243         SyncEventGuard guard (sNfaEnableDisablePollingEvent);
   1244         sNfaEnableDisablePollingEvent.notifyOne ();
   1245     }
   1246 
   1247     NfcAdaptation& theInstance = NfcAdaptation::GetInstance();
   1248     theInstance.Finalize();
   1249 
   1250     ALOGD ("%s: exit", __FUNCTION__);
   1251     return JNI_TRUE;
   1252 }
   1253 
   1254 
   1255 /*******************************************************************************
   1256 **
   1257 ** Function:        nfcManager_doCreateLlcpSocket
   1258 **
   1259 ** Description:     Create a LLCP connection-oriented socket.
   1260 **                  e: JVM environment.
   1261 **                  o: Java object.
   1262 **                  nSap: Service access point.
   1263 **                  miu: Maximum information unit.
   1264 **                  rw: Receive window size.
   1265 **                  linearBufferLength: Max buffer size.
   1266 **
   1267 ** Returns:         NativeLlcpSocket Java object.
   1268 **
   1269 *******************************************************************************/
   1270 static jobject nfcManager_doCreateLlcpSocket (JNIEnv* e, jobject, jint nSap, jint miu, jint rw, jint linearBufferLength)
   1271 {
   1272     ALOGD ("%s: enter; sap=%d; miu=%d; rw=%d; buffer len=%d", __FUNCTION__, nSap, miu, rw, linearBufferLength);
   1273 
   1274     PeerToPeer::tJNI_HANDLE jniHandle = PeerToPeer::getInstance().getNewJniHandle ();
   1275     PeerToPeer::getInstance().createClient (jniHandle, miu, rw);
   1276 
   1277     /* Create new NativeLlcpSocket object */
   1278     jobject clientSocket = NULL;
   1279     if (nfc_jni_cache_object_local(e, gNativeLlcpSocketClassName, &(clientSocket)) == -1)
   1280     {
   1281         ALOGE ("%s: fail Llcp socket creation", __FUNCTION__);
   1282         return clientSocket;
   1283     }
   1284 
   1285     /* Get NativeConnectionless class object */
   1286     ScopedLocalRef<jclass> clsNativeLlcpSocket(e, e->GetObjectClass(clientSocket));
   1287     if (e->ExceptionCheck())
   1288     {
   1289         e->ExceptionClear();
   1290         ALOGE ("%s: fail get class object", __FUNCTION__);
   1291         return clientSocket;
   1292     }
   1293 
   1294     jfieldID f;
   1295 
   1296     /* Set socket SAP */
   1297     f = e->GetFieldID (clsNativeLlcpSocket.get(), "mSap", "I");
   1298     e->SetIntField (clientSocket, f, (jint) nSap);
   1299 
   1300     /* Set socket handle */
   1301     f = e->GetFieldID (clsNativeLlcpSocket.get(), "mHandle", "I");
   1302     e->SetIntField (clientSocket, f, (jint) jniHandle);
   1303 
   1304     /* Set socket MIU */
   1305     f = e->GetFieldID (clsNativeLlcpSocket.get(), "mLocalMiu", "I");
   1306     e->SetIntField (clientSocket, f, (jint) miu);
   1307 
   1308     /* Set socket RW */
   1309     f = e->GetFieldID (clsNativeLlcpSocket.get(), "mLocalRw", "I");
   1310     e->SetIntField (clientSocket, f, (jint) rw);
   1311 
   1312     ALOGD ("%s: exit", __FUNCTION__);
   1313     return clientSocket;
   1314 }
   1315 
   1316 
   1317 /*******************************************************************************
   1318 **
   1319 ** Function:        nfcManager_doCreateLlcpConnectionlessSocket
   1320 **
   1321 ** Description:     Create a connection-less socket.
   1322 **                  e: JVM environment.
   1323 **                  o: Java object.
   1324 **                  nSap: Service access point.
   1325 **                  sn: Service name.
   1326 **
   1327 ** Returns:         NativeLlcpConnectionlessSocket Java object.
   1328 **
   1329 *******************************************************************************/
   1330 static jobject nfcManager_doCreateLlcpConnectionlessSocket (JNIEnv *, jobject, jint nSap, jstring /*sn*/)
   1331 {
   1332     ALOGD ("%s: nSap=0x%X", __FUNCTION__, nSap);
   1333     return NULL;
   1334 }
   1335 
   1336 /*******************************************************************************
   1337 **
   1338 ** Function:        isPeerToPeer
   1339 **
   1340 ** Description:     Whether the activation data indicates the peer supports NFC-DEP.
   1341 **                  activated: Activation data.
   1342 **
   1343 ** Returns:         True if the peer supports NFC-DEP.
   1344 **
   1345 *******************************************************************************/
   1346 static bool isPeerToPeer (tNFA_ACTIVATED& activated)
   1347 {
   1348     return activated.activate_ntf.protocol == NFA_PROTOCOL_NFC_DEP;
   1349 }
   1350 
   1351 /*******************************************************************************
   1352 **
   1353 ** Function:        isListenMode
   1354 **
   1355 ** Description:     Indicates whether the activation data indicates it is
   1356 **                  listen mode.
   1357 **
   1358 ** Returns:         True if this listen mode.
   1359 **
   1360 *******************************************************************************/
   1361 static bool isListenMode(tNFA_ACTIVATED& activated)
   1362 {
   1363     return ((NFC_DISCOVERY_TYPE_LISTEN_A == activated.activate_ntf.rf_tech_param.mode)
   1364             || (NFC_DISCOVERY_TYPE_LISTEN_B == activated.activate_ntf.rf_tech_param.mode)
   1365             || (NFC_DISCOVERY_TYPE_LISTEN_F == activated.activate_ntf.rf_tech_param.mode)
   1366             || (NFC_DISCOVERY_TYPE_LISTEN_A_ACTIVE == activated.activate_ntf.rf_tech_param.mode)
   1367             || (NFC_DISCOVERY_TYPE_LISTEN_F_ACTIVE == activated.activate_ntf.rf_tech_param.mode)
   1368             || (NFC_DISCOVERY_TYPE_LISTEN_ISO15693 == activated.activate_ntf.rf_tech_param.mode)
   1369             || (NFC_DISCOVERY_TYPE_LISTEN_B_PRIME == activated.activate_ntf.rf_tech_param.mode));
   1370 }
   1371 
   1372 /*******************************************************************************
   1373 **
   1374 ** Function:        nfcManager_doCheckLlcp
   1375 **
   1376 ** Description:     Not used.
   1377 **
   1378 ** Returns:         True
   1379 **
   1380 *******************************************************************************/
   1381 static jboolean nfcManager_doCheckLlcp(JNIEnv*, jobject)
   1382 {
   1383     ALOGD("%s", __FUNCTION__);
   1384     return JNI_TRUE;
   1385 }
   1386 
   1387 
   1388 /*******************************************************************************
   1389 **
   1390 ** Function:        nfcManager_doActivateLlcp
   1391 **
   1392 ** Description:     Not used.
   1393 **
   1394 ** Returns:         True
   1395 **
   1396 *******************************************************************************/
   1397 static jboolean nfcManager_doActivateLlcp(JNIEnv*, jobject)
   1398 {
   1399     ALOGD("%s", __FUNCTION__);
   1400     return JNI_TRUE;
   1401 }
   1402 
   1403 
   1404 /*******************************************************************************
   1405 **
   1406 ** Function:        nfcManager_doAbort
   1407 **
   1408 ** Description:     Not used.
   1409 **
   1410 ** Returns:         None
   1411 **
   1412 *******************************************************************************/
   1413 static void nfcManager_doAbort(JNIEnv*, jobject)
   1414 {
   1415     ALOGE("%s: abort()", __FUNCTION__);
   1416     abort();
   1417 }
   1418 
   1419 
   1420 /*******************************************************************************
   1421 **
   1422 ** Function:        nfcManager_doDownload
   1423 **
   1424 ** Description:     Download firmware patch files.  Do not turn on NFC.
   1425 **
   1426 ** Returns:         True if ok.
   1427 **
   1428 *******************************************************************************/
   1429 static jboolean nfcManager_doDownload(JNIEnv*, jobject)
   1430 {
   1431     ALOGD ("%s: enter", __FUNCTION__);
   1432     NfcAdaptation& theInstance = NfcAdaptation::GetInstance();
   1433 
   1434     theInstance.Initialize(); //start GKI, NCI task, NFC task
   1435     theInstance.DownloadFirmware ();
   1436     theInstance.Finalize();
   1437     ALOGD ("%s: exit", __FUNCTION__);
   1438     return JNI_TRUE;
   1439 }
   1440 
   1441 
   1442 /*******************************************************************************
   1443 **
   1444 ** Function:        nfcManager_doResetTimeouts
   1445 **
   1446 ** Description:     Not used.
   1447 **
   1448 ** Returns:         None
   1449 **
   1450 *******************************************************************************/
   1451 static void nfcManager_doResetTimeouts(JNIEnv*, jobject)
   1452 {
   1453     ALOGD ("%s", __FUNCTION__);
   1454     NfcTag::getInstance().resetAllTransceiveTimeouts ();
   1455 }
   1456 
   1457 
   1458 /*******************************************************************************
   1459 **
   1460 ** Function:        nfcManager_doSetTimeout
   1461 **
   1462 ** Description:     Set timeout value.
   1463 **                  e: JVM environment.
   1464 **                  o: Java object.
   1465 **                  tech: technology ID.
   1466 **                  timeout: Timeout value.
   1467 **
   1468 ** Returns:         True if ok.
   1469 **
   1470 *******************************************************************************/
   1471 static bool nfcManager_doSetTimeout(JNIEnv*, jobject, jint tech, jint timeout)
   1472 {
   1473     if (timeout <= 0)
   1474     {
   1475         ALOGE("%s: Timeout must be positive.",__FUNCTION__);
   1476         return false;
   1477     }
   1478     ALOGD ("%s: tech=%d, timeout=%d", __FUNCTION__, tech, timeout);
   1479     NfcTag::getInstance().setTransceiveTimeout (tech, timeout);
   1480     return true;
   1481 }
   1482 
   1483 
   1484 /*******************************************************************************
   1485 **
   1486 ** Function:        nfcManager_doGetTimeout
   1487 **
   1488 ** Description:     Get timeout value.
   1489 **                  e: JVM environment.
   1490 **                  o: Java object.
   1491 **                  tech: technology ID.
   1492 **
   1493 ** Returns:         Timeout value.
   1494 **
   1495 *******************************************************************************/
   1496 static jint nfcManager_doGetTimeout(JNIEnv*, jobject, jint tech)
   1497 {
   1498     int timeout = NfcTag::getInstance().getTransceiveTimeout (tech);
   1499     ALOGD ("%s: tech=%d, timeout=%d", __FUNCTION__, tech, timeout);
   1500     return timeout;
   1501 }
   1502 
   1503 
   1504 /*******************************************************************************
   1505 **
   1506 ** Function:        nfcManager_doDump
   1507 **
   1508 ** Description:     Not used.
   1509 **                  e: JVM environment.
   1510 **                  o: Java object.
   1511 **
   1512 ** Returns:         Text dump.
   1513 **
   1514 *******************************************************************************/
   1515 static jstring nfcManager_doDump(JNIEnv* e, jobject)
   1516 {
   1517     char buffer[100];
   1518     snprintf(buffer, sizeof(buffer), "libnfc llc error_count=%u", /*libnfc_llc_error_count*/ 0);
   1519     return e->NewStringUTF(buffer);
   1520 }
   1521 
   1522 
   1523 /*******************************************************************************
   1524 **
   1525 ** Function:        nfcManager_doSetP2pInitiatorModes
   1526 **
   1527 ** Description:     Set P2P initiator's activation modes.
   1528 **                  e: JVM environment.
   1529 **                  o: Java object.
   1530 **                  modes: Active and/or passive modes.  The values are specified
   1531 **                          in external/libnfc-nxp/inc/phNfcTypes.h.  See
   1532 **                          enum phNfc_eP2PMode_t.
   1533 **
   1534 ** Returns:         None.
   1535 **
   1536 *******************************************************************************/
   1537 static void nfcManager_doSetP2pInitiatorModes (JNIEnv *e, jobject o, jint modes)
   1538 {
   1539     ALOGD ("%s: modes=0x%X", __FUNCTION__, modes);
   1540     struct nfc_jni_native_data *nat = getNative(e, o);
   1541 
   1542     tNFA_TECHNOLOGY_MASK mask = 0;
   1543     if (modes & 0x01) mask |= NFA_TECHNOLOGY_MASK_A;
   1544     if (modes & 0x02) mask |= NFA_TECHNOLOGY_MASK_F;
   1545     if (modes & 0x04) mask |= NFA_TECHNOLOGY_MASK_F;
   1546     if (modes & 0x08) mask |= NFA_TECHNOLOGY_MASK_A_ACTIVE;
   1547     if (modes & 0x10) mask |= NFA_TECHNOLOGY_MASK_F_ACTIVE;
   1548     if (modes & 0x20) mask |= NFA_TECHNOLOGY_MASK_F_ACTIVE;
   1549     nat->tech_mask = mask;
   1550 }
   1551 
   1552 
   1553 /*******************************************************************************
   1554 **
   1555 ** Function:        nfcManager_doSetP2pTargetModes
   1556 **
   1557 ** Description:     Set P2P target's activation modes.
   1558 **                  e: JVM environment.
   1559 **                  o: Java object.
   1560 **                  modes: Active and/or passive modes.
   1561 **
   1562 ** Returns:         None.
   1563 **
   1564 *******************************************************************************/
   1565 static void nfcManager_doSetP2pTargetModes (JNIEnv*, jobject, jint modes)
   1566 {
   1567     ALOGD ("%s: modes=0x%X", __FUNCTION__, modes);
   1568     // Map in the right modes
   1569     tNFA_TECHNOLOGY_MASK mask = 0;
   1570     if (modes & 0x01) mask |= NFA_TECHNOLOGY_MASK_A;
   1571     if (modes & 0x02) mask |= NFA_TECHNOLOGY_MASK_F;
   1572     if (modes & 0x04) mask |= NFA_TECHNOLOGY_MASK_F;
   1573     if (modes & 0x08) mask |= NFA_TECHNOLOGY_MASK_A_ACTIVE | NFA_TECHNOLOGY_MASK_F_ACTIVE;
   1574 
   1575     PeerToPeer::getInstance().setP2pListenMask(mask);
   1576 }
   1577 
   1578 static void nfcManager_doEnableScreenOffSuspend(JNIEnv* e, jobject o)
   1579 {
   1580     PowerSwitch::getInstance().setScreenOffPowerState(PowerSwitch::POWER_STATE_FULL);
   1581 }
   1582 
   1583 static void nfcManager_doDisableScreenOffSuspend(JNIEnv* e, jobject o)
   1584 {
   1585     PowerSwitch::getInstance().setScreenOffPowerState(PowerSwitch::POWER_STATE_OFF);
   1586 }
   1587 
   1588 /*****************************************************************************
   1589 **
   1590 ** JNI functions for android-4.0.1_r1
   1591 **
   1592 *****************************************************************************/
   1593 static JNINativeMethod gMethods[] =
   1594 {
   1595     {"doDownload", "()Z",
   1596             (void *)nfcManager_doDownload},
   1597 
   1598     {"initializeNativeStructure", "()Z",
   1599             (void*) nfcManager_initNativeStruc},
   1600 
   1601     {"doInitialize", "()Z",
   1602             (void*) nfcManager_doInitialize},
   1603 
   1604     {"doDeinitialize", "()Z",
   1605             (void*) nfcManager_doDeinitialize},
   1606 
   1607     {"sendRawFrame", "([B)Z",
   1608             (void*) nfcManager_sendRawFrame},
   1609 
   1610     {"routeAid", "([BI)Z",
   1611             (void*) nfcManager_routeAid},
   1612 
   1613     {"unrouteAid", "([B)Z",
   1614             (void*) nfcManager_unrouteAid},
   1615 
   1616     {"commitRouting", "()Z",
   1617             (void*) nfcManager_commitRouting},
   1618 
   1619     {"doEnableDiscovery", "(IZZZZ)V",
   1620             (void*) nfcManager_enableDiscovery},
   1621 
   1622     {"doCheckLlcp", "()Z",
   1623             (void *)nfcManager_doCheckLlcp},
   1624 
   1625     {"doActivateLlcp", "()Z",
   1626             (void *)nfcManager_doActivateLlcp},
   1627 
   1628     {"doCreateLlcpConnectionlessSocket", "(ILjava/lang/String;)Lcom/android/nfc/dhimpl/NativeLlcpConnectionlessSocket;",
   1629             (void *)nfcManager_doCreateLlcpConnectionlessSocket},
   1630 
   1631     {"doCreateLlcpServiceSocket", "(ILjava/lang/String;III)Lcom/android/nfc/dhimpl/NativeLlcpServiceSocket;",
   1632             (void*) nfcManager_doCreateLlcpServiceSocket},
   1633 
   1634     {"doCreateLlcpSocket", "(IIII)Lcom/android/nfc/dhimpl/NativeLlcpSocket;",
   1635             (void*) nfcManager_doCreateLlcpSocket},
   1636 
   1637     {"doGetLastError", "()I",
   1638             (void*) nfcManager_doGetLastError},
   1639 
   1640     {"disableDiscovery", "()V",
   1641             (void*) nfcManager_disableDiscovery},
   1642 
   1643     {"doSetTimeout", "(II)Z",
   1644             (void *)nfcManager_doSetTimeout},
   1645 
   1646     {"doGetTimeout", "(I)I",
   1647             (void *)nfcManager_doGetTimeout},
   1648 
   1649     {"doResetTimeouts", "()V",
   1650             (void *)nfcManager_doResetTimeouts},
   1651 
   1652     {"doAbort", "()V",
   1653             (void *)nfcManager_doAbort},
   1654 
   1655     {"doSetP2pInitiatorModes", "(I)V",
   1656             (void *)nfcManager_doSetP2pInitiatorModes},
   1657 
   1658     {"doSetP2pTargetModes", "(I)V",
   1659             (void *)nfcManager_doSetP2pTargetModes},
   1660 
   1661     {"doEnableScreenOffSuspend", "()V",
   1662             (void *)nfcManager_doEnableScreenOffSuspend},
   1663 
   1664     {"doDisableScreenOffSuspend", "()V",
   1665             (void *)nfcManager_doDisableScreenOffSuspend},
   1666 
   1667     {"doDump", "()Ljava/lang/String;",
   1668             (void *)nfcManager_doDump},
   1669 };
   1670 
   1671 
   1672 /*******************************************************************************
   1673 **
   1674 ** Function:        register_com_android_nfc_NativeNfcManager
   1675 **
   1676 ** Description:     Regisgter JNI functions with Java Virtual Machine.
   1677 **                  e: Environment of JVM.
   1678 **
   1679 ** Returns:         Status of registration.
   1680 **
   1681 *******************************************************************************/
   1682 int register_com_android_nfc_NativeNfcManager (JNIEnv *e)
   1683 {
   1684     ALOGD ("%s: enter", __FUNCTION__);
   1685     PowerSwitch::getInstance ().initialize (PowerSwitch::UNKNOWN_LEVEL);
   1686     ALOGD ("%s: exit", __FUNCTION__);
   1687     return jniRegisterNativeMethods (e, gNativeNfcManagerClassName, gMethods, NELEM (gMethods));
   1688 }
   1689 
   1690 
   1691 /*******************************************************************************
   1692 **
   1693 ** Function:        startRfDiscovery
   1694 **
   1695 ** Description:     Ask stack to start polling and listening for devices.
   1696 **                  isStart: Whether to start.
   1697 **
   1698 ** Returns:         None
   1699 **
   1700 *******************************************************************************/
   1701 void startRfDiscovery(bool isStart)
   1702 {
   1703     tNFA_STATUS status = NFA_STATUS_FAILED;
   1704 
   1705     ALOGD ("%s: is start=%d", __FUNCTION__, isStart);
   1706     SyncEventGuard guard (sNfaEnableDisablePollingEvent);
   1707     status  = isStart ? NFA_StartRfDiscovery () : NFA_StopRfDiscovery ();
   1708     if (status == NFA_STATUS_OK)
   1709     {
   1710         sNfaEnableDisablePollingEvent.wait (); //wait for NFA_RF_DISCOVERY_xxxx_EVT
   1711         sRfEnabled = isStart;
   1712     }
   1713     else
   1714     {
   1715         ALOGE ("%s: Failed to start/stop RF discovery; error=0x%X", __FUNCTION__, status);
   1716     }
   1717 }
   1718 
   1719 
   1720 /*******************************************************************************
   1721 **
   1722 ** Function:        doStartupConfig
   1723 **
   1724 ** Description:     Configure the NFC controller.
   1725 **
   1726 ** Returns:         None
   1727 **
   1728 *******************************************************************************/
   1729 void doStartupConfig()
   1730 {
   1731     struct nfc_jni_native_data *nat = getNative(0, 0);
   1732     tNFA_STATUS stat = NFA_STATUS_FAILED;
   1733     int actualLen = 0;
   1734 
   1735     // If polling for Active mode, set the ordering so that we choose Active over Passive mode first.
   1736     if (nat && (nat->tech_mask & (NFA_TECHNOLOGY_MASK_A_ACTIVE | NFA_TECHNOLOGY_MASK_F_ACTIVE)))
   1737     {
   1738         UINT8  act_mode_order_param[] = { 0x01 };
   1739         SyncEventGuard guard (sNfaSetConfigEvent);
   1740         stat = NFA_SetConfig(NCI_PARAM_ID_ACT_ORDER, sizeof(act_mode_order_param), &act_mode_order_param[0]);
   1741         if (stat == NFA_STATUS_OK)
   1742             sNfaSetConfigEvent.wait ();
   1743     }
   1744 
   1745     //configure RF polling frequency for each technology
   1746     static tNFA_DM_DISC_FREQ_CFG nfa_dm_disc_freq_cfg;
   1747     //values in the polling_frequency[] map to members of nfa_dm_disc_freq_cfg
   1748     UINT8 polling_frequency [8] = {1, 1, 1, 1, 1, 1, 1, 1};
   1749     actualLen = GetStrValue(NAME_POLL_FREQUENCY, (char*)polling_frequency, 8);
   1750     if (actualLen == 8)
   1751     {
   1752         ALOGD ("%s: polling frequency", __FUNCTION__);
   1753         memset (&nfa_dm_disc_freq_cfg, 0, sizeof(nfa_dm_disc_freq_cfg));
   1754         nfa_dm_disc_freq_cfg.pa = polling_frequency [0];
   1755         nfa_dm_disc_freq_cfg.pb = polling_frequency [1];
   1756         nfa_dm_disc_freq_cfg.pf = polling_frequency [2];
   1757         nfa_dm_disc_freq_cfg.pi93 = polling_frequency [3];
   1758         nfa_dm_disc_freq_cfg.pbp = polling_frequency [4];
   1759         nfa_dm_disc_freq_cfg.pk = polling_frequency [5];
   1760         nfa_dm_disc_freq_cfg.paa = polling_frequency [6];
   1761         nfa_dm_disc_freq_cfg.pfa = polling_frequency [7];
   1762         p_nfa_dm_rf_disc_freq_cfg = &nfa_dm_disc_freq_cfg;
   1763     }
   1764 }
   1765 
   1766 
   1767 /*******************************************************************************
   1768 **
   1769 ** Function:        nfcManager_isNfcActive
   1770 **
   1771 ** Description:     Used externaly to determine if NFC is active or not.
   1772 **
   1773 ** Returns:         'true' if the NFC stack is running, else 'false'.
   1774 **
   1775 *******************************************************************************/
   1776 bool nfcManager_isNfcActive()
   1777 {
   1778     return sIsNfaEnabled;
   1779 }
   1780 
   1781 /*******************************************************************************
   1782 **
   1783 ** Function:        startStopPolling
   1784 **
   1785 ** Description:     Start or stop polling.
   1786 **                  isStartPolling: true to start polling; false to stop polling.
   1787 **
   1788 ** Returns:         None.
   1789 **
   1790 *******************************************************************************/
   1791 void startStopPolling (bool isStartPolling)
   1792 {
   1793     ALOGD ("%s: enter; isStart=%u", __FUNCTION__, isStartPolling);
   1794     startRfDiscovery (false);
   1795 
   1796     if (isStartPolling) startPolling_rfDiscoveryDisabled(0);
   1797     else stopPolling_rfDiscoveryDisabled();
   1798 
   1799     startRfDiscovery (true);
   1800     ALOGD ("%s: exit", __FUNCTION__);
   1801 }
   1802 
   1803 
   1804 static tNFA_STATUS startPolling_rfDiscoveryDisabled(tNFA_TECHNOLOGY_MASK tech_mask) {
   1805     tNFA_STATUS stat = NFA_STATUS_FAILED;
   1806 
   1807     unsigned long num = 0;
   1808 
   1809     if (tech_mask == 0 && GetNumValue(NAME_POLLING_TECH_MASK, &num, sizeof(num)))
   1810         tech_mask = num;
   1811     else if (tech_mask == 0) tech_mask = DEFAULT_TECH_MASK;
   1812 
   1813     SyncEventGuard guard (sNfaEnableDisablePollingEvent);
   1814     ALOGD ("%s: enable polling", __FUNCTION__);
   1815     stat = NFA_EnablePolling (tech_mask);
   1816     if (stat == NFA_STATUS_OK)
   1817     {
   1818         ALOGD ("%s: wait for enable event", __FUNCTION__);
   1819         sPollingEnabled = true;
   1820         sNfaEnableDisablePollingEvent.wait (); //wait for NFA_POLL_ENABLED_EVT
   1821     }
   1822     else
   1823     {
   1824         ALOGE ("%s: fail enable polling; error=0x%X", __FUNCTION__, stat);
   1825     }
   1826 
   1827     return stat;
   1828 }
   1829 
   1830 static tNFA_STATUS stopPolling_rfDiscoveryDisabled() {
   1831     tNFA_STATUS stat = NFA_STATUS_FAILED;
   1832 
   1833     SyncEventGuard guard (sNfaEnableDisablePollingEvent);
   1834     ALOGD ("%s: disable polling", __FUNCTION__);
   1835     stat = NFA_DisablePolling ();
   1836     if (stat == NFA_STATUS_OK) {
   1837         sPollingEnabled = false;
   1838         sNfaEnableDisablePollingEvent.wait (); //wait for NFA_POLL_DISABLED_EVT
   1839     } else {
   1840         ALOGE ("%s: fail disable polling; error=0x%X", __FUNCTION__, stat);
   1841     }
   1842 
   1843     return stat;
   1844 }
   1845 
   1846 
   1847 } /* namespace android */
   1848