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