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 #include <android-base/logging.h>
19 #include <android-base/stringprintf.h>
20 #include <errno.h>
21 #include <malloc.h>
22 #include <pthread.h> /* must be 1st header defined */
23
24 #include "gki_int.h"
25
26 using android::base::StringPrintf;
27
28 /* Temp android logging...move to android tgt config file */
29
30 #ifndef LINUX_NATIVE
31 #else
32 #define LOGV(format, ...) fprintf(stdout, LOG_TAG format, ##__VA_ARGS__)
33 #define LOGE(format, ...) fprintf(stderr, LOG_TAG format, ##__VA_ARGS__)
34 #define LOGI(format, ...) fprintf(stdout, LOG_TAG format, ##__VA_ARGS__)
35
36 #define SCHED_NORMAL 0
37 #define SCHED_FIFO 1
38 #define SCHED_RR 2
39 #define SCHED_BATCH 3
40
41 #endif
42
43 /* Define the structure that holds the GKI variables */
44 tGKI_CB gki_cb;
45
46 #define NANOSEC_PER_MILLISEC (1000000)
47 #define NSEC_PER_SEC (1000 * NANOSEC_PER_MILLISEC)
48
49 /* works only for 1ms to 1000ms heart beat ranges */
50 #define LINUX_SEC (1000 / TICKS_PER_SEC)
51 // #define GKI_TICK_TIMER_DEBUG
52
53 /* this kind of mutex go into tGKI_OS control block!!!! */
54 /* static pthread_mutex_t GKI_sched_mutex; */
55 /*static pthread_mutex_t thread_delay_mutex;
56 static pthread_cond_t thread_delay_cond;
57 static pthread_mutex_t gki_timer_update_mutex;
58 static pthread_cond_t gki_timer_update_cond;
59 */
60 #ifdef NO_GKI_RUN_RETURN
61 static pthread_t timer_thread_id = 0;
62 #endif
63
64 typedef struct {
65 uint8_t task_id; /* GKI task id */
66 TASKPTR task_entry; /* Task entry function*/
67 uintptr_t params; /* Extra params to pass to task entry function */
68 pthread_cond_t* pCond; /* for android*/
69 pthread_mutex_t* pMutex; /* for android*/
70 } gki_pthread_info_t;
71 gki_pthread_info_t gki_pthread_info[GKI_MAX_TASKS];
72
73 /*******************************************************************************
74 **
75 ** Function gki_task_entry
76 **
77 ** Description entry point of GKI created tasks
78 **
79 ** Returns void
80 **
81 *******************************************************************************/
gki_task_entry(void * params)82 void* gki_task_entry(void* params) {
83 pthread_t thread_id = pthread_self();
84 gki_pthread_info_t* p_pthread_info = (gki_pthread_info_t*)params;
85 LOG(VERBOSE) << StringPrintf(
86 "gki_task_entry task_id=%i, thread_id=%lx/%lx, pCond/pMutex=%p/%p",
87 p_pthread_info->task_id, gki_cb.os.thread_id[p_pthread_info->task_id],
88 pthread_self(), p_pthread_info->pCond, p_pthread_info->pMutex);
89
90 gki_cb.os.thread_id[p_pthread_info->task_id] = thread_id;
91 /* Call the actual thread entry point */
92 (p_pthread_info->task_entry)(p_pthread_info->params);
93
94 LOG(WARNING) << StringPrintf("gki_task task_id=%i terminating",
95 p_pthread_info->task_id);
96 gki_cb.os.thread_id[p_pthread_info->task_id] = 0;
97
98 return nullptr;
99 }
100 /* end android */
101
102 /*******************************************************************************
103 **
104 ** Function GKI_init
105 **
106 ** Description This function is called once at startup to initialize
107 ** all the timer structures.
108 **
109 ** Returns void
110 **
111 *******************************************************************************/
112
GKI_init(void)113 void GKI_init(void) {
114 pthread_mutexattr_t attr;
115 tGKI_OS* p_os;
116
117 gki_buffer_init();
118 gki_timers_init();
119
120 /* Start ticks from 0 */
121 gki_cb.com.OSTicks = 0;
122
123 pthread_mutexattr_init(&attr);
124
125 #ifndef __CYGWIN__
126 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
127 #endif
128 p_os = &gki_cb.os;
129 pthread_mutex_init(&p_os->GKI_mutex, &attr);
130 /* pthread_mutex_init(&GKI_sched_mutex, NULL); */
131 /* pthread_mutex_init(&thread_delay_mutex, NULL); */ /* used in GKI_delay */
132 /* pthread_cond_init (&thread_delay_cond, NULL); */
133
134 /* Initialiase GKI_timer_update suspend variables & mutexes to be in running
135 * state.
136 * this works too even if GKI_NO_TICK_STOP is defined in btld.txt */
137 p_os->no_timer_suspend = GKI_TIMER_TICK_RUN_COND;
138 pthread_mutex_init(&p_os->gki_timer_mutex, nullptr);
139 pthread_cond_init(&p_os->gki_timer_cond, nullptr);
140 }
141
142 /*******************************************************************************
143 **
144 ** Function GKI_get_os_tick_count
145 **
146 ** Description This function is called to retrieve the native OS system
147 ** tick.
148 **
149 ** Returns Tick count of native OS.
150 **
151 *******************************************************************************/
GKI_get_os_tick_count(void)152 uint32_t GKI_get_os_tick_count(void) {
153 /* TODO - add any OS specific code here */
154 return (gki_cb.com.OSTicks);
155 }
156
157 /*******************************************************************************
158 **
159 ** Function GKI_create_task
160 **
161 ** Description This function is called to create a new OSS task.
162 **
163 ** Parameters: task_entry - (input) pointer to the entry function of the
164 ** task
165 ** task_id - (input) Task id is mapped to priority
166 ** taskname - (input) name given to the task
167 ** stack - (input) pointer to the top of the stack
168 ** (highest memory location)
169 ** stacksize - (input) size of the stack allocated for the
170 ** task
171 **
172 ** Returns GKI_SUCCESS if all OK, GKI_FAILURE if any problem
173 **
174 ** NOTE This function take some parameters that may not be needed
175 ** by your particular OS. They are here for compatability
176 ** of the function prototype.
177 **
178 *******************************************************************************/
GKI_create_task(TASKPTR task_entry,uint8_t task_id,int8_t * taskname,uint16_t * stack,uint16_t stacksize,void * pCondVar,void * pMutex)179 uint8_t GKI_create_task(TASKPTR task_entry, uint8_t task_id, int8_t* taskname,
180 uint16_t* stack, uint16_t stacksize, void* pCondVar,
181 void* pMutex) {
182 struct sched_param param;
183 int policy, ret = 0;
184 pthread_condattr_t attr;
185 pthread_attr_t attr1;
186
187 pthread_condattr_init(&attr);
188 pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
189 LOG(VERBOSE) << StringPrintf(
190 "GKI_create_task func=0x%p id=%d name=%s stack=0x%p stackSize=%d",
191 task_entry, task_id, taskname, stack, stacksize);
192
193 if (task_id >= GKI_MAX_TASKS) {
194 LOG(VERBOSE) << StringPrintf("Error! task ID > max task allowed");
195 return (GKI_FAILURE);
196 }
197
198 gki_cb.com.OSRdyTbl[task_id] = TASK_READY;
199 gki_cb.com.OSTName[task_id] = taskname;
200 gki_cb.com.OSWaitTmr[task_id] = 0;
201 gki_cb.com.OSWaitEvt[task_id] = 0;
202
203 /* Initialize mutex and condition variable objects for events and timeouts */
204 pthread_mutex_init(&gki_cb.os.thread_evt_mutex[task_id], nullptr);
205 pthread_cond_init(&gki_cb.os.thread_evt_cond[task_id], &attr);
206 pthread_mutex_init(&gki_cb.os.thread_timeout_mutex[task_id], nullptr);
207 pthread_cond_init(&gki_cb.os.thread_timeout_cond[task_id], &attr);
208
209 pthread_attr_init(&attr1);
210 /* by default, pthread creates a joinable thread */
211 #if (FALSE == GKI_PTHREAD_JOINABLE)
212 pthread_attr_setdetachstate(&attr1, PTHREAD_CREATE_DETACHED);
213
214 LOG(VERBOSE) << StringPrintf("GKI creating task %i, pCond/pMutex=%p/%p",
215 task_id, pCondVar, pMutex);
216 #else
217 LOG(VERBOSE) << StringPrintf("GKI creating JOINABLE task %i", task_id);
218 #endif
219
220 /* On Android, the new tasks starts running before
221 * 'gki_cb.os.thread_id[task_id]' is initialized */
222 /* Pass task_id to new task so it can initialize gki_cb.os.thread_id[task_id]
223 * for it calls GKI_wait */
224 gki_pthread_info[task_id].task_id = task_id;
225 gki_pthread_info[task_id].task_entry = task_entry;
226 gki_pthread_info[task_id].params = 0;
227 gki_pthread_info[task_id].pCond = (pthread_cond_t*)pCondVar;
228 gki_pthread_info[task_id].pMutex = (pthread_mutex_t*)pMutex;
229
230 ret = pthread_create(&gki_cb.os.thread_id[task_id], &attr1, gki_task_entry,
231 &gki_pthread_info[task_id]);
232
233 if (ret != 0) {
234 LOG(VERBOSE) << StringPrintf("pthread_create failed(%d), %s!", ret, taskname);
235 return GKI_FAILURE;
236 }
237
238 if (pthread_getschedparam(gki_cb.os.thread_id[task_id], &policy, ¶m) ==
239 0) {
240 #if (PBS_SQL_TASK == TRUE)
241 if (task_id == PBS_SQL_TASK) {
242 LOG(VERBOSE) << StringPrintf("PBS SQL lowest priority task");
243 policy = SCHED_NORMAL;
244 } else
245 #endif
246 {
247 policy = SCHED_RR;
248 param.sched_priority = 30 - task_id - 2;
249 }
250 pthread_setschedparam(gki_cb.os.thread_id[task_id], policy, ¶m);
251 }
252
253 LOG(VERBOSE) << StringPrintf("Leaving GKI_create_task %p %d %lx %s %p %d",
254 task_entry, task_id, gki_cb.os.thread_id[task_id],
255 taskname, stack, stacksize);
256
257 return (GKI_SUCCESS);
258 }
259
260 /*******************************************************************************
261 **
262 ** Function GKI_shutdown
263 **
264 ** Description shutdowns the GKI tasks/threads in from max task id to 0 and
265 ** frees pthread resources!
266 ** IMPORTANT: in case of join method, GKI_shutdown must be
267 ** called outside a GKI thread context!
268 **
269 ** Returns void
270 **
271 *******************************************************************************/
GKI_shutdown(void)272 void GKI_shutdown(void) {
273 uint8_t task_id;
274 volatile int* p_run_cond = &gki_cb.os.no_timer_suspend;
275 int oldCOnd = 0;
276 #if (FALSE == GKI_PTHREAD_JOINABLE)
277 int i = 0;
278 #else
279 int result;
280 #endif
281
282 /* release threads and set as TASK_DEAD. going from low to high priority fixes
283 * GKI_exception problem due to btu->hci sleep request events */
284 for (task_id = GKI_MAX_TASKS; task_id > 0; task_id--) {
285 if (gki_cb.com.OSRdyTbl[task_id - 1] != TASK_DEAD) {
286 /* paranoi settings, make sure that we do not execute any mailbox events
287 */
288 gki_cb.com.OSWaitEvt[task_id - 1] &=
289 ~(TASK_MBOX_0_EVT_MASK | TASK_MBOX_1_EVT_MASK | TASK_MBOX_2_EVT_MASK |
290 TASK_MBOX_3_EVT_MASK);
291 GKI_send_event(task_id - 1, EVENT_MASK(GKI_SHUTDOWN_EVT));
292
293 if (((task_id - 1) == BTU_TASK)) {
294 gki_cb.com.system_tick_running = false;
295 *p_run_cond = GKI_TIMER_TICK_EXIT_COND; /* stop system tick */
296 }
297 #if (FALSE == GKI_PTHREAD_JOINABLE)
298 i = 0;
299
300 while ((gki_cb.com.OSWaitEvt[task_id - 1] != 0) && (++i < 10))
301 usleep(100 * 1000);
302 #else
303 /* Skip BTU_TASK due to BTU_TASK is used for GKI_run() and it terminates
304 * after GKI_shutdown().
305 */
306 if ((task_id - 1) != BTU_TASK) {
307 /* wait for proper Arnold Schwarzenegger task state */
308 result = pthread_join(gki_cb.os.thread_id[task_id - 1], NULL);
309 if (result < 0) {
310 LOG(VERBOSE) << StringPrintf("FAILED: result: %d", result);
311 }
312 }
313 #endif
314 LOG(VERBOSE) << StringPrintf("task %s dead",
315 gki_cb.com.OSTName[task_id - 1]);
316 GKI_exit_task(task_id - 1);
317 }
318 }
319
320 /* Destroy mutex and condition variable objects */
321 pthread_mutex_destroy(&gki_cb.os.GKI_mutex);
322 /* pthread_mutex_destroy(&GKI_sched_mutex); */
323 /* pthread_mutex_destroy(&thread_delay_mutex);
324 pthread_cond_destroy (&thread_delay_cond); */
325 #if (FALSE == GKI_PTHREAD_JOINABLE)
326 i = 0;
327 #endif
328
329 #ifdef NO_GKI_RUN_RETURN
330 shutdown_timer = 1;
331 #endif
332 oldCOnd = *p_run_cond;
333 *p_run_cond = GKI_TIMER_TICK_EXIT_COND;
334 if (oldCOnd == GKI_TIMER_TICK_STOP_COND ||
335 oldCOnd == GKI_TIMER_TICK_EXIT_COND)
336 pthread_cond_signal(&gki_cb.os.gki_timer_cond);
337 }
338
339 /*******************************************************************************
340 **
341 ** Function gki_system_tick_start_stop_cback
342 **
343 ** Description This function starts or stops timer
344 **
345 ** Parameters: start: TRUE start system tick (again), FALSE stop
346 **
347 ** Returns void
348 **
349 ******************************************************************************/
gki_system_tick_start_stop_cback(bool start)350 void gki_system_tick_start_stop_cback(bool start) {
351 tGKI_OS* p_os = &gki_cb.os;
352 volatile int* p_run_cond = &p_os->no_timer_suspend;
353 if (start == false) {
354 /* this can lead to a race condition. however as we only read this variable
355 * in the timer loop
356 * we should be fine with this approach. otherwise uncomment below mutexes.
357 */
358 /* GKI_disable(); */
359 *p_run_cond = GKI_TIMER_TICK_STOP_COND;
360 /* GKI_enable(); */
361 } else {
362 /* restart GKI_timer_update() loop */
363 *p_run_cond = GKI_TIMER_TICK_RUN_COND;
364 pthread_mutex_lock(&p_os->gki_timer_mutex);
365 pthread_cond_signal(&p_os->gki_timer_cond);
366 pthread_mutex_unlock(&p_os->gki_timer_mutex);
367 }
368 }
369
370 /*******************************************************************************
371 **
372 ** Function timer_thread
373 **
374 ** Description Timer thread
375 **
376 ** Parameters: id - (input) timer ID
377 **
378 ** Returns void
379 **
380 *******************************************************************************/
381 #ifdef NO_GKI_RUN_RETURN
timer_thread(signed long id)382 void timer_thread(signed long id) {
383 LOG(VERBOSE) << StringPrintf("%s enter", __func__);
384 struct timespec delay;
385 int timeout = 1000; /* 10 ms per system tick */
386 int err;
387
388 while (!shutdown_timer) {
389 delay.tv_sec = timeout / 1000;
390 delay.tv_nsec = 1000 * 1000 * (timeout % 1000);
391
392 /* [u]sleep can't be used because it uses SIGALRM */
393
394 do {
395 err = nanosleep(&delay, &delay);
396 } while (err < 0 && errno == EINTR);
397
398 GKI_timer_update(1);
399 }
400 LOG(ERROR) << StringPrintf("%s exit", __func__);
401 return;
402 }
403 #endif
404
405 /*******************************************************************************
406 **
407 ** Function GKI_run
408 **
409 ** Description This function runs a task
410 **
411 ** Parameters: p_task_id - (input) pointer to task id
412 **
413 ** Returns void
414 **
415 ** NOTE This function is only needed for operating systems where
416 ** starting a task is a 2-step process. Most OS's do it in
417 ** one step, If your OS does it in one step, this function
418 ** should be empty.
419 *******************************************************************************/
GKI_run(void * p_task_id)420 void GKI_run(__attribute__((unused)) void* p_task_id) {
421 LOG(VERBOSE) << StringPrintf("%s enter", __func__);
422 struct timespec delay;
423 int err = 0;
424 volatile int* p_run_cond = &gki_cb.os.no_timer_suspend;
425
426 #ifndef GKI_NO_TICK_STOP
427 /* register start stop function which disable timer loop in GKI_run() when no
428 * timers are
429 * in any GKI/BTA/BTU this should save power when BTLD is idle! */
430 GKI_timer_queue_register_callback(gki_system_tick_start_stop_cback);
431 LOG(VERBOSE) << StringPrintf("Start/Stop GKI_timer_update_registered!");
432 #endif
433
434 #ifdef NO_GKI_RUN_RETURN
435 LOG(VERBOSE) << StringPrintf("GKI_run == NO_GKI_RUN_RETURN");
436 pthread_attr_t timer_attr;
437
438 shutdown_timer = 0;
439
440 pthread_attr_init(&timer_attr);
441 pthread_attr_setdetachstate(&timer_attr, PTHREAD_CREATE_DETACHED);
442 if (pthread_create(&timer_thread_id, &timer_attr, timer_thread, NULL) != 0) {
443 LOG(VERBOSE) << StringPrintf(
444 "GKI_run: pthread_create failed to create timer_thread!");
445 return GKI_FAILURE;
446 }
447 #else
448 LOG(VERBOSE) << StringPrintf("GKI_run, run_cond(%p)=%d ", p_run_cond,
449 *p_run_cond);
450 for (; GKI_TIMER_TICK_EXIT_COND != *p_run_cond;) {
451 do {
452 /* adjust hear bit tick in btld by changning TICKS_PER_SEC!!!!! this
453 * formula works only for
454 * 1-1000ms heart beat units! */
455 delay.tv_sec = LINUX_SEC / 1000;
456 delay.tv_nsec = 1000 * 1000 * (LINUX_SEC % 1000);
457
458 /* [u]sleep can't be used because it uses SIGALRM */
459 do {
460 err = nanosleep(&delay, &delay);
461 } while (err < 0 && errno == EINTR);
462
463 if (GKI_TIMER_TICK_RUN_COND != *p_run_cond) break; // GKI has shutdown
464
465 /* the unit should be alsways 1 (1 tick). only if you vary for some reason
466 * heart beat tick
467 * e.g. power saving you may want to provide more ticks
468 */
469 GKI_timer_update(1);
470 } while (GKI_TIMER_TICK_RUN_COND == *p_run_cond);
471
472 /* currently on reason to exit above loop is no_timer_suspend ==
473 * GKI_TIMER_TICK_STOP_COND
474 * block timer main thread till re-armed by */
475 #ifdef GKI_TICK_TIMER_DEBUG
476 LOG(VERBOSE) << StringPrintf(">>> SUSPENDED");
477 #endif
478 if (GKI_TIMER_TICK_EXIT_COND != *p_run_cond) {
479 pthread_mutex_lock(&gki_cb.os.gki_timer_mutex);
480 pthread_cond_wait(&gki_cb.os.gki_timer_cond, &gki_cb.os.gki_timer_mutex);
481 pthread_mutex_unlock(&gki_cb.os.gki_timer_mutex);
482 }
483 /* potentially we need to adjust os gki_cb.com.OSTicks */
484
485 #ifdef GKI_TICK_TIMER_DEBUG
486 LOG(VERBOSE) << StringPrintf(">>> RESTARTED run_cond: %d", *p_run_cond);
487 #endif
488 } /* for */
489 #endif
490 gki_cb.com.OSWaitEvt[BTU_TASK] = 0;
491 LOG(VERBOSE) << StringPrintf("%s exit", __func__);
492 }
493
494 /*******************************************************************************
495 **
496 ** Function GKI_stop
497 **
498 ** Description This function is called to stop
499 ** the tasks and timers when the system is being stopped
500 **
501 ** Returns void
502 **
503 ** NOTE This function is NOT called by the Widcomm stack and
504 ** profiles. If you want to use it in your own implementation,
505 ** put specific code here.
506 **
507 *******************************************************************************/
GKI_stop(void)508 void GKI_stop(void) {
509 uint8_t task_id;
510
511 /* gki_queue_timer_cback(FALSE); */
512 /* TODO - add code here if needed*/
513
514 for (task_id = 0; task_id < GKI_MAX_TASKS; task_id++) {
515 if (gki_cb.com.OSRdyTbl[task_id] != TASK_DEAD) {
516 GKI_exit_task(task_id);
517 }
518 }
519 }
520
521 /*******************************************************************************
522 **
523 ** Function GKI_wait
524 **
525 ** Description This function is called by tasks to wait for a specific
526 ** event or set of events. The task may specify the duration
527 ** that it wants to wait for, or 0 if infinite.
528 **
529 ** Parameters: flag - (input) the event or set of events to wait for
530 ** timeout - (input) the duration that the task wants to wait
531 ** for the specific events (in system ticks)
532 **
533 **
534 ** Returns the event mask of received events or zero if timeout
535 **
536 *******************************************************************************/
GKI_wait(uint16_t flag,uint32_t timeout)537 uint16_t GKI_wait(uint16_t flag, uint32_t timeout) {
538 uint16_t evt;
539 uint8_t rtask;
540 struct timespec abstime = {0, 0};
541 int sec;
542 int nano_sec;
543
544 rtask = GKI_get_taskid();
545 if (rtask >= GKI_MAX_TASKS) {
546 LOG(ERROR) << StringPrintf("%s() Exiting thread; rtask %d >= %d", __func__,
547 rtask, GKI_MAX_TASKS);
548 return EVENT_MASK(GKI_SHUTDOWN_EVT);
549 }
550
551 gki_pthread_info_t* p_pthread_info = &gki_pthread_info[rtask];
552 if (p_pthread_info->pCond != nullptr && p_pthread_info->pMutex != nullptr) {
553 LOG(VERBOSE) << StringPrintf("GKI_wait task=%i, pCond/pMutex = %p/%p", rtask,
554 p_pthread_info->pCond, p_pthread_info->pMutex);
555 pthread_mutex_lock(p_pthread_info->pMutex);
556 pthread_cond_signal(p_pthread_info->pCond);
557 pthread_mutex_unlock(p_pthread_info->pMutex);
558 p_pthread_info->pMutex = nullptr;
559 p_pthread_info->pCond = nullptr;
560 }
561 gki_cb.com.OSWaitForEvt[rtask] = flag;
562
563 /* protect OSWaitEvt[rtask] from modification from an other thread */
564 pthread_mutex_lock(&gki_cb.os.thread_evt_mutex[rtask]);
565
566 #if 0 /* for clean scheduling we probably should always call \
567 pthread_cond_wait() */
568 /* Check if anything in any of the mailboxes. There is a potential race condition where OSTaskQFirst[rtask]
569 has been modified. however this should only result in addtional call to pthread_cond_wait() but as
570 the cond is met, it will exit immediately (depending on schedulling) */
571 if (gki_cb.com.OSTaskQFirst[rtask][0])
572 gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_0_EVT_MASK;
573 if (gki_cb.com.OSTaskQFirst[rtask][1])
574 gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_1_EVT_MASK;
575 if (gki_cb.com.OSTaskQFirst[rtask][2])
576 gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_2_EVT_MASK;
577 if (gki_cb.com.OSTaskQFirst[rtask][3])
578 gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_3_EVT_MASK;
579 #endif
580
581 if (!(gki_cb.com.OSWaitEvt[rtask] & flag)) {
582 if (timeout) {
583 // timeout = GKI_MS_TO_TICKS(timeout); /* convert from
584 // milliseconds to ticks */
585
586 /* get current system time */
587 // clock_gettime(CLOCK_MONOTONIC, &currSysTime);
588 // abstime.tv_sec = currSysTime.time;
589 // abstime.tv_nsec = NANOSEC_PER_MILLISEC *
590 // currSysTime.millitm;
591 clock_gettime(CLOCK_MONOTONIC, &abstime);
592
593 /* add timeout */
594 sec = timeout / 1000;
595 nano_sec = (timeout % 1000) * NANOSEC_PER_MILLISEC;
596 abstime.tv_nsec += nano_sec;
597 if (abstime.tv_nsec > NSEC_PER_SEC) {
598 abstime.tv_sec += (abstime.tv_nsec / NSEC_PER_SEC);
599 abstime.tv_nsec = abstime.tv_nsec % NSEC_PER_SEC;
600 }
601 abstime.tv_sec += sec;
602
603 pthread_cond_timedwait(&gki_cb.os.thread_evt_cond[rtask],
604 &gki_cb.os.thread_evt_mutex[rtask], &abstime);
605
606 } else {
607 pthread_cond_wait(&gki_cb.os.thread_evt_cond[rtask],
608 &gki_cb.os.thread_evt_mutex[rtask]);
609 }
610
611 /* TODO: check, this is probably neither not needed depending on
612 phtread_cond_wait() implmentation,
613 e.g. it looks like it is implemented as a counter in which case multiple
614 cond_signal
615 should NOT be lost! */
616 // we are waking up after waiting for some events, so refresh variables
617 // no need to call GKI_disable() here as we know that we will have some
618 // events as we've been waking up after condition pending or timeout
619 if (gki_cb.com.OSTaskQFirst[rtask][0])
620 gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_0_EVT_MASK;
621 if (gki_cb.com.OSTaskQFirst[rtask][1])
622 gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_1_EVT_MASK;
623 if (gki_cb.com.OSTaskQFirst[rtask][2])
624 gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_2_EVT_MASK;
625 if (gki_cb.com.OSTaskQFirst[rtask][3])
626 gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_3_EVT_MASK;
627
628 if (gki_cb.com.OSWaitEvt[rtask] == EVENT_MASK(GKI_SHUTDOWN_EVT)) {
629 gki_cb.com.OSWaitEvt[rtask] = 0;
630 /* unlock thread_evt_mutex as pthread_cond_wait() does auto lock when cond
631 * is met */
632 pthread_mutex_unlock(&gki_cb.os.thread_evt_mutex[rtask]);
633 LOG(WARNING) << StringPrintf("GKI TASK_DEAD received. exit thread %d...",
634 rtask);
635
636 gki_cb.os.thread_id[rtask] = 0;
637 return (EVENT_MASK(GKI_SHUTDOWN_EVT));
638 }
639 }
640
641 /* Clear the wait for event mask */
642 gki_cb.com.OSWaitForEvt[rtask] = 0;
643
644 /* Return only those bits which user wants... */
645 evt = gki_cb.com.OSWaitEvt[rtask] & flag;
646
647 /* Clear only those bits which user wants... */
648 gki_cb.com.OSWaitEvt[rtask] &= ~flag;
649
650 /* unlock thread_evt_mutex as pthread_cond_wait() does auto lock mutex when
651 * cond is met */
652 pthread_mutex_unlock(&gki_cb.os.thread_evt_mutex[rtask]);
653 return (evt);
654 }
655
656 /*******************************************************************************
657 **
658 ** Function GKI_delay
659 **
660 ** Description This function is called by tasks to sleep unconditionally
661 ** for a specified amount of time. The duration is in
662 ** milliseconds
663 **
664 ** Parameters: timeout - (input) the duration in milliseconds
665 **
666 ** Returns void
667 **
668 *******************************************************************************/
669
GKI_delay(uint32_t timeout)670 void GKI_delay(uint32_t timeout) {
671 uint8_t rtask = GKI_get_taskid();
672 struct timespec delay;
673 int err;
674
675 LOG(VERBOSE) << StringPrintf("GKI_delay %d %d", rtask, timeout);
676
677 delay.tv_sec = timeout / 1000;
678 delay.tv_nsec = 1000 * 1000 * (timeout % 1000);
679
680 /* [u]sleep can't be used because it uses SIGALRM */
681
682 do {
683 err = nanosleep(&delay, &delay);
684 } while (err < 0 && errno == EINTR);
685
686 /* Check if task was killed while sleeping */
687 /* NOTE
688 ** if you do not implement task killing, you do not
689 ** need this check.
690 */
691 if (rtask && gki_cb.com.OSRdyTbl[rtask] == TASK_DEAD) {
692 }
693
694 LOG(VERBOSE) << StringPrintf("GKI_delay %d %d done", rtask, timeout);
695 return;
696 }
697
698 /*******************************************************************************
699 **
700 ** Function GKI_send_event
701 **
702 ** Description This function is called by tasks to send events to other
703 ** tasks. Tasks can also send events to themselves.
704 **
705 ** Parameters: task_id - (input) The id of the task to which the event has
706 ** to be sent
707 ** event - (input) The event that has to be sent
708 **
709 **
710 ** Returns GKI_SUCCESS if all OK, else GKI_FAILURE
711 **
712 *******************************************************************************/
GKI_send_event(uint8_t task_id,uint16_t event)713 uint8_t GKI_send_event(uint8_t task_id, uint16_t event) {
714 /* use efficient coding to avoid pipeline stalls */
715 if (task_id < GKI_MAX_TASKS) {
716 /* protect OSWaitEvt[task_id] from manipulation in GKI_wait() */
717 pthread_mutex_lock(&gki_cb.os.thread_evt_mutex[task_id]);
718
719 /* Set the event bit */
720 gki_cb.com.OSWaitEvt[task_id] |= event;
721
722 pthread_cond_signal(&gki_cb.os.thread_evt_cond[task_id]);
723
724 pthread_mutex_unlock(&gki_cb.os.thread_evt_mutex[task_id]);
725
726 return (GKI_SUCCESS);
727 }
728 return (GKI_FAILURE);
729 }
730
731 /*******************************************************************************
732 **
733 ** Function GKI_isend_event
734 **
735 ** Description This function is called from ISRs to send events to other
736 ** tasks. The only difference between this function and
737 ** GKI_send_event is that this function assumes interrupts are
738 ** already disabled.
739 **
740 ** Parameters: task_id - (input) The destination task Id for the event.
741 ** event - (input) The event flag
742 **
743 ** Returns GKI_SUCCESS if all OK, else GKI_FAILURE
744 **
745 ** NOTE This function is NOT called by the Widcomm stack and
746 ** profiles. If you want to use it in your own implementation,
747 ** put your code here, otherwise you can delete the entire
748 ** body of the function.
749 **
750 *******************************************************************************/
GKI_isend_event(uint8_t task_id,uint16_t event)751 uint8_t GKI_isend_event(uint8_t task_id, uint16_t event) {
752 LOG(VERBOSE) << StringPrintf("GKI_isend_event %d %x", task_id, event);
753 LOG(VERBOSE) << StringPrintf("GKI_isend_event %d %x done", task_id, event);
754 return GKI_send_event(task_id, event);
755 }
756
757 /*******************************************************************************
758 **
759 ** Function GKI_get_taskid
760 **
761 ** Description This function gets the currently running task ID.
762 **
763 ** Returns task ID
764 **
765 ** NOTE The Widcomm upper stack and profiles may run as a single
766 ** task. If you only have one GKI task, then you can hard-code
767 ** this function to return a '1'. Otherwise, you should have
768 ** some OS-specific method to determine the current task.
769 **
770 *******************************************************************************/
GKI_get_taskid(void)771 uint8_t GKI_get_taskid(void) {
772 int i;
773 pthread_t thread_id = pthread_self();
774 for (i = 0; i < GKI_MAX_TASKS; i++) {
775 if (gki_cb.os.thread_id[i] == thread_id) {
776 return (i);
777 }
778 }
779 return (-1);
780 }
781
782 /*******************************************************************************
783 **
784 ** Function GKI_map_taskname
785 **
786 ** Description This function gets the task name of the taskid passed as
787 ** arg. If GKI_MAX_TASKS is passed as arg the currently running
788 ** task name is returned
789 **
790 ** Parameters: task_id - (input) The id of the task whose name is being
791 ** sought. GKI_MAX_TASKS is passed to get the name of the
792 ** currently running task.
793 **
794 ** Returns pointer to task name
795 **
796 ** NOTE this function needs no customization
797 **
798 *******************************************************************************/
GKI_map_taskname(uint8_t task_id)799 int8_t* GKI_map_taskname(uint8_t task_id) {
800 LOG(VERBOSE) << StringPrintf("GKI_map_taskname %d", task_id);
801
802 if (task_id < GKI_MAX_TASKS) {
803 LOG(VERBOSE) << StringPrintf("GKI_map_taskname %d %s done", task_id,
804 gki_cb.com.OSTName[task_id]);
805 return (gki_cb.com.OSTName[task_id]);
806 } else if (task_id == GKI_MAX_TASKS) {
807 return (gki_cb.com.OSTName[GKI_get_taskid()]);
808 } else {
809 return (int8_t*)"BAD";
810 }
811 }
812
813 /*******************************************************************************
814 **
815 ** Function GKI_enable
816 **
817 ** Description This function enables interrupts.
818 **
819 ** Returns void
820 **
821 *******************************************************************************/
GKI_enable(void)822 void GKI_enable(void) {
823 pthread_mutex_unlock(&gki_cb.os.GKI_mutex);
824 /* pthread_mutex_xx is nesting save, no need for this: already_disabled =
825 * 0; */
826 return;
827 }
828
829 /*******************************************************************************
830 **
831 ** Function GKI_disable
832 **
833 ** Description This function disables interrupts.
834 **
835 ** Returns void
836 **
837 *******************************************************************************/
838
GKI_disable(void)839 void GKI_disable(void) {
840 // LOG(VERBOSE) <<
841 // StringPrintf("GKI_disable");
842
843 /* pthread_mutex_xx is nesting save, no need for this: if
844 (!already_disabled) {
845 already_disabled = 1; */
846 pthread_mutex_lock(&gki_cb.os.GKI_mutex);
847 /* } */
848 // LOG(VERBOSE) <<
849 // StringPrintf("Leaving GKI_disable");
850 return;
851 }
852
853 /*******************************************************************************
854 **
855 ** Function GKI_exception
856 **
857 ** Description This function throws an exception.
858 ** This is normally only called for a nonrecoverable error.
859 **
860 ** Parameters: code - (input) The code for the error
861 ** msg - (input) The message that has to be logged
862 **
863 ** Returns void
864 **
865 *******************************************************************************/
866
GKI_exception(uint16_t code,std::string msg)867 void GKI_exception(uint16_t code, std::string msg) {
868 uint8_t task_id;
869
870 LOG(ERROR) << StringPrintf("Task State Table");
871
872 for (task_id = 0; task_id < GKI_MAX_TASKS; task_id++) {
873 LOG(ERROR) << StringPrintf("TASK ID [%d] task name [%s] state [%d]",
874 task_id, gki_cb.com.OSTName[task_id],
875 gki_cb.com.OSRdyTbl[task_id]);
876 }
877
878 LOG(ERROR) << StringPrintf("%d %s", code, msg.c_str());
879 LOG(ERROR) << StringPrintf(
880 "********************************************************************");
881 LOG(ERROR) << StringPrintf("* %d %s", code, msg.c_str());
882 LOG(ERROR) << StringPrintf(
883 "********************************************************************");
884
885 LOG(ERROR) << StringPrintf("%d %s done", code, msg.c_str());
886
887 return;
888 }
889
890 /*******************************************************************************
891 **
892 ** Function GKI_get_time_stamp
893 **
894 ** Description This function formats the time into a user area
895 **
896 ** Parameters: tbuf - (output) the address to the memory containing the
897 ** formatted time
898 **
899 ** Returns the address of the user area containing the formatted time
900 ** The format of the time is ????
901 **
902 ** NOTE This function is only called by OBEX.
903 **
904 *******************************************************************************/
GKI_get_time_stamp(int8_t * tbuf)905 int8_t* GKI_get_time_stamp(int8_t* tbuf) {
906 uint32_t ms_time;
907 uint32_t s_time;
908 uint32_t m_time;
909 uint32_t h_time;
910 int8_t* p_out = tbuf;
911
912 ms_time = GKI_TICKS_TO_MS(times(nullptr));
913 s_time = ms_time / 100; /* 100 Ticks per second */
914 m_time = s_time / 60;
915 h_time = m_time / 60;
916
917 ms_time -= s_time * 100;
918 s_time -= m_time * 60;
919 m_time -= h_time * 60;
920
921 *p_out++ = (int8_t)((h_time / 10) + '0');
922 *p_out++ = (int8_t)((h_time % 10) + '0');
923 *p_out++ = ':';
924 *p_out++ = (int8_t)((m_time / 10) + '0');
925 *p_out++ = (int8_t)((m_time % 10) + '0');
926 *p_out++ = ':';
927 *p_out++ = (int8_t)((s_time / 10) + '0');
928 *p_out++ = (int8_t)((s_time % 10) + '0');
929 *p_out++ = ':';
930 *p_out++ = (int8_t)((ms_time / 10) + '0');
931 *p_out++ = (int8_t)((ms_time % 10) + '0');
932 *p_out++ = ':';
933 *p_out = 0;
934
935 return (tbuf);
936 }
937
938 /*******************************************************************************
939 **
940 ** Function GKI_register_mempool
941 **
942 ** Description This function registers a specific memory pool.
943 **
944 ** Parameters: p_mem - (input) pointer to the memory pool
945 **
946 ** Returns void
947 **
948 ** NOTE This function is NOT called by the Widcomm stack and
949 ** profiles. If your OS has different memory pools, you
950 ** can tell GKI the pool to use by calling this function.
951 **
952 *******************************************************************************/
GKI_register_mempool(void * p_mem)953 void GKI_register_mempool(void* p_mem) {
954 gki_cb.com.p_user_mempool = p_mem;
955
956 return;
957 }
958
959 /*******************************************************************************
960 **
961 ** Function GKI_os_malloc
962 **
963 ** Description This function allocates memory
964 **
965 ** Parameters: size - (input) The size of the memory that has to be
966 ** allocated
967 **
968 ** Returns the address of the memory allocated, or NULL if failed
969 **
970 ** NOTE This function is called by the Widcomm stack when
971 ** dynamic memory allocation is used.
972 **
973 *******************************************************************************/
GKI_os_malloc(uint32_t size)974 void* GKI_os_malloc(uint32_t size) { return (malloc(size)); }
975
976 /*******************************************************************************
977 **
978 ** Function GKI_os_free
979 **
980 ** Description This function frees memory
981 **
982 ** Parameters: size - (input) The address of the memory that has to be
983 ** freed
984 **
985 ** Returns void
986 **
987 ** NOTE This function is NOT called by the Widcomm stack and
988 ** profiles. It is only called from within GKI if dynamic
989 **
990 *******************************************************************************/
GKI_os_free(void * p_mem)991 void GKI_os_free(void* p_mem) {
992 if (p_mem != nullptr) free(p_mem);
993 return;
994 }
995
996 /*******************************************************************************
997 **
998 ** Function GKI_suspend_task()
999 **
1000 ** Description This function suspends the task specified in the argument.
1001 **
1002 ** Parameters: task_id - (input) the id of the task that has to suspended
1003 **
1004 ** Returns GKI_SUCCESS if all OK, else GKI_FAILURE
1005 **
1006 ** NOTE This function is NOT called by the Widcomm stack and
1007 ** profiles. If you want to implement task suspension
1008 ** capability, put specific code here.
1009 **
1010 *******************************************************************************/
GKI_suspend_task(uint8_t task_id)1011 uint8_t GKI_suspend_task(uint8_t task_id) {
1012 LOG(VERBOSE) << StringPrintf("GKI_suspend_task %d - NOT implemented", task_id);
1013
1014 LOG(VERBOSE) << StringPrintf("GKI_suspend_task %d done", task_id);
1015
1016 return (GKI_SUCCESS);
1017 }
1018
1019 /*******************************************************************************
1020 **
1021 ** Function GKI_resume_task()
1022 **
1023 ** Description This function resumes the task specified in the argument.
1024 **
1025 ** Parameters: task_id - (input) the id of the task that has to resumed
1026 **
1027 ** Returns GKI_SUCCESS if all OK
1028 **
1029 ** NOTE This function is NOT called by the Widcomm stack and
1030 ** profiles. If you want to implement task suspension
1031 ** capability, put specific code here.
1032 **
1033 *******************************************************************************/
GKI_resume_task(uint8_t task_id)1034 uint8_t GKI_resume_task(uint8_t task_id) {
1035 LOG(VERBOSE) << StringPrintf("GKI_resume_task %d - NOT implemented", task_id);
1036
1037 LOG(VERBOSE) << StringPrintf("GKI_resume_task %d done", task_id);
1038
1039 return (GKI_SUCCESS);
1040 }
1041
1042 /*******************************************************************************
1043 **
1044 ** Function GKI_exit_task
1045 **
1046 ** Description This function is called to stop a GKI task.
1047 **
1048 ** Parameters: task_id - (input) the id of the task that has to be stopped
1049 **
1050 ** Returns void
1051 **
1052 ** NOTE This function is NOT called by the Widcomm stack and
1053 ** profiles. If you want to use it in your own implementation,
1054 ** put specific code here to kill a task.
1055 **
1056 *******************************************************************************/
GKI_exit_task(uint8_t task_id)1057 void GKI_exit_task(uint8_t task_id) {
1058 if (task_id >= GKI_MAX_TASKS) {
1059 return;
1060 }
1061 GKI_disable();
1062 if (gki_cb.com.OSRdyTbl[task_id] == TASK_DEAD) {
1063 GKI_enable();
1064 LOG(WARNING) << StringPrintf("%s: task_id %d was already stopped.",
1065 __func__, task_id);
1066 return;
1067 }
1068 gki_cb.com.OSRdyTbl[task_id] = TASK_DEAD;
1069
1070 /* Destroy mutex and condition variable objects */
1071 pthread_mutex_destroy(&gki_cb.os.thread_evt_mutex[task_id]);
1072 pthread_cond_destroy(&gki_cb.os.thread_evt_cond[task_id]);
1073 pthread_mutex_destroy(&gki_cb.os.thread_timeout_mutex[task_id]);
1074 pthread_cond_destroy(&gki_cb.os.thread_timeout_cond[task_id]);
1075
1076 GKI_enable();
1077
1078 // GKI_send_event(task_id, EVENT_MASK(GKI_SHUTDOWN_EVT));
1079
1080 LOG(VERBOSE) << StringPrintf("GKI_exit_task %d done", task_id);
1081 return;
1082 }
1083
1084 /*******************************************************************************
1085 **
1086 ** Function GKI_sched_lock
1087 **
1088 ** Description This function is called by tasks to disable scheduler
1089 ** task context switching.
1090 **
1091 ** Returns void
1092 **
1093 ** NOTE This function is NOT called by the Widcomm stack and
1094 ** profiles. If you want to use it in your own implementation,
1095 ** put code here to tell the OS to disable context switching.
1096 **
1097 *******************************************************************************/
GKI_sched_lock(void)1098 void GKI_sched_lock(void) {
1099 LOG(VERBOSE) << StringPrintf("GKI_sched_lock");
1100 GKI_disable();
1101 return;
1102 }
1103
1104 /*******************************************************************************
1105 **
1106 ** Function GKI_sched_unlock
1107 **
1108 ** Description This function is called by tasks to enable scheduler
1109 ** switching.
1110 **
1111 ** Returns void
1112 **
1113 ** NOTE This function is NOT called by the Widcomm stack and
1114 ** profiles. If you want to use it in your own implementation,
1115 ** put code here to tell the OS to re-enable context switching.
1116 **
1117 *******************************************************************************/
GKI_sched_unlock(void)1118 void GKI_sched_unlock(void) {
1119 LOG(VERBOSE) << StringPrintf("GKI_sched_unlock");
1120 GKI_enable();
1121 }
1122
1123 /*******************************************************************************
1124 **
1125 ** Function GKI_shiftdown
1126 **
1127 ** Description shift memory down (to make space to insert a record)
1128 **
1129 *******************************************************************************/
GKI_shiftdown(uint8_t * p_mem,uint32_t len,uint32_t shift_amount)1130 void GKI_shiftdown(uint8_t* p_mem, uint32_t len, uint32_t shift_amount) {
1131 uint8_t* ps = p_mem + len - 1;
1132 uint8_t* pd = ps + shift_amount;
1133 uint32_t xx;
1134
1135 for (xx = 0; xx < len; xx++) *pd-- = *ps--;
1136 }
1137
1138 /*******************************************************************************
1139 **
1140 ** Function GKI_shiftup
1141 **
1142 ** Description shift memory up (to delete a record)
1143 **
1144 *******************************************************************************/
GKI_shiftup(uint8_t * p_dest,uint8_t * p_src,uint32_t len)1145 void GKI_shiftup(uint8_t* p_dest, uint8_t* p_src, uint32_t len) {
1146 uint8_t* ps = p_src;
1147 uint8_t* pd = p_dest;
1148 uint32_t xx;
1149
1150 for (xx = 0; xx < len; xx++) *pd++ = *ps++;
1151 }
1152