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