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