21 #define PIT_TIMER_INTR 8
22 #define DOS_TIMER_INTR 0x1c
24 /* macro to divide and round to the nearest integer */
25 #define DIV_ROUND(a, b) \
26 ((a) / (b) + ((a) % (b)) / ((b) / 2))
28 static void set_timer_reload(int reload_val);
29 static void cleanup(void);
32 #define INTERRUPT __interrupt __far
34 static void INTERRUPT dos_timer_intr();
36 static void (INTERRUPT *prev_timer_intr)();
42 static _go32_dpmi_seginfo intr, prev_intr;
44 #define outp(p, v) outportb(p, v)
47 static void INTERRUPT timer_irq();
49 static volatile unsigned long ticks;
50 static unsigned long tick_interval, ticks_per_dos_intr;
53 void init_timer(int res_hz)
58 int reload_val = DIV_ROUND(OSC_FREQ_HZ, res_hz);
59 set_timer_reload(reload_val);
61 tick_interval = DIV_ROUND(1000, res_hz);
62 ticks_per_dos_intr = DIV_ROUND(65535L, reload_val);
64 inum = PIT_TIMER_INTR;
66 prev_timer_intr = _dos_getvect(inum);
67 _dos_setvect(inum, timer_irq);
70 _go32_dpmi_get_protected_mode_interrupt_vector(inum, &prev_intr);
71 intr.pm_offset = (intptr_t)timer_irq;
72 intr.pm_selector = _go32_my_cs();
73 _go32_dpmi_allocate_iret_wrapper(&intr);
74 _go32_dpmi_set_protected_mode_interrupt_vector(inum, &intr);
79 inum = DOS_TIMER_INTR;
81 prev_timer_intr = _dos_getvect(inum);
82 _dos_setvect(inum, dos_timer_intr);
93 static void cleanup(void)
96 return; /* init hasn't ran, there's nothing to cleanup */
100 if(inum == PIT_TIMER_INTR) {
101 /* restore the original timer frequency */
102 set_timer_reload(65535);
105 /* restore the original interrupt handler */
107 _dos_setvect(inum, prev_timer_intr);
110 _go32_dpmi_set_protected_mode_interrupt_vector(inum, &prev_intr);
111 _go32_dpmi_free_iret_wrapper(&intr);
117 void reset_timer(void)
122 unsigned long get_msec(void)
124 return ticks * tick_interval;
127 void sleep_msec(unsigned long msec)
129 unsigned long wakeup_time = ticks + msec / tick_interval;
130 while(ticks < wakeup_time) {
137 static void set_timer_reload(int reload_val)
139 outp(PORT_CMD, CMD_CHAN0 | CMD_ACCESS_BOTH | CMD_OP_SQWAVE);
140 outp(PORT_DATA0, reload_val & 0xff);
141 outp(PORT_DATA0, (reload_val >> 8) & 0xff);
145 static void INTERRUPT dos_timer_intr()
148 _chain_intr(prev_timer_intr); /* DOES NOT RETURN */
152 /* first PIC command port */
153 #define PIC1_CMD 0x20
154 /* end of interrupt control word */
155 #define OCW2_EOI (1 << 5)
157 static void INTERRUPT timer_irq()
159 static unsigned long dos_ticks;
164 if(++dos_ticks >= ticks_per_dos_intr) {
165 /* I suppose the dos irq handler does the EOI so I shouldn't
166 * do it if I am to call the previous function
169 _chain_intr(prev_timer_intr); /* XXX DOES NOT RETURN */
170 return; /* just for clarity */
174 /* send EOI to the PIC */
175 outp(PIC1_CMD, OCW2_EOI);