1 /******************************************************************************
2  *
3  *  Copyright (C) 2010-2014 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 
19 /******************************************************************************
20  *
21  *  This file contains functions that interface with the NFC NCI transport.
22  *  On the receive side, it routes events to the appropriate handler
23  *  (callback). On the transmit side, it manages the command transmission.
24  *
25  ******************************************************************************/
26 #include <string.h>
27 
28 #include <android-base/stringprintf.h>
29 #include <android/hardware/nfc/1.1/types.h>
30 #include <base/logging.h>
31 
32 #include "nfc_target.h"
33 
34 #include "bt_types.h"
35 #include "ce_int.h"
36 #include "gki.h"
37 #include "nci_hmsgs.h"
38 #include "nfc_int.h"
39 #include "rw_int.h"
40 
41 #if (NFC_RW_ONLY == FALSE)
42 
43 #include "llcp_int.h"
44 
45 /* NFC mandates support for at least one logical connection;
46  * Update max_conn to the NFCC capability on InitRsp */
47 #define NFC_SET_MAX_CONN_DEFAULT() \
48   { nfc_cb.max_conn = 1; }
49 
50 #else /* NFC_RW_ONLY */
51 #define ce_init()
52 #define llcp_init()
53 
54 #define NFC_SET_MAX_CONN_DEFAULT()
55 
56 #endif /* NFC_RW_ONLY */
57 
58 using android::base::StringPrintf;
59 using android::hardware::nfc::V1_1::NfcEvent;
60 
61 extern bool nfc_debug_enabled;
62 extern void delete_stack_non_volatile_store(bool forceDelete);
63 
64 /****************************************************************************
65 ** Declarations
66 ****************************************************************************/
67 tNFC_CB nfc_cb;
68 
69 #if (NFC_RW_ONLY == FALSE)
70 #define NFC_NUM_INTERFACE_MAP 2
71 #else
72 #define NFC_NUM_INTERFACE_MAP 1
73 #endif
74 
75 static const tNCI_DISCOVER_MAPS nfc_interface_mapping[NFC_NUM_INTERFACE_MAP] = {
76     /* Protocols that use Frame Interface do not need to be included in the
77        interface mapping */
78     {NCI_PROTOCOL_ISO_DEP, NCI_INTERFACE_MODE_POLL_N_LISTEN,
79      NCI_INTERFACE_ISO_DEP}
80 #if (NFC_RW_ONLY == FALSE)
81     ,
82     /* this can not be set here due to 2079xB0 NFCC issues */
83     {NCI_PROTOCOL_NFC_DEP, NCI_INTERFACE_MODE_POLL_N_LISTEN,
84      NCI_INTERFACE_NFC_DEP}
85 #endif
86 };
87 
88 /*******************************************************************************
89 **
90 ** Function         nfc_state_name
91 **
92 ** Description      This function returns the state name.
93 **
94 ** NOTE             conditionally compiled to save memory.
95 **
96 ** Returns          pointer to the name
97 **
98 *******************************************************************************/
nfc_state_name(uint8_t state)99 static std::string nfc_state_name(uint8_t state) {
100   switch (state) {
101     case NFC_STATE_NONE:
102       return "NONE";
103     case NFC_STATE_W4_HAL_OPEN:
104       return "W4_HAL_OPEN";
105     case NFC_STATE_CORE_INIT:
106       return "CORE_INIT";
107     case NFC_STATE_W4_POST_INIT_CPLT:
108       return "W4_POST_INIT_CPLT";
109     case NFC_STATE_IDLE:
110       return "IDLE";
111     case NFC_STATE_OPEN:
112       return "OPEN";
113     case NFC_STATE_CLOSING:
114       return "CLOSING";
115     case NFC_STATE_W4_HAL_CLOSE:
116       return "W4_HAL_CLOSE";
117     case NFC_STATE_NFCC_POWER_OFF_SLEEP:
118       return "NFCC_POWER_OFF_SLEEP";
119     default:
120       return "???? UNKNOWN STATE";
121   }
122 }
123 
124 /*******************************************************************************
125 **
126 ** Function         nfc_hal_event_name
127 **
128 ** Description      This function returns the HAL event name.
129 **
130 ** NOTE             conditionally compiled to save memory.
131 **
132 ** Returns          pointer to the name
133 **
134 *******************************************************************************/
nfc_hal_event_name(uint8_t event)135 static std::string nfc_hal_event_name(uint8_t event) {
136   switch (event) {
137     case HAL_NFC_OPEN_CPLT_EVT:
138       return "HAL_NFC_OPEN_CPLT_EVT";
139     case HAL_NFC_CLOSE_CPLT_EVT:
140       return "HAL_NFC_CLOSE_CPLT_EVT";
141     case HAL_NFC_POST_INIT_CPLT_EVT:
142       return "HAL_NFC_POST_INIT_CPLT_EVT";
143     case HAL_NFC_PRE_DISCOVER_CPLT_EVT:
144       return "HAL_NFC_PRE_DISCOVER_CPLT_EVT";
145     case HAL_NFC_REQUEST_CONTROL_EVT:
146       return "HAL_NFC_REQUEST_CONTROL_EVT";
147     case HAL_NFC_RELEASE_CONTROL_EVT:
148       return "HAL_NFC_RELEASE_CONTROL_EVT";
149     case HAL_NFC_ERROR_EVT:
150       return "HAL_NFC_ERROR_EVT";
151     case (uint32_t)NfcEvent::HCI_NETWORK_RESET:
152       return "HCI_NETWORK_RESET";
153     default:
154       return "???? UNKNOWN EVENT";
155   }
156 }
157 
158 /*******************************************************************************
159 **
160 ** Function         nfc_main_notify_enable_status
161 **
162 ** Description      Notify status of Enable/PowerOffSleep/PowerCycle
163 **
164 *******************************************************************************/
nfc_main_notify_enable_status(tNFC_STATUS nfc_status)165 static void nfc_main_notify_enable_status(tNFC_STATUS nfc_status) {
166   tNFC_RESPONSE evt_data;
167 
168   evt_data.status = nfc_status;
169 
170   if (nfc_cb.p_resp_cback) {
171     /* if getting out of PowerOffSleep mode or restarting NFCC */
172     if (nfc_cb.flags & (NFC_FL_RESTARTING | NFC_FL_POWER_CYCLE_NFCC)) {
173       nfc_cb.flags &= ~(NFC_FL_RESTARTING | NFC_FL_POWER_CYCLE_NFCC);
174       if (nfc_status != NFC_STATUS_OK) {
175         nfc_cb.flags |= NFC_FL_POWER_OFF_SLEEP;
176       }
177       (*nfc_cb.p_resp_cback)(NFC_NFCC_RESTART_REVT, &evt_data);
178     } else {
179       (*nfc_cb.p_resp_cback)(NFC_ENABLE_REVT, &evt_data);
180     }
181   }
182 }
183 
184 /*******************************************************************************
185 **
186 ** Function         nfc_enabled
187 **
188 ** Description      NFCC enabled, proceed with stack start up.
189 **
190 ** Returns          void
191 **
192 *******************************************************************************/
nfc_enabled(tNFC_STATUS nfc_status,NFC_HDR * p_init_rsp_msg)193 void nfc_enabled(tNFC_STATUS nfc_status, NFC_HDR* p_init_rsp_msg) {
194   tNFC_RESPONSE evt_data;
195   tNFC_CONN_CB* p_cb = &nfc_cb.conn_cb[NFC_RF_CONN_ID];
196   int16_t lremain = 0;
197   uint8_t* p;
198   uint8_t num_interfaces = 0, xx;
199   uint8_t num_interface_extensions = 0, zz;
200   uint8_t interface_type;
201   int yy = 0;
202   memset(&evt_data, 0, sizeof(tNFC_RESPONSE));
203 
204   if (nfc_status == NCI_STATUS_OK) {
205     nfc_set_state(NFC_STATE_IDLE);
206 
207     p = (uint8_t*)(p_init_rsp_msg + 1) + p_init_rsp_msg->offset +
208         NCI_MSG_HDR_SIZE + 1;
209 
210     lremain = p_init_rsp_msg->len - NCI_MSG_HDR_SIZE - 1 - sizeof(uint32_t) - 5;
211     if (lremain < 0) {
212       nfc_status = NCI_STATUS_FAILED;
213       goto plen_err;
214     }
215     /* we currently only support NCI of the same version.
216     * We may need to change this, when we support multiple version of NFCC */
217 
218     evt_data.enable.nci_version = nfc_cb.nci_version;
219     STREAM_TO_UINT32(evt_data.enable.nci_features, p);
220     if (nfc_cb.nci_version == NCI_VERSION_1_0) {
221       /* this byte is consumed in the top expression */
222       STREAM_TO_UINT8(num_interfaces, p);
223       lremain -= num_interfaces;
224       if (lremain < 0) {
225         nfc_status = NCI_STATUS_FAILED;
226         goto plen_err;
227       }
228       evt_data.enable.nci_interfaces = 0;
229       for (xx = 0; xx < num_interfaces; xx++) {
230         if ((*p) <= NCI_INTERFACE_MAX)
231           evt_data.enable.nci_interfaces |= (1 << (*p));
232         else if (((*p) >= NCI_INTERFACE_FIRST_VS) &&
233                  (yy < NFC_NFCC_MAX_NUM_VS_INTERFACE)) {
234           /* save the VS RF interface in control block, if there's still room */
235           nfc_cb.vs_interface[yy++] = *p;
236         }
237         p++;
238       }
239       nfc_cb.nci_interfaces = evt_data.enable.nci_interfaces;
240       memcpy(evt_data.enable.vs_interface, nfc_cb.vs_interface,
241              NFC_NFCC_MAX_NUM_VS_INTERFACE);
242     }
243     /* four bytes below are consumed in the top expression */
244     evt_data.enable.max_conn = *p++;
245     STREAM_TO_UINT16(evt_data.enable.max_ce_table, p);
246 #if (NFC_RW_ONLY == FALSE)
247     nfc_cb.max_ce_table = evt_data.enable.max_ce_table;
248     nfc_cb.nci_features = evt_data.enable.nci_features;
249     nfc_cb.max_conn = evt_data.enable.max_conn;
250 #endif
251     nfc_cb.nci_ctrl_size = *p++; /* Max Control Packet Payload Length */
252     p_cb->init_credits = p_cb->num_buff = 0;
253     nfc_set_conn_id(p_cb, NFC_RF_CONN_ID);
254     if (nfc_cb.nci_version == NCI_VERSION_2_0) {
255       /* one byte is consumed in the top expression and
256        * 3 bytes from uit16+uint8 below */
257       lremain -= 4;
258       if (lremain < 0) {
259         nfc_status = NCI_STATUS_FAILED;
260         goto plen_err;
261       }
262       if (evt_data.enable.nci_features & NCI_FEAT_HCI_NETWORK) {
263         p_cb = &nfc_cb.conn_cb[NFC_HCI_CONN_ID];
264         nfc_set_conn_id(p_cb, NFC_HCI_CONN_ID);
265         p_cb->id = NFC_HCI_CONN_ID;
266         STREAM_TO_UINT8(p_cb->buff_size, p);
267         STREAM_TO_UINT8(p_cb->num_buff, p);
268         p_cb->init_credits = p_cb->num_buff;
269         evt_data.enable.hci_packet_size = p_cb->buff_size;
270         evt_data.enable.hci_conn_credits = p_cb->init_credits;
271         DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf(
272             "hci num_buf=%d buf_size=%d", p_cb->num_buff, p_cb->buff_size);
273       } else {
274         /*HCI n/w not enabled skip data buff size and data credit HCI conn */
275         p += 2;
276       }
277       STREAM_TO_UINT16(evt_data.enable.max_nfc_v_size, p);
278       STREAM_TO_UINT8(num_interfaces, p);
279 #if (NFC_RW_ONLY == FALSE)
280       nfc_cb.hci_packet_size = evt_data.enable.hci_packet_size;
281       nfc_cb.hci_conn_credits = evt_data.enable.hci_conn_credits;
282       nfc_cb.nci_max_v_size = evt_data.enable.max_nfc_v_size;
283 #endif
284       evt_data.enable.nci_interfaces = 0;
285 
286       for (xx = 0; xx < num_interfaces; xx++) {
287         lremain -= 2;
288         if (lremain < 0) {
289           nfc_status = NCI_STATUS_FAILED;
290           goto plen_err;
291         }
292         if ((*p) <= NCI_INTERFACE_MAX)
293           evt_data.enable.nci_interfaces |= (1 << (*p));
294         else if (((*p) >= NCI_INTERFACE_FIRST_VS) &&
295                  (yy < NFC_NFCC_MAX_NUM_VS_INTERFACE)) {
296           /* save the VS RF interface in control block, if there's still room */
297           nfc_cb.vs_interface[yy++] = *p;
298         }
299         interface_type = *p++;
300         num_interface_extensions = *p++;
301         lremain -= num_interface_extensions;
302         if (lremain < 0) {
303           nfc_status = NCI_STATUS_FAILED;
304           goto plen_err;
305         }
306         for (zz = 0; zz < num_interface_extensions; zz++) {
307           if (((*p) < NCI_INTERFACE_EXTENSION_MAX) &&
308               (interface_type <= NCI_INTERFACE_MAX)) {
309             nfc_cb.nci_intf_extensions |= (1 << (*p));
310             nfc_cb.nci_intf_extension_map[*p] = (1 << interface_type);
311           }
312           p++;
313         }
314       }
315 
316       nfc_cb.nci_interfaces = evt_data.enable.nci_interfaces;
317       memcpy(evt_data.enable.vs_interface, nfc_cb.vs_interface,
318              NFC_NFCC_MAX_NUM_VS_INTERFACE);
319     } else {
320       /* For VERSION_UNKNOWN one byte is consumed in the top expression */
321       lremain -= sizeof(uint16_t) + NFC_NFCC_INFO_LEN +
322                  (nfc_cb.nci_version == NCI_VERSION_1_0 ? 1 : 0);
323       if (lremain < 0) {
324         nfc_status = NCI_STATUS_FAILED;
325         goto plen_err;
326       }
327       STREAM_TO_UINT16(evt_data.enable.max_param_size, p);
328       evt_data.enable.manufacture_id = *p++;
329       STREAM_TO_ARRAY(evt_data.enable.nfcc_info, p, NFC_NFCC_INFO_LEN);
330     }
331     NFC_DiscoveryMap(nfc_cb.num_disc_maps,
332                      (tNCI_DISCOVER_MAPS*)nfc_cb.p_disc_maps, nullptr);
333   }
334   /* else not successful. the buffers will be freed in nfc_free_conn_cb () */
335   else {
336   plen_err:
337     if (nfc_cb.flags & NFC_FL_RESTARTING) {
338       nfc_set_state(NFC_STATE_NFCC_POWER_OFF_SLEEP);
339     } else {
340       nfc_free_conn_cb(p_cb);
341 
342       /* if NFCC didn't respond to CORE_RESET or CORE_INIT */
343       if (nfc_cb.nfc_state == NFC_STATE_CORE_INIT) {
344         /* report status after closing HAL */
345         nfc_cb.p_hal->close();
346         return;
347       } else
348         nfc_set_state(NFC_STATE_NONE);
349     }
350   }
351 
352   nfc_main_notify_enable_status(nfc_status);
353 }
354 
355 /*******************************************************************************
356 **
357 ** Function         nfc_set_state
358 **
359 ** Description      Set the state of NFC stack
360 **
361 ** Returns          void
362 **
363 *******************************************************************************/
nfc_set_state(tNFC_STATE nfc_state)364 void nfc_set_state(tNFC_STATE nfc_state) {
365   DLOG_IF(INFO, nfc_debug_enabled)
366       << StringPrintf("nfc_set_state %d (%s)->%d (%s)", nfc_cb.nfc_state,
367                       nfc_state_name(nfc_cb.nfc_state).c_str(), nfc_state,
368                       nfc_state_name(nfc_state).c_str());
369   nfc_cb.nfc_state = nfc_state;
370 }
371 
372 /*******************************************************************************
373 **
374 ** Function         nfc_gen_cleanup
375 **
376 ** Description      Clean up for both going into low power mode and disabling
377 **                  NFC
378 **
379 *******************************************************************************/
nfc_gen_cleanup(void)380 void nfc_gen_cleanup(void) {
381   nfc_cb.flags &= ~NFC_FL_DEACTIVATING;
382 
383   /* the HAL pre-discover is still active - clear the pending flag/free the
384    * buffer */
385   if (nfc_cb.flags & NFC_FL_DISCOVER_PENDING) {
386     nfc_cb.flags &= ~NFC_FL_DISCOVER_PENDING;
387     GKI_freebuf(nfc_cb.p_disc_pending);
388     nfc_cb.p_disc_pending = nullptr;
389   }
390 
391   nfc_cb.flags &= ~(NFC_FL_CONTROL_REQUESTED | NFC_FL_CONTROL_GRANTED |
392                     NFC_FL_HAL_REQUESTED);
393 
394   nfc_stop_timer(&nfc_cb.deactivate_timer);
395 
396   /* Reset the connection control blocks */
397   nfc_reset_all_conn_cbs();
398 
399   if (nfc_cb.p_nci_init_rsp) {
400     GKI_freebuf(nfc_cb.p_nci_init_rsp);
401     nfc_cb.p_nci_init_rsp = nullptr;
402   }
403 
404   /* clear any pending CMD/RSP */
405   nfc_main_flush_cmd_queue();
406 }
407 
408 /*******************************************************************************
409 **
410 ** Function         nfc_main_handle_hal_evt
411 **
412 ** Description      Handle BT_EVT_TO_NFC_MSGS
413 **
414 *******************************************************************************/
nfc_main_handle_hal_evt(tNFC_HAL_EVT_MSG * p_msg)415 void nfc_main_handle_hal_evt(tNFC_HAL_EVT_MSG* p_msg) {
416   uint8_t* ps;
417 
418   DLOG_IF(INFO, nfc_debug_enabled)
419       << StringPrintf("HAL event=0x%x", p_msg->hal_evt);
420 
421   switch (p_msg->hal_evt) {
422     case HAL_NFC_OPEN_CPLT_EVT: /* only for failure case */
423       nfc_enabled(NFC_STATUS_FAILED, nullptr);
424       break;
425 
426     case HAL_NFC_CLOSE_CPLT_EVT:
427       if (nfc_cb.p_resp_cback) {
428         if (nfc_cb.nfc_state == NFC_STATE_W4_HAL_CLOSE) {
429           if (nfc_cb.flags & NFC_FL_POWER_OFF_SLEEP) {
430             nfc_cb.flags &= ~NFC_FL_POWER_OFF_SLEEP;
431             nfc_set_state(NFC_STATE_NFCC_POWER_OFF_SLEEP);
432             (*nfc_cb.p_resp_cback)(NFC_NFCC_POWER_OFF_REVT, nullptr);
433           } else {
434             nfc_set_state(NFC_STATE_NONE);
435             (*nfc_cb.p_resp_cback)(NFC_DISABLE_REVT, nullptr);
436             nfc_cb.p_resp_cback = nullptr;
437           }
438         } else {
439           /* found error during initialization */
440           nfc_set_state(NFC_STATE_NONE);
441           nfc_main_notify_enable_status(NFC_STATUS_FAILED);
442         }
443       }
444       break;
445 
446     case HAL_NFC_POST_INIT_CPLT_EVT:
447       if (nfc_cb.p_nci_init_rsp) {
448         /*
449         ** if NFC_Disable() is called before receiving
450         ** HAL_NFC_POST_INIT_CPLT_EVT, then wait for HAL_NFC_CLOSE_CPLT_EVT.
451         */
452         if (nfc_cb.nfc_state == NFC_STATE_W4_POST_INIT_CPLT) {
453           if (p_msg->status == HAL_NFC_STATUS_OK) {
454             nfc_enabled(NCI_STATUS_OK, nfc_cb.p_nci_init_rsp);
455           } else /* if post initailization failed */
456           {
457             nfc_enabled(NCI_STATUS_FAILED, nullptr);
458           }
459         }
460 
461         GKI_freebuf(nfc_cb.p_nci_init_rsp);
462         nfc_cb.p_nci_init_rsp = nullptr;
463       }
464       break;
465 
466     case HAL_NFC_PRE_DISCOVER_CPLT_EVT:
467       /* restore the command window, no matter if the discover command is still
468        * pending */
469       nfc_cb.nci_cmd_window = NCI_MAX_CMD_WINDOW;
470       nfc_cb.flags &= ~NFC_FL_CONTROL_GRANTED;
471       if (nfc_cb.flags & NFC_FL_DISCOVER_PENDING) {
472         /* issue the discovery command now, if it is still pending */
473         nfc_cb.flags &= ~NFC_FL_DISCOVER_PENDING;
474         ps = (uint8_t*)nfc_cb.p_disc_pending;
475         nci_snd_discover_cmd(*ps, (tNFC_DISCOVER_PARAMS*)(ps + 1));
476         GKI_freebuf(nfc_cb.p_disc_pending);
477         nfc_cb.p_disc_pending = nullptr;
478       } else {
479         /* check if there's other pending commands */
480         nfc_ncif_check_cmd_queue(nullptr);
481       }
482 
483       if (p_msg->status == HAL_NFC_STATUS_ERR_CMD_TIMEOUT)
484         nfc_ncif_event_status(NFC_NFCC_TIMEOUT_REVT, NFC_STATUS_HW_TIMEOUT);
485       break;
486 
487     case HAL_NFC_REQUEST_CONTROL_EVT:
488       nfc_cb.flags |= NFC_FL_CONTROL_REQUESTED;
489       nfc_cb.flags |= NFC_FL_HAL_REQUESTED;
490       nfc_ncif_check_cmd_queue(nullptr);
491       break;
492 
493     case HAL_NFC_RELEASE_CONTROL_EVT:
494       if (nfc_cb.flags & NFC_FL_CONTROL_GRANTED) {
495         nfc_cb.flags &= ~NFC_FL_CONTROL_GRANTED;
496         nfc_cb.nci_cmd_window = NCI_MAX_CMD_WINDOW;
497         nfc_ncif_check_cmd_queue(nullptr);
498 
499         if (p_msg->status == HAL_NFC_STATUS_ERR_CMD_TIMEOUT)
500           nfc_ncif_event_status(NFC_NFCC_TIMEOUT_REVT, NFC_STATUS_HW_TIMEOUT);
501       }
502       break;
503 
504     case HAL_NFC_ERROR_EVT:
505       switch (p_msg->status) {
506         case HAL_NFC_STATUS_ERR_TRANSPORT:
507           /* Notify app of transport error */
508           if (nfc_cb.p_resp_cback) {
509             (*nfc_cb.p_resp_cback)(NFC_NFCC_TRANSPORT_ERR_REVT, nullptr);
510 
511             /* if enabling NFC, notify upper layer of failure after closing HAL
512              */
513             if (nfc_cb.nfc_state < NFC_STATE_IDLE) {
514               nfc_enabled(NFC_STATUS_FAILED, nullptr);
515             }
516           }
517           break;
518 
519         case HAL_NFC_STATUS_ERR_CMD_TIMEOUT:
520           nfc_ncif_event_status(NFC_NFCC_TIMEOUT_REVT, NFC_STATUS_HW_TIMEOUT);
521 
522           /* if enabling NFC, notify upper layer of failure after closing HAL */
523           if (nfc_cb.nfc_state < NFC_STATE_IDLE) {
524             nfc_enabled(NFC_STATUS_FAILED, nullptr);
525             return;
526           }
527           break;
528 
529         case (uint32_t)NfcEvent::HCI_NETWORK_RESET:
530           delete_stack_non_volatile_store(true);
531           break;
532 
533         default:
534           break;
535       }
536       break;
537 
538     default:
539       LOG(ERROR) << StringPrintf("unhandled event (0x%x).", p_msg->hal_evt);
540       break;
541   }
542 }
543 
544 /*******************************************************************************
545 **
546 ** Function         nfc_main_flush_cmd_queue
547 **
548 ** Description      This function is called when setting power off sleep state.
549 **
550 ** Returns          void
551 **
552 *******************************************************************************/
nfc_main_flush_cmd_queue(void)553 void nfc_main_flush_cmd_queue(void) {
554   NFC_HDR* p_msg;
555 
556   DLOG_IF(INFO, nfc_debug_enabled) << __func__;
557 
558   /* initialize command window */
559   nfc_cb.nci_cmd_window = NCI_MAX_CMD_WINDOW;
560 
561   /* Stop command-pending timer */
562   nfc_stop_timer(&nfc_cb.nci_wait_rsp_timer);
563 
564   /* dequeue and free buffer */
565   while ((p_msg = (NFC_HDR*)GKI_dequeue(&nfc_cb.nci_cmd_xmit_q)) != nullptr) {
566     GKI_freebuf(p_msg);
567   }
568 }
569 
570 /*******************************************************************************
571 **
572 ** Function         nfc_main_post_hal_evt
573 **
574 ** Description      This function posts HAL event to NFC_TASK
575 **
576 ** Returns          void
577 **
578 *******************************************************************************/
nfc_main_post_hal_evt(uint8_t hal_evt,tHAL_NFC_STATUS status)579 void nfc_main_post_hal_evt(uint8_t hal_evt, tHAL_NFC_STATUS status) {
580   tNFC_HAL_EVT_MSG* p_msg;
581 
582   p_msg = (tNFC_HAL_EVT_MSG*)GKI_getbuf(sizeof(tNFC_HAL_EVT_MSG));
583   if (p_msg != nullptr) {
584     /* Initialize NFC_HDR */
585     p_msg->hdr.len = 0;
586     p_msg->hdr.event = BT_EVT_TO_NFC_MSGS;
587     p_msg->hdr.offset = 0;
588     p_msg->hdr.layer_specific = 0;
589     p_msg->hal_evt = hal_evt;
590     p_msg->status = status;
591     GKI_send_msg(NFC_TASK, NFC_MBOX_ID, p_msg);
592   } else {
593     LOG(ERROR) << StringPrintf("No buffer");
594   }
595 }
596 
597 /*******************************************************************************
598 **
599 ** Function         nfc_main_hal_cback
600 **
601 ** Description      HAL event handler
602 **
603 ** Returns          void
604 **
605 *******************************************************************************/
nfc_main_hal_cback(uint8_t event,tHAL_NFC_STATUS status)606 static void nfc_main_hal_cback(uint8_t event, tHAL_NFC_STATUS status) {
607   DLOG_IF(INFO, nfc_debug_enabled)
608       << StringPrintf("nfc_main_hal_cback event: %s(0x%x), status=%d",
609                       nfc_hal_event_name(event).c_str(), event, status);
610 
611   switch (event) {
612     case HAL_NFC_OPEN_CPLT_EVT:
613       /*
614       ** if NFC_Disable() is called before receiving HAL_NFC_OPEN_CPLT_EVT,
615       ** then wait for HAL_NFC_CLOSE_CPLT_EVT.
616       */
617       if (nfc_cb.nfc_state == NFC_STATE_W4_HAL_OPEN) {
618         if (status == HAL_NFC_STATUS_OK) {
619           /* Notify NFC_TASK that NCI tranport is initialized */
620           GKI_send_event(NFC_TASK, NFC_TASK_EVT_TRANSPORT_READY);
621         } else {
622           nfc_main_post_hal_evt(event, status);
623         }
624       }
625       break;
626 
627     case HAL_NFC_CLOSE_CPLT_EVT:
628     case HAL_NFC_POST_INIT_CPLT_EVT:
629     case HAL_NFC_PRE_DISCOVER_CPLT_EVT:
630     case HAL_NFC_REQUEST_CONTROL_EVT:
631     case HAL_NFC_RELEASE_CONTROL_EVT:
632     case HAL_NFC_ERROR_EVT:
633     case (uint32_t)NfcEvent::HCI_NETWORK_RESET:
634       nfc_main_post_hal_evt(event, status);
635       break;
636 
637     default:
638       DLOG_IF(INFO, nfc_debug_enabled)
639           << StringPrintf("nfc_main_hal_cback unhandled event %x", event);
640       break;
641   }
642 }
643 
644 /*******************************************************************************
645 **
646 ** Function         nfc_main_hal_data_cback
647 **
648 ** Description      HAL data event handler
649 **
650 ** Returns          void
651 **
652 *******************************************************************************/
nfc_main_hal_data_cback(uint16_t data_len,uint8_t * p_data)653 static void nfc_main_hal_data_cback(uint16_t data_len, uint8_t* p_data) {
654   NFC_HDR* p_msg;
655 
656   /* ignore all data while shutting down NFCC */
657   if (nfc_cb.nfc_state == NFC_STATE_W4_HAL_CLOSE) {
658     return;
659   }
660 
661   if (p_data) {
662 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
663     // GKI_getpoolbuf returns a fixed size of memory buffer, which is usually
664     // bigger than NFC packets. This may hide OOB issues.
665     p_msg = (NFC_HDR*)GKI_getbuf(sizeof(NFC_HDR) + NFC_RECEIVE_MSGS_OFFSET +
666                                  data_len);
667 #else
668     p_msg = (NFC_HDR*)GKI_getpoolbuf(NFC_NCI_POOL_ID);
669 #endif
670     if (p_msg != nullptr) {
671       /* Initialize NFC_HDR */
672       p_msg->len = data_len;
673       p_msg->event = BT_EVT_TO_NFC_NCI;
674       p_msg->offset = NFC_RECEIVE_MSGS_OFFSET;
675 
676       /* no need to check length, it always less than pool size */
677       memcpy((uint8_t*)(p_msg + 1) + p_msg->offset, p_data, p_msg->len);
678 
679       GKI_send_msg(NFC_TASK, NFC_MBOX_ID, p_msg);
680     } else {
681       LOG(ERROR) << StringPrintf("No buffer");
682     }
683   }
684 }
685 
686 /*******************************************************************************
687 **
688 ** Function         NFC_Enable
689 **
690 ** Description      This function enables NFC. Prior to calling NFC_Enable:
691 **                  - the NFCC must be powered up, and ready to receive
692 **                    commands.
693 **                  - GKI must be enabled
694 **                  - NFC_TASK must be started
695 **                  - NCIT_TASK must be started (if using dedicated NCI
696 **                    transport)
697 **
698 **                  This function opens the NCI transport (if applicable),
699 **                  resets the NFC controller, and initializes the NFC
700 **                  subsystems.
701 **
702 **                  When the NFC startup procedure is completed, an
703 **                  NFC_ENABLE_REVT is returned to the application using the
704 **                  tNFC_RESPONSE_CBACK.
705 **
706 ** Returns          tNFC_STATUS
707 **
708 *******************************************************************************/
NFC_Enable(tNFC_RESPONSE_CBACK * p_cback)709 tNFC_STATUS NFC_Enable(tNFC_RESPONSE_CBACK* p_cback) {
710   DLOG_IF(INFO, nfc_debug_enabled) << __func__;
711 
712   /* Validate callback */
713   if (!p_cback) {
714     return (NFC_STATUS_INVALID_PARAM);
715   }
716   nfc_cb.p_resp_cback = p_cback;
717 
718   /* Open HAL transport. */
719   nfc_set_state(NFC_STATE_W4_HAL_OPEN);
720   nfc_cb.p_hal->open(nfc_main_hal_cback, nfc_main_hal_data_cback);
721 
722   return (NFC_STATUS_OK);
723 }
724 
725 /*******************************************************************************
726 **
727 ** Function         NFC_Disable
728 **
729 ** Description      This function performs clean up routines for shutting down
730 **                  NFC and closes the NCI transport (if using dedicated NCI
731 **                  transport).
732 **
733 **                  When the NFC shutdown procedure is completed, an
734 **                  NFC_DISABLED_REVT is returned to the application using the
735 **                  tNFC_RESPONSE_CBACK.
736 **
737 ** Returns          nothing
738 **
739 *******************************************************************************/
NFC_Disable(void)740 void NFC_Disable(void) {
741   DLOG_IF(INFO, nfc_debug_enabled)
742       << StringPrintf("nfc_state = %d", nfc_cb.nfc_state);
743 
744   if ((nfc_cb.nfc_state == NFC_STATE_NONE) ||
745       (nfc_cb.nfc_state == NFC_STATE_NFCC_POWER_OFF_SLEEP)) {
746     nfc_set_state(NFC_STATE_NONE);
747     if (nfc_cb.p_resp_cback) {
748       (*nfc_cb.p_resp_cback)(NFC_DISABLE_REVT, nullptr);
749       nfc_cb.p_resp_cback = nullptr;
750     }
751     return;
752   }
753 
754   /* Close transport and clean up */
755   nfc_task_shutdown_nfcc();
756 }
757 
758 /*******************************************************************************
759 **
760 ** Function         NFC_Init
761 **
762 ** Description      This function initializes control block for NFC
763 **
764 ** Returns          nothing
765 **
766 *******************************************************************************/
NFC_Init(tHAL_NFC_ENTRY * p_hal_entry_tbl)767 void NFC_Init(tHAL_NFC_ENTRY* p_hal_entry_tbl) {
768   int xx;
769 
770   /* Clear nfc control block */
771   memset(&nfc_cb, 0, sizeof(tNFC_CB));
772 
773   /* Reset the nfc control block */
774   for (xx = 0; xx < NCI_MAX_CONN_CBS; xx++) {
775     nfc_cb.conn_cb[xx].conn_id = NFC_ILLEGAL_CONN_ID;
776   }
777 
778   /* NCI init */
779   nfc_cb.p_hal = p_hal_entry_tbl;
780   nfc_cb.nfc_state = NFC_STATE_NONE;
781   nfc_cb.nci_cmd_window = NCI_MAX_CMD_WINDOW;
782   nfc_cb.nci_wait_rsp_tout = NFC_CMD_CMPL_TIMEOUT;
783   nfc_cb.p_disc_maps = nfc_interface_mapping;
784   nfc_cb.num_disc_maps = NFC_NUM_INTERFACE_MAP;
785   nfc_cb.nci_ctrl_size = NCI_CTRL_INIT_SIZE;
786   nfc_cb.reassembly = true;
787   nfc_cb.nci_version = NCI_VERSION_UNKNOWN;
788   rw_init();
789   ce_init();
790   llcp_init();
791   NFC_SET_MAX_CONN_DEFAULT();
792 }
793 
794 /*******************************************************************************
795 **
796 ** Function         NFC_GetLmrtSize
797 **
798 ** Description      Called by application wto query the Listen Mode Routing
799 **                  Table size supported by NFCC
800 **
801 ** Returns          Listen Mode Routing Table size
802 **
803 *******************************************************************************/
NFC_GetLmrtSize(void)804 uint16_t NFC_GetLmrtSize(void) {
805   uint16_t size = 0;
806 #if (NFC_RW_ONLY == FALSE)
807   size = nfc_cb.max_ce_table;
808 #endif
809   return size;
810 }
811 
812 /*******************************************************************************
813 **
814 ** Function         NFC_SetConfig
815 **
816 ** Description      This function is called to send the configuration parameter
817 **                  TLV to NFCC. The response from NFCC is reported by
818 **                  tNFC_RESPONSE_CBACK as NFC_SET_CONFIG_REVT.
819 **
820 ** Parameters       tlv_size - the length of p_param_tlvs.
821 **                  p_param_tlvs - the parameter ID/Len/Value list
822 **
823 ** Returns          tNFC_STATUS
824 **
825 *******************************************************************************/
NFC_SetConfig(uint8_t tlv_size,uint8_t * p_param_tlvs)826 tNFC_STATUS NFC_SetConfig(uint8_t tlv_size, uint8_t* p_param_tlvs) {
827   return nci_snd_core_set_config(p_param_tlvs, tlv_size);
828 }
829 
830 /*******************************************************************************
831 **
832 ** Function         NFC_GetConfig
833 **
834 ** Description      This function is called to retrieve the parameter TLV from
835 **                  NFCC. The response from NFCC is reported by
836 **                  tNFC_RESPONSE_CBACK as NFC_GET_CONFIG_REVT.
837 **
838 ** Parameters       num_ids - the number of parameter IDs
839 **                  p_param_ids - the parameter ID list.
840 **
841 ** Returns          tNFC_STATUS
842 **
843 *******************************************************************************/
NFC_GetConfig(uint8_t num_ids,uint8_t * p_param_ids)844 tNFC_STATUS NFC_GetConfig(uint8_t num_ids, uint8_t* p_param_ids) {
845   return nci_snd_core_get_config(p_param_ids, num_ids);
846 }
847 
848 /*******************************************************************************
849 **
850 ** Function         NFC_DiscoveryMap
851 **
852 ** Description      This function is called to set the discovery interface
853 **                  mapping. The response from NFCC is reported by
854 **                  tNFC_DISCOVER_CBACK as NFC_MAP_DEVT.
855 **
856 ** Parameters       num - the number of items in p_params.
857 **                  p_maps - the discovery interface mappings
858 **                  p_cback - the discovery callback function
859 **
860 ** Returns          tNFC_STATUS
861 **
862 *******************************************************************************/
NFC_DiscoveryMap(uint8_t num,tNFC_DISCOVER_MAPS * p_maps,tNFC_DISCOVER_CBACK * p_cback)863 tNFC_STATUS NFC_DiscoveryMap(uint8_t num, tNFC_DISCOVER_MAPS* p_maps,
864                              tNFC_DISCOVER_CBACK* p_cback) {
865   uint8_t num_disc_maps = num;
866   uint8_t xx, yy, num_intf, intf_mask;
867   tNFC_DISCOVER_MAPS
868       max_maps[NFC_NFCC_MAX_NUM_VS_INTERFACE + NCI_INTERFACE_MAX];
869   bool is_supported;
870 
871   nfc_cb.p_discv_cback = p_cback;
872   num_intf = 0;
873   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf(
874       "nci_interfaces supported by NFCC: 0x%x", nfc_cb.nci_interfaces);
875 
876   for (xx = 0; xx < NFC_NFCC_MAX_NUM_VS_INTERFACE + NCI_INTERFACE_MAX; xx++) {
877     memset(&max_maps[xx], 0x00, sizeof(tNFC_DISCOVER_MAPS));
878   }
879 
880   for (xx = 0; xx < num_disc_maps; xx++) {
881     is_supported = false;
882     if (p_maps[xx].intf_type > NCI_INTERFACE_MAX) {
883       for (yy = 0; yy < NFC_NFCC_MAX_NUM_VS_INTERFACE; yy++) {
884         if (nfc_cb.vs_interface[yy] == p_maps[xx].intf_type)
885           is_supported = true;
886       }
887       DLOG_IF(INFO, nfc_debug_enabled)
888           << StringPrintf("[%d]: vs intf_type:0x%x is_supported:%d", xx,
889                           p_maps[xx].intf_type, is_supported);
890     } else {
891       intf_mask = (1 << (p_maps[xx].intf_type));
892       if (intf_mask & nfc_cb.nci_interfaces) {
893         is_supported = true;
894       }
895       DLOG_IF(INFO, nfc_debug_enabled)
896           << StringPrintf("[%d]: intf_type:%d intf_mask: 0x%x is_supported:%d",
897                           xx, p_maps[xx].intf_type, intf_mask, is_supported);
898     }
899     if (is_supported)
900       memcpy(&max_maps[num_intf++], &p_maps[xx], sizeof(tNFC_DISCOVER_MAPS));
901     else {
902       LOG(WARNING) << StringPrintf(
903           "NFC_DiscoveryMap interface=0x%x is not supported by NFCC",
904           p_maps[xx].intf_type);
905     }
906   }
907 
908   return nci_snd_discover_map_cmd(num_intf, (tNCI_DISCOVER_MAPS*)max_maps);
909 }
910 
911 /*******************************************************************************
912 **
913 ** Function         NFC_DiscoveryStart
914 **
915 ** Description      This function is called to start Polling and/or Listening.
916 **                  The response from NFCC is reported by tNFC_DISCOVER_CBACK as
917 **                  NFC_START_DEVT. The notification from NFCC is reported by
918 **                  tNFC_DISCOVER_CBACK as NFC_RESULT_DEVT.
919 **
920 ** Parameters       num_params - the number of items in p_params.
921 **                  p_params - the discovery parameters
922 **                  p_cback - the discovery callback function
923 **
924 ** Returns          tNFC_STATUS
925 **
926 *******************************************************************************/
NFC_DiscoveryStart(uint8_t num_params,tNFC_DISCOVER_PARAMS * p_params,tNFC_DISCOVER_CBACK * p_cback)927 tNFC_STATUS NFC_DiscoveryStart(uint8_t num_params,
928                                tNFC_DISCOVER_PARAMS* p_params,
929                                tNFC_DISCOVER_CBACK* p_cback) {
930   uint8_t* p;
931   int params_size;
932   tNFC_STATUS status = NFC_STATUS_NO_BUFFERS;
933 
934   DLOG_IF(INFO, nfc_debug_enabled) << __func__;
935   if (nfc_cb.p_disc_pending) {
936     LOG(ERROR) << StringPrintf("There's pending NFC_DiscoveryStart");
937     status = NFC_STATUS_BUSY;
938   } else {
939     nfc_cb.p_discv_cback = p_cback;
940     nfc_cb.flags |= NFC_FL_DISCOVER_PENDING;
941     nfc_cb.flags |= NFC_FL_CONTROL_REQUESTED;
942     params_size = sizeof(tNFC_DISCOVER_PARAMS) * num_params;
943     nfc_cb.p_disc_pending =
944         GKI_getbuf((uint16_t)(NFC_HDR_SIZE + 1 + params_size));
945     if (nfc_cb.p_disc_pending) {
946       p = (uint8_t*)nfc_cb.p_disc_pending;
947       *p++ = num_params;
948       memcpy(p, p_params, params_size);
949       status = NFC_STATUS_CMD_STARTED;
950       nfc_ncif_check_cmd_queue(nullptr);
951     }
952   }
953 
954   DLOG_IF(INFO, nfc_debug_enabled)
955       << StringPrintf("NFC_DiscoveryStart status: 0x%x", status);
956   return status;
957 }
958 
959 /*******************************************************************************
960 **
961 ** Function         NFC_DiscoverySelect
962 **
963 ** Description      If tNFC_DISCOVER_CBACK reports status=NFC_MULTIPLE_PROT,
964 **                  the application needs to use this function to select the
965 **                  the logical endpoint to continue. The response from NFCC is
966 **                  reported by tNFC_DISCOVER_CBACK as NFC_SELECT_DEVT.
967 **
968 ** Parameters       rf_disc_id - The ID identifies the remote device.
969 **                  protocol - the logical endpoint on the remote devide
970 **                  rf_interface - the RF interface to communicate with NFCC
971 **
972 ** Returns          tNFC_STATUS
973 **
974 *******************************************************************************/
NFC_DiscoverySelect(uint8_t rf_disc_id,uint8_t protocol,uint8_t rf_interface)975 tNFC_STATUS NFC_DiscoverySelect(uint8_t rf_disc_id, uint8_t protocol,
976                                 uint8_t rf_interface) {
977   return nci_snd_discover_select_cmd(rf_disc_id, protocol, rf_interface);
978 }
979 
980 /*******************************************************************************
981 **
982 ** Function         NFC_ConnCreate
983 **
984 ** Description      This function is called to create a logical connection with
985 **                  NFCC for data exchange.
986 **
987 ** Parameters       dest_type - the destination type
988 **                  id   - the NFCEE ID or RF Discovery ID .
989 **                  protocol   - the protocol.
990 **                  p_cback - the connection callback function
991 **
992 ** Returns          tNFC_STATUS
993 **
994 *******************************************************************************/
NFC_ConnCreate(uint8_t dest_type,uint8_t id,uint8_t protocol,tNFC_CONN_CBACK * p_cback)995 tNFC_STATUS NFC_ConnCreate(uint8_t dest_type, uint8_t id, uint8_t protocol,
996                            tNFC_CONN_CBACK* p_cback) {
997   tNFC_STATUS status = NFC_STATUS_FAILED;
998   tNFC_CONN_CB* p_cb;
999   uint8_t num_tlv = 0, tlv_size = 0;
1000   uint8_t param_tlvs[4], *pp;
1001 
1002   p_cb = nfc_alloc_conn_cb(p_cback);
1003   if (p_cb) {
1004     p_cb->id = id;
1005     pp = param_tlvs;
1006     if (dest_type == NCI_DEST_TYPE_NFCEE) {
1007       num_tlv = 1;
1008       UINT8_TO_STREAM(pp, NCI_CON_CREATE_TAG_NFCEE_VAL);
1009       UINT8_TO_STREAM(pp, 2);
1010       UINT8_TO_STREAM(pp, id);
1011       UINT8_TO_STREAM(pp, protocol);
1012       tlv_size = 4;
1013     } else if (dest_type == NCI_DEST_TYPE_REMOTE) {
1014       num_tlv = 1;
1015       UINT8_TO_STREAM(pp, NCI_CON_CREATE_TAG_RF_DISC_ID);
1016       UINT8_TO_STREAM(pp, 1);
1017       UINT8_TO_STREAM(pp, id);
1018       tlv_size = 3;
1019     } else if (dest_type == NCI_DEST_TYPE_NFCC) {
1020       p_cb->id = NFC_TEST_ID;
1021     }
1022     /* Add handling of NCI_DEST_TYPE_REMOTE when more RF interface definitions
1023      * are added */
1024     p_cb->act_protocol = protocol;
1025     p_cb->p_cback = p_cback;
1026     status = nci_snd_core_conn_create(dest_type, num_tlv, tlv_size, param_tlvs);
1027     if (status == NFC_STATUS_FAILED) nfc_free_conn_cb(p_cb);
1028   }
1029   return status;
1030 }
1031 
1032 /*******************************************************************************
1033 **
1034 ** Function         NFC_ConnClose
1035 **
1036 ** Description      This function is called to close a logical connection with
1037 **                  NFCC.
1038 **
1039 ** Parameters       conn_id - the connection id.
1040 **
1041 ** Returns          tNFC_STATUS
1042 **
1043 *******************************************************************************/
NFC_ConnClose(uint8_t conn_id)1044 tNFC_STATUS NFC_ConnClose(uint8_t conn_id) {
1045   tNFC_CONN_CB* p_cb = nfc_find_conn_cb_by_conn_id(conn_id);
1046   tNFC_STATUS status = NFC_STATUS_FAILED;
1047 
1048   if (p_cb) {
1049     status = nci_snd_core_conn_close(conn_id);
1050   }
1051   return status;
1052 }
1053 
1054 /*******************************************************************************
1055 **
1056 ** Function         NFC_SetStaticRfCback
1057 **
1058 ** Description      This function is called to update the data callback function
1059 **                  to receive the data for the given connection id.
1060 **
1061 ** Parameters       p_cback - the connection callback function
1062 **
1063 ** Returns          Nothing
1064 **
1065 *******************************************************************************/
NFC_SetStaticRfCback(tNFC_CONN_CBACK * p_cback)1066 void NFC_SetStaticRfCback(tNFC_CONN_CBACK* p_cback) {
1067   tNFC_CONN_CB* p_cb = &nfc_cb.conn_cb[NFC_RF_CONN_ID];
1068 
1069   p_cb->p_cback = p_cback;
1070   /* just in case DH has received NCI data before the data callback is set
1071    * check if there's any data event to report on this connection id */
1072   nfc_data_event(p_cb);
1073 }
1074 
1075 /*******************************************************************************
1076 **
1077 ** Function         NFC_SetReassemblyFlag
1078 **
1079 ** Description      This function is called to set if nfc will reassemble
1080 **                  nci packet as much as its buffer can hold or it should not
1081 **                  reassemble but forward the fragmented nci packet to layer
1082 **                  above. If nci data pkt is fragmented, nfc may send multiple
1083 **                  NFC_DATA_CEVT with status NFC_STATUS_CONTINUE before sending
1084 **                  NFC_DATA_CEVT with status NFC_STATUS_OK based on reassembly
1085 **                  configuration and reassembly buffer size
1086 **
1087 ** Parameters       reassembly - flag to indicate if nfc may reassemble or not
1088 **
1089 ** Returns          Nothing
1090 **
1091 *******************************************************************************/
NFC_SetReassemblyFlag(bool reassembly)1092 void NFC_SetReassemblyFlag(bool reassembly) { nfc_cb.reassembly = reassembly; }
1093 
1094 /*******************************************************************************
1095 **
1096 ** Function         NFC_SendData
1097 **
1098 ** Description      This function is called to send the given data packet
1099 **                  to the connection identified by the given connection id.
1100 **
1101 ** Parameters       conn_id - the connection id.
1102 **                  p_data - the data packet.
1103 **                  p_data->offset must be >= NCI_MSG_OFFSET_SIZE +
1104 **                  NCI_DATA_HDR_SIZE
1105 **                  The data payload starts at
1106 **                  ((uint8_t *) (p_data + 1) + p_data->offset)
1107 **
1108 ** Returns          tNFC_STATUS
1109 **
1110 *******************************************************************************/
NFC_SendData(uint8_t conn_id,NFC_HDR * p_data)1111 tNFC_STATUS NFC_SendData(uint8_t conn_id, NFC_HDR* p_data) {
1112   tNFC_STATUS status = NFC_STATUS_FAILED;
1113   tNFC_CONN_CB* p_cb = nfc_find_conn_cb_by_conn_id(conn_id);
1114 
1115   if (p_cb && p_data &&
1116       p_data->offset >= NCI_MSG_OFFSET_SIZE + NCI_DATA_HDR_SIZE) {
1117     status = nfc_ncif_send_data(p_cb, p_data);
1118   }
1119 
1120   if (status != NFC_STATUS_OK) GKI_freebuf(p_data);
1121 
1122   return status;
1123 }
1124 
1125 /*******************************************************************************
1126 **
1127 ** Function         NFC_FlushData
1128 **
1129 ** Description      This function is called to discard the tx data queue of
1130 **                  the given connection id.
1131 **
1132 ** Parameters       conn_id - the connection id.
1133 **
1134 ** Returns          tNFC_STATUS
1135 **
1136 *******************************************************************************/
NFC_FlushData(uint8_t conn_id)1137 tNFC_STATUS NFC_FlushData(uint8_t conn_id) {
1138   tNFC_STATUS status = NFC_STATUS_FAILED;
1139   tNFC_CONN_CB* p_cb = nfc_find_conn_cb_by_conn_id(conn_id);
1140   void* p_buf;
1141 
1142   if (p_cb) {
1143     status = NFC_STATUS_OK;
1144     while ((p_buf = GKI_dequeue(&p_cb->tx_q)) != nullptr) GKI_freebuf(p_buf);
1145   }
1146 
1147   return status;
1148 }
1149 
1150 /*******************************************************************************
1151 **
1152 ** Function         NFC_Deactivate
1153 **
1154 ** Description      This function is called to stop the discovery process or
1155 **                  put the listen device in sleep mode or terminate the NFC
1156 **                  link.
1157 **
1158 **                  The response from NFCC is reported by tNFC_DISCOVER_CBACK
1159 **                  as NFC_DEACTIVATE_DEVT.
1160 **
1161 ** Parameters       deactivate_type - NFC_DEACTIVATE_TYPE_IDLE, to IDLE mode.
1162 **                                    NFC_DEACTIVATE_TYPE_SLEEP to SLEEP mode.
1163 **                                    NFC_DEACTIVATE_TYPE_SLEEP_AF to SLEEP_AF
1164 **                                    mode.
1165 **
1166 ** Returns          tNFC_STATUS
1167 **
1168 *******************************************************************************/
NFC_Deactivate(tNFC_DEACT_TYPE deactivate_type)1169 tNFC_STATUS NFC_Deactivate(tNFC_DEACT_TYPE deactivate_type) {
1170   tNFC_CONN_CB* p_cb = &nfc_cb.conn_cb[NFC_RF_CONN_ID];
1171   tNFC_STATUS status = NFC_STATUS_OK;
1172 
1173   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf(
1174       "NFC_Deactivate %d (%s) deactivate_type:%d", nfc_cb.nfc_state,
1175       nfc_state_name(nfc_cb.nfc_state).c_str(), deactivate_type);
1176 
1177   if (nfc_cb.flags & NFC_FL_DISCOVER_PENDING) {
1178     /* the HAL pre-discover is still active - clear the pending flag */
1179     nfc_cb.flags &= ~NFC_FL_DISCOVER_PENDING;
1180     if (!(nfc_cb.flags & NFC_FL_HAL_REQUESTED)) {
1181       /* if HAL did not request for control, clear this bit now */
1182       nfc_cb.flags &= ~NFC_FL_CONTROL_REQUESTED;
1183     }
1184     GKI_freebuf(nfc_cb.p_disc_pending);
1185     nfc_cb.p_disc_pending = nullptr;
1186     return NFC_STATUS_OK;
1187   }
1188 
1189   if (nfc_cb.nfc_state == NFC_STATE_OPEN) {
1190     nfc_set_state(NFC_STATE_CLOSING);
1191     DLOG_IF(INFO, nfc_debug_enabled)
1192         << StringPrintf("act_protocol %d credits:%d/%d", p_cb->act_protocol,
1193                         p_cb->init_credits, p_cb->num_buff);
1194     if ((p_cb->act_protocol == NCI_PROTOCOL_NFC_DEP) &&
1195         (p_cb->init_credits != p_cb->num_buff)) {
1196       nfc_cb.flags |= NFC_FL_DEACTIVATING;
1197       nfc_cb.deactivate_timer.param = (uintptr_t)deactivate_type;
1198       nfc_start_timer(&nfc_cb.deactivate_timer,
1199                       (uint16_t)(NFC_TTYPE_WAIT_2_DEACTIVATE),
1200                       NFC_DEACTIVATE_TIMEOUT);
1201       return status;
1202     }
1203   }
1204 
1205   status = nci_snd_deactivate_cmd(deactivate_type);
1206   return status;
1207 }
1208 /*******************************************************************************
1209 **
1210 ** Function         NFC_SetPowerSubState
1211 **
1212 ** Description      This function is called to send the power sub state (screen
1213 **                  state) to NFCC. The response from NFCC is reported by
1214 **                  tNFC_RESPONSE_CBACK as NFC_SET_POWER_STATE_REVT.
1215 **
1216 ** Parameters       scree_state
1217 **
1218 ** Returns          tNFC_STATUS
1219 **
1220 *******************************************************************************/
NFC_SetPowerSubState(uint8_t screen_state)1221 tNFC_STATUS NFC_SetPowerSubState(uint8_t screen_state) {
1222   return nci_snd_core_set_power_sub_state(screen_state);
1223 }
1224 /*******************************************************************************
1225 **
1226 ** Function         NFC_UpdateRFCommParams
1227 **
1228 ** Description      This function is called to update RF Communication
1229 **                  parameters once the Frame RF Interface has been activated.
1230 **
1231 **                  The response from NFCC is reported by tNFC_RESPONSE_CBACK
1232 **                  as NFC_RF_COMM_PARAMS_UPDATE_REVT.
1233 **
1234 ** Returns          tNFC_STATUS
1235 **
1236 *******************************************************************************/
NFC_UpdateRFCommParams(tNFC_RF_COMM_PARAMS * p_params)1237 tNFC_STATUS NFC_UpdateRFCommParams(tNFC_RF_COMM_PARAMS* p_params) {
1238   uint8_t tlvs[12];
1239   uint8_t* p = tlvs;
1240   uint8_t data_exch_config;
1241 
1242   /* RF Technology and Mode */
1243   if (p_params->include_rf_tech_mode) {
1244     UINT8_TO_STREAM(p, NCI_RF_PARAM_ID_TECH_N_MODE);
1245     UINT8_TO_STREAM(p, 1);
1246     UINT8_TO_STREAM(p, p_params->rf_tech_n_mode);
1247   }
1248 
1249   /* Transmit Bit Rate */
1250   if (p_params->include_tx_bit_rate) {
1251     UINT8_TO_STREAM(p, NCI_RF_PARAM_ID_TX_BIT_RATE);
1252     UINT8_TO_STREAM(p, 1);
1253     UINT8_TO_STREAM(p, p_params->tx_bit_rate);
1254   }
1255 
1256   /* Receive Bit Rate */
1257   if (p_params->include_tx_bit_rate) {
1258     UINT8_TO_STREAM(p, NCI_RF_PARAM_ID_RX_BIT_RATE);
1259     UINT8_TO_STREAM(p, 1);
1260     UINT8_TO_STREAM(p, p_params->rx_bit_rate);
1261   }
1262 
1263   /* NFC-B Data Exchange Configuration */
1264   if (p_params->include_nfc_b_config) {
1265     UINT8_TO_STREAM(p, NCI_RF_PARAM_ID_B_DATA_EX_PARAM);
1266     UINT8_TO_STREAM(p, 1);
1267 
1268     data_exch_config = (p_params->min_tr0 & 0x03) << 6; /* b7b6 : Mininum TR0 */
1269     data_exch_config |= (p_params->min_tr1 & 0x03)
1270                         << 4; /* b5b4 : Mininum TR1 */
1271     data_exch_config |= (p_params->suppression_eos & 0x01)
1272                         << 3; /* b3 :   Suppression of EoS */
1273     data_exch_config |= (p_params->suppression_sos & 0x01)
1274                         << 2; /* b2 :   Suppression of SoS */
1275     data_exch_config |= (p_params->min_tr2 & 0x03); /* b1b0 : Mininum TR2 */
1276 
1277     UINT8_TO_STREAM(p, data_exch_config);
1278   }
1279 
1280   return nci_snd_parameter_update_cmd(tlvs, (uint8_t)(p - tlvs));
1281 }
1282 
1283 /*******************************************************************************
1284 **
1285 ** Function         NFC_SetPowerOffSleep
1286 **
1287 ** Description      This function closes/opens transport and turns off/on NFCC.
1288 **
1289 ** Returns          tNFC_STATUS
1290 **
1291 *******************************************************************************/
NFC_SetPowerOffSleep(bool enable)1292 tNFC_STATUS NFC_SetPowerOffSleep(bool enable) {
1293   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("enable = %d", enable);
1294 
1295   if ((enable == false) &&
1296       (nfc_cb.nfc_state == NFC_STATE_NFCC_POWER_OFF_SLEEP)) {
1297     nfc_cb.flags |= NFC_FL_RESTARTING;
1298 
1299     /* open transport */
1300     nfc_set_state(NFC_STATE_W4_HAL_OPEN);
1301     nfc_cb.p_hal->open(nfc_main_hal_cback, nfc_main_hal_data_cback);
1302 
1303     return NFC_STATUS_OK;
1304   } else if ((enable == true) && (nfc_cb.nfc_state == NFC_STATE_IDLE)) {
1305     /* close transport to turn off NFCC and clean up */
1306     nfc_cb.flags |= NFC_FL_POWER_OFF_SLEEP;
1307     nfc_task_shutdown_nfcc();
1308 
1309     return NFC_STATUS_OK;
1310   }
1311 
1312   LOG(ERROR) << StringPrintf("invalid state = %d", nfc_cb.nfc_state);
1313   return NFC_STATUS_FAILED;
1314 }
1315 
1316 /*******************************************************************************
1317 **
1318 ** Function         NFC_PowerCycleNFCC
1319 **
1320 ** Description      This function turns off and then on NFCC.
1321 **
1322 ** Returns          tNFC_STATUS
1323 **
1324 *******************************************************************************/
NFC_PowerCycleNFCC(void)1325 tNFC_STATUS NFC_PowerCycleNFCC(void) {
1326   DLOG_IF(INFO, nfc_debug_enabled) << __func__;
1327 
1328   if (nfc_cb.nfc_state == NFC_STATE_IDLE) {
1329     /* power cycle NFCC */
1330     nfc_cb.flags |= NFC_FL_POWER_CYCLE_NFCC;
1331     nfc_task_shutdown_nfcc();
1332 
1333     return NFC_STATUS_OK;
1334   }
1335 
1336   LOG(ERROR) << StringPrintf("invalid state = %d", nfc_cb.nfc_state);
1337   return NFC_STATUS_FAILED;
1338 }
1339 
1340 /*******************************************************************************
1341 **
1342 ** Function         NFC_GetNCIVersion
1343 **
1344 ** Description      Called by higher layer to get the current nci
1345 **                  version of nfc.
1346 **
1347 ** Returns          NCI version NCI2.0 / NCI1.0
1348 **
1349 *******************************************************************************/
NFC_GetNCIVersion()1350 uint8_t NFC_GetNCIVersion() { return nfc_cb.nci_version; }
1351 
1352 /*******************************************************************************
1353 **
1354 ** Function         NFC_ISODEPNakPresCheck
1355 **
1356 ** Description      This function is called to send the ISO DEP nak presenc
1357 **                  check cmd to check that the remote end point in RF field.
1358 **
1359 **                  The response from NFCC is reported by call back.The ntf
1360 **                  indicates success if card is present in field or failed
1361 **                  if card is lost.
1362 **
1363 ** Returns          tNFC_STATUS
1364 **
1365 *******************************************************************************/
NFC_ISODEPNakPresCheck()1366 tNFC_STATUS NFC_ISODEPNakPresCheck() {
1367   return nci_snd_iso_dep_nak_presence_check_cmd();
1368 }
1369 
1370 /*******************************************************************************
1371 **
1372 ** Function         NFC_SetStaticHciCback
1373 **
1374 ** Description      This function is called to update the data callback function
1375 **                  to receive the data for the static Hci connection id.
1376 **
1377 ** Parameters       p_cback - the connection callback function
1378 **
1379 ** Returns          Nothing
1380 **
1381 *******************************************************************************/
NFC_SetStaticHciCback(tNFC_CONN_CBACK * p_cback)1382 void NFC_SetStaticHciCback(tNFC_CONN_CBACK* p_cback) {
1383   DLOG_IF(INFO, nfc_debug_enabled)
1384       << StringPrintf("%s dest: %d", __func__, NCI_DEST_TYPE_NFCEE);
1385   tNFC_CONN_CB* p_cb = &nfc_cb.conn_cb[NFC_HCI_CONN_ID];
1386   tNFC_CONN evt_data;
1387 
1388   p_cb->p_cback = p_cback;
1389   if (p_cback && p_cb->buff_size && p_cb->num_buff) {
1390     DLOG_IF(INFO, nfc_debug_enabled)
1391         << StringPrintf("%s dest: %d", __func__, NCI_DEST_TYPE_NFCEE);
1392     evt_data.conn_create.status = NFC_STATUS_OK;
1393     evt_data.conn_create.dest_type = NCI_DEST_TYPE_NFCEE;
1394     evt_data.conn_create.id = p_cb->id;
1395     evt_data.conn_create.buff_size = p_cb->buff_size;
1396     evt_data.conn_create.num_buffs = p_cb->num_buff;
1397     (*p_cback)(NFC_HCI_CONN_ID, NFC_CONN_CREATE_CEVT, &evt_data);
1398   }
1399 }
1400 
1401 /*******************************************************************************
1402 **
1403 ** Function         NFC_GetStatusName
1404 **
1405 ** Description      This function returns the status name.
1406 **
1407 ** NOTE             conditionally compiled to save memory.
1408 **
1409 ** Returns          pointer to the name
1410 **
1411 *******************************************************************************/
NFC_GetStatusName(tNFC_STATUS status)1412 std::string NFC_GetStatusName(tNFC_STATUS status) {
1413   switch (status) {
1414     case NFC_STATUS_OK:
1415       return "OK";
1416     case NFC_STATUS_REJECTED:
1417       return "REJECTED";
1418     case NFC_STATUS_MSG_CORRUPTED:
1419       return "CORRUPTED";
1420     case NFC_STATUS_BUFFER_FULL:
1421       return "BUFFER_FULL";
1422     case NFC_STATUS_FAILED:
1423       return "FAILED";
1424     case NFC_STATUS_NOT_INITIALIZED:
1425       return "NOT_INITIALIZED";
1426     case NFC_STATUS_SYNTAX_ERROR:
1427       return "SYNTAX_ERROR";
1428     case NFC_STATUS_SEMANTIC_ERROR:
1429       return "SEMANTIC_ERROR";
1430     case NFC_STATUS_UNKNOWN_GID:
1431       return "UNKNOWN_GID";
1432     case NFC_STATUS_UNKNOWN_OID:
1433       return "UNKNOWN_OID";
1434     case NFC_STATUS_INVALID_PARAM:
1435       return "INVALID_PARAM";
1436     case NFC_STATUS_MSG_SIZE_TOO_BIG:
1437       return "MSG_SIZE_TOO_BIG";
1438     case NFC_STATUS_ALREADY_STARTED:
1439       return "ALREADY_STARTED";
1440     case NFC_STATUS_ACTIVATION_FAILED:
1441       return "ACTIVATION_FAILED";
1442     case NFC_STATUS_TEAR_DOWN:
1443       return "TEAR_DOWN";
1444     case NFC_STATUS_RF_TRANSMISSION_ERR:
1445       return "RF_TRANSMISSION_ERR";
1446     case NFC_STATUS_RF_PROTOCOL_ERR:
1447       return "RF_PROTOCOL_ERR";
1448     case NFC_STATUS_TIMEOUT:
1449       return "TIMEOUT";
1450     case NFC_STATUS_EE_INTF_ACTIVE_FAIL:
1451       return "EE_INTF_ACTIVE_FAIL";
1452     case NFC_STATUS_EE_TRANSMISSION_ERR:
1453       return "EE_TRANSMISSION_ERR";
1454     case NFC_STATUS_EE_PROTOCOL_ERR:
1455       return "EE_PROTOCOL_ERR";
1456     case NFC_STATUS_EE_TIMEOUT:
1457       return "EE_TIMEOUT";
1458     case NFC_STATUS_CMD_STARTED:
1459       return "CMD_STARTED";
1460     case NFC_STATUS_HW_TIMEOUT:
1461       return "HW_TIMEOUT";
1462     case NFC_STATUS_CONTINUE:
1463       return "CONTINUE";
1464     case NFC_STATUS_REFUSED:
1465       return "REFUSED";
1466     case NFC_STATUS_BAD_RESP:
1467       return "BAD_RESP";
1468     case NFC_STATUS_CMD_NOT_CMPLTD:
1469       return "CMD_NOT_CMPLTD";
1470     case NFC_STATUS_NO_BUFFERS:
1471       return "NO_BUFFERS";
1472     case NFC_STATUS_WRONG_PROTOCOL:
1473       return "WRONG_PROTOCOL";
1474     case NFC_STATUS_BUSY:
1475       return "BUSY";
1476     case NFC_STATUS_LINK_LOSS:
1477       return "LINK_LOSS";
1478     case NFC_STATUS_BAD_LENGTH:
1479       return "BAD_LENGTH";
1480     case NFC_STATUS_BAD_HANDLE:
1481       return "BAD_HANDLE";
1482     case NFC_STATUS_CONGESTED:
1483       return "CONGESTED";
1484     default:
1485       return "UNKNOWN";
1486   }
1487 }
1488