826f5b6ad47a80b9e459c863e1b08925e2aa6ff7
[coreboot.git] / src / cpu / x86 / lapic / apic_timer.c
1 /*
2  * This file is part of the coreboot project.
3  *
4  * Copyright (C) 2007 Advanced Micro Devices, Inc.
5  * Copyright (C) 2009 coresystems GmbH
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; version 2 of the License.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19  */
20
21 #include <stdint.h>
22 #include <delay.h>
23 #include <cpu/x86/msr.h>
24 #include <cpu/x86/lapic.h>
25
26 /* NOTE: This code uses global variables, so it can not be used during
27  * memory init.
28  */
29
30 #define FSB_CLOCK_STS 0xcd
31
32 static u32 timer_fsb = 200; // default to 200MHz
33
34 void init_timer(void)
35 {
36         msr_t fsb_clock_sts;
37
38         /* Set the apic timer to no interrupts and periodic mode */
39         lapic_write(LAPIC_LVTT, (LAPIC_LVT_TIMER_PERIODIC | LAPIC_LVT_MASKED));
40
41         /* Set the divider to 1, no divider */
42         lapic_write(LAPIC_TDCR, LAPIC_TDR_DIV_1);
43
44         /* Set the initial counter to 0xffffffff */
45         lapic_write(LAPIC_TMICT, 0xffffffff);
46
47         /* Set FSB frequency to a reasonable value */
48         fsb_clock_sts = rdmsr(FSB_CLOCK_STS);
49         switch ((fsb_clock_sts.lo >> 4) & 0x07) {
50         case 0: timer_fsb = 266; break;
51         case 1: timer_fsb = 133; break;
52         case 2: timer_fsb = 200; break;
53         case 3: timer_fsb = 166; break;
54         case 5: timer_fsb = 100; break;
55         }
56 }
57
58 void udelay(u32 usecs)
59 {
60         u32 start, value, ticks;
61         /* Calculate the number of ticks to run, our FSB runs at timer_fsb Mhz */
62         ticks = usecs * timer_fsb;
63         start = lapic_read(LAPIC_TMCCT);
64         do {
65                 value = lapic_read(LAPIC_TMCCT);
66         } while((start - value) < ticks);
67 }