• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright (C) 1999-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 <android-base/stringprintf.h>
27 #include <base/logging.h>
28 #include <fcntl.h>
29 #include <log/log.h>
30 #include <statslog_nfc.h>
31 #include <sys/stat.h>
32 #include <sys/time.h>
33 
34 #include "include/debug_nfcsnoop.h"
35 #include "metrics.h"
36 #include "nci_defs.h"
37 #include "nci_hmsgs.h"
38 #include "nfc_api.h"
39 #include "nfc_int.h"
40 #include "nfc_target.h"
41 #include "rw_api.h"
42 #include "rw_int.h"
43 
44 using android::base::StringPrintf;
45 
46 #if (NFC_RW_ONLY == FALSE)
47 static const uint8_t nfc_mpl_code_to_size[] = {64, 128, 192, 254};
48 
49 #endif /* NFC_RW_ONLY */
50 #if (APPL_DTA_MODE == TRUE)
51 // Global Structure varibale for FW Version
52 static tNFC_FW_VERSION nfc_fw_version;
53 #endif
54 #define NFC_PB_ATTRIB_REQ_FIXED_BYTES 1
55 #define NFC_LB_ATTRIB_REQ_FIXED_BYTES 8
56 
57 extern unsigned char appl_dta_mode_flag;
58 extern bool nfc_debug_enabled;
59 extern std::string nfc_storage_path;
60 
61 static struct timeval timer_start;
62 static struct timeval timer_end;
63 
64 #define DEFAULT_CRASH_NFCSNOOP_PATH "/data/misc/nfc/logs/native_crash_logs"
65 static const off_t NATIVE_CRASH_FILE_SIZE = (1024 * 1024);
66 
67 /*******************************************************************************
68 **
69 ** Function         nfc_ncif_update_window
70 **
71 ** Description      Update tx cmd window to indicate that NFCC can received
72 **
73 ** Returns          void
74 **
75 *******************************************************************************/
nfc_ncif_update_window(void)76 void nfc_ncif_update_window(void) {
77   /* Sanity check - see if we were expecting a update_window */
78   if (nfc_cb.nci_cmd_window == NCI_MAX_CMD_WINDOW) {
79     if (nfc_cb.nfc_state != NFC_STATE_W4_HAL_CLOSE) {
80       LOG(ERROR) << StringPrintf("nfc_ncif_update_window: Unexpected call");
81     }
82     return;
83   }
84 
85   /* Stop command-pending timer */
86   nfc_stop_timer(&nfc_cb.nci_wait_rsp_timer);
87 
88   nfc_cb.p_vsc_cback = nullptr;
89   nfc_cb.nci_cmd_window++;
90 
91   /* Check if there were any commands waiting to be sent */
92   nfc_ncif_check_cmd_queue(nullptr);
93 }
94 
95 /*******************************************************************************
96 **
97 ** Function         nfc_ncif_cmd_timeout
98 **
99 ** Description      Handle a command timeout
100 **
101 ** Returns          void
102 **
103 *******************************************************************************/
nfc_ncif_cmd_timeout(void)104 void nfc_ncif_cmd_timeout(void) {
105   LOG(ERROR) << StringPrintf("nfc_ncif_cmd_timeout");
106 
107   storeNfcSnoopLogs(DEFAULT_CRASH_NFCSNOOP_PATH, NATIVE_CRASH_FILE_SIZE);
108 
109   /* report an error */
110   nfc_ncif_event_status(NFC_GEN_ERROR_REVT, NFC_STATUS_HW_TIMEOUT);
111   nfc_ncif_event_status(NFC_NFCC_TIMEOUT_REVT, NFC_STATUS_HW_TIMEOUT);
112 
113   /* if enabling NFC, notify upper layer of failure */
114   if (nfc_cb.nfc_state == NFC_STATE_CORE_INIT) {
115     nfc_enabled(NFC_STATUS_FAILED, nullptr);
116   }
117 }
118 
119 /*******************************************************************************
120 **
121 ** Function         nfc_wait_2_deactivate_timeout
122 **
123 ** Description      Handle a command timeout
124 **
125 ** Returns          void
126 **
127 *******************************************************************************/
nfc_wait_2_deactivate_timeout(void)128 void nfc_wait_2_deactivate_timeout(void) {
129   LOG(ERROR) << StringPrintf("nfc_wait_2_deactivate_timeout");
130   nfc_cb.flags &= ~NFC_FL_DEACTIVATING;
131   nci_snd_deactivate_cmd((uint8_t)nfc_cb.deactivate_timer.param);
132 }
133 
134 /*******************************************************************************
135 **
136 ** Function         nfc_ncif_send_data
137 **
138 ** Description      This function is called to add the NCI data header
139 **                  and send it to NCIT task for sending it to transport
140 **                  as credits are available.
141 **
142 ** Returns          void
143 **
144 *******************************************************************************/
nfc_ncif_send_data(tNFC_CONN_CB * p_cb,NFC_HDR * p_data)145 uint8_t nfc_ncif_send_data(tNFC_CONN_CB* p_cb, NFC_HDR* p_data) {
146   uint8_t* pp;
147   uint8_t* ps;
148   uint8_t ulen = NCI_MAX_PAYLOAD_SIZE;
149   NFC_HDR* p;
150   uint8_t pbf = 1;
151   uint8_t buffer_size = p_cb->buff_size;
152   uint8_t hdr0 = p_cb->conn_id;
153   bool fragmented = false;
154 
155   DLOG_IF(INFO, nfc_debug_enabled)
156       << StringPrintf("nfc_ncif_send_data :%d, num_buff:%d qc:%d",
157                       p_cb->conn_id, p_cb->num_buff, p_cb->tx_q.count);
158   if (p_cb->id == NFC_RF_CONN_ID) {
159     if (nfc_cb.nfc_state != NFC_STATE_OPEN) {
160       if (nfc_cb.nfc_state == NFC_STATE_CLOSING) {
161         if ((p_data == nullptr) && /* called because credit from NFCC */
162             (nfc_cb.flags & NFC_FL_DEACTIVATING)) {
163           if (p_cb->init_credits == p_cb->num_buff) {
164             /* all the credits are back */
165             nfc_cb.flags &= ~NFC_FL_DEACTIVATING;
166             DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf(
167                 "deactivating NFC-DEP init_credits:%d, num_buff:%d",
168                 p_cb->init_credits, p_cb->num_buff);
169             nfc_stop_timer(&nfc_cb.deactivate_timer);
170             nci_snd_deactivate_cmd((uint8_t)nfc_cb.deactivate_timer.param);
171           }
172         }
173       }
174       return NCI_STATUS_FAILED;
175     }
176   }
177 
178   if (p_data) {
179     /* always enqueue the data to the tx queue */
180     GKI_enqueue(&p_cb->tx_q, p_data);
181   }
182 
183   /* try to send the first data packet in the tx queue  */
184   p_data = (NFC_HDR*)GKI_getfirst(&p_cb->tx_q);
185 
186   /* post data fragment to NCIT task as credits are available */
187   while (p_data && (p_cb->num_buff > 0)) {
188     if (p_data->len <= buffer_size) {
189       pbf = 0; /* last fragment */
190       ulen = (uint8_t)(p_data->len);
191       fragmented = false;
192     } else {
193       fragmented = true;
194       ulen = buffer_size;
195     }
196 
197     if (!fragmented) {
198       /* if data packet is not fragmented, use the original buffer */
199       p = p_data;
200       p_data = (NFC_HDR*)GKI_dequeue(&p_cb->tx_q);
201     } else {
202       /* the data packet is too big and need to be fragmented
203        * prepare a new GKI buffer
204        * (even the last fragment to avoid issues) */
205       p = NCI_GET_CMD_BUF(ulen);
206       if (p == nullptr) return (NCI_STATUS_BUFFER_FULL);
207       p->len = ulen;
208       p->offset = NCI_MSG_OFFSET_SIZE + NCI_DATA_HDR_SIZE + 1;
209       if (p->len) {
210         pp = (uint8_t*)(p + 1) + p->offset;
211         ps = (uint8_t*)(p_data + 1) + p_data->offset;
212         memcpy(pp, ps, ulen);
213       }
214       /* adjust the NFC_HDR on the old fragment */
215       p_data->len -= ulen;
216       p_data->offset += ulen;
217     }
218 
219     p->event = BT_EVT_TO_NFC_NCI;
220     p->layer_specific = pbf;
221     p->len += NCI_DATA_HDR_SIZE;
222     p->offset -= NCI_DATA_HDR_SIZE;
223     pp = (uint8_t*)(p + 1) + p->offset;
224     /* build NCI Data packet header */
225     NCI_DATA_PBLD_HDR(pp, pbf, hdr0, ulen);
226 
227     if (p_cb->num_buff != NFC_CONN_NO_FC) p_cb->num_buff--;
228 
229     /* send to HAL */
230     nfcsnoop_capture(p, false);
231     HAL_WRITE(p);
232 
233     if (!fragmented) {
234       /* check if there are more data to send */
235       p_data = (NFC_HDR*)GKI_getfirst(&p_cb->tx_q);
236     }
237   }
238 
239   // log duration for the first hce data response
240   if (timer_start.tv_sec != 0 || timer_start.tv_usec != 0) {
241     gettimeofday(&timer_end, nullptr);
242     uint32_t delta_time_ms = (timer_end.tv_sec - timer_start.tv_sec) * 1000 +
243                              (timer_end.tv_usec - timer_start.tv_usec) / 1000;
244     memset(&timer_start, 0, sizeof(timer_start));
245     memset(&timer_end, 0, sizeof(timer_end));
246     nfc::stats::stats_write(nfc::stats::NFC_HCE_TRANSACTION_OCCURRED,
247                             (int32_t)delta_time_ms);
248   }
249   return (NCI_STATUS_OK);
250 }
251 
252 /*******************************************************************************
253 **
254 ** Function         nfc_ncif_check_cmd_queue
255 **
256 ** Description      Send NCI command to the transport
257 **
258 ** Returns          void
259 **
260 *******************************************************************************/
nfc_ncif_check_cmd_queue(NFC_HDR * p_buf)261 void nfc_ncif_check_cmd_queue(NFC_HDR* p_buf) {
262   uint8_t* ps;
263   /* If there are commands waiting in the xmit queue, or if the controller
264    * cannot accept any more commands, */
265   /* then enqueue this command */
266   if (p_buf) {
267     if ((nfc_cb.nci_cmd_xmit_q.count) || (nfc_cb.nci_cmd_window == 0)) {
268       GKI_enqueue(&nfc_cb.nci_cmd_xmit_q, p_buf);
269       p_buf = nullptr;
270     }
271   }
272 
273   /* If controller can accept another command, then send the next command */
274   if (nfc_cb.nci_cmd_window > 0) {
275     /* If no command was provided, or if older commands were in the queue, then
276      * get cmd from the queue */
277     if (!p_buf) p_buf = (NFC_HDR*)GKI_dequeue(&nfc_cb.nci_cmd_xmit_q);
278 
279     if (p_buf) {
280       /* save the message header to double check the response */
281       ps = (uint8_t*)(p_buf + 1) + p_buf->offset;
282       memcpy(nfc_cb.last_hdr, ps, NFC_SAVED_HDR_SIZE);
283       memcpy(nfc_cb.last_cmd, ps + NCI_MSG_HDR_SIZE, NFC_SAVED_CMD_SIZE);
284       // Check first byte to check if this is an NFCEE command
285       if (*ps == ((NCI_MT_CMD << NCI_MT_SHIFT) | NCI_GID_EE_MANAGE)) {
286         memcpy(nfc_cb.last_nfcee_cmd, ps + NCI_MSG_HDR_SIZE,
287                NFC_SAVED_CMD_SIZE);
288       }
289       if (p_buf->layer_specific == NFC_WAIT_RSP_VSC) {
290         /* save the callback for NCI VSCs)  */
291         nfc_cb.p_vsc_cback = (void*)((tNFC_NCI_VS_MSG*)p_buf)->p_cback;
292       } else if (p_buf->layer_specific == NFC_WAIT_RSP_RAW_VS) {
293         /* save the callback for RAW VS */
294         nfc_cb.p_vsc_cback = (void*)((tNFC_NCI_VS_MSG*)p_buf)->p_cback;
295         nfc_cb.rawVsCbflag = true;
296       }
297 
298       /* Indicate command is pending */
299       nfc_cb.nci_cmd_window--;
300 
301       /* send to HAL */
302       HAL_WRITE(p_buf);
303       /* start NFC command-timeout timer */
304       nfc_start_timer(&nfc_cb.nci_wait_rsp_timer,
305                       (uint16_t)(NFC_TTYPE_NCI_WAIT_RSP),
306                       nfc_cb.nci_wait_rsp_tout);
307     }
308   }
309 
310   if (nfc_cb.nci_cmd_window == NCI_MAX_CMD_WINDOW) {
311     /* the command queue must be empty now */
312     if (nfc_cb.flags & NFC_FL_CONTROL_REQUESTED) {
313       /* HAL requested control or stack needs to handle pre-discover */
314       nfc_cb.flags &= ~NFC_FL_CONTROL_REQUESTED;
315       if (nfc_cb.flags & NFC_FL_DISCOVER_PENDING) {
316         if (nfc_cb.p_hal->prediscover()) {
317           /* HAL has the command window now */
318           nfc_cb.flags |= NFC_FL_CONTROL_GRANTED;
319           nfc_cb.nci_cmd_window = 0;
320         } else {
321           /* HAL does not need to send command,
322            * - restore the command window and issue the discovery command now */
323           nfc_cb.flags &= ~NFC_FL_DISCOVER_PENDING;
324           ps = (uint8_t*)nfc_cb.p_disc_pending;
325           nci_snd_discover_cmd(*ps, (tNFC_DISCOVER_PARAMS*)(ps + 1));
326           GKI_freebuf(nfc_cb.p_disc_pending);
327           nfc_cb.p_disc_pending = nullptr;
328         }
329       } else if (nfc_cb.flags & NFC_FL_HAL_REQUESTED) {
330         /* grant the control to HAL */
331         nfc_cb.flags &= ~NFC_FL_HAL_REQUESTED;
332         nfc_cb.flags |= NFC_FL_CONTROL_GRANTED;
333         nfc_cb.nci_cmd_window = 0;
334         nfc_cb.p_hal->control_granted();
335       }
336     }
337   }
338 }
339 
340 #if (APPL_DTA_MODE == TRUE)
341 /*******************************************************************************
342 **
343 ** Function         nfc_ncif_getFWVersion
344 **
345 ** Description      This function is called to fet the FW Version
346 **
347 ** Returns          tNFC_FW_VERSION
348 **
349 *******************************************************************************/
nfc_ncif_getFWVersion()350 tNFC_FW_VERSION nfc_ncif_getFWVersion() { return nfc_fw_version; }
351 #endif
352 
353 /*******************************************************************************
354 **
355 ** Function         nfc_ncif_send_cmd
356 **
357 ** Description      Send NCI command to the NCIT task
358 **
359 ** Returns          void
360 **
361 *******************************************************************************/
nfc_ncif_send_cmd(NFC_HDR * p_buf)362 void nfc_ncif_send_cmd(NFC_HDR* p_buf) {
363   /* post the p_buf to NCIT task */
364   p_buf->event = BT_EVT_TO_NFC_NCI;
365   p_buf->layer_specific = 0;
366   nfcsnoop_capture(p_buf, false);
367   nfc_ncif_check_cmd_queue(p_buf);
368 }
369 
370 /*******************************************************************************
371 **
372 ** Function         nfc_ncif_process_event
373 **
374 ** Description      This function is called to process the
375 **                  data/response/notification from NFCC
376 **
377 ** Returns          TRUE if need to free buffer
378 **
379 *******************************************************************************/
nfc_ncif_process_event(NFC_HDR * p_msg)380 bool nfc_ncif_process_event(NFC_HDR* p_msg) {
381   uint8_t mt, pbf, gid, *p;
382   bool free = true;
383   uint8_t oid;
384   uint16_t len;
385   uint8_t *p_old, old_gid, old_oid, old_mt;
386 
387   p = (uint8_t*)(p_msg + 1) + p_msg->offset;
388 
389   if (p_msg->len < 3) {
390     // Per NCI spec, every packets should have at least 3 bytes: HDR0, HDR1, and
391     // LEN field.
392     LOG(ERROR) << StringPrintf("Invalid NCI packet: p_msg->len: %d",
393                                p_msg->len);
394     return free;
395   }
396 
397   // LEN field contains the size of the payload, not including the 3-byte packet
398   // header.
399   len = p[2] + 3;
400   if (p_msg->len < len) {
401     // Making sure the packet holds enough data than it claims.
402     LOG(ERROR) << StringPrintf("Invalid NCI packet: p_msg->len (%d) < len (%d)",
403                                p_msg->len, len);
404     return free;
405   }
406 
407   NCI_MSG_PRS_HDR0(p, mt, pbf, gid);
408   oid = ((*p) & NCI_OID_MASK);
409   if (nfc_cb.rawVsCbflag == true &&
410       nfc_ncif_proc_proprietary_rsp(mt, gid, oid) == true) {
411     nci_proc_prop_raw_vs_rsp(p_msg);
412     nfc_cb.rawVsCbflag = false;
413     return free;
414   }
415 
416   nfcsnoop_capture(p_msg, true);
417   switch (mt) {
418     case NCI_MT_DATA:
419       DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("NFC received data");
420       nfc_ncif_proc_data(p_msg);
421       free = false;
422       break;
423 
424     case NCI_MT_RSP:
425       DLOG_IF(INFO, nfc_debug_enabled)
426           << StringPrintf("NFC received rsp gid:%d", gid);
427       oid = ((*p) & NCI_OID_MASK);
428       p_old = nfc_cb.last_hdr;
429       NCI_MSG_PRS_HDR0(p_old, old_mt, pbf, old_gid);
430       old_oid = ((*p_old) & NCI_OID_MASK);
431       /* make sure this is the RSP we are waiting for before updating the
432        * command window */
433       if ((old_gid != gid) || (old_oid != oid)) {
434         LOG(ERROR) << StringPrintf(
435             "nfc_ncif_process_event unexpected rsp: gid:0x%x, oid:0x%x", gid,
436             oid);
437         return true;
438       }
439 
440       switch (gid) {
441         case NCI_GID_CORE: /* 0000b NCI Core group */
442           free = nci_proc_core_rsp(p_msg);
443           break;
444         case NCI_GID_RF_MANAGE: /* 0001b NCI Discovery group */
445           nci_proc_rf_management_rsp(p_msg);
446           break;
447 #if (NFC_NFCEE_INCLUDED == TRUE)
448 #if (NFC_RW_ONLY == FALSE)
449         case NCI_GID_EE_MANAGE: /* 0x02 0010b NFCEE Discovery group */
450           nci_proc_ee_management_rsp(p_msg);
451           break;
452 #endif
453 #endif
454         case NCI_GID_PROP: /* 1111b Proprietary */
455           nci_proc_prop_rsp(p_msg);
456           break;
457         default:
458           LOG(ERROR) << StringPrintf("NFC: Unknown gid:%d", gid);
459           break;
460       }
461 
462       nfc_ncif_update_window();
463       break;
464 
465     case NCI_MT_NTF:
466       DLOG_IF(INFO, nfc_debug_enabled)
467           << StringPrintf("NFC received ntf gid:%d", gid);
468       switch (gid) {
469         case NCI_GID_CORE: /* 0000b NCI Core group */
470           nci_proc_core_ntf(p_msg);
471           break;
472         case NCI_GID_RF_MANAGE: /* 0001b NCI Discovery group */
473           nci_proc_rf_management_ntf(p_msg);
474           break;
475 #if (NFC_NFCEE_INCLUDED == TRUE)
476 #if (NFC_RW_ONLY == FALSE)
477         case NCI_GID_EE_MANAGE: /* 0x02 0010b NFCEE Discovery group */
478           nci_proc_ee_management_ntf(p_msg);
479           break;
480 #endif
481 #endif
482         case NCI_GID_PROP: /* 1111b Proprietary */
483           nci_proc_prop_ntf(p_msg);
484           break;
485         default:
486           LOG(ERROR) << StringPrintf("NFC: Unknown gid:%d", gid);
487           break;
488       }
489       break;
490 
491     default:
492       DLOG_IF(INFO, nfc_debug_enabled)
493           << StringPrintf("NFC received unknown mt:0x%x, gid:%d", mt, gid);
494   }
495 
496   return (free);
497 }
498 
499 /*******************************************************************************
500 **
501 ** Function         nfc_ncif_rf_management_status
502 **
503 ** Description      This function is called to report an event
504 **
505 ** Returns          void
506 **
507 *******************************************************************************/
nfc_ncif_rf_management_status(tNFC_DISCOVER_EVT event,uint8_t status)508 void nfc_ncif_rf_management_status(tNFC_DISCOVER_EVT event, uint8_t status) {
509   tNFC_DISCOVER evt_data;
510   if (nfc_cb.p_discv_cback) {
511     evt_data.status = (tNFC_STATUS)status;
512     (*nfc_cb.p_discv_cback)(event, &evt_data);
513   }
514 }
515 
516 /*******************************************************************************
517 **
518 ** Function         nfc_ncif_set_config_status
519 **
520 ** Description      This function is called to report NFC_SET_CONFIG_REVT
521 **
522 ** Returns          void
523 **
524 *******************************************************************************/
nfc_ncif_set_config_status(uint8_t * p,uint8_t len)525 void nfc_ncif_set_config_status(uint8_t* p, uint8_t len) {
526   tNFC_RESPONSE evt_data;
527   if (nfc_cb.p_resp_cback) {
528     evt_data.set_config.num_param_id = 0;
529     if (len == 0) {
530       LOG(ERROR) << StringPrintf("Insufficient RSP length");
531       evt_data.set_config.status = NFC_STATUS_SYNTAX_ERROR;
532       (*nfc_cb.p_resp_cback)(NFC_SET_CONFIG_REVT, &evt_data);
533       return;
534     }
535     evt_data.set_config.status = (tNFC_STATUS)*p++;
536     if (evt_data.set_config.status != NFC_STATUS_OK && len > 1) {
537       evt_data.set_config.num_param_id = *p++;
538       if (evt_data.set_config.num_param_id > NFC_MAX_NUM_IDS) {
539         android_errorWriteLog(0x534e4554, "114047681");
540         LOG(ERROR) << StringPrintf("OOB write num_param_id %d",
541                                    evt_data.set_config.num_param_id);
542         evt_data.set_config.num_param_id = 0;
543       } else if (evt_data.set_config.num_param_id <= len - 2) {
544         STREAM_TO_ARRAY(evt_data.set_config.param_ids, p,
545                         evt_data.set_config.num_param_id);
546       } else {
547         LOG(ERROR) << StringPrintf("Insufficient RSP length %d,num_param_id %d",
548                                    len, evt_data.set_config.num_param_id);
549         evt_data.set_config.num_param_id = 0;
550       }
551     }
552     (*nfc_cb.p_resp_cback)(NFC_SET_CONFIG_REVT, &evt_data);
553   }
554 }
555 
556 /*******************************************************************************
557 **
558 ** Function         nfc_ncif_event_status
559 **
560 ** Description      This function is called to report an event
561 **
562 ** Returns          void
563 **
564 *******************************************************************************/
nfc_ncif_event_status(tNFC_RESPONSE_EVT event,uint8_t status)565 void nfc_ncif_event_status(tNFC_RESPONSE_EVT event, uint8_t status) {
566   tNFC_RESPONSE evt_data;
567   if (event == NFC_NFCC_TIMEOUT_REVT && status == NFC_STATUS_HW_TIMEOUT) {
568     uint32_t cmd_hdr = (nfc_cb.last_hdr[0] << 8) | nfc_cb.last_hdr[1];
569     nfc::stats::stats_write(nfc::stats::NFC_ERROR_OCCURRED,
570                             (int32_t)NCI_TIMEOUT, (int32_t)cmd_hdr,
571                             (int32_t)status);
572   }
573   if (nfc_cb.p_resp_cback) {
574     evt_data.status = (tNFC_STATUS)status;
575     (*nfc_cb.p_resp_cback)(event, &evt_data);
576   }
577 }
578 
579 /*******************************************************************************
580 **
581 ** Function         nfc_ncif_error_status
582 **
583 ** Description      This function is called to report an error event to data
584 **                  cback
585 **
586 ** Returns          void
587 **
588 *******************************************************************************/
nfc_ncif_error_status(uint8_t conn_id,uint8_t status)589 void nfc_ncif_error_status(uint8_t conn_id, uint8_t status) {
590   tNFC_CONN_CB* p_cb = nfc_find_conn_cb_by_conn_id(conn_id);
591   if (p_cb && p_cb->p_cback) {
592     tNFC_CONN nfc_conn;
593     nfc_conn.status = status;
594     (*p_cb->p_cback)(conn_id, NFC_ERROR_CEVT, &nfc_conn);
595   }
596   nfc::stats::stats_write(nfc::stats::NFC_ERROR_OCCURRED, (int32_t)ERROR_NTF,
597                           (int32_t)0, (int32_t)status);
598 }
599 
600 /*******************************************************************************
601 **
602 ** Function         nfc_ncif_proc_rf_field_ntf
603 **
604 ** Description      This function is called to process RF field notification
605 **
606 ** Returns          void
607 **
608 *******************************************************************************/
609 #if (NFC_RW_ONLY == FALSE)
nfc_ncif_proc_rf_field_ntf(uint8_t rf_status)610 void nfc_ncif_proc_rf_field_ntf(uint8_t rf_status) {
611   tNFC_RESPONSE evt_data;
612   if (nfc_cb.p_resp_cback) {
613     evt_data.status = (tNFC_STATUS)NFC_STATUS_OK;
614     evt_data.rf_field.rf_field = rf_status;
615     (*nfc_cb.p_resp_cback)(NFC_RF_FIELD_REVT, &evt_data);
616   }
617 }
618 #endif
619 
620 /*******************************************************************************
621 **
622 ** Function         nfc_ncif_proc_credits
623 **
624 ** Description      This function is called to process data credits
625 **
626 ** Returns          void
627 **
628 *******************************************************************************/
nfc_ncif_proc_credits(uint8_t * p,uint16_t plen)629 void nfc_ncif_proc_credits(uint8_t* p, uint16_t plen) {
630   uint8_t num, xx;
631   tNFC_CONN_CB* p_cb;
632 
633   if (plen != 0) {
634     num = *p++;
635     plen--;
636     if (num * 2 > plen) {
637       android_errorWriteLog(0x534e4554, "118148142");
638       return;
639     }
640     for (xx = 0; xx < num; xx++) {
641       p_cb = nfc_find_conn_cb_by_conn_id(*p++);
642       if (p_cb && p_cb->num_buff != NFC_CONN_NO_FC) {
643         p_cb->num_buff += (*p);
644 #if (BT_USE_TRACES == TRUE)
645         if (p_cb->num_buff > p_cb->init_credits) {
646           if (nfc_cb.nfc_state == NFC_STATE_OPEN) {
647             /* if this happens in activated state, it's very likely that our
648              * NFCC has issues */
649             /* However, credit may be returned after deactivation */
650             LOG(ERROR) << StringPrintf("num_buff:0x%x, init_credits:0x%x",
651                                        p_cb->num_buff, p_cb->init_credits);
652           }
653           p_cb->num_buff = p_cb->init_credits;
654         }
655 #endif
656         /* check if there's nay data in tx q to be sent */
657         nfc_ncif_send_data(p_cb, nullptr);
658       }
659       p++;
660     }
661   }
662 }
663 /*******************************************************************************
664 **
665 ** Function         nfc_ncif_decode_rf_params
666 **
667 ** Description      This function is called to process the detected technology
668 **                  and mode and the associated parameters for DISCOVER_NTF and
669 **                  ACTIVATE_NTF
670 **
671 ** Returns          void
672 **
673 *******************************************************************************/
nfc_ncif_decode_rf_params(tNFC_RF_TECH_PARAMS * p_param,uint8_t * p)674 uint8_t* nfc_ncif_decode_rf_params(tNFC_RF_TECH_PARAMS* p_param, uint8_t* p) {
675   tNFC_RF_PA_PARAMS* p_pa;
676   uint8_t len, *p_start, u8;
677   tNFC_RF_PB_PARAMS* p_pb;
678   tNFC_RF_LF_PARAMS* p_lf;
679   tNFC_RF_PF_PARAMS* p_pf;
680   tNFC_RF_PISO15693_PARAMS* p_i93;
681   tNFC_RF_ACM_P_PARAMS* acm_p;
682   uint8_t mpl_idx = 0;
683   uint8_t gb_idx = 0, mpl;
684   uint8_t plen;
685   plen = len = *p++;
686   p_start = p;
687   memset(&p_param->param, 0, sizeof(tNFC_RF_TECH_PARAMU));
688 
689   if (NCI_DISCOVERY_TYPE_POLL_A == p_param->mode ||
690       (NCI_DISCOVERY_TYPE_POLL_A_ACTIVE == p_param->mode &&
691        NFC_GetNCIVersion() != NCI_VERSION_2_0)) {
692     p_pa = &p_param->param.pa;
693     /*
694 SENS_RES Response   2 bytes Defined in [DIGPROT] Available after Technology
695 Detection
696 NFCID1 length   1 byte  Length of NFCID1 Available after Collision Resolution
697 NFCID1  4, 7, or 10 bytes   Defined in [DIGPROT]Available after Collision
698 Resolution
699 SEL_RES Response    1 byte  Defined in [DIGPROT]Available after Collision
700 Resolution
701 HRx Length  1 Octets    Length of HRx Parameters collected from the response to
702 the T1T RID command.
703 HRx 0 or 2 Octets   If present, the first byte SHALL contain HR0 and the second
704 byte SHALL contain HR1 as defined in [DIGITAL].
705     */
706     if (plen < 3) {
707       goto invalid_packet;
708     }
709     plen -= 3;
710     STREAM_TO_ARRAY(p_pa->sens_res, p, 2);
711     p_pa->nfcid1_len = *p++;
712     if (p_pa->nfcid1_len > NCI_NFCID1_MAX_LEN)
713       p_pa->nfcid1_len = NCI_NFCID1_MAX_LEN;
714 
715     if (plen < p_pa->nfcid1_len + 1) {
716       goto invalid_packet;
717     }
718     plen -= (p_pa->nfcid1_len + 1);
719     STREAM_TO_ARRAY(p_pa->nfcid1, p, p_pa->nfcid1_len);
720     u8 = *p++;
721 
722     if (u8) {
723       if (plen < 1) {
724         goto invalid_packet;
725       }
726       plen--;
727       p_pa->sel_rsp = *p++;
728     }
729 
730     if (len ==
731         (7 + p_pa->nfcid1_len + u8)) /* 2(sens_res) + 1(len) +
732                                         p_pa->nfcid1_len + 1(len) + u8 + hr
733                                         (1:len + 2) */
734     {
735       p_pa->hr_len = *p++;
736       if (p_pa->hr_len == NCI_T1T_HR_LEN) {
737         p_pa->hr[0] = *p++;
738         p_pa->hr[1] = *p;
739       }
740     }
741   } else if (NCI_DISCOVERY_TYPE_POLL_B == p_param->mode) {
742     /*
743 SENSB_RES Response length (n)   1 byte  Length of SENSB_RES Response (Byte 2 -
744 Byte 12 or 13)Available after Technology Detection
745 SENSB_RES Response Byte 2 - Byte 12 or 13   11 or 12 bytes  Defined in [DIGPROT]
746 Available after Technology Detection
747     */
748     p_pb = &p_param->param.pb;
749 
750     if (plen < 1) {
751       goto invalid_packet;
752     }
753     plen--;
754     p_pb->sensb_res_len = *p++;
755     if (p_pb->sensb_res_len > NCI_MAX_SENSB_RES_LEN)
756       p_pb->sensb_res_len = NCI_MAX_SENSB_RES_LEN;
757 
758     if (plen < p_pb->sensb_res_len) {
759       goto invalid_packet;
760     }
761     plen -= p_pb->sensb_res_len;
762     STREAM_TO_ARRAY(p_pb->sensb_res, p, p_pb->sensb_res_len);
763     memcpy(p_pb->nfcid0, p_pb->sensb_res, NFC_NFCID0_MAX_LEN);
764   } else if (NCI_DISCOVERY_TYPE_POLL_F == p_param->mode ||
765              (NCI_DISCOVERY_TYPE_POLL_F_ACTIVE == p_param->mode &&
766               NFC_GetNCIVersion() != NCI_VERSION_2_0)) {
767     /*
768 Bit Rate    1 byte  1   212 kbps/2   424 kbps/0 and 3 to 255  RFU
769 SENSF_RES Response length.(n) 1 byte  Length of SENSF_RES (Byte 2 - Byte 17 or
770 19).Available after Technology Detection
771 SENSF_RES Response Byte 2 - Byte 17 or 19  n bytes Defined in [DIGPROT]
772 Available after Technology Detection
773     */
774     p_pf = &p_param->param.pf;
775 
776     if (plen < 2) {
777       goto invalid_packet;
778     }
779     plen -= 2;
780     p_pf->bit_rate = *p++;
781     p_pf->sensf_res_len = *p++;
782     if (p_pf->sensf_res_len > NCI_MAX_SENSF_RES_LEN)
783       p_pf->sensf_res_len = NCI_MAX_SENSF_RES_LEN;
784 
785     if (plen < p_pf->sensf_res_len) {
786       goto invalid_packet;
787     }
788     plen -= p_pf->sensf_res_len;
789     STREAM_TO_ARRAY(p_pf->sensf_res, p, p_pf->sensf_res_len);
790 
791     if (p_pf->sensf_res_len < NCI_MRTI_UPDATE_INDEX + 1) {
792       goto invalid_packet;
793     }
794     memcpy(p_pf->nfcid2, p_pf->sensf_res, NCI_NFCID2_LEN);
795     p_pf->mrti_check = p_pf->sensf_res[NCI_MRTI_CHECK_INDEX];
796     p_pf->mrti_update = p_pf->sensf_res[NCI_MRTI_UPDATE_INDEX];
797   } else if (NCI_DISCOVERY_TYPE_LISTEN_F == p_param->mode ||
798              (NCI_DISCOVERY_TYPE_LISTEN_F_ACTIVE == p_param->mode &&
799               NFC_GetNCIVersion() != NCI_VERSION_2_0)) {
800     p_lf = &p_param->param.lf;
801 
802     if (plen < 1) {
803       goto invalid_packet;
804     }
805     plen--;
806     u8 = *p++;
807     if (u8) {
808       if (plen < NCI_NFCID2_LEN) {
809         goto invalid_packet;
810       }
811       plen -= NCI_NFCID2_LEN;
812       STREAM_TO_ARRAY(p_lf->nfcid2, p, NCI_NFCID2_LEN);
813     }
814   } else if (NCI_DISCOVERY_TYPE_POLL_V == p_param->mode) {
815     p_i93 = &p_param->param.pi93;
816 
817     if (plen < 2) {
818       goto invalid_packet;
819     }
820     plen -= 2;
821     p_i93->flag = *p++;
822     p_i93->dsfid = *p++;
823 
824     if (plen < NFC_ISO15693_UID_LEN) {
825       goto invalid_packet;
826     }
827     plen -= NFC_ISO15693_UID_LEN;
828     STREAM_TO_ARRAY(p_i93->uid, p, NFC_ISO15693_UID_LEN);
829   } else if (NCI_DISCOVERY_TYPE_POLL_KOVIO == p_param->mode) {
830     p_param->param.pk.uid_len = len;
831     if (p_param->param.pk.uid_len > NFC_KOVIO_MAX_LEN) {
832       LOG(ERROR) << StringPrintf("Kovio UID len:0x%x exceeds max(0x%x)",
833                                  p_param->param.pk.uid_len, NFC_KOVIO_MAX_LEN);
834       p_param->param.pk.uid_len = NFC_KOVIO_MAX_LEN;
835     }
836     STREAM_TO_ARRAY(p_param->param.pk.uid, p, p_param->param.pk.uid_len);
837   } else if (NCI_DISCOVERY_TYPE_POLL_ACTIVE == p_param->mode) {
838     acm_p = &p_param->param.acm_p;
839 
840     /* Skip RF Tech Specific Parametres +
841      * Skip RF Technology mode, Tx , Rx baud rate & length params
842      * Byte 1         Byte 2     Byte 3    Byte 4
843      * Tech and Mode  Tx BR      Rx BR     Length of Act Param
844      */
845     p = p + len + 3;
846     plen = *p++;
847     if (plen < 1) {
848       goto invalid_packet;
849     }
850     LOG(INFO) << StringPrintf(
851         "RF Tech Specific Params, plen: 0x%x, atr_res_len: 0x%x", plen, *p);
852     plen--;
853     acm_p->atr_res_len = *p++;
854     if (acm_p->atr_res_len > 0) {
855       if (acm_p->atr_res_len > NFC_MAX_ATS_LEN)
856         acm_p->atr_res_len = NFC_MAX_ATS_LEN;
857 
858       if (plen < acm_p->atr_res_len) {
859         goto invalid_packet;
860       }
861       plen -= acm_p->atr_res_len;
862       STREAM_TO_ARRAY(acm_p->atr_res, p, acm_p->atr_res_len);
863       /* ATR_RES
864       Byte 3~12 Byte 13 Byte 14 Byte 15 Byte 16 Byte 17 Byte 18~18+n
865       NFCID3T   DIDT    BST     BRT     TO      PPT     [GT0 ... GTn] */
866       mpl_idx = 14;
867       gb_idx = NCI_P_GEN_BYTE_INDEX;
868 
869       if (acm_p->atr_res_len < mpl_idx + 1) {
870         goto invalid_packet;
871       }
872       acm_p->waiting_time = acm_p->atr_res[NCI_L_NFC_DEP_TO_INDEX] & 0x0F;
873       mpl = ((acm_p->atr_res[mpl_idx]) >> 4) & 0x03;
874       acm_p->max_payload_size = nfc_mpl_code_to_size[mpl];
875       if (acm_p->atr_res_len > gb_idx) {
876         acm_p->gen_bytes_len = acm_p->atr_res_len - gb_idx;
877         if (acm_p->gen_bytes_len > NFC_MAX_GEN_BYTES_LEN)
878           acm_p->gen_bytes_len = NFC_MAX_GEN_BYTES_LEN;
879         memcpy(acm_p->gen_bytes, &acm_p->atr_res[gb_idx], acm_p->gen_bytes_len);
880       }
881     }
882   } else if (NCI_DISCOVERY_TYPE_LISTEN_ACTIVE == p_param->mode) {
883     acm_p = &p_param->param.acm_p;
884 
885     if (plen < 1) {
886       goto invalid_packet;
887     }
888     plen--;
889     acm_p->atr_res_len = *p++;
890     if (acm_p->atr_res_len > 0) {
891       if (acm_p->atr_res_len > NFC_MAX_ATS_LEN)
892         acm_p->atr_res_len = NFC_MAX_ATS_LEN;
893 
894       if (plen < acm_p->atr_res_len) {
895         goto invalid_packet;
896       }
897       plen -= acm_p->atr_res_len;
898       STREAM_TO_ARRAY(acm_p->atr_res, p, acm_p->atr_res_len);
899       /* ATR_REQ
900       Byte 3~12 Byte 13 Byte 14 Byte 15 Byte 16 Byte 17~17+n
901       NFCID3I   DIDI    BSI     BRI     PPI     [GI0 ... GIn] */
902       mpl_idx = 13;
903       gb_idx = NCI_L_GEN_BYTE_INDEX;
904 
905       if (acm_p->atr_res_len < mpl_idx + 1) {
906         goto invalid_packet;
907       }
908       mpl = ((acm_p->atr_res[mpl_idx]) >> 4) & 0x03;
909       acm_p->max_payload_size = nfc_mpl_code_to_size[mpl];
910       if (acm_p->atr_res_len > gb_idx) {
911         acm_p->gen_bytes_len = acm_p->atr_res_len - gb_idx;
912         if (acm_p->gen_bytes_len > NFC_MAX_GEN_BYTES_LEN)
913           acm_p->gen_bytes_len = NFC_MAX_GEN_BYTES_LEN;
914         memcpy(acm_p->gen_bytes, &acm_p->atr_res[gb_idx], acm_p->gen_bytes_len);
915       }
916     }
917   }
918 invalid_packet:
919   return (p_start + len);
920 }
921 
922 /*******************************************************************************
923 **
924 ** Function         nfc_ncif_proc_discover_ntf
925 **
926 ** Description      This function is called to process discover notification
927 **
928 ** Returns          void
929 **
930 *******************************************************************************/
nfc_ncif_proc_discover_ntf(uint8_t * p,uint16_t plen)931 void nfc_ncif_proc_discover_ntf(uint8_t* p, uint16_t plen) {
932   tNFC_DISCOVER evt_data;
933 
934   if (nfc_cb.p_discv_cback) {
935     // validate packet length should be larger than (NCI header + rf_disc_id +
936     // protocol + mode + length of rf parameters).
937     if (plen < NCI_MSG_HDR_SIZE + 4) {
938       evt_data.status = NCI_STATUS_FAILED;
939       goto invalid_packet;
940     }
941     plen -= (NCI_MSG_HDR_SIZE + 4);
942     p += NCI_MSG_HDR_SIZE;
943     evt_data.status = NCI_STATUS_OK;
944     evt_data.result.rf_disc_id = *p++;
945     evt_data.result.protocol = *p++;
946 
947     /* fill in tNFC_RESULT_DEVT */
948     evt_data.result.rf_tech_param.mode = *p++;
949 
950     // validate packet length should be larger than (rf_tech_param + ntf_type)
951     if (plen < *p + 1) {
952       evt_data.status = NCI_STATUS_FAILED;
953       goto invalid_packet;
954     }
955     plen -= (*p + 1);
956     p = nfc_ncif_decode_rf_params(&evt_data.result.rf_tech_param, p);
957 
958     evt_data.result.more = *p++;
959 
960   invalid_packet:
961     (*nfc_cb.p_discv_cback)(NFC_RESULT_DEVT, &evt_data);
962   }
963 }
964 
965 /*******************************************************************************
966 **
967 ** Function         nfc_ncif_proc_isodep_nak_presence_check_status
968 **
969 ** Description      This function is called to handle response and notification
970 **                  for presence check nak command
971 **
972 ** Returns          void
973 **
974 *******************************************************************************/
nfc_ncif_proc_isodep_nak_presence_check_status(uint8_t status,bool is_ntf)975 void nfc_ncif_proc_isodep_nak_presence_check_status(uint8_t status,
976                                                     bool is_ntf) {
977   rw_t4t_handle_isodep_nak_rsp(status, is_ntf);
978 }
979 /*******************************************************************************
980 **
981 ** Function         nfc_ncif_proc_activate
982 **
983 ** Description      This function is called to process de-activate
984 **                  response and notification
985 **
986 ** Returns          void
987 **
988 *******************************************************************************/
nfc_ncif_proc_activate(uint8_t * p,uint8_t len)989 void nfc_ncif_proc_activate(uint8_t* p, uint8_t len) {
990   tNFC_DISCOVER evt_data;
991   tNFC_INTF_PARAMS* p_intf = &evt_data.activate.intf_param;
992   tNFC_INTF_PA_ISO_DEP* p_pa_iso;
993   tNFC_INTF_LB_ISO_DEP* p_lb_iso;
994   tNFC_INTF_PB_ISO_DEP* p_pb_iso;
995 #if (NFC_RW_ONLY == FALSE)
996   tNFC_INTF_PA_NFC_DEP* p_pa_nfc;
997   int mpl_idx = 0;
998   uint8_t gb_idx = 0, mpl;
999 #endif
1000   uint8_t t0;
1001   tNCI_DISCOVERY_TYPE mode;
1002   tNFC_CONN_CB* p_cb = &nfc_cb.conn_cb[NFC_RF_CONN_ID];
1003   uint8_t *pp, len_act;
1004   uint8_t buff_size, num_buff;
1005   tNFC_RF_PA_PARAMS* p_pa;
1006   uint8_t plen = len, pplen = 0;
1007 
1008   nfc_set_state(NFC_STATE_OPEN);
1009 
1010   memset(p_intf, 0, sizeof(tNFC_INTF_PARAMS));
1011   // validate packet length should be larger than (rf_disc_id + type +
1012   // protocol + mode + buff_size + num_buff + length of rf parameters).
1013   if (plen < 7) {
1014     evt_data.status = NCI_STATUS_FAILED;
1015     goto invalid_packet;
1016   }
1017   plen -= 7;
1018 
1019   evt_data.activate.rf_disc_id = *p++;
1020   p_intf->type = *p++;
1021   evt_data.activate.protocol = *p++;
1022 
1023   if (evt_data.activate.protocol == NCI_PROTOCOL_18092_ACTIVE)
1024     evt_data.activate.protocol = NCI_PROTOCOL_NFC_DEP;
1025 
1026   evt_data.activate.rf_tech_param.mode = *p++;
1027   buff_size = *p++;
1028   num_buff = *p++;
1029   /* fill in tNFC_activate_DEVT */
1030   // validate remaining packet length should be larger than (rf_tech_param +
1031   // data_mode + tx_bitrate + rx_bitrte + len_act).
1032   if (plen < *p + 4) {
1033     evt_data.status = NCI_STATUS_FAILED;
1034     goto invalid_packet;
1035   }
1036   plen -= (*p + 4);
1037   p = nfc_ncif_decode_rf_params(&evt_data.activate.rf_tech_param, p);
1038 
1039   evt_data.activate.data_mode = *p++;
1040   evt_data.activate.tx_bitrate = *p++;
1041   evt_data.activate.rx_bitrate = *p++;
1042   mode = evt_data.activate.rf_tech_param.mode;
1043   len_act = *p++;
1044   DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf(
1045       "nfc_ncif_proc_activate:%d %d, mode:0x%02x", len, len_act, mode);
1046   /* just in case the interface reports activation parameters not defined in the
1047    * NCI spec */
1048   p_intf->intf_param.frame.param_len = len_act;
1049   if (p_intf->intf_param.frame.param_len > NFC_MAX_RAW_PARAMS)
1050     p_intf->intf_param.frame.param_len = NFC_MAX_RAW_PARAMS;
1051   pp = p;
1052 
1053   if (plen < p_intf->intf_param.frame.param_len) {
1054     evt_data.status = NCI_STATUS_FAILED;
1055     goto invalid_packet;
1056   }
1057   STREAM_TO_ARRAY(p_intf->intf_param.frame.param, pp,
1058                   p_intf->intf_param.frame.param_len);
1059   if (evt_data.activate.intf_param.type == NCI_INTERFACE_ISO_DEP) {
1060     /* Make max payload of NCI aligned to max payload of ISO-DEP for better
1061      * performance */
1062     if (buff_size > NCI_ISO_DEP_MAX_INFO) buff_size = NCI_ISO_DEP_MAX_INFO;
1063 
1064     switch (mode) {
1065       case NCI_DISCOVERY_TYPE_POLL_A:
1066         p_pa_iso = &p_intf->intf_param.pa_iso;
1067 
1068         if (plen < 1) {
1069           evt_data.status = NCI_STATUS_FAILED;
1070           goto invalid_packet;
1071         }
1072         plen--;
1073         p_pa_iso->ats_res_len = *p++;
1074 
1075         if (p_pa_iso->ats_res_len == 0) break;
1076 
1077         if (p_pa_iso->ats_res_len > NFC_MAX_ATS_LEN)
1078           p_pa_iso->ats_res_len = NFC_MAX_ATS_LEN;
1079 
1080         if (plen < p_pa_iso->ats_res_len) {
1081           evt_data.status = NCI_STATUS_FAILED;
1082           goto invalid_packet;
1083         }
1084         plen -= p_pa_iso->ats_res_len;
1085         STREAM_TO_ARRAY(p_pa_iso->ats_res, p, p_pa_iso->ats_res_len);
1086 
1087         pplen = p_pa_iso->ats_res_len;
1088         pp = &p_pa_iso->ats_res[NCI_ATS_T0_INDEX];
1089         t0 = p_pa_iso->ats_res[NCI_ATS_T0_INDEX];
1090         pp++;                           /* T0 */
1091         pplen--;
1092         if (t0 & NCI_ATS_TA_MASK) {
1093           if (pplen < 1) {
1094             evt_data.status = NCI_STATUS_FAILED;
1095             goto invalid_packet;
1096           }
1097           pplen--;
1098           pp++; /* TA */
1099         }
1100         if (t0 & NCI_ATS_TB_MASK) {
1101           /* FWI (Frame Waiting time Integer) & SPGI (Start-up Frame Guard time
1102            * Integer) */
1103           if (pplen < 1) {
1104             evt_data.status = NCI_STATUS_FAILED;
1105             goto invalid_packet;
1106           }
1107           pplen--;
1108           p_pa_iso->fwi = (((*pp) >> 4) & 0x0F);
1109           p_pa_iso->sfgi = ((*pp) & 0x0F);
1110           pp++; /* TB */
1111         }
1112         if (t0 & NCI_ATS_TC_MASK) {
1113           if (pplen < 1) {
1114             evt_data.status = NCI_STATUS_FAILED;
1115             goto invalid_packet;
1116           }
1117           pplen--;
1118           p_pa_iso->nad_used = ((*pp) & 0x01);
1119           pp++; /* TC */
1120         }
1121         p_pa_iso->his_byte_len =
1122             (uint8_t)(p_pa_iso->ats_res_len - (pp - p_pa_iso->ats_res));
1123         if (p_pa_iso->his_byte_len > NFC_MAX_HIS_BYTES_LEN)
1124           p_pa_iso->his_byte_len = NFC_MAX_HIS_BYTES_LEN;
1125         if (pplen < p_pa_iso->his_byte_len) {
1126           evt_data.status = NCI_STATUS_FAILED;
1127           goto invalid_packet;
1128         }
1129         memcpy(p_pa_iso->his_byte, pp, p_pa_iso->his_byte_len);
1130         break;
1131 
1132       case NCI_DISCOVERY_TYPE_LISTEN_A:
1133         if (plen < 1) {
1134           evt_data.status = NCI_STATUS_FAILED;
1135           goto invalid_packet;
1136         }
1137         plen--;
1138         p_intf->intf_param.la_iso.rats = *p++;
1139         gettimeofday(&timer_start, nullptr);
1140         break;
1141 
1142       case NCI_DISCOVERY_TYPE_POLL_B:
1143         /* ATTRIB RSP
1144         Byte 1   Byte 2 ~ 2+n-1
1145         MBLI/DID Higher layer - Response
1146         */
1147         p_pb_iso = &p_intf->intf_param.pb_iso;
1148 
1149         if (plen < 1) {
1150           evt_data.status = NCI_STATUS_FAILED;
1151           goto invalid_packet;
1152         }
1153         plen--;
1154         p_pb_iso->attrib_res_len = *p++;
1155 
1156         if (p_pb_iso->attrib_res_len == 0) break;
1157 
1158         if (p_pb_iso->attrib_res_len > NFC_MAX_ATTRIB_LEN)
1159           p_pb_iso->attrib_res_len = NFC_MAX_ATTRIB_LEN;
1160 
1161         if (plen < p_pb_iso->attrib_res_len) {
1162           evt_data.status = NCI_STATUS_FAILED;
1163           goto invalid_packet;
1164         }
1165         plen -= p_pb_iso->attrib_res_len;
1166         STREAM_TO_ARRAY(p_pb_iso->attrib_res, p, p_pb_iso->attrib_res_len);
1167         p_pb_iso->mbli = (p_pb_iso->attrib_res[0]) >> 4;
1168         if (p_pb_iso->attrib_res_len > NFC_PB_ATTRIB_REQ_FIXED_BYTES) {
1169           p_pb_iso->hi_info_len =
1170               p_pb_iso->attrib_res_len - NFC_PB_ATTRIB_REQ_FIXED_BYTES;
1171           if (p_pb_iso->hi_info_len > NFC_MAX_GEN_BYTES_LEN)
1172             p_pb_iso->hi_info_len = NFC_MAX_GEN_BYTES_LEN;
1173           memcpy(p_pb_iso->hi_info,
1174                  &p_pb_iso->attrib_res[NFC_PB_ATTRIB_REQ_FIXED_BYTES],
1175                  p_pb_iso->hi_info_len);
1176         }
1177         break;
1178 
1179       case NCI_DISCOVERY_TYPE_LISTEN_B:
1180         /* ATTRIB CMD
1181         Byte 2~5 Byte 6  Byte 7  Byte 8  Byte 9  Byte 10 ~ 10+k-1
1182         NFCID0   Param 1 Param 2 Param 3 Param 4 Higher layer - INF
1183         */
1184         p_lb_iso = &p_intf->intf_param.lb_iso;
1185 
1186         if (plen < 1) {
1187           evt_data.status = NCI_STATUS_FAILED;
1188           goto invalid_packet;
1189         }
1190         plen--;
1191         p_lb_iso->attrib_req_len = *p++;
1192 
1193         if (p_lb_iso->attrib_req_len == 0) break;
1194 
1195         if (p_lb_iso->attrib_req_len > NFC_MAX_ATTRIB_LEN)
1196           p_lb_iso->attrib_req_len = NFC_MAX_ATTRIB_LEN;
1197 
1198         if (plen < p_lb_iso->attrib_req_len) {
1199           evt_data.status = NCI_STATUS_FAILED;
1200           goto invalid_packet;
1201         }
1202         plen -= p_lb_iso->attrib_req_len;
1203         STREAM_TO_ARRAY(p_lb_iso->attrib_req, p, p_lb_iso->attrib_req_len);
1204 
1205         if (p_lb_iso->attrib_req_len < NFC_NFCID0_MAX_LEN) {
1206           evt_data.status = NCI_STATUS_FAILED;
1207           goto invalid_packet;
1208         }
1209         memcpy(p_lb_iso->nfcid0, p_lb_iso->attrib_req, NFC_NFCID0_MAX_LEN);
1210         if (p_lb_iso->attrib_req_len > NFC_LB_ATTRIB_REQ_FIXED_BYTES) {
1211           p_lb_iso->hi_info_len =
1212               p_lb_iso->attrib_req_len - NFC_LB_ATTRIB_REQ_FIXED_BYTES;
1213           if (p_lb_iso->hi_info_len > NFC_MAX_GEN_BYTES_LEN)
1214             p_lb_iso->hi_info_len = NFC_MAX_GEN_BYTES_LEN;
1215           memcpy(p_lb_iso->hi_info,
1216                  &p_lb_iso->attrib_req[NFC_LB_ATTRIB_REQ_FIXED_BYTES],
1217                  p_lb_iso->hi_info_len);
1218         }
1219         gettimeofday(&timer_start, nullptr);
1220         break;
1221     }
1222 
1223   }
1224 #if (NFC_RW_ONLY == FALSE)
1225   else if (evt_data.activate.intf_param.type == NCI_INTERFACE_NFC_DEP) {
1226     /* Make max payload of NCI aligned to max payload of NFC-DEP for better
1227      * performance */
1228     if (buff_size > NCI_NFC_DEP_MAX_DATA) buff_size = NCI_NFC_DEP_MAX_DATA;
1229 
1230     p_pa_nfc = &p_intf->intf_param.pa_nfc;
1231 
1232     /* Active mode, no info in activation parameters (NCI 2.0) */
1233     if ((NFC_GetNCIVersion() == NCI_VERSION_2_0) &&
1234         ((mode == NCI_DISCOVERY_TYPE_POLL_ACTIVE) ||
1235          (mode == NCI_DISCOVERY_TYPE_LISTEN_ACTIVE))) {
1236         p_pa_nfc->atr_res_len =
1237                   evt_data.activate.rf_tech_param.param.acm_p.atr_res_len;
1238     } else {
1239       if (plen < 1) {
1240         evt_data.status = NCI_STATUS_FAILED;
1241         goto invalid_packet;
1242       }
1243       plen--;
1244       p_pa_nfc->atr_res_len = *p++;
1245     }
1246 
1247     if (p_pa_nfc->atr_res_len > 0) {
1248       if (p_pa_nfc->atr_res_len > NFC_MAX_ATS_LEN)
1249         p_pa_nfc->atr_res_len = NFC_MAX_ATS_LEN;
1250 
1251       if ((NFC_GetNCIVersion() == NCI_VERSION_2_0) &&
1252           ((mode == NCI_DISCOVERY_TYPE_POLL_ACTIVE) ||
1253            (mode == NCI_DISCOVERY_TYPE_LISTEN_ACTIVE))) {
1254          /* NCI 2.0 : ATR_RES is included in RF technology parameters in active mode */
1255          memcpy(p_pa_nfc->atr_res,
1256                 evt_data.activate.rf_tech_param.param.acm_p.atr_res,
1257                 p_pa_nfc->atr_res_len);
1258       } else {
1259         if (plen < p_pa_nfc->atr_res_len) {
1260           evt_data.status = NCI_STATUS_FAILED;
1261           goto invalid_packet;
1262         }
1263         plen -= p_pa_nfc->atr_res_len;
1264         STREAM_TO_ARRAY(p_pa_nfc->atr_res, p, p_pa_nfc->atr_res_len);
1265       }
1266 
1267       if ((mode == NCI_DISCOVERY_TYPE_POLL_A) ||
1268           (mode == NCI_DISCOVERY_TYPE_POLL_F) ||
1269           ((mode == NCI_DISCOVERY_TYPE_POLL_A_ACTIVE ||
1270             mode == NCI_DISCOVERY_TYPE_POLL_F_ACTIVE) &&
1271            NFC_GetNCIVersion() != NCI_VERSION_2_0) ||
1272           (NFC_GetNCIVersion() == NCI_VERSION_2_0 &&
1273            mode == NCI_DISCOVERY_TYPE_POLL_ACTIVE)) {
1274         /* ATR_RES
1275         Byte 3~12 Byte 13 Byte 14 Byte 15 Byte 16 Byte 17 Byte 18~18+n
1276         NFCID3T   DIDT    BST     BRT     TO      PPT     [GT0 ... GTn] */
1277         mpl_idx = 14;
1278         gb_idx = NCI_P_GEN_BYTE_INDEX;
1279 
1280         if (p_pa_nfc->atr_res_len < NCI_L_NFC_DEP_TO_INDEX + 1) {
1281           evt_data.status = NCI_STATUS_FAILED;
1282           goto invalid_packet;
1283         }
1284         p_pa_nfc->waiting_time =
1285             p_pa_nfc->atr_res[NCI_L_NFC_DEP_TO_INDEX] & 0x0F;
1286       } else if ((mode == NCI_DISCOVERY_TYPE_LISTEN_A) ||
1287                  (mode == NCI_DISCOVERY_TYPE_LISTEN_F) ||
1288                  (NFC_GetNCIVersion() != NCI_VERSION_2_0 &&
1289                   (mode == NCI_DISCOVERY_TYPE_LISTEN_A_ACTIVE ||
1290                    mode == NCI_DISCOVERY_TYPE_LISTEN_F_ACTIVE)) ||
1291                  (NFC_GetNCIVersion() == NCI_VERSION_2_0 &&
1292                   mode == NCI_DISCOVERY_TYPE_LISTEN_ACTIVE)) {
1293         /* ATR_REQ
1294         Byte 3~12 Byte 13 Byte 14 Byte 15 Byte 16 Byte 17~17+n
1295         NFCID3I   DIDI    BSI     BRI     PPI     [GI0 ... GIn] */
1296         mpl_idx = 13;
1297         gb_idx = NCI_L_GEN_BYTE_INDEX;
1298       }
1299 
1300       if (p_pa_nfc->atr_res_len < mpl_idx + 1) {
1301         evt_data.status = NCI_STATUS_FAILED;
1302         goto invalid_packet;
1303       }
1304       mpl = ((p_pa_nfc->atr_res[mpl_idx]) >> 4) & 0x03;
1305       p_pa_nfc->max_payload_size = nfc_mpl_code_to_size[mpl];
1306       if (p_pa_nfc->atr_res_len > gb_idx) {
1307         p_pa_nfc->gen_bytes_len = p_pa_nfc->atr_res_len - gb_idx;
1308         if (p_pa_nfc->gen_bytes_len > NFC_MAX_GEN_BYTES_LEN)
1309           p_pa_nfc->gen_bytes_len = NFC_MAX_GEN_BYTES_LEN;
1310         memcpy(p_pa_nfc->gen_bytes, &p_pa_nfc->atr_res[gb_idx],
1311                p_pa_nfc->gen_bytes_len);
1312       }
1313     }
1314   }
1315 #endif
1316   else if ((evt_data.activate.intf_param.type == NCI_INTERFACE_FRAME) &&
1317            (evt_data.activate.protocol == NCI_PROTOCOL_T1T)) {
1318     p_pa = &evt_data.activate.rf_tech_param.param.pa;
1319     if ((len_act == NCI_T1T_HR_LEN) && (p_pa->hr_len == 0)) {
1320       p_pa->hr_len = NCI_T1T_HR_LEN;
1321 
1322       if (plen < 2) {
1323         evt_data.status = NCI_STATUS_FAILED;
1324         goto invalid_packet;
1325       }
1326       plen -= 2;
1327       p_pa->hr[0] = *p++;
1328       p_pa->hr[1] = *p++;
1329     }
1330   }
1331 
1332   p_cb->act_protocol = evt_data.activate.protocol;
1333   p_cb->act_interface = evt_data.activate.intf_param.type;
1334   p_cb->buff_size = buff_size;
1335   p_cb->num_buff = num_buff;
1336   p_cb->init_credits = num_buff;
1337 
1338 invalid_packet:
1339   if (nfc_cb.p_discv_cback) {
1340     (*nfc_cb.p_discv_cback)(NFC_ACTIVATE_DEVT, &evt_data);
1341   }
1342 }
1343 
1344 /*******************************************************************************
1345 **
1346 ** Function         nfc_ncif_proc_deactivate
1347 **
1348 ** Description      This function is called to process de-activate
1349 **                  response and notification
1350 **
1351 ** Returns          void
1352 **
1353 *******************************************************************************/
nfc_ncif_proc_deactivate(uint8_t status,uint8_t deact_type,bool is_ntf)1354 void nfc_ncif_proc_deactivate(uint8_t status, uint8_t deact_type, bool is_ntf) {
1355   tNFC_DISCOVER evt_data;
1356   tNFC_CONN_CB* p_cb = &nfc_cb.conn_cb[NFC_RF_CONN_ID];
1357   void* p_data;
1358 
1359   nfc_set_state(NFC_STATE_IDLE);
1360   evt_data.deactivate.status = status;
1361   evt_data.deactivate.type = deact_type;
1362   evt_data.deactivate.is_ntf = is_ntf;
1363   if (NFC_GetNCIVersion() == NCI_VERSION_2_0) {
1364     evt_data.deactivate.reason = nfc_cb.deact_reason;
1365   }
1366 
1367   while ((p_data = GKI_dequeue(&p_cb->rx_q)) != nullptr) {
1368     GKI_freebuf(p_data);
1369   }
1370 
1371   while ((p_data = GKI_dequeue(&p_cb->tx_q)) != nullptr) {
1372     GKI_freebuf(p_data);
1373   }
1374 
1375   if (p_cb->p_cback) {
1376     tNFC_CONN nfc_conn;
1377     nfc_conn.deactivate = evt_data.deactivate;
1378     (*p_cb->p_cback)(NFC_RF_CONN_ID, NFC_DEACTIVATE_CEVT, &nfc_conn);
1379   }
1380 
1381   if (nfc_cb.p_discv_cback) {
1382     (*nfc_cb.p_discv_cback)(NFC_DEACTIVATE_DEVT, &evt_data);
1383   }
1384 
1385   // clear previous stored tick count if not comsumed
1386   if (timer_start.tv_sec != 0 || timer_start.tv_usec != 0) {
1387     memset(&timer_start, 0, sizeof(timer_start));
1388   }
1389 }
1390 /*******************************************************************************
1391 **
1392 ** Function         nfc_ncif_proc_ee_action
1393 **
1394 ** Description      This function is called to process NFCEE ACTION NTF
1395 **
1396 ** Returns          void
1397 **
1398 *******************************************************************************/
1399 #if (NFC_NFCEE_INCLUDED == TRUE && NFC_RW_ONLY == FALSE)
nfc_ncif_proc_ee_action(uint8_t * p,uint16_t plen)1400 void nfc_ncif_proc_ee_action(uint8_t* p, uint16_t plen) {
1401   tNFC_EE_ACTION_REVT evt_data;
1402   tNFC_RESPONSE_CBACK* p_cback = nfc_cb.p_resp_cback;
1403   tNFC_RESPONSE nfc_response;
1404   uint8_t data_len, ulen, tag, *p_data;
1405   uint8_t max_len;
1406 
1407   if (p_cback) {
1408     memset(&evt_data.act_data, 0, sizeof(tNFC_ACTION_DATA));
1409     if (plen > 3) {
1410       plen -= 3;
1411     } else {
1412       evt_data.status = NFC_STATUS_FAILED;
1413       evt_data.nfcee_id = 0;
1414       nfc_response.ee_action = evt_data;
1415       (*p_cback)(NFC_EE_ACTION_REVT, &nfc_response);
1416       android_errorWriteLog(0x534e4554, "157649306");
1417       return;
1418     }
1419     evt_data.status = NFC_STATUS_OK;
1420     evt_data.nfcee_id = *p++;
1421     evt_data.act_data.trigger = *p++;
1422     data_len = *p++;
1423     if (data_len > plen) data_len = (uint8_t)plen;
1424 
1425     switch (evt_data.act_data.trigger) {
1426       case NCI_EE_TRIG_7816_SELECT:
1427         if (data_len > NFC_MAX_AID_LEN) data_len = NFC_MAX_AID_LEN;
1428         evt_data.act_data.param.aid.len_aid = data_len;
1429         STREAM_TO_ARRAY(evt_data.act_data.param.aid.aid, p, data_len);
1430         break;
1431       case NCI_EE_TRIG_RF_PROTOCOL:
1432         evt_data.act_data.param.protocol = *p++;
1433         break;
1434       case NCI_EE_TRIG_RF_TECHNOLOGY:
1435         evt_data.act_data.param.technology = *p++;
1436         break;
1437       case NCI_EE_TRIG_APP_INIT:
1438         while (data_len > NFC_TL_SIZE) {
1439           data_len -= NFC_TL_SIZE;
1440           tag = *p++;
1441           ulen = *p++;
1442           if (ulen > data_len) ulen = data_len;
1443           p_data = nullptr;
1444           max_len = ulen;
1445           switch (tag) {
1446             case NCI_EE_ACT_TAG_AID: /* AID                 */
1447               if (max_len > NFC_MAX_AID_LEN) max_len = NFC_MAX_AID_LEN;
1448               evt_data.act_data.param.app_init.len_aid = max_len;
1449               p_data = evt_data.act_data.param.app_init.aid;
1450               break;
1451             case NCI_EE_ACT_TAG_DATA: /* hex data for app    */
1452               if (max_len > NFC_MAX_APP_DATA_LEN)
1453                 max_len = NFC_MAX_APP_DATA_LEN;
1454               evt_data.act_data.param.app_init.len_data = max_len;
1455               p_data = evt_data.act_data.param.app_init.data;
1456               break;
1457           }
1458           if (p_data) {
1459             STREAM_TO_ARRAY(p_data, p, max_len);
1460           }
1461           data_len -= ulen;
1462         }
1463         break;
1464     }
1465     nfc_response.ee_action = evt_data;
1466     (*p_cback)(NFC_EE_ACTION_REVT, &nfc_response);
1467   }
1468 }
1469 
1470 /*******************************************************************************
1471 **
1472 ** Function         nfc_ncif_proc_ee_discover_req
1473 **
1474 ** Description      This function is called to process NFCEE DISCOVER REQ NTF
1475 **
1476 ** Returns          void
1477 **
1478 *******************************************************************************/
nfc_ncif_proc_ee_discover_req(uint8_t * p,uint16_t plen)1479 void nfc_ncif_proc_ee_discover_req(uint8_t* p, uint16_t plen) {
1480   tNFC_RESPONSE_CBACK* p_cback = nfc_cb.p_resp_cback;
1481   tNFC_EE_DISCOVER_REQ_REVT ee_disc_req;
1482   tNFC_EE_DISCOVER_INFO* p_info;
1483   uint8_t u8;
1484 
1485   if (!plen) {
1486     android_errorWriteLog(0x534e4554, "221856662");
1487     return;
1488   }
1489 
1490   DLOG_IF(INFO, nfc_debug_enabled)
1491       << StringPrintf("nfc_ncif_proc_ee_discover_req %d len:%d", *p, plen);
1492 
1493   if (!plen) {
1494     android_errorWriteLog(0x534e4554, "221856662");
1495     return;
1496   }
1497 
1498   if (*p > NFC_MAX_EE_DISC_ENTRIES) {
1499     android_errorWriteLog(0x534e4554, "122361874");
1500     LOG(ERROR) << __func__ << "Exceed NFC_MAX_EE_DISC_ENTRIES";
1501     return;
1502   }
1503 
1504   if (p_cback) {
1505     u8 = *p;
1506     ee_disc_req.status = NFC_STATUS_OK;
1507     ee_disc_req.num_info = *p++;
1508     p_info = ee_disc_req.info;
1509     if (plen) plen--;
1510     while ((u8 > 0) && (plen >= NFC_EE_DISCOVER_ENTRY_LEN)) {
1511       p_info->op = *p++;                  /* T */
1512       if (*p != NFC_EE_DISCOVER_INFO_LEN) /* L */
1513       {
1514         DLOG_IF(INFO, nfc_debug_enabled)
1515             << StringPrintf("bad entry len:%d", *p);
1516         return;
1517       }
1518       p++;
1519       /* V */
1520       p_info->nfcee_id = *p++;
1521       p_info->tech_n_mode = *p++;
1522       p_info->protocol = *p++;
1523       u8--;
1524       plen -= NFC_EE_DISCOVER_ENTRY_LEN;
1525       p_info++;
1526     }
1527     tNFC_RESPONSE nfc_response;
1528     nfc_response.ee_discover_req = ee_disc_req;
1529     (*p_cback)(NFC_EE_DISCOVER_REQ_REVT, &nfc_response);
1530   }
1531 }
1532 
1533 /*******************************************************************************
1534 **
1535 ** Function         nfc_ncif_proc_get_routing
1536 **
1537 ** Description      This function is called to process get routing notification
1538 **
1539 ** Returns          void
1540 **
1541 *******************************************************************************/
nfc_ncif_proc_get_routing(uint8_t * p,uint8_t len)1542 void nfc_ncif_proc_get_routing(uint8_t* p, uint8_t len) {
1543   tNFC_GET_ROUTING_REVT evt_data;
1544   uint8_t more, num_entries, xx, *pn;
1545   tNFC_STATUS status = NFC_STATUS_CONTINUE;
1546 
1547   if (len >= 2 && nfc_cb.p_resp_cback) {
1548     more = *p++;
1549     num_entries = *p++;
1550     if (num_entries == 0) return;
1551     len -= 2;
1552     if (len < 2) {
1553       LOG(ERROR) << StringPrintf("Invalid len=%d", len);
1554       return;
1555     }
1556     for (xx = 0; xx < num_entries; xx++) {
1557       if ((more == false) && (xx == (num_entries - 1))) status = NFC_STATUS_OK;
1558       evt_data.status = (tNFC_STATUS)status;
1559       if (len >= 2)
1560         len -= 2;
1561       else
1562         return;
1563       evt_data.qualifier_type = *p++;
1564       evt_data.num_tlvs = 1;
1565       evt_data.tlv_size = *p++;
1566       if (evt_data.tlv_size > NFC_MAX_EE_TLV_SIZE) {
1567         android_errorWriteLog(0x534e4554, "117554809");
1568         LOG(ERROR) << __func__ << "Invalid data format";
1569         return;
1570       }
1571       if (evt_data.tlv_size > len) {
1572         LOG(ERROR) << StringPrintf("Invalid evt_data.tlv_size");
1573         return;
1574       } else
1575         len -= evt_data.tlv_size;
1576       pn = evt_data.param_tlvs;
1577       STREAM_TO_ARRAY(pn, p, evt_data.tlv_size);
1578       tNFC_RESPONSE nfc_response;
1579       nfc_response.get_routing = evt_data;
1580       (*nfc_cb.p_resp_cback)(NFC_GET_ROUTING_REVT, &nfc_response);
1581     }
1582   }
1583 }
1584 #endif
1585 
1586 /*******************************************************************************
1587 **
1588 ** Function         nfc_ncif_proc_conn_create_rsp
1589 **
1590 ** Description      This function is called to process connection create
1591 **                  response
1592 **
1593 ** Returns          void
1594 **
1595 *******************************************************************************/
nfc_ncif_proc_conn_create_rsp(uint8_t * p,uint16_t plen,uint8_t dest_type)1596 void nfc_ncif_proc_conn_create_rsp(uint8_t* p,
1597                                    __attribute__((unused)) uint16_t plen,
1598                                    uint8_t dest_type) {
1599   tNFC_CONN_CB* p_cb;
1600   tNFC_STATUS status;
1601   tNFC_CONN_CBACK* p_cback;
1602   tNFC_CONN evt_data;
1603   uint8_t conn_id;
1604 
1605   /* find the pending connection control block */
1606   p_cb = nfc_find_conn_cb_by_conn_id(NFC_PEND_CONN_ID);
1607   if (p_cb) {
1608     p += NCI_MSG_HDR_SIZE;
1609     status = *p++;
1610     p_cb->buff_size = *p++;
1611     p_cb->num_buff = p_cb->init_credits = *p++;
1612     conn_id = *p++;
1613     if (conn_id > NFC_MAX_CONN_ID) {
1614       status = NCI_STATUS_FAILED;
1615       conn_id = NFC_ILLEGAL_CONN_ID;
1616     }
1617     evt_data.conn_create.status = status;
1618     evt_data.conn_create.dest_type = dest_type;
1619     evt_data.conn_create.id = p_cb->id;
1620     evt_data.conn_create.buff_size = p_cb->buff_size;
1621     evt_data.conn_create.num_buffs = p_cb->num_buff;
1622     p_cback = p_cb->p_cback;
1623     if (status == NCI_STATUS_OK) {
1624       nfc_set_conn_id(p_cb, conn_id);
1625     } else {
1626       nfc_free_conn_cb(p_cb);
1627     }
1628 
1629     if (p_cback) (*p_cback)(conn_id, NFC_CONN_CREATE_CEVT, &evt_data);
1630   }
1631 }
1632 
1633 /*******************************************************************************
1634 **
1635 ** Function         nfc_ncif_report_conn_close_evt
1636 **
1637 ** Description      This function is called to report connection close event
1638 **
1639 ** Returns          void
1640 **
1641 *******************************************************************************/
nfc_ncif_report_conn_close_evt(uint8_t conn_id,tNFC_STATUS status)1642 void nfc_ncif_report_conn_close_evt(uint8_t conn_id, tNFC_STATUS status) {
1643   tNFC_CONN evt_data;
1644   tNFC_CONN_CBACK* p_cback;
1645   tNFC_CONN_CB* p_cb;
1646 
1647   p_cb = nfc_find_conn_cb_by_conn_id(conn_id);
1648   if (p_cb) {
1649     p_cback = p_cb->p_cback;
1650     nfc_free_conn_cb(p_cb);
1651     evt_data.status = status;
1652     if (p_cback) (*p_cback)(conn_id, NFC_CONN_CLOSE_CEVT, &evt_data);
1653   }
1654 }
1655 
1656 /*******************************************************************************
1657 **
1658 ** Function         nfc_ncif_proc_reset_rsp
1659 **
1660 ** Description      This function is called to process reset
1661 **                  response/notification
1662 **
1663 ** Returns          void
1664 **
1665 *******************************************************************************/
nfc_ncif_proc_reset_rsp(uint8_t * p,bool is_ntf)1666 void nfc_ncif_proc_reset_rsp(uint8_t* p, bool is_ntf) {
1667   uint8_t* p_len = p - 1;
1668   uint8_t status = NCI_STATUS_FAILED;
1669   uint8_t wait_for_ntf = FALSE;
1670 
1671   status = *p_len > 0 ? *p++ : NCI_STATUS_FAILED;
1672   if (*p_len > 2 && is_ntf) {
1673     LOG(WARNING) << StringPrintf("reset notification!!:0x%x ", status);
1674     /* clean up, if the state is OPEN
1675      * FW does not report reset ntf right now */
1676     if (status == NCI2_0_RESET_TRIGGER_TYPE_CORE_RESET_CMD_RECEIVED ||
1677         status == NCI2_0_RESET_TRIGGER_TYPE_POWERED_ON) {
1678       DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf(
1679           "CORE_RESET_NTF Received status nfc_state : 0x%x : 0x%x", status,
1680           nfc_cb.nfc_state);
1681       nfc_stop_timer(&nfc_cb.nci_wait_rsp_timer);
1682       p++;
1683       STREAM_TO_UINT8(nfc_cb.nci_version, p);
1684       DLOG_IF(INFO, nfc_debug_enabled)
1685           << StringPrintf(" CORE_RESET_NTF nci_version%x", nfc_cb.nci_version);
1686       status = NCI_STATUS_OK;
1687     } else {
1688       /* CORE_RESET_NTF received error case , trigger recovery*/
1689       LOG(ERROR) << StringPrintf(
1690           "CORE_RESET_NTF Received status nfc_state : 0x%x : 0x%x", status,
1691           nfc_cb.nfc_state);
1692       nfc_ncif_cmd_timeout();
1693       status = NCI_STATUS_FAILED;
1694     }
1695     if (nfc_cb.nfc_state == NFC_STATE_OPEN) {
1696       /*if any conn_cb is connected, close it.
1697         if any pending outgoing packets are dropped.*/
1698       nfc_reset_all_conn_cbs();
1699     }
1700   } else {
1701     DLOG_IF(INFO, nfc_debug_enabled)
1702         << StringPrintf("CORE_RESET_RSP len :0x%x ", *p_len);
1703     if ((*p_len) == NCI_CORE_RESET_RSP_LEN(NCI_VERSION_2_0)) {
1704       wait_for_ntf = TRUE;
1705     } else if ((*p_len) == NCI_CORE_RESET_RSP_LEN(NCI_VERSION_1_0)) {
1706       nfc_cb.nci_version = NCI_VERSION_1_0;
1707     }
1708   }
1709 
1710   if (nfc_cb.flags & (NFC_FL_RESTARTING | NFC_FL_POWER_CYCLE_NFCC)) {
1711     nfc_reset_all_conn_cbs();
1712   }
1713 
1714   if (status == NCI_STATUS_OK) {
1715     if (wait_for_ntf == TRUE) {
1716       /* reset version reported by NFCC is NCI2.0 , start a timer for 2000ms to
1717        * wait for NTF*/
1718       nfc_start_timer(&nfc_cb.nci_wait_rsp_timer,
1719                       (uint16_t)(NFC_TTYPE_NCI_WAIT_RSP),
1720                       nfc_cb.nci_wait_rsp_tout);
1721     } else {
1722       if (nfc_cb.nci_version == NCI_VERSION_1_0)
1723         nci_snd_core_init(NCI_VERSION_1_0);
1724       else
1725         nci_snd_core_init(NCI_VERSION_2_0);
1726     }
1727   } else {
1728     LOG(ERROR) << StringPrintf("Failed to reset NFCC");
1729     nfc_enabled(status, nullptr);
1730   }
1731 }
1732 
1733 /*******************************************************************************
1734 **
1735 ** Function         nfc_ncif_proc_init_rsp
1736 **
1737 ** Description      This function is called to process init response
1738 **
1739 ** Returns          void
1740 **
1741 *******************************************************************************/
nfc_ncif_proc_init_rsp(NFC_HDR * p_msg)1742 void nfc_ncif_proc_init_rsp(NFC_HDR* p_msg) {
1743   uint8_t *p, status;
1744   tNFC_CONN_CB* p_cb = &nfc_cb.conn_cb[NFC_RF_CONN_ID];
1745 
1746   p = (uint8_t*)(p_msg + 1) + p_msg->offset;
1747 
1748   /* handle init params in nfc_enabled */
1749   status = *(p + NCI_MSG_HDR_SIZE);
1750   if (status == NCI_STATUS_OK) {
1751     if (nfc_cb.nci_version == NCI_VERSION_UNKNOWN) {
1752       nci_snd_core_reset(NCI_RESET_TYPE_RESET_CFG);
1753     } else {
1754       p_cb->id = NFC_RF_CONN_ID;
1755       // check scbr bit as per NCI 2.0 spec
1756       nfc_cb.isScbrSupported = p[5] & NCI_SCBR_MASK;
1757       DLOG_IF(INFO, nfc_debug_enabled)
1758           << StringPrintf("scbr support: 0x%x", nfc_cb.isScbrSupported);
1759       p_cb->act_protocol = NCI_PROTOCOL_UNKNOWN;
1760 
1761       nfc_set_state(NFC_STATE_W4_POST_INIT_CPLT);
1762 
1763       nfc_cb.p_nci_init_rsp = p_msg;
1764       nfc_cb.p_hal->core_initialized(p_msg->len, p);
1765     }
1766   } else {
1767     if (nfc_cb.nci_version == NCI_VERSION_UNKNOWN) {
1768       nfc_cb.nci_version = NCI_VERSION_1_0;
1769       nci_snd_core_reset(NCI_RESET_TYPE_RESET_CFG);
1770     } else {
1771       nfc_enabled(status, nullptr);
1772       GKI_freebuf(p_msg);
1773     }
1774   }
1775 }
1776 
1777 /*******************************************************************************
1778 **
1779 ** Function         nfc_ncif_proc_get_config_rsp
1780 **
1781 ** Description      This function is called to process get config response
1782 **
1783 ** Returns          void
1784 **
1785 *******************************************************************************/
nfc_ncif_proc_get_config_rsp(NFC_HDR * p_evt)1786 void nfc_ncif_proc_get_config_rsp(NFC_HDR* p_evt) {
1787   uint8_t* p;
1788   tNFC_RESPONSE_CBACK* p_cback = nfc_cb.p_resp_cback;
1789   tNFC_RESPONSE evt_data;
1790 
1791   p_evt->offset += NCI_MSG_HDR_SIZE;
1792   p_evt->len -= NCI_MSG_HDR_SIZE;
1793   if (p_cback) {
1794     p = (uint8_t*)(p_evt + 1) + p_evt->offset;
1795     evt_data.get_config.status = *p++;
1796     evt_data.get_config.tlv_size = p_evt->len;
1797     evt_data.get_config.p_param_tlvs = p;
1798     (*p_cback)(NFC_GET_CONFIG_REVT, &evt_data);
1799   }
1800 }
1801 
1802 /*******************************************************************************
1803 **
1804 ** Function         nfc_ncif_proc_t3t_polling_rsp
1805 **
1806 ** Description      Handle NCI_MSG_RF_T3T_POLLING RSP
1807 **
1808 ** Returns          void
1809 **
1810 *******************************************************************************/
nfc_ncif_proc_t3t_polling_rsp(uint8_t status)1811 void nfc_ncif_proc_t3t_polling_rsp(uint8_t status) {
1812   rw_t3t_handle_nci_poll_rsp(status);
1813 }
1814 
1815 /*******************************************************************************
1816 **
1817 ** Function         nfc_ncif_proc_t3t_polling_ntf
1818 **
1819 ** Description      Handle NCI_MSG_RF_T3T_POLLING NTF
1820 **
1821 ** Returns          void
1822 **
1823 *******************************************************************************/
nfc_ncif_proc_t3t_polling_ntf(uint8_t * p,uint16_t plen)1824 void nfc_ncif_proc_t3t_polling_ntf(uint8_t* p, uint16_t plen) {
1825   uint8_t status;
1826   uint8_t num_responses;
1827 
1828   if (plen < NFC_TL_SIZE) {
1829     return;
1830   }
1831 
1832   /* Pass result to RW_T3T for processing */
1833   STREAM_TO_UINT8(status, p);
1834   STREAM_TO_UINT8(num_responses, p);
1835   plen -= NFC_TL_SIZE;
1836   rw_t3t_handle_nci_poll_ntf(status, num_responses, (uint8_t)plen, p);
1837 }
1838 
1839 /*******************************************************************************
1840 **
1841 ** Function         nfc_data_event
1842 **
1843 ** Description      Report Data event on the given connection control block
1844 **
1845 ** Returns          void
1846 **
1847 *******************************************************************************/
nfc_data_event(tNFC_CONN_CB * p_cb)1848 void nfc_data_event(tNFC_CONN_CB* p_cb) {
1849   NFC_HDR* p_evt;
1850   tNFC_DATA_CEVT data_cevt;
1851   uint8_t* p;
1852 
1853   if (p_cb->p_cback) {
1854     while ((p_evt = (NFC_HDR*)GKI_getfirst(&p_cb->rx_q)) != nullptr) {
1855       if (p_evt->layer_specific & NFC_RAS_FRAGMENTED) {
1856         /* Not the last fragment */
1857         if (!(p_evt->layer_specific & NFC_RAS_TOO_BIG)) {
1858           /* buffer can hold more */
1859           if ((p_cb->conn_id != NFC_RF_CONN_ID) || (nfc_cb.reassembly)) {
1860             /* If not rf connection or If rf connection and reassembly
1861              * requested,
1862              * try to Reassemble next packet */
1863             break;
1864           }
1865         }
1866       }
1867 
1868       p_evt = (NFC_HDR*)GKI_dequeue(&p_cb->rx_q);
1869       /* report data event */
1870       p_evt->offset += NCI_MSG_HDR_SIZE;
1871       p_evt->len -= NCI_MSG_HDR_SIZE;
1872 
1873       if (p_evt->layer_specific)
1874         data_cevt.status = NFC_STATUS_CONTINUE;
1875       else {
1876         nfc_cb.reassembly = true;
1877         data_cevt.status = NFC_STATUS_OK;
1878       }
1879 
1880       data_cevt.p_data = p_evt;
1881       /* adjust payload, if needed */
1882       if (p_cb->conn_id == NFC_RF_CONN_ID && p_evt->len) {
1883         /* if NCI_PROTOCOL_T1T/NCI_PROTOCOL_T2T/NCI_PROTOCOL_T3T, the status
1884          * byte needs to be removed
1885          */
1886         if ((p_cb->act_protocol >= NCI_PROTOCOL_T1T) &&
1887             (p_cb->act_protocol <= NCI_PROTOCOL_T3T)) {
1888           p_evt->len--;
1889           p = (uint8_t*)(p_evt + 1);
1890           data_cevt.status = *(p + p_evt->offset + p_evt->len);
1891           if ((NFC_GetNCIVersion() == NCI_VERSION_2_0) &&
1892               (p_cb->act_protocol == NCI_PROTOCOL_T2T) &&
1893               (p_cb->act_interface == NCI_INTERFACE_FRAME)) {
1894             if ((data_cevt.status != NFC_STATUS_OK) &&
1895                 ((data_cevt.status >= T2T_STATUS_OK_1_BIT) &&
1896                  (data_cevt.status <= T2T_STATUS_OK_7_BIT))) {
1897               DLOG_IF(INFO, nfc_debug_enabled)
1898                   << StringPrintf("%s: T2T tag data xchange", __func__);
1899               data_cevt.status = NFC_STATUS_OK;
1900             }
1901           }
1902         }
1903         if ((NFC_GetNCIVersion() == NCI_VERSION_2_0) &&
1904             (p_cb->act_protocol == NCI_PROTOCOL_T5T)) {
1905           p_evt->len--;
1906           p = (uint8_t*)(p_evt + 1);
1907           data_cevt.status = *(p + p_evt->offset + p_evt->len);
1908         }
1909       }
1910       tNFC_CONN nfc_conn;
1911       nfc_conn.data = data_cevt;
1912       (*p_cb->p_cback)(p_cb->conn_id, NFC_DATA_CEVT, &nfc_conn);
1913       p_evt = nullptr;
1914     }
1915   }
1916 }
1917 
1918 /*******************************************************************************
1919 **
1920 ** Function         nfc_ncif_proc_data
1921 **
1922 ** Description      Find the connection control block associated with the data
1923 **                  packet. Assemble the data packet, if needed.
1924 **                  Report the Data event.
1925 **
1926 ** Returns          void
1927 **
1928 *******************************************************************************/
nfc_ncif_proc_data(NFC_HDR * p_msg)1929 void nfc_ncif_proc_data(NFC_HDR* p_msg) {
1930   uint8_t *pp, cid;
1931   tNFC_CONN_CB* p_cb;
1932   uint8_t pbf;
1933   NFC_HDR* p_last;
1934   uint8_t *ps, *pd;
1935   uint16_t size;
1936   NFC_HDR* p_max = nullptr;
1937   uint16_t len;
1938 
1939   pp = (uint8_t*)(p_msg + 1) + p_msg->offset;
1940   DLOG_IF(INFO, nfc_debug_enabled)
1941       << StringPrintf("nfc_ncif_proc_data 0x%02x%02x%02x", pp[0], pp[1], pp[2]);
1942   NCI_DATA_PRS_HDR(pp, pbf, cid, len);
1943   p_cb = nfc_find_conn_cb_by_conn_id(cid);
1944   if (p_cb && (p_msg->len >= NCI_DATA_HDR_SIZE)) {
1945     DLOG_IF(INFO, nfc_debug_enabled)
1946         << StringPrintf("nfc_ncif_proc_data len:%d", len);
1947 
1948     len = p_msg->len - NCI_MSG_HDR_SIZE;
1949     p_msg->layer_specific = 0;
1950     if (pbf) {
1951       NFC_SetReassemblyFlag(true);
1952       p_msg->layer_specific = NFC_RAS_FRAGMENTED;
1953     }
1954     p_last = (NFC_HDR*)GKI_getlast(&p_cb->rx_q);
1955     if (p_last && (p_last->layer_specific & NFC_RAS_FRAGMENTED)) {
1956       /* last data buffer is not last fragment, append this new packet to the
1957        * last */
1958       size = GKI_get_buf_size(p_last);
1959       if (size < (NFC_HDR_SIZE + p_last->len + p_last->offset + len)) {
1960         /* the current size of p_last is not big enough to hold the new
1961          * fragment, p_msg */
1962         if (size != GKI_MAX_BUF_SIZE) {
1963           /* try the biggest GKI pool */
1964           p_max = (NFC_HDR*)GKI_getpoolbuf(GKI_MAX_BUF_SIZE_POOL_ID);
1965           if (p_max) {
1966             /* copy the content of last buffer to the new buffer */
1967             memcpy(p_max, p_last, NFC_HDR_SIZE);
1968             pd = (uint8_t*)(p_max + 1) + p_max->offset;
1969             ps = (uint8_t*)(p_last + 1) + p_last->offset;
1970             memcpy(pd, ps, p_last->len);
1971 
1972             /* place the new buffer in the queue instead */
1973             GKI_remove_from_queue(&p_cb->rx_q, p_last);
1974             GKI_freebuf(p_last);
1975             GKI_enqueue(&p_cb->rx_q, p_max);
1976             p_last = p_max;
1977           }
1978         }
1979         if (p_max == nullptr) {
1980           /* Biggest GKI Pool not available (or)
1981            * Biggest available GKI Pool is not big enough to hold the new
1982            * fragment, p_msg */
1983           p_last->layer_specific |= NFC_RAS_TOO_BIG;
1984         }
1985       }
1986 
1987       ps = (uint8_t*)(p_msg + 1) + p_msg->offset + NCI_MSG_HDR_SIZE;
1988 
1989       if (!(p_last->layer_specific & NFC_RAS_TOO_BIG)) {
1990         pd = (uint8_t*)(p_last + 1) + p_last->offset + p_last->len;
1991         memcpy(pd, ps, len);
1992         p_last->len += len;
1993         /* do not need to update pbf and len in NCI header.
1994          * They are stripped off at NFC_DATA_CEVT and len may exceed 255 */
1995         DLOG_IF(INFO, nfc_debug_enabled)
1996             << StringPrintf("nfc_ncif_proc_data len:%d", p_last->len);
1997         p_last->layer_specific = p_msg->layer_specific;
1998         GKI_freebuf(p_msg);
1999         nfc_data_event(p_cb);
2000       } else {
2001         /* Not enough memory to add new buffer
2002          * Send data already in queue first with status Continue */
2003         nfc_data_event(p_cb);
2004         /* now enqueue the new buffer to the rx queue */
2005         GKI_enqueue(&p_cb->rx_q, p_msg);
2006       }
2007     } else {
2008       /* if this is the first fragment on RF link */
2009       if ((p_msg->layer_specific & NFC_RAS_FRAGMENTED) &&
2010           (p_cb->conn_id == NFC_RF_CONN_ID) && (p_cb->p_cback)) {
2011         /* Indicate upper layer that local device started receiving data */
2012         (*p_cb->p_cback)(p_cb->conn_id, NFC_DATA_START_CEVT, nullptr);
2013       }
2014       /* enqueue the new buffer to the rx queue */
2015       GKI_enqueue(&p_cb->rx_q, p_msg);
2016       nfc_data_event(p_cb);
2017     }
2018     return;
2019   }
2020   GKI_freebuf(p_msg);
2021 }
2022 
2023 /*******************************************************************************
2024 **
2025 ** Function         nfc_ncif_process_proprietary_rsp
2026 **
2027 ** Description      Process the response to avoid collision
2028 **                  while rawVsCbflag is set
2029 **
2030 ** Returns          true if proprietary response else false
2031 **
2032 *******************************************************************************/
nfc_ncif_proc_proprietary_rsp(uint8_t mt,uint8_t gid,uint8_t oid)2033 bool nfc_ncif_proc_proprietary_rsp(uint8_t mt, uint8_t gid, uint8_t oid) {
2034   bool stat = FALSE;
2035   DLOG_IF(INFO, nfc_debug_enabled)
2036       << StringPrintf("%s: mt=%u, gid=%u, oid=%u", __func__, mt, gid, oid);
2037 
2038   switch (mt) {
2039     case NCI_MT_DATA:
2040       /* check for Data Response */
2041       if (gid != 0x03 && oid != 0x00) stat = TRUE;
2042       break;
2043 
2044     case NCI_MT_NTF:
2045       switch (gid) {
2046         case NCI_GID_CORE:
2047           /* check for CORE_RESET_NTF or CORE_CONN_CREDITS_NTF */
2048           if (oid != 0x00 && oid != 0x06) stat = TRUE;
2049           break;
2050         case NCI_GID_RF_MANAGE:
2051           /* check for CORE_CONN_CREDITS_NTF or NFA_EE_ACTION_NTF or
2052            * NFA_EE_DISCOVERY_REQ_NTF */
2053           if (oid != 0x06 && oid != 0x09 && oid != 0x0A) stat = TRUE;
2054           break;
2055         case NCI_GID_EE_MANAGE:
2056           if (oid != 0x00) stat = TRUE;
2057           break;
2058         default:
2059           stat = TRUE;
2060           break;
2061       }
2062       break;
2063 
2064     default:
2065       stat = TRUE;
2066       break;
2067   }
2068   DLOG_IF(INFO, nfc_debug_enabled)
2069       << StringPrintf("%s: exit status=%u", __func__, stat);
2070   return stat;
2071 }
2072 
2073 /*******************************************************************************
2074 ** Function         nfc_mode_set_ntf_timeout
2075 **
2076 ** Description      This function is invoked on mode set ntf timeout
2077 **
2078 ** Returns          void
2079 **
2080 *******************************************************************************/
nfc_mode_set_ntf_timeout()2081 void nfc_mode_set_ntf_timeout() {
2082   LOG(ERROR) << StringPrintf("%s", __func__);
2083   tNFC_RESPONSE nfc_response;
2084   nfc_response.mode_set.status = NCI_STATUS_FAILED;
2085   nfc_response.mode_set.nfcee_id = *nfc_cb.last_nfcee_cmd;
2086   nfc_response.mode_set.mode = NCI_NFCEE_MD_DEACTIVATE;
2087 
2088   tNFC_RESPONSE_CBACK* p_cback = nfc_cb.p_resp_cback;
2089   tNFC_RESPONSE_EVT event = NFC_NFCEE_MODE_SET_REVT;
2090   if (p_cback) (*p_cback)(event, &nfc_response);
2091 }
2092