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