summaryrefslogtreecommitdiff
path: root/kernel/drivers/pit.c
blob: ac4e55598088e7f8090a4e754f98f57804a27102 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include "pit.h"
#include <arch/i386/tsc.h>

#define PIT_IO_CHANNEL_0 0x40
#define PIT_IO_MODE_COMMAND 0x43

u64 clock_num_ms_ticks = 0;
u32 pit_counter = 0;
u32 switch_counter = 0;
u16 hertz;

u64 cpu_mhz = 0;
u64 pit_num_ms(void) {
  return (get_tsc()) / (cpu_mhz * 1000);
}

u16 read_pit_count(void) {
  u16 count = 0;

  outb(PIT_IO_MODE_COMMAND, 0x0 /*0b00000000*/);

  count = inb(PIT_IO_CHANNEL_0);
  count |= inb(PIT_IO_CHANNEL_0) << 8;

  return count;
}

void set_pit_count(u16 _hertz) {
  cpu_mhz = get_hz() / 10000;

  hertz = _hertz;
  u16 divisor = 1193180 / hertz;

  /*
   * 0b00110110
   *   ^^
   * channel - 0
   *     ^^
   * r/w mode - LSB then MSB
   *       ^^^
   * mode - 3 Square Wave Mode
   *          ^
   * BCD - no
   */
  outb(PIT_IO_MODE_COMMAND, 0x36 /*0b00110110*/);
  outb(PIT_IO_CHANNEL_0, divisor & 0xFF);
  outb(PIT_IO_CHANNEL_0, (divisor & 0xFF00) >> 8);
}

int last_flush = 0;

u64 last_tsc = 0;

extern int is_switching_tasks;
void int_clock(reg_t *regs) {
  u64 current_tsc = get_tsc();

  u64 delta = (current_tsc - last_tsc) / (cpu_mhz * 1000);

  clock_num_ms_ticks += delta;

  last_tsc = current_tsc;

  switch_counter++;
  if (clock_num_ms_ticks - last_flush > 50) {
    tcp_flush_acks();
    last_flush = clock_num_ms_ticks;
  }
  if (switch_counter >= hertz) {
    EOI(0x20);
    switch_counter = 0;
    if (is_switching_tasks) {
      return;
    }
    switch_task();
  } else {
    EOI(0x20);
  }
}

void pit_install(void) {
  install_handler(int_clock, INT_32_INTERRUPT_GATE(0x3), 0x20);
}