/*******************************************************************************
**
** Function        select_read
**
** Description     check if fd is ready for reading and listen for termination
**                  signal. need to use select in order to avoid collision
**                  between read and close on the same fd
**
** Returns         -1: termination
**                 >=0: numbers of bytes read back from fd
**
*******************************************************************************/
static int select_read(int fd, uint8_t *pbuf, int len)
{
    fd_set input;
    int n = 0, ret = -1;
    char reason = 0;

    while (userial_running)
    {
        /* Initialize the input fd set */
        FD_ZERO(&input);
        if (rx_flow_on == TRUE)
        {
            FD_SET(fd, &input);
        }
        int fd_max = create_signal_fds(&input);
        fd_max = fd_max > fd ? fd_max : fd;

        /* Do the select */
        n = select(fd_max+1, &input, NULL, NULL, NULL);
        if(is_signaled(&input))
        {
            reason = reset_signal();
            if (reason == USERIAL_RX_EXIT)
            {
                USERIALDBG("RX termination");
                return -1;
            }
            else if (reason == USERIAL_RX_FLOW_OFF)
            {
                USERIALDBG("RX flow OFF");
                rx_flow_on = FALSE;
            }
            else if (reason == USERIAL_RX_FLOW_ON)
            {
                USERIALDBG("RX flow ON");
                rx_flow_on = TRUE;
            }
        }

        if (n > 0)
        {
            /* We might have input */
            if (FD_ISSET(fd, &input))
            {
                ret = read(fd, pbuf, (size_t)len);
                if (0 == ret)
                    ALOGW( "read() returned 0!" );

                return ret;
            }
        }
        else if (n < 0)
            ALOGW( "select() Failed");
        else if (n == 0)
            ALOGW( "Got a select() TIMEOUT");

    }

    return ret;
}
/*******************************************************************************
**
** Function        userial_close
**
** Description     Close the userial port
**
** Returns         None
**
*******************************************************************************/
void userial_close(void)
{
    int result;
    TRANSAC p_buf;

    USERIALDBG("userial_close(fd:%d)", userial_cb.fd);

    if (userial_running)
        send_wakeup_signal(USERIAL_RX_EXIT);

    if ((result=pthread_join(userial_cb.read_thread, NULL)) < 0)
        ALOGE( "pthread_join() FAILED result:%d", result);

    /* Calling vendor-specific part */
    if (bt_vnd_if)
        bt_vnd_if->op(BT_VND_OP_USERIAL_CLOSE, NULL);

    userial_cb.fd = -1;

    if (bt_hc_cbacks)
    {
        while ((p_buf = utils_dequeue (&(userial_cb.rx_q))) != NULL)
        {
            bt_hc_cbacks->dealloc(p_buf, (char *) ((HC_BT_HDR *)p_buf+1));
        }
    }
}
/*******************************************************************************
**
** Function        userial_init
**
** Description     Initializes the userial driver
**
** Returns         TRUE/FALSE
**
*******************************************************************************/
uint8_t userial_init(void)
{
    USERIALDBG("userial_init");
    memset(&userial_cb, 0, sizeof(tUSERIAL_CB));
    userial_cb.fd = -1;
    utils_queue_init(&(userial_cb.rx_q));
    return TRUE;
}
/*******************************************************************************
**
** Function        userial_init
**
** Description     Initializes the userial driver
**
** Returns         TRUE/FALSE
**
*******************************************************************************/
uint8_t userial_init(void)
{
    int idx;

    USERIALDBG("userial_init");
    memset(&userial_cb, 0, sizeof(tUSERIAL_CB));
    for (idx=0; idx < CH_MAX; idx++)
        userial_cb.fd[idx] = -1;
    utils_queue_init(&(userial_cb.rx_q));
    return TRUE;
}
/*******************************************************************************
**
** Function        userial_close
**
** Description     Close the userial port
**
** Returns         None
**
*******************************************************************************/
void userial_close(void)
{
    int idx, result;

    USERIALDBG("userial_close");

    if (userial_running)
        send_wakeup_signal(USERIAL_RX_EXIT);

    if ((result=pthread_join(userial_cb.read_thread, NULL)) < 0)
        ALOGE( "pthread_join() FAILED result:%d", result);

    /* Calling vendor-specific part */
    if (bt_vnd_if)
        bt_vnd_if->op(BT_VND_OP_USERIAL_CLOSE, NULL);

    for (idx=0; idx < CH_MAX; idx++)
        userial_cb.fd[idx] = -1;
}
/*******************************************************************************
**
** Function        userial_open
**
** Description     Open Bluetooth device with the port ID
**
** Returns         TRUE/FALSE
**
*******************************************************************************/
uint8_t userial_open(uint8_t port)
{
    struct sched_param param;
    int policy, result;
    pthread_attr_t thread_attr;

    USERIALDBG("userial_open(port:%d)", port);

    if (userial_running)
    {
        /* Userial is open; close it first */
        userial_close();
        utils_delay(50);
    }

    if (port >= MAX_SERIAL_PORT)
    {
        ALOGE("Port > MAX_SERIAL_PORT");
        return FALSE;
    }

    /* Calling vendor-specific part */
    if (bt_vnd_if)
    {
        result = bt_vnd_if->op(BT_VND_OP_USERIAL_OPEN, &userial_cb.fd);

        if ((result != 2) && (result != 4))
        {
            ALOGE("userial_open: wrong numbers of open fd in vendor lib [%d]!",
                    result);
            ALOGE("userial_open: HCI MCT expects 2 or 4 open file descriptors");
            bt_vnd_if->op(BT_VND_OP_USERIAL_CLOSE, NULL);
            return FALSE;
        }
    }
    else
    {
        ALOGE("userial_open: missing vendor lib interface !!!");
        ALOGE("userial_open: unable to open BT transport");
        return FALSE;
    }

    ALOGI("CMD=%d, EVT=%d, ACL_Out=%d, ACL_In=%d", \
        userial_cb.fd[CH_CMD], userial_cb.fd[CH_EVT], \
        userial_cb.fd[CH_ACL_OUT], userial_cb.fd[CH_ACL_IN]);

    if ((userial_cb.fd[CH_CMD] == -1) || (userial_cb.fd[CH_EVT] == -1) ||
        (userial_cb.fd[CH_ACL_OUT] == -1) || (userial_cb.fd[CH_ACL_IN] == -1))
    {
        ALOGE("userial_open: failed to open BT transport");
        bt_vnd_if->op(BT_VND_OP_USERIAL_CLOSE, NULL);
        return FALSE;
    }

    userial_cb.port = port;

    /* Start listening thread */
    pthread_attr_init(&thread_attr);

    if (pthread_create(&(userial_cb.read_thread), &thread_attr, \
                       userial_read_thread, NULL) != 0 )
    {
        ALOGE("pthread_create failed!");
        bt_vnd_if->op(BT_VND_OP_USERIAL_CLOSE, NULL);
        return FALSE;
    }

    if(pthread_getschedparam(userial_cb.read_thread, &policy, &param)==0)
    {
        policy = BTHC_LINUX_BASE_POLICY;
#if (BTHC_LINUX_BASE_POLICY != SCHED_NORMAL)
        param.sched_priority = BTHC_USERIAL_READ_THREAD_PRIORITY;
#else
        param.sched_priority = 0;
#endif
        result = pthread_setschedparam(userial_cb.read_thread, policy, &param);
        if (result != 0)
        {
            ALOGW("userial_open: pthread_setschedparam failed (%s)", \
                  strerror(result));
        }
    }

    return TRUE;
}
/*******************************************************************************
**
** Function        userial_evt_read_thread
**
** Description     The reading thread on EVT and ACL_IN channels
**
** Returns         void *
**
*******************************************************************************/
static void *userial_read_thread(void *arg)
{
    fd_set input;
    int n;
    char reason = 0;

    USERIALDBG("Entering userial_read_thread()");

    rx_flow_on = TRUE;
    userial_running = 1;

    raise_priority_a2dp(TASK_HIGH_USERIAL_READ);

    while (userial_running)
    {
        /* Initialize the input fd set */
        FD_ZERO(&input);
        if (rx_flow_on == TRUE)
        {
            FD_SET(userial_cb.fd[CH_EVT], &input);
            FD_SET(userial_cb.fd[CH_ACL_IN], &input);
        }

        int fd_max = create_signal_fds(&input);
        fd_max = (fd_max>userial_cb.fd[CH_EVT]) ? fd_max : userial_cb.fd[CH_EVT];
        fd_max = (fd_max>userial_cb.fd[CH_ACL_IN]) ? fd_max : userial_cb.fd[CH_ACL_IN];

        /* Do the select */
        n = 0;
        n = select(fd_max+1, &input, NULL, NULL, NULL);
        if(is_signaled(&input))
        {
            reason = reset_signal();
            if (reason == USERIAL_RX_EXIT)
            {
                ALOGI("exiting userial_read_thread");
                userial_running = 0;
                break;
            }
            else if (reason == USERIAL_RX_FLOW_OFF)
            {
                USERIALDBG("RX flow OFF");
                rx_flow_on = FALSE;
            }
            else if (reason == USERIAL_RX_FLOW_ON)
            {
                USERIALDBG("RX flow ON");
                rx_flow_on = TRUE;
            }
        }

        if (n > 0)
        {
            /* We might have input */
            if (FD_ISSET(userial_cb.fd[CH_EVT], &input))
            {
                hci_mct_receive_evt_msg();
            }

            if (FD_ISSET(userial_cb.fd[CH_ACL_IN], &input))
            {
                hci_mct_receive_acl_msg();
            }
        }
        else if (n < 0)
            ALOGW( "select() Failed");
        else if (n == 0)
            ALOGW( "Got a select() TIMEOUT");
    } /* while */

    userial_running = 0;
    USERIALDBG("Leaving userial_evt_read_thread()");
    pthread_exit(NULL);

    return NULL;    // Compiler friendly
}
/*******************************************************************************
**
** Function        userial_open
**
** Description     Open Bluetooth device with the port ID
**
** Returns         TRUE/FALSE
**
*******************************************************************************/
uint8_t userial_open(uint8_t port)
{
    struct sched_param param;
    int policy, result;
    pthread_attr_t thread_attr;
    int fd_array[CH_MAX];

    USERIALDBG("userial_open(port:%d)", port);

    if (userial_running)
    {
        /* Userial is open; close it first */
        userial_close();
        utils_delay(50);
    }

    if (port >= MAX_SERIAL_PORT)
    {
        ALOGE("Port > MAX_SERIAL_PORT");
        return FALSE;
    }

    /* Calling vendor-specific part */
    if (bt_vnd_if)
    {
        result = bt_vnd_if->op(BT_VND_OP_USERIAL_OPEN, &fd_array);

        if (result != 1)
        {
            ALOGE("userial_open: wrong numbers of open fd in vendor lib [%d]!",
                    result);
            ALOGE("userial_open: HCI UART expects only one open fd");
            bt_vnd_if->op(BT_VND_OP_USERIAL_CLOSE, NULL);
            return FALSE;
        }

        userial_cb.fd = fd_array[0];
    }
    else
    {
        ALOGE("userial_open: missing vendor lib interface !!!");
        ALOGE("userial_open: unable to open UART port");
        return FALSE;
    }

    if (userial_cb.fd == -1)
    {
        ALOGE("userial_open: failed to open UART port");
        return FALSE;
    }

    USERIALDBG( "fd = %d", userial_cb.fd);

    userial_cb.port = port;

    pthread_attr_init(&thread_attr);

    if (pthread_create(&(userial_cb.read_thread), &thread_attr, \
                       userial_read_thread, NULL) != 0 )
    {
        ALOGE("pthread_create failed!");
        return FALSE;
    }

    if(pthread_getschedparam(userial_cb.read_thread, &policy, &param)==0)
    {
        policy = BTHC_LINUX_BASE_POLICY;
#if (BTHC_LINUX_BASE_POLICY!=SCHED_NORMAL)
        param.sched_priority = BTHC_USERIAL_READ_THREAD_PRIORITY;
#endif
        result = pthread_setschedparam(userial_cb.read_thread, policy, &param);
        if (result != 0)
        {
            ALOGW("userial_open: pthread_setschedparam failed (%s)", \
                  strerror(result));
        }
    }

    return TRUE;
}
/*******************************************************************************
**
** Function        userial_read_thread
**
** Description
**
** Returns         void *
**
*******************************************************************************/
static void *userial_read_thread(void *arg)
{
    int rx_length = 0;
    HC_BT_HDR *p_buf = NULL;
    uint8_t *p;

    USERIALDBG("Entering userial_read_thread()");
    prctl(PR_SET_NAME, (unsigned long)"userial_read", 0, 0, 0);

    rx_flow_on = TRUE;
    userial_running = 1;

    raise_priority_a2dp(TASK_HIGH_USERIAL_READ);

    while (userial_running)
    {
        if (bt_hc_cbacks)
        {
            p_buf = (HC_BT_HDR *) bt_hc_cbacks->alloc( \
                                                BTHC_USERIAL_READ_MEM_SIZE);
        }
        else
            p_buf = NULL;

        if (p_buf != NULL)
        {
            p_buf->offset = 0;
            p_buf->layer_specific = 0;

            p = (uint8_t *) (p_buf + 1);
            rx_length = select_read(userial_cb.fd, p, READ_LIMIT);
        }
        else
        {
            rx_length = 0;
            utils_delay(100);
            ALOGW("userial_read_thread() failed to gain buffers");
            continue;
        }


        if (rx_length > 0)
        {
            p_buf->len = (uint16_t)rx_length;
            utils_enqueue(&(userial_cb.rx_q), p_buf);
            bthc_signal_event(HC_EVENT_RX);
        }
        else /* either 0 or < 0 */
        {
            ALOGW("select_read return size <=0:%d, exiting userial_read_thread",\
                 rx_length);
            /* if we get here, we should have a buffer */
            bt_hc_cbacks->dealloc((TRANSAC) p_buf, (char *) (p_buf + 1));
            /* negative value means exit thread */
            break;
        }
    } /* for */

    userial_running = 0;
    USERIALDBG("Leaving userial_read_thread()");
    pthread_exit(NULL);

    return NULL;    // Compiler friendly
}