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