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