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