Home | History | Annotate | Download | only in adaptation
      1 /******************************************************************************
      2  *
      3  *  Copyright (C) 1999-2012 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 #include "OverrideLog.h"
     20 #include <string.h>
     21 #include "gki.h"
     22 #include "nfc_hal_api.h"
     23 #include "nfc_hal_int.h"
     24 #include "userial.h"
     25 #include "nfc_target.h"
     26 
     27 #include <pthread.h>
     28 #include <termios.h>
     29 #include <fcntl.h>
     30 #include <errno.h>
     31 #include <stdio.h>
     32 #include <gki_int.h>
     33 #include "hcidefs.h"
     34 #include <poll.h>
     35 #include "upio.h"
     36 #include "bcm2079x.h"
     37 #include "config.h"
     38 
     39 #define HCISU_EVT                           EVENT_MASK(APPL_EVT_0)
     40 #define MAX_ERROR                           10
     41 #define default_transport                   "/dev/bcm2079x"
     42 
     43 #define NUM_RESET_ATTEMPTS                  5
     44 #define NFC_WAKE_ASSERTED_ON_POR            UPIO_OFF
     45 
     46 #ifndef BTE_APPL_MAX_USERIAL_DEV_NAME
     47 #define BTE_APPL_MAX_USERIAL_DEV_NAME           (256)
     48 #endif
     49 extern UINT8 appl_trace_level;
     50 
     51 /* Mapping of USERIAL_PORT_x to linux */
     52 extern UINT32 ScrProtocolTraceFlag;
     53 static tUPIO_STATE current_nfc_wake_state = UPIO_OFF;
     54 int uart_port  = 0;
     55 int isLowSpeedTransport = 0;
     56 int nfc_wake_delay = 0;
     57 int nfc_write_delay = 0;
     58 int gPowerOnDelay = 300;
     59 static int gPrePowerOffDelay = 0;    // default value
     60 static int gPostPowerOffDelay = 0;     // default value
     61 static pthread_mutex_t close_thread_mutex = PTHREAD_MUTEX_INITIALIZER;
     62 
     63 char userial_dev[BTE_APPL_MAX_USERIAL_DEV_NAME+1];
     64 char power_control_dev[BTE_APPL_MAX_USERIAL_DEV_NAME+1];
     65 tSNOOZE_MODE_CONFIG gSnoozeModeCfg = {
     66     NFC_HAL_LP_SNOOZE_MODE_SPI_I2C,     /* Sleep Mode (0=Disabled 1=UART 8=SPI/I2C) */
     67     NFC_HAL_LP_IDLE_THRESHOLD_HOST,     /* Idle Threshold Host */
     68     NFC_HAL_LP_IDLE_THRESHOLD_HC,       /* Idle Threshold HC */
     69     NFC_HAL_LP_ACTIVE_LOW,              /* NFC Wake active mode (0=ActiveLow 1=ActiveHigh) */
     70     NFC_HAL_LP_ACTIVE_HIGH              /* Host Wake active mode (0=ActiveLow 1=ActiveHigh) */
     71 };
     72 
     73 UINT8 bcmi2cnfc_client_addr = 0;
     74 UINT8 bcmi2cnfc_read_multi_packets = 0;
     75 
     76 #define USERIAL_Debug_verbose     ((ScrProtocolTraceFlag & 0x80000000) == 0x80000000)
     77 
     78 #include <sys/socket.h>
     79 
     80 #define LOG_TAG "USERIAL_LINUX"
     81 
     82 static UINT8 spi_negotiation[10] = { 0xF0, /* CMD */
     83                                     0x00, /* SPI PARM Negotiation */
     84                                     0x01, /* SPI Version */
     85                                     0x00, /* SPI Mode:0, SPI_INT active low */
     86                                     0x00, /* 8Bit, MSB first, Little Endian byte order */
     87                                     0x00, /* Reserved */
     88                                     0xFF, /* Sleep timeout Lower Byte */
     89                                     0xFF, /* Sleep timeout Upper Byte */
     90                                     0x00, /* Reserved */
     91                                     0x00 /* Reserved */
     92 };
     93 static UINT8 spi_nego_res[20];
     94 
     95 #include <ctype.h>
     96 
     97 #define USING_BRCM_USB TRUE
     98 
     99 /* use tc interface to change baudrate instead of close/open sequence which can fail on some platforms
    100  * due to tx line movement when opeing/closing the UART. the 43xx do not like this. */
    101 #ifndef USERIAL_USE_TCIO_BAUD_CHANGE
    102 #define USERIAL_USE_TCIO_BAUD_CHANGE FALSE
    103 #endif
    104 
    105 #ifndef USERIAL_USE_IO_BT_WAKE
    106 #define USERIAL_USE_IO_BT_WAKE FALSE
    107 #endif
    108 
    109 /* this are the ioctl values used for bt_wake ioctl via UART driver. you may need to redefine at for
    110  * you platform! Logically they need to be unique and not colide with existing uart ioctl's.
    111  */
    112 #ifndef USERIAL_IO_BT_WAKE_ASSERT
    113 #define USERIAL_IO_BT_WAKE_ASSERT   0x8003
    114 #endif
    115 #ifndef USERIAL_IO_BT_WAKE_DEASSERT
    116 #define USERIAL_IO_BT_WAKE_DEASSERT 0x8004
    117 #endif
    118 #ifndef USERIAL_IO_BT_WAKE_GET_ST
    119 #define USERIAL_IO_BT_WAKE_GET_ST   0x8005
    120 #endif
    121 
    122 /* the read limit in this current implementation depends on the GKI_BUF3_SIZE
    123  * It would be better to use some ring buffer from the USERIAL_Read() is reading
    124  * instead of putting it into GKI buffers.
    125  */
    126 #define READ_LIMIT (USERIAL_POOL_BUF_SIZE-BT_HDR_SIZE)
    127 /*
    128  * minimum buffer size requirement to read a full sized packet from NFCC = 255 + 4 byte header
    129  */
    130 #define MIN_BUFSIZE 259
    131 #define     POLL_TIMEOUT    1000
    132 /* priority of the reader thread */
    133 #define USERIAL_READ_TRHEAD_PRIO 90
    134 /* time (ms) to wait before trying to allocate again a GKI buffer */
    135 #define NO_GKI_BUFFER_RECOVER_TIME 100
    136 #define MAX_SERIAL_PORT (USERIAL_PORT_15 + 1)
    137 
    138 extern void dumpbin(const char* data, int size);
    139 extern UINT8 *scru_dump_hex (UINT8 *p, char *p_title, UINT32 len, UINT32 trace_layer, UINT32 trace_type);
    140 
    141 static pthread_t      worker_thread1 = 0;
    142 
    143 typedef struct  {
    144     volatile unsigned long bt_wake_state;
    145     int             sock;
    146     tUSERIAL_CBACK      *ser_cb;
    147     UINT16      baud;
    148     UINT8       data_bits;
    149     UINT16      parity;
    150     UINT8       stop_bits;
    151     UINT8       port;
    152     tUSERIAL_OPEN_CFG open_cfg;
    153     int         sock_power_control;
    154     int         client_device_address;
    155     struct timespec write_time;
    156 } tLINUX_CB;
    157 
    158 static tLINUX_CB linux_cb;  /* case of multipel port support use array : [MAX_SERIAL_PORT] */
    159 
    160 void userial_close_thread(UINT32 params);
    161 
    162 static UINT8 device_name[BTE_APPL_MAX_USERIAL_DEV_NAME+1];
    163 static int   bSerialPortDevice = FALSE;
    164 static int _timeout = POLL_TIMEOUT;
    165 static BOOLEAN is_close_thread_is_waiting = FALSE;
    166 
    167 static int change_client_addr(int addr);
    168 
    169 int   perf_log_every_count = 0;
    170 typedef struct {
    171     const char* label;
    172     long    lapse;
    173     long    bytes;
    174     long    count;
    175     long    overhead;
    176 } tPERF_DATA;
    177 
    178 /*******************************************************************************
    179 **
    180 ** Function         perf_reset
    181 **
    182 ** Description      reset performance measurement data
    183 **
    184 ** Returns          none
    185 **
    186 *******************************************************************************/
    187 void perf_reset(tPERF_DATA* t)
    188 {
    189     t->count =
    190     t->bytes =
    191     t->lapse = 0;
    192 }
    193 
    194 /*******************************************************************************
    195 **
    196 ** Function         perf_log
    197 **
    198 ** Description      produce a log entry of cvurrent performance data
    199 **
    200 ** Returns          none
    201 **
    202 *******************************************************************************/
    203 void perf_log(tPERF_DATA* t)
    204 {
    205     // round to nearest ms
    206     // t->lapse += 500;
    207     // t->lapse /= 1000;
    208     if (t->lapse)
    209     {
    210         if (t->bytes)
    211             ALOGD( "%s:%s, bytes=%ld, lapse=%ld (%d.%02d kbps) (bus data rate %d.%02d kbps) overhead %d(%d percent)\n",
    212                     __func__,
    213                     t->label, t->bytes, t->lapse,
    214                     (int)(8 * t->bytes / t->lapse), (int)(800 * t->bytes / (t->lapse)) % 100,
    215                     (int)(9 * (t->bytes + t->count * t->overhead) / t->lapse), (int)(900 * (t->bytes + t->count * t->overhead) / (t->lapse)) % 100,
    216                     (int)(t->count * t->overhead), (int)(t->count * t->overhead * 100 / t->bytes)
    217                     );
    218         else
    219             ALOGD( "%s:%s, lapse=%ld (average %ld)\n", __func__,
    220                     t->label, t->lapse, (int)t->lapse / t->count
    221                     );
    222     }
    223     perf_reset(t);
    224 }
    225 
    226 /*******************************************************************************
    227 **
    228 ** Function         perf_update
    229 **
    230 ** Description      update perforamnce measurement data
    231 **
    232 ** Returns          none
    233 **
    234 *******************************************************************************/
    235 void perf_update(tPERF_DATA* t, long lapse, long bytes)
    236 {
    237     if (!perf_log_every_count)
    238         return;
    239     // round to nearest ms
    240     lapse += 500;
    241     lapse /= 1000;
    242     t->count++;
    243     t->bytes += bytes;
    244     t->lapse += lapse;
    245     if (t->count == perf_log_every_count)
    246         perf_log(t);
    247 }
    248 
    249 static tPERF_DATA   perf_poll = {"USERIAL_Poll", 0, 0, 0, 0};
    250 static tPERF_DATA   perf_read = {"USERIAL_Read", 0, 0, 0, 9};
    251 static tPERF_DATA   perf_write = {"USERIAL_Write", 0, 0, 0, 3};
    252 static tPERF_DATA   perf_poll_2_poll = {"USERIAL_Poll_to_Poll", 0, 0, 0, 0};
    253 static clock_t      _poll_t0 = 0;
    254 
    255 static UINT32 userial_baud_tbl[] =
    256 {
    257     300,        /* USERIAL_BAUD_300          0 */
    258     600,        /* USERIAL_BAUD_600          1 */
    259     1200,       /* USERIAL_BAUD_1200         2 */
    260     2400,       /* USERIAL_BAUD_2400         3 */
    261     9600,       /* USERIAL_BAUD_9600         4 */
    262     19200,      /* USERIAL_BAUD_19200        5 */
    263     57600,      /* USERIAL_BAUD_57600        6 */
    264     115200,     /* USERIAL_BAUD_115200       7 */
    265     230400,     /* USERIAL_BAUD_230400       8 */
    266     460800,     /* USERIAL_BAUD_460800       9 */
    267     921600,     /* USERIAL_BAUD_921600       10 */
    268     1000000,    /* USERIAL_BAUD_1M           11 */
    269     1500000,    /* USERIAL_BAUD_1_5M         12 */
    270     2000000,    /* USERIAL_BAUD_2M           13 */
    271     3000000,    /* USERIAL_BAUD_3M           14 */
    272     4000000     /* USERIAL_BAUD_4M           15 */
    273 };
    274 
    275 /*******************************************************************************
    276 **
    277 ** Function         wake_state
    278 **
    279 ** Description      return current state of NFC_WAKE gpio
    280 **
    281 ** Returns          GPIO value to wake NFCC
    282 **
    283 *******************************************************************************/
    284 static inline int wake_state()
    285 {
    286     return ((gSnoozeModeCfg.nfc_wake_active_mode == NFC_HAL_LP_ACTIVE_HIGH) ? UPIO_ON : UPIO_OFF);
    287 }
    288 
    289 /*******************************************************************************
    290 **
    291 ** Function         sleep_state
    292 **
    293 ** Description      return current state of NFC_WAKE gpio
    294 **
    295 ** Returns          GPIO value to allow NFCC to goto sleep
    296 **
    297 *******************************************************************************/
    298 static inline int sleep_state()
    299 {
    300     return ((gSnoozeModeCfg.nfc_wake_active_mode == NFC_HAL_LP_ACTIVE_HIGH) ? UPIO_OFF : UPIO_ON);
    301 }
    302 
    303 /*******************************************************************************
    304 **
    305 ** Function         isWake
    306 **
    307 ** Description      return current state of NFC_WAKE gpio based on the active mode setting
    308 **
    309 ** Returns          asserted_state if it's awake, deasserted_state if it's allowed to sleep
    310 **
    311 *******************************************************************************/
    312 static inline int isWake(int state)
    313 {
    314     int     asserted_state = ((gSnoozeModeCfg.nfc_wake_active_mode == NFC_HAL_LP_ACTIVE_HIGH) ? UPIO_ON : UPIO_OFF);
    315     return (state != -1) ?
    316         state == asserted_state :
    317         current_nfc_wake_state == asserted_state;
    318 }
    319 
    320 /*******************************************************************************
    321 **
    322 ** Function           setWriteDelay
    323 **
    324 ** Description        Record a delay for the next write operation
    325 **
    326 ** Input Parameter    delay in milliseconds
    327 **
    328 ** Comments           use this function to register a delay before next write,
    329 **                    This is used in three instances: power up delay, wake delay
    330 **                    and write delay
    331 **
    332 *******************************************************************************/
    333 static void setWriteDelay(int delay)
    334 {
    335     if (delay <= 0) {
    336         // Set a minimum delay of 5ms between back-to-back writes
    337         delay = 5;
    338     }
    339 
    340     clock_gettime(CLOCK_MONOTONIC, &linux_cb.write_time);
    341     if (delay > 1000)
    342     {
    343         linux_cb.write_time.tv_sec += delay / 1000;
    344         delay %= 1000;
    345     }
    346     unsigned long write_delay = delay * 1000 * 1000;
    347     linux_cb.write_time.tv_nsec += write_delay;
    348     if (linux_cb.write_time.tv_nsec > 1000*1000*1000)
    349     {
    350         linux_cb.write_time.tv_nsec -= 1000*1000*1000;
    351         linux_cb.write_time.tv_sec++;
    352     }
    353 }
    354 
    355 /*******************************************************************************
    356 **
    357 ** Function           doWriteDelay
    358 **
    359 ** Description        Execute a delay as registered in setWriteDelay()
    360 **
    361 ** Output Parameter   none
    362 **
    363 ** Returns            none
    364 **
    365 ** Comments           This function calls GKI_Delay to execute a delay to fulfill
    366 **                    the delay registered earlier.
    367 **
    368 *******************************************************************************/
    369 static void doWriteDelay()
    370 {
    371     struct timespec now;
    372     clock_gettime(CLOCK_MONOTONIC, &now);
    373     long delay = 0;
    374 
    375     if (now.tv_sec > linux_cb.write_time.tv_sec)
    376         return;
    377     else if (now.tv_sec == linux_cb.write_time.tv_sec)
    378     {
    379         if (now.tv_nsec > linux_cb.write_time.tv_nsec)
    380             return;
    381         delay = (linux_cb.write_time.tv_nsec - now.tv_nsec) / 1000000;
    382     }
    383     else
    384         delay = (linux_cb.write_time.tv_sec - now.tv_sec) * 1000 + linux_cb.write_time.tv_nsec / 1000000 - now.tv_nsec / 1000000;
    385 
    386     if (delay > 0 && delay < 1000)
    387     {
    388         ALOGD_IF((appl_trace_level>=BT_TRACE_LEVEL_DEBUG), "doWriteDelay() delay %ld ms", delay);
    389         GKI_delay(delay);
    390     }
    391 }
    392 
    393 /*******************************************************************************
    394 **
    395 ** Function         create_signal_fds
    396 **
    397 ** Description      create a socketpair for read thread to use
    398 **
    399 ** Returns          file descriptor
    400 **
    401 *******************************************************************************/
    402 
    403 static int signal_fds[2];
    404 static inline int create_signal_fds(struct pollfd* set)
    405 {
    406     if (signal_fds[0] == 0 && socketpair(AF_UNIX, SOCK_STREAM, 0, signal_fds) < 0)
    407     {
    408         ALOGE("%s create_signal_sockets:socketpair failed, errno: %d", __func__, errno);
    409         return -1;
    410     }
    411     set->fd = signal_fds[0];
    412     return signal_fds[0];
    413 }
    414 
    415 /*******************************************************************************
    416 **
    417 ** Function         close_signal_fds
    418 **
    419 ** Description      close the socketpair
    420 **
    421 ** Returns          none
    422 **
    423 *******************************************************************************/
    424 static inline void close_signal_fds()
    425 {
    426     close(signal_fds[0]);
    427     signal_fds[0] = 0;
    428 
    429     close(signal_fds[1]);
    430     signal_fds[1] = 0;
    431 }
    432 
    433 /*******************************************************************************
    434 **
    435 ** Function         send_wakeup_signal
    436 **
    437 ** Description      send a one byte data to the socket as signal to the read thread
    438 **                  for it to stop
    439 **
    440 ** Returns          number of bytes sent, or error no
    441 **
    442 *******************************************************************************/
    443 static inline int send_wakeup_signal()
    444 {
    445     char sig_on = 1;
    446     ALOGD("%s: Sending signal to %d", __func__, signal_fds[1]);
    447     return send(signal_fds[1], &sig_on, sizeof(sig_on), 0);
    448 }
    449 
    450 /*******************************************************************************
    451 **
    452 ** Function         reset_signal
    453 **
    454 ** Description      read the one byte data from the socket
    455 **
    456 ** Returns          received data
    457 **
    458 *******************************************************************************/
    459 static inline int reset_signal()
    460 {
    461     char sig_recv = 0;
    462     ALOGD("%s: Receiving signal from %d", __func__, signal_fds[0]);
    463     recv(signal_fds[0], &sig_recv, sizeof(sig_recv), MSG_WAITALL);
    464     return (int)sig_recv;
    465 }
    466 
    467 /*******************************************************************************
    468 **
    469 ** Function         is_signaled
    470 **
    471 ** Description      test if there's data waiting on the socket
    472 **
    473 ** Returns          TRUE is data is available
    474 **
    475 *******************************************************************************/
    476 static inline int is_signaled(struct pollfd* set)
    477 {
    478     return ((set->revents & POLLIN) == POLLIN) || ((set->revents & POLLRDNORM) == POLLRDNORM) ;
    479 }
    480 
    481 /******************************************************************************/
    482 
    483 typedef unsigned char uchar;
    484 
    485 BUFFER_Q Userial_in_q;
    486 
    487 /*******************************************************************************
    488  **
    489  ** Function           USERIAL_GetLineSpeed
    490  **
    491  ** Description        This function convert USERIAL baud to line speed.
    492  **
    493  ** Output Parameter   None
    494  **
    495  ** Returns            line speed
    496  **
    497  *******************************************************************************/
    498 UDRV_API extern UINT32 USERIAL_GetLineSpeed(UINT8 baud)
    499 {
    500     return (baud <= USERIAL_BAUD_4M) ?
    501             userial_baud_tbl[baud-USERIAL_BAUD_300] : 0;
    502 }
    503 
    504 /*******************************************************************************
    505  **
    506  ** Function           USERIAL_GetBaud
    507  **
    508  ** Description        This function convert line speed to USERIAL baud.
    509  **
    510  ** Output Parameter   None
    511  **
    512  ** Returns            line speed
    513  **
    514  *******************************************************************************/
    515 UDRV_API extern UINT8 USERIAL_GetBaud(UINT32 line_speed)
    516 {
    517     UINT8 i;
    518     for (i = USERIAL_BAUD_300; i <= USERIAL_BAUD_921600; i++)
    519     {
    520         if (userial_baud_tbl[i-USERIAL_BAUD_300] == line_speed)
    521             return i;
    522     }
    523 
    524     return USERIAL_BAUD_AUTO;
    525 }
    526 
    527 /*******************************************************************************
    528 **
    529 ** Function           USERIAL_Init
    530 **
    531 ** Description        This function initializes the  serial driver.
    532 **
    533 ** Output Parameter   None
    534 **
    535 ** Returns            Nothing
    536 **
    537 *******************************************************************************/
    538 
    539 UDRV_API void    USERIAL_Init(void * p_cfg)
    540 {
    541     ALOGI(__FUNCTION__);
    542 
    543     memset(&linux_cb, 0, sizeof(linux_cb));
    544     linux_cb.sock = -1;
    545     linux_cb.ser_cb = NULL;
    546     linux_cb.sock_power_control = -1;
    547     linux_cb.client_device_address = 0;
    548     GKI_init_q(&Userial_in_q);
    549     return;
    550 }
    551 
    552 /*******************************************************************************
    553  **
    554  ** Function           my_read
    555  **
    556  ** Description        This function read a packet from driver.
    557  **
    558  ** Output Parameter   None
    559  **
    560  ** Returns            number of bytes in the packet or error code
    561  **
    562  *******************************************************************************/
    563 int my_read(int fd, uchar *pbuf, int len)
    564 {
    565     struct pollfd fds[2];
    566 
    567     int n = 0;
    568     int ret = 0;
    569     int count = 0;
    570     int offset = 0;
    571     clock_t t1, t2;
    572 
    573     if (!isLowSpeedTransport && _timeout != POLL_TIMEOUT)
    574         ALOGD_IF((appl_trace_level>=BT_TRACE_LEVEL_DEBUG), "%s: enter, pbuf=%lx, len = %d\n", __func__, (unsigned long)pbuf, len);
    575     memset(pbuf, 0, len);
    576     /* need to use select in order to avoid collistion between read and close on same fd */
    577     /* Initialize the input set */
    578     fds[0].fd = fd;
    579     fds[0].events = POLLIN | POLLERR | POLLRDNORM;
    580     fds[0].revents = 0;
    581 
    582     create_signal_fds(&fds[1]);
    583     fds[1].events = POLLIN | POLLERR | POLLRDNORM;
    584     fds[1].revents = 0;
    585     t1 = clock();
    586     n = poll(fds, 2, _timeout);
    587     t2 = clock();
    588     perf_update(&perf_poll, t2 - t1, 0);
    589     if (_poll_t0)
    590         perf_update(&perf_poll_2_poll, t2 - _poll_t0, 0);
    591 
    592     _poll_t0 = t2;
    593     /* See if there was an error */
    594     if (n < 0)
    595     {
    596         ALOGD( "select failed; errno = %d\n", errno);
    597         return -errno;
    598     }
    599     else if (n == 0)
    600         return -EAGAIN;
    601 
    602     if (is_signaled(&fds[1]))
    603     {
    604         ALOGD( "%s: exit signal received\n", __func__);
    605         reset_signal();
    606         return -1;
    607     }
    608     if (!bSerialPortDevice || len < MIN_BUFSIZE)
    609         count = len;
    610     else
    611         count = 1;
    612     do {
    613         t2 = clock();
    614         ret = read(fd, pbuf+offset, (size_t)count);
    615         if (ret > 0)
    616             perf_update(&perf_read, clock()-t2, ret);
    617 
    618         if (ret <= 0 || !bSerialPortDevice || len < MIN_BUFSIZE)
    619             break;
    620 
    621         if (isLowSpeedTransport)
    622             goto done;
    623 
    624         if (offset == 0)
    625         {
    626             if (pbuf[offset] == HCIT_TYPE_NFC)
    627                 count = 3;
    628             else if (pbuf[offset] == HCIT_TYPE_EVENT)
    629                 count = 2;
    630             else
    631             {
    632                 ALOGD( "%s: unknown HCIT type header pbuf[%d] = %x\n", __func__, offset, pbuf[offset]);
    633                 break;
    634             }
    635             offset = 1;
    636         }
    637         else if (offset == 1)
    638         {
    639             offset += count;
    640             count = pbuf[offset-1];
    641             if (count > (len - offset)) //if (count > (remaining buffer size))
    642                 count = len - offset; //only read what the remaining buffer size can hold
    643         }
    644         else
    645         {
    646             offset += ret;
    647             count -= ret;
    648         }
    649         if (count == 0)
    650         {
    651             ret = offset;
    652             break;
    653         }
    654     } while (count > 0);
    655  #if VALIDATE_PACKET
    656 /*
    657  * vallidate the packet structure
    658  */
    659     if (ret > 0 && len >= MIN_BUFSIZE)
    660     {
    661         count = 0;
    662         while (count < ret)
    663         {
    664             if (pbuf[count] == HCIT_TYPE_NFC)
    665             {
    666                 if (USERIAL_Debug_verbose)
    667                     scru_dump_hex(pbuf+count, NULL, pbuf[count+3]+4, 0, 0);
    668                 count += pbuf[count+3]+4;
    669             }
    670             else if (pbuf[count] == HCIT_TYPE_EVENT)
    671             {
    672                 if (USERIAL_Debug_verbose)
    673                     scru_dump_hex(pbuf+count, NULL, pbuf[count+2]+3, 0, 0);
    674                 count += pbuf[count+2]+3;
    675             }
    676             else
    677             {
    678                 ALOGD( "%s: unknown HCIT type header pbuf[%d] = %x, remain %d bytes\n", __func__, count, pbuf[count], ret-count);
    679                 scru_dump_hex(pbuf+count, NULL, ret - count, 0, 0);
    680                 break;
    681             }
    682         } /* while*/
    683     }
    684 #endif
    685 done:
    686     if (!isLowSpeedTransport)
    687         ALOGD_IF((appl_trace_level>=BT_TRACE_LEVEL_DEBUG), "%s: return %d(0x%x) bytes, errno=%d count=%d, n=%d, timeout=%d\n", __func__,
    688             ret, ret, errno, count, n, _timeout);
    689     if (_timeout == POLL_TIMEOUT)
    690         _timeout = -1;
    691     return ret;
    692 }
    693 extern BOOLEAN gki_chk_buf_damage(void *p_buf);
    694 static int sRxLength = 0;
    695 
    696 /*******************************************************************************
    697  **
    698  ** Function           userial_read_thread
    699  **
    700  ** Description        entry point of read thread.
    701  **
    702  ** Output Parameter   None
    703  **
    704  ** Returns            0
    705  **
    706  *******************************************************************************/
    707 UINT32 userial_read_thread(UINT32 arg)
    708 {
    709     int rx_length;
    710     int error_count = 0;
    711     int bErrorReported = 0;
    712     int iMaxError = MAX_ERROR;
    713     BT_HDR *p_buf = NULL;
    714 
    715     worker_thread1 = pthread_self();
    716 
    717     ALOGD( "start userial_read_thread, id=%lx", worker_thread1);
    718     _timeout = POLL_TIMEOUT;
    719 
    720     for (;linux_cb.sock > 0;)
    721     {
    722         BT_HDR *p_buf;
    723         UINT8 *current_packet;
    724 
    725         if ((p_buf = (BT_HDR *) GKI_getpoolbuf( USERIAL_POOL_ID ) )!= NULL)
    726         {
    727             p_buf->offset = 0;
    728             p_buf->layer_specific = 0;
    729 
    730             current_packet = (UINT8 *) (p_buf + 1);
    731             rx_length = my_read(linux_cb.sock, current_packet, READ_LIMIT);
    732 
    733         }
    734         else
    735         {
    736             ALOGE( "userial_read_thread(): unable to get buffer from GKI p_buf = %p poolid = %d\n", p_buf, USERIAL_POOL_ID);
    737             rx_length = 0;  /* paranoia setting */
    738             GKI_delay( NO_GKI_BUFFER_RECOVER_TIME );
    739             continue;
    740         }
    741         if (rx_length > 0)
    742         {
    743             bErrorReported = 0;
    744             error_count = 0;
    745             iMaxError = 3;
    746             if (rx_length > sRxLength)
    747                 sRxLength = rx_length;
    748             p_buf->len = (UINT16)rx_length;
    749             GKI_enqueue(&Userial_in_q, p_buf);
    750             if (!isLowSpeedTransport)
    751                 ALOGD_IF((appl_trace_level>=BT_TRACE_LEVEL_DEBUG), "userial_read_thread(): enqueued p_buf=%p, count=%d, length=%d\n",
    752                             p_buf, Userial_in_q.count, rx_length);
    753 
    754             if (linux_cb.ser_cb != NULL)
    755                 (*linux_cb.ser_cb)(linux_cb.port, USERIAL_RX_READY_EVT, (tUSERIAL_EVT_DATA *)p_buf);
    756 
    757             GKI_send_event(USERIAL_HAL_TASK, HCISU_EVT);
    758         }
    759         else
    760         {
    761             GKI_freebuf( p_buf );
    762             if (rx_length == -EAGAIN)
    763                 continue;
    764             else if (rx_length == -1)
    765             {
    766                 ALOGD( "userial_read_thread(): exiting\n");
    767                 break;
    768             }
    769             else if (rx_length == 0 && !isWake(-1))
    770                 continue;
    771             ++error_count;
    772             if (rx_length <= 0 && ((error_count > 0) && ((error_count % iMaxError) == 0)))
    773             {
    774                 if (bErrorReported == 0)
    775                 {
    776                     ALOGE( "userial_read_thread(): my_read returned (%d) error count = %d, errno=%d return USERIAL_ERR_EVT\n",
    777                             rx_length, error_count, errno);
    778                     if (linux_cb.ser_cb != NULL)
    779                         (*linux_cb.ser_cb)(linux_cb.port, USERIAL_ERR_EVT, (tUSERIAL_EVT_DATA *)p_buf);
    780 
    781                     GKI_send_event(USERIAL_HAL_TASK, HCISU_EVT);
    782                     ++bErrorReported;
    783                 }
    784                 if (sRxLength == 0)
    785                 {
    786                     ALOGE( "userial_read_thread(): my_read returned (%d) error count = %d, errno=%d exit read thread\n",
    787                             rx_length, error_count, errno);
    788                     break;
    789                 }
    790             }
    791         }
    792     } /* for */
    793 
    794     ALOGD( "userial_read_thread(): freeing GKI_buffers\n");
    795     while ((p_buf = (BT_HDR *) GKI_dequeue (&Userial_in_q)) != NULL)
    796     {
    797         GKI_freebuf(p_buf);
    798         ALOGD("userial_read_thread: dequeued buffer from Userial_in_q\n");
    799     }
    800 
    801     GKI_exit_task (GKI_get_taskid ());
    802     ALOGD( "USERIAL READ: EXITING TASK\n");
    803 
    804     return 0;
    805 }
    806 
    807 /*******************************************************************************
    808  **
    809  ** Function           userial_to_tcio_baud
    810  **
    811  ** Description        helper function converts USERIAL baud rates into TCIO conforming baud rates
    812  **
    813  ** Output Parameter   None
    814  **
    815  ** Returns            TRUE - success
    816  **                    FALSE - unsupported baud rate, default of 115200 is used
    817  **
    818  *******************************************************************************/
    819 BOOLEAN userial_to_tcio_baud(UINT8 cfg_baud, UINT32 * baud)
    820 {
    821     if (cfg_baud == USERIAL_BAUD_600)
    822         *baud = B600;
    823     else if (cfg_baud == USERIAL_BAUD_1200)
    824         *baud = B1200;
    825     else if (cfg_baud == USERIAL_BAUD_9600)
    826         *baud = B9600;
    827     else if (cfg_baud == USERIAL_BAUD_19200)
    828         *baud = B19200;
    829     else if (cfg_baud == USERIAL_BAUD_57600)
    830         *baud = B57600;
    831     else if (cfg_baud == USERIAL_BAUD_115200)
    832         *baud = B115200 | CBAUDEX;
    833     else if (cfg_baud == USERIAL_BAUD_230400)
    834         *baud = B230400;
    835     else if (cfg_baud == USERIAL_BAUD_460800)
    836         *baud = B460800;
    837     else if (cfg_baud == USERIAL_BAUD_921600)
    838         *baud = B921600;
    839     else if (cfg_baud == USERIAL_BAUD_1M)
    840         *baud = B1000000;
    841     else if (cfg_baud == USERIAL_BAUD_2M)
    842         *baud = B2000000;
    843     else if (cfg_baud == USERIAL_BAUD_3M)
    844         *baud = B3000000;
    845     else if (cfg_baud == USERIAL_BAUD_4M)
    846         *baud = B4000000;
    847     else
    848     {
    849         ALOGE( "USERIAL_Open: unsupported baud idx %i", cfg_baud );
    850         *baud = B115200;
    851         return FALSE;
    852     }
    853     return TRUE;
    854 }
    855 
    856 #if (USERIAL_USE_IO_BT_WAKE==TRUE)
    857 /*******************************************************************************
    858  **
    859  ** Function           userial_io_init_bt_wake
    860  **
    861  ** Description        helper function to set the open state of the bt_wake if ioctl
    862  **                    is used. it should not hurt in the rfkill case but it might
    863  **                    be better to compile it out.
    864  **
    865  ** Returns            none
    866  **
    867  *******************************************************************************/
    868 void userial_io_init_bt_wake( int fd, unsigned long * p_wake_state )
    869 {
    870     /* assert BT_WAKE for ioctl. should NOT hurt on rfkill version */
    871     ioctl( fd, USERIAL_IO_BT_WAKE_ASSERT, NULL);
    872     ioctl( fd, USERIAL_IO_BT_WAKE_GET_ST, p_wake_state );
    873     if ( *p_wake_state == 0)
    874         ALOGI("\n***userial_io_init_bt_wake(): Ooops, asserted BT_WAKE signal, but still got BT_WAKE state == to %d\n",
    875              *p_wake_state );
    876 
    877     *p_wake_state = 1;
    878 }
    879 #endif
    880 
    881 /*******************************************************************************
    882 **
    883 ** Function           USERIAL_Open
    884 **
    885 ** Description        Open the indicated serial port with the given configuration
    886 **
    887 ** Output Parameter   None
    888 **
    889 ** Returns            Nothing
    890 **
    891 *******************************************************************************/
    892 UDRV_API void USERIAL_Open(tUSERIAL_PORT port, tUSERIAL_OPEN_CFG *p_cfg, tUSERIAL_CBACK *p_cback)
    893 {
    894     UINT32 baud = 0;
    895     UINT8 data_bits = 0;
    896     UINT16 parity = 0;
    897     UINT8 stop_bits = 0;
    898     struct termios termios;
    899     const char ttyusb[] = "/dev/ttyUSB";
    900     const char devtty[] = "/dev/tty";
    901     unsigned long num = 0;
    902     int     ret = 0;
    903 
    904     ALOGI("USERIAL_Open(): enter");
    905 
    906     //if userial_close_thread() is waiting to run; let it go first;
    907     //let it finish; then continue this function
    908     while (TRUE)
    909     {
    910         pthread_mutex_lock(&close_thread_mutex);
    911         if (is_close_thread_is_waiting)
    912         {
    913             pthread_mutex_unlock(&close_thread_mutex);
    914             ALOGI("USERIAL_Open(): wait for close-thread");
    915             sleep (1);
    916         }
    917         else
    918             break;
    919     }
    920 
    921     // restore default power off delay settings incase they were changed in userial_set_poweroff_delays()
    922     gPrePowerOffDelay = 0;
    923     gPostPowerOffDelay = 0;
    924 
    925     if ( !GetStrValue ( NAME_TRANSPORT_DRIVER, userial_dev, sizeof ( userial_dev ) ) )
    926         strcpy ( userial_dev, default_transport );
    927     if ( GetNumValue ( NAME_UART_PORT, &num, sizeof ( num ) ) )
    928         uart_port = num;
    929     if ( GetNumValue ( NAME_LOW_SPEED_TRANSPORT, &num, sizeof ( num ) ) )
    930         isLowSpeedTransport = num;
    931     if ( GetNumValue ( NAME_NFC_WAKE_DELAY, &num, sizeof ( num ) ) )
    932         nfc_wake_delay = num;
    933     if ( GetNumValue ( NAME_NFC_WRITE_DELAY, &num, sizeof ( num ) ) )
    934         nfc_write_delay = num;
    935     if ( GetNumValue ( NAME_PERF_MEASURE_FREQ, &num, sizeof ( num ) ) )
    936         perf_log_every_count = num;
    937     if ( GetNumValue ( NAME_POWER_ON_DELAY, &num, sizeof ( num ) ) )
    938         gPowerOnDelay = num;
    939     if ( GetNumValue ( NAME_PRE_POWER_OFF_DELAY, &num, sizeof ( num ) ) )
    940         gPrePowerOffDelay = num;
    941     if ( GetNumValue ( NAME_POST_POWER_OFF_DELAY, &num, sizeof ( num ) ) )
    942         gPostPowerOffDelay = num;
    943     ALOGI("USERIAL_Open() device: %s port=%d, uart_port=%d WAKE_DELAY(%d) WRITE_DELAY(%d) POWER_ON_DELAY(%d) PRE_POWER_OFF_DELAY(%d) POST_POWER_OFF_DELAY(%d)",
    944             (char*)userial_dev, port, uart_port, nfc_wake_delay, nfc_write_delay, gPowerOnDelay, gPrePowerOffDelay,
    945             gPostPowerOffDelay);
    946 
    947     strcpy((char*)device_name, (char*)userial_dev);
    948     sRxLength = 0;
    949     _poll_t0 = 0;
    950 
    951     if ((strncmp(userial_dev, ttyusb, sizeof(ttyusb)-1) == 0) ||
    952         (strncmp(userial_dev, devtty, sizeof(devtty)-1) == 0) )
    953     {
    954         if (uart_port >= MAX_SERIAL_PORT)
    955         {
    956             ALOGD( "Port > MAX_SERIAL_PORT\n");
    957             goto done_open;
    958         }
    959         bSerialPortDevice = TRUE;
    960         sprintf((char*)device_name, "%s%d", (char*)userial_dev, uart_port);
    961         ALOGI("USERIAL_Open() using device_name: %s ", (char*)device_name);
    962         if (!userial_to_tcio_baud(p_cfg->baud, &baud))
    963             goto done_open;
    964 
    965         if (p_cfg->fmt & USERIAL_DATABITS_8)
    966             data_bits = CS8;
    967         else if (p_cfg->fmt & USERIAL_DATABITS_7)
    968             data_bits = CS7;
    969         else if (p_cfg->fmt & USERIAL_DATABITS_6)
    970             data_bits = CS6;
    971         else if (p_cfg->fmt & USERIAL_DATABITS_5)
    972             data_bits = CS5;
    973         else
    974             goto done_open;
    975 
    976         if (p_cfg->fmt & USERIAL_PARITY_NONE)
    977             parity = 0;
    978         else if (p_cfg->fmt & USERIAL_PARITY_EVEN)
    979             parity = PARENB;
    980         else if (p_cfg->fmt & USERIAL_PARITY_ODD)
    981             parity = (PARENB | PARODD);
    982         else
    983             goto done_open;
    984 
    985         if (p_cfg->fmt & USERIAL_STOPBITS_1)
    986             stop_bits = 0;
    987         else if (p_cfg->fmt & USERIAL_STOPBITS_2)
    988             stop_bits = CSTOPB;
    989         else
    990             goto done_open;
    991     }
    992     else
    993         strcpy((char*)device_name, (char*)userial_dev);
    994 
    995     {
    996         ALOGD("%s Opening %s\n",  __FUNCTION__, device_name);
    997         if ((linux_cb.sock = open((char*)device_name, O_RDWR | O_NOCTTY )) == -1)
    998         {
    999             ALOGI("%s unable to open %s",  __FUNCTION__, device_name);
   1000             GKI_send_event(NFC_HAL_TASK, NFC_HAL_TASK_EVT_TERMINATE);
   1001             goto done_open;
   1002         }
   1003         ALOGD( "sock = %d\n", linux_cb.sock);
   1004         if (GetStrValue ( NAME_POWER_CONTROL_DRIVER, power_control_dev, sizeof ( power_control_dev ) ) &&
   1005             power_control_dev[0] != '\0')
   1006         {
   1007             if (strcmp(power_control_dev, userial_dev) == 0)
   1008                 linux_cb.sock_power_control = linux_cb.sock;
   1009             else
   1010             {
   1011                 if ((linux_cb.sock_power_control = open((char*)power_control_dev, O_RDWR | O_NOCTTY )) == -1)
   1012                 {
   1013                     ALOGI("%s unable to open %s",  __FUNCTION__, power_control_dev);
   1014                 }
   1015             }
   1016         }
   1017         if ( bSerialPortDevice )
   1018         {
   1019             tcflush(linux_cb.sock, TCIOFLUSH);
   1020             tcgetattr(linux_cb.sock, &termios);
   1021 
   1022             termios.c_cflag &= ~(CSIZE | PARENB);
   1023             termios.c_cflag = CLOCAL|CREAD|data_bits|stop_bits|parity;
   1024             if (!parity)
   1025                 termios.c_cflag |= IGNPAR;
   1026             // termios.c_cflag &= ~CRTSCTS;
   1027             termios.c_oflag = 0;
   1028             termios.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN | ISIG);
   1029             termios.c_iflag &= ~(BRKINT | ICRNL | INLCR | ISTRIP | IXON | IGNBRK | PARMRK | INPCK);
   1030             termios.c_lflag = 0;
   1031             termios.c_iflag = 0;
   1032             cfsetospeed(&termios, baud);
   1033             cfsetispeed(&termios, baud);
   1034 
   1035             termios.c_cc[VTIME] = 0;
   1036             termios.c_cc[VMIN] = 1;
   1037             tcsetattr(linux_cb.sock, TCSANOW, &termios);
   1038 
   1039             tcflush(linux_cb.sock, TCIOFLUSH);
   1040 
   1041 #if (USERIAL_USE_IO_BT_WAKE==TRUE)
   1042             userial_io_init_bt_wake( linux_cb.sock, &linux_cb.bt_wake_state );
   1043 #endif
   1044             GKI_delay(gPowerOnDelay);
   1045         }
   1046         else
   1047         {
   1048             USERIAL_PowerupDevice(port);
   1049         }
   1050     }
   1051 
   1052     linux_cb.ser_cb     = p_cback;
   1053     linux_cb.port = port;
   1054     memcpy(&linux_cb.open_cfg, p_cfg, sizeof(tUSERIAL_OPEN_CFG));
   1055     GKI_create_task ((TASKPTR)userial_read_thread, USERIAL_HAL_TASK, (INT8*)"USERIAL_HAL_TASK", 0, 0, (pthread_cond_t*)NULL, NULL);
   1056 
   1057 
   1058 #if (defined USERIAL_DEBUG) && (USERIAL_DEBUG == TRUE)
   1059     ALOGD( "Leaving USERIAL_Open\n");
   1060 #endif
   1061 
   1062 #if (SERIAL_AMBA == TRUE)
   1063     /* give 20ms time for reader thread */
   1064     GKI_delay(20);
   1065 #endif
   1066 
   1067 done_open:
   1068     pthread_mutex_unlock(&close_thread_mutex);
   1069     ALOGI("USERIAL_Open(): exit");
   1070     return;
   1071 }
   1072 
   1073 /*******************************************************************************
   1074 **
   1075 ** Function           USERIAL_Read
   1076 **
   1077 ** Description        Read data from a serial port using byte buffers.
   1078 **
   1079 ** Output Parameter   None
   1080 **
   1081 ** Returns            Number of bytes actually read from the serial port and
   1082 **                    copied into p_data.  This may be less than len.
   1083 **
   1084 *******************************************************************************/
   1085 
   1086 static BT_HDR *pbuf_USERIAL_Read = NULL;
   1087 
   1088 UDRV_API UINT16  USERIAL_Read(tUSERIAL_PORT port, UINT8 *p_data, UINT16 len)
   1089 {
   1090     UINT16 total_len = 0;
   1091     UINT16 copy_len = 0;
   1092     UINT8 * current_packet = NULL;
   1093 
   1094 #if (defined USERIAL_DEBUG) && (USERIAL_DEBUG == TRUE)
   1095     ALOGD( "%s ++ len=%d pbuf_USERIAL_Read=%p, p_data=%p\n", __func__, len, pbuf_USERIAL_Read, p_data);
   1096 #endif
   1097     do
   1098     {
   1099         if (pbuf_USERIAL_Read != NULL)
   1100         {
   1101             current_packet = ((UINT8 *)(pbuf_USERIAL_Read + 1)) + (pbuf_USERIAL_Read->offset);
   1102 
   1103             if ((pbuf_USERIAL_Read->len) <= (len - total_len))
   1104                 copy_len = pbuf_USERIAL_Read->len;
   1105             else
   1106                 copy_len = (len - total_len);
   1107 
   1108             memcpy((p_data + total_len), current_packet, copy_len);
   1109 
   1110             total_len += copy_len;
   1111 
   1112             pbuf_USERIAL_Read->offset += copy_len;
   1113             pbuf_USERIAL_Read->len -= copy_len;
   1114 
   1115             if (pbuf_USERIAL_Read->len == 0)
   1116             {
   1117                 GKI_freebuf(pbuf_USERIAL_Read);
   1118                 pbuf_USERIAL_Read = NULL;
   1119             }
   1120         }
   1121 
   1122         if (pbuf_USERIAL_Read == NULL && (total_len < len))
   1123             pbuf_USERIAL_Read = (BT_HDR *)GKI_dequeue(&Userial_in_q);
   1124 
   1125     } while ((pbuf_USERIAL_Read != NULL) && (total_len < len));
   1126 
   1127 #if (defined USERIAL_DEBUG) && (USERIAL_DEBUG == TRUE)
   1128     ALOGD( "%s: returned %d bytes", __func__, total_len);
   1129 #endif
   1130     return total_len;
   1131 }
   1132 
   1133 /*******************************************************************************
   1134 **
   1135 ** Function           USERIAL_Readbuf
   1136 **
   1137 ** Description        Read data from a serial port using GKI buffers.
   1138 **
   1139 ** Output Parameter   Pointer to a GKI buffer which contains the data.
   1140 **
   1141 ** Returns            Nothing
   1142 **
   1143 ** Comments           The caller of this function is responsible for freeing the
   1144 **                    GKI buffer when it is finished with the data.  If there is
   1145 **                    no data to be read, the value of the returned pointer is
   1146 **                    NULL.
   1147 **
   1148 *******************************************************************************/
   1149 
   1150 UDRV_API void    USERIAL_ReadBuf(tUSERIAL_PORT port, BT_HDR **p_buf)
   1151 {
   1152 
   1153 }
   1154 
   1155 /*******************************************************************************
   1156 **
   1157 ** Function           USERIAL_WriteBuf
   1158 **
   1159 ** Description        Write data to a serial port using a GKI buffer.
   1160 **
   1161 ** Output Parameter   None
   1162 **
   1163 ** Returns            TRUE  if buffer accepted for write.
   1164 **                    FALSE if there is already a buffer being processed.
   1165 **
   1166 ** Comments           The buffer will be freed by the serial driver.  Therefore,
   1167 **                    the application calling this function must not free the
   1168 **                    buffer.
   1169 **
   1170 *******************************************************************************/
   1171 
   1172 UDRV_API BOOLEAN USERIAL_WriteBuf(tUSERIAL_PORT port, BT_HDR *p_buf)
   1173 {
   1174     return FALSE;
   1175 }
   1176 
   1177 /*******************************************************************************
   1178 **
   1179 ** Function           USERIAL_Write
   1180 **
   1181 ** Description        Write data to a serial port using a byte buffer.
   1182 **
   1183 ** Output Parameter   None
   1184 **
   1185 ** Returns            Number of bytes actually written to the transport.  This
   1186 **                    may be less than len.
   1187 **
   1188 *******************************************************************************/
   1189 UDRV_API UINT16  USERIAL_Write(tUSERIAL_PORT port, UINT8 *p_data, UINT16 len)
   1190 {
   1191     int ret = 0, total = 0;
   1192     int i = 0;
   1193     clock_t t;
   1194 
   1195     ALOGD_IF((appl_trace_level>=BT_TRACE_LEVEL_DEBUG), "USERIAL_Write: (%d bytes)", len);
   1196     pthread_mutex_lock(&close_thread_mutex);
   1197 
   1198     doWriteDelay();
   1199     t = clock();
   1200     while (len != 0 && linux_cb.sock != -1)
   1201     {
   1202         ret = write(linux_cb.sock, p_data + total, len);
   1203         if (ret < 0)
   1204         {
   1205             ALOGE("USERIAL_Write len = %d, ret = %d, errno = %d", len, ret, errno);
   1206             break;
   1207         }
   1208         else
   1209         {
   1210             ALOGD_IF((appl_trace_level>=BT_TRACE_LEVEL_DEBUG), "USERIAL_Write len = %d, ret = %d", len, ret);
   1211         }
   1212 
   1213         total += ret;
   1214         len -= ret;
   1215     }
   1216     perf_update(&perf_write, clock() - t, total);
   1217 
   1218     /* register a delay for next write */
   1219     setWriteDelay(total * nfc_write_delay / 1000);
   1220 
   1221     pthread_mutex_unlock(&close_thread_mutex);
   1222 
   1223     return ((UINT16)total);
   1224 }
   1225 
   1226 /*******************************************************************************
   1227 **
   1228 ** Function           userial_change_rate
   1229 **
   1230 ** Description        change naud rate
   1231 **
   1232 ** Output Parameter   None
   1233 **
   1234 ** Returns            None
   1235 **
   1236 *******************************************************************************/
   1237 void userial_change_rate(UINT8 baud)
   1238 {
   1239 #if defined (USING_BRCM_USB) && (USING_BRCM_USB == FALSE)
   1240     struct termios termios;
   1241 #endif
   1242 #if (USERIAL_USE_TCIO_BAUD_CHANGE==TRUE)
   1243     UINT32 tcio_baud;
   1244 #endif
   1245 
   1246 #if defined (USING_BRCM_USB) && (USING_BRCM_USB == FALSE)
   1247     tcflush(linux_cb.sock, TCIOFLUSH);
   1248 
   1249     tcgetattr(linux_cb.sock, &termios);
   1250 
   1251     cfmakeraw(&termios);
   1252     cfsetospeed(&termios, baud);
   1253     cfsetispeed(&termios, baud);
   1254 
   1255     termios.c_cflag |= (CLOCAL | CREAD | CRTSCTS | stop_bits);
   1256 
   1257     tcsetattr(linux_cb.sock, TCSANOW, &termios);
   1258     tcflush(linux_cb.sock, TCIOFLUSH);
   1259 
   1260 #else
   1261 #if (USERIAL_USE_TCIO_BAUD_CHANGE==FALSE)
   1262     fprintf(stderr, "userial_change_rate: Closing UART Port\n");
   1263     ALOGI("userial_change_rate: Closing UART Port\n");
   1264     USERIAL_Close(linux_cb.port);
   1265 
   1266     GKI_delay(50);
   1267 
   1268     /* change baud rate in settings - leave everything else the same  */
   1269     linux_cb.open_cfg.baud = baud;
   1270 
   1271     ALOGD( "userial_change_rate: Attempting to reopen the UART Port at 0x%08x\n", (unsigned int)USERIAL_GetLineSpeed(baud));
   1272     ALOGI("userial_change_rate: Attempting to reopen the UART Port at %i\n", (unsigned int)USERIAL_GetLineSpeed(baud));
   1273 
   1274     USERIAL_Open(linux_cb.port, &linux_cb.open_cfg, linux_cb.ser_cb);
   1275 #else /* amba uart */
   1276     fprintf(stderr, "userial_change_rate(): changeing baud rate via TCIO \n");
   1277     ALOGI( "userial_change_rate: (): changeing baud rate via TCIO \n");
   1278     /* change baud rate in settings - leave everything else the same  */
   1279     linux_cb.open_cfg.baud = baud;
   1280     if (!userial_to_tcio_baud(linux_cb.open_cfg.baud, &tcio_baud))
   1281         return;
   1282 
   1283     tcflush(linux_cb.sock, TCIOFLUSH);
   1284 
   1285     /* get current settings. they should be fine besides baud rate we want to change */
   1286     tcgetattr(linux_cb.sock, &termios);
   1287 
   1288     /* set input/output baudrate */
   1289     cfsetospeed(&termios, tcio_baud);
   1290     cfsetispeed(&termios, tcio_baud);
   1291     tcsetattr(linux_cb.sock, TCSANOW, &termios);
   1292 
   1293     tcflush(linux_cb.sock, TCIOFLUSH);
   1294 #endif
   1295 #endif   /* USING_BRCM_USB  */
   1296 }
   1297 
   1298 /*******************************************************************************
   1299 **
   1300 ** Function           userial_close_port
   1301 **
   1302 ** Description        close the transport driver
   1303 **
   1304 ** Returns            Nothing
   1305 **
   1306 *******************************************************************************/
   1307 void userial_close_port( void )
   1308 {
   1309     USERIAL_Close(linux_cb.port);
   1310 }
   1311 
   1312 /*******************************************************************************
   1313 **
   1314 ** Function           USERIAL_Ioctl
   1315 **
   1316 ** Description        Perform an operation on a serial port.
   1317 **
   1318 ** Output Parameter   The p_data parameter is either an input or output depending
   1319 **                    on the operation.
   1320 **
   1321 ** Returns            Nothing
   1322 **
   1323 *******************************************************************************/
   1324 
   1325 UDRV_API void    USERIAL_Ioctl(tUSERIAL_PORT port, tUSERIAL_OP op, tUSERIAL_IOCTL_DATA *p_data)
   1326 {
   1327 #if (defined LINUX_OS) && (LINUX_OS == TRUE)
   1328     USB_SCO_CONTROL ioctl_data;
   1329 
   1330     /* just ignore port parameter as we are using USB in this case  */
   1331 #endif
   1332 
   1333     switch (op)
   1334     {
   1335     case USERIAL_OP_FLUSH:
   1336         break;
   1337     case USERIAL_OP_FLUSH_RX:
   1338         break;
   1339     case USERIAL_OP_FLUSH_TX:
   1340         break;
   1341     case USERIAL_OP_BAUD_WR:
   1342         ALOGI( "USERIAL_Ioctl: Received USERIAL_OP_BAUD_WR on port: %d, ioctl baud%i\n", port, p_data->baud);
   1343         linux_cb.port = port;
   1344         userial_change_rate(p_data->baud);
   1345         break;
   1346 
   1347     default:
   1348         break;
   1349     }
   1350 
   1351     return;
   1352 }
   1353 
   1354 
   1355 /*******************************************************************************
   1356 **
   1357 ** Function         USERIAL_SetPowerOffDelays
   1358 **
   1359 ** Description      Set power off delays used during USERIAL_Close().  The
   1360 **                  values in the conf. file setting override these if set.
   1361 **
   1362 ** Returns          None.
   1363 **
   1364 *******************************************************************************/
   1365 UDRV_API void USERIAL_SetPowerOffDelays(int pre_poweroff_delay, int post_poweroff_delay)
   1366 {
   1367     gPrePowerOffDelay = pre_poweroff_delay;
   1368     gPostPowerOffDelay = post_poweroff_delay;
   1369 }
   1370 
   1371 /*******************************************************************************
   1372 **
   1373 ** Function           USERIAL_Close
   1374 **
   1375 ** Description        Close a serial port
   1376 **
   1377 ** Output Parameter   None
   1378 **
   1379 ** Returns            Nothing
   1380 **
   1381 *******************************************************************************/
   1382 UDRV_API void    USERIAL_Close(tUSERIAL_PORT port)
   1383 {
   1384     pthread_attr_t attr;
   1385     pthread_t      close_thread;
   1386 
   1387     ALOGD ("%s: enter", __FUNCTION__);
   1388     // check to see if thread is already running
   1389     if (pthread_mutex_trylock(&close_thread_mutex) == 0)
   1390     {
   1391         // mutex aquired so thread is not running
   1392         is_close_thread_is_waiting = TRUE;
   1393         pthread_mutex_unlock(&close_thread_mutex);
   1394 
   1395         // close transport in a new thread so we don't block the caller
   1396         // make thread detached, no other thread will join
   1397         pthread_attr_init(&attr);
   1398         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
   1399         pthread_create( &close_thread, &attr, (void *)userial_close_thread,(void*)port);
   1400         pthread_attr_destroy(&attr);
   1401     }
   1402     else
   1403     {
   1404         // mutex not aquired to thread is already running
   1405         ALOGD( "USERIAL_Close(): already closing \n");
   1406     }
   1407     ALOGD ("%s: exit", __FUNCTION__);
   1408 }
   1409 
   1410 
   1411 /*******************************************************************************
   1412 **
   1413 ** Function         userial_close_thread
   1414 **
   1415 ** Description      Thread to close USERIAL
   1416 **
   1417 ** Returns          None.
   1418 **
   1419 *******************************************************************************/
   1420 void userial_close_thread(UINT32 params)
   1421 {
   1422     tUSERIAL_PORT port = (tUSERIAL_PORT )params;
   1423     BT_HDR                  *p_buf = NULL;
   1424     int result;
   1425 
   1426     ALOGD( "%s: closing transport (%d)\n", __FUNCTION__, linux_cb.sock);
   1427     pthread_mutex_lock(&close_thread_mutex);
   1428     is_close_thread_is_waiting = FALSE;
   1429 
   1430     if (linux_cb.sock <= 0)
   1431     {
   1432         ALOGD( "%s: already closed (%d)\n", __FUNCTION__, linux_cb.sock);
   1433         pthread_mutex_unlock(&close_thread_mutex);
   1434         return;
   1435     }
   1436 
   1437     send_wakeup_signal();
   1438     result = pthread_join( worker_thread1, NULL );
   1439     if ( result < 0 )
   1440         ALOGE( "%s: pthread_join() FAILED: result: %d", __FUNCTION__, result );
   1441     else
   1442         ALOGD( "%s: pthread_join() joined: result: %d", __FUNCTION__, result );
   1443 
   1444     if (linux_cb.sock_power_control > 0)
   1445     {
   1446         result = ioctl(linux_cb.sock_power_control, BCMNFC_WAKE_CTL, sleep_state());
   1447         ALOGD("%s: Delay %dms before turning off the chip", __FUNCTION__, gPrePowerOffDelay);
   1448         GKI_delay(gPrePowerOffDelay);
   1449         result = ioctl(linux_cb.sock_power_control, BCMNFC_POWER_CTL, 0);
   1450         ALOGD("%s: Delay %dms after turning off the chip", __FUNCTION__, gPostPowerOffDelay);
   1451         GKI_delay(gPostPowerOffDelay);
   1452     }
   1453     result = close(linux_cb.sock);
   1454     if (result<0)
   1455         ALOGD("%s: close return %d", __FUNCTION__, result);
   1456 
   1457     if (linux_cb.sock_power_control > 0 && linux_cb.sock_power_control != linux_cb.sock)
   1458     result = close(linux_cb.sock_power_control);
   1459     if (result<0)
   1460         ALOGD("%s: close return %d", __FUNCTION__, result);
   1461 
   1462     linux_cb.sock_power_control = -1;
   1463     linux_cb.sock = -1;
   1464 
   1465     close_signal_fds();
   1466     pthread_mutex_unlock(&close_thread_mutex);
   1467     ALOGD("%s: exiting", __FUNCTION__);
   1468 }
   1469 
   1470 /*******************************************************************************
   1471 **
   1472 ** Function           USERIAL_Feature
   1473 **
   1474 ** Description        Check whether a feature of the serial API is supported.
   1475 **
   1476 ** Output Parameter   None
   1477 **
   1478 ** Returns            TRUE  if the feature is supported
   1479 **                    FALSE if the feature is not supported
   1480 **
   1481 *******************************************************************************/
   1482 
   1483 UDRV_API BOOLEAN USERIAL_Feature(tUSERIAL_FEATURE feature)
   1484 {
   1485     switch (feature)
   1486     {
   1487     case USERIAL_FEAT_PORT_1:
   1488     case USERIAL_FEAT_PORT_2:
   1489     case USERIAL_FEAT_PORT_3:
   1490     case USERIAL_FEAT_PORT_4:
   1491 
   1492     case USERIAL_FEAT_BAUD_600:
   1493     case USERIAL_FEAT_BAUD_1200:
   1494     case USERIAL_FEAT_BAUD_9600:
   1495     case USERIAL_FEAT_BAUD_19200:
   1496     case USERIAL_FEAT_BAUD_57600:
   1497     case USERIAL_FEAT_BAUD_115200:
   1498 
   1499     case USERIAL_FEAT_STOPBITS_1:
   1500     case USERIAL_FEAT_STOPBITS_2:
   1501 
   1502     case USERIAL_FEAT_PARITY_NONE:
   1503     case USERIAL_FEAT_PARITY_EVEN:
   1504     case USERIAL_FEAT_PARITY_ODD:
   1505 
   1506     case USERIAL_FEAT_DATABITS_5:
   1507     case USERIAL_FEAT_DATABITS_6:
   1508     case USERIAL_FEAT_DATABITS_7:
   1509     case USERIAL_FEAT_DATABITS_8:
   1510 
   1511     case USERIAL_FEAT_FC_HW:
   1512     case USERIAL_FEAT_BUF_BYTE:
   1513 
   1514     case USERIAL_FEAT_OP_FLUSH_RX:
   1515     case USERIAL_FEAT_OP_FLUSH_TX:
   1516         return TRUE;
   1517     default:
   1518         return FALSE;
   1519     }
   1520 
   1521     return FALSE;
   1522 }
   1523 
   1524 /*****************************************************************************
   1525 **
   1526 ** Function         UPIO_Set
   1527 **
   1528 ** Description
   1529 **      This function sets one or more GPIO devices to the given state.
   1530 **      Multiple GPIOs of the same type can be masked together to set more
   1531 **      than one GPIO. This function can only be used on types UPIO_LED and
   1532 **      UPIO_GENERAL.
   1533 **
   1534 ** Input Parameters:
   1535 **      type    The type of device.
   1536 **      pio     Indicates the particular GPIOs.
   1537 **      state   The desired state.
   1538 **
   1539 ** Output Parameter:
   1540 **      None.
   1541 **
   1542 ** Returns:
   1543 **      None.
   1544 **
   1545 *****************************************************************************/
   1546 UDRV_API void UPIO_Set(tUPIO_TYPE type, tUPIO pio, tUPIO_STATE new_state)
   1547 {
   1548     int     ret;
   1549     if (type == UPIO_GENERAL)
   1550     {
   1551         if (pio == NFC_HAL_LP_NFC_WAKE_GPIO)
   1552         {
   1553             if (new_state == UPIO_ON || new_state == UPIO_OFF)
   1554             {
   1555                 if (linux_cb.sock_power_control > 0)
   1556                 {
   1557                     ALOGD("%s: ioctl, state=%d", __func__, new_state);
   1558                     ret = ioctl(linux_cb.sock_power_control, BCMNFC_WAKE_CTL, new_state);
   1559                     if (isWake(new_state) && nfc_wake_delay > 0 && new_state != current_nfc_wake_state)
   1560                     {
   1561                         ALOGD("%s: ioctl, old state=%d, insert delay for %d ms", __func__, current_nfc_wake_state, nfc_wake_delay);
   1562                         setWriteDelay(nfc_wake_delay);
   1563                     }
   1564                     current_nfc_wake_state = new_state;
   1565                 }
   1566             }
   1567         }
   1568     }
   1569 }
   1570 
   1571 /*****************************************************************************
   1572 **
   1573 ** Function         setReadPacketSize
   1574 **
   1575 ** Description
   1576 **      This function sets the packetSize to the driver.
   1577 **      this enables faster read operation of NCI/HCI responses
   1578 **
   1579 ** Input Parameters:
   1580 **      len     number of bytes to read per operation.
   1581 **
   1582 ** Output Parameter:
   1583 **      None.
   1584 **
   1585 ** Returns:
   1586 **      None.
   1587 **
   1588 *****************************************************************************/
   1589 void setReadPacketSize(int len)
   1590 {
   1591     int ret;
   1592     ALOGD("%s: ioctl, len=%d", __func__, len);
   1593     ret = ioctl(linux_cb.sock, BCMNFC_READ_FULL_PACKET, len);
   1594 }
   1595 
   1596 
   1597 UDRV_API BOOLEAN USERIAL_IsClosed()
   1598 {
   1599     return (linux_cb.sock == -1) ? TRUE : FALSE;
   1600 }
   1601 
   1602 UDRV_API void USERIAL_PowerupDevice(tUSERIAL_PORT port)
   1603 {
   1604     int ret = -1;
   1605     unsigned long num = 0;
   1606     unsigned int resetSuccess = 0;
   1607     unsigned int numTries = 0;
   1608     unsigned char spi_negotiation[64];
   1609     int delay = gPowerOnDelay;
   1610     ALOGD("%s: enter", __FUNCTION__);
   1611 
   1612     if ( GetNumValue ( NAME_READ_MULTI_PACKETS, &num, sizeof ( num ) ) )
   1613         bcmi2cnfc_read_multi_packets = num;
   1614 
   1615     if (bcmi2cnfc_read_multi_packets > 0)
   1616         ioctl(linux_cb.sock, BCMNFC_READ_MULTI_PACKETS, bcmi2cnfc_read_multi_packets);
   1617 
   1618     while (!resetSuccess && numTries < NUM_RESET_ATTEMPTS) {
   1619         if (numTries++ > 0) {
   1620             ALOGW("BCM2079x: retrying reset, attempt %d/%d", numTries, NUM_RESET_ATTEMPTS);
   1621         }
   1622         if (linux_cb.sock_power_control > 0)
   1623         {
   1624             current_nfc_wake_state = NFC_WAKE_ASSERTED_ON_POR;
   1625             ioctl(linux_cb.sock_power_control, BCMNFC_WAKE_CTL, NFC_WAKE_ASSERTED_ON_POR);
   1626             ioctl(linux_cb.sock_power_control, BCMNFC_POWER_CTL, 0);
   1627             GKI_delay(10);
   1628             ret = ioctl(linux_cb.sock_power_control, BCMNFC_POWER_CTL, 1);
   1629         }
   1630 
   1631         ret = GetStrValue ( NAME_SPI_NEGOTIATION, (char*)spi_negotiation, sizeof ( spi_negotiation ) );
   1632         if (ret > 0 && spi_negotiation[0] > 0 && spi_negotiation[0] < sizeof ( spi_negotiation ) - 1)
   1633         {
   1634             int len = spi_negotiation[0];
   1635             /* Wake control is not available: Start SPI negotiation*/
   1636             USERIAL_Write(port, &spi_negotiation[1], len);
   1637             USERIAL_Read(port, spi_negotiation, sizeof ( spi_negotiation ));
   1638         }
   1639 
   1640         if ( GetNumValue ( NAME_CLIENT_ADDRESS, &num, sizeof ( num ) ) )
   1641             bcmi2cnfc_client_addr = num & 0xFF;
   1642         if (bcmi2cnfc_client_addr != 0 &&
   1643             0x07 < bcmi2cnfc_client_addr &&
   1644             bcmi2cnfc_client_addr < 0x78)
   1645         {
   1646             /* Delay needed after turning on chip */
   1647             GKI_delay(delay);
   1648             ALOGD( "Change client address to %x\n", bcmi2cnfc_client_addr);
   1649             ret = change_client_addr(bcmi2cnfc_client_addr);
   1650             if (!ret) {
   1651                 resetSuccess = 1;
   1652                 linux_cb.client_device_address = bcmi2cnfc_client_addr;
   1653                 /* Delay long enough for address change */
   1654                 delay = 200;
   1655             }
   1656         } else {
   1657             resetSuccess = 1;
   1658         }
   1659     }
   1660 
   1661     if (!resetSuccess) {
   1662         ALOGE("BCM2079x: failed to initialize NFC controller");
   1663     }
   1664 
   1665     GKI_delay(delay);
   1666     ALOGD("%s: exit", __FUNCTION__);
   1667 }
   1668 
   1669 #define DEFAULT_CLIENT_ADDRESS 0x77
   1670 #define ALIAS_CLIENT_ADDRESS   0x79
   1671 static int change_client_addr(int addr)
   1672 {
   1673     int ret;
   1674     int i;
   1675     char addr_data[] = {
   1676         0xFA, 0xF2, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x2A
   1677     };
   1678     int size = sizeof(addr_data) - 1;
   1679 
   1680     addr_data[5] = addr & 0xFF;
   1681 
   1682     /* set the checksum */
   1683     ret = 0;
   1684     for (i = 1; i < size; ++i)
   1685         ret += addr_data[i];
   1686     addr_data[size] = (ret & 0xFF);
   1687     ALOGD( "change_client_addr() change addr from 0x%x to 0x%x\n", DEFAULT_CLIENT_ADDRESS, addr);
   1688     /* ignore the return code from IOCTL */
   1689     /* always revert back to the default client address */
   1690     ioctl(linux_cb.sock, BCMNFC_SET_CLIENT_ADDR, DEFAULT_CLIENT_ADDRESS);
   1691     /* Send address change command (skipping first byte) */
   1692     ret = write(linux_cb.sock, &addr_data[1], size);
   1693 
   1694     /* If it fails, it is likely a B3 we are talking to */
   1695     if (ret != size) {
   1696         ALOGD( "change_client_addr() change addr to 0x%x by setting BSP address to 0x%x\n", addr, ALIAS_CLIENT_ADDRESS);
   1697         /* MACO changed to support B3 with old kernel driver */
   1698         ret = ioctl(linux_cb.sock, BCMNFC_CHANGE_ADDR, addr);
   1699         return ret;
   1700     }
   1701 
   1702     if (ret == size) {
   1703         ALOGD( "change_client_addr() set client address 0x%x to client driver\n", addr);
   1704         ret = ioctl(linux_cb.sock, BCMNFC_SET_CLIENT_ADDR, addr);
   1705     }
   1706     else {
   1707         ret = -EIO;
   1708     }
   1709     return ret;
   1710 }
   1711