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