void sched_init(void)
{
/* ... */
outb_p(0x36,0x43); /* binary, mode 3, LSB/MSB, ch 0 */
outb_p(LATCH & 0xff , 0x40); /* LSB */
outb(LATCH >> 8 , 0x40); /* MSB */
set_intr_gate(0x20,&timer_interrupt);
/* ... */
}
定时器0的端口地址是0x40,而控制寄存器的端口地址是0x43。那么首先是配置定时器0,定时器0的工作模式为模式3,二进制计数,然后是写入定时器初值,由于8253/8254定时器的数据总线只有8位,所以需要分两次写入,这里是先写入低8位,再写入高8位,那么写入的初值是多少呢,就是这里的LATCH,LATCH为(1193180/HZ),HZ定义为100,而8253/8254的输入时钟为1.193180MHz,那么定时的时间约为11931/1.1931=10000us=10ms,也就是定时器10毫秒产生一次中断,而中断处理函数为timer_interrupt,代码如下:
_timer_interrupt:
push %ds # save ds,es and put kernel data space
push %es # into them. %fs is used by _system_call
push %fs
pushl %edx # we save %eax,%ecx,%edx as gcc doesn't
pushl %ecx # save those across function calls. %ebx
pushl %ebx # is saved as we use that in ret_sys_call
pushl %eax
movl $0x10,%eax
mov %ax,%ds
mov %ax,%es
movl $0x17,%eax
mov %ax,%fs
incl _jiffies
movb $0x20,%al # EOI to interrupt controller #1
outb %al,$0x20
movl CS(%esp),%eax
andl $3,%eax # %eax is CPL (0 or 3, 0=supervisor)
pushl %eax
call _do_timer # 'do_timer(long CPL)' does everything from
addl $4,%esp # task switching to accounting ...
jmp ret_from_sys_call
注意在seched_init函数中,设置定时器的中断处理函数为timer_interrupt,而这里变成了_timer_interrupt,即多了个'_'前缀,这是为什么呢?在老版本的gcc在编译过程中会给全局变量和函数加上'_'前缀,而新版本的gcc则不会加上这个'_'前缀,因为新版本的gcc默认选项是-fnoleading-underscore,如果需要加上'_'前缀,可以使用-fleading-underscore选项,大家可以试一下(只编译生成.s文件,不汇编)。
void do_timer(long cpl)
{
extern int beepcount;
extern void sysbeepstop(void);
if (beepcount)
if (!--beepcount)
sysbeepstop();
if (cpl)
current->utime++;
else
current->stime++;
if (next_timer) {
next_timer->jiffies--;
while (next_timer && next_timer->jiffies <= 0) {
void (*fn)(void);
fn = next_timer->fn;
next_timer->fn = NULL;
next_timer = next_timer->next;
(fn)();
}
}
if (current_DOR & 0xf0)
do_floppy_timer();
if ((--current->counter)>0) return;
current->counter=0;
if (!cpl) return;
schedule();
}
beepcount为蜂鸣器的鸣叫时间,如果为0,需要停止蜂鸣器。
void schedule(void)
{
int i,next,c;
struct task_struct ** p;
/* check alarm, wake up any interruptible tasks that have got a signal */
for(p = &LAST_TASK ; p > &FIRST_TASK ; --p)
if (*p) {
if ((*p)->alarm && (*p)->alarm < jiffies) {
(*p)->signal |= (1<<(SIGALRM-1));
(*p)->alarm = 0;
}
if (((*p)->signal & ~(_BLOCKABLE & (*p)->blocked)) &&
(*p)->state==TASK_INTERRUPTIBLE)
(*p)->state=TASK_RUNNING;
}
/* this is the scheduler proper: */
while (1) {
c = -1;
next = 0;
i = NR_TASKS;
p = &task[NR_TASKS];
while (--i) {
if (!*--p)
continue;
if ((*p)->state == TASK_RUNNING && (*p)->counter > c)
c = (*p)->counter, next = i;
}
if (c) break;
for(p = &LAST_TASK ; p > &FIRST_TASK ; --p)
if (*p)
(*p)->counter = ((*p)->counter >> 1) +
(*p)->priority;
}
switch_to(next);
}
首先是在for循环中,检查每个任务的alarm值,如果设置了alarm值,并且alarm值小于jiffies值(即已经过期),则在任务的signal位图中设置SIGALRM信号(即向任务发送SIGALRM信号),并将alarm值清零。