20 #define PIT_TIMER_INTR 8
21 #define DOS_TIMER_INTR 0x1c
23 /* macro to divide and round to the nearest integer */
24 #define DIV_ROUND(a, b) \
25 ((a) / (b) + ((a) % (b)) / ((b) / 2))
27 static void set_timer_reload(int reload_val);
28 static void cleanup(void);
31 #define INTERRUPT __interrupt __far
33 static void INTERRUPT dos_timer_intr();
35 static void (INTERRUPT *prev_timer_intr)();
41 static _go32_dpmi_seginfo intr, prev_intr;
43 #define outp(p, v) outportb(p, v)
46 static void INTERRUPT timer_irq();
48 static unsigned long ticks;
49 static unsigned long tick_interval, ticks_per_dos_intr;
52 void init_timer(int res_hz)
57 int reload_val = DIV_ROUND(OSC_FREQ_HZ, res_hz);
58 set_timer_reload(reload_val);
60 tick_interval = DIV_ROUND(1000, res_hz);
61 ticks_per_dos_intr = DIV_ROUND(65535L, reload_val);
63 inum = PIT_TIMER_INTR;
65 prev_timer_intr = _dos_getvect(inum);
66 _dos_setvect(inum, timer_irq);
69 _go32_dpmi_get_protected_mode_interrupt_vector(inum, &prev_intr);
70 intr.pm_offset = (intptr_t)timer_irq;
71 intr.pm_selector = _go32_my_cs();
72 _go32_dpmi_allocate_iret_wrapper(&intr);
73 _go32_dpmi_set_protected_mode_interrupt_vector(inum, &intr);
78 inum = DOS_TIMER_INTR;
80 prev_timer_intr = _dos_getvect(inum);
81 _dos_setvect(inum, dos_timer_intr);
92 static void cleanup(void)
95 return; /* init hasn't ran, there's nothing to cleanup */
99 if(inum == PIT_TIMER_INTR) {
100 /* restore the original timer frequency */
101 set_timer_reload(65535);
104 /* restore the original interrupt handler */
106 _dos_setvect(inum, prev_timer_intr);
109 _go32_dpmi_set_protected_mode_interrupt_vector(inum, &prev_intr);
110 _go32_dpmi_free_iret_wrapper(&intr);
116 void reset_timer(void)
121 unsigned long get_msec(void)
123 return ticks * tick_interval;
126 static void set_timer_reload(int reload_val)
128 outp(PORT_CMD, CMD_CHAN0 | CMD_ACCESS_BOTH | CMD_OP_SQWAVE);
129 outp(PORT_DATA0, reload_val & 0xff);
130 outp(PORT_DATA0, (reload_val >> 8) & 0xff);
134 static void INTERRUPT dos_timer_intr()
137 _chain_intr(prev_timer_intr); /* DOES NOT RETURN */
141 /* first PIC command port */
142 #define PIC1_CMD 0x20
143 /* end of interrupt control word */
144 #define OCW2_EOI (1 << 5)
146 static void INTERRUPT timer_irq()
148 static unsigned long dos_ticks;
153 if(++dos_ticks >= ticks_per_dos_intr) {
154 /* I suppose the dos irq handler does the EOI so I shouldn't
155 * do it if I am to call the previous function
158 _chain_intr(prev_timer_intr); /* XXX DOES NOT RETURN */
159 return; /* just for clarity */
163 /* send EOI to the PIC */
164 outp(PIC1_CMD, OCW2_EOI);