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