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