btif_sock_thread.c revision 104e3f238f500cacdb8afaccdc672dfc34eae7ee
1/******************************************************************************
2 *
3 *  Copyright (C) 2009-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/************************************************************************************
20 *
21 *  Filename:      btif_sock_thread.c
22 *
23 *  Description:   socket select thread
24 *
25 *
26 ***********************************************************************************/
27
28#include <hardware/bluetooth.h>
29#include <hardware/bt_sock.h>
30
31//bta_jv_co_rfc_data
32#include <stdio.h>
33#include <stdlib.h>
34#include <errno.h>
35#include <string.h>
36#include <sys/types.h>
37#include <sys/socket.h>
38#include <sys/un.h>
39#include <time.h>
40#include <fcntl.h>
41#include <unistd.h>
42#include <signal.h>
43#include <pthread.h>
44#include <ctype.h>
45
46#include <sys/select.h>
47#include <sys/poll.h>
48#include <cutils/sockets.h>
49#include <alloca.h>
50
51#define LOG_TAG "BTIF_SOCK"
52#include "btif_common.h"
53#include "btif_util.h"
54
55#include "bd.h"
56
57#include "bta_api.h"
58#include "btif_sock.h"
59#include "btif_sock_thread.h"
60#include "btif_sock_util.h"
61
62#include <cutils/log.h>
63#define asrt(s) if(!(s)) APPL_TRACE_ERROR("## %s assert %s failed at line:%d ##",__FUNCTION__, #s, __LINE__)
64#define print_events(events) do { \
65    APPL_TRACE_DEBUG("print poll event:%x", events); \
66    if (events & POLLIN) APPL_TRACE_DEBUG(  "   POLLIN "); \
67    if (events & POLLPRI) APPL_TRACE_DEBUG( "   POLLPRI "); \
68    if (events & POLLOUT) APPL_TRACE_DEBUG( "   POLLOUT "); \
69    if (events & POLLERR) APPL_TRACE_DEBUG( "   POLLERR "); \
70    if (events & POLLHUP) APPL_TRACE_DEBUG( "   POLLHUP "); \
71    if (events & POLLNVAL) APPL_TRACE_DEBUG("   POLLNVAL "); \
72    if (events & POLLRDHUP) APPL_TRACE_DEBUG("   POLLRDHUP"); \
73    } while(0)
74
75#define MAX_THREAD 8
76#define MAX_POLL 64
77#define POLL_EXCEPTION_EVENTS (POLLHUP | POLLRDHUP | POLLERR | POLLNVAL)
78#define IS_EXCEPTION(e) ((e) & POLL_EXCEPTION_EVENTS)
79#define IS_READ(e) ((e) & POLLIN)
80#define IS_WRITE(e) ((e) & POLLOUT)
81/*cmd executes in socket poll thread */
82#define CMD_WAKEUP       1
83#define CMD_EXIT         2
84#define CMD_ADD_FD       3
85#define CMD_USER_PRIVATE 4
86
87typedef struct {
88    struct pollfd pfd;
89    uint32_t user_id;
90    int type;
91    int flags;
92} poll_slot_t;
93typedef struct {
94    int cmd_fdr, cmd_fdw;
95    int poll_count;
96    poll_slot_t ps[MAX_POLL];
97    int psi[MAX_POLL]; //index of poll slot
98    volatile pid_t thread_id;
99    btsock_signaled_cb callback;
100    btsock_cmd_cb cmd_callback;
101    int used;
102} thread_slot_t;
103static thread_slot_t ts[MAX_THREAD];
104
105
106
107static void *sock_poll_thread(void *arg);
108static inline void close_cmd_fd(int h);
109
110static inline void add_poll(int h, int fd, int type, int flags, uint32_t user_id);
111
112static pthread_mutex_t thread_slot_lock;
113
114
115static inline pthread_t create_thread(void *(*start_routine)(void *), void * arg)
116{
117    pthread_attr_t thread_attr;
118    pthread_attr_init(&thread_attr);
119    pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE);
120    pthread_t thread_id = -1;
121    if( pthread_create(&thread_id, &thread_attr, start_routine, arg)!=0 )
122    {
123        APPL_TRACE_ERROR("pthread_create : %s", strerror(errno));
124        return -1;
125    }
126    return thread_id;
127}
128static void init_poll(int cmd_fd);
129static int alloc_thread_slot()
130{
131    int i;
132    //revserd order to save guard uninitialized access to 0 index
133    for(i = MAX_THREAD - 1; i >=0; i--)
134    {
135        APPL_TRACE_DEBUG("ts[%d].used:%d", i, ts[i].used);
136        if(!ts[i].used)
137        {
138            ts[i].used = 1;
139            return i;
140        }
141    }
142    APPL_TRACE_ERROR("execeeded max thread count");
143    return -1;
144}
145static void free_thread_slot(int h)
146{
147    if(0 <= h && h < MAX_THREAD)
148    {
149        close_cmd_fd(h);
150        ts[h].used = 0;
151    }
152    else APPL_TRACE_ERROR("invalid thread handle:%d", h);
153}
154int btsock_thread_init()
155{
156    static int initialized;
157    APPL_TRACE_DEBUG("in initialized:%d", initialized);
158    if(!initialized)
159    {
160        initialized = 1;
161        init_slot_lock(&thread_slot_lock);
162        int h;
163        for(h = 0; h < MAX_THREAD; h++)
164        {
165            ts[h].cmd_fdr = ts[h].cmd_fdw = -1;
166            ts[h].used = 0;
167            ts[h].thread_id = -1;
168            ts[h].poll_count = 0;
169            ts[h].callback = NULL;
170            ts[h].cmd_callback = NULL;
171        }
172    }
173    return TRUE;
174}
175int btsock_thread_create(btsock_signaled_cb callback, btsock_cmd_cb cmd_callback)
176{
177    asrt(callback || cmd_callback);
178    lock_slot(&thread_slot_lock);
179    int h = alloc_thread_slot();
180    unlock_slot(&thread_slot_lock);
181    APPL_TRACE_DEBUG("alloc_thread_slot ret:%d", h);
182    if(h >= 0)
183    {
184        init_poll(h);
185        if((ts[h].thread_id = create_thread(sock_poll_thread, (void*)(uintptr_t)h)) != -1)
186        {
187            APPL_TRACE_DEBUG("h:%d, thread id:%d", h, ts[h].thread_id);
188            ts[h].callback = callback;
189            ts[h].cmd_callback = cmd_callback;
190        }
191        else
192        {
193            free_thread_slot(h);
194            h = -1;
195        }
196    }
197    return h;
198}
199
200/* create dummy socket pair used to wake up select loop */
201static inline void init_cmd_fd(int h)
202{
203    asrt(ts[h].cmd_fdr == -1 && ts[h].cmd_fdw == -1);
204    if(socketpair(AF_UNIX, SOCK_STREAM, 0, &ts[h].cmd_fdr) < 0)
205    {
206        APPL_TRACE_ERROR("socketpair failed: %s", strerror(errno));
207        return;
208    }
209    APPL_TRACE_DEBUG("h:%d, cmd_fdr:%d, cmd_fdw:%d", h, ts[h].cmd_fdr, ts[h].cmd_fdw);
210    //add the cmd fd for read & write
211    add_poll(h, ts[h].cmd_fdr, 0, SOCK_THREAD_FD_RD, 0);
212}
213static inline void close_cmd_fd(int h)
214{
215    if(ts[h].cmd_fdr != -1)
216    {
217        close(ts[h].cmd_fdr);
218        ts[h].cmd_fdr = -1;
219    }
220    if(ts[h].cmd_fdw != -1)
221    {
222        close(ts[h].cmd_fdw);
223        ts[h].cmd_fdw = -1;
224    }
225}
226typedef struct
227{
228    int id;
229    int fd;
230    int type;
231    int flags;
232    uint32_t user_id;
233} sock_cmd_t;
234int btsock_thread_add_fd(int h, int fd, int type, int flags, uint32_t user_id)
235{
236    if(h < 0 || h >= MAX_THREAD)
237    {
238        APPL_TRACE_ERROR("invalid bt thread handle:%d", h);
239        return FALSE;
240    }
241    if(ts[h].cmd_fdw == -1)
242    {
243        APPL_TRACE_ERROR("cmd socket is not created. socket thread may not initialized");
244        return FALSE;
245    }
246    if(flags & SOCK_THREAD_ADD_FD_SYNC)
247    {
248        //must executed in socket poll thread
249        if(ts[h].thread_id == pthread_self())
250        {
251            //cleanup one-time flags
252            flags &= ~SOCK_THREAD_ADD_FD_SYNC;
253            add_poll(h, fd, type, flags, user_id);
254            return TRUE;
255        }
256        APPL_TRACE_DEBUG("THREAD_ADD_FD_SYNC is not called in poll thread, fallback to async");
257    }
258    sock_cmd_t cmd = {CMD_ADD_FD, fd, type, flags, user_id};
259    APPL_TRACE_DEBUG("adding fd:%d, flags:0x%x", fd, flags);
260    return send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0) == sizeof(cmd);
261}
262int btsock_thread_post_cmd(int h, int type, const unsigned char* data, int size, uint32_t user_id)
263{
264    if(h < 0 || h >= MAX_THREAD)
265    {
266        APPL_TRACE_ERROR("invalid bt thread handle:%d", h);
267        return FALSE;
268    }
269    if(ts[h].cmd_fdw == -1)
270    {
271        APPL_TRACE_ERROR("cmd socket is not created. socket thread may not initialized");
272        return FALSE;
273    }
274    sock_cmd_t cmd = {CMD_USER_PRIVATE, 0, type, size, user_id};
275    APPL_TRACE_DEBUG("post cmd type:%d, size:%d, h:%d, ", type, size, h);
276    sock_cmd_t* cmd_send = &cmd;
277    int size_send = sizeof(cmd);
278    if(data && size)
279    {
280        size_send = sizeof(cmd) + size;
281        cmd_send = (sock_cmd_t*)alloca(size_send);
282        if(cmd_send)
283        {
284            *cmd_send = cmd;
285            memcpy(cmd_send + 1, data, size);
286        }
287        else
288        {
289            APPL_TRACE_ERROR("alloca failed at h:%d, cmd type:%d, size:%d", h, type, size_send);
290            return FALSE;
291        }
292    }
293    return send(ts[h].cmd_fdw, cmd_send, size_send, 0) == size_send;
294}
295int btsock_thread_wakeup(int h)
296{
297    if(h < 0 || h >= MAX_THREAD)
298    {
299        APPL_TRACE_ERROR("invalid bt thread handle:%d", h);
300        return FALSE;
301    }
302    if(ts[h].cmd_fdw == -1)
303    {
304        APPL_TRACE_ERROR("thread handle:%d, cmd socket is not created", h);
305        return FALSE;
306    }
307    sock_cmd_t cmd = {CMD_WAKEUP, 0, 0, 0, 0};
308    return send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0) == sizeof(cmd);
309}
310int btsock_thread_exit(int h)
311{
312    if(h < 0 || h >= MAX_THREAD)
313    {
314        APPL_TRACE_ERROR("invalid bt thread handle:%d", h);
315        return FALSE;
316    }
317    if(ts[h].cmd_fdw == -1)
318    {
319        APPL_TRACE_ERROR("cmd socket is not created");
320        return FALSE;
321    }
322    sock_cmd_t cmd = {CMD_EXIT, 0, 0, 0, 0};
323    if(send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0) == sizeof(cmd))
324    {
325        pthread_join(ts[h].thread_id, 0);
326        lock_slot(&thread_slot_lock);
327        free_thread_slot(h);
328        unlock_slot(&thread_slot_lock);
329        return TRUE;
330    }
331    return FALSE;
332}
333static void init_poll(int h)
334{
335    int i;
336    ts[h].poll_count = 0;
337    ts[h].thread_id = -1;
338    ts[h].callback = NULL;
339    ts[h].cmd_callback = NULL;
340    for(i = 0; i < MAX_POLL; i++)
341    {
342        ts[h].ps[i].pfd.fd = -1;
343        ts[h].psi[i] = -1;
344    }
345    init_cmd_fd(h);
346}
347static inline unsigned int flags2pevents(int flags)
348{
349    unsigned int pevents = 0;
350    if(flags & SOCK_THREAD_FD_WR)
351        pevents |= POLLOUT;
352    if(flags & SOCK_THREAD_FD_RD)
353        pevents |= POLLIN;
354    pevents |= POLL_EXCEPTION_EVENTS;
355    return pevents;
356}
357
358static inline void set_poll(poll_slot_t* ps, int fd, int type, int flags, uint32_t user_id)
359{
360    ps->pfd.fd = fd;
361    ps->user_id = user_id;
362    if(ps->type != 0 && ps->type != type)
363        APPL_TRACE_ERROR("poll socket type should not changed! type was:%d, type now:%d", ps->type, type);
364    ps->type = type;
365    ps->flags = flags;
366    ps->pfd.events = flags2pevents(flags);
367    ps->pfd.revents = 0;
368}
369static inline void add_poll(int h, int fd, int type, int flags, uint32_t user_id)
370{
371    asrt(fd != -1);
372    int i;
373    int empty = -1;
374    poll_slot_t* ps = ts[h].ps;
375
376    for(i = 0; i < MAX_POLL; i++)
377    {
378        if(ps[i].pfd.fd == fd)
379        {
380            asrt(ts[h].poll_count < MAX_POLL);
381
382            set_poll(&ps[i], fd, type, flags | ps[i].flags, user_id);
383            return;
384        }
385        else if(empty < 0 && ps[i].pfd.fd == -1)
386            empty = i;
387    }
388    if(empty >= 0)
389    {
390        asrt(ts[h].poll_count < MAX_POLL);
391        set_poll(&ps[empty], fd, type, flags, user_id);
392        ++ts[h].poll_count;
393        return;
394    }
395    APPL_TRACE_ERROR("exceeded max poll slot:%d!", MAX_POLL);
396}
397static inline void remove_poll(int h, poll_slot_t* ps, int flags)
398{
399    if(flags == ps->flags)
400    {
401        //all monitored events signaled. To remove it, just clear the slot
402        --ts[h].poll_count;
403        memset(ps, 0, sizeof(*ps));
404        ps->pfd.fd = -1;
405    }
406    else
407    {
408        //one read or one write monitor event signaled, removed the accordding bit
409        ps->flags &= ~flags;
410        //update the poll events mask
411        ps->pfd.events = flags2pevents(ps->flags);
412    }
413}
414static int process_cmd_sock(int h)
415{
416    sock_cmd_t cmd = {-1, 0, 0, 0, 0};
417    int fd = ts[h].cmd_fdr;
418    if(recv(fd, &cmd, sizeof(cmd), MSG_WAITALL) != sizeof(cmd))
419    {
420        APPL_TRACE_ERROR("recv cmd errno:%d", errno);
421        return FALSE;
422    }
423    APPL_TRACE_DEBUG("cmd.id:%d", cmd.id);
424    switch(cmd.id)
425    {
426        case CMD_ADD_FD:
427            add_poll(h, cmd.fd, cmd.type, cmd.flags, cmd.user_id);
428            break;
429        case CMD_WAKEUP:
430            break;
431        case CMD_USER_PRIVATE:
432            asrt(ts[h].cmd_callback);
433            if(ts[h].cmd_callback)
434                ts[h].cmd_callback(fd, cmd.type, cmd.flags, cmd.user_id);
435            break;
436        case CMD_EXIT:
437            return FALSE;
438        default:
439            APPL_TRACE_DEBUG("unknown cmd: %d", cmd.id);
440             break;
441    }
442    return TRUE;
443}
444static void process_data_sock(int h, struct pollfd *pfds, int count)
445{
446    asrt(count <= ts[h].poll_count);
447    int i;
448    for( i= 1; i < ts[h].poll_count; i++)
449    {
450        if(pfds[i].revents)
451        {
452            int ps_i = ts[h].psi[i];
453            asrt(pfds[i].fd == ts[h].ps[ps_i].pfd.fd);
454            uint32_t user_id = ts[h].ps[ps_i].user_id;
455            int type = ts[h].ps[ps_i].type;
456            int flags = 0;
457            print_events(pfds[i].revents);
458            if(IS_READ(pfds[i].revents))
459            {
460                flags |= SOCK_THREAD_FD_RD;
461            }
462            if(IS_WRITE(pfds[i].revents))
463            {
464                flags |= SOCK_THREAD_FD_WR;
465            }
466            if(IS_EXCEPTION(pfds[i].revents))
467            {
468                flags |= SOCK_THREAD_FD_EXCEPTION;
469                //remove the whole slot not flags
470                remove_poll(h, &ts[h].ps[ps_i], ts[h].ps[ps_i].flags);
471            }
472            else if(flags)
473                 remove_poll(h, &ts[h].ps[ps_i], flags); //remove the monitor flags that already processed
474            if(flags)
475                ts[h].callback(pfds[i].fd, type, flags, user_id);
476        }
477    }
478}
479
480static void prepare_poll_fds(int h, struct pollfd* pfds)
481{
482    int count = 0;
483    int ps_i = 0;
484    int pfd_i = 0;
485    asrt(ts[h].poll_count <= MAX_POLL);
486    memset(pfds, 0, sizeof(pfds[0])*ts[h].poll_count);
487    while(count < ts[h].poll_count)
488    {
489        if(ps_i >= MAX_POLL)
490        {
491            APPL_TRACE_ERROR("exceed max poll range, ps_i:%d, MAX_POLL:%d, count:%d, ts[h].poll_count:%d",
492                    ps_i, MAX_POLL, count, ts[h].poll_count);
493            return;
494        }
495        if(ts[h].ps[ps_i].pfd.fd >= 0)
496        {
497            pfds[pfd_i] =  ts[h].ps[ps_i].pfd;
498            ts[h].psi[pfd_i] = ps_i;
499            count++;
500            pfd_i++;
501        }
502        ps_i++;
503    }
504}
505static void *sock_poll_thread(void *arg)
506{
507    struct pollfd pfds[MAX_POLL];
508    memset(pfds, 0, sizeof(pfds));
509    int h = (intptr_t)arg;
510    for(;;)
511    {
512        prepare_poll_fds(h, pfds);
513        int ret = poll(pfds, ts[h].poll_count, -1);
514        if(ret == -1)
515        {
516            APPL_TRACE_ERROR("poll ret -1, exit the thread, errno:%d, err:%s", errno, strerror(errno));
517            break;
518        }
519        if(ret != 0)
520        {
521            int need_process_data_fd = TRUE;
522            if(pfds[0].revents) //cmd fd always is the first one
523            {
524                asrt(pfds[0].fd == ts[h].cmd_fdr);
525                if(!process_cmd_sock(h))
526                {
527                    APPL_TRACE_DEBUG("h:%d, process_cmd_sock return false, exit...", h);
528                    break;
529                }
530                if(ret == 1)
531                    need_process_data_fd = FALSE;
532                else ret--; //exclude the cmd fd
533            }
534            if(need_process_data_fd)
535                process_data_sock(h, pfds, ret);
536        }
537        else {APPL_TRACE_DEBUG("no data, select ret: %d", ret)};
538    }
539    ts[h].thread_id = -1;
540    APPL_TRACE_DEBUG("socket poll thread exiting, h:%d", h);
541    return 0;
542}
543
544