gki_ulinux.c revision cf7f6a154aed48659260d391994dc59151be937b
1/******************************************************************************
2 *
3 *  Copyright (C) 2009-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
19/****************************************************************************
20**
21**  Name        gki_linux_pthreads.c
22**
23**  Function    pthreads version of Linux GKI. This version is used for
24**              settop projects that already use pthreads and not pth.
25**
26*****************************************************************************/
27
28#include <assert.h>
29#include <sys/times.h>
30
31#include "gki_int.h"
32#include "bt_utils.h"
33
34#define LOG_TAG "GKI_LINUX"
35
36#include <utils/Log.h>
37#include <hardware/bluetooth.h>
38
39/*****************************************************************************
40**  Constants & Macros
41******************************************************************************/
42
43#define SCHED_NORMAL 0
44#define SCHED_FIFO 1
45#define SCHED_RR 2
46#define SCHED_BATCH 3
47
48#define NANOSEC_PER_MILLISEC    1000000
49#define NSEC_PER_SEC            (1000 * NANOSEC_PER_MILLISEC)
50#define USEC_PER_SEC            1000000
51#define NSEC_PER_USEC           1000
52
53#define WAKE_LOCK_ID "bluedroid_timer"
54
55#if GKI_DYNAMIC_MEMORY == FALSE
56tGKI_CB   gki_cb;
57#endif
58
59#ifndef GKI_SHUTDOWN_EVT
60#define GKI_SHUTDOWN_EVT    APPL_EVT_7
61#endif
62
63/*****************************************************************************
64**  Local type definitions
65******************************************************************************/
66
67typedef struct
68{
69    UINT8 task_id;          /* GKI task id */
70    TASKPTR task_entry;     /* Task entry function*/
71    UINT32 params;          /* Extra params to pass to task entry function */
72} gki_pthread_info_t;
73
74// Alarm service structure used to pass up via JNI to the bluetooth
75// app in order to create a wakeable Alarm.
76typedef struct
77{
78    UINT32 ticks_scheduled;
79    UINT64 timer_started_us;
80    UINT64 timer_last_expired_us;
81    bool wakelock;
82} alarm_service_t;
83
84/*****************************************************************************
85**  Static variables
86******************************************************************************/
87
88gki_pthread_info_t gki_pthread_info[GKI_MAX_TASKS];
89
90// Only a single alarm is used to wake bluedroid.
91// NOTE: Must be manipulated with the GKI_disable() lock held.
92static alarm_service_t alarm_service;
93
94static timer_t posix_timer;
95static bool timer_created;
96
97
98// If the next wakeup time is less than this threshold, we should acquire
99// a wakelock instead of setting a wake alarm so we're not bouncing in
100// and out of suspend frequently.
101static const uint32_t TIMER_INTERVAL_FOR_WAKELOCK_IN_MS = 100;
102
103/*****************************************************************************
104**  Externs
105******************************************************************************/
106
107extern bt_os_callouts_t *bt_os_callouts;
108
109/*****************************************************************************
110**  Functions
111******************************************************************************/
112
113static UINT64 now_us()
114{
115    struct timespec ts_now;
116    clock_gettime(CLOCK_BOOTTIME, &ts_now);
117    return ((UINT64)ts_now.tv_sec * USEC_PER_SEC) + ((UINT64)ts_now.tv_nsec / NSEC_PER_USEC);
118}
119
120static bool set_nonwake_alarm(UINT64 delay_millis)
121{
122    if (!timer_created)
123    {
124        ALOGE("%s timer is not available, not setting timer for %llums", __func__, delay_millis);
125        return false;
126    }
127
128    const UINT64 now = now_us();
129    alarm_service.timer_started_us = now;
130
131    UINT64 prev_timer_delay = 0;
132    if (alarm_service.timer_last_expired_us)
133        prev_timer_delay = now - alarm_service.timer_last_expired_us;
134
135    UINT64 delay_micros = delay_millis * 1000;
136    if (delay_micros > prev_timer_delay)
137        delay_micros -= prev_timer_delay;
138    else
139        delay_micros = 1;
140
141    struct itimerspec new_value;
142    memset(&new_value, 0, sizeof(new_value));
143    new_value.it_value.tv_sec = (delay_micros / USEC_PER_SEC);
144    new_value.it_value.tv_nsec = (delay_micros % USEC_PER_SEC) * NSEC_PER_USEC;
145    if (timer_settime(posix_timer, 0, &new_value, NULL) == -1)
146    {
147        ALOGE("%s unable to set timer: %s", __func__, strerror(errno));
148        return false;
149    }
150    return true;
151}
152
153/** Callback from Java thread after alarm from AlarmService fires. */
154static void bt_alarm_cb(void *data)
155{
156    alarm_service.timer_last_expired_us = now_us();
157    UINT32 ticks_taken = GKI_MS_TO_TICKS((alarm_service.timer_last_expired_us
158                                        - alarm_service.timer_started_us) / 1000);
159
160    GKI_timer_update(ticks_taken > alarm_service.ticks_scheduled
161                   ? ticks_taken : alarm_service.ticks_scheduled);
162}
163
164/** NOTE: This is only called on init and may be called without the GKI_disable()
165  * lock held.
166  */
167static void alarm_service_init()
168{
169    alarm_service.ticks_scheduled = 0;
170    alarm_service.timer_started_us = 0;
171    alarm_service.timer_last_expired_us = 0;
172    alarm_service.wakelock = FALSE;
173    raise_priority_a2dp(TASK_JAVA_ALARM);
174}
175
176/** Requests an alarm from AlarmService to fire when the next
177  * timer in the timer queue is set to expire. Only takes a wakelock
178  * if the timer tick expiration is a short interval in the future
179  * and releases the wakelock if the timer is a longer interval
180  * or if there are no more timers in the queue.
181  *
182  * NOTE: Must be called with GKI_disable() lock held.
183  */
184void alarm_service_reschedule()
185{
186    int32_t ticks_till_next_exp = GKI_ready_to_sleep();
187
188    assert(ticks_till_next_exp >= 0);
189    alarm_service.ticks_scheduled = ticks_till_next_exp;
190
191    // No more timers remaining. Release wakelock if we're holding one.
192    if (ticks_till_next_exp == 0)
193    {
194        alarm_service.timer_last_expired_us = 0;
195        alarm_service.timer_started_us = 0;
196        if (alarm_service.wakelock)
197        {
198            ALOGV("%s releasing wake lock.", __func__);
199            alarm_service.wakelock = false;
200            int rc = bt_os_callouts->release_wake_lock(WAKE_LOCK_ID);
201            if (rc != BT_STATUS_SUCCESS)
202            {
203                ALOGE("%s unable to release wake lock with no timers: %d", __func__, rc);
204            }
205        }
206        ALOGV("%s no more alarms.", __func__);
207        return;
208    }
209
210    UINT64 ticks_in_millis = GKI_TICKS_TO_MS(ticks_till_next_exp);
211    if (ticks_in_millis <= TIMER_INTERVAL_FOR_WAKELOCK_IN_MS)
212    {
213        // The next deadline is close, just take a wakelock and set a regular (non-wake) timer.
214        if (!alarm_service.wakelock)
215        {
216            int rc = bt_os_callouts->acquire_wake_lock(WAKE_LOCK_ID);
217            if (rc != BT_STATUS_SUCCESS)
218            {
219                ALOGE("%s unable to acquire wake lock: %d", __func__, rc);
220                return;
221            }
222            alarm_service.wakelock = true;
223        }
224        ALOGV("%s acquired wake lock, setting short alarm (%lldms).", __func__, ticks_in_millis);
225
226        if (!set_nonwake_alarm(ticks_in_millis))
227        {
228            ALOGE("%s unable to set short alarm.", __func__);
229        }
230    } else {
231        // The deadline is far away, set a wake alarm and release wakelock if we're holding it.
232        alarm_service.timer_started_us = now_us();
233        alarm_service.timer_last_expired_us = 0;
234        if (!bt_os_callouts->set_wake_alarm(ticks_in_millis, true, bt_alarm_cb, &alarm_service))
235        {
236            ALOGE("%s unable to set long alarm, releasing wake lock anyway.", __func__);
237        } else {
238            ALOGV("%s set long alarm (%lldms), releasing wake lock.", __func__, ticks_in_millis);
239        }
240
241        if (alarm_service.wakelock)
242        {
243            alarm_service.wakelock = false;
244            bt_os_callouts->release_wake_lock(WAKE_LOCK_ID);
245        }
246    }
247}
248
249
250/*****************************************************************************
251**
252** Function        gki_task_entry
253**
254** Description     GKI pthread callback
255**
256** Returns         void
257**
258*******************************************************************************/
259static void gki_task_entry(UINT32 params)
260{
261    gki_pthread_info_t *p_pthread_info = (gki_pthread_info_t *)params;
262    gki_cb.os.thread_id[p_pthread_info->task_id] = pthread_self();
263
264    prctl(PR_SET_NAME, (unsigned long)gki_cb.com.OSTName[p_pthread_info->task_id], 0, 0, 0);
265
266    ALOGI("gki_task_entry task_id=%i [%s] starting\n", p_pthread_info->task_id,
267                gki_cb.com.OSTName[p_pthread_info->task_id]);
268
269    /* Call the actual thread entry point */
270    (p_pthread_info->task_entry)(p_pthread_info->params);
271
272    ALOGI("gki_task task_id=%i [%s] terminating\n", p_pthread_info->task_id,
273                gki_cb.com.OSTName[p_pthread_info->task_id]);
274
275    pthread_exit(0);    /* GKI tasks have no return value */
276}
277
278/*******************************************************************************
279**
280** Function         GKI_init
281**
282** Description      This function is called once at startup to initialize
283**                  all the timer structures.
284**
285** Returns          void
286**
287*******************************************************************************/
288
289void GKI_init(void)
290{
291    pthread_mutexattr_t attr;
292    tGKI_OS             *p_os;
293
294    memset (&gki_cb, 0, sizeof (gki_cb));
295
296    gki_buffer_init();
297    gki_timers_init();
298    alarm_service_init();
299
300    gki_cb.com.OSTicks = (UINT32) times(0);
301
302    pthread_mutexattr_init(&attr);
303
304#ifndef __CYGWIN__
305    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
306#endif
307    p_os = &gki_cb.os;
308    pthread_mutex_init(&p_os->GKI_mutex, &attr);
309    /* pthread_mutex_init(&GKI_sched_mutex, NULL); */
310#if (GKI_DEBUG == TRUE)
311    pthread_mutex_init(&p_os->GKI_trace_mutex, NULL);
312#endif
313    /* pthread_mutex_init(&thread_delay_mutex, NULL); */  /* used in GKI_delay */
314    /* pthread_cond_init (&thread_delay_cond, NULL); */
315
316    struct sigevent sigevent;
317    memset(&sigevent, 0, sizeof(sigevent));
318    sigevent.sigev_notify = SIGEV_THREAD;
319    sigevent.sigev_notify_function = (void (*)(union sigval))bt_alarm_cb;
320    sigevent.sigev_value.sival_ptr = NULL;
321    if (timer_create(CLOCK_REALTIME, &sigevent, &posix_timer) == -1) {
322        ALOGE("%s unable to create POSIX timer: %s", __func__, strerror(errno));
323        timer_created = false;
324    } else {
325        timer_created = true;
326    }
327}
328
329
330/*******************************************************************************
331**
332** Function         GKI_get_os_tick_count
333**
334** Description      This function is called to retrieve the native OS system tick.
335**
336** Returns          Tick count of native OS.
337**
338*******************************************************************************/
339UINT32 GKI_get_os_tick_count(void)
340{
341    return gki_cb.com.OSTicks;
342}
343
344/*******************************************************************************
345**
346** Function         GKI_create_task
347**
348** Description      This function is called to create a new OSS task.
349**
350** Parameters:      task_entry  - (input) pointer to the entry function of the task
351**                  task_id     - (input) Task id is mapped to priority
352**                  taskname    - (input) name given to the task
353**                  stack       - (input) pointer to the top of the stack (highest memory location)
354**                  stacksize   - (input) size of the stack allocated for the task
355**
356** Returns          GKI_SUCCESS if all OK, GKI_FAILURE if any problem
357**
358** NOTE             This function take some parameters that may not be needed
359**                  by your particular OS. They are here for compatability
360**                  of the function prototype.
361**
362*******************************************************************************/
363UINT8 GKI_create_task (TASKPTR task_entry, UINT8 task_id, INT8 *taskname, UINT16 *stack, UINT16 stacksize)
364{
365    UINT16  i;
366    UINT8   *p;
367    struct sched_param param;
368    int policy, ret = 0;
369    pthread_attr_t attr1;
370    UNUSED(stack);
371    UNUSED(stacksize);
372
373    GKI_TRACE( "GKI_create_task %x %d %s %x %d", (int)task_entry, (int)task_id,
374            (char*) taskname, (int) stack, (int)stacksize);
375
376    if (task_id >= GKI_MAX_TASKS)
377    {
378        ALOGE("Error! task ID > max task allowed");
379        return (GKI_FAILURE);
380    }
381
382
383    gki_cb.com.OSRdyTbl[task_id]    = TASK_READY;
384    gki_cb.com.OSTName[task_id]     = taskname;
385    gki_cb.com.OSWaitTmr[task_id]   = 0;
386    gki_cb.com.OSWaitEvt[task_id]   = 0;
387
388    /* Initialize mutex and condition variable objects for events and timeouts */
389    pthread_condattr_t cond_attr;
390    pthread_condattr_init(&cond_attr);
391    pthread_condattr_setclock(&cond_attr, CLOCK_MONOTONIC);
392
393    pthread_mutex_init(&gki_cb.os.thread_evt_mutex[task_id], NULL);
394    pthread_cond_init (&gki_cb.os.thread_evt_cond[task_id], &cond_attr);
395    pthread_mutex_init(&gki_cb.os.thread_timeout_mutex[task_id], NULL);
396    pthread_cond_init (&gki_cb.os.thread_timeout_cond[task_id], NULL);
397
398    pthread_attr_init(&attr1);
399    /* by default, pthread creates a joinable thread */
400#if ( FALSE == GKI_PTHREAD_JOINABLE )
401    pthread_attr_setdetachstate(&attr1, PTHREAD_CREATE_DETACHED);
402
403    GKI_TRACE("GKI creating task %i\n", task_id);
404#else
405    GKI_TRACE("GKI creating JOINABLE task %i\n", task_id);
406#endif
407
408    /* On Android, the new tasks starts running before 'gki_cb.os.thread_id[task_id]' is initialized */
409    /* Pass task_id to new task so it can initialize gki_cb.os.thread_id[task_id] for it calls GKI_wait */
410    gki_pthread_info[task_id].task_id = task_id;
411    gki_pthread_info[task_id].task_entry = task_entry;
412    gki_pthread_info[task_id].params = 0;
413
414    ret = pthread_create( &gki_cb.os.thread_id[task_id],
415              &attr1,
416              (void *)gki_task_entry,
417              &gki_pthread_info[task_id]);
418
419    if (ret != 0)
420    {
421         ALOGE("pthread_create failed(%d), %s!", ret, taskname);
422         return GKI_FAILURE;
423    }
424
425    if(pthread_getschedparam(gki_cb.os.thread_id[task_id], &policy, &param)==0)
426     {
427#if (GKI_LINUX_BASE_POLICY!=GKI_SCHED_NORMAL)
428#if defined(PBS_SQL_TASK)
429         if (task_id == PBS_SQL_TASK)
430         {
431             GKI_TRACE("PBS SQL lowest priority task");
432             policy = SCHED_NORMAL;
433         }
434         else
435#endif
436#endif
437         {
438             /* check if define in gki_int.h is correct for this compile environment! */
439             policy = GKI_LINUX_BASE_POLICY;
440#if (GKI_LINUX_BASE_POLICY != GKI_SCHED_NORMAL)
441             param.sched_priority = GKI_LINUX_BASE_PRIORITY - task_id - 2;
442#else
443             param.sched_priority = 0;
444#endif
445         }
446         pthread_setschedparam(gki_cb.os.thread_id[task_id], policy, &param);
447     }
448
449    GKI_TRACE( "Leaving GKI_create_task %x %d %x %s %x %d\n",
450              (int)task_entry,
451              (int)task_id,
452              (int)gki_cb.os.thread_id[task_id],
453              (char*)taskname,
454              (int)stack,
455              (int)stacksize);
456
457    return (GKI_SUCCESS);
458}
459
460void GKI_destroy_task(UINT8 task_id)
461{
462#if ( FALSE == GKI_PTHREAD_JOINABLE )
463        int i = 0;
464#else
465        int result;
466#endif
467    if (gki_cb.com.OSRdyTbl[task_id] != TASK_DEAD)
468    {
469        gki_cb.com.OSRdyTbl[task_id] = TASK_DEAD;
470
471        /* paranoi settings, make sure that we do not execute any mailbox events */
472        gki_cb.com.OSWaitEvt[task_id] &= ~(TASK_MBOX_0_EVT_MASK|TASK_MBOX_1_EVT_MASK|
473                                            TASK_MBOX_2_EVT_MASK|TASK_MBOX_3_EVT_MASK);
474
475#if (GKI_NUM_TIMERS > 0)
476        gki_cb.com.OSTaskTmr0R[task_id] = 0;
477        gki_cb.com.OSTaskTmr0 [task_id] = 0;
478#endif
479
480#if (GKI_NUM_TIMERS > 1)
481        gki_cb.com.OSTaskTmr1R[task_id] = 0;
482        gki_cb.com.OSTaskTmr1 [task_id] = 0;
483#endif
484
485#if (GKI_NUM_TIMERS > 2)
486        gki_cb.com.OSTaskTmr2R[task_id] = 0;
487        gki_cb.com.OSTaskTmr2 [task_id] = 0;
488#endif
489
490#if (GKI_NUM_TIMERS > 3)
491        gki_cb.com.OSTaskTmr3R[task_id] = 0;
492        gki_cb.com.OSTaskTmr3 [task_id] = 0;
493#endif
494
495        GKI_send_event(task_id, EVENT_MASK(GKI_SHUTDOWN_EVT));
496
497#if ( FALSE == GKI_PTHREAD_JOINABLE )
498        i = 0;
499
500        while ((gki_cb.com.OSWaitEvt[task_id] != 0) && (++i < 10))
501            usleep(100 * 1000);
502#else
503        result = pthread_join( gki_cb.os.thread_id[task_id], NULL );
504        if ( result < 0 )
505        {
506            ALOGE( "pthread_join() FAILED: result: %d", result );
507        }
508#endif
509        GKI_exit_task(task_id);
510        ALOGI( "GKI_shutdown(): task [%s] terminated\n", gki_cb.com.OSTName[task_id]);
511    }
512}
513
514
515/*******************************************************************************
516**
517** Function         GKI_task_self_cleanup
518**
519** Description      This function is used in the case when the calling thread
520**                  is exiting itself. The GKI_destroy_task function can not be
521**                  used in this case due to the pthread_join call. The function
522**                  cleans up GKI control block associated to the terminating
523**                  thread.
524**
525** Parameters:      task_id     - (input) Task id is used for sanity check to
526**                                 make sure the calling thread is in the right
527**                                 context.
528**
529** Returns          None
530**
531*******************************************************************************/
532void GKI_task_self_cleanup(UINT8 task_id)
533{
534    UINT8 my_task_id = GKI_get_taskid();
535
536    if (task_id != my_task_id)
537    {
538        ALOGE("%s: Wrong context - current task %d is not the given task id %d",\
539                      __FUNCTION__, my_task_id, task_id);
540        return;
541    }
542
543    if (gki_cb.com.OSRdyTbl[task_id] != TASK_DEAD)
544    {
545        /* paranoi settings, make sure that we do not execute any mailbox events */
546        gki_cb.com.OSWaitEvt[task_id] &= ~(TASK_MBOX_0_EVT_MASK|TASK_MBOX_1_EVT_MASK|
547                                            TASK_MBOX_2_EVT_MASK|TASK_MBOX_3_EVT_MASK);
548
549#if (GKI_NUM_TIMERS > 0)
550        gki_cb.com.OSTaskTmr0R[task_id] = 0;
551        gki_cb.com.OSTaskTmr0 [task_id] = 0;
552#endif
553
554#if (GKI_NUM_TIMERS > 1)
555        gki_cb.com.OSTaskTmr1R[task_id] = 0;
556        gki_cb.com.OSTaskTmr1 [task_id] = 0;
557#endif
558
559#if (GKI_NUM_TIMERS > 2)
560        gki_cb.com.OSTaskTmr2R[task_id] = 0;
561        gki_cb.com.OSTaskTmr2 [task_id] = 0;
562#endif
563
564#if (GKI_NUM_TIMERS > 3)
565        gki_cb.com.OSTaskTmr3R[task_id] = 0;
566        gki_cb.com.OSTaskTmr3 [task_id] = 0;
567#endif
568
569        GKI_exit_task(task_id);
570
571        /* Calling pthread_detach here to mark the thread as detached.
572           Once the thread terminates, the system can reclaim its resources
573           without waiting for another thread to join with.
574        */
575        pthread_detach(gki_cb.os.thread_id[task_id]);
576    }
577}
578
579/*******************************************************************************
580**
581** Function         GKI_shutdown
582**
583** Description      shutdowns the GKI tasks/threads in from max task id to 0 and frees
584**                  pthread resources!
585**                  IMPORTANT: in case of join method, GKI_shutdown must be called outside
586**                  a GKI thread context!
587**
588** Returns          void
589**
590*******************************************************************************/
591
592void GKI_shutdown(void)
593{
594    UINT8 task_id;
595#if ( FALSE == GKI_PTHREAD_JOINABLE )
596    int i = 0;
597#else
598    int result;
599#endif
600
601#ifdef GKI_USE_DEFERED_ALLOC_BUF_POOLS
602    gki_dealloc_free_queue();
603#endif
604
605    /* release threads and set as TASK_DEAD. going from low to high priority fixes
606     * GKI_exception problem due to btu->hci sleep request events  */
607    for (task_id = GKI_MAX_TASKS; task_id > 0; task_id--)
608    {
609        if (gki_cb.com.OSRdyTbl[task_id - 1] != TASK_DEAD)
610        {
611            gki_cb.com.OSRdyTbl[task_id - 1] = TASK_DEAD;
612
613            /* paranoi settings, make sure that we do not execute any mailbox events */
614            gki_cb.com.OSWaitEvt[task_id-1] &= ~(TASK_MBOX_0_EVT_MASK|TASK_MBOX_1_EVT_MASK|
615                                                TASK_MBOX_2_EVT_MASK|TASK_MBOX_3_EVT_MASK);
616            GKI_send_event(task_id - 1, EVENT_MASK(GKI_SHUTDOWN_EVT));
617
618#if ( FALSE == GKI_PTHREAD_JOINABLE )
619            i = 0;
620
621            while ((gki_cb.com.OSWaitEvt[task_id - 1] != 0) && (++i < 10))
622                usleep(100 * 1000);
623#else
624            result = pthread_join( gki_cb.os.thread_id[task_id-1], NULL );
625
626            if ( result < 0 )
627            {
628                ALOGE( "pthread_join() FAILED: result: %d", result );
629            }
630#endif
631            GKI_exit_task(task_id - 1);
632        }
633    }
634
635    /* Destroy mutex and condition variable objects */
636    pthread_mutex_destroy(&gki_cb.os.GKI_mutex);
637
638    /*    pthread_mutex_destroy(&GKI_sched_mutex); */
639#if (GKI_DEBUG == TRUE)
640    pthread_mutex_destroy(&gki_cb.os.GKI_trace_mutex);
641#endif
642    /*    pthread_mutex_destroy(&thread_delay_mutex);
643     pthread_cond_destroy (&thread_delay_cond); */
644#if ( FALSE == GKI_PTHREAD_JOINABLE )
645    i = 0;
646#endif
647
648    if (timer_created) {
649        timer_delete(posix_timer);
650        timer_created = false;
651    }
652}
653
654/*****************************************************************************
655**
656** Function        gki_set_timer_scheduling
657**
658** Description     helper function to set scheduling policy and priority of btdl
659**
660** Returns         void
661**
662*******************************************************************************/
663
664static void gki_set_timer_scheduling( void )
665{
666    pid_t               main_pid = getpid();
667    struct sched_param  param;
668    int                 policy;
669
670    policy = sched_getscheduler(main_pid);
671
672    if ( policy != -1 )
673    {
674        GKI_TRACE("gki_set_timer_scheduling(()::scheduler current policy: %d", policy);
675
676        /* ensure highest priority in the system + 2 to allow space for read threads */
677        param.sched_priority = GKI_LINUX_TIMER_TICK_PRIORITY;
678
679        if ( 0!=sched_setscheduler(main_pid, GKI_LINUX_TIMER_POLICY, &param ) )
680        {
681            GKI_TRACE("sched_setscheduler() failed with error: %d", errno);
682        }
683    }
684    else
685    {
686        GKI_TRACE( "getscheduler failed: %d", errno);
687    }
688}
689
690
691/*****************************************************************************
692**
693** Function        GKI_run
694**
695** Description     Main GKI loop
696**
697** Returns
698**
699*******************************************************************************/
700
701void GKI_run(void)
702{
703    /* adjust btld scheduling scheme now */
704    gki_set_timer_scheduling();
705    GKI_TRACE( "GKI_run(): Start/Stop GKI_timer_update_registered!" );
706}
707
708
709/*******************************************************************************
710**
711** Function         GKI_stop
712**
713** Description      This function is called to stop
714**                  the tasks and timers when the system is being stopped
715**
716** Returns          void
717**
718** NOTE             This function is NOT called by the Broadcom stack and
719**                  profiles. If you want to use it in your own implementation,
720**                  put specific code here.
721**
722*******************************************************************************/
723
724void GKI_stop (void)
725{
726    UINT8 task_id;
727
728    /*  gki_queue_timer_cback(FALSE); */
729    /* TODO - add code here if needed*/
730
731    for(task_id = 0; task_id<GKI_MAX_TASKS; task_id++)
732    {
733        if(gki_cb.com.OSRdyTbl[task_id] != TASK_DEAD)
734        {
735            GKI_exit_task(task_id);
736        }
737    }
738}
739
740
741/*******************************************************************************
742**
743** Function         GKI_wait
744**
745** Description      This function is called by tasks to wait for a specific
746**                  event or set of events. The task may specify the duration
747**                  that it wants to wait for, or 0 if infinite.
748**
749** Parameters:      flag -    (input) the event or set of events to wait for
750**                  timeout - (input) the duration that the task wants to wait
751**                                    for the specific events (in system ticks)
752**
753**
754** Returns          the event mask of received events or zero if timeout
755**
756*******************************************************************************/
757UINT16 GKI_wait (UINT16 flag, UINT32 timeout)
758{
759    UINT16 evt;
760    UINT8 rtask;
761    struct timespec abstime = { 0, 0 };
762
763    int sec;
764    int nano_sec;
765
766    rtask = GKI_get_taskid();
767
768    GKI_TRACE("GKI_wait %d %x %d", (int)rtask, (int)flag, (int)timeout);
769
770    gki_cb.com.OSWaitForEvt[rtask] = flag;
771
772    /* protect OSWaitEvt[rtask] from modification from an other thread */
773    pthread_mutex_lock(&gki_cb.os.thread_evt_mutex[rtask]);
774
775    if (!(gki_cb.com.OSWaitEvt[rtask] & flag))
776    {
777        if (timeout)
778        {
779            clock_gettime(CLOCK_MONOTONIC, &abstime);
780
781            /* add timeout */
782            sec = timeout / 1000;
783            nano_sec = (timeout % 1000) * NANOSEC_PER_MILLISEC;
784            abstime.tv_nsec += nano_sec;
785            if (abstime.tv_nsec > NSEC_PER_SEC)
786            {
787                abstime.tv_sec += (abstime.tv_nsec / NSEC_PER_SEC);
788                abstime.tv_nsec = abstime.tv_nsec % NSEC_PER_SEC;
789            }
790            abstime.tv_sec += sec;
791
792            pthread_cond_timedwait(&gki_cb.os.thread_evt_cond[rtask],
793                    &gki_cb.os.thread_evt_mutex[rtask], &abstime);
794        }
795        else
796        {
797            pthread_cond_wait(&gki_cb.os.thread_evt_cond[rtask], &gki_cb.os.thread_evt_mutex[rtask]);
798        }
799
800        /* TODO: check, this is probably neither not needed depending on phtread_cond_wait() implmentation,
801         e.g. it looks like it is implemented as a counter in which case multiple cond_signal
802         should NOT be lost! */
803
804        /* we are waking up after waiting for some events, so refresh variables
805           no need to call GKI_disable() here as we know that we will have some events as we've been waking
806           up after condition pending or timeout */
807
808        if (gki_cb.com.OSTaskQFirst[rtask][0])
809            gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_0_EVT_MASK;
810        if (gki_cb.com.OSTaskQFirst[rtask][1])
811            gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_1_EVT_MASK;
812        if (gki_cb.com.OSTaskQFirst[rtask][2])
813            gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_2_EVT_MASK;
814        if (gki_cb.com.OSTaskQFirst[rtask][3])
815            gki_cb.com.OSWaitEvt[rtask] |= TASK_MBOX_3_EVT_MASK;
816
817        if (gki_cb.com.OSRdyTbl[rtask] == TASK_DEAD)
818        {
819            gki_cb.com.OSWaitEvt[rtask] = 0;
820            /* unlock thread_evt_mutex as pthread_cond_wait() does auto lock when cond is met */
821            pthread_mutex_unlock(&gki_cb.os.thread_evt_mutex[rtask]);
822            return (EVENT_MASK(GKI_SHUTDOWN_EVT));
823        }
824    }
825
826    /* Clear the wait for event mask */
827    gki_cb.com.OSWaitForEvt[rtask] = 0;
828
829    /* Return only those bits which user wants... */
830    evt = gki_cb.com.OSWaitEvt[rtask] & flag;
831
832    /* Clear only those bits which user wants... */
833    gki_cb.com.OSWaitEvt[rtask] &= ~flag;
834
835    /* unlock thread_evt_mutex as pthread_cond_wait() does auto lock mutex when cond is met */
836    pthread_mutex_unlock(&gki_cb.os.thread_evt_mutex[rtask]);
837
838    GKI_TRACE("GKI_wait %d %x %d %x done", (int)rtask, (int)flag, (int)timeout, (int)evt);
839    return (evt);
840}
841
842
843/*******************************************************************************
844**
845** Function         GKI_delay
846**
847** Description      This function is called by tasks to sleep unconditionally
848**                  for a specified amount of time. The duration is in milliseconds
849**
850** Parameters:      timeout -    (input) the duration in milliseconds
851**
852** Returns          void
853**
854*******************************************************************************/
855
856void GKI_delay (UINT32 timeout)
857{
858    UINT8 rtask = GKI_get_taskid();
859    struct timespec delay;
860    int err;
861
862    GKI_TRACE("GKI_delay %d %d", (int)rtask, (int)timeout);
863
864    delay.tv_sec = timeout / 1000;
865    delay.tv_nsec = 1000 * 1000 * (timeout%1000);
866
867    /* [u]sleep can't be used because it uses SIGALRM */
868
869    do {
870        err = nanosleep(&delay, &delay);
871    } while (err < 0 && errno ==EINTR);
872
873    /* Check if task was killed while sleeping */
874
875     /* NOTE : if you do not implement task killing, you do not need this check */
876
877    if (rtask && gki_cb.com.OSRdyTbl[rtask] == TASK_DEAD)
878    {
879    }
880
881    GKI_TRACE("GKI_delay %d %d done", (int)rtask, (int)timeout);
882
883    return;
884}
885
886
887/*******************************************************************************
888**
889** Function         GKI_send_event
890**
891** Description      This function is called by tasks to send events to other
892**                  tasks. Tasks can also send events to themselves.
893**
894** Parameters:      task_id -  (input) The id of the task to which the event has to
895**                  be sent
896**                  event   -  (input) The event that has to be sent
897**
898**
899** Returns          GKI_SUCCESS if all OK, else GKI_FAILURE
900**
901*******************************************************************************/
902
903UINT8 GKI_send_event (UINT8 task_id, UINT16 event)
904{
905    GKI_TRACE("GKI_send_event %d %x", task_id, event);
906
907    if (task_id < GKI_MAX_TASKS)
908    {
909        /* protect OSWaitEvt[task_id] from manipulation in GKI_wait() */
910        pthread_mutex_lock(&gki_cb.os.thread_evt_mutex[task_id]);
911
912        /* Set the event bit */
913        gki_cb.com.OSWaitEvt[task_id] |= event;
914
915        pthread_cond_signal(&gki_cb.os.thread_evt_cond[task_id]);
916
917        pthread_mutex_unlock(&gki_cb.os.thread_evt_mutex[task_id]);
918
919        GKI_TRACE("GKI_send_event %d %x done", task_id, event);
920        return ( GKI_SUCCESS );
921    }
922    GKI_TRACE("############## GKI_send_event FAILED!! ##################");
923    return (GKI_FAILURE);
924}
925
926
927/*******************************************************************************
928**
929** Function         GKI_get_taskid
930**
931** Description      This function gets the currently running task ID.
932**
933** Returns          task ID
934**
935** NOTE             The Broadcom upper stack and profiles may run as a single task.
936**                  If you only have one GKI task, then you can hard-code this
937**                  function to return a '1'. Otherwise, you should have some
938**                  OS-specific method to determine the current task.
939**
940*******************************************************************************/
941UINT8 GKI_get_taskid (void)
942{
943    int i;
944
945    pthread_t thread_id = pthread_self( );
946
947    GKI_TRACE("GKI_get_taskid %x", (int)thread_id);
948
949    for (i = 0; i < GKI_MAX_TASKS; i++) {
950        if (gki_cb.os.thread_id[i] == thread_id) {
951            //GKI_TRACE("GKI_get_taskid %x %d done", thread_id, i);
952            return(i);
953        }
954    }
955
956    GKI_TRACE("GKI_get_taskid: task id = -1");
957
958    return(-1);
959}
960
961
962/*******************************************************************************
963**
964** Function         GKI_map_taskname
965**
966** Description      This function gets the task name of the taskid passed as arg.
967**                  If GKI_MAX_TASKS is passed as arg the currently running task
968**                  name is returned
969**
970** Parameters:      task_id -  (input) The id of the task whose name is being
971**                  sought. GKI_MAX_TASKS is passed to get the name of the
972**                  currently running task.
973**
974** Returns          pointer to task name
975**
976** NOTE             this function needs no customization
977**
978*******************************************************************************/
979
980INT8 *GKI_map_taskname (UINT8 task_id)
981{
982    GKI_TRACE("GKI_map_taskname %d", task_id);
983
984    if (task_id < GKI_MAX_TASKS)
985    {
986        GKI_TRACE("GKI_map_taskname %d %s done", task_id, gki_cb.com.OSTName[task_id]);
987         return (gki_cb.com.OSTName[task_id]);
988    }
989    else if (task_id == GKI_MAX_TASKS )
990    {
991        return (gki_cb.com.OSTName[GKI_get_taskid()]);
992    }
993    else
994    {
995        return (INT8*)"BAD";
996    }
997}
998
999
1000/*******************************************************************************
1001**
1002** Function         GKI_enable
1003**
1004** Description      This function enables interrupts.
1005**
1006** Returns          void
1007**
1008*******************************************************************************/
1009void GKI_enable (void)
1010{
1011    pthread_mutex_unlock(&gki_cb.os.GKI_mutex);
1012}
1013
1014
1015/*******************************************************************************
1016**
1017** Function         GKI_disable
1018**
1019** Description      This function disables interrupts.
1020**
1021** Returns          void
1022**
1023*******************************************************************************/
1024
1025void GKI_disable (void)
1026{
1027    pthread_mutex_lock(&gki_cb.os.GKI_mutex);
1028}
1029
1030
1031/*******************************************************************************
1032**
1033** Function         GKI_exception
1034**
1035** Description      This function throws an exception.
1036**                  This is normally only called for a nonrecoverable error.
1037**
1038** Parameters:      code    -  (input) The code for the error
1039**                  msg     -  (input) The message that has to be logged
1040**
1041** Returns          void
1042**
1043*******************************************************************************/
1044
1045void GKI_exception (UINT16 code, char *msg)
1046{
1047    UINT8 task_id;
1048    int i = 0;
1049
1050    ALOGE( "GKI_exception(): Task State Table");
1051
1052    for(task_id = 0; task_id < GKI_MAX_TASKS; task_id++)
1053    {
1054        ALOGE( "TASK ID [%d] task name [%s] state [%d]",
1055                         task_id,
1056                         gki_cb.com.OSTName[task_id],
1057                         gki_cb.com.OSRdyTbl[task_id]);
1058    }
1059
1060    ALOGE("GKI_exception %d %s", code, msg);
1061    ALOGE( "********************************************************************");
1062    ALOGE( "* GKI_exception(): %d %s", code, msg);
1063    ALOGE( "********************************************************************");
1064
1065#if 0//(GKI_DEBUG == TRUE)
1066    GKI_disable();
1067
1068    if (gki_cb.com.ExceptionCnt < GKI_MAX_EXCEPTION)
1069    {
1070        EXCEPTION_T *pExp;
1071
1072        pExp =  &gki_cb.com.Exception[gki_cb.com.ExceptionCnt++];
1073        pExp->type = code;
1074        pExp->taskid = GKI_get_taskid();
1075        strncpy((char *)pExp->msg, msg, GKI_MAX_EXCEPTION_MSGLEN - 1);
1076    }
1077
1078    GKI_enable();
1079#endif
1080
1081    GKI_TRACE("GKI_exception %d %s done", code, msg);
1082    return;
1083}
1084
1085/*******************************************************************************
1086**
1087** Function         GKI_os_malloc
1088**
1089** Description      This function allocates memory
1090**
1091** Parameters:      size -  (input) The size of the memory that has to be
1092**                  allocated
1093**
1094** Returns          the address of the memory allocated, or NULL if failed
1095**
1096** NOTE             This function is called by the Broadcom stack when
1097**                  dynamic memory allocation is used. (see dyn_mem.h)
1098**
1099*******************************************************************************/
1100void *GKI_os_malloc (UINT32 size)
1101{
1102    return malloc(size);
1103}
1104
1105/*******************************************************************************
1106**
1107** Function         GKI_os_free
1108**
1109** Description      This function frees memory
1110**
1111** Parameters:      size -  (input) The address of the memory that has to be
1112**                  freed
1113**
1114** Returns          void
1115**
1116** NOTE             This function is NOT called by the Broadcom stack and
1117**                  profiles. It is only called from within GKI if dynamic
1118**
1119*******************************************************************************/
1120void GKI_os_free (void *p_mem)
1121{
1122    free(p_mem);
1123}
1124
1125
1126/*******************************************************************************
1127**
1128** Function         GKI_exit_task
1129**
1130** Description      This function is called to stop a GKI task.
1131**
1132** Parameters:      task_id  - (input) the id of the task that has to be stopped
1133**
1134** Returns          void
1135**
1136** NOTE             This function is NOT called by the Broadcom stack and
1137**                  profiles. If you want to use it in your own implementation,
1138**                  put specific code here to kill a task.
1139**
1140*******************************************************************************/
1141void GKI_exit_task (UINT8 task_id)
1142{
1143    GKI_disable();
1144    gki_cb.com.OSRdyTbl[task_id] = TASK_DEAD;
1145
1146    /* Destroy mutex and condition variable objects */
1147    pthread_mutex_destroy(&gki_cb.os.thread_evt_mutex[task_id]);
1148    pthread_cond_destroy (&gki_cb.os.thread_evt_cond[task_id]);
1149    pthread_mutex_destroy(&gki_cb.os.thread_timeout_mutex[task_id]);
1150    pthread_cond_destroy (&gki_cb.os.thread_timeout_cond[task_id]);
1151
1152    GKI_enable();
1153
1154    ALOGI("GKI_exit_task %d done", task_id);
1155    return;
1156}
1157