|
| 1 | +#include "pit.h" |
| 2 | + |
| 3 | +static ISRHandler s_pit_handler = NULL; |
| 4 | + |
| 5 | +void __pit_handler(registers_t reg) |
| 6 | +{ |
| 7 | + if (s_pit_handler != NULL) |
| 8 | + s_pit_handler(reg); |
| 9 | +} |
| 10 | + |
| 11 | +void __pit_cmd_tx(u8 cmd) |
| 12 | +{ |
| 13 | + outb(PIT_REG_COMMAND, cmd); |
| 14 | +} |
| 15 | + |
| 16 | +void __pit_data_tx(u8 data, u8 counter) |
| 17 | +{ |
| 18 | + u8 port = (counter == PIT_OCW_COUNTER_0) ? PIT_REG_COUNTER0 : ((counter == PIT_OCW_COUNTER_1) ? PIT_REG_COUNTER1 : PIT_REG_COUNTER2); |
| 19 | + outb(port, data); |
| 20 | +} |
| 21 | + |
| 22 | +void __pit_start_counter(u32 freq, u8 counter, u8 mode) |
| 23 | +{ |
| 24 | + if (freq == 0) |
| 25 | + return; |
| 26 | + |
| 27 | + BIOSPrintf("PIT counter %d started with frequency %dHz\n", counter / 0x40, freq); |
| 28 | + |
| 29 | + uint16_t divisor = (uint16_t)(1193181 / (uint16_t)freq); |
| 30 | + |
| 31 | + // send operational command words |
| 32 | + uint8_t ocw = 0; |
| 33 | + ocw = (ocw & ~PIT_OCW_MASK_MODE) | mode; |
| 34 | + ocw = (ocw & ~PIT_OCW_MASK_RL) | PIT_OCW_RL_DATA; |
| 35 | + ocw = (ocw & ~PIT_OCW_MASK_COUNTER) | counter; |
| 36 | + __pit_cmd_tx(ocw); |
| 37 | + |
| 38 | + // set frequency rate |
| 39 | + __pit_data_tx(divisor & 0xff, 0); |
| 40 | + __pit_data_tx((divisor >> 8) & 0xff, 0); |
| 41 | +} |
| 42 | + |
| 43 | +void PITInit() |
| 44 | +{ |
| 45 | + BIOSPrintf("Initializing PIT...\n"); |
| 46 | + |
| 47 | + ISRRegisterHandler(IRQ_0, __pit_handler); |
| 48 | + |
| 49 | + __pit_start_counter(60, PIT_OCW_COUNTER_0, PIT_OCW_MODE_SQUAREWAVEGEN); |
| 50 | + |
| 51 | + BIOSPrintf("PIT initialized\n"); |
| 52 | +} |
| 53 | + |
| 54 | +void PITAttach(ISRHandler handler) |
| 55 | +{ |
| 56 | + if (s_pit_handler != NULL) |
| 57 | + { |
| 58 | + BIOSPrint("Warning: PIT handler overwritten\n"); |
| 59 | + } |
| 60 | + s_pit_handler = handler; |
| 61 | +} |
| 62 | + |
| 63 | +void PITDetach() |
| 64 | +{ |
| 65 | + s_pit_handler = NULL; |
| 66 | +} |
0 commit comments