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 <android-base/stringprintf.h>
19 #include <android/hardware/nfc/1.1/INfc.h>
20 #include <android/hardware/nfc/1.2/INfc.h>
21 #include <base/command_line.h>
22 #include <base/logging.h>
23 #include <cutils/properties.h>
24 #include <hwbinder/ProcessState.h>
25 
26 #include "NfcAdaptation.h"
27 #include "debug_nfcsnoop.h"
28 #include "nfa_api.h"
29 #include "nfa_rw_api.h"
30 #include "nfc_config.h"
31 #include "nfc_int.h"
32 
33 using ::android::wp;
34 using ::android::hardware::hidl_death_recipient;
35 using ::android::hidl::base::V1_0::IBase;
36 
37 using android::OK;
38 using android::sp;
39 using android::status_t;
40 
41 using android::base::StringPrintf;
42 using android::hardware::ProcessState;
43 using android::hardware::Return;
44 using android::hardware::Void;
45 using android::hardware::nfc::V1_0::INfc;
46 using android::hardware::nfc::V1_1::PresenceCheckAlgorithm;
47 using INfcV1_1 = android::hardware::nfc::V1_1::INfc;
48 using INfcV1_2 = android::hardware::nfc::V1_2::INfc;
49 using NfcVendorConfigV1_1 = android::hardware::nfc::V1_1::NfcConfig;
50 using NfcVendorConfigV1_2 = android::hardware::nfc::V1_2::NfcConfig;
51 using android::hardware::nfc::V1_1::INfcClientCallback;
52 using android::hardware::hidl_vec;
53 
54 extern bool nfc_debug_enabled;
55 
56 extern void GKI_shutdown();
57 extern void verify_stack_non_volatile_store();
58 extern void delete_stack_non_volatile_store(bool forceDelete);
59 
60 NfcAdaptation* NfcAdaptation::mpInstance = nullptr;
61 ThreadMutex NfcAdaptation::sLock;
62 tHAL_NFC_CBACK* NfcAdaptation::mHalCallback = nullptr;
63 tHAL_NFC_DATA_CBACK* NfcAdaptation::mHalDataCallback = nullptr;
64 ThreadCondVar NfcAdaptation::mHalOpenCompletedEvent;
65 ThreadCondVar NfcAdaptation::mHalCloseCompletedEvent;
66 sp<INfc> NfcAdaptation::mHal;
67 sp<INfcV1_1> NfcAdaptation::mHal_1_1;
68 sp<INfcV1_2> NfcAdaptation::mHal_1_2;
69 INfcClientCallback* NfcAdaptation::mCallback;
70 
71 bool nfc_debug_enabled = false;
72 std::string nfc_storage_path;
73 uint8_t appl_dta_mode_flag = 0x00;
74 bool isDownloadFirmwareCompleted = false;
75 
76 extern tNFA_DM_CFG nfa_dm_cfg;
77 extern tNFA_PROPRIETARY_CFG nfa_proprietary_cfg;
78 extern tNFA_HCI_CFG nfa_hci_cfg;
79 extern uint8_t nfa_ee_max_ee_cfg;
80 extern bool nfa_poll_bail_out_mode;
81 
82 // Whitelist for hosts allowed to create a pipe
83 // See ADM_CREATE_PIPE command in the ETSI test specification
84 // ETSI TS 102 622, section 6.1.3.1
85 static std::vector<uint8_t> host_whitelist;
86 
87 namespace {
initializeGlobalDebugEnabledFlag()88 void initializeGlobalDebugEnabledFlag() {
89   nfc_debug_enabled =
90       (NfcConfig::getUnsigned(NAME_NFC_DEBUG_ENABLED, 0) != 0) ? true : false;
91 
92   char valueStr[PROPERTY_VALUE_MAX] = {0};
93   int len = property_get("nfc.debug_enabled", valueStr, "");
94   if (len > 0) {
95     // let Android property override .conf variable
96     unsigned debug_enabled = 0;
97     sscanf(valueStr, "%u", &debug_enabled);
98     nfc_debug_enabled = (debug_enabled == 0) ? false : true;
99   }
100 
101   DLOG_IF(INFO, nfc_debug_enabled)
102       << StringPrintf("%s: level=%u", __func__, nfc_debug_enabled);
103 }
104 }  // namespace
105 
106 class NfcClientCallback : public INfcClientCallback {
107  public:
NfcClientCallback(tHAL_NFC_CBACK * eventCallback,tHAL_NFC_DATA_CBACK dataCallback)108   NfcClientCallback(tHAL_NFC_CBACK* eventCallback,
109                     tHAL_NFC_DATA_CBACK dataCallback) {
110     mEventCallback = eventCallback;
111     mDataCallback = dataCallback;
112   };
113   virtual ~NfcClientCallback() = default;
sendEvent_1_1(::android::hardware::nfc::V1_1::NfcEvent event,::android::hardware::nfc::V1_0::NfcStatus event_status)114   Return<void> sendEvent_1_1(
115       ::android::hardware::nfc::V1_1::NfcEvent event,
116       ::android::hardware::nfc::V1_0::NfcStatus event_status) override {
117     mEventCallback((uint8_t)event, (tHAL_NFC_STATUS)event_status);
118     return Void();
119   };
sendEvent(::android::hardware::nfc::V1_0::NfcEvent event,::android::hardware::nfc::V1_0::NfcStatus event_status)120   Return<void> sendEvent(
121       ::android::hardware::nfc::V1_0::NfcEvent event,
122       ::android::hardware::nfc::V1_0::NfcStatus event_status) override {
123     mEventCallback((uint8_t)event, (tHAL_NFC_STATUS)event_status);
124     return Void();
125   };
sendData(const::android::hardware::nfc::V1_0::NfcData & data)126   Return<void> sendData(
127       const ::android::hardware::nfc::V1_0::NfcData& data) override {
128     ::android::hardware::nfc::V1_0::NfcData copy = data;
129     mDataCallback(copy.size(), &copy[0]);
130     return Void();
131   };
132 
133  private:
134   tHAL_NFC_CBACK* mEventCallback;
135   tHAL_NFC_DATA_CBACK* mDataCallback;
136 };
137 
138 class NfcHalDeathRecipient : public hidl_death_recipient {
139  public:
140   android::sp<android::hardware::nfc::V1_0::INfc> mNfcDeathHal;
NfcHalDeathRecipient(android::sp<android::hardware::nfc::V1_0::INfc> & mHal)141   NfcHalDeathRecipient(android::sp<android::hardware::nfc::V1_0::INfc>& mHal) {
142     mNfcDeathHal = mHal;
143   }
144 
serviceDied(uint64_t,const wp<::android::hidl::base::V1_0::IBase> &)145   virtual void serviceDied(
146       uint64_t /* cookie */,
147       const wp<::android::hidl::base::V1_0::IBase>& /* who */) {
148     ALOGE(
149         "NfcHalDeathRecipient::serviceDied - Nfc-Hal service died. Killing "
150         "NfcServie");
151     if (mNfcDeathHal) {
152       mNfcDeathHal->unlinkToDeath(this);
153     }
154     mNfcDeathHal = NULL;
155     abort();
156   }
157 };
158 
159 /*******************************************************************************
160 **
161 ** Function:    NfcAdaptation::NfcAdaptation()
162 **
163 ** Description: class constructor
164 **
165 ** Returns:     none
166 **
167 *******************************************************************************/
NfcAdaptation()168 NfcAdaptation::NfcAdaptation() {
169   mNfcHalDeathRecipient = new NfcHalDeathRecipient(mHal);
170   memset(&mHalEntryFuncs, 0, sizeof(mHalEntryFuncs));
171 }
172 
173 /*******************************************************************************
174 **
175 ** Function:    NfcAdaptation::~NfcAdaptation()
176 **
177 ** Description: class destructor
178 **
179 ** Returns:     none
180 **
181 *******************************************************************************/
~NfcAdaptation()182 NfcAdaptation::~NfcAdaptation() { mpInstance = nullptr; }
183 
184 /*******************************************************************************
185 **
186 ** Function:    NfcAdaptation::GetInstance()
187 **
188 ** Description: access class singleton
189 **
190 ** Returns:     pointer to the singleton object
191 **
192 *******************************************************************************/
GetInstance()193 NfcAdaptation& NfcAdaptation::GetInstance() {
194   AutoThreadMutex a(sLock);
195 
196   if (!mpInstance) {
197     mpInstance = new NfcAdaptation;
198     mpInstance->InitializeHalDeviceContext();
199   }
200   return *mpInstance;
201 }
202 
GetVendorConfigs(std::map<std::string,ConfigValue> & configMap)203 void NfcAdaptation::GetVendorConfigs(
204     std::map<std::string, ConfigValue>& configMap) {
205   NfcVendorConfigV1_2 configValue;
206   if (mHal_1_2) {
207     mHal_1_2->getConfig_1_2(
208         [&configValue](NfcVendorConfigV1_2 config) { configValue = config; });
209   } else if (mHal_1_1) {
210     mHal_1_1->getConfig([&configValue](NfcVendorConfigV1_1 config) {
211       configValue.v1_1 = config;
212       configValue.defaultIsoDepRoute = 0x00;
213     });
214   }
215 
216   if (mHal_1_1 || mHal_1_2) {
217     std::vector<uint8_t> nfaPropCfg = {
218         configValue.v1_1.nfaProprietaryCfg.protocol18092Active,
219         configValue.v1_1.nfaProprietaryCfg.protocolBPrime,
220         configValue.v1_1.nfaProprietaryCfg.protocolDual,
221         configValue.v1_1.nfaProprietaryCfg.protocol15693,
222         configValue.v1_1.nfaProprietaryCfg.protocolKovio,
223         configValue.v1_1.nfaProprietaryCfg.protocolMifare,
224         configValue.v1_1.nfaProprietaryCfg.discoveryPollKovio,
225         configValue.v1_1.nfaProprietaryCfg.discoveryPollBPrime,
226         configValue.v1_1.nfaProprietaryCfg.discoveryListenBPrime};
227     configMap.emplace(NAME_NFA_PROPRIETARY_CFG, ConfigValue(nfaPropCfg));
228     configMap.emplace(NAME_NFA_POLL_BAIL_OUT_MODE,
229                       ConfigValue(configValue.v1_1.nfaPollBailOutMode ? 1 : 0));
230     configMap.emplace(NAME_DEFAULT_OFFHOST_ROUTE,
231                       ConfigValue(configValue.v1_1.defaultOffHostRoute));
232     if (configValue.offHostRouteUicc.size() != 0) {
233       configMap.emplace(NAME_OFFHOST_ROUTE_UICC,
234                         ConfigValue(configValue.offHostRouteUicc));
235     }
236     if (configValue.offHostRouteEse.size() != 0) {
237       configMap.emplace(NAME_OFFHOST_ROUTE_ESE,
238                         ConfigValue(configValue.offHostRouteEse));
239     }
240     configMap.emplace(NAME_DEFAULT_ROUTE,
241                       ConfigValue(configValue.v1_1.defaultRoute));
242     configMap.emplace(NAME_DEFAULT_NFCF_ROUTE,
243                       ConfigValue(configValue.v1_1.defaultOffHostRouteFelica));
244     configMap.emplace(NAME_DEFAULT_ISODEP_ROUTE,
245                       ConfigValue(configValue.defaultIsoDepRoute));
246     configMap.emplace(NAME_DEFAULT_SYS_CODE_ROUTE,
247                       ConfigValue(configValue.v1_1.defaultSystemCodeRoute));
248     configMap.emplace(
249         NAME_DEFAULT_SYS_CODE_PWR_STATE,
250         ConfigValue(configValue.v1_1.defaultSystemCodePowerState));
251     configMap.emplace(NAME_OFF_HOST_SIM_PIPE_ID,
252                       ConfigValue(configValue.v1_1.offHostSIMPipeId));
253     configMap.emplace(NAME_OFF_HOST_ESE_PIPE_ID,
254                       ConfigValue(configValue.v1_1.offHostESEPipeId));
255     configMap.emplace(NAME_ISO_DEP_MAX_TRANSCEIVE,
256                       ConfigValue(configValue.v1_1.maxIsoDepTransceiveLength));
257     if (configValue.v1_1.hostWhitelist.size() != 0) {
258       configMap.emplace(NAME_DEVICE_HOST_WHITE_LIST,
259                         ConfigValue(configValue.v1_1.hostWhitelist));
260     }
261     /* For Backwards compatibility */
262     if (configValue.v1_1.presenceCheckAlgorithm ==
263         PresenceCheckAlgorithm::ISO_DEP_NAK) {
264       configMap.emplace(NAME_PRESENCE_CHECK_ALGORITHM,
265                         ConfigValue((uint32_t)NFA_RW_PRES_CHK_ISO_DEP_NAK));
266     } else {
267       configMap.emplace(
268           NAME_PRESENCE_CHECK_ALGORITHM,
269           ConfigValue((uint32_t)configValue.v1_1.presenceCheckAlgorithm));
270     }
271   }
272 }
273 /*******************************************************************************
274 **
275 ** Function:    NfcAdaptation::Initialize()
276 **
277 ** Description: class initializer
278 **
279 ** Returns:     none
280 **
281 *******************************************************************************/
Initialize()282 void NfcAdaptation::Initialize() {
283   const char* func = "NfcAdaptation::Initialize";
284   const char* argv[] = {"libnfc_nci"};
285   // Init log tag
286   base::CommandLine::Init(1, argv);
287 
288   // Android already logs thread_id, proc_id, timestamp, so disable those.
289   logging::SetLogItems(false, false, false, false);
290 
291   initializeGlobalDebugEnabledFlag();
292 
293   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s: enter", func);
294 
295   nfc_storage_path = NfcConfig::getString(NAME_NFA_STORAGE, "/data/nfc");
296 
297   if (NfcConfig::hasKey(NAME_NFA_DM_CFG)) {
298     std::vector<uint8_t> dm_config = NfcConfig::getBytes(NAME_NFA_DM_CFG);
299     if (dm_config.size() > 0) nfa_dm_cfg.auto_detect_ndef = dm_config[0];
300     if (dm_config.size() > 1) nfa_dm_cfg.auto_read_ndef = dm_config[1];
301     if (dm_config.size() > 2) nfa_dm_cfg.auto_presence_check = dm_config[2];
302     if (dm_config.size() > 3) nfa_dm_cfg.presence_check_option = dm_config[3];
303     // NOTE: The timeout value is not configurable here because the endianess
304     // of a byte array is ambiguous and needlessly difficult to configure.
305     // If this value needs to be configgurable, a numeric config option should
306     // be used.
307   }
308 
309   if (NfcConfig::hasKey(NAME_NFA_MAX_EE_SUPPORTED)) {
310     nfa_ee_max_ee_cfg = NfcConfig::getUnsigned(NAME_NFA_MAX_EE_SUPPORTED);
311     DLOG_IF(INFO, nfc_debug_enabled)
312         << StringPrintf("%s: Overriding NFA_EE_MAX_EE_SUPPORTED to use %d",
313                         func, nfa_ee_max_ee_cfg);
314   }
315 
316   if (NfcConfig::hasKey(NAME_NFA_POLL_BAIL_OUT_MODE)) {
317     nfa_poll_bail_out_mode =
318         NfcConfig::getUnsigned(NAME_NFA_POLL_BAIL_OUT_MODE);
319     DLOG_IF(INFO, nfc_debug_enabled)
320         << StringPrintf("%s: Overriding NFA_POLL_BAIL_OUT_MODE to use %d", func,
321                         nfa_poll_bail_out_mode);
322   }
323 
324   if (NfcConfig::hasKey(NAME_NFA_PROPRIETARY_CFG)) {
325     std::vector<uint8_t> p_config =
326         NfcConfig::getBytes(NAME_NFA_PROPRIETARY_CFG);
327     if (p_config.size() > 0)
328       nfa_proprietary_cfg.pro_protocol_18092_active = p_config[0];
329     if (p_config.size() > 1)
330       nfa_proprietary_cfg.pro_protocol_b_prime = p_config[1];
331     if (p_config.size() > 2)
332       nfa_proprietary_cfg.pro_protocol_dual = p_config[2];
333     if (p_config.size() > 3)
334       nfa_proprietary_cfg.pro_protocol_15693 = p_config[3];
335     if (p_config.size() > 4)
336       nfa_proprietary_cfg.pro_protocol_kovio = p_config[4];
337     if (p_config.size() > 5) nfa_proprietary_cfg.pro_protocol_mfc = p_config[5];
338     if (p_config.size() > 6)
339       nfa_proprietary_cfg.pro_discovery_kovio_poll = p_config[6];
340     if (p_config.size() > 7)
341       nfa_proprietary_cfg.pro_discovery_b_prime_poll = p_config[7];
342     if (p_config.size() > 8)
343       nfa_proprietary_cfg.pro_discovery_b_prime_listen = p_config[8];
344   }
345 
346   // Configure whitelist of HCI host ID's
347   // See specification: ETSI TS 102 622, section 6.1.3.1
348   if (NfcConfig::hasKey(NAME_DEVICE_HOST_WHITE_LIST)) {
349     host_whitelist = NfcConfig::getBytes(NAME_DEVICE_HOST_WHITE_LIST);
350     nfa_hci_cfg.num_whitelist_host = host_whitelist.size();
351     nfa_hci_cfg.p_whitelist = &host_whitelist[0];
352   }
353 
354   verify_stack_non_volatile_store();
355   if (NfcConfig::hasKey(NAME_PRESERVE_STORAGE) &&
356       NfcConfig::getUnsigned(NAME_PRESERVE_STORAGE) == 1) {
357     DLOG_IF(INFO, nfc_debug_enabled)
358         << StringPrintf("%s: preserve stack NV store", __func__);
359   } else {
360     delete_stack_non_volatile_store(FALSE);
361   }
362 
363   GKI_init();
364   GKI_enable();
365   GKI_create_task((TASKPTR)NFCA_TASK, BTU_TASK, (int8_t*)"NFCA_TASK", nullptr, 0,
366                   (pthread_cond_t*)nullptr, nullptr);
367   {
368     AutoThreadMutex guard(mCondVar);
369     GKI_create_task((TASKPTR)Thread, MMI_TASK, (int8_t*)"NFCA_THREAD", nullptr, 0,
370                     (pthread_cond_t*)nullptr, nullptr);
371     mCondVar.wait();
372   }
373 
374   debug_nfcsnoop_init();
375   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s: exit", func);
376 }
377 
378 /*******************************************************************************
379 **
380 ** Function:    NfcAdaptation::Finalize()
381 **
382 ** Description: class finalizer
383 **
384 ** Returns:     none
385 **
386 *******************************************************************************/
Finalize()387 void NfcAdaptation::Finalize() {
388   const char* func = "NfcAdaptation::Finalize";
389   AutoThreadMutex a(sLock);
390 
391   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s: enter", func);
392   GKI_shutdown();
393 
394   NfcConfig::clear();
395 
396   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s: exit", func);
397   delete this;
398 }
399 
FactoryReset()400 void NfcAdaptation::FactoryReset() {
401   if (mHal_1_2 != nullptr) {
402     mHal_1_2->factoryReset();
403   } else if (mHal_1_1 != nullptr) {
404     mHal_1_1->factoryReset();
405   }
406 }
407 
DeviceShutdown()408 void NfcAdaptation::DeviceShutdown() {
409   if (mHal_1_2 != nullptr) {
410     mHal_1_2->closeForPowerOffCase();
411   } else if (mHal_1_1 != nullptr) {
412     mHal_1_1->closeForPowerOffCase();
413   }
414 }
415 
416 /*******************************************************************************
417 **
418 ** Function:    NfcAdaptation::Dump
419 **
420 ** Description: Native support for dumpsys function.
421 **
422 ** Returns:     None.
423 **
424 *******************************************************************************/
Dump(int fd)425 void NfcAdaptation::Dump(int fd) { debug_nfcsnoop_dump(fd); }
426 
427 /*******************************************************************************
428 **
429 ** Function:    NfcAdaptation::signal()
430 **
431 ** Description: signal the CondVar to release the thread that is waiting
432 **
433 ** Returns:     none
434 **
435 *******************************************************************************/
signal()436 void NfcAdaptation::signal() { mCondVar.signal(); }
437 
438 /*******************************************************************************
439 **
440 ** Function:    NfcAdaptation::NFCA_TASK()
441 **
442 ** Description: NFCA_TASK runs the GKI main task
443 **
444 ** Returns:     none
445 **
446 *******************************************************************************/
NFCA_TASK(uint32_t arg)447 uint32_t NfcAdaptation::NFCA_TASK(__attribute__((unused)) uint32_t arg) {
448   const char* func = "NfcAdaptation::NFCA_TASK";
449   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s: enter", func);
450   GKI_run(nullptr);
451   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s: exit", func);
452   return 0;
453 }
454 
455 /*******************************************************************************
456 **
457 ** Function:    NfcAdaptation::Thread()
458 **
459 ** Description: Creates work threads
460 **
461 ** Returns:     none
462 **
463 *******************************************************************************/
Thread(uint32_t arg)464 uint32_t NfcAdaptation::Thread(__attribute__((unused)) uint32_t arg) {
465   const char* func = "NfcAdaptation::Thread";
466   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s: enter", func);
467 
468   {
469     ThreadCondVar CondVar;
470     AutoThreadMutex guard(CondVar);
471     GKI_create_task((TASKPTR)nfc_task, NFC_TASK, (int8_t*)"NFC_TASK", nullptr, 0,
472                     (pthread_cond_t*)CondVar, (pthread_mutex_t*)CondVar);
473     CondVar.wait();
474   }
475 
476   NfcAdaptation::GetInstance().signal();
477 
478   GKI_exit_task(GKI_get_taskid());
479   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s: exit", func);
480   return 0;
481 }
482 
483 /*******************************************************************************
484 **
485 ** Function:    NfcAdaptation::GetHalEntryFuncs()
486 **
487 ** Description: Get the set of HAL entry points.
488 **
489 ** Returns:     Functions pointers for HAL entry points.
490 **
491 *******************************************************************************/
GetHalEntryFuncs()492 tHAL_NFC_ENTRY* NfcAdaptation::GetHalEntryFuncs() { return &mHalEntryFuncs; }
493 
494 /*******************************************************************************
495 **
496 ** Function:    NfcAdaptation::InitializeHalDeviceContext
497 **
498 ** Description: Ask the generic Android HAL to find the Broadcom-specific HAL.
499 **
500 ** Returns:     None.
501 **
502 *******************************************************************************/
InitializeHalDeviceContext()503 void NfcAdaptation::InitializeHalDeviceContext() {
504   const char* func = "NfcAdaptation::InitializeHalDeviceContext";
505 
506   mHalEntryFuncs.initialize = HalInitialize;
507   mHalEntryFuncs.terminate = HalTerminate;
508   mHalEntryFuncs.open = HalOpen;
509   mHalEntryFuncs.close = HalClose;
510   mHalEntryFuncs.core_initialized = HalCoreInitialized;
511   mHalEntryFuncs.write = HalWrite;
512   mHalEntryFuncs.prediscover = HalPrediscover;
513   mHalEntryFuncs.control_granted = HalControlGranted;
514   mHalEntryFuncs.power_cycle = HalPowerCycle;
515   mHalEntryFuncs.get_max_ee = HalGetMaxNfcee;
516   LOG(INFO) << StringPrintf("%s: INfc::getService()", func);
517   mHal = mHal_1_1 = mHal_1_2 = INfcV1_2::getService();
518   if (mHal_1_2 == nullptr) {
519     mHal = mHal_1_1 = INfcV1_1::getService();
520     if (mHal_1_1 == nullptr) {
521       mHal = INfc::getService();
522     }
523   }
524   LOG_FATAL_IF(mHal == nullptr, "Failed to retrieve the NFC HAL!");
525   LOG(INFO) << StringPrintf("%s: INfc::getService() returned %p (%s)", func,
526                             mHal.get(),
527                             (mHal->isRemote() ? "remote" : "local"));
528   if (mHal) {
529     mHal->linkToDeath(mNfcHalDeathRecipient, 0);
530   }
531 }
532 
533 /*******************************************************************************
534 **
535 ** Function:    NfcAdaptation::HalInitialize
536 **
537 ** Description: Not implemented because this function is only needed
538 **              within the HAL.
539 **
540 ** Returns:     None.
541 **
542 *******************************************************************************/
HalInitialize()543 void NfcAdaptation::HalInitialize() {
544   const char* func = "NfcAdaptation::HalInitialize";
545   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s", func);
546 }
547 
548 /*******************************************************************************
549 **
550 ** Function:    NfcAdaptation::HalTerminate
551 **
552 ** Description: Not implemented because this function is only needed
553 **              within the HAL.
554 **
555 ** Returns:     None.
556 **
557 *******************************************************************************/
HalTerminate()558 void NfcAdaptation::HalTerminate() {
559   const char* func = "NfcAdaptation::HalTerminate";
560   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s", func);
561 }
562 
563 /*******************************************************************************
564 **
565 ** Function:    NfcAdaptation::HalOpen
566 **
567 ** Description: Turn on controller, download firmware.
568 **
569 ** Returns:     None.
570 **
571 *******************************************************************************/
HalOpen(tHAL_NFC_CBACK * p_hal_cback,tHAL_NFC_DATA_CBACK * p_data_cback)572 void NfcAdaptation::HalOpen(tHAL_NFC_CBACK* p_hal_cback,
573                             tHAL_NFC_DATA_CBACK* p_data_cback) {
574   const char* func = "NfcAdaptation::HalOpen";
575   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s", func);
576   mCallback = new NfcClientCallback(p_hal_cback, p_data_cback);
577   if (mHal_1_1 != nullptr) {
578     mHal_1_1->open_1_1(mCallback);
579   } else {
580     mHal->open(mCallback);
581   }
582 }
583 
584 /*******************************************************************************
585 **
586 ** Function:    NfcAdaptation::HalClose
587 **
588 ** Description: Turn off controller.
589 **
590 ** Returns:     None.
591 **
592 *******************************************************************************/
HalClose()593 void NfcAdaptation::HalClose() {
594   const char* func = "NfcAdaptation::HalClose";
595   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s", func);
596   mHal->close();
597 }
598 
599 /*******************************************************************************
600 **
601 ** Function:    NfcAdaptation::HalDeviceContextCallback
602 **
603 ** Description: Translate generic Android HAL's callback into Broadcom-specific
604 **              callback function.
605 **
606 ** Returns:     None.
607 **
608 *******************************************************************************/
HalDeviceContextCallback(nfc_event_t event,nfc_status_t event_status)609 void NfcAdaptation::HalDeviceContextCallback(nfc_event_t event,
610                                              nfc_status_t event_status) {
611   const char* func = "NfcAdaptation::HalDeviceContextCallback";
612   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s: event=%u", func, event);
613   if (mHalCallback) mHalCallback(event, (tHAL_NFC_STATUS)event_status);
614 }
615 
616 /*******************************************************************************
617 **
618 ** Function:    NfcAdaptation::HalDeviceContextDataCallback
619 **
620 ** Description: Translate generic Android HAL's callback into Broadcom-specific
621 **              callback function.
622 **
623 ** Returns:     None.
624 **
625 *******************************************************************************/
HalDeviceContextDataCallback(uint16_t data_len,uint8_t * p_data)626 void NfcAdaptation::HalDeviceContextDataCallback(uint16_t data_len,
627                                                  uint8_t* p_data) {
628   const char* func = "NfcAdaptation::HalDeviceContextDataCallback";
629   DLOG_IF(INFO, nfc_debug_enabled)
630       << StringPrintf("%s: len=%u", func, data_len);
631   if (mHalDataCallback) mHalDataCallback(data_len, p_data);
632 }
633 
634 /*******************************************************************************
635 **
636 ** Function:    NfcAdaptation::HalWrite
637 **
638 ** Description: Write NCI message to the controller.
639 **
640 ** Returns:     None.
641 **
642 *******************************************************************************/
HalWrite(uint16_t data_len,uint8_t * p_data)643 void NfcAdaptation::HalWrite(uint16_t data_len, uint8_t* p_data) {
644   const char* func = "NfcAdaptation::HalWrite";
645   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s", func);
646   ::android::hardware::nfc::V1_0::NfcData data;
647   data.setToExternal(p_data, data_len);
648   mHal->write(data);
649 }
650 
651 /*******************************************************************************
652 **
653 ** Function:    NfcAdaptation::HalCoreInitialized
654 **
655 ** Description: Adjust the configurable parameters in the controller.
656 **
657 ** Returns:     None.
658 **
659 *******************************************************************************/
HalCoreInitialized(uint16_t data_len,uint8_t * p_core_init_rsp_params)660 void NfcAdaptation::HalCoreInitialized(uint16_t data_len,
661                                        uint8_t* p_core_init_rsp_params) {
662   const char* func = "NfcAdaptation::HalCoreInitialized";
663   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s", func);
664   hidl_vec<uint8_t> data;
665   data.setToExternal(p_core_init_rsp_params, data_len);
666 
667   mHal->coreInitialized(data);
668 }
669 
670 /*******************************************************************************
671 **
672 ** Function:    NfcAdaptation::HalPrediscover
673 **
674 ** Description:     Perform any vendor-specific pre-discovery actions (if
675 **                  needed) If any actions were performed TRUE will be returned,
676 **                  and HAL_PRE_DISCOVER_CPLT_EVT will notify when actions are
677 **                  completed.
678 **
679 ** Returns:         TRUE if vendor-specific pre-discovery actions initialized
680 **                  FALSE if no vendor-specific pre-discovery actions are
681 **                  needed.
682 **
683 *******************************************************************************/
HalPrediscover()684 bool NfcAdaptation::HalPrediscover() {
685   const char* func = "NfcAdaptation::HalPrediscover";
686   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s", func);
687   bool retval = FALSE;
688   mHal->prediscover();
689   return retval;
690 }
691 
692 /*******************************************************************************
693 **
694 ** Function:        HAL_NfcControlGranted
695 **
696 ** Description:     Grant control to HAL control for sending NCI commands.
697 **                  Call in response to HAL_REQUEST_CONTROL_EVT.
698 **                  Must only be called when there are no NCI commands pending.
699 **                  HAL_RELEASE_CONTROL_EVT will notify when HAL no longer
700 **                  needs control of NCI.
701 **
702 ** Returns:         void
703 **
704 *******************************************************************************/
HalControlGranted()705 void NfcAdaptation::HalControlGranted() {
706   const char* func = "NfcAdaptation::HalControlGranted";
707   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s", func);
708   mHal->controlGranted();
709 }
710 
711 /*******************************************************************************
712 **
713 ** Function:    NfcAdaptation::HalPowerCycle
714 **
715 ** Description: Turn off and turn on the controller.
716 **
717 ** Returns:     None.
718 **
719 *******************************************************************************/
HalPowerCycle()720 void NfcAdaptation::HalPowerCycle() {
721   const char* func = "NfcAdaptation::HalPowerCycle";
722   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s", func);
723   mHal->powerCycle();
724 }
725 
726 /*******************************************************************************
727 **
728 ** Function:    NfcAdaptation::HalGetMaxNfcee
729 **
730 ** Description: Turn off and turn on the controller.
731 **
732 ** Returns:     None.
733 **
734 *******************************************************************************/
HalGetMaxNfcee()735 uint8_t NfcAdaptation::HalGetMaxNfcee() {
736   const char* func = "NfcAdaptation::HalPowerCycle";
737   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s", func);
738 
739   return nfa_ee_max_ee_cfg;
740 }
741 
742 /*******************************************************************************
743 **
744 ** Function:    NfcAdaptation::DownloadFirmware
745 **
746 ** Description: Download firmware patch files.
747 **
748 ** Returns:     None.
749 **
750 *******************************************************************************/
DownloadFirmware()751 bool NfcAdaptation::DownloadFirmware() {
752   const char* func = "NfcAdaptation::DownloadFirmware";
753   isDownloadFirmwareCompleted = false;
754   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s: enter", func);
755   HalInitialize();
756 
757   mHalOpenCompletedEvent.lock();
758   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s: try open HAL", func);
759   HalOpen(HalDownloadFirmwareCallback, HalDownloadFirmwareDataCallback);
760   mHalOpenCompletedEvent.wait();
761 
762   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s: try close HAL", func);
763   HalClose();
764 
765   HalTerminate();
766   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s: exit", func);
767 
768   return isDownloadFirmwareCompleted;
769 }
770 
771 /*******************************************************************************
772 **
773 ** Function:    NfcAdaptation::HalDownloadFirmwareCallback
774 **
775 ** Description: Receive events from the HAL.
776 **
777 ** Returns:     None.
778 **
779 *******************************************************************************/
HalDownloadFirmwareCallback(nfc_event_t event,nfc_status_t event_status)780 void NfcAdaptation::HalDownloadFirmwareCallback(nfc_event_t event,
781                                                 __attribute__((unused))
782                                                 nfc_status_t event_status) {
783   const char* func = "NfcAdaptation::HalDownloadFirmwareCallback";
784   DLOG_IF(INFO, nfc_debug_enabled)
785       << StringPrintf("%s: event=0x%X", func, event);
786   switch (event) {
787     case HAL_NFC_OPEN_CPLT_EVT: {
788       DLOG_IF(INFO, nfc_debug_enabled)
789           << StringPrintf("%s: HAL_NFC_OPEN_CPLT_EVT", func);
790       if (event_status == HAL_NFC_STATUS_OK) isDownloadFirmwareCompleted = true;
791       mHalOpenCompletedEvent.signal();
792       break;
793     }
794     case HAL_NFC_CLOSE_CPLT_EVT: {
795       DLOG_IF(INFO, nfc_debug_enabled)
796           << StringPrintf("%s: HAL_NFC_CLOSE_CPLT_EVT", func);
797       break;
798     }
799   }
800 }
801 
802 /*******************************************************************************
803 **
804 ** Function:    NfcAdaptation::HalDownloadFirmwareDataCallback
805 **
806 ** Description: Receive data events from the HAL.
807 **
808 ** Returns:     None.
809 **
810 *******************************************************************************/
HalDownloadFirmwareDataCallback(uint16_t data_len,uint8_t * p_data)811 void NfcAdaptation::HalDownloadFirmwareDataCallback(__attribute__((unused))
812                                                     uint16_t data_len,
813                                                     __attribute__((unused))
814                                                     uint8_t* p_data) {}
815 
816 /*******************************************************************************
817 **
818 ** Function:    ThreadMutex::ThreadMutex()
819 **
820 ** Description: class constructor
821 **
822 ** Returns:     none
823 **
824 *******************************************************************************/
ThreadMutex()825 ThreadMutex::ThreadMutex() {
826   pthread_mutexattr_t mutexAttr;
827 
828   pthread_mutexattr_init(&mutexAttr);
829   pthread_mutex_init(&mMutex, &mutexAttr);
830   pthread_mutexattr_destroy(&mutexAttr);
831 }
832 
833 /*******************************************************************************
834 **
835 ** Function:    ThreadMutex::~ThreadMutex()
836 **
837 ** Description: class destructor
838 **
839 ** Returns:     none
840 **
841 *******************************************************************************/
~ThreadMutex()842 ThreadMutex::~ThreadMutex() { pthread_mutex_destroy(&mMutex); }
843 
844 /*******************************************************************************
845 **
846 ** Function:    ThreadMutex::lock()
847 **
848 ** Description: lock kthe mutex
849 **
850 ** Returns:     none
851 **
852 *******************************************************************************/
lock()853 void ThreadMutex::lock() { pthread_mutex_lock(&mMutex); }
854 
855 /*******************************************************************************
856 **
857 ** Function:    ThreadMutex::unblock()
858 **
859 ** Description: unlock the mutex
860 **
861 ** Returns:     none
862 **
863 *******************************************************************************/
unlock()864 void ThreadMutex::unlock() { pthread_mutex_unlock(&mMutex); }
865 
866 /*******************************************************************************
867 **
868 ** Function:    ThreadCondVar::ThreadCondVar()
869 **
870 ** Description: class constructor
871 **
872 ** Returns:     none
873 **
874 *******************************************************************************/
ThreadCondVar()875 ThreadCondVar::ThreadCondVar() {
876   pthread_condattr_t CondAttr;
877 
878   pthread_condattr_init(&CondAttr);
879   pthread_cond_init(&mCondVar, &CondAttr);
880 
881   pthread_condattr_destroy(&CondAttr);
882 }
883 
884 /*******************************************************************************
885 **
886 ** Function:    ThreadCondVar::~ThreadCondVar()
887 **
888 ** Description: class destructor
889 **
890 ** Returns:     none
891 **
892 *******************************************************************************/
~ThreadCondVar()893 ThreadCondVar::~ThreadCondVar() { pthread_cond_destroy(&mCondVar); }
894 
895 /*******************************************************************************
896 **
897 ** Function:    ThreadCondVar::wait()
898 **
899 ** Description: wait on the mCondVar
900 **
901 ** Returns:     none
902 **
903 *******************************************************************************/
wait()904 void ThreadCondVar::wait() {
905   pthread_cond_wait(&mCondVar, *this);
906   pthread_mutex_unlock(*this);
907 }
908 
909 /*******************************************************************************
910 **
911 ** Function:    ThreadCondVar::signal()
912 **
913 ** Description: signal the mCondVar
914 **
915 ** Returns:     none
916 **
917 *******************************************************************************/
signal()918 void ThreadCondVar::signal() {
919   AutoThreadMutex a(*this);
920   pthread_cond_signal(&mCondVar);
921 }
922 
923 /*******************************************************************************
924 **
925 ** Function:    AutoThreadMutex::AutoThreadMutex()
926 **
927 ** Description: class constructor, automatically lock the mutex
928 **
929 ** Returns:     none
930 **
931 *******************************************************************************/
AutoThreadMutex(ThreadMutex & m)932 AutoThreadMutex::AutoThreadMutex(ThreadMutex& m) : mm(m) { mm.lock(); }
933 
934 /*******************************************************************************
935 **
936 ** Function:    AutoThreadMutex::~AutoThreadMutex()
937 **
938 ** Description: class destructor, automatically unlock the mutex
939 **
940 ** Returns:     none
941 **
942 *******************************************************************************/
~AutoThreadMutex()943 AutoThreadMutex::~AutoThreadMutex() { mm.unlock(); }
944