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