summaryrefslogtreecommitdiff
path: root/arch/x86/machine/pit.c
blob: d3fece511e650a92a27c8af5f3a60a773fd68e68 (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
84
85
86
87
88
89
/*
 * Copyright (c) 2011, 2012 Richard Braun.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <kern/assert.h>
#include <kern/init.h>
#include <machine/io.h>
#include <machine/pit.h>

/*
 * I/O ports.
 */
#define PIT_PORT_COUNTER0   0x40
#define PIT_PORT_MODE       0x43

/*
 * Mode control register bits.
 */
#define PIT_MODE_LATCH      0x00
#define PIT_MODE_RATE_GEN   0x04
#define PIT_MODE_RW_LSB     0x10
#define PIT_MODE_RW_MSB     0x20

/*
 * Native timer frequency.
 */
#define PIT_FREQ 1193182

/*
 * Maximum value of a counter.
 */
#define PIT_MAX_COUNT 0xffff

void __init
pit_setup(void)
{
    io_write_byte(PIT_PORT_MODE, PIT_MODE_RATE_GEN | PIT_MODE_RW_LSB
                                 | PIT_MODE_RW_MSB);
    io_write_byte(PIT_PORT_COUNTER0, PIT_MAX_COUNT & 0xff);
    io_write_byte(PIT_PORT_COUNTER0, PIT_MAX_COUNT >> 8);
}

static unsigned int
pit_read(void)
{
    unsigned int low, high;

    io_write_byte(PIT_PORT_MODE, PIT_MODE_LATCH);
    low = io_read_byte(PIT_PORT_COUNTER0);
    high = io_read_byte(PIT_PORT_COUNTER0);
    return (high << 8) | low;
}

void
pit_delay(unsigned long usecs)
{
    long total, prev, count, diff;

    assert(usecs != 0);

    /* TODO Avoid 64-bits conversion if result is known not to overflow */
    total = (long)(((long long)usecs * PIT_FREQ + 999999) / 1000000);
    prev = pit_read();

    do {
        count = pit_read();
        diff = prev - count;
        prev = count;

        if (diff < 0) {
            diff += PIT_MAX_COUNT;
        }

        total -= diff;
    } while (total > 0);
}