• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright (C) 1999-2012 Broadcom Corporation
4  *  Copyright 2019 NXP
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at:
9  *
10  *  http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  ******************************************************************************/
19 #include <errno.h>
20 #include <malloc.h>
21 #include <pthread.h> /* must be 1st header defined  */
22 
23 #include "uci_log.h"
24 #include "uwb_gki_int.h"
25 
26 /* Temp android logging...move to android tgt config file */
27 
28 #ifndef LINUX_NATIVE
29 #else
30 #define LOGV(format, ...) fprintf(stdout, LOG_TAG format, ##__VA_ARGS__)
31 #define LOGE(format, ...) fprintf(stderr, LOG_TAG format, ##__VA_ARGS__)
32 #define LOGI(format, ...) fprintf(stdout, LOG_TAG format, ##__VA_ARGS__)
33 
34 #define SCHED_NORMAL 0
35 #define SCHED_FIFO 1
36 #define SCHED_RR 2
37 #define SCHED_BATCH 3
38 
39 #endif
40 
41 /* Define the structure that holds the GKI variables
42  */
43 tGKI_CB gki_cb;
44 
45 #define NANOSEC_PER_MILLISEC (1000000)
46 #define NSEC_PER_SEC (1000 * NANOSEC_PER_MILLISEC)
47 
48 /* works only for 1ms to 1000ms heart beat ranges */
49 #define LINUX_SEC (1000 / TICKS_PER_SEC)
50 // #define GKI_TICK_TIMER_DEBUG
51 
52 /* this kind of mutex go into tGKI_OS control block!!!! */
53 /* static pthread_mutex_t GKI_sched_mutex; */
54 /*static pthread_mutex_t thread_delay_mutex;
55 static pthread_cond_t thread_delay_cond;
56 static pthread_mutex_t gki_timer_update_mutex;
57 static pthread_cond_t   gki_timer_update_cond;
58 */
59 
60 typedef struct {
61   uint8_t task_id;         /* GKI task id */
62   TASKPTR task_entry;      /* Task entry function*/
63   uint32_t params;         /* Extra params to pass to task entry function */
64   pthread_cond_t* pCond;   /* for android*/
65   pthread_mutex_t* pMutex; /* for android*/
66 } gki_pthread_info_t;
67 gki_pthread_info_t gki_pthread_info[GKI_MAX_TASKS];
68 
69 /*******************************************************************************
70 **
71 ** Function         phUwb_gki_task_entry
72 **
73 ** Description      entry point of GKI created tasks
74 **
75 ** Returns          void
76 **
77 *******************************************************************************/
phUwb_gki_task_entry(void * params)78 void* phUwb_gki_task_entry(void* params) {
79   pthread_t thread_id = pthread_self();
80   gki_pthread_info_t* p_pthread_info = (gki_pthread_info_t*)params;
81   UCI_TRACE_I(
82       "gki_task_entry task_id=%i, thread_id=%lx/%lx, pCond/pMutex=%p/%p",
83       p_pthread_info->task_id, gki_cb.os.thread_id[p_pthread_info->task_id],
84       pthread_self(), p_pthread_info->pCond, p_pthread_info->pMutex);
85 
86   gki_cb.os.thread_id[p_pthread_info->task_id] = thread_id;
87   /* Call the actual thread entry point */
88   (p_pthread_info->task_entry)(p_pthread_info->params);
89 
90   UCI_TRACE_E("gki_task task_id=%i terminating", p_pthread_info->task_id);
91   gki_cb.os.thread_id[p_pthread_info->task_id] = 0;
92 
93   return NULL;
94 }
95 /* end android */
96 
97 /*******************************************************************************
98 **
99 ** Function         phUwb_GKI_init
100 **
101 ** Description      This function is called once at startup to initialize
102 **                  all the timer structures.
103 **
104 ** Returns          void
105 **
106 *******************************************************************************/
107 
phUwb_GKI_init(void)108 void phUwb_GKI_init(void) {
109   pthread_mutexattr_t attr;
110   tGKI_OS* p_os;
111 
112   memset(&gki_cb, 0, sizeof(gki_cb));
113 
114   phUwb_gki_buffer_init();
115   phUwb_gki_timers_init();
116   gki_cb.com.OSTicks = (uint32_t)times(0);
117 
118   pthread_mutexattr_init(&attr);
119   p_os = &gki_cb.os;
120   pthread_mutex_init(&p_os->GKI_mutex, &attr);
121   /* pthread_mutex_init(&GKI_sched_mutex, NULL); */
122   /* pthread_mutex_init(&thread_delay_mutex, NULL); */ /* used in GKI_delay */
123   /* pthread_cond_init (&thread_delay_cond, NULL); */
124 
125   /* Initialiase GKI_timer_update suspend variables & mutexes to be in running
126    * state.
127    * this works too even if GKI_NO_TICK_STOP is defined in btld.txt */
128   p_os->no_timer_suspend = GKI_TIMER_TICK_RUN_COND;
129   pthread_mutex_init(&p_os->gki_timer_mutex, NULL);
130   pthread_cond_init(&p_os->gki_timer_cond, NULL);
131 }
132 
133 /*******************************************************************************
134 **
135 ** Function         phUwb_GKI_create_task
136 **
137 ** Description      This function is called to create a new OSS task.
138 **
139 ** Parameters:      task_entry  - (input) pointer to the entry function of the
140 **                                        task
141 **                  task_id     - (input) Task id is mapped to priority
142 **                  taskname    - (input) name given to the task
143 **                  stack       - (input) pointer to the top of the stack
144 **                                        (highest memory location)
145 **                  stacksize   - (input) size of the stack allocated for the
146 **                                        task
147 **
148 ** Returns          GKI_SUCCESS if all OK, GKI_FAILURE if any problem
149 **
150 ** NOTE             This function take some parameters that may not be needed
151 **                  by your particular OS. They are here for compatability
152 **                  of the function prototype.
153 **
154 *******************************************************************************/
phUwb_GKI_create_task(TASKPTR task_entry,uint8_t task_id,int8_t * taskname,uint16_t * stack,uint16_t stacksize,void * pCondVar,void * pMutex)155 uint8_t phUwb_GKI_create_task(TASKPTR task_entry, uint8_t task_id,
156                               int8_t* taskname, uint16_t* stack,
157                               uint16_t stacksize, void* pCondVar,
158                               void* pMutex) {
159   struct sched_param param;
160   int policy, ret = 0;
161   pthread_condattr_t attr;
162   pthread_attr_t attr1;
163 
164   pthread_condattr_init(&attr);
165   pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
166   UCI_TRACE_I(
167       "GKI_create_task func=0x%p  id=%d  name=%s  stack=0x%p  stackSize=%d",
168       task_entry, task_id, taskname, stack, stacksize);
169 
170   if (task_id >= GKI_MAX_TASKS) {
171     UCI_TRACE_I("Error! task ID > max task allowed");
172     return (GKI_FAILURE);
173   }
174 
175   gki_cb.com.OSRdyTbl[task_id] = TASK_READY;
176   gki_cb.com.OSTName[task_id] = taskname;
177   gki_cb.com.OSWaitTmr[task_id] = 0;
178   gki_cb.com.OSWaitEvt[task_id] = 0;
179 
180   /* Initialize mutex and condition variable objects for events and timeouts */
181   pthread_mutex_init(&gki_cb.os.thread_evt_mutex[task_id], NULL);
182   pthread_cond_init(&gki_cb.os.thread_evt_cond[task_id], &attr);
183   pthread_mutex_init(&gki_cb.os.thread_timeout_mutex[task_id], NULL);
184   pthread_cond_init(&gki_cb.os.thread_timeout_cond[task_id], &attr);
185 
186   pthread_attr_init(&attr1);
187 /* by default, pthread creates a joinable thread */
188 #if (FALSE == GKI_PTHREAD_JOINABLE)
189   pthread_attr_setdetachstate(&attr1, PTHREAD_CREATE_DETACHED);
190 
191   UCI_TRACE_I("GKI creating task %i, pCond/pMutex=%p/%p", task_id, pCondVar,
192               pMutex);
193 #else
194   UCI_TRACE_I("GKI creating JOINABLE task %i", task_id);
195 #endif
196 
197   /* On Android, the new tasks starts running before
198    * 'gki_cb.os.thread_id[task_id]' is initialized */
199   /* Pass task_id to new task so it can initialize gki_cb.os.thread_id[task_id]
200    * for it calls GKI_wait */
201   gki_pthread_info[task_id].task_id = task_id;
202   gki_pthread_info[task_id].task_entry = task_entry;
203   gki_pthread_info[task_id].params = 0;
204   gki_pthread_info[task_id].pCond = (pthread_cond_t*)pCondVar;
205   gki_pthread_info[task_id].pMutex = (pthread_mutex_t*)pMutex;
206 
207   ret = pthread_create(&gki_cb.os.thread_id[task_id], &attr1,
208                        phUwb_gki_task_entry, &gki_pthread_info[task_id]);
209 
210   if (ret != 0) {
211     UCI_TRACE_I("pthread_create failed(%d), %s!", ret, taskname);
212     return GKI_FAILURE;
213   }
214 
215   if (pthread_getschedparam(gki_cb.os.thread_id[task_id], &policy, &param) ==
216       0) {
217     {
218       policy = SCHED_RR;
219       param.sched_priority = 30 - task_id - 2;
220     }
221     pthread_setschedparam(gki_cb.os.thread_id[task_id], policy, &param);
222   }
223 
224   UCI_TRACE_I("Leaving GKI_create_task %p %d %lx %s %p %d", task_entry, task_id,
225               gki_cb.os.thread_id[task_id], taskname, stack, stacksize);
226 
227   return (GKI_SUCCESS);
228 }
229 
230 /*******************************************************************************
231 **
232 ** Function         phUwb_GKI_shutdown
233 **
234 ** Description      shutdowns the GKI tasks/threads in from max task id to 0 and
235 **                  frees pthread resources!
236 **                  IMPORTANT: in case of join method, GKI_shutdown must be
237 **                  called outside a GKI thread context!
238 **
239 ** Returns          void
240 **
241 *******************************************************************************/
242 #define WAKE_LOCK_ID "brcm_uwba"
243 #define PARTIAL_WAKE_LOCK 1
244 extern "C" int acquire_wake_lock(int lock, const char* id);
245 extern "C" int release_wake_lock(const char* id);
246 
phUwb_GKI_shutdown(void)247 void phUwb_GKI_shutdown(void) {
248   uint8_t task_id;
249   volatile int* p_run_cond = &gki_cb.os.no_timer_suspend;
250   int oldCOnd = 0;
251 #if (FALSE != GKI_PTHREAD_JOINABLE)
252   int result;
253 #endif
254 
255   /* release threads and set as TASK_DEAD. going from low to high priority fixes
256    * GKI_exception problem due to btu->hci sleep request events  */
257   for (task_id = GKI_MAX_TASKS; task_id > 0; task_id--) {
258     if (gki_cb.com.OSRdyTbl[task_id - 1] != TASK_DEAD) {
259       gki_cb.com.OSRdyTbl[task_id - 1] = TASK_DEAD;
260 
261       /* paranoi settings, make sure that we do not execute any mailbox events
262        */
263       gki_cb.com.OSWaitEvt[task_id - 1] &=
264           ~(TASK_MBOX_0_EVT_MASK | TASK_MBOX_1_EVT_MASK | TASK_MBOX_2_EVT_MASK |
265             TASK_MBOX_3_EVT_MASK);
266       phUwb_GKI_send_event(task_id - 1, EVENT_MASK(GKI_SHUTDOWN_EVT));
267 
268 #if (FALSE == GKI_PTHREAD_JOINABLE)
269       int i = 0;
270       if((task_id - 1) != BTU_TASK) {
271         while ((gki_cb.com.OSWaitEvt[task_id - 1] != 0) && (++i < 10))
272           usleep(50 * 1000);
273       } else {
274         usleep(50 * 1000);
275         UCI_TRACE_D("%s: Wait not needed for UWBA_TASK with task id %d", __func__,(task_id - 1));
276       }
277 #else
278       /* wait for proper Arnold Schwarzenegger task state */
279       result = pthread_join(gki_cb.os.thread_id[task_id - 1], NULL);
280       if (result < 0) {
281         UCI_TRACE_I("FAILED: result: %d", result);
282       }
283 #endif
284       UCI_TRACE_I("task %s dead", gki_cb.com.OSTName[task_id - 1]);
285       phUwb_GKI_exit_task(task_id - 1);
286     }
287   }
288 /*    pthread_mutex_destroy(&GKI_sched_mutex); */
289 /*    pthread_mutex_destroy(&thread_delay_mutex);
290  pthread_cond_destroy (&thread_delay_cond); */
291   if (gki_cb.os.gki_timer_wake_lock_on) {
292     UCI_TRACE_I("GKI_shutdown :  release_wake_lock(brcm_btld)");
293     release_wake_lock(WAKE_LOCK_ID);
294     gki_cb.os.gki_timer_wake_lock_on = 0;
295   }
296   oldCOnd = *p_run_cond;
297   *p_run_cond = GKI_TIMER_TICK_EXIT_COND;
298   if (oldCOnd == GKI_TIMER_TICK_STOP_COND)
299     pthread_cond_signal(&gki_cb.os.gki_timer_cond);
300   /* Destroy mutex and condition variable objects */
301   pthread_mutex_destroy(&gki_cb.os.GKI_mutex);
302 }
303 
304 /*******************************************************************************
305  **
306  ** Function        phUwb_GKI_run
307  **
308  ** Description     This function runs a task
309  **
310  ** Parameters:     start: TRUE start system tick (again), FALSE stop
311  **
312  ** Returns         void
313  **
314  ******************************************************************************/
phUwb_gki_system_tick_start_stop_cback(bool start)315 void phUwb_gki_system_tick_start_stop_cback(bool start) {
316   tGKI_OS* p_os = &gki_cb.os;
317   volatile int* p_run_cond = &p_os->no_timer_suspend;
318 #ifdef GKI_TICK_TIMER_DEBUG
319   static volatile int wake_lock_count;
320 #endif
321   if (start == false) {
322     /* this can lead to a race condition. however as we only read this variable
323      * in the timer loop
324      * we should be fine with this approach. otherwise uncomment below mutexes.
325      */
326     /* GKI_disable(); */
327     *p_run_cond = GKI_TIMER_TICK_STOP_COND;
328 /* GKI_enable(); */
329 #ifdef GKI_TICK_TIMER_DEBUG
330     UCI_TRACE_I(">>> STOP wake_lock_count:%d", --wake_lock_count);
331 #endif
332     release_wake_lock(WAKE_LOCK_ID);
333     gki_cb.os.gki_timer_wake_lock_on = 0;
334   } else {
335     /* restart GKI_timer_update() loop */
336     acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
337     gki_cb.os.gki_timer_wake_lock_on = 1;
338     *p_run_cond = GKI_TIMER_TICK_RUN_COND;
339     pthread_mutex_lock(&p_os->gki_timer_mutex);
340     pthread_cond_signal(&p_os->gki_timer_cond);
341     pthread_mutex_unlock(&p_os->gki_timer_mutex);
342 
343 #ifdef GKI_TICK_TIMER_DEBUG
344     UCI_TRACE_I(">>> START wake_lock_count:%d", ++wake_lock_count);
345 #endif
346   }
347 }
348 
349 /*******************************************************************************
350 **
351 ** Function         phUwb_GKI_run
352 **
353 ** Description      This function runs a task
354 **
355 ** Parameters:      p_task_id  - (input) pointer to task id
356 **
357 ** Returns          void
358 **
359 ** NOTE             This function is only needed for operating systems where
360 **                  starting a task is a 2-step process. Most OS's do it in
361 **                  one step, If your OS does it in one step, this function
362 **                  should be empty.
363 *******************************************************************************/
phUwb_GKI_run(void * p_task_id)364 void phUwb_GKI_run(__attribute__((unused)) void* p_task_id) {
365   UCI_TRACE_I("%s enter", __func__);
366   struct timespec delay;
367   int err = 0;
368   volatile int* p_run_cond = &gki_cb.os.no_timer_suspend;
369 
370 #ifndef GKI_NO_TICK_STOP
371   /* register start stop function which disable timer loop in GKI_run() when no
372    * timers are
373    * in any GKI/BTA/BTU this should save power when BTLD is idle! */
374   phUwb_GKI_timer_queue_register_callback(
375       phUwb_gki_system_tick_start_stop_cback);
376   UCI_TRACE_I("Start/Stop GKI_timer_update_registered!");
377 #endif
378   UCI_TRACE_I("GKI_run, run_cond(%p)=%d ", p_run_cond, *p_run_cond);
379   for (; GKI_TIMER_TICK_EXIT_COND != *p_run_cond;) {
380     do {
381       /* adjust hear bit tick in btld by changning TICKS_PER_SEC!!!!! this
382        * formula works only for
383        * 1-1000ms heart beat units! */
384       delay.tv_sec = LINUX_SEC / 1000;
385       delay.tv_nsec = 1000 * 1000 * (LINUX_SEC % 1000);
386 
387       /* [u]sleep can't be used because it uses SIGALRM */
388       do {
389         err = nanosleep(&delay, &delay);
390       } while (err < 0 && errno == EINTR);
391 
392       if (GKI_TIMER_TICK_RUN_COND != *p_run_cond) break;  // GKI has shutdown
393 
394       /* the unit should be alsways 1 (1 tick). only if you vary for some reason
395        * heart beat tick
396        * e.g. power saving you may want to provide more ticks
397        */
398       phUwb_GKI_timer_update(1);
399     } while (GKI_TIMER_TICK_RUN_COND == *p_run_cond);
400 
401 /* currently on reason to exit above loop is no_timer_suspend ==
402  * GKI_TIMER_TICK_STOP_COND
403  * block timer main thread till re-armed by  */
404 #ifdef GKI_TICK_TIMER_DEBUG
405     UCI_TRACE_I(">>> SUSPENDED");
406 #endif
407     if (GKI_TIMER_TICK_EXIT_COND != *p_run_cond) {
408       pthread_mutex_lock(&gki_cb.os.gki_timer_mutex);
409       pthread_cond_wait(&gki_cb.os.gki_timer_cond, &gki_cb.os.gki_timer_mutex);
410       pthread_mutex_unlock(&gki_cb.os.gki_timer_mutex);
411     }
412     /* potentially we need to adjust os gki_cb.com.OSTicks */
413 
414 #ifdef GKI_TICK_TIMER_DEBUG
415     UCI_TRACE_I(">>> RESTARTED run_cond: %d", *p_run_cond);
416 #endif
417   } /* for */
418   UCI_TRACE_I("%s exit", __func__);
419 }
420 
421 /*******************************************************************************
422 **
423 ** Function         phUwb_GKI_wait
424 **
425 ** Description      This function is called by tasks to wait for a specific
426 **                  event or set of events. The task may specify the duration
427 **                  that it wants to wait for, or 0 if infinite.
428 **
429 ** Parameters:      flag -    (input) the event or set of events to wait for
430 **                  timeout - (input) the duration that the task wants to wait
431 **                                    for the specific events (in system ticks)
432 **
433 **
434 ** Returns          the event mask of received events or zero if timeout
435 **
436 *******************************************************************************/
phUwb_GKI_wait(uint16_t flag,uint32_t timeout)437 uint16_t phUwb_GKI_wait(uint16_t flag, uint32_t timeout) {
438   uint16_t evt;
439   uint8_t rtask;
440   struct timespec abstime = {0, 0};
441   int sec;
442   int nano_sec;
443 
444   rtask = phUwb_GKI_get_taskid();
445   if (rtask >= GKI_MAX_TASKS) {
446     UCI_TRACE_E("%s() Exiting thread; rtask %d >= %d", __func__, rtask,
447                 GKI_MAX_TASKS);
448     return EVENT_MASK(GKI_SHUTDOWN_EVT);
449   }
450 
451   gki_pthread_info_t* p_pthread_info = &gki_pthread_info[rtask];
452   if (p_pthread_info->pCond != NULL && p_pthread_info->pMutex != NULL) {
453     int ret;
454     UCI_TRACE_I("GKI_wait task=%i, pCond/pMutex = %p/%p", rtask,
455                 p_pthread_info->pCond, p_pthread_info->pMutex);
456     ret = pthread_mutex_lock(p_pthread_info->pMutex);
457     ret = pthread_cond_signal(p_pthread_info->pCond);
458     ret = pthread_mutex_unlock(p_pthread_info->pMutex);
459     p_pthread_info->pMutex = NULL;
460     p_pthread_info->pCond = NULL;
461   }
462   gki_cb.com.OSWaitForEvt[rtask] = flag;
463 
464   /* protect OSWaitEvt[rtask] from modification from an other thread */
465   pthread_mutex_lock(&gki_cb.os.thread_evt_mutex[rtask]);
466 
467   if (!(gki_cb.com.OSWaitEvt[rtask] & flag)) {
468     if (timeout) {
469       if (clock_gettime(CLOCK_MONOTONIC, &abstime) == -1) {
470         UCI_TRACE_E("phUwb_GKI_wait: fail get time");
471       } else {
472         /* add timeout */
473         sec = timeout / 1000;
474         nano_sec = (timeout % 1000) * NANOSEC_PER_MILLISEC;
475         abstime.tv_nsec += nano_sec;
476         if (abstime.tv_nsec > NSEC_PER_SEC) {
477           abstime.tv_sec += (abstime.tv_nsec / NSEC_PER_SEC);
478           abstime.tv_nsec = abstime.tv_nsec % NSEC_PER_SEC;
479         }
480         abstime.tv_sec += sec;
481       }
482 
483       int waitResult =
484           pthread_cond_timedwait(&gki_cb.os.thread_evt_cond[rtask],
485                                  &gki_cb.os.thread_evt_mutex[rtask], &abstime);
486       if ((waitResult != 0) && (waitResult != ETIMEDOUT))
487         UCI_TRACE_E("phUwb_GKI_wait::wait: fail timed wait; error=0x%X",
488                     waitResult);
489 
490     } else {
491       pthread_cond_wait(&gki_cb.os.thread_evt_cond[rtask],
492                         &gki_cb.os.thread_evt_mutex[rtask]);
493     }
494 
495     /* TODO: check, this is probably neither not needed depending on
496      phtread_cond_wait() implmentation,
497      e.g. it looks like it is implemented as a counter in which case multiple
498      cond_signal
499      should NOT be lost! */
500     // we are waking up after waiting for some events, so refresh variables
501     // no need to call GKI_disable() here as we know that we will have some
502     // events as we've been waking up after condition pending or timeout
503     if (gki_cb.com.OSTaskQFirst[rtask][0])
504       gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_0_EVT_MASK;
505     if (gki_cb.com.OSTaskQFirst[rtask][1])
506       gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_1_EVT_MASK;
507     if (gki_cb.com.OSTaskQFirst[rtask][2])
508       gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_2_EVT_MASK;
509     if (gki_cb.com.OSTaskQFirst[rtask][3])
510       gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_3_EVT_MASK;
511 
512     if (gki_cb.com.OSRdyTbl[rtask] == TASK_DEAD) {
513       gki_cb.com.OSWaitEvt[rtask] = 0;
514       /* unlock thread_evt_mutex as pthread_cond_wait() does auto lock when cond
515        * is met */
516       pthread_mutex_unlock(&gki_cb.os.thread_evt_mutex[rtask]);
517       UCI_TRACE_E("GKI TASK_DEAD received. exit thread %d...", rtask);
518 
519       gki_cb.os.thread_id[rtask] = 0;
520       return (EVENT_MASK(GKI_SHUTDOWN_EVT));
521     }
522   }
523 
524   /* Clear the wait for event mask */
525   gki_cb.com.OSWaitForEvt[rtask] = 0;
526 
527   /* Return only those bits which user wants... */
528   evt = gki_cb.com.OSWaitEvt[rtask] & flag;
529 
530   /* Clear only those bits which user wants... */
531   gki_cb.com.OSWaitEvt[rtask] &= ~flag;
532 
533   /* unlock thread_evt_mutex as pthread_cond_wait() does auto lock mutex when
534    * cond is met */
535   pthread_mutex_unlock(&gki_cb.os.thread_evt_mutex[rtask]);
536   return (evt);
537 }
538 
539 /*******************************************************************************
540 **
541 ** Function         phUwb_GKI_send_event
542 **
543 ** Description      This function is called by tasks to send events to other
544 **                  tasks. Tasks can also send events to themselves.
545 **
546 ** Parameters:      task_id -  (input) The id of the task to which the event has
547 **                                     to be sent
548 **                  event   -  (input) The event that has to be sent
549 **
550 **
551 ** Returns          GKI_SUCCESS if all OK, else GKI_FAILURE
552 **
553 *******************************************************************************/
phUwb_GKI_send_event(uint8_t task_id,uint16_t event)554 uint8_t phUwb_GKI_send_event(uint8_t task_id, uint16_t event) {
555   /* use efficient coding to avoid pipeline stalls */
556   if (task_id < GKI_MAX_TASKS) {
557     /* protect OSWaitEvt[task_id] from manipulation in GKI_wait() */
558     pthread_mutex_lock(&gki_cb.os.thread_evt_mutex[task_id]);
559 
560     /* Set the event bit */
561     gki_cb.com.OSWaitEvt[task_id] |= event;
562 
563     pthread_cond_signal(&gki_cb.os.thread_evt_cond[task_id]);
564 
565     pthread_mutex_unlock(&gki_cb.os.thread_evt_mutex[task_id]);
566 
567     return (GKI_SUCCESS);
568   }
569   return (GKI_FAILURE);
570 }
571 
572 /*******************************************************************************
573 **
574 ** Function         phUwb_GKI_isend_event
575 **
576 ** Description      This function is called from ISRs to send events to other
577 **                  tasks. The only difference between this function and
578 **                  GKI_send_event is that this function assumes interrupts are
579 **                  already disabled.
580 **
581 ** Parameters:      task_id -  (input) The destination task Id for the event.
582 **                  event   -  (input) The event flag
583 **
584 ** Returns          GKI_SUCCESS if all OK, else GKI_FAILURE
585 **
586 ** NOTE             This function is NOT called by the Widcomm stack and
587 **                  profiles. If you want to use it in your own implementation,
588 **                  put your code here, otherwise you can delete the entire
589 **                  body of the function.
590 **
591 *******************************************************************************/
phUwb_GKI_isend_event(uint8_t task_id,uint16_t event)592 uint8_t phUwb_GKI_isend_event(uint8_t task_id, uint16_t event) {
593   UCI_TRACE_I("GKI_isend_event %d %x", task_id, event);
594   UCI_TRACE_I("GKI_isend_event %d %x done", task_id, event);
595   return phUwb_GKI_send_event(task_id, event);
596 }
597 
598 /*******************************************************************************
599 **
600 ** Function         phUwb_GKI_get_taskid
601 **
602 ** Description      This function gets the currently running task ID.
603 **
604 ** Returns          task ID
605 **
606 ** NOTE             The Widcomm upper stack and profiles may run as a single
607 **                  task. If you only have one GKI task, then you can hard-code
608 **                  this function to return a '1'. Otherwise, you should have
609 **                  some OS-specific method to determine the current task.
610 **
611 *******************************************************************************/
phUwb_GKI_get_taskid(void)612 uint8_t phUwb_GKI_get_taskid(void) {
613   uint8_t i;
614   pthread_t thread_id = pthread_self();
615   for (i = 0; i < GKI_MAX_TASKS; i++) {
616     if (gki_cb.os.thread_id[i] == thread_id) {
617       return (i);
618     }
619   }
620   return (0xFF);
621 }
622 
623 /*******************************************************************************
624 **
625 ** Function         phUwb_GKI_enable
626 **
627 ** Description      This function enables interrupts.
628 **
629 ** Returns          void
630 **
631 *******************************************************************************/
phUwb_GKI_enable(void)632 void phUwb_GKI_enable(void) {
633   pthread_mutex_unlock(&gki_cb.os.GKI_mutex);
634   /*     pthread_mutex_xx is nesting save, no need for this: already_disabled =
635    * 0; */
636   return;
637 }
638 
639 /*******************************************************************************
640 **
641 ** Function         phUwb_GKI_disable
642 **
643 ** Description      This function disables interrupts.
644 **
645 ** Returns          void
646 **
647 *******************************************************************************/
648 
phUwb_GKI_disable(void)649 void phUwb_GKI_disable(void) {
650   UCI_TRACE_I("GKI_disable");
651   pthread_mutex_lock(&gki_cb.os.GKI_mutex);
652   UCI_TRACE_I("Leaving GKI_disable");
653   return;
654 }
655 
656 /*******************************************************************************
657 **
658 ** Function         phUwb_GKI_exception
659 **
660 ** Description      This function throws an exception.
661 **                  This is normally only called for a nonrecoverable error.
662 **
663 ** Parameters:      code    -  (input) The code for the error
664 **                  msg     -  (input) The message that has to be logged
665 **
666 ** Returns          void
667 **
668 *******************************************************************************/
669 
phUwb_GKI_exception(uint16_t code,std::string msg)670 void phUwb_GKI_exception(uint16_t code, std::string msg) {
671   uint8_t task_id;
672 
673   UCI_TRACE_E("Task State Table");
674 
675   for (task_id = 0; task_id < GKI_MAX_TASKS; task_id++) {
676     UCI_TRACE_E("TASK ID [%d] task name [%s] state [%d]", task_id,
677                 gki_cb.com.OSTName[task_id], gki_cb.com.OSRdyTbl[task_id]);
678   }
679 
680   UCI_TRACE_E("%d %s", code, msg.c_str());
681   UCI_TRACE_E(
682       "********************************************************************");
683   UCI_TRACE_E("* %d %s", code, msg.c_str());
684   UCI_TRACE_E(
685       "********************************************************************");
686 
687   UCI_TRACE_E("%d %s done", code, msg.c_str());
688 
689   return;
690 }
691 
692 /*******************************************************************************
693 **
694 ** Function         phUwb_GKI_os_malloc
695 **
696 ** Description      This function allocates memory
697 **
698 ** Parameters:      size -  (input) The size of the memory that has to be
699 **                  allocated
700 **
701 ** Returns          the address of the memory allocated, or NULL if failed
702 **
703 ** NOTE             This function is called by the Widcomm stack when
704 **                  dynamic memory allocation is used.
705 **
706 *******************************************************************************/
phUwb_GKI_os_malloc(uint32_t size)707 void* phUwb_GKI_os_malloc(uint32_t size) { return (malloc(size)); }
708 
709 /*******************************************************************************
710 **
711 ** Function         phUwb_GKI_os_free
712 **
713 ** Description      This function frees memory
714 **
715 ** Parameters:      size -  (input) The address of the memory that has to be
716 **                  freed
717 **
718 ** Returns          void
719 **
720 ** NOTE             This function is NOT called by the Widcomm stack and
721 **                  profiles. It is only called from within GKI if dynamic
722 **
723 *******************************************************************************/
phUwb_GKI_os_free(void * p_mem)724 void phUwb_GKI_os_free(void* p_mem) {
725   if (p_mem != NULL) free(p_mem);
726   return;
727 }
728 
729 /*******************************************************************************
730 **
731 ** Function         phUwb_GKI_exit_task
732 **
733 ** Description      This function is called to stop a GKI task.
734 **
735 ** Parameters:      task_id  - (input) the id of the task that has to be stopped
736 **
737 ** Returns          void
738 **
739 ** NOTE             This function is NOT called by the Widcomm stack and
740 **                  profiles. If you want to use it in your own implementation,
741 **                  put specific code here to kill a task.
742 **
743 *******************************************************************************/
phUwb_GKI_exit_task(uint8_t task_id)744 void phUwb_GKI_exit_task(uint8_t task_id) {
745   if (task_id >= GKI_MAX_TASKS) {
746     return;
747   }
748   phUwb_GKI_disable();
749   gki_cb.com.OSRdyTbl[task_id] = TASK_DEAD;
750 
751   /* Destroy mutex and condition variable objects */
752   pthread_mutex_destroy(&gki_cb.os.thread_evt_mutex[task_id]);
753   pthread_cond_destroy(&gki_cb.os.thread_evt_cond[task_id]);
754   pthread_mutex_destroy(&gki_cb.os.thread_timeout_mutex[task_id]);
755   pthread_cond_destroy(&gki_cb.os.thread_timeout_cond[task_id]);
756 
757   phUwb_GKI_enable();
758 
759   UCI_TRACE_I("GKI_exit_task %d done", task_id);
760   return;
761 }
762