Smart Timing Mechanism
- Why need this mechanism?
最近在跑一個超薄NB專案,這個專案的power sequence比較奇怪,很多地方需要很多的定時一段時間然後再去調整某一部分的時序。我真是受夠了code base中的定時方式。每次定時都要定義一個變量,需要使用時給它指派,然後再8051的定時器中斷到來時,再計數累加。一個函數非常的長,而且充斥着亂七八糟的變量。經過這麼多年的發展,代碼裡到處都是壞味道,看的我非常不爽,于是就産生了改造這個機制的想法。
- How to improve it?
既然決定了那麼就行動吧 ! 打開google 大神 進入code search,看看有沒有什麼好東西(J我不想重新造輪子,如果有好的代碼那麼就拿來參考)。搜來搜去,發現linux 2.6核心中的定時機制很酷,可是不适合我的環境,它太大了,光這個機制就能把我的EC搞爆了L。然後再狂搜!果然不負我一番苦心,我發現linux 0.95核心中的定時機制挺适合。可是仔細閱讀之後發現這個機制有些缺陷,它隻處理了插入結點時間比頭結點時間長的情況,而沒有處理插入結點時間比連結清單頭結點短的狀況。下面就是我修改後的source code:
#ifndef OEM_TIMER_SERVICE__H
#define OEM_TIMER_SERVIEC__H
void add_timer(unsigned short jiffies,void (*callback)());
void do_timer(void);
#endif
#include <stdio.h>
#include "OEMTimerService.H"
#define TIMER_REQUESTS 0x30
struct timer_list
{
struct timer_list *next;
unsigned short jiffies;
void (*callback)(void);
};
struct timer_list timer_list[TIMER_REQUESTS] = {NULL};
struct timer_list *timer_header = NULL;
void add_timer(unsigned short jiffies,void (*callback)())
{
struct timer_list *ptmp;
if(!callback)
return ;
EA = 0;
if(jiffies <= 0)
(*callback)();
for(ptmp = timer_list; ptmp < timer_list + TIMER_REQUESTS; ptmp++)
if(ptmp->callback == NULL)
break;
if(ptmp >= timer_list + TIMER_REQUESTS)
{
goto EXIT;
}
ptmp->jiffies = jiffies;
ptmp->callback = callback;
ptmp->next = timer_header;
timer_header = ptmp;
//add bellow code to fix linux on timer’s bugs ++>>
if(ptmp->next && ptmp->next->jiffies > ptmp->jiffies)
{
ptmp->next->jiffies -= ptmp->jiffies;
}//++<<
else
{
while(ptmp->next && (ptmp->next->jiffies < ptmp->jiffies))
{
ptmp->jiffies -= ptmp->next->jiffies;
callback = ptmp->callback;
ptmp->callback = ptmp->next->callback;
ptmp->next->callback = callback;
jiffies = ptmp->jiffies;
ptmp->jiffies = ptmp->next->jiffies;
ptmp->next->jiffies = jiffies;
ptmp = ptmp->next;
}
}
EXIT:
EA = 1;
return;
}
void do_timer(void)
{
while((timer_header != NULL)
&&(timer_header->callback != NULL)
&&(--timer_header->jiffies <= 0))
{
void (*callback_fptr)(void);
callback_fptr = timer_header->callback;
timer_header->callback = NULL;
timer_header = timer_header->next;
(*callback_fptr)();
}
}
上述code,我已經導入并開始測試了,短短幾十行代碼大大改善了我的code base的感官,降低了代碼的耦合度,現在看上去清爽多了J!
野人獻曝,博君一笑!
Peter