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