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