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