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