i945: fix tsc udelay()
[coreboot.git] / src / northbridge / intel / i945 / udelay.c
1 /*
2  * This file is part of the coreboot project.
3  *
4  * Copyright (C) 2007-2008 coresystems GmbH
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; version 2 of the License.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  */
19
20 #include <delay.h>
21 #include <stdint.h>
22 #include <cpu/x86/tsc.h>
23 #include <cpu/x86/msr.h>
24
25 /**
26  * Intel Core(tm) cpus always run the TSC at the maximum possible CPU clock
27  */
28
29 void udelay(u32 us)
30 {
31         u32 dword;
32         tsc_t tsc, tsc1, tscd;
33         msr_t msr;
34         u32 fsb = 0, divisor;
35         u32 d;                  /* ticks per us */
36         u32 dn = 0x1000000 / 2; /* how many us before we need to use hi */
37
38         msr = rdmsr(0xcd);
39         switch (msr.lo & 0x07) {
40         case 5:
41                 fsb = 400;
42                 break;
43         case 1:
44                 fsb = 533;
45                 break;
46         case 3:
47                 fsb = 667;
48                 break;
49         case 2:
50                 fsb = 800;
51                 break;
52         case 0:
53                 fsb = 1067;
54                 break;
55         case 4:
56                 fsb = 1333;
57                 break;
58         case 6:
59                 fsb = 1600;
60                 break;
61         }
62
63         msr = rdmsr(0x198);
64         divisor = (msr.hi >> 8) & 0x1f;
65
66         d = fsb * divisor;
67
68         tscd.hi = us / dn;
69         tscd.lo = (us - tscd.hi * dn) * d;
70
71         tsc1 = rdtsc();
72         dword = tsc1.lo + tscd.lo;
73         if ((dword < tsc1.lo) || (dword < tscd.lo)) {
74                 tsc1.hi++;
75         }
76         tsc1.lo = dword;
77         tsc1.hi += tscd.hi;
78
79         do {
80                 tsc = rdtsc();
81         } while ((tsc.hi < tsc1.hi)
82                  || ((tsc.hi == tsc1.hi) && (tsc.lo < tsc1.lo)));
83
84 }