2 pit8254 timer code for DOS programs.
3 Copyright (C) 2011-2014 John Tsiombikas <nuclear@member.fsf.org>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
26 #error borland unsupported
29 #define PIT_TIMER_INTR 8
30 #define DOS_TIMER_INTR 0x1c
32 /* macro to divide and round to the nearest integer */
33 #define DIV_ROUND(a, b) \
34 ((a) / (b) + ((a) % (b)) / ((b) / 2))
36 static void set_timer_reload(int reload_val);
37 static void cleanup(void);
38 static void __interrupt __far timer_irq();
39 static void __interrupt __far dos_timer_intr();
41 static void (__interrupt __far *prev_timer_intr)();
43 static unsigned long ticks;
44 static unsigned long tick_interval, ticks_per_dos_intr;
47 void init_timer(int res_hz)
52 int reload_val = DIV_ROUND(OSC_FREQ_HZ, res_hz);
53 set_timer_reload(reload_val);
55 tick_interval = DIV_ROUND(1000, res_hz);
56 ticks_per_dos_intr = DIV_ROUND(65535L, reload_val);
58 inum = PIT_TIMER_INTR;
59 prev_timer_intr = _dos_getvect(inum);
60 _dos_setvect(inum, timer_irq);
64 inum = DOS_TIMER_INTR;
65 prev_timer_intr = _dos_getvect(inum);
66 _dos_setvect(inum, dos_timer_intr);
73 static void cleanup(void)
75 if(!prev_timer_intr) {
76 return; /* init hasn't ran, there's nothing to cleanup */
80 if(inum == PIT_TIMER_INTR) {
81 /* restore the original timer frequency */
82 set_timer_reload(65535);
85 /* restore the original interrupt handler */
86 _dos_setvect(inum, prev_timer_intr);
90 void reset_timer(void)
95 unsigned long get_msec(void)
97 return ticks * tick_interval;
100 static void set_timer_reload(int reload_val)
102 outp(PORT_CMD, CMD_CHAN0 | CMD_ACCESS_BOTH | CMD_OP_SQWAVE);
103 outp(PORT_DATA0, reload_val & 0xff);
104 outp(PORT_DATA0, (reload_val >> 8) & 0xff);
107 static void __interrupt __far dos_timer_intr()
110 _chain_intr(prev_timer_intr); /* DOES NOT RETURN */
113 /* first PIC command port */
114 #define PIC1_CMD 0x20
115 /* end of interrupt control word */
116 #define OCW2_EOI (1 << 5)
118 static void __interrupt __far timer_irq()
120 static unsigned long dos_ticks;
124 if(++dos_ticks >= ticks_per_dos_intr) {
125 /* I suppose the dos irq handler does the EOI so I shouldn't
126 * do it if I am to call the previous function
129 _chain_intr(prev_timer_intr); /* XXX DOES NOT RETURN */
130 return; /* just for clarity */
133 /* send EOI to the PIC */
134 outp(PIC1_CMD, OCW2_EOI);