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