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