• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright (C) 1999-2012 Broadcom Corporation
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 #include "NfcAdaptation.h"
19 
20 #include <aidl/android/hardware/nfc/BnNfc.h>
21 #include <aidl/android/hardware/nfc/BnNfcClientCallback.h>
22 #include <aidl/android/hardware/nfc/INfc.h>
23 #include <android-base/logging.h>
24 #include <android-base/properties.h>
25 #include <android-base/stringprintf.h>
26 #include <android/binder_ibinder.h>
27 #include <android/binder_manager.h>
28 #include <android/binder_process.h>
29 #include <android/hardware/nfc/1.1/INfc.h>
30 #include <android/hardware/nfc/1.2/INfc.h>
31 #include <cutils/properties.h>
32 #include <hwbinder/ProcessState.h>
33 
34 #include <thread>
35 
36 #include "NfcVendorExtn.h"
37 #include "debug_nfcsnoop.h"
38 #include "nfa_api.h"
39 #include "nfa_rw_api.h"
40 #include "nfa_sys.h"
41 #include "nfa_sys_int.h"
42 #include "nfc_config.h"
43 #include "nfc_int.h"
44 
45 using ::android::wp;
46 using ::android::hardware::hidl_death_recipient;
47 using ::android::hidl::base::V1_0::IBase;
48 
49 using android::OK;
50 using android::sp;
51 using android::status_t;
52 
53 using android::base::StringPrintf;
54 using android::hardware::ProcessState;
55 using android::hardware::Return;
56 using android::hardware::Void;
57 using android::hardware::nfc::V1_0::INfc;
58 using android::hardware::nfc::V1_1::PresenceCheckAlgorithm;
59 using INfcV1_1 = android::hardware::nfc::V1_1::INfc;
60 using INfcV1_2 = android::hardware::nfc::V1_2::INfc;
61 using NfcVendorConfigV1_1 = android::hardware::nfc::V1_1::NfcConfig;
62 using NfcVendorConfigV1_2 = android::hardware::nfc::V1_2::NfcConfig;
63 using android::hardware::nfc::V1_1::INfcClientCallback;
64 using android::hardware::hidl_vec;
65 using INfcAidl = ::aidl::android::hardware::nfc::INfc;
66 using NfcAidlConfig = ::aidl::android::hardware::nfc::NfcConfig;
67 using AidlPresenceCheckAlgorithm =
68     ::aidl::android::hardware::nfc::PresenceCheckAlgorithm;
69 using INfcAidlClientCallback =
70     ::aidl::android::hardware::nfc::INfcClientCallback;
71 using NfcAidlEvent = ::aidl::android::hardware::nfc::NfcEvent;
72 using NfcAidlStatus = ::aidl::android::hardware::nfc::NfcStatus;
73 using ::aidl::android::hardware::nfc::NfcCloseType;
74 using Status = ::ndk::ScopedAStatus;
75 
76 #define VERBOSE_VENDOR_LOG_PROPERTY "persist.nfc.vendor_debug_enabled"
77 #define DEFAULT_CRASH_LOGS_PATH "/data/misc/nfc/logs/hal_crash_logs"
78 
79 std::string NFC_AIDL_HAL_SERVICE_NAME = "android.hardware.nfc.INfc/default";
80 
81 extern void GKI_shutdown();
82 extern void verify_stack_non_volatile_store();
83 extern void delete_stack_non_volatile_store(bool forceDelete);
84 
85 NfcAdaptation* NfcAdaptation::mpInstance = nullptr;
86 ThreadMutex NfcAdaptation::sLock;
87 ThreadCondVar NfcAdaptation::mHalOpenCompletedEvent;
88 sp<INfc> NfcAdaptation::mHal;
89 sp<INfcV1_1> NfcAdaptation::mHal_1_1;
90 sp<INfcV1_2> NfcAdaptation::mHal_1_2;
91 INfcClientCallback* NfcAdaptation::mCallback;
92 std::shared_ptr<INfcAidlClientCallback> mAidlCallback;
93 ::ndk::ScopedAIBinder_DeathRecipient mDeathRecipient;
94 std::shared_ptr<INfcAidl> mAidlHal;
95 int32_t mAidlHalVer;
96 static NfcVendorExtn* sNfcVendorExtn = nullptr;
97 static bool sVndExtnsPresent = false;
98 
99 bool nfc_nci_reset_keep_cfg_enabled = false;
100 uint8_t nfc_nci_reset_type = 0x00;
101 std::string nfc_storage_path;
102 uint8_t appl_dta_mode_flag = 0x00;
103 bool isDownloadFirmwareCompleted = false;
104 bool use_aidl = false;
105 uint8_t mute_tech_route_option = 0x00;
106 unsigned int t5t_mute_legacy = 0;
107 bool nfa_ee_route_debounce_timer = true;
108 
109 extern tNFA_DM_CFG nfa_dm_cfg;
110 extern tNFA_PROPRIETARY_CFG nfa_proprietary_cfg;
111 extern tNFA_HCI_CFG nfa_hci_cfg;
112 extern uint8_t nfa_ee_max_ee_cfg;
113 extern bool nfa_poll_bail_out_mode;
114 
115 // Whitelist for hosts allowed to create a pipe
116 // See ADM_CREATE_PIPE command in the ETSI test specification
117 // ETSI TS 102 622, section 6.1.3.1
118 static std::vector<uint8_t> host_allowlist;
119 
get_vsr_api_level()120 [[maybe_unused]] static int get_vsr_api_level() {
121   int vendor_api_level =
122       ::android::base::GetIntProperty("ro.vendor.api_level", -1);
123   if (vendor_api_level != -1) {
124     return vendor_api_level;
125   }
126 
127   // Android S and older devices do not define ro.vendor.api_level
128   vendor_api_level = ::android::base::GetIntProperty("ro.board.api_level", -1);
129   if (vendor_api_level == -1) {
130     vendor_api_level =
131         ::android::base::GetIntProperty("ro.board.first_api_level", -1);
132   }
133 
134   int product_api_level =
135       ::android::base::GetIntProperty("ro.product.first_api_level", -1);
136   if (product_api_level == -1) {
137     product_api_level =
138         ::android::base::GetIntProperty("ro.build.version.sdk", -1);
139   }
140 
141   // VSR API level is the minimum of vendor_api_level and product_api_level.
142   if (vendor_api_level == -1 || vendor_api_level > product_api_level) {
143     return product_api_level;
144   }
145   return vendor_api_level;
146 }
147 
notifyHalBinderDied()148 static void notifyHalBinderDied() {
149   if (sVndExtnsPresent) {
150     uint8_t event = -1, status = -1;
151     sNfcVendorExtn->processEvent(event, status);
152   }
153 }
154 
155 namespace {
initializeGlobalDebugEnabledFlag()156 void initializeGlobalDebugEnabledFlag() {
157   bool nfc_debug_enabled =
158       (NfcConfig::getUnsigned(NAME_NFC_DEBUG_ENABLED, 0) != 0) ||
159       property_get_bool("persist.nfc.debug_enabled", true);
160 
161   android::base::SetMinimumLogSeverity(nfc_debug_enabled ? android::base::DEBUG
162                                                          : android::base::INFO);
163 
164   LOG(VERBOSE) << StringPrintf("%s: level=%u", __func__, nfc_debug_enabled);
165 }
166 
167 // initialize NciResetType Flag
168 // NCI_RESET_TYPE
169 // 0x00 default, reset configurations every time.
170 // 0x01, reset configurations only once every boot.
171 // 0x02, keep configurations.
initializeNciResetTypeFlag()172 void initializeNciResetTypeFlag() {
173   nfc_nci_reset_type = NfcConfig::getUnsigned(NAME_NCI_RESET_TYPE, 0);
174   LOG(VERBOSE) << StringPrintf("%s: nfc_nci_reset_type=%u", __func__,
175                              nfc_nci_reset_type);
176 }
177 
178 // initialize MuteTechRouteOption Flag
179 // MUTE_TECH_ROUTE_OPTION
180 // 0x00: Default. Route mute techs to DH, enable block bit and set power state
181 // to 0x00 0x01: Remove mute techs from rf discover cmd
initializeNfcMuteTechRouteOptionFlag()182 void initializeNfcMuteTechRouteOptionFlag() {
183   mute_tech_route_option =
184       NfcConfig::getUnsigned(NAME_MUTE_TECH_ROUTE_OPTION, 0);
185   LOG(VERBOSE) << StringPrintf("%s: mute_tech_route_option=%u", __func__,
186                                mute_tech_route_option);
187 }
188 
189 // Abort nfc service when AIDL process died.
HalAidlBinderDied(void *)190 void HalAidlBinderDied(void* /* cookie */) {
191   LOG(ERROR) << StringPrintf("%s: INfc aidl hal died, exiting procces to restart", __func__);
192   storeNfcSnoopLogs(DEFAULT_CRASH_LOGS_PATH, DEFAULT_NFCSNOOP_FILE_SIZE);
193   notifyHalBinderDied();
194   exit(0);
195 }
196 
197 }  // namespace
198 
199 class NfcClientCallback : public INfcClientCallback {
200  public:
NfcClientCallback(tHAL_NFC_CBACK * eventCallback,tHAL_NFC_DATA_CBACK dataCallback)201   NfcClientCallback(tHAL_NFC_CBACK* eventCallback,
202                     tHAL_NFC_DATA_CBACK dataCallback) {
203     mEventCallback = eventCallback;
204     mDataCallback = dataCallback;
205   };
206   virtual ~NfcClientCallback() = default;
sendEvent_1_1(::android::hardware::nfc::V1_1::NfcEvent event,::android::hardware::nfc::V1_0::NfcStatus event_status)207   Return<void> sendEvent_1_1(
208       ::android::hardware::nfc::V1_1::NfcEvent event,
209       ::android::hardware::nfc::V1_0::NfcStatus event_status) override {
210     if (sVndExtnsPresent) {
211       sNfcVendorExtn->processEvent((uint8_t)event,
212                                    (tHAL_NFC_STATUS)event_status);
213     }
214     mEventCallback((uint8_t)event, (tHAL_NFC_STATUS)event_status);
215     return Void();
216   };
sendEvent(::android::hardware::nfc::V1_0::NfcEvent event,::android::hardware::nfc::V1_0::NfcStatus event_status)217   Return<void> sendEvent(
218       ::android::hardware::nfc::V1_0::NfcEvent event,
219       ::android::hardware::nfc::V1_0::NfcStatus event_status) override {
220     if (sVndExtnsPresent) {
221       sNfcVendorExtn->processEvent((uint8_t)event,
222                                    (tHAL_NFC_STATUS)event_status);
223     }
224     mEventCallback((uint8_t)event, (tHAL_NFC_STATUS)event_status);
225     return Void();
226   };
sendData(const::android::hardware::nfc::V1_0::NfcData & data)227   Return<void> sendData(
228       const ::android::hardware::nfc::V1_0::NfcData& data) override {
229     ::android::hardware::nfc::V1_0::NfcData copy = data;
230     if (sVndExtnsPresent) {
231       bool isVndExtSpecRsp =
232           sNfcVendorExtn->processRspNtf(copy.size(), &copy[0]);
233       // If true to be consumed by vendor extension, otherwise need to be
234       // handled in libnfc-nci
235       if (isVndExtSpecRsp) {
236         return Void();
237       }
238     }
239     mDataCallback(copy.size(), &copy[0]);
240     return Void();
241   };
242 
243  private:
244   tHAL_NFC_CBACK* mEventCallback;
245   tHAL_NFC_DATA_CBACK* mDataCallback;
246 };
247 
248 class NfcHalDeathRecipient : public hidl_death_recipient {
249  public:
250   android::sp<android::hardware::nfc::V1_0::INfc> mNfcDeathHal;
NfcHalDeathRecipient(android::sp<android::hardware::nfc::V1_0::INfc> & mHal)251   NfcHalDeathRecipient(android::sp<android::hardware::nfc::V1_0::INfc>& mHal) {
252     mNfcDeathHal = mHal;
253   }
254 
serviceDied(uint64_t,const wp<::android::hidl::base::V1_0::IBase> &)255   virtual void serviceDied(
256       uint64_t /* cookie */,
257       const wp<::android::hidl::base::V1_0::IBase>& /* who */) {
258     ALOGE(
259         "NfcHalDeathRecipient::serviceDied - Nfc-Hal service died. Killing "
260         "NfcService");
261     if (mNfcDeathHal) {
262       mNfcDeathHal->unlinkToDeath(this);
263     }
264     mNfcDeathHal = NULL;
265     notifyHalBinderDied();
266     exit(0);
267   }
finalize()268   void finalize() {
269     if (mNfcDeathHal) {
270       mNfcDeathHal->unlinkToDeath(this);
271     } else {
272       LOG(VERBOSE) << StringPrintf("%s: mNfcDeathHal is not set", __func__);
273     }
274 
275     ALOGI("NfcHalDeathRecipient::destructor - NfcService");
276     mNfcDeathHal = NULL;
277   }
278 };
279 
280 class NfcAidlClientCallback
281     : public ::aidl::android::hardware::nfc::BnNfcClientCallback {
282  public:
NfcAidlClientCallback(tHAL_NFC_CBACK * eventCallback,tHAL_NFC_DATA_CBACK dataCallback)283   NfcAidlClientCallback(tHAL_NFC_CBACK* eventCallback,
284                         tHAL_NFC_DATA_CBACK dataCallback) {
285     mEventCallback = eventCallback;
286     mDataCallback = dataCallback;
287   };
288   virtual ~NfcAidlClientCallback() = default;
289 
sendEvent(NfcAidlEvent event,NfcAidlStatus event_status)290   ::ndk::ScopedAStatus sendEvent(NfcAidlEvent event,
291                                  NfcAidlStatus event_status) override {
292     if (sVndExtnsPresent) {
293       bool isVndExtSpecEvt =
294           sNfcVendorExtn->processEvent((uint8_t)event, (uint8_t)event_status);
295       if (isVndExtSpecEvt) {
296         // If true to be handled only in extension,
297         // otherwise processed in libNfc
298         return ::ndk::ScopedAStatus::ok();
299       }
300     }
301     uint8_t e_num;
302     uint8_t s_num;
303     switch (event) {
304       case NfcAidlEvent::OPEN_CPLT:
305         e_num = HAL_NFC_OPEN_CPLT_EVT;
306         break;
307       case NfcAidlEvent::CLOSE_CPLT:
308         e_num = HAL_NFC_CLOSE_CPLT_EVT;
309         break;
310       case NfcAidlEvent::POST_INIT_CPLT:
311         e_num = HAL_NFC_POST_INIT_CPLT_EVT;
312         break;
313       case NfcAidlEvent::PRE_DISCOVER_CPLT:
314         e_num = HAL_NFC_PRE_DISCOVER_CPLT_EVT;
315         break;
316       case NfcAidlEvent::HCI_NETWORK_RESET:
317         e_num = HAL_HCI_NETWORK_RESET;
318         break;
319       case NfcAidlEvent::REQUEST_CONTROL:
320         e_num = HAL_NFC_REQUEST_CONTROL_EVT;
321         break;
322       case NfcAidlEvent::RELEASE_CONTROL:
323         e_num = HAL_NFC_RELEASE_CONTROL_EVT;
324         break;
325       case NfcAidlEvent::ERROR:
326       default:
327         e_num = HAL_NFC_ERROR_EVT;
328     }
329     switch (event_status) {
330       case NfcAidlStatus::OK:
331         s_num = HAL_NFC_STATUS_OK;
332         break;
333       case NfcAidlStatus::FAILED:
334         s_num = HAL_NFC_STATUS_FAILED;
335         break;
336       case NfcAidlStatus::ERR_TRANSPORT:
337         s_num = HAL_NFC_STATUS_ERR_TRANSPORT;
338         break;
339       case NfcAidlStatus::ERR_CMD_TIMEOUT:
340         s_num = HAL_NFC_STATUS_ERR_CMD_TIMEOUT;
341         break;
342       case NfcAidlStatus::REFUSED:
343         s_num = HAL_NFC_STATUS_REFUSED;
344         break;
345       default:
346         s_num = HAL_NFC_STATUS_FAILED;
347     }
348     mEventCallback(e_num, (tHAL_NFC_STATUS)s_num);
349     return ::ndk::ScopedAStatus::ok();
350   };
sendData(const std::vector<uint8_t> & data)351   ::ndk::ScopedAStatus sendData(const std::vector<uint8_t>& data) override {
352     std::vector<uint8_t> copy = data;
353     if (sVndExtnsPresent) {
354       bool isVndExtSpecRsp =
355           sNfcVendorExtn->processRspNtf(copy.size(), &copy[0]);
356       // If true to be consumed by vendor extension, otherwise need to be
357       // handled in libnfc-nci
358       if (isVndExtSpecRsp) {
359         return ::ndk::ScopedAStatus::ok();
360       }
361     }
362     mDataCallback(copy.size(), &copy[0]);
363     return ::ndk::ScopedAStatus::ok();
364   };
365 
366  private:
367   tHAL_NFC_CBACK* mEventCallback;
368   tHAL_NFC_DATA_CBACK* mDataCallback;
369 };
370 
371 /*******************************************************************************
372 **
373 ** Function:    NfcAdaptation::NfcAdaptation()
374 **
375 ** Description: class constructor
376 **
377 ** Returns:     none
378 **
379 *******************************************************************************/
NfcAdaptation()380 NfcAdaptation::NfcAdaptation() {
381   memset(&mHalEntryFuncs, 0, sizeof(mHalEntryFuncs));
382   mDeathRecipient = ::ndk::ScopedAIBinder_DeathRecipient(
383       AIBinder_DeathRecipient_new(HalAidlBinderDied));
384   sNfcVendorExtn = NfcVendorExtn::getInstance();
385 }
386 
387 /*******************************************************************************
388 **
389 ** Function:    NfcAdaptation::~NfcAdaptation()
390 **
391 ** Description: class destructor
392 **
393 ** Returns:     none
394 **
395 *******************************************************************************/
~NfcAdaptation()396 NfcAdaptation::~NfcAdaptation() { mpInstance = nullptr; }
397 
398 /*******************************************************************************
399 **
400 ** Function:    NfcAdaptation::GetInstance()
401 **
402 ** Description: access class singleton
403 **
404 ** Returns:     pointer to the singleton object
405 **
406 *******************************************************************************/
GetInstance()407 NfcAdaptation& NfcAdaptation::GetInstance() {
408   AutoThreadMutex a(sLock);
409 
410   if (!mpInstance) {
411     mpInstance = new NfcAdaptation;
412     mpInstance->InitializeHalDeviceContext();
413   }
414   return *mpInstance;
415 }
416 
GetVendorConfigs(std::map<std::string,ConfigValue> & configMap)417 void NfcAdaptation::GetVendorConfigs(
418     std::map<std::string, ConfigValue>& configMap) {
419   NfcVendorConfigV1_2 configValue;
420   NfcAidlConfig aidlConfigValue;
421   if (mAidlHal) {
422     mAidlHal->getConfig(&aidlConfigValue);
423   } else if (mHal_1_2) {
424     mHal_1_2->getConfig_1_2(
425         [&configValue](NfcVendorConfigV1_2 config) { configValue = config; });
426   } else if (mHal_1_1) {
427     mHal_1_1->getConfig([&configValue](NfcVendorConfigV1_1 config) {
428       configValue.v1_1 = config;
429       configValue.defaultIsoDepRoute = 0x00;
430     });
431   }
432 
433   if (mAidlHal) {
434     std::vector<int8_t> nfaPropCfg = {
435         aidlConfigValue.nfaProprietaryCfg.protocol18092Active,
436         aidlConfigValue.nfaProprietaryCfg.protocolBPrime,
437         aidlConfigValue.nfaProprietaryCfg.protocolDual,
438         aidlConfigValue.nfaProprietaryCfg.protocol15693,
439         aidlConfigValue.nfaProprietaryCfg.protocolKovio,
440         aidlConfigValue.nfaProprietaryCfg.protocolMifare,
441         aidlConfigValue.nfaProprietaryCfg.discoveryPollKovio,
442         aidlConfigValue.nfaProprietaryCfg.discoveryPollBPrime,
443         aidlConfigValue.nfaProprietaryCfg.discoveryListenBPrime};
444     if (mAidlHalVer > 1) {
445       nfaPropCfg.push_back(aidlConfigValue.nfaProprietaryCfg.protocolChineseId);
446     }
447     configMap.emplace(NAME_NFA_PROPRIETARY_CFG, ConfigValue(nfaPropCfg));
448     configMap.emplace(NAME_NFA_POLL_BAIL_OUT_MODE,
449                       ConfigValue(aidlConfigValue.nfaPollBailOutMode ? 1 : 0));
450     if (aidlConfigValue.offHostRouteUicc.size() != 0) {
451       configMap.emplace(NAME_OFFHOST_ROUTE_UICC,
452                         ConfigValue(aidlConfigValue.offHostRouteUicc));
453     }
454     if (aidlConfigValue.offHostRouteEse.size() != 0) {
455       configMap.emplace(NAME_OFFHOST_ROUTE_ESE,
456                         ConfigValue(aidlConfigValue.offHostRouteEse));
457     }
458     // AIDL byte would be int8_t in C++.
459     // Here we force cast int8_t to uint8_t for ConfigValue
460     configMap.emplace(
461         NAME_DEFAULT_OFFHOST_ROUTE,
462         ConfigValue((uint8_t)aidlConfigValue.defaultOffHostRoute));
463     configMap.emplace(NAME_DEFAULT_ROUTE,
464                       ConfigValue((uint8_t)aidlConfigValue.defaultRoute));
465     configMap.emplace(
466         NAME_DEFAULT_NFCF_ROUTE,
467         ConfigValue((uint8_t)aidlConfigValue.defaultOffHostRouteFelica));
468     configMap.emplace(NAME_DEFAULT_ISODEP_ROUTE,
469                       ConfigValue((uint8_t)aidlConfigValue.defaultIsoDepRoute));
470     configMap.emplace(
471         NAME_DEFAULT_SYS_CODE_ROUTE,
472         ConfigValue((uint8_t)aidlConfigValue.defaultSystemCodeRoute));
473     configMap.emplace(
474         NAME_DEFAULT_SYS_CODE_PWR_STATE,
475         ConfigValue((uint8_t)aidlConfigValue.defaultSystemCodePowerState));
476     configMap.emplace(NAME_OFF_HOST_SIM_PIPE_ID,
477                       ConfigValue((uint8_t)aidlConfigValue.offHostSIMPipeId));
478     configMap.emplace(NAME_OFF_HOST_ESE_PIPE_ID,
479                       ConfigValue((uint8_t)aidlConfigValue.offHostESEPipeId));
480     configMap.emplace(NAME_T4T_NFCEE_ENABLE,
481                       ConfigValue(aidlConfigValue.t4tNfceeEnable ? 1 : 0));
482 
483     if (aidlConfigValue.offHostSimPipeIds.size() != 0) {
484       configMap.emplace(NAME_OFF_HOST_SIM_PIPE_IDS,
485                         ConfigValue(aidlConfigValue.offHostSimPipeIds));
486     }
487     configMap.emplace(NAME_ISO_DEP_MAX_TRANSCEIVE,
488                       ConfigValue(aidlConfigValue.maxIsoDepTransceiveLength));
489     if (aidlConfigValue.hostAllowlist.size() != 0) {
490       configMap.emplace(NAME_DEVICE_HOST_ALLOW_LIST,
491                         ConfigValue(aidlConfigValue.hostAllowlist));
492     }
493     /* For Backwards compatibility */
494     if (aidlConfigValue.presenceCheckAlgorithm ==
495         AidlPresenceCheckAlgorithm::ISO_DEP_NAK) {
496       configMap.emplace(NAME_PRESENCE_CHECK_ALGORITHM,
497                         ConfigValue((uint32_t)NFA_RW_PRES_CHK_ISO_DEP_NAK));
498     } else {
499       configMap.emplace(
500           NAME_PRESENCE_CHECK_ALGORITHM,
501           ConfigValue((uint32_t)aidlConfigValue.presenceCheckAlgorithm));
502     }
503   } else if (mHal_1_1 || mHal_1_2) {
504     std::vector<uint8_t> nfaPropCfg = {
505         configValue.v1_1.nfaProprietaryCfg.protocol18092Active,
506         configValue.v1_1.nfaProprietaryCfg.protocolBPrime,
507         configValue.v1_1.nfaProprietaryCfg.protocolDual,
508         configValue.v1_1.nfaProprietaryCfg.protocol15693,
509         configValue.v1_1.nfaProprietaryCfg.protocolKovio,
510         configValue.v1_1.nfaProprietaryCfg.protocolMifare,
511         configValue.v1_1.nfaProprietaryCfg.discoveryPollKovio,
512         configValue.v1_1.nfaProprietaryCfg.discoveryPollBPrime,
513         configValue.v1_1.nfaProprietaryCfg.discoveryListenBPrime};
514     configMap.emplace(NAME_NFA_PROPRIETARY_CFG, ConfigValue(nfaPropCfg));
515     configMap.emplace(NAME_NFA_POLL_BAIL_OUT_MODE,
516                       ConfigValue(configValue.v1_1.nfaPollBailOutMode ? 1 : 0));
517     configMap.emplace(NAME_DEFAULT_OFFHOST_ROUTE,
518                       ConfigValue(configValue.v1_1.defaultOffHostRoute));
519     if (configValue.offHostRouteUicc.size() != 0) {
520       configMap.emplace(NAME_OFFHOST_ROUTE_UICC,
521                         ConfigValue(configValue.offHostRouteUicc));
522     }
523     if (configValue.offHostRouteEse.size() != 0) {
524       configMap.emplace(NAME_OFFHOST_ROUTE_ESE,
525                         ConfigValue(configValue.offHostRouteEse));
526     }
527     configMap.emplace(NAME_DEFAULT_ROUTE,
528                       ConfigValue(configValue.v1_1.defaultRoute));
529     configMap.emplace(NAME_DEFAULT_NFCF_ROUTE,
530                       ConfigValue(configValue.v1_1.defaultOffHostRouteFelica));
531     configMap.emplace(NAME_DEFAULT_ISODEP_ROUTE,
532                       ConfigValue(configValue.defaultIsoDepRoute));
533     configMap.emplace(NAME_DEFAULT_SYS_CODE_ROUTE,
534                       ConfigValue(configValue.v1_1.defaultSystemCodeRoute));
535     configMap.emplace(
536         NAME_DEFAULT_SYS_CODE_PWR_STATE,
537         ConfigValue(configValue.v1_1.defaultSystemCodePowerState));
538     configMap.emplace(NAME_OFF_HOST_SIM_PIPE_ID,
539                       ConfigValue(configValue.v1_1.offHostSIMPipeId));
540     configMap.emplace(NAME_OFF_HOST_ESE_PIPE_ID,
541                       ConfigValue(configValue.v1_1.offHostESEPipeId));
542     configMap.emplace(NAME_ISO_DEP_MAX_TRANSCEIVE,
543                       ConfigValue(configValue.v1_1.maxIsoDepTransceiveLength));
544     if (configValue.v1_1.hostWhitelist.size() != 0) {
545       configMap.emplace(NAME_DEVICE_HOST_ALLOW_LIST,
546                         ConfigValue(configValue.v1_1.hostWhitelist));
547     }
548     /* For Backwards compatibility */
549     if (configValue.v1_1.presenceCheckAlgorithm ==
550         PresenceCheckAlgorithm::ISO_DEP_NAK) {
551       configMap.emplace(NAME_PRESENCE_CHECK_ALGORITHM,
552                         ConfigValue((uint32_t)NFA_RW_PRES_CHK_ISO_DEP_NAK));
553     } else {
554       configMap.emplace(
555           NAME_PRESENCE_CHECK_ALGORITHM,
556           ConfigValue((uint32_t)configValue.v1_1.presenceCheckAlgorithm));
557     }
558   }
559   if (sVndExtnsPresent) {
560     sNfcVendorExtn->getVendorConfigs(&configMap);
561   }
562 }
563 /*******************************************************************************
564 **
565 ** Function:    NfcAdaptation::Initialize()
566 **
567 ** Description: class initializer
568 **
569 ** Returns:     none
570 **
571 *******************************************************************************/
Initialize()572 void NfcAdaptation::Initialize() {
573   const char* func = "NfcAdaptation::Initialize";
574   if (sVndExtnsPresent) {
575     sNfcVendorExtn->processEvent(HANDLE_NFC_ADAPTATION_INIT, HAL_NFC_STATUS_OK);
576   }
577   // Init log tag
578   android::base::InitLogging(nullptr);
579   android::base::SetDefaultTag("libnfc_nci");
580 
581   initializeGlobalDebugEnabledFlag();
582   initializeNciResetTypeFlag();
583   initializeNfcMuteTechRouteOptionFlag();
584 
585   LOG(VERBOSE) << StringPrintf("%s: enter", func);
586 
587   nfc_storage_path = NfcConfig::getString(NAME_NFA_STORAGE, "/data/nfc");
588 
589   if (NfcConfig::hasKey(NAME_NFA_DM_CFG)) {
590     std::vector<uint8_t> dm_config = NfcConfig::getBytes(NAME_NFA_DM_CFG);
591     if (dm_config.size() > 0) nfa_dm_cfg.auto_detect_ndef = dm_config[0];
592     if (dm_config.size() > 1) nfa_dm_cfg.auto_read_ndef = dm_config[1];
593     if (dm_config.size() > 2) nfa_dm_cfg.auto_presence_check = dm_config[2];
594     if (dm_config.size() > 3) nfa_dm_cfg.presence_check_option = dm_config[3];
595     // NOTE: The timeout value is not configurable here because the endianness
596     // of a byte array is ambiguous and needlessly difficult to configure.
597     // If this value needs to be configurable, a numeric config option should
598     // be used.
599   }
600 
601   if (NfcConfig::hasKey(NAME_NFA_MAX_EE_SUPPORTED)) {
602     nfa_ee_max_ee_cfg = NfcConfig::getUnsigned(NAME_NFA_MAX_EE_SUPPORTED);
603     LOG(VERBOSE) << StringPrintf(
604         "%s: Overriding NFA_EE_MAX_EE_SUPPORTED to use %d", func,
605         nfa_ee_max_ee_cfg);
606   }
607 
608   if (NfcConfig::hasKey(NAME_NFA_POLL_BAIL_OUT_MODE)) {
609     nfa_poll_bail_out_mode =
610         NfcConfig::getUnsigned(NAME_NFA_POLL_BAIL_OUT_MODE);
611     LOG(VERBOSE) << StringPrintf(
612         "%s: Overriding NFA_POLL_BAIL_OUT_MODE to use %d", func,
613         nfa_poll_bail_out_mode);
614   }
615 
616   if (NfcConfig::hasKey(NAME_NFA_PROPRIETARY_CFG)) {
617     std::vector<uint8_t> p_config =
618         NfcConfig::getBytes(NAME_NFA_PROPRIETARY_CFG);
619     if (p_config.size() > 0)
620       nfa_proprietary_cfg.pro_protocol_18092_active = p_config[0];
621     if (p_config.size() > 1)
622       nfa_proprietary_cfg.pro_protocol_b_prime = p_config[1];
623     if (p_config.size() > 2)
624       nfa_proprietary_cfg.pro_protocol_dual = p_config[2];
625     if (p_config.size() > 3)
626       nfa_proprietary_cfg.pro_protocol_15693 = p_config[3];
627     if (p_config.size() > 4)
628       nfa_proprietary_cfg.pro_protocol_kovio = p_config[4];
629     if (p_config.size() > 5) nfa_proprietary_cfg.pro_protocol_mfc = p_config[5];
630     if (p_config.size() > 6)
631       nfa_proprietary_cfg.pro_discovery_kovio_poll = p_config[6];
632     if (p_config.size() > 7)
633       nfa_proprietary_cfg.pro_discovery_b_prime_poll = p_config[7];
634     if (p_config.size() > 8)
635       nfa_proprietary_cfg.pro_discovery_b_prime_listen = p_config[8];
636     if (p_config.size() > 9)
637       nfa_proprietary_cfg.pro_protocol_chinese_id = p_config[9];
638   }
639 
640   // Configure allowlist of HCI host ID's
641   // See specification: ETSI TS 102 622, section 6.1.3.1
642   if (NfcConfig::hasKey(NAME_DEVICE_HOST_ALLOW_LIST)) {
643     host_allowlist = NfcConfig::getBytes(NAME_DEVICE_HOST_ALLOW_LIST);
644     nfa_hci_cfg.num_allowlist_host = host_allowlist.size();
645     nfa_hci_cfg.p_allowlist = &host_allowlist[0];
646   }
647 
648   if (NfcConfig::hasKey(NAME_ISO15693_SKIP_GET_SYS_INFO_CMD)) {
649     t5t_mute_legacy =
650         NfcConfig::getUnsigned(NAME_ISO15693_SKIP_GET_SYS_INFO_CMD);
651   }
652 
653   if (NfcConfig::hasKey(NAME_NFA_DM_LISTEN_ACTIVE_DEACT_NTF_TIMEOUT)) {
654     unsigned int value =
655         NfcConfig::getUnsigned(NAME_NFA_DM_LISTEN_ACTIVE_DEACT_NTF_TIMEOUT);
656     if (value > 0) {
657       nfa_dm_cfg.deact_ntf_listen_active_timeout = value * 1000;
658     }
659   }
660 
661   if (NfcConfig::hasKey(NAME_NFA_EE_ROUTE_DEBOUNCE_TIMER)) {
662     if (NfcConfig::getUnsigned(NAME_NFA_EE_ROUTE_DEBOUNCE_TIMER) == 0x00) {
663       nfa_ee_route_debounce_timer = false;
664     }
665   }
666 
667   verify_stack_non_volatile_store();
668   if (NfcConfig::hasKey(NAME_PRESERVE_STORAGE) &&
669       NfcConfig::getUnsigned(NAME_PRESERVE_STORAGE) == 1) {
670     LOG(VERBOSE) << StringPrintf("%s: preserve stack NV store", __func__);
671   } else {
672     delete_stack_non_volatile_store(FALSE);
673   }
674 
675   GKI_init();
676   GKI_enable();
677   GKI_create_task((TASKPTR)NFCA_TASK, BTU_TASK, (int8_t*)"NFCA_TASK", nullptr, 0,
678                   (pthread_cond_t*)nullptr, nullptr);
679   {
680     AutoThreadMutex guard(mCondVar);
681     GKI_create_task((TASKPTR)Thread, MMI_TASK, (int8_t*)"NFCA_THREAD", nullptr, 0,
682                     (pthread_cond_t*)nullptr, nullptr);
683     mCondVar.wait();
684   }
685 
686   debug_nfcsnoop_init();
687   LOG(VERBOSE) << StringPrintf("%s: exit", func);
688 }
689 
690 /*******************************************************************************
691 **
692 ** Function:    NfcAdaptation::Finalize()
693 **
694 ** Description: class finalizer
695 **
696 ** Returns:     none
697 **
698 *******************************************************************************/
Finalize()699 void NfcAdaptation::Finalize() {
700   const char* func = "NfcAdaptation::Finalize";
701   AutoThreadMutex a(sLock);
702 
703   LOG(VERBOSE) << StringPrintf("%s: enter", func);
704   GKI_shutdown();
705 
706   NfcConfig::clear();
707 
708   if (mAidlHal != nullptr && AIBinder_isAlive(mAidlHal->asBinder().get())) {
709     if (sVndExtnsPresent) {
710       sNfcVendorExtn->finalize();
711     }
712     AIBinder_unlinkToDeath(mAidlHal->asBinder().get(), mDeathRecipient.get(),
713                            nullptr);
714     mAidlHal = nullptr;
715   } else if (mHal != nullptr) {
716     if (sVndExtnsPresent) {
717       sNfcVendorExtn->finalize();
718     }
719     mNfcHalDeathRecipient->finalize();
720   }
721   LOG(VERBOSE) << StringPrintf("%s: exit", func);
722   delete this;
723 }
724 
FactoryReset()725 void NfcAdaptation::FactoryReset() {
726   if (mAidlHal != nullptr) {
727     mAidlHal->factoryReset();
728   } else if (mHal_1_2 != nullptr) {
729     mHal_1_2->factoryReset();
730   } else if (mHal_1_1 != nullptr) {
731     mHal_1_1->factoryReset();
732   }
733 }
734 
DeviceShutdown()735 void NfcAdaptation::DeviceShutdown() {
736   if (mAidlHal != nullptr && AIBinder_isAlive(mAidlHal->asBinder().get())) {
737     mAidlHal->close(NfcCloseType::HOST_SWITCHED_OFF);
738     AIBinder_unlinkToDeath(mAidlHal->asBinder().get(), mDeathRecipient.get(),
739                            nullptr);
740     mAidlHal = nullptr;
741   } else {
742     if (mHal_1_2 != nullptr) {
743       mHal_1_2->closeForPowerOffCase();
744     } else if (mHal_1_1 != nullptr) {
745       mHal_1_1->closeForPowerOffCase();
746     }
747     if (mHal != nullptr) {
748       mHal->unlinkToDeath(mNfcHalDeathRecipient);
749     }
750   }
751 }
752 
753 /*******************************************************************************
754 **
755 ** Function:    NfcAdaptation::Dump
756 **
757 ** Description: Native support for dumpsys function.
758 **
759 ** Returns:     None.
760 **
761 *******************************************************************************/
Dump(int fd)762 void NfcAdaptation::Dump(int fd) {
763   LOG(DEBUG) << StringPrintf("%s :enable_cplt_flags=0x%x, enable_cplt_mask=0x%x",
764                                __func__,
765                                nfa_sys_cb.enable_cplt_flags,
766                                nfa_sys_cb.enable_cplt_mask);
767   dprintf(fd, "enable_cplt_flags=0x%x, enable_cplt_mask=0x%x\n",
768           nfa_sys_cb.enable_cplt_flags,
769           nfa_sys_cb.enable_cplt_mask);
770   debug_nfcsnoop_dump(fd);
771 }
772 
773 /*******************************************************************************
774 **
775 ** Function:    NfcAdaptation::signal()
776 **
777 ** Description: signal the CondVar to release the thread that is waiting
778 **
779 ** Returns:     none
780 **
781 *******************************************************************************/
signal()782 void NfcAdaptation::signal() { mCondVar.signal(); }
783 
784 /*******************************************************************************
785 **
786 ** Function:    NfcAdaptation::NFCA_TASK()
787 **
788 ** Description: NFCA_TASK runs the GKI main task
789 **
790 ** Returns:     none
791 **
792 *******************************************************************************/
NFCA_TASK(uint32_t arg)793 uint32_t NfcAdaptation::NFCA_TASK(__attribute__((unused)) uint32_t arg) {
794   const char* func = "NfcAdaptation::NFCA_TASK";
795   LOG(VERBOSE) << StringPrintf("%s: enter", func);
796   GKI_run(nullptr);
797   LOG(VERBOSE) << StringPrintf("%s: exit", func);
798   return 0;
799 }
800 
801 /*******************************************************************************
802 **
803 ** Function:    NfcAdaptation::Thread()
804 **
805 ** Description: Creates work threads
806 **
807 ** Returns:     none
808 **
809 *******************************************************************************/
Thread(uint32_t arg)810 uint32_t NfcAdaptation::Thread(__attribute__((unused)) uint32_t arg) {
811   const char* func = "NfcAdaptation::Thread";
812   LOG(VERBOSE) << StringPrintf("%s: enter", func);
813 
814   {
815     ThreadCondVar CondVar;
816     AutoThreadMutex guard(CondVar);
817     GKI_create_task((TASKPTR)nfc_task, NFC_TASK, (int8_t*)"NFC_TASK", nullptr, 0,
818                     (pthread_cond_t*)CondVar, (pthread_mutex_t*)CondVar);
819     CondVar.wait();
820   }
821 
822   NfcAdaptation::GetInstance().signal();
823 
824   GKI_exit_task(GKI_get_taskid());
825   LOG(VERBOSE) << StringPrintf("%s: exit", func);
826   return 0;
827 }
828 
829 /*******************************************************************************
830 **
831 ** Function:    NfcAdaptation::GetHalEntryFuncs()
832 **
833 ** Description: Get the set of HAL entry points.
834 **
835 ** Returns:     Functions pointers for HAL entry points.
836 **
837 *******************************************************************************/
GetHalEntryFuncs()838 tHAL_NFC_ENTRY* NfcAdaptation::GetHalEntryFuncs() { return &mHalEntryFuncs; }
839 
840 /*******************************************************************************
841 **
842 ** Function:    NfcAdaptation::InitializeHalDeviceContext
843 **
844 ** Description: Check validity of current handle to the nfc HAL service
845 **
846 ** Returns:     None.
847 **
848 *******************************************************************************/
InitializeHalDeviceContext()849 void NfcAdaptation::InitializeHalDeviceContext() {
850   const char* func = "NfcAdaptation::InitializeHalDeviceContext";
851 
852   mHalEntryFuncs.initialize = HalInitialize;
853   mHalEntryFuncs.terminate = HalTerminate;
854   mHalEntryFuncs.open = HalOpen;
855   mHalEntryFuncs.close = HalClose;
856   mHalEntryFuncs.core_initialized = HalCoreInitialized;
857   mHalEntryFuncs.write = HalWrite;
858   mHalEntryFuncs.prediscover = HalPrediscover;
859   mHalEntryFuncs.control_granted = HalControlGranted;
860   mHalEntryFuncs.power_cycle = HalPowerCycle;
861   mHalEntryFuncs.get_max_ee = HalGetMaxNfcee;
862   LOG(INFO) << StringPrintf("%s: INfc::getService()", func);
863   mAidlHal = nullptr;
864   mHal = mHal_1_1 = mHal_1_2 = nullptr;
865   if (!use_aidl) {
866     mHal = mHal_1_1 = mHal_1_2 = INfcV1_2::getService();
867   }
868   if (!use_aidl && mHal_1_2 == nullptr) {
869     mHal = mHal_1_1 = INfcV1_1::getService();
870     if (mHal_1_1 == nullptr) {
871       mHal = INfc::getService();
872     }
873   }
874   if (mHal == nullptr) {
875     // Try get AIDL
876     ::ndk::SpAIBinder binder(
877         AServiceManager_waitForService(NFC_AIDL_HAL_SERVICE_NAME.c_str()));
878     mAidlHal = INfcAidl::fromBinder(binder);
879     if (mAidlHal != nullptr) {
880       use_aidl = true;
881       AIBinder_linkToDeath(mAidlHal->asBinder().get(), mDeathRecipient.get(),
882                            nullptr /* cookie */);
883       mHal = mHal_1_1 = mHal_1_2 = nullptr;
884       mAidlHal->getInterfaceVersion(&mAidlHalVer);
885       LOG(INFO) << StringPrintf("%s: INfcAidl::fromBinder returned ver(%d)",
886                                 func, mAidlHalVer);
887       // TODO: Enforce VSR API level check later
888       // if (get_vsr_api_level() <= __ANDROID_API_V__) {
889       if (mAidlHalVer <= 1) {
890         sVndExtnsPresent = sNfcVendorExtn->Initialize(nullptr, mAidlHal);
891       }
892     }
893     LOG_ALWAYS_FATAL_IF(mAidlHal == nullptr,
894                         "Failed to retrieve the NFC AIDL!");
895   } else {
896     LOG(INFO) << StringPrintf("%s: INfc::getService() returned %p (%s)", func,
897                               mHal.get(),
898                               (mHal->isRemote() ? "remote" : "local"));
899     mNfcHalDeathRecipient = new NfcHalDeathRecipient(mHal);
900     mHal->linkToDeath(mNfcHalDeathRecipient, 0);
901     sVndExtnsPresent = sNfcVendorExtn->Initialize(mHal, nullptr);
902   }
903 }
904 
905 /*******************************************************************************
906 **
907 ** Function:    NfcAdaptation::HalInitialize
908 **
909 ** Description: Not implemented because this function is only needed
910 **              within the HAL.
911 **
912 ** Returns:     None.
913 **
914 *******************************************************************************/
HalInitialize()915 void NfcAdaptation::HalInitialize() {
916   const char* func = "NfcAdaptation::HalInitialize";
917   LOG(VERBOSE) << StringPrintf("%s", func);
918 }
919 
920 /*******************************************************************************
921 **
922 ** Function:    NfcAdaptation::HalTerminate
923 **
924 ** Description: Not implemented because this function is only needed
925 **              within the HAL.
926 **
927 ** Returns:     None.
928 **
929 *******************************************************************************/
HalTerminate()930 void NfcAdaptation::HalTerminate() {
931   const char* func = "NfcAdaptation::HalTerminate";
932   LOG(VERBOSE) << StringPrintf("%s", func);
933 }
934 
935 /*******************************************************************************
936 **
937 ** Function:    NfcAdaptation::HalOpenInternal
938 **
939 ** Description: Turn on controller, download firmware.
940 **
941 ** Returns:     None.
942 **
943 *******************************************************************************/
HalOpenInternal(tHAL_NFC_CBACK * p_hal_cback,tHAL_NFC_DATA_CBACK * p_data_cback)944 void NfcAdaptation::HalOpenInternal(tHAL_NFC_CBACK* p_hal_cback,
945                                     tHAL_NFC_DATA_CBACK* p_data_cback) {
946   const char* func = "NfcAdaptation::HalOpenInternal";
947   LOG(VERBOSE) << StringPrintf("%s", func);
948   if (sVndExtnsPresent) {
949     sNfcVendorExtn->setNciCallback(p_hal_cback, p_data_cback);
950   }
951   if (mAidlHal != nullptr) {
952     mAidlCallback = ::ndk::SharedRefBase::make<NfcAidlClientCallback>(
953         p_hal_cback, p_data_cback);
954     Status status = mAidlHal->open(mAidlCallback);
955     if (!status.isOk()) {
956       LOG(ERROR) << StringPrintf(
957           "%s: Open Error=%s", __func__,
958           ::aidl::android::hardware::nfc::toString(
959               static_cast<NfcAidlStatus>(status.getServiceSpecificError()))
960               .c_str());
961     } else {
962       bool verbose_vendor_log =
963           android::base::GetBoolProperty(VERBOSE_VENDOR_LOG_PROPERTY, false);
964       mAidlHal->setEnableVerboseLogging(verbose_vendor_log);
965       LOG(VERBOSE) << StringPrintf("%s: verbose_vendor_log=%u", __func__,
966                                    verbose_vendor_log);
967     }
968   } else if (mHal_1_1 != nullptr) {
969     mCallback = new NfcClientCallback(p_hal_cback, p_data_cback);
970     mHal_1_1->open_1_1(mCallback);
971   } else if (mHal != nullptr) {
972     mCallback = new NfcClientCallback(p_hal_cback, p_data_cback);
973     mHal->open(mCallback);
974   }
975 }
976 
977 /*******************************************************************************
978 **
979 ** Function:    NfcAdaptation::HalOpen
980 **
981 ** Description: Invoke HalOpenInternal in separate thread to not to block
982 **              caller.
983 **
984 ** Returns:     None.
985 **
986 *******************************************************************************/
HalOpen(tHAL_NFC_CBACK * p_hal_cback,tHAL_NFC_DATA_CBACK * p_data_cback)987 void NfcAdaptation::HalOpen(tHAL_NFC_CBACK* p_hal_cback,
988                             tHAL_NFC_DATA_CBACK* p_data_cback) {
989   const char* func = "NfcAdaptation::HalOpen";
990   LOG(VERBOSE) << StringPrintf("%s", func);
991   std::thread([p_hal_cback, p_data_cback]() {
992     HalOpenInternal(p_hal_cback, p_data_cback);
993   }).detach();
994 }
995 
996 /*******************************************************************************
997 **
998 ** Function:    NfcAdaptation::HalClose
999 **
1000 ** Description: Turn off controller.
1001 **
1002 ** Returns:     None.
1003 **
1004 *******************************************************************************/
HalClose()1005 void NfcAdaptation::HalClose() {
1006   const char* func = "NfcAdaptation::HalClose";
1007   LOG(VERBOSE) << StringPrintf("%s", func);
1008   if (sVndExtnsPresent) {
1009     sNfcVendorExtn->processEvent(HANDLE_NFC_HAL_CLOSE, HAL_NFC_STATUS_OK);
1010   }
1011   if (mAidlHal != nullptr) {
1012     mAidlHal->close(NfcCloseType::DISABLE);
1013   } else if (mHal != nullptr) {
1014     mHal->close();
1015   }
1016 }
1017 
1018 /*******************************************************************************
1019 **
1020 ** Function:    NfcAdaptation::HalWrite
1021 **
1022 ** Description: Write NCI message to the controller.
1023 **
1024 ** Returns:     None.
1025 **
1026 *******************************************************************************/
HalWrite(uint16_t data_len,uint8_t * p_data)1027 void NfcAdaptation::HalWrite(uint16_t data_len, uint8_t* p_data) {
1028   const char* func = "NfcAdaptation::HalWrite";
1029   LOG(VERBOSE) << StringPrintf("%s", func);
1030 
1031   if (sVndExtnsPresent) {
1032     bool isVndExtSpecCmd = sNfcVendorExtn->processCmd(data_len, p_data);
1033     // If true to be handled in extension, otherwise processed to hal
1034     if (isVndExtSpecCmd) {
1035       return;
1036     }
1037   }
1038   if (mAidlHal != nullptr) {
1039     int ret;
1040     std::vector<uint8_t> aidl_data(p_data, p_data + data_len);
1041     mAidlHal->write(aidl_data, &ret);
1042   } else if (mHal != nullptr) {
1043     ::android::hardware::nfc::V1_0::NfcData data;
1044     data.setToExternal(p_data, data_len);
1045     mHal->write(data);
1046   }
1047 }
1048 
1049 /*******************************************************************************
1050 **
1051 ** Function:    NfcAdaptation::HalCoreInitialized
1052 **
1053 ** Description: Adjust the configurable parameters in the controller.
1054 **
1055 ** Returns:     None.
1056 **
1057 *******************************************************************************/
HalCoreInitialized(uint16_t data_len,uint8_t * p_core_init_rsp_params)1058 void NfcAdaptation::HalCoreInitialized(uint16_t data_len,
1059                                        uint8_t* p_core_init_rsp_params) {
1060   const char* func = "NfcAdaptation::HalCoreInitialized";
1061   LOG(VERBOSE) << StringPrintf("%s", func);
1062   if (sVndExtnsPresent) {
1063     sNfcVendorExtn->processEvent(HANDLE_NFC_HAL_CORE_INITIALIZE,
1064                                  HAL_NFC_STATUS_OK);
1065   }
1066   if (mAidlHal != nullptr) {
1067     // AIDL coreInitialized doesn't send data to HAL.
1068     mAidlHal->coreInitialized();
1069   } else if (mHal != nullptr) {
1070     hidl_vec<uint8_t> data;
1071     data.setToExternal(p_core_init_rsp_params, data_len);
1072     mHal->coreInitialized(data);
1073   }
1074 }
1075 
1076 /*******************************************************************************
1077 **
1078 ** Function:    NfcAdaptation::HalPrediscover
1079 **
1080 ** Description:     Perform any vendor-specific pre-discovery actions (if
1081 **                  needed) If any actions were performed TRUE will be returned,
1082 **                  and HAL_PRE_DISCOVER_CPLT_EVT will notify when actions are
1083 **                  completed.
1084 **
1085 ** Returns:         TRUE if vendor-specific pre-discovery actions initialized
1086 **                  FALSE if no vendor-specific pre-discovery actions are
1087 **                  needed.
1088 **
1089 *******************************************************************************/
HalPrediscover()1090 bool NfcAdaptation::HalPrediscover() {
1091   const char* func = "NfcAdaptation::HalPrediscover";
1092   LOG(VERBOSE) << StringPrintf("%s", func);
1093   if (sVndExtnsPresent) {
1094     sNfcVendorExtn->processEvent(HANDLE_NFC_PRE_DISCOVER, HAL_NFC_STATUS_OK);
1095   }
1096   if (mAidlHal != nullptr) {
1097     Status status = mAidlHal->preDiscover();
1098     if (status.isOk()) {
1099       LOG(VERBOSE) << StringPrintf("%s: wait for NFC_PRE_DISCOVER_CPLT_EVT",
1100                                    func);
1101       return true;
1102     }
1103   } else if (mHal != nullptr) {
1104     mHal->prediscover();
1105   }
1106 
1107   return false;
1108 }
1109 
1110 /*******************************************************************************
1111 **
1112 ** Function:        HAL_NfcControlGranted
1113 **
1114 ** Description:     Grant control to HAL control for sending NCI commands.
1115 **                  Call in response to HAL_REQUEST_CONTROL_EVT.
1116 **                  Must only be called when there are no NCI commands pending.
1117 **                  HAL_RELEASE_CONTROL_EVT will notify when HAL no longer
1118 **                  needs control of NCI.
1119 **
1120 ** Returns:         void
1121 **
1122 *******************************************************************************/
HalControlGranted()1123 void NfcAdaptation::HalControlGranted() {
1124   const char* func = "NfcAdaptation::HalControlGranted";
1125   LOG(VERBOSE) << StringPrintf("%s", func);
1126   if (mAidlHal != nullptr) {
1127     if (mAidlHalVer > 1) {
1128       NfcAidlStatus aidl_status;
1129       mAidlHal->controlGranted(&aidl_status);
1130     } else {
1131       LOG(ERROR) << StringPrintf("%s: Unsupported function", func);
1132     }
1133   } else if (mHal != nullptr) {
1134     mHal->controlGranted();
1135   }
1136 }
1137 
1138 /*******************************************************************************
1139 **
1140 ** Function:    NfcAdaptation::HalPowerCycle
1141 **
1142 ** Description: Turn off and turn on the controller.
1143 **
1144 ** Returns:     None.
1145 **
1146 *******************************************************************************/
HalPowerCycle()1147 void NfcAdaptation::HalPowerCycle() {
1148   const char* func = "NfcAdaptation::HalPowerCycle";
1149   LOG(VERBOSE) << StringPrintf("%s", func);
1150   if (sVndExtnsPresent) {
1151     sNfcVendorExtn->processEvent(HANDLE_NFC_HAL_POWER_CYCLE, HAL_NFC_STATUS_OK);
1152   }
1153   if (mAidlHal != nullptr) {
1154     mAidlHal->powerCycle();
1155   } else if (mHal != nullptr) {
1156     mHal->powerCycle();
1157   }
1158 }
1159 
1160 /*******************************************************************************
1161 **
1162 ** Function:    NfcAdaptation::HalGetMaxNfcee
1163 **
1164 ** Description: Turn off and turn on the controller.
1165 **
1166 ** Returns:     None.
1167 **
1168 *******************************************************************************/
HalGetMaxNfcee()1169 uint8_t NfcAdaptation::HalGetMaxNfcee() {
1170   const char* func = "NfcAdaptation::HalGetMaxNfcee";
1171   LOG(VERBOSE) << StringPrintf("%s", func);
1172   if (sVndExtnsPresent) {
1173     sNfcVendorExtn->processEvent(HANDLE_NFC_GET_MAX_NFCEE, HAL_NFC_STATUS_OK);
1174   }
1175   return nfa_ee_max_ee_cfg;
1176 }
1177 
1178 /*******************************************************************************
1179 **
1180 ** Function:    NfcAdaptation::DownloadFirmware
1181 **
1182 ** Description: Download firmware patch files.
1183 **
1184 ** Returns:     None.
1185 **
1186 *******************************************************************************/
DownloadFirmware()1187 bool NfcAdaptation::DownloadFirmware() {
1188   const char* func = "NfcAdaptation::DownloadFirmware";
1189   isDownloadFirmwareCompleted = false;
1190   LOG(VERBOSE) << StringPrintf("%s: enter", func);
1191   HalInitialize();
1192   if (sVndExtnsPresent) {
1193     sNfcVendorExtn->processEvent(HANDLE_DOWNLOAD_FIRMWARE_REQUEST,
1194                                  HAL_NFC_STATUS_OK);
1195   }
1196   mHalOpenCompletedEvent.lock();
1197   LOG(VERBOSE) << StringPrintf("%s: try open HAL", func);
1198   HalOpen(HalDownloadFirmwareCallback, HalDownloadFirmwareDataCallback);
1199   // wait up to 60s, if not opened in this delay, give up and close anyway.
1200   mHalOpenCompletedEvent.wait(60000);
1201   mHalOpenCompletedEvent.unlock();
1202 
1203   LOG(VERBOSE) << StringPrintf("%s: try core init HAL", func);
1204   uint8_t coreInitRspParams = 0;
1205   HalCoreInitialized(sizeof(uint8_t), &coreInitRspParams);
1206 
1207   LOG(VERBOSE) << StringPrintf("%s: try close HAL", func);
1208   HalClose();
1209 
1210   HalTerminate();
1211   LOG(VERBOSE) << StringPrintf("%s: exit", func);
1212 
1213   return isDownloadFirmwareCompleted;
1214 }
1215 
1216 /*******************************************************************************
1217 **
1218 ** Function:    NfcAdaptation::HalDownloadFirmwareCallback
1219 **
1220 ** Description: Receive events from the HAL.
1221 **
1222 ** Returns:     None.
1223 **
1224 *******************************************************************************/
HalDownloadFirmwareCallback(nfc_event_t event,nfc_status_t event_status)1225 void NfcAdaptation::HalDownloadFirmwareCallback(nfc_event_t event,
1226                                                 nfc_status_t event_status) {
1227   const char* func = "NfcAdaptation::HalDownloadFirmwareCallback";
1228   LOG(VERBOSE) << StringPrintf("%s: event=0x%X", func, event);
1229   switch (event) {
1230     case HAL_NFC_OPEN_CPLT_EVT: {
1231       LOG(VERBOSE) << StringPrintf("%s: HAL_NFC_OPEN_CPLT_EVT", func);
1232       if (event_status == HAL_NFC_STATUS_OK) isDownloadFirmwareCompleted = true;
1233       mHalOpenCompletedEvent.signal();
1234       break;
1235     }
1236     case HAL_NFC_CLOSE_CPLT_EVT: {
1237       LOG(VERBOSE) << StringPrintf("%s: HAL_NFC_CLOSE_CPLT_EVT", func);
1238       break;
1239     }
1240   }
1241   tNFC_HAL_EVT_MSG* p_msg =
1242       (tNFC_HAL_EVT_MSG*)GKI_getbuf(sizeof(tNFC_HAL_EVT_MSG));
1243   if (p_msg != nullptr) {
1244     /* Initialize NFC_HDR */
1245     p_msg->hdr.len = 0;
1246     p_msg->hdr.event = BT_EVT_TO_NFC_MSGS;
1247     p_msg->hdr.offset = 0;
1248     p_msg->hdr.layer_specific = 0;
1249     p_msg->hal_evt = event;
1250     p_msg->status = event_status;
1251     GKI_send_msg(NFC_TASK, NFC_MBOX_ID, p_msg);
1252   } else {
1253     LOG(ERROR) << StringPrintf("No buffer");
1254   };
1255 }
1256 
1257 /*******************************************************************************
1258 **
1259 ** Function:    NfcAdaptation::HalDownloadFirmwareDataCallback
1260 **
1261 ** Description: Receive data events from the HAL.
1262 **
1263 ** Returns:     None.
1264 **
1265 *******************************************************************************/
HalDownloadFirmwareDataCallback(uint16_t data_len,uint8_t * p_data)1266 void NfcAdaptation::HalDownloadFirmwareDataCallback(uint16_t data_len,
1267                                                     uint8_t* p_data) {
1268   const char* func = "NfcAdaptation::HalDownloadFirmwareDataCallback";
1269   LOG(VERBOSE) << StringPrintf("%s: data_len= %d", func, data_len);
1270   if (p_data == nullptr) {
1271     LOG(ERROR) << StringPrintf("%s: Invalid data!", func);
1272     return;
1273   }
1274   NFC_HDR* p_msg = (NFC_HDR*)GKI_getbuf(sizeof(NFC_HDR) +
1275                                         NFC_RECEIVE_MSGS_OFFSET + data_len);
1276   if (p_msg != nullptr) {
1277     /* Initialize NFC_HDR */
1278     p_msg->len = data_len;
1279     p_msg->event = BT_EVT_TO_NFC_NCI;
1280     p_msg->offset = NFC_RECEIVE_MSGS_OFFSET;
1281 
1282     /* no need to check length, it always less than pool size */
1283     memcpy((uint8_t*)(p_msg + 1) + p_msg->offset, p_data, p_msg->len);
1284 
1285     GKI_send_msg(NFC_TASK, NFC_MBOX_ID, p_msg);
1286     LOG(VERBOSE) << StringPrintf("GKI msg sent!");
1287   } else {
1288     LOG(ERROR) << StringPrintf("No buffer");
1289   }
1290 }
1291 
1292 /*******************************************************************************
1293 **
1294 ** Function:    ThreadMutex::ThreadMutex()
1295 **
1296 ** Description: class constructor
1297 **
1298 ** Returns:     none
1299 **
1300 *******************************************************************************/
ThreadMutex()1301 ThreadMutex::ThreadMutex() {
1302   pthread_mutexattr_t mutexAttr;
1303 
1304   pthread_mutexattr_init(&mutexAttr);
1305   pthread_mutexattr_settype(&mutexAttr, PTHREAD_MUTEX_RECURSIVE);
1306   pthread_mutex_init(&mMutex, &mutexAttr);
1307   pthread_mutexattr_destroy(&mutexAttr);
1308 }
1309 
1310 /*******************************************************************************
1311 **
1312 ** Function:    ThreadMutex::~ThreadMutex()
1313 **
1314 ** Description: class destructor
1315 **
1316 ** Returns:     none
1317 **
1318 *******************************************************************************/
~ThreadMutex()1319 ThreadMutex::~ThreadMutex() { pthread_mutex_destroy(&mMutex); }
1320 
1321 /*******************************************************************************
1322 **
1323 ** Function:    ThreadMutex::lock()
1324 **
1325 ** Description: lock kthe mutex
1326 **
1327 ** Returns:     none
1328 **
1329 *******************************************************************************/
lock()1330 void ThreadMutex::lock() { pthread_mutex_lock(&mMutex); }
1331 
1332 /*******************************************************************************
1333 **
1334 ** Function:    ThreadMutex::unblock()
1335 **
1336 ** Description: unlock the mutex
1337 **
1338 ** Returns:     none
1339 **
1340 *******************************************************************************/
unlock()1341 void ThreadMutex::unlock() { pthread_mutex_unlock(&mMutex); }
1342 
1343 /*******************************************************************************
1344 **
1345 ** Function:    ThreadCondVar::ThreadCondVar()
1346 **
1347 ** Description: class constructor
1348 **
1349 ** Returns:     none
1350 **
1351 *******************************************************************************/
ThreadCondVar()1352 ThreadCondVar::ThreadCondVar() {
1353   pthread_condattr_t CondAttr;
1354 
1355   pthread_condattr_init(&CondAttr);
1356   pthread_condattr_setclock(&CondAttr, CLOCK_MONOTONIC);
1357   pthread_cond_init(&mCondVar, &CondAttr);
1358 
1359   pthread_condattr_destroy(&CondAttr);
1360 }
1361 
1362 /*******************************************************************************
1363 **
1364 ** Function:    ThreadCondVar::~ThreadCondVar()
1365 **
1366 ** Description: class destructor
1367 **
1368 ** Returns:     none
1369 **
1370 *******************************************************************************/
~ThreadCondVar()1371 ThreadCondVar::~ThreadCondVar() { pthread_cond_destroy(&mCondVar); }
1372 
1373 /*******************************************************************************
1374 **
1375 ** Function:    ThreadCondVar::wait()
1376 **
1377 ** Description: wait on the mCondVar
1378 **
1379 ** Returns:     none
1380 **
1381 *******************************************************************************/
wait()1382 void ThreadCondVar::wait() {
1383   pthread_cond_wait(&mCondVar, *this);
1384   pthread_mutex_unlock(*this);
1385 }
1386 
1387 /*******************************************************************************
1388 **
1389 ** Function:    ThreadCondVar::wait()
1390 **
1391 ** Description: wait on the mCondVar for the indicated amount of time (ms)
1392 **
1393 ** Returns:     true if wait succeeded
1394 **
1395 *******************************************************************************/
wait(long millisec)1396 bool ThreadCondVar::wait(long millisec) {
1397   bool retVal = false;
1398   struct timespec absoluteTime;
1399 
1400   if (clock_gettime(CLOCK_MONOTONIC, &absoluteTime) == -1) {
1401     LOG(ERROR) << StringPrintf("ThreadCondVar::wait: fail get time; errno=0x%X",
1402                                errno);
1403   } else {
1404     absoluteTime.tv_sec += millisec / 1000;
1405     long ns = absoluteTime.tv_nsec + ((millisec % 1000) * 1000000);
1406     if (ns > 1000000000) {
1407       absoluteTime.tv_sec++;
1408       absoluteTime.tv_nsec = ns - 1000000000;
1409     } else
1410       absoluteTime.tv_nsec = ns;
1411   }
1412 
1413   int waitResult = pthread_cond_timedwait(&mCondVar, *this, &absoluteTime);
1414   if ((waitResult != 0) && (waitResult != ETIMEDOUT))
1415     LOG(ERROR) << StringPrintf("ThreadCondVar::wait: fail timed wait; error=0x%X",
1416                                waitResult);
1417   retVal = (waitResult == 0);  // waited successfully
1418   if (retVal) pthread_mutex_unlock(*this);
1419   return retVal;
1420 }
1421 
1422 /*******************************************************************************
1423 **
1424 ** Function:    ThreadCondVar::signal()
1425 **
1426 ** Description: signal the mCondVar
1427 **
1428 ** Returns:     none
1429 **
1430 *******************************************************************************/
signal()1431 void ThreadCondVar::signal() {
1432   AutoThreadMutex a(*this);
1433   pthread_cond_signal(&mCondVar);
1434 }
1435 
1436 /*******************************************************************************
1437 **
1438 ** Function:    AutoThreadMutex::AutoThreadMutex()
1439 **
1440 ** Description: class constructor, automatically lock the mutex
1441 **
1442 ** Returns:     none
1443 **
1444 *******************************************************************************/
AutoThreadMutex(ThreadMutex & m)1445 AutoThreadMutex::AutoThreadMutex(ThreadMutex& m) : mm(m) { mm.lock(); }
1446 
1447 /*******************************************************************************
1448 **
1449 ** Function:    AutoThreadMutex::~AutoThreadMutex()
1450 **
1451 ** Description: class destructor, automatically unlock the mutex
1452 **
1453 ** Returns:     none
1454 **
1455 *******************************************************************************/
~AutoThreadMutex()1456 AutoThreadMutex::~AutoThreadMutex() { mm.unlock(); }
1457