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