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