Implement tsc based delay timers, and use them throughout code.
[seabios.git] / src / clock.c
1 // 16bit code to handle system clocks.
2 //
3 // Copyright (C) 2008  Kevin O'Connor <kevin@koconnor.net>
4 // Copyright (C) 2002  MandrakeSoft S.A.
5 //
6 // This file may be distributed under the terms of the GNU GPLv3 license.
7
8 #include "biosvar.h" // SET_BDA
9 #include "util.h" // debug_enter
10 #include "disk.h" // floppy_tick
11 #include "cmos.h" // inb_cmos
12 #include "pic.h" // eoi_pic1
13 #include "bregs.h" // struct bregs
14
15 // RTC register flags
16 #define RTC_A_UIP 0x80
17 #define RTC_B_SET 0x80
18 #define RTC_B_PIE 0x40
19 #define RTC_B_AIE 0x20
20 #define RTC_B_UIE 0x10
21
22 // Bits for PORT_PS2_CTRLB
23 #define PPCB_T2GATE (1<<0)
24 #define PPCB_SPKR   (1<<1)
25 #define PPCB_T2OUT  (1<<5)
26
27 // Bits for PORT_PIT_MODE
28 #define PM_SEL_TIMER0   (0<<6)
29 #define PM_SEL_TIMER1   (1<<6)
30 #define PM_SEL_TIMER2   (2<<6)
31 #define PM_SEL_READBACK (3<<6)
32 #define PM_ACCESS_LATCH  (0<<4)
33 #define PM_ACCESS_LOBYTE (1<<4)
34 #define PM_ACCESS_HIBYTE (2<<4)
35 #define PM_ACCESS_WORD   (3<<4)
36 #define PM_MODE0 (0<<1)
37 #define PM_MODE1 (1<<1)
38 #define PM_MODE2 (2<<1)
39 #define PM_MODE3 (3<<1)
40 #define PM_MODE4 (4<<1)
41 #define PM_MODE5 (5<<1)
42 #define PM_CNT_BINARY (0<<0)
43 #define PM_CNT_BCD    (1<<0)
44
45
46 /****************************************************************
47  * TSC timer
48  ****************************************************************/
49
50 #define PIT_TICK_RATE 1193182 // Underlying HZ of PIT
51 #define CALIBRATE_COUNT 0x800 // Approx 1.7ms
52
53 extern u32 cpu_khz;
54 #if MODE16
55 u32 cpu_khz VISIBLE16;
56 #endif
57
58 static void
59 calibrate_tsc()
60 {
61     // Setup "timer2"
62     u8 orig = inb(PORT_PS2_CTRLB);
63     outb((orig & ~PPCB_SPKR) | PPCB_T2GATE, PORT_PS2_CTRLB);
64     /* binary, mode 0, LSB/MSB, Ch 2 */
65     outb(PM_SEL_TIMER2|PM_ACCESS_WORD|PM_MODE0|PM_CNT_BINARY, PORT_PIT_MODE);
66     /* LSB of ticks */
67     outb(CALIBRATE_COUNT & 0xFF, PORT_PIT_COUNTER2);
68     /* MSB of ticks */
69     outb(CALIBRATE_COUNT >> 8, PORT_PIT_COUNTER2);
70
71     u64 start = rdtscll();
72     while ((inb(PORT_PS2_CTRLB) & PPCB_T2OUT) == 0)
73         ;
74     u64 end = rdtscll();
75
76     // Restore PORT_PS2_CTRLB
77     outb(orig, PORT_PS2_CTRLB);
78
79     // Store calibrated cpu khz.
80     u64 diff = end - start;
81     dprintf(6, "tsc calibrate start=%u end=%u diff=%u\n"
82             , (u32)start, (u32)end, (u32)diff);
83     u32 hz = diff * PIT_TICK_RATE / CALIBRATE_COUNT;
84     SET_VAR(CS, cpu_khz, hz / 1000);
85
86     dprintf(1, "CPU Mhz=%u\n", hz / 1000000);
87 }
88
89 static void
90 tscsleep(u64 diff)
91 {
92     u64 start = rdtscll();
93     u64 end = start + diff;
94     while (rdtscll() < end)
95         cpu_relax();
96 }
97
98 void
99 ndelay(u32 count)
100 {
101     u32 khz = GET_VAR(CS, cpu_khz);
102     tscsleep(count * khz / 1000000);
103 }
104 void
105 udelay(u32 count)
106 {
107     u32 khz = GET_VAR(CS, cpu_khz);
108     tscsleep(count * khz / 1000);
109 }
110 void
111 mdelay(u32 count)
112 {
113     u32 khz = GET_VAR(CS, cpu_khz);
114     tscsleep(count * khz);
115 }
116
117
118 /****************************************************************
119  * Init
120  ****************************************************************/
121
122 static void
123 pit_setup()
124 {
125     // timer0: binary count, 16bit count, mode 2
126     outb(PM_SEL_TIMER0|PM_ACCESS_WORD|PM_MODE2|PM_CNT_BINARY, PORT_PIT_MODE);
127     // maximum count of 0000H = 18.2Hz
128     outb(0x0, PORT_PIT_COUNTER0);
129     outb(0x0, PORT_PIT_COUNTER0);
130 }
131
132 static u32
133 bcd2bin(u8 val)
134 {
135     return (val & 0xf) + ((val >> 4) * 10);
136 }
137
138 void
139 timer_setup()
140 {
141     dprintf(3, "init timer\n");
142     calibrate_tsc();
143     pit_setup();
144
145     u32 seconds = bcd2bin(inb_cmos(CMOS_RTC_SECONDS));
146     u32 ticks = (seconds * 18206507) / 1000000;
147     u32 minutes = bcd2bin(inb_cmos(CMOS_RTC_MINUTES));
148     ticks += (minutes * 10923904) / 10000;
149     u32 hours = bcd2bin(inb_cmos(CMOS_RTC_HOURS));
150     ticks += (hours * 65543427) / 1000;
151     SET_BDA(timer_counter, ticks);
152     SET_BDA(timer_rollover, 0);
153
154     enable_hwirq(0, entry_08);
155     enable_hwirq(8, entry_70);
156 }
157
158 static void
159 init_rtc()
160 {
161     outb_cmos(0x26, CMOS_STATUS_A);
162     outb_cmos(0x02, CMOS_STATUS_B);
163     inb_cmos(CMOS_STATUS_C);
164     inb_cmos(CMOS_STATUS_D);
165 }
166
167
168 /****************************************************************
169  * Standard clock functions
170  ****************************************************************/
171
172 static u8
173 rtc_updating()
174 {
175     // This function checks to see if the update-in-progress bit
176     // is set in CMOS Status Register A.  If not, it returns 0.
177     // If it is set, it tries to wait until there is a transition
178     // to 0, and will return 0 if such a transition occurs.  A 1
179     // is returned only after timing out.  The maximum period
180     // that this bit should be set is constrained to 244useconds.
181     // The count I use below guarantees coverage or more than
182     // this time, with any reasonable IPS setting.
183
184     u16 count = 25000;
185     while (--count != 0) {
186         if ( (inb_cmos(CMOS_STATUS_A) & 0x80) == 0 )
187             return 0;
188     }
189     return 1; // update-in-progress never transitioned to 0
190 }
191
192 // get current clock count
193 static void
194 handle_1a00(struct bregs *regs)
195 {
196     u32 ticks = GET_BDA(timer_counter);
197     regs->cx = ticks >> 16;
198     regs->dx = ticks;
199     regs->al = GET_BDA(timer_rollover);
200     SET_BDA(timer_rollover, 0); // reset flag
201     set_success(regs);
202 }
203
204 // Set Current Clock Count
205 static void
206 handle_1a01(struct bregs *regs)
207 {
208     u32 ticks = (regs->cx << 16) | regs->dx;
209     SET_BDA(timer_counter, ticks);
210     SET_BDA(timer_rollover, 0); // reset flag
211     regs->ah = 0;
212     set_success(regs);
213 }
214
215 // Read CMOS Time
216 static void
217 handle_1a02(struct bregs *regs)
218 {
219     if (rtc_updating()) {
220         set_fail(regs);
221         return;
222     }
223
224     regs->dh = inb_cmos(CMOS_RTC_SECONDS);
225     regs->cl = inb_cmos(CMOS_RTC_MINUTES);
226     regs->ch = inb_cmos(CMOS_RTC_HOURS);
227     regs->dl = inb_cmos(CMOS_STATUS_B) & 0x01;
228     regs->ah = 0;
229     regs->al = regs->ch;
230     set_success(regs);
231 }
232
233 // Set CMOS Time
234 static void
235 handle_1a03(struct bregs *regs)
236 {
237     // Using a debugger, I notice the following masking/setting
238     // of bits in Status Register B, by setting Reg B to
239     // a few values and getting its value after INT 1A was called.
240     //
241     //        try#1       try#2       try#3
242     // before 1111 1101   0111 1101   0000 0000
243     // after  0110 0010   0110 0010   0000 0010
244     //
245     // Bit4 in try#1 flipped in hardware (forced low) due to bit7=1
246     // My assumption: RegB = ((RegB & 01100000b) | 00000010b)
247     if (rtc_updating()) {
248         init_rtc();
249         // fall through as if an update were not in progress
250     }
251     outb_cmos(regs->dh, CMOS_RTC_SECONDS);
252     outb_cmos(regs->cl, CMOS_RTC_MINUTES);
253     outb_cmos(regs->ch, CMOS_RTC_HOURS);
254     // Set Daylight Savings time enabled bit to requested value
255     u8 val8 = (inb_cmos(CMOS_STATUS_B) & 0x60) | 0x02 | (regs->dl & 0x01);
256     outb_cmos(val8, CMOS_STATUS_B);
257     regs->ah = 0;
258     regs->al = val8; // val last written to Reg B
259     set_success(regs);
260 }
261
262 // Read CMOS Date
263 static void
264 handle_1a04(struct bregs *regs)
265 {
266     regs->ah = 0;
267     if (rtc_updating()) {
268         set_fail(regs);
269         return;
270     }
271     regs->cl = inb_cmos(CMOS_RTC_YEAR);
272     regs->dh = inb_cmos(CMOS_RTC_MONTH);
273     regs->dl = inb_cmos(CMOS_RTC_DAY_MONTH);
274     regs->ch = inb_cmos(CMOS_CENTURY);
275     regs->al = regs->ch;
276     set_success(regs);
277 }
278
279 // Set CMOS Date
280 static void
281 handle_1a05(struct bregs *regs)
282 {
283     // Using a debugger, I notice the following masking/setting
284     // of bits in Status Register B, by setting Reg B to
285     // a few values and getting its value after INT 1A was called.
286     //
287     //        try#1       try#2       try#3       try#4
288     // before 1111 1101   0111 1101   0000 0010   0000 0000
289     // after  0110 1101   0111 1101   0000 0010   0000 0000
290     //
291     // Bit4 in try#1 flipped in hardware (forced low) due to bit7=1
292     // My assumption: RegB = (RegB & 01111111b)
293     if (rtc_updating()) {
294         init_rtc();
295         set_fail(regs);
296         return;
297     }
298     outb_cmos(regs->cl, CMOS_RTC_YEAR);
299     outb_cmos(regs->dh, CMOS_RTC_MONTH);
300     outb_cmos(regs->dl, CMOS_RTC_DAY_MONTH);
301     outb_cmos(regs->ch, CMOS_CENTURY);
302     // clear halt-clock bit
303     u8 val8 = inb_cmos(CMOS_STATUS_B) & ~RTC_B_SET;
304     outb_cmos(val8, CMOS_STATUS_B);
305     regs->ah = 0;
306     regs->al = val8; // AL = val last written to Reg B
307     set_success(regs);
308 }
309
310 // Set Alarm Time in CMOS
311 static void
312 handle_1a06(struct bregs *regs)
313 {
314     // Using a debugger, I notice the following masking/setting
315     // of bits in Status Register B, by setting Reg B to
316     // a few values and getting its value after INT 1A was called.
317     //
318     //        try#1       try#2       try#3
319     // before 1101 1111   0101 1111   0000 0000
320     // after  0110 1111   0111 1111   0010 0000
321     //
322     // Bit4 in try#1 flipped in hardware (forced low) due to bit7=1
323     // My assumption: RegB = ((RegB & 01111111b) | 00100000b)
324     u8 val8 = inb_cmos(CMOS_STATUS_B); // Get Status Reg B
325     regs->ax = 0;
326     if (val8 & 0x20) {
327         // Alarm interrupt enabled already
328         set_fail(regs);
329         return;
330     }
331     if (rtc_updating()) {
332         init_rtc();
333         // fall through as if an update were not in progress
334     }
335     outb_cmos(regs->dh, CMOS_RTC_SECONDS_ALARM);
336     outb_cmos(regs->cl, CMOS_RTC_MINUTES_ALARM);
337     outb_cmos(regs->ch, CMOS_RTC_HOURS_ALARM);
338     // enable Status Reg B alarm bit, clear halt clock bit
339     outb_cmos((val8 & ~RTC_B_SET) | RTC_B_AIE, CMOS_STATUS_B);
340     set_success(regs);
341 }
342
343 // Turn off Alarm
344 static void
345 handle_1a07(struct bregs *regs)
346 {
347     // Using a debugger, I notice the following masking/setting
348     // of bits in Status Register B, by setting Reg B to
349     // a few values and getting its value after INT 1A was called.
350     //
351     //        try#1       try#2       try#3       try#4
352     // before 1111 1101   0111 1101   0010 0000   0010 0010
353     // after  0100 0101   0101 0101   0000 0000   0000 0010
354     //
355     // Bit4 in try#1 flipped in hardware (forced low) due to bit7=1
356     // My assumption: RegB = (RegB & 01010111b)
357     u8 val8 = inb_cmos(CMOS_STATUS_B); // Get Status Reg B
358     // clear clock-halt bit, disable alarm bit
359     outb_cmos(val8 & ~(RTC_B_SET|RTC_B_AIE), CMOS_STATUS_B);
360     regs->ah = 0;
361     regs->al = val8; // val last written to Reg B
362     set_success(regs);
363 }
364
365 // Unsupported
366 static void
367 handle_1aXX(struct bregs *regs)
368 {
369     set_fail(regs);
370 }
371
372 // INT 1Ah Time-of-day Service Entry Point
373 void VISIBLE16
374 handle_1a(struct bregs *regs)
375 {
376     debug_enter(regs, DEBUG_HDL_1a);
377     switch (regs->ah) {
378     case 0x00: handle_1a00(regs); break;
379     case 0x01: handle_1a01(regs); break;
380     case 0x02: handle_1a02(regs); break;
381     case 0x03: handle_1a03(regs); break;
382     case 0x04: handle_1a04(regs); break;
383     case 0x05: handle_1a05(regs); break;
384     case 0x06: handle_1a06(regs); break;
385     case 0x07: handle_1a07(regs); break;
386     case 0xb1: handle_1ab1(regs); break;
387     default:   handle_1aXX(regs); break;
388     }
389 }
390
391 // User Timer Tick
392 void VISIBLE16
393 handle_1c()
394 {
395     debug_isr(DEBUG_ISR_1c);
396 }
397
398 // INT 08h System Timer ISR Entry Point
399 void VISIBLE16
400 handle_08()
401 {
402     debug_isr(DEBUG_ISR_08);
403     irq_enable();
404
405     floppy_tick();
406
407     u32 counter = GET_BDA(timer_counter);
408     counter++;
409     // compare to one days worth of timer ticks at 18.2 hz
410     if (counter >= 0x001800B0) {
411         // there has been a midnight rollover at this point
412         counter = 0;
413         SET_BDA(timer_rollover, GET_BDA(timer_rollover) + 1);
414     }
415
416     SET_BDA(timer_counter, counter);
417
418     // chain to user timer tick INT #0x1c
419     struct bregs br;
420     memset(&br, 0, sizeof(br));
421     call16_int(0x1c, &br);
422
423     irq_disable();
424
425     eoi_pic1();
426 }
427
428
429 /****************************************************************
430  * Periodic timer
431  ****************************************************************/
432
433 static int
434 set_usertimer(u32 usecs, u16 seg, u16 offset)
435 {
436     if (GET_BDA(rtc_wait_flag) & RWS_WAIT_PENDING)
437         return -1;
438
439     // Interval not already set.
440     SET_BDA(rtc_wait_flag, RWS_WAIT_PENDING);  // Set status byte.
441     SET_BDA(ptr_user_wait_complete_flag, (seg << 16) | offset);
442     SET_BDA(user_wait_timeout, usecs);
443
444     // Turn on the Periodic Interrupt timer
445     u8 bRegister = inb_cmos(CMOS_STATUS_B);
446     outb_cmos(bRegister | RTC_B_PIE, CMOS_STATUS_B);
447
448     return 0;
449 }
450
451 static void
452 clear_usertimer()
453 {
454     // Turn off status byte.
455     SET_BDA(rtc_wait_flag, 0);
456     // Clear the Periodic Interrupt.
457     u8 bRegister = inb_cmos(CMOS_STATUS_B);
458     outb_cmos(bRegister & ~RTC_B_PIE, CMOS_STATUS_B);
459 }
460
461 #define RET_ECLOCKINUSE  0x83
462
463 // Wait for CX:DX microseconds
464 void
465 handle_1586(struct bregs *regs)
466 {
467     // Use the rtc to wait for the specified time.
468     u8 statusflag = 0;
469     u32 count = (regs->cx << 16) | regs->dx;
470     int ret = set_usertimer(count, GET_SEG(SS), (u32)&statusflag);
471     if (ret) {
472         set_code_fail(regs, RET_ECLOCKINUSE);
473         return;
474     }
475     irq_enable();
476     while (!statusflag)
477         cpu_relax();
478     irq_disable();
479     set_success(regs);
480 }
481
482 // Set Interval requested.
483 static void
484 handle_158300(struct bregs *regs)
485 {
486     int ret = set_usertimer((regs->cx << 16) | regs->dx, regs->es, regs->bx);
487     if (ret)
488         // Interval already set.
489         set_code_fail(regs, RET_EUNSUPPORTED);
490     else
491         set_success(regs);
492 }
493
494 // Clear interval requested
495 static void
496 handle_158301(struct bregs *regs)
497 {
498     clear_usertimer();
499     set_success(regs);
500 }
501
502 static void
503 handle_1583XX(struct bregs *regs)
504 {
505     set_code_fail(regs, RET_EUNSUPPORTED);
506     regs->al--;
507 }
508
509 void
510 handle_1583(struct bregs *regs)
511 {
512     switch (regs->al) {
513     case 0x00: handle_158300(regs); break;
514     case 0x01: handle_158301(regs); break;
515     default:   handle_1583XX(regs); break;
516     }
517 }
518
519 // int70h: IRQ8 - CMOS RTC
520 void VISIBLE16
521 handle_70()
522 {
523     debug_isr(DEBUG_ISR_70);
524
525     // Check which modes are enabled and have occurred.
526     u8 registerB = inb_cmos(CMOS_STATUS_B);
527     u8 registerC = inb_cmos(CMOS_STATUS_C);
528
529     if (!(registerB & (RTC_B_PIE|RTC_B_AIE)))
530         goto done;
531     if (registerC & 0x20) {
532         // Handle Alarm Interrupt.
533         struct bregs br;
534         memset(&br, 0, sizeof(br));
535         call16_int(0x4a, &br);
536         irq_disable();
537     }
538     if (!(registerC & 0x40))
539         goto done;
540
541     // Handle Periodic Interrupt.
542
543     if (!GET_BDA(rtc_wait_flag))
544         goto done;
545
546     // Wait Interval (Int 15, AH=83) active.
547     u32 time = GET_BDA(user_wait_timeout);  // Time left in microseconds.
548     if (time < 0x3D1) {
549         // Done waiting - write to specified flag byte.
550         u32 segoff = GET_BDA(ptr_user_wait_complete_flag);
551         u16 segment = segoff >> 16;
552         u16 offset = segoff & 0xffff;
553         u8 oldval = GET_FARVAR(segment, *(u8*)(offset+0));
554         SET_FARVAR(segment, *(u8*)(offset+0), oldval | 0x80);
555
556         clear_usertimer();
557     } else {
558         // Continue waiting.
559         time -= 0x3D1;
560         SET_BDA(user_wait_timeout, time);
561     }
562
563 done:
564     eoi_pic2();
565 }