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