18#include <timer_alarm.h>
23 vs32 timer_counter_id;
24 timer_alarm_handler_t callback_handler;
25 void *callback_handler_arg;
28#define PTR_TO_ALARM_ID(ptr_, cid_) ((s32)((((uiptr)(ptr_)) << 4) | ((cid_) & 0xFE) | 1))
29#define ALARM_ID_TO_PTR(id_) ((alarm_struct_t *)((((uiptr)(id_)) >> 8) << 4))
30#define ALARM_ID_IS_VALID(id_) ((ALARM_ID_TO_PTR(id_) != NULL) && ((siptr)(id_) >= 0) && ((((((uiptr)id_) & 0xFF) == (((ALARM_ID_TO_PTR(id_))->timer_counter_id) & 0xFF)))))
36alarm_struct_t *g_pFreeAlarm = NULL;
39extern alarm_struct_t *g_pFreeAlarm;
42#ifdef F_ForTimer_InitAlarm
45 g_pFreeAlarm = &g_AlarmBuf[0];
46 for (u32 i = 0; i < (ALARM_COUNT - 1); i += 1)
48 g_AlarmBuf[i].alarm_next = &g_AlarmBuf[i + 1];
50 g_AlarmBuf[ALARM_COUNT - 1].alarm_next = NULL;
54static inline alarm_struct_t *ForTimer_AllocAlarm(
void)
56 alarm_struct_t *alarm_current;
57 alarm_current = g_pFreeAlarm;
58 if (alarm_current != NULL)
60 g_pFreeAlarm = alarm_current->alarm_next;
65static inline void ForTimer_FreeAlarm(alarm_struct_t *alarm_current)
67 alarm_current->alarm_next = g_pFreeAlarm;
68 alarm_current->timer_counter_id = 0;
69 g_pFreeAlarm = alarm_current;
73u64 AlarmHandler(s32 alarm_id, u64 scheduled_time, u64 actual_time,
void *arg,
void *last_pc)
76 alarm_struct_t *alarm_current;
78 alarm_current = (alarm_struct_t *)arg;
79 result = alarm_current->callback_handler(
80 PTR_TO_ALARM_ID(alarm_current, alarm_id),
83 alarm_current->callback_handler_arg, last_pc);
86 ForTimer_FreeAlarm(alarm_current);
93#ifdef F_iSetTimerAlarm
94s32 iSetTimerAlarm(u64 clock_cycles, timer_alarm_handler_t callback_handler,
void *arg)
97 alarm_struct_t *alarm_current;
99 if (callback_handler == NULL)
103 alarm_current = ForTimer_AllocAlarm();
104 if (alarm_current == NULL)
108 timer_counter_id = iAllocTimerCounter();
109 if (timer_counter_id < 0)
111 ForTimer_FreeAlarm(alarm_current);
112 return timer_counter_id;
114 alarm_current->timer_counter_id = timer_counter_id;
115 alarm_current->callback_handler = callback_handler;
116 alarm_current->callback_handler_arg = arg;
117 iSetTimerHandler(timer_counter_id, clock_cycles, AlarmHandler, alarm_current);
118 iStartTimerCounter(timer_counter_id);
119 return PTR_TO_ALARM_ID(alarm_current, timer_counter_id);
123#ifdef F_SetTimerAlarm
132s32 SetTimerAlarm(u64 clock_cycles, timer_alarm_handler_t callback_handler,
void *arg)
138 ret = iSetTimerAlarm(clock_cycles, callback_handler, arg);
147#ifdef F_iReleaseTimerAlarm
148s32 iReleaseTimerAlarm(s32
id)
150 alarm_struct_t *alarm_current;
153 alarm_current = ALARM_ID_TO_PTR(
id);
154 if (!ALARM_ID_IS_VALID(
id))
158 ret = iFreeTimerCounter(alarm_current->timer_counter_id);
161 ForTimer_FreeAlarm(alarm_current);
167#ifdef F_ReleaseTimerAlarm
168s32 ReleaseTimerAlarm(s32
id)
170 alarm_struct_t *alarm_current;
173 alarm_current = ALARM_ID_TO_PTR(
id);
175 if (!ALARM_ID_IS_VALID(
id))
183 FreeTimerCounter(alarm_current->timer_counter_id);
185 ForTimer_FreeAlarm(alarm_current);