1/*
2 * Copyright 2014, General Dynamics C4 Systems
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 */
6
7#include <linker.h>
8#include <machine/io.h>
9#include <plat/machine/pit.h>
10
11/* PIT (i8253) registers */
12#define PIT_MODE 0x43
13#define PIT_CH0  0x40
14
15/* Count frequency in Hz */
16#define PIT_HZ 1193182
17
18BOOT_CODE void pit_init(void)
19{
20    uint16_t divisor = (PIT_HZ * PIT_WRAPAROUND_MS) / 1000;
21
22    out8(PIT_MODE, 0x34);          /* Set mode 2 and wait for divisor bytes */
23    out8(PIT_CH0, divisor & 0xff); /* Set low byte of divisor */
24    out8(PIT_CH0, divisor >> 8);   /* Set high byte of divisor */
25}
26
27BOOT_CODE void pit_wait_wraparound(void)
28{
29    uint16_t count;
30    uint16_t count_old;
31
32    out8(PIT_MODE, 0x00);
33    count = in8(PIT_CH0);
34    count |= (in8(PIT_CH0) << 8);
35    count_old = count;
36
37    while (count <= count_old) {
38        count_old = count;
39        out8(PIT_MODE, 0x00);
40        count = in8(PIT_CH0);
41        count |= (in8(PIT_CH0) << 8);
42    }
43}
44