3bdf8c3b11b4cad46663422823cb0d04a357f8ed
[coreboot.git] / src / northbridge / amd / amdk8 / raminit.c
1 /*      This should be done by Eric
2         2004.11 yhlu add 4 rank DIMM support
3         2004.12 yhlu add D0 support
4         2005.02 yhlu add E0 memory hole support
5 */
6
7 #include <cpu/x86/mem.h>
8 #include <cpu/x86/cache.h>
9 #include <cpu/x86/mtrr.h>
10 #include "raminit.h"
11 #include "amdk8.h"
12
13 #if (CONFIG_LB_MEM_TOPK & (CONFIG_LB_MEM_TOPK -1)) != 0
14 # error "CONFIG_LB_MEM_TOPK must be a power of 2"
15 #endif
16
17 #ifndef K8_4RANK_DIMM_SUPPORT
18 #define K8_4RANK_DIMM_SUPPORT 0
19 #endif
20
21 #if 1
22 static void setup_resource_map(const unsigned int *register_values, int max)
23 {
24         int i;
25 //      print_debug("setting up resource map....");
26 #if 0
27         print_debug("\r\n");
28 #endif
29         for(i = 0; i < max; i += 3) {
30                 device_t dev;
31                 unsigned where;
32                 unsigned long reg;
33 #if 0
34                 print_debug_hex32(register_values[i]);
35                 print_debug(" <-");
36                 print_debug_hex32(register_values[i+2]);
37                 print_debug("\r\n");
38 #endif
39                 dev = register_values[i] & ~0xff;
40                 where = register_values[i] & 0xff;
41                 reg = pci_read_config32(dev, where);
42                 reg &= register_values[i+1];
43                 reg |= register_values[i+2];
44                 pci_write_config32(dev, where, reg);
45 #if 0
46                 reg = pci_read_config32(register_values[i]);
47                 reg &= register_values[i+1];
48                 reg |= register_values[i+2] & ~register_values[i+1];
49                 pci_write_config32(register_values[i], reg);
50 #endif
51         }
52 //      print_debug("done.\r\n");
53 }
54 #endif
55
56 static int controller_present(const struct mem_controller *ctrl)
57 {
58         return pci_read_config32(ctrl->f0, 0) == 0x11001022;
59 }
60
61 static void sdram_set_registers(const struct mem_controller *ctrl)
62 {
63         static const unsigned int register_values[] = {
64
65         /* Careful set limit registers before base registers which contain the enables */
66         /* DRAM Limit i Registers
67          * F1:0x44 i = 0
68          * F1:0x4C i = 1
69          * F1:0x54 i = 2
70          * F1:0x5C i = 3
71          * F1:0x64 i = 4
72          * F1:0x6C i = 5
73          * F1:0x74 i = 6
74          * F1:0x7C i = 7
75          * [ 2: 0] Destination Node ID
76          *         000 = Node 0
77          *         001 = Node 1
78          *         010 = Node 2
79          *         011 = Node 3
80          *         100 = Node 4
81          *         101 = Node 5
82          *         110 = Node 6
83          *         111 = Node 7
84          * [ 7: 3] Reserved
85          * [10: 8] Interleave select
86          *         specifies the values of A[14:12] to use with interleave enable.
87          * [15:11] Reserved
88          * [31:16] DRAM Limit Address i Bits 39-24
89          *         This field defines the upper address bits of a 40 bit  address
90          *         that define the end of the DRAM region.
91          */
92         PCI_ADDR(0, 0x18, 1, 0x44), 0x0000f8f8, 0x00000000,
93         PCI_ADDR(0, 0x18, 1, 0x4C), 0x0000f8f8, 0x00000001,
94         PCI_ADDR(0, 0x18, 1, 0x54), 0x0000f8f8, 0x00000002,
95         PCI_ADDR(0, 0x18, 1, 0x5C), 0x0000f8f8, 0x00000003,
96         PCI_ADDR(0, 0x18, 1, 0x64), 0x0000f8f8, 0x00000004,
97         PCI_ADDR(0, 0x18, 1, 0x6C), 0x0000f8f8, 0x00000005,
98         PCI_ADDR(0, 0x18, 1, 0x74), 0x0000f8f8, 0x00000006,
99         PCI_ADDR(0, 0x18, 1, 0x7C), 0x0000f8f8, 0x00000007,
100         /* DRAM Base i Registers
101          * F1:0x40 i = 0
102          * F1:0x48 i = 1
103          * F1:0x50 i = 2
104          * F1:0x58 i = 3
105          * F1:0x60 i = 4
106          * F1:0x68 i = 5
107          * F1:0x70 i = 6
108          * F1:0x78 i = 7
109          * [ 0: 0] Read Enable
110          *         0 = Reads Disabled
111          *         1 = Reads Enabled
112          * [ 1: 1] Write Enable
113          *         0 = Writes Disabled
114          *         1 = Writes Enabled
115          * [ 7: 2] Reserved
116          * [10: 8] Interleave Enable
117          *         000 = No interleave
118          *         001 = Interleave on A[12] (2 nodes)
119          *         010 = reserved
120          *         011 = Interleave on A[12] and A[14] (4 nodes)
121          *         100 = reserved
122          *         101 = reserved
123          *         110 = reserved
124          *         111 = Interleve on A[12] and A[13] and A[14] (8 nodes)
125          * [15:11] Reserved
126          * [13:16] DRAM Base Address i Bits 39-24
127          *         This field defines the upper address bits of a 40-bit address
128          *         that define the start of the DRAM region.
129          */
130         PCI_ADDR(0, 0x18, 1, 0x40), 0x0000f8fc, 0x00000000,
131         PCI_ADDR(0, 0x18, 1, 0x48), 0x0000f8fc, 0x00000000,
132         PCI_ADDR(0, 0x18, 1, 0x50), 0x0000f8fc, 0x00000000,
133         PCI_ADDR(0, 0x18, 1, 0x58), 0x0000f8fc, 0x00000000,
134         PCI_ADDR(0, 0x18, 1, 0x60), 0x0000f8fc, 0x00000000,
135         PCI_ADDR(0, 0x18, 1, 0x68), 0x0000f8fc, 0x00000000,
136         PCI_ADDR(0, 0x18, 1, 0x70), 0x0000f8fc, 0x00000000,
137         PCI_ADDR(0, 0x18, 1, 0x78), 0x0000f8fc, 0x00000000,
138
139         /* DRAM CS Base Address i Registers
140          * F2:0x40 i = 0
141          * F2:0x44 i = 1
142          * F2:0x48 i = 2
143          * F2:0x4C i = 3
144          * F2:0x50 i = 4
145          * F2:0x54 i = 5
146          * F2:0x58 i = 6
147          * F2:0x5C i = 7
148          * [ 0: 0] Chip-Select Bank Enable
149          *         0 = Bank Disabled
150          *         1 = Bank Enabled
151          * [ 8: 1] Reserved
152          * [15: 9] Base Address (19-13)
153          *         An optimization used when all DIMM are the same size...
154          * [20:16] Reserved
155          * [31:21] Base Address (35-25)
156          *         This field defines the top 11 addresses bit of a 40-bit
157          *         address that define the memory address space.  These
158          *         bits decode 32-MByte blocks of memory.
159          */
160         PCI_ADDR(0, 0x18, 2, 0x40), 0x001f01fe, 0x00000000,
161         PCI_ADDR(0, 0x18, 2, 0x44), 0x001f01fe, 0x00000000,
162         PCI_ADDR(0, 0x18, 2, 0x48), 0x001f01fe, 0x00000000,
163         PCI_ADDR(0, 0x18, 2, 0x4C), 0x001f01fe, 0x00000000,
164         PCI_ADDR(0, 0x18, 2, 0x50), 0x001f01fe, 0x00000000,
165         PCI_ADDR(0, 0x18, 2, 0x54), 0x001f01fe, 0x00000000,
166         PCI_ADDR(0, 0x18, 2, 0x58), 0x001f01fe, 0x00000000,
167         PCI_ADDR(0, 0x18, 2, 0x5C), 0x001f01fe, 0x00000000,
168         /* DRAM CS Mask Address i Registers
169          * F2:0x60 i = 0
170          * F2:0x64 i = 1
171          * F2:0x68 i = 2
172          * F2:0x6C i = 3
173          * F2:0x70 i = 4
174          * F2:0x74 i = 5
175          * F2:0x78 i = 6
176          * F2:0x7C i = 7
177          * Select bits to exclude from comparison with the DRAM Base address register.
178          * [ 8: 0] Reserved
179          * [15: 9] Address Mask (19-13)
180          *         Address to be excluded from the optimized case
181          * [20:16] Reserved
182          * [29:21] Address Mask (33-25)
183          *         The bits with an address mask of 1 are excluded from address comparison
184          * [31:30] Reserved
185          * 
186          */
187         PCI_ADDR(0, 0x18, 2, 0x60), 0xC01f01ff, 0x00000000,
188         PCI_ADDR(0, 0x18, 2, 0x64), 0xC01f01ff, 0x00000000,
189         PCI_ADDR(0, 0x18, 2, 0x68), 0xC01f01ff, 0x00000000,
190         PCI_ADDR(0, 0x18, 2, 0x6C), 0xC01f01ff, 0x00000000,
191         PCI_ADDR(0, 0x18, 2, 0x70), 0xC01f01ff, 0x00000000,
192         PCI_ADDR(0, 0x18, 2, 0x74), 0xC01f01ff, 0x00000000,
193         PCI_ADDR(0, 0x18, 2, 0x78), 0xC01f01ff, 0x00000000,
194         PCI_ADDR(0, 0x18, 2, 0x7C), 0xC01f01ff, 0x00000000,
195         /* DRAM Bank Address Mapping Register
196          * F2:0x80
197          * Specify the memory module size
198          * [ 2: 0] CS1/0 
199          * [ 6: 4] CS3/2
200          * [10: 8] CS5/4
201          * [14:12] CS7/6
202          *         000 = 32Mbyte  (Rows = 12 & Col =  8)
203          *         001 = 64Mbyte  (Rows = 12 & Col =  9)
204          *         010 = 128Mbyte (Rows = 13 & Col =  9)|(Rows = 12 & Col = 10)
205          *         011 = 256Mbyte (Rows = 13 & Col = 10)|(Rows = 12 & Col = 11)
206          *         100 = 512Mbyte (Rows = 13 & Col = 11)|(Rows = 14 & Col = 10)
207          *         101 = 1Gbyte   (Rows = 14 & Col = 11)|(Rows = 13 & Col = 12)
208          *         110 = 2Gbyte   (Rows = 14 & Col = 12)
209          *         111 = reserved 
210          * [ 3: 3] Reserved
211          * [ 7: 7] Reserved
212          * [11:11] Reserved
213          * [31:15]
214          */
215         PCI_ADDR(0, 0x18, 2, 0x80), 0xffff8888, 0x00000000,
216         /* DRAM Timing Low Register
217          * F2:0x88
218          * [ 2: 0] Tcl (Cas# Latency, Cas# to read-data-valid)
219          *         000 = reserved
220          *         001 = CL 2
221          *         010 = CL 3
222          *         011 = reserved
223          *         100 = reserved
224          *         101 = CL 2.5
225          *         110 = reserved
226          *         111 = reserved
227          * [ 3: 3] Reserved
228          * [ 7: 4] Trc (Row Cycle Time, Ras#-active to Ras#-active/bank auto refresh)
229          *         0000 =  7 bus clocks
230          *         0001 =  8 bus clocks
231          *         ...
232          *         1110 = 21 bus clocks
233          *         1111 = 22 bus clocks
234          * [11: 8] Trfc (Row refresh Cycle time, Auto-refresh-active to RAS#-active or RAS#auto-refresh)
235          *         0000 = 9 bus clocks
236          *         0010 = 10 bus clocks
237          *         ....
238          *         1110 = 23 bus clocks
239          *         1111 = 24 bus clocks
240          * [14:12] Trcd (Ras#-active to Case#-read/write Delay)
241          *         000 = reserved
242          *         001 = reserved
243          *         010 = 2 bus clocks
244          *         011 = 3 bus clocks
245          *         100 = 4 bus clocks
246          *         101 = 5 bus clocks
247          *         110 = 6 bus clocks
248          *         111 = reserved
249          * [15:15] Reserved
250          * [18:16] Trrd (Ras# to Ras# Delay)
251          *         000 = reserved
252          *         001 = reserved
253          *         010 = 2 bus clocks
254          *         011 = 3 bus clocks
255          *         100 = 4 bus clocks
256          *         101 = reserved
257          *         110 = reserved
258          *         111 = reserved
259          * [19:19] Reserved
260          * [23:20] Tras (Minmum Ras# Active Time)
261          *         0000 to 0100 = reserved
262          *         0101 = 5 bus clocks
263          *         ...
264          *         1111 = 15 bus clocks
265          * [26:24] Trp (Row Precharge Time)
266          *         000 = reserved
267          *         001 = reserved
268          *         010 = 2 bus clocks
269          *         011 = 3 bus clocks
270          *         100 = 4 bus clocks
271          *         101 = 5 bus clocks
272          *         110 = 6 bus clocks
273          *         111 = reserved
274          * [27:27] Reserved
275          * [28:28] Twr (Write Recovery Time)
276          *         0 = 2 bus clocks
277          *         1 = 3 bus clocks
278          * [31:29] Reserved
279          */
280         PCI_ADDR(0, 0x18, 2, 0x88), 0xe8088008, 0x02522001 /* 0x03623125 */ ,
281         /* DRAM Timing High Register
282          * F2:0x8C
283          * [ 0: 0] Twtr (Write to Read Delay)
284          *         0 = 1 bus Clocks
285          *         1 = 2 bus Clocks
286          * [ 3: 1] Reserved
287          * [ 6: 4] Trwt (Read to Write Delay)
288          *         000 = 1 bus clocks
289          *         001 = 2 bus clocks
290          *         010 = 3 bus clocks
291          *         011 = 4 bus clocks
292          *         100 = 5 bus clocks
293          *         101 = 6 bus clocks
294          *         110 = reserved
295          *         111 = reserved
296          * [ 7: 7] Reserved
297          * [12: 8] Tref (Refresh Rate)
298          *         00000 = 100Mhz 4K rows
299          *         00001 = 133Mhz 4K rows
300          *         00010 = 166Mhz 4K rows
301          *         00011 = 200Mhz 4K rows
302          *         01000 = 100Mhz 8K/16K rows
303          *         01001 = 133Mhz 8K/16K rows
304          *         01010 = 166Mhz 8K/16K rows
305          *         01011 = 200Mhz 8K/16K rows
306          * [19:13] Reserved
307          * [22:20] Twcl (Write CAS Latency)
308          *         000 = 1 Mem clock after CAS# (Unbuffered Dimms)
309          *         001 = 2 Mem clocks after CAS# (Registered Dimms)
310          * [31:23] Reserved
311          */
312         PCI_ADDR(0, 0x18, 2, 0x8c), 0xff8fe08e, (0 << 20)|(0 << 8)|(0 << 4)|(0 << 0),
313         /* DRAM Config Low Register
314          * F2:0x90
315          * [ 0: 0] DLL Disable
316          *         0 = Enabled
317          *         1 = Disabled
318          * [ 1: 1] D_DRV
319          *         0 = Normal Drive
320          *         1 = Weak Drive
321          * [ 2: 2] QFC_EN
322          *         0 = Disabled
323          *         1 = Enabled
324          * [ 3: 3] Disable DQS Hystersis  (FIXME handle this one carefully)
325          *         0 = Enable DQS input filter 
326          *         1 = Disable DQS input filtering 
327          * [ 7: 4] Reserved
328          * [ 8: 8] DRAM_Init
329          *         0 = Initialization done or not yet started.
330          *         1 = Initiate DRAM intialization sequence
331          * [ 9: 9] SO-Dimm Enable
332          *         0 = Do nothing
333          *         1 = SO-Dimms present
334          * [10:10] DramEnable
335          *         0 = DRAM not enabled
336          *         1 = DRAM initialized and enabled
337          * [11:11] Memory Clear Status
338          *         0 = Memory Clear function has not completed
339          *         1 = Memory Clear function has completed
340          * [12:12] Exit Self-Refresh
341          *         0 = Exit from self-refresh done or not yet started
342          *         1 = DRAM exiting from self refresh
343          * [13:13] Self-Refresh Status
344          *         0 = Normal Operation
345          *         1 = Self-refresh mode active
346          * [15:14] Read/Write Queue Bypass Count
347          *         00 = 2
348          *         01 = 4
349          *         10 = 8
350          *         11 = 16
351          * [16:16] 128-bit/64-Bit
352          *         0 = 64bit Interface to DRAM
353          *         1 = 128bit Interface to DRAM
354          * [17:17] DIMM ECC Enable
355          *         0 = Some DIMMs do not have ECC
356          *         1 = ALL DIMMS have ECC bits
357          * [18:18] UnBuffered DIMMs
358          *         0 = Buffered DIMMS
359          *         1 = Unbuffered DIMMS
360          * [19:19] Enable 32-Byte Granularity
361          *         0 = Optimize for 64byte bursts
362          *         1 = Optimize for 32byte bursts
363          * [20:20] DIMM 0 is x4
364          * [21:21] DIMM 1 is x4
365          * [22:22] DIMM 2 is x4
366          * [23:23] DIMM 3 is x4
367          *         0 = DIMM is not x4
368          *         1 = x4 DIMM present
369          * [24:24] Disable DRAM Receivers
370          *         0 = Receivers enabled
371          *         1 = Receivers disabled
372          * [27:25] Bypass Max
373          *         000 = Arbiters chois is always respected
374          *         001 = Oldest entry in DCQ can be bypassed 1 time
375          *         010 = Oldest entry in DCQ can be bypassed 2 times
376          *         011 = Oldest entry in DCQ can be bypassed 3 times
377          *         100 = Oldest entry in DCQ can be bypassed 4 times
378          *         101 = Oldest entry in DCQ can be bypassed 5 times
379          *         110 = Oldest entry in DCQ can be bypassed 6 times
380          *         111 = Oldest entry in DCQ can be bypassed 7 times
381          * [31:28] Reserved
382          */
383         PCI_ADDR(0, 0x18, 2, 0x90), 0xf0000000, 
384         (4 << 25)|(0 << 24)| 
385         (0 << 23)|(0 << 22)|(0 << 21)|(0 << 20)| 
386         (1 << 19)|(0 << 18)|(1 << 17)|(0 << 16)| 
387         (2 << 14)|(0 << 13)|(0 << 12)| 
388         (0 << 11)|(0 << 10)|(0 << 9)|(0 << 8)| 
389         (0 << 3) |(0 << 1) |(0 << 0),
390         /* DRAM Config High Register
391          * F2:0x94
392          * [ 0: 3] Maximum Asynchronous Latency
393          *         0000 = 0 ns
394          *         ...
395          *         1111 = 15 ns
396          * [ 7: 4] Reserved
397          * [11: 8] Read Preamble
398          *         0000 = 2.0 ns
399          *         0001 = 2.5 ns
400          *         0010 = 3.0 ns
401          *         0011 = 3.5 ns
402          *         0100 = 4.0 ns
403          *         0101 = 4.5 ns
404          *         0110 = 5.0 ns
405          *         0111 = 5.5 ns
406          *         1000 = 6.0 ns
407          *         1001 = 6.5 ns
408          *         1010 = 7.0 ns
409          *         1011 = 7.5 ns
410          *         1100 = 8.0 ns
411          *         1101 = 8.5 ns
412          *         1110 = 9.0 ns
413          *         1111 = 9.5 ns
414          * [15:12] Reserved
415          * [18:16] Idle Cycle Limit
416          *         000 = 0 cycles
417          *         001 = 4 cycles
418          *         010 = 8 cycles
419          *         011 = 16 cycles
420          *         100 = 32 cycles
421          *         101 = 64 cycles
422          *         110 = 128 cycles
423          *         111 = 256 cycles
424          * [19:19] Dynamic Idle Cycle Center Enable
425          *         0 = Use Idle Cycle Limit
426          *         1 = Generate a dynamic Idle cycle limit
427          * [22:20] DRAM MEMCLK Frequency
428          *         000 = 100Mhz
429          *         001 = reserved
430          *         010 = 133Mhz
431          *         011 = reserved
432          *         100 = reserved
433          *         101 = 166Mhz
434          *         110 = reserved
435          *         111 = reserved
436          * [24:23] Reserved
437          * [25:25] Memory Clock Ratio Valid (FIXME carefully enable memclk)
438          *         0 = Disable MemClks
439          *         1 = Enable MemClks
440          * [26:26] Memory Clock 0 Enable
441          *         0 = Disabled
442          *         1 = Enabled
443          * [27:27] Memory Clock 1 Enable
444          *         0 = Disabled
445          *         1 = Enabled
446          * [28:28] Memory Clock 2 Enable
447          *         0 = Disabled
448          *         1 = Enabled
449          * [29:29] Memory Clock 3 Enable
450          *         0 = Disabled
451          *         1 = Enabled
452          * [31:30] Reserved
453          */
454         PCI_ADDR(0, 0x18, 2, 0x94), 0xc180f0f0,
455         (0 << 29)|(0 << 28)|(0 << 27)|(0 << 26)|(0 << 25)|
456         (0 << 20)|(0 << 19)|(DCH_IDLE_LIMIT_16 << 16)|(0 << 8)|(0 << 0),
457         /* DRAM Delay Line Register
458          * F2:0x98
459          * Adjust the skew of the input DQS strobe relative to DATA
460          * [15: 0] Reserved
461          * [23:16] Delay Line Adjust
462          *         Adjusts the DLL derived PDL delay by one or more delay stages
463          *         in either the faster or slower direction.
464          * [24:24} Adjust Slower
465          *         0 = Do Nothing
466          *         1 = Adj is used to increase the PDL delay
467          * [25:25] Adjust Faster
468          *         0 = Do Nothing
469          *         1 = Adj is used to decrease the PDL delay
470          * [31:26] Reserved
471          */
472         PCI_ADDR(0, 0x18, 2, 0x98), 0xfc00ffff, 0x00000000,
473         /* DRAM Scrub Control Register
474          * F3:0x58
475          * [ 4: 0] DRAM Scrube Rate
476          * [ 7: 5] reserved
477          * [12: 8] L2 Scrub Rate
478          * [15:13] reserved
479          * [20:16] Dcache Scrub
480          * [31:21] reserved
481          *         Scrub Rates
482          *         00000 = Do not scrub
483          *         00001 =  40.00 ns
484          *         00010 =  80.00 ns
485          *         00011 = 160.00 ns
486          *         00100 = 320.00 ns
487          *         00101 = 640.00 ns
488          *         00110 =   1.28 us
489          *         00111 =   2.56 us
490          *         01000 =   5.12 us
491          *         01001 =  10.20 us
492          *         01011 =  41.00 us
493          *         01100 =  81.90 us
494          *         01101 = 163.80 us
495          *         01110 = 327.70 us
496          *         01111 = 655.40 us
497          *         10000 =   1.31 ms
498          *         10001 =   2.62 ms
499          *         10010 =   5.24 ms
500          *         10011 =  10.49 ms
501          *         10100 =  20.97 ms
502          *         10101 =  42.00 ms
503          *         10110 =  84.00 ms
504          *         All Others = Reserved
505          */
506         PCI_ADDR(0, 0x18, 3, 0x58), 0xffe0e0e0, 0x00000000,
507         /* DRAM Scrub Address Low Register
508          * F3:0x5C
509          * [ 0: 0] DRAM Scrubber Redirect Enable
510          *         0 = Do nothing
511          *         1 = Scrubber Corrects errors found in normal operation
512          * [ 5: 1] Reserved
513          * [31: 6] DRAM Scrub Address 31-6
514          */
515         PCI_ADDR(0, 0x18, 3, 0x5C), 0x0000003e, 0x00000000,
516         /* DRAM Scrub Address High Register
517          * F3:0x60
518          * [ 7: 0] DRAM Scrubb Address 39-32
519          * [31: 8] Reserved
520          */
521         PCI_ADDR(0, 0x18, 3, 0x60), 0xffffff00, 0x00000000,
522         };
523         int i;
524         int max;
525
526 #if 1
527         if (!controller_present(ctrl)) {
528 //                print_debug("No memory controller present\r\n");
529                 return;
530         }
531 #endif
532         print_spew("setting up CPU");
533         print_spew_hex8(ctrl->node_id);
534         print_spew(" northbridge registers\r\n");
535         max = sizeof(register_values)/sizeof(register_values[0]);
536         for(i = 0; i < max; i += 3) {
537                 device_t dev;
538                 unsigned where;
539                 unsigned long reg;
540 #if 0
541                 print_spew_hex32(register_values[i]);
542                 print_spew(" <-");
543                 print_spew_hex32(register_values[i+2]);
544                 print_spew("\r\n");
545 #endif
546                 dev = (register_values[i] & ~0xff) - PCI_DEV(0, 0x18, 0) + ctrl->f0;
547                 where = register_values[i] & 0xff;
548                 reg = pci_read_config32(dev, where);
549                 reg &= register_values[i+1];
550                 reg |= register_values[i+2];
551                 pci_write_config32(dev, where, reg);
552 #if 0
553
554                 reg = pci_read_config32(register_values[i]);
555                 reg &= register_values[i+1];
556                 reg |= register_values[i+2];
557                 pci_write_config32(register_values[i], reg);
558 #endif
559         }
560         print_spew("done.\r\n");
561 }
562
563
564 static void hw_enable_ecc(const struct mem_controller *ctrl)
565 {
566         uint32_t dcl, nbcap;
567         nbcap = pci_read_config32(ctrl->f3, NORTHBRIDGE_CAP);
568         dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
569         dcl &= ~DCL_DimmEccEn;
570         if (nbcap & NBCAP_ECC) {
571                 dcl |= DCL_DimmEccEn;
572         }
573         if (read_option(CMOS_VSTART_ECC_memory, CMOS_VLEN_ECC_memory, 1) == 0) {
574                 dcl &= ~DCL_DimmEccEn;
575         }
576         pci_write_config32(ctrl->f2, DRAM_CONFIG_LOW, dcl);
577         
578 }
579
580 static int is_dual_channel(const struct mem_controller *ctrl)
581 {
582         uint32_t dcl;
583         dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
584         return dcl & DCL_128BitEn;
585 }
586
587 static int is_opteron(const struct mem_controller *ctrl)
588 {
589         /* Test to see if I am an Opteron.  
590          * FIXME Testing dual channel capability is correct for now
591          * but a beter test is probably required.
592          */
593 #warning "FIXME implement a better test for opterons"
594         uint32_t nbcap;
595         nbcap = pci_read_config32(ctrl->f3, NORTHBRIDGE_CAP);
596         return !!(nbcap & NBCAP_128Bit);
597 }
598
599 static int is_registered(const struct mem_controller *ctrl)
600 {
601         /* Test to see if we are dealing with registered SDRAM.
602          * If we are not registered we are unbuffered.
603          * This function must be called after spd_handle_unbuffered_dimms.
604          */
605         uint32_t dcl;
606         dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
607         return !(dcl & DCL_UnBufDimm);
608 }
609
610 struct dimm_size {
611         unsigned long side1;
612         unsigned long side2;
613         unsigned long rows;
614         unsigned long col;
615 #if K8_4RANK_DIMM_SUPPORT == 1
616         unsigned long rank;
617 #endif
618 };
619
620 static struct dimm_size spd_get_dimm_size(unsigned device)
621 {
622         /* Calculate the log base 2 size of a DIMM in bits */
623         struct dimm_size sz;
624         int value, low;
625         sz.side1 = 0;
626         sz.side2 = 0;
627         sz.rows = 0;
628         sz.col = 0;
629 #if K8_4RANK_DIMM_SUPPORT == 1
630         sz.rank = 0;
631 #endif
632
633         /* Note it might be easier to use byte 31 here, it has the DIMM size as
634          * a multiple of 4MB.  The way we do it now we can size both
635          * sides of an assymetric dimm.
636          */
637         value = spd_read_byte(device, 3);       /* rows */
638         if (value < 0) goto hw_err;
639         if ((value & 0xf) == 0) goto val_err;
640         sz.side1 += value & 0xf;
641         sz.rows = value & 0xf;
642
643         value = spd_read_byte(device, 4);       /* columns */
644         if (value < 0) goto hw_err;
645         if ((value & 0xf) == 0) goto val_err;
646         sz.side1 += value & 0xf;
647         sz.col = value & 0xf;
648
649         value = spd_read_byte(device, 17);      /* banks */
650         if (value < 0) goto hw_err;
651         if ((value & 0xff) == 0) goto val_err;
652         sz.side1 += log2(value & 0xff);
653
654         /* Get the module data width and convert it to a power of two */
655         value = spd_read_byte(device, 7);       /* (high byte) */
656         if (value < 0) goto hw_err;
657         value &= 0xff;
658         value <<= 8;
659         
660         low = spd_read_byte(device, 6); /* (low byte) */
661         if (low < 0) goto hw_err;
662         value = value | (low & 0xff);
663         if ((value != 72) && (value != 64)) goto val_err;
664         sz.side1 += log2(value);
665
666         /* side 2 */
667         value = spd_read_byte(device, 5);       /* number of physical banks */
668         if (value < 0) goto hw_err;
669         if (value == 1) goto out;
670         if ((value != 2) && (value != 4 )) {
671                 goto val_err;
672         }
673 #if K8_4RANK_DIMM_SUPPORT == 1
674         sz.rank = value;
675 #endif
676
677         /* Start with the symmetrical case */
678         sz.side2 = sz.side1;
679
680         value = spd_read_byte(device, 3);       /* rows */
681         if (value < 0) goto hw_err;
682         if ((value & 0xf0) == 0) goto out;      /* If symmetrical we are done */
683         sz.side2 -= (value & 0x0f);             /* Subtract out rows on side 1 */
684         sz.side2 += ((value >> 4) & 0x0f);      /* Add in rows on side 2 */
685
686         value = spd_read_byte(device, 4);       /* columns */
687         if (value < 0) goto hw_err;
688         if ((value & 0xff) == 0) goto val_err;
689         sz.side2 -= (value & 0x0f);             /* Subtract out columns on side 1 */
690         sz.side2 += ((value >> 4) & 0x0f);      /* Add in columsn on side 2 */
691
692         goto out;
693
694  val_err:
695         die("Bad SPD value\r\n");
696         /* If an hw_error occurs report that I have no memory */
697 hw_err:
698         sz.side1 = 0;
699         sz.side2 = 0;
700         sz.rows = 0;
701         sz.col = 0;
702 #if K8_4RANK_DIMM_SUPPORT == 1
703         sz.rank = 0;
704 #endif
705  out:
706         return sz;
707 }
708
709 static const unsigned cs_map_aa[15] = {
710         /* (row=12, col=8)(14, 12) ---> (0, 0) (2, 4) */
711         0, 1, 3, 6, 0,
712         0, 2, 4, 7, 9,
713         0, 0, 5, 8,10,
714 };
715
716 static void set_dimm_size(const struct mem_controller *ctrl, struct dimm_size sz, unsigned index)
717 {
718         uint32_t base0, base1, map;
719         uint32_t dch;
720
721         if (sz.side1 != sz.side2) {
722                 sz.side2 = 0;
723         }
724         map = pci_read_config32(ctrl->f2, DRAM_BANK_ADDR_MAP);
725         map &= ~(0xf << (index * 4));
726 #if K8_4RANK_DIMM_SUPPORT == 1
727         if(sz.rank == 4) {
728                 map &= ~(0xf << ( (index + 2) * 4));
729         }
730 #endif
731
732         /* For each base register.
733          * Place the dimm size in 32 MB quantities in the bits 31 - 21.
734          * The initialize dimm size is in bits.
735          * Set the base enable bit0.
736          */
737         
738         base0 = base1 = 0;
739
740         /* Make certain side1 of the dimm is at least 32MB */
741         if (sz.side1 >= (25 +3)) {
742                 if(is_cpu_pre_d0()) {
743                         map |= (sz.side1 - (25 + 3)) << (index *4);
744 #if K8_4RANK_DIMM_SUPPORT == 1
745                         if(sz.rank == 4) {
746                               map |= (sz.side1 - (25 + 3)) << ( (index + 2) * 4);
747                         }
748 #endif
749                 }
750                 else {
751                         map |= cs_map_aa[(sz.rows - 12) * 5 + (sz.col - 8) ] << (index*4);
752 #if K8_4RANK_DIMM_SUPPORT == 1
753                         if(sz.rank == 4) {
754                                map |=  cs_map_aa[(sz.rows - 12) * 5 + (sz.col - 8) ] << ( (index + 2) * 4);
755                         }
756 #endif
757                 }
758                 base0 = (1 << ((sz.side1 - (25 + 3)) + 21)) | 1;
759         }
760         
761         /* Make certain side2 of the dimm is at least 32MB */
762         if (sz.side2 >= (25 + 3)) {
763                 base1 = (1 << ((sz.side2 - (25 + 3)) + 21)) | 1;
764         }
765
766         /* Double the size if we are using dual channel memory */
767         if (is_dual_channel(ctrl)) {
768                 base0 = (base0 << 1) | (base0 & 1);
769                 base1 = (base1 << 1) | (base1 & 1);
770         }
771
772         /* Clear the reserved bits */
773         base0 &= ~0x001ffffe;
774         base1 &= ~0x001ffffe;
775
776         /* Set the appropriate DIMM base address register */
777         pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1)+0)<<2), base0);
778         pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1)+1)<<2), base1);
779 #if K8_4RANK_DIMM_SUPPORT == 1
780         if(sz.rank == 4) {
781                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1)+4)<<2), base0);
782                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1)+5)<<2), base1);
783         }
784 #endif
785
786         pci_write_config32(ctrl->f2, DRAM_BANK_ADDR_MAP, map);
787         
788         /* Enable the memory clocks for this DIMM */
789         if (base0) {
790                 dch = pci_read_config32(ctrl->f2, DRAM_CONFIG_HIGH);
791                 dch |= DCH_MEMCLK_EN0 << index;
792 #if K8_4RANK_DIMM_SUPPORT == 1
793                 if(sz.rank == 4) {
794                         dch |= DCH_MEMCLK_EN0 << (index + 2);
795                 }
796 #endif
797                 pci_write_config32(ctrl->f2, DRAM_CONFIG_HIGH, dch);
798         }
799 }
800
801 static long spd_set_ram_size(const struct mem_controller *ctrl, long dimm_mask)
802 {
803         int i;
804         
805         for(i = 0; i < DIMM_SOCKETS; i++) {
806                 struct dimm_size sz;
807                 if (!(dimm_mask & (1 << i))) {
808                         continue;
809                 }
810                 sz = spd_get_dimm_size(ctrl->channel0[i]);
811                 if (sz.side1 == 0) {
812                         return -1; /* Report SPD error */
813                 }
814                 set_dimm_size(ctrl, sz, i);
815         }
816         return dimm_mask;
817 }
818
819 static void route_dram_accesses(const struct mem_controller *ctrl,
820         unsigned long base_k, unsigned long limit_k)
821 {
822         /* Route the addresses to the controller node */
823         unsigned node_id;
824         unsigned limit;
825         unsigned base;
826         unsigned index;
827         unsigned limit_reg, base_reg;
828         device_t device;
829
830         node_id = ctrl->node_id;
831         index = (node_id << 3);
832         limit = (limit_k << 2);
833         limit &= 0xffff0000;
834         limit -= 0x00010000;
835         limit |= ( 0 << 8) | (node_id << 0);
836         base = (base_k << 2);
837         base &= 0xffff0000;
838         base |= (0 << 8) | (1<<1) | (1<<0);
839
840         limit_reg = 0x44 + index;
841         base_reg = 0x40 + index;
842         for(device = PCI_DEV(0, 0x18, 1); device <= PCI_DEV(0, 0x1f, 1); device += PCI_DEV(0, 1, 0)) {
843                 pci_write_config32(device, limit_reg, limit);
844                 pci_write_config32(device, base_reg, base);
845         }
846 }
847
848 static void set_top_mem(unsigned tom_k)
849 {
850         /* Error if I don't have memory */
851         if (!tom_k) {
852                 die("No memory?");
853         }
854
855         /* Report the amount of memory. */
856         print_spew("RAM: 0x");
857         print_spew_hex32(tom_k);
858         print_spew(" KB\r\n");
859
860         /* Now set top of memory */
861         msr_t msr;
862         msr.lo = (tom_k & 0x003fffff) << 10;
863         msr.hi = (tom_k & 0xffc00000) >> 22;
864         wrmsr(TOP_MEM2, msr);
865
866         /* Leave a 64M hole between TOP_MEM and TOP_MEM2
867          * so I can see my rom chip and other I/O devices.
868          */
869         if (tom_k >= 0x003f0000) {
870                 tom_k = 0x3f0000;
871         }
872         msr.lo = (tom_k & 0x003fffff) << 10;
873         msr.hi = (tom_k & 0xffc00000) >> 22;
874         wrmsr(TOP_MEM, msr);
875 }
876
877 static unsigned long interleave_chip_selects(const struct mem_controller *ctrl)
878 {
879         /* 35 - 25 */
880         static const uint32_t csbase_low[] = { 
881         /* 32MB */      (1 << (13 - 4)),
882         /* 64MB */      (1 << (14 - 4)),
883         /* 128MB */     (1 << (14 - 4)), 
884         /* 256MB */     (1 << (15 - 4)),
885         /* 512MB */     (1 << (15 - 4)),
886         /* 1GB */       (1 << (16 - 4)),
887         /* 2GB */       (1 << (16 - 4)), 
888         };
889
890         static const uint32_t csbase_low_d0[] = {
891         /* 32MB */      (1 << (13 - 4)),
892         /* 64MB */      (1 << (14 - 4)),
893         /* 128MB */     (1 << (14 - 4)),
894         /* 128MB */     (1 << (15 - 4)),
895         /* 256MB */     (1 << (15 - 4)),
896         /* 512MB */     (1 << (15 - 4)),
897         /* 256MB */     (1 << (16 - 4)),
898         /* 512MB */     (1 << (16 - 4)),
899         /* 1GB */       (1 << (16 - 4)),
900         /* 1GB */       (1 << (17 - 4)),
901         /* 2GB */       (1 << (17 - 4)),
902         };
903
904         /* cs_base_high is not changed */
905
906         uint32_t csbase_inc;
907         int chip_selects, index;
908         int bits;
909         unsigned common_size;
910         unsigned common_cs_mode;
911         uint32_t csbase, csmask;
912
913         /* See if all of the memory chip selects are the same size
914          * and if so count them.
915          */
916         chip_selects = 0;
917         common_size = 0;
918         common_cs_mode = 0;
919         for(index = 0; index < 8; index++) {
920                 unsigned size;
921                 unsigned cs_mode;
922                 uint32_t value;
923                 
924                 value = pci_read_config32(ctrl->f2, DRAM_CSBASE + (index << 2));
925                 
926                 /* Is it enabled? */
927                 if (!(value & 1)) {
928                         continue;
929                 }
930                 chip_selects++;
931                 size = value >> 21;
932                 if (common_size == 0) {
933                         common_size = size;
934                 }
935                 /* The size differed fail */
936                 if (common_size != size) {
937                         return 0;
938                 }
939
940                 value = pci_read_config32(ctrl->f2, DRAM_BANK_ADDR_MAP);
941                 cs_mode =( value >> ((index>>1)*4)) & 0xf;
942                 if(cs_mode == 0 ) continue;
943                 if(common_cs_mode == 0) {
944                         common_cs_mode = cs_mode;
945                 }
946                 /* The size differed fail */
947                 if(common_cs_mode != cs_mode) {
948                         return 0;
949                 }
950         }
951
952         /* Chip selects can only be interleaved when there is
953          * more than one and their is a power of two of them.
954          */
955         bits = log2(chip_selects);
956         if (((1 << bits) != chip_selects) || (bits < 1) || (bits > 3)) {
957                 return 0;
958         }
959
960         /* Find the bits of csbase that we need to interleave on */
961         if(is_cpu_pre_d0()){
962                 csbase_inc = csbase_low[common_cs_mode];
963                 if(is_dual_channel(ctrl)) {
964                 /* Also we run out of address mask bits if we try and interleave 8 4GB dimms */
965                         if ((bits == 3) && (common_size == (1 << (32 - 3)))) {
966 //                              print_debug("8 4GB chip selects cannot be interleaved\r\n");
967                                 return 0;
968                         }  
969                         csbase_inc <<=1;
970                 }
971         }
972         else {
973                 csbase_inc = csbase_low_d0[common_cs_mode];
974                 if(is_dual_channel(ctrl)) {
975                         if( (bits==3) && (common_cs_mode > 8)) {
976 //                              print_debug("8 cs_mode>8 chip selects cannot be interleaved\r\n");
977                                 return 0;
978                         }
979                         csbase_inc <<=1;
980                 }   
981         }
982
983         /* Compute the initial values for csbase and csbask. 
984          * In csbase just set the enable bit and the base to zero.
985          * In csmask set the mask bits for the size and page level interleave.
986          */
987         csbase = 0 | 1;
988         csmask = (((common_size  << bits) - 1) << 21);
989         csmask |= 0xfe00 & ~((csbase_inc << bits) - csbase_inc);
990         for(index = 0; index < 8; index++) {
991                 uint32_t value;
992
993                 value = pci_read_config32(ctrl->f2, DRAM_CSBASE + (index << 2));
994                 /* Is it enabled? */
995                 if (!(value & 1)) {
996                         continue;
997                 }
998                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (index << 2), csbase);
999                 pci_write_config32(ctrl->f2, DRAM_CSMASK + (index << 2), csmask);
1000                 csbase += csbase_inc;
1001         }
1002         
1003         print_spew("Interleaved\r\n");
1004
1005         /* Return the memory size in K */
1006         return common_size << (15 + bits);
1007 }
1008
1009 static unsigned long order_chip_selects(const struct mem_controller *ctrl)
1010 {
1011         unsigned long tom;
1012
1013         /* Remember which registers we have used in the high 8 bits of tom */
1014         tom = 0;
1015         for(;;) {
1016                 /* Find the largest remaining canidate */
1017                 unsigned index, canidate;
1018                 uint32_t csbase, csmask;
1019                 unsigned size;
1020                 csbase = 0;
1021                 canidate = 0;
1022                 for(index = 0; index < 8; index++) {
1023                         uint32_t value;
1024                         value = pci_read_config32(ctrl->f2, DRAM_CSBASE + (index << 2));
1025
1026                         /* Is it enabled? */
1027                         if (!(value & 1)) {
1028                                 continue;
1029                         }
1030                         
1031                         /* Is it greater? */
1032                         if (value <= csbase) {
1033                                 continue;
1034                         }
1035                         
1036                         /* Has it already been selected */
1037                         if (tom & (1 << (index + 24))) {
1038                                 continue;
1039                         }
1040                         /* I have a new canidate */
1041                         csbase = value;
1042                         canidate = index;
1043                 }
1044                 /* See if I have found a new canidate */
1045                 if (csbase == 0) {
1046                         break;
1047                 }
1048
1049                 /* Remember the dimm size */
1050                 size = csbase >> 21;
1051
1052                 /* Remember I have used this register */
1053                 tom |= (1 << (canidate + 24));
1054
1055                 /* Recompute the cs base register value */
1056                 csbase = (tom << 21) | 1;
1057
1058                 /* Increment the top of memory */
1059                 tom += size;
1060
1061                 /* Compute the memory mask */
1062                 csmask = ((size -1) << 21);
1063                 csmask |= 0xfe00;               /* For now don't optimize */
1064
1065                 /* Write the new base register */
1066                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (canidate << 2), csbase);
1067                 /* Write the new mask register */
1068                 pci_write_config32(ctrl->f2, DRAM_CSMASK + (canidate << 2), csmask);
1069                 
1070         }
1071         /* Return the memory size in K */
1072         return (tom & ~0xff000000) << 15;
1073 }
1074
1075 unsigned long memory_end_k(const struct mem_controller *ctrl, int max_node_id)
1076 {
1077         unsigned node_id;
1078         unsigned end_k;
1079         /* Find the last memory address used */
1080         end_k = 0;
1081         for(node_id = 0; node_id < max_node_id; node_id++) {
1082                 uint32_t limit, base;
1083                 unsigned index;
1084                 index = node_id << 3;
1085                 base = pci_read_config32(ctrl->f1, 0x40 + index);
1086                 /* Only look at the limit if the base is enabled */
1087                 if ((base & 3) == 3) {
1088                         limit = pci_read_config32(ctrl->f1, 0x44 + index);
1089                         end_k = ((limit + 0x00010000) & 0xffff0000) >> 2;
1090                 }
1091         }
1092         return end_k;
1093 }
1094
1095 #if K8_E0_MEM_HOLE_SIZEK != 0
1096 #define K8_E0_MEM_HOLE_LIMITK 4*1024*1024
1097 #define K8_E0_MEM_HOLE_BASEK (K8_E0_MEM_HOLE_LIMITK - K8_E0_MEM_HOLE_SIZEK )
1098
1099 static void set_e0_mem_hole(const struct mem_controller *ctrl, unsigned base_k)
1100 {
1101         /* Route the addresses to the controller node */
1102         unsigned val;
1103
1104         val = pci_read_config32(ctrl->f1,0xf0);
1105
1106         val &= 0x00ff00fe;
1107         val = (K8_E0_MEM_HOLE_BASEK << 10) | ((K8_E0_MEM_HOLE_SIZEK+base_k)>>(16-10)) | 1;
1108
1109         pci_write_config32(ctrl->f1, 0xf0, val);
1110 }
1111         
1112 #endif
1113
1114 static void order_dimms(const struct mem_controller *ctrl)
1115 {
1116         unsigned long tom_k, base_k;
1117
1118         if (read_option(CMOS_VSTART_interleave_chip_selects, CMOS_VLEN_interleave_chip_selects, 1) != 0) {
1119                 tom_k = interleave_chip_selects(ctrl);
1120         } else {
1121                 print_debug("Interleaving disabled\r\n");
1122                 tom_k = 0;
1123         }
1124         if (!tom_k) {
1125                 tom_k = order_chip_selects(ctrl);
1126         }
1127         /* Compute the memory base address */
1128         base_k = memory_end_k(ctrl, ctrl->node_id);
1129         tom_k += base_k;
1130 #if K8_E0_MEM_HOLE_SIZEK != 0
1131         if(!is_cpu_pre_e0()) {
1132                 /* See if I need to check the range cover hole */
1133                 if ((base_k <= K8_E0_MEM_HOLE_BASEK) && (tom_k > K8_E0_MEM_HOLE_BASEK)) {
1134                         tom_k += K8_E0_MEM_HOLE_SIZEK;
1135                 }
1136         }
1137 #endif
1138         route_dram_accesses(ctrl, base_k, tom_k);
1139         set_top_mem(tom_k);
1140 }
1141
1142 static long disable_dimm(const struct mem_controller *ctrl, unsigned index, long dimm_mask)
1143 {
1144         print_debug("disabling dimm"); 
1145         print_debug_hex8(index); 
1146         print_debug("\r\n");
1147         pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1)+0)<<2), 0);
1148         pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1)+1)<<2), 0);
1149         dimm_mask &= ~(1 << index);
1150         return dimm_mask;
1151 }
1152
1153 static long spd_handle_unbuffered_dimms(const struct mem_controller *ctrl, long dimm_mask)
1154 {
1155         int i;
1156         int registered;
1157         int unbuffered;
1158         uint32_t dcl;
1159         unbuffered = 0;
1160         registered = 0;
1161         for(i = 0; (i < DIMM_SOCKETS); i++) {
1162                 int value;
1163                 if (!(dimm_mask & (1 << i))) {
1164                         continue;
1165                 }
1166                 value = spd_read_byte(ctrl->channel0[i], 21);
1167                 if (value < 0) {
1168                         return -1;
1169                 }
1170                 /* Registered dimm ? */
1171                 if (value & (1 << 1)) {
1172                         registered = 1;
1173                 } 
1174                 /* Otherwise it must be an unbuffered dimm */
1175                 else {
1176                         unbuffered = 1;
1177                 }
1178         }
1179         if (unbuffered && registered) {
1180                 die("Mixed buffered and registered dimms not supported");
1181         }
1182 #if 1
1183         //By yhlu for debug Athlon64 939 can do dual channel, but it use unbuffer DIMM
1184         if (unbuffered && is_opteron(ctrl)) {
1185                 die("Unbuffered Dimms not supported on Opteron");
1186         }
1187 #endif
1188
1189         dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
1190         dcl &= ~DCL_UnBufDimm;
1191         if (unbuffered) {
1192                 dcl |= DCL_UnBufDimm;
1193         }
1194         pci_write_config32(ctrl->f2, DRAM_CONFIG_LOW, dcl);
1195 #if 0
1196         if (is_registered(ctrl)) {
1197                 print_debug("Registered\r\n");
1198         } else {
1199                 print_debug("Unbuffered\r\n");
1200         }
1201 #endif
1202         return dimm_mask;
1203 }
1204
1205 static unsigned int spd_detect_dimms(const struct mem_controller *ctrl)
1206 {
1207         unsigned dimm_mask;
1208         int i;
1209         dimm_mask = 0;
1210         for(i = 0; i < DIMM_SOCKETS; i++) {
1211                 int byte;
1212                 unsigned device;
1213                 device = ctrl->channel0[i];
1214                 if (device) {
1215                         byte = spd_read_byte(ctrl->channel0[i], 2);  /* Type */
1216                         if (byte == 7) {
1217                                 dimm_mask |= (1 << i);
1218                         }
1219                 }
1220                 device = ctrl->channel1[i];
1221                 if (device) {
1222                         byte = spd_read_byte(ctrl->channel1[i], 2);
1223                         if (byte == 7) {
1224                                 dimm_mask |= (1 << (i + DIMM_SOCKETS));
1225                         }
1226                 }
1227         }
1228         return dimm_mask;
1229 }
1230
1231 static long spd_enable_2channels(const struct mem_controller *ctrl, long dimm_mask)
1232 {
1233         int i;
1234         uint32_t nbcap;
1235         /* SPD addresses to verify are identical */
1236         static const unsigned addresses[] = {
1237                 2,      /* Type should be DDR SDRAM */
1238                 3,      /* *Row addresses */
1239                 4,      /* *Column addresses */
1240                 5,      /* *Physical Banks */
1241                 6,      /* *Module Data Width low */
1242                 7,      /* *Module Data Width high */
1243                 9,      /* *Cycle time at highest CAS Latency CL=X */
1244                 11,     /* *SDRAM Type */
1245                 13,     /* *SDRAM Width */
1246                 17,     /* *Logical Banks */
1247                 18,     /* *Supported CAS Latencies */
1248                 21,     /* *SDRAM Module Attributes */
1249                 23,     /* *Cycle time at CAS Latnecy (CLX - 0.5) */
1250                 26,     /* *Cycle time at CAS Latnecy (CLX - 1.0) */
1251                 27,     /* *tRP Row precharge time */
1252                 28,     /* *Minimum Row Active to Row Active Delay (tRRD) */
1253                 29,     /* *tRCD RAS to CAS */
1254                 30,     /* *tRAS Activate to Precharge */
1255                 41,     /* *Minimum Active to Active/Auto Refresh Time(Trc) */
1256                 42,     /* *Minimum Auto Refresh Command Time(Trfc) */
1257         };
1258         /* If the dimms are not in pairs do not do dual channels */
1259         if ((dimm_mask & ((1 << DIMM_SOCKETS) - 1)) !=
1260                 ((dimm_mask >> DIMM_SOCKETS) & ((1 << DIMM_SOCKETS) - 1))) { 
1261                 goto single_channel;
1262         }
1263         /* If the cpu is not capable of doing dual channels don't do dual channels */
1264         nbcap = pci_read_config32(ctrl->f3, NORTHBRIDGE_CAP);
1265         if (!(nbcap & NBCAP_128Bit)) {
1266                 goto single_channel;
1267         }
1268         for(i = 0; (i < 4) && (ctrl->channel0[i]); i++) {
1269                 unsigned device0, device1;
1270                 int value0, value1;
1271                 int j;
1272                 /* If I don't have a dimm skip this one */
1273                 if (!(dimm_mask & (1 << i))) {
1274                         continue;
1275                 }
1276                 device0 = ctrl->channel0[i];
1277                 device1 = ctrl->channel1[i];
1278                 for(j = 0; j < sizeof(addresses)/sizeof(addresses[0]); j++) {
1279                         unsigned addr;
1280                         addr = addresses[j];
1281                         value0 = spd_read_byte(device0, addr);
1282                         if (value0 < 0) {
1283                                 return -1;
1284                         }
1285                         value1 = spd_read_byte(device1, addr);
1286                         if (value1 < 0) {
1287                                 return -1;
1288                         }
1289                         if (value0 != value1) {
1290                                 goto single_channel;
1291                         }
1292                 }
1293         }
1294         print_spew("Enabling dual channel memory\r\n");
1295         uint32_t dcl;
1296         dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
1297         dcl &= ~DCL_32ByteEn;
1298         dcl |= DCL_128BitEn;
1299         pci_write_config32(ctrl->f2, DRAM_CONFIG_LOW, dcl);
1300         return dimm_mask;
1301  single_channel:
1302         dimm_mask &= ~((1 << (DIMM_SOCKETS *2)) - (1 << DIMM_SOCKETS));
1303         return dimm_mask;
1304 }
1305
1306 struct mem_param {
1307         uint8_t cycle_time;
1308         uint8_t divisor; /* In 1/2 ns increments */
1309         uint8_t tRC;
1310         uint8_t tRFC;
1311         uint32_t dch_memclk;
1312         uint16_t dch_tref4k, dch_tref8k;
1313         uint8_t  dtl_twr;
1314         char name[9];
1315 };
1316
1317 static const struct mem_param *get_mem_param(unsigned min_cycle_time)
1318 {
1319         static const struct mem_param speed[] = {
1320                 {
1321                         .name       = "100Mhz\r\n",
1322                         .cycle_time = 0xa0,
1323                         .divisor    = (10 <<1),
1324                         .tRC        = 0x46,
1325                         .tRFC       = 0x50,
1326                         .dch_memclk = DCH_MEMCLK_100MHZ << DCH_MEMCLK_SHIFT,
1327                         .dch_tref4k = DTH_TREF_100MHZ_4K,
1328                         .dch_tref8k = DTH_TREF_100MHZ_8K,
1329                         .dtl_twr    = 2,
1330                 },
1331                 {
1332                         .name       = "133Mhz\r\n",
1333                         .cycle_time = 0x75,
1334                         .divisor    = (7<<1)+1,
1335                         .tRC        = 0x41,
1336                         .tRFC       = 0x4B,
1337                         .dch_memclk = DCH_MEMCLK_133MHZ << DCH_MEMCLK_SHIFT,
1338                         .dch_tref4k = DTH_TREF_133MHZ_4K,
1339                         .dch_tref8k = DTH_TREF_133MHZ_8K,
1340                         .dtl_twr    = 2,
1341                 },
1342                 {
1343                         .name       = "166Mhz\r\n",
1344                         .cycle_time = 0x60,
1345                         .divisor    = (6<<1),
1346                         .tRC        = 0x3C,
1347                         .tRFC       = 0x48,
1348                         .dch_memclk = DCH_MEMCLK_166MHZ << DCH_MEMCLK_SHIFT,
1349                         .dch_tref4k = DTH_TREF_166MHZ_4K,
1350                         .dch_tref8k = DTH_TREF_166MHZ_8K,
1351                         .dtl_twr    = 3,
1352                 },
1353                 {
1354                         .name       = "200Mhz\r\n",
1355                         .cycle_time = 0x50,
1356                         .divisor    = (5<<1),
1357                         .tRC        = 0x37,
1358                         .tRFC       = 0x46,
1359                         .dch_memclk = DCH_MEMCLK_200MHZ << DCH_MEMCLK_SHIFT,
1360                         .dch_tref4k = DTH_TREF_200MHZ_4K,
1361                         .dch_tref8k = DTH_TREF_200MHZ_8K,
1362                         .dtl_twr    = 3,
1363                 },
1364                 {
1365                         .cycle_time = 0x00,
1366                 },
1367         };
1368         const struct mem_param *param;
1369         for(param = &speed[0]; param->cycle_time ; param++) {
1370                 if (min_cycle_time > (param+1)->cycle_time) {
1371                         break;
1372                 }
1373         }
1374         if (!param->cycle_time) {
1375                 die("min_cycle_time to low");
1376         }
1377         print_spew(param->name);
1378 #ifdef DRAM_MIN_CYCLE_TIME
1379         print_debug(param->name);
1380 #endif
1381         return param;
1382 }
1383
1384 struct spd_set_memclk_result {
1385         const struct mem_param *param;
1386         long dimm_mask;
1387 };
1388 static struct spd_set_memclk_result spd_set_memclk(const struct mem_controller *ctrl, long dimm_mask)
1389 {
1390         /* Compute the minimum cycle time for these dimms */
1391         struct spd_set_memclk_result result;
1392         unsigned min_cycle_time, min_latency, bios_cycle_time;
1393         int i;
1394         uint32_t value;
1395
1396         static const int latency_indicies[] = { 26, 23, 9 };
1397         static const unsigned char min_cycle_times[] = {
1398                 [NBCAP_MEMCLK_200MHZ] = 0x50, /* 5ns */
1399                 [NBCAP_MEMCLK_166MHZ] = 0x60, /* 6ns */
1400                 [NBCAP_MEMCLK_133MHZ] = 0x75, /* 7.5ns */
1401                 [NBCAP_MEMCLK_100MHZ] = 0xa0, /* 10ns */
1402         };
1403
1404
1405         value = pci_read_config32(ctrl->f3, NORTHBRIDGE_CAP);
1406         min_cycle_time = min_cycle_times[(value >> NBCAP_MEMCLK_SHIFT) & NBCAP_MEMCLK_MASK];
1407         bios_cycle_time = min_cycle_times[
1408                 read_option(CMOS_VSTART_max_mem_clock, CMOS_VLEN_max_mem_clock, 0)];
1409         if (bios_cycle_time > min_cycle_time) {
1410                 min_cycle_time = bios_cycle_time;
1411         }
1412         min_latency = 2;
1413
1414         /* Compute the least latency with the fastest clock supported
1415          * by both the memory controller and the dimms.
1416          */
1417         for(i = 0; i < DIMM_SOCKETS; i++) {
1418                 int new_cycle_time, new_latency;
1419                 int index;
1420                 int latencies;
1421                 int latency;
1422
1423                 if (!(dimm_mask & (1 << i))) {
1424                         continue;
1425                 }
1426
1427                 /* First find the supported CAS latencies
1428                  * Byte 18 for DDR SDRAM is interpreted:
1429                  * bit 0 == CAS Latency = 1.0
1430                  * bit 1 == CAS Latency = 1.5
1431                  * bit 2 == CAS Latency = 2.0
1432                  * bit 3 == CAS Latency = 2.5
1433                  * bit 4 == CAS Latency = 3.0
1434                  * bit 5 == CAS Latency = 3.5
1435                  * bit 6 == TBD
1436                  * bit 7 == TBD
1437                  */
1438                 new_cycle_time = 0xa0;
1439                 new_latency = 5;
1440
1441                 latencies = spd_read_byte(ctrl->channel0[i], 18);
1442                 if (latencies <= 0) continue;
1443
1444                 /* Compute the lowest cas latency supported */
1445                 latency = log2(latencies) -2;
1446
1447                 /* Loop through and find a fast clock with a low latency */
1448                 for(index = 0; index < 3; index++, latency++) {
1449                         int value;
1450                         if ((latency < 2) || (latency > 4) ||
1451                                 (!(latencies & (1 << latency)))) {
1452                                 continue;
1453                         }
1454                         value = spd_read_byte(ctrl->channel0[i], latency_indicies[index]);
1455                         if (value < 0) {
1456                                 goto hw_error;
1457                         }
1458
1459                         /* Only increase the latency if we decreas the clock */
1460                         if ((value >= min_cycle_time) && (value < new_cycle_time)) {
1461                                 new_cycle_time = value;
1462                                 new_latency = latency;
1463                         }
1464                 }
1465                 if (new_latency > 4){
1466                         continue;
1467                 }
1468                 /* Does min_latency need to be increased? */
1469                 if (new_cycle_time > min_cycle_time) {
1470                         min_cycle_time = new_cycle_time;
1471                 }
1472                 /* Does min_cycle_time need to be increased? */
1473                 if (new_latency > min_latency) {
1474                         min_latency = new_latency;
1475                 }
1476         }
1477         /* Make a second pass through the dimms and disable
1478          * any that cannot support the selected memclk and cas latency.
1479          */
1480         
1481         for(i = 0; (i < 4) && (ctrl->channel0[i]); i++) {
1482                 int latencies;
1483                 int latency;
1484                 int index;
1485                 int value;
1486                 if (!(dimm_mask & (1 << i))) {
1487                         continue;
1488                 }
1489                 latencies = spd_read_byte(ctrl->channel0[i], 18);
1490                 if (latencies < 0) goto hw_error;
1491                 if (latencies == 0) {
1492                         goto dimm_err;
1493                 }
1494
1495                 /* Compute the lowest cas latency supported */
1496                 latency = log2(latencies) -2;
1497
1498                 /* Walk through searching for the selected latency */
1499                 for(index = 0; index < 3; index++, latency++) {
1500                         if (!(latencies & (1 << latency))) {
1501                                 continue;
1502                         }
1503                         if (latency == min_latency)
1504                                 break;
1505                 }
1506                 /* If I can't find the latency or my index is bad error */
1507                 if ((latency != min_latency) || (index >= 3)) {
1508                         goto dimm_err;
1509                 }
1510                 
1511                 /* Read the min_cycle_time for this latency */
1512                 value = spd_read_byte(ctrl->channel0[i], latency_indicies[index]);
1513                 if (value < 0) goto hw_error;
1514                 
1515                 /* All is good if the selected clock speed 
1516                  * is what I need or slower.
1517                  */
1518                 if (value <= min_cycle_time) {
1519                         continue;
1520                 }
1521                 /* Otherwise I have an error, disable the dimm */
1522         dimm_err:
1523                 dimm_mask = disable_dimm(ctrl, i, dimm_mask);
1524         }
1525 #if 0
1526 //down speed for full load 4 rank support
1527 #if K8_4RANK_DIMM_SUPPORT
1528         if(dimm_mask == (3|(3<<DIMM_SOCKETS)) ) {
1529                 int ranks = 4;
1530                 for(i = 0; (i < 4) && (ctrl->channel0[i]); i++) {
1531                         int val;
1532                         if (!(dimm_mask & (1 << i))) {
1533                                 continue;
1534                         }
1535                         val = spd_read_byte(ctrl->channel0[i], 5);
1536                         if(val!=ranks) {
1537                                 ranks = val;
1538                                 break;
1539                         }
1540                 }
1541                 if(ranks==4) {
1542                         if(min_cycle_time <= 0x50 ) {
1543                                 min_cycle_time = 0x60;
1544                         }
1545                 }
1546                 
1547         }
1548 #endif
1549 #endif
1550         /* Now that I know the minimum cycle time lookup the memory parameters */
1551         result.param = get_mem_param(min_cycle_time);
1552
1553         /* Update DRAM Config High with our selected memory speed */
1554         value = pci_read_config32(ctrl->f2, DRAM_CONFIG_HIGH);
1555         value &= ~(DCH_MEMCLK_MASK << DCH_MEMCLK_SHIFT);
1556 #if 1
1557         /* Improves DQS centering by correcting for case when core speed multiplier and MEMCLK speed result in odd clock divisor, by selecting the next lowest memory speed, required only at DDR400 and higher speeds with certain DIMM loadings ---- cheating???*/
1558         if(!is_cpu_pre_e0()) {
1559                 if(min_cycle_time==0x50) {
1560                         value |= 1<<31;
1561                 }
1562         }
1563 #endif
1564
1565         value |= result.param->dch_memclk;
1566         pci_write_config32(ctrl->f2, DRAM_CONFIG_HIGH, value);
1567
1568         static const unsigned latencies[] = { DTL_CL_2, DTL_CL_2_5, DTL_CL_3 };
1569         /* Update DRAM Timing Low with our selected cas latency */
1570         value = pci_read_config32(ctrl->f2, DRAM_TIMING_LOW);
1571         value &= ~(DTL_TCL_MASK << DTL_TCL_SHIFT);
1572         value |= latencies[min_latency - 2] << DTL_TCL_SHIFT;
1573         pci_write_config32(ctrl->f2, DRAM_TIMING_LOW, value);
1574         
1575         result.dimm_mask = dimm_mask;
1576         return result;
1577  hw_error:
1578         result.param = (const struct mem_param *)0;
1579         result.dimm_mask = -1;
1580         return result;
1581 }
1582
1583
1584 static int update_dimm_Trc(const struct mem_controller *ctrl, const struct mem_param *param, int i)
1585 {
1586         unsigned clocks, old_clocks;
1587         uint32_t dtl;
1588         int value;
1589         value = spd_read_byte(ctrl->channel0[i], 41);
1590         if (value < 0) return -1;
1591         if ((value == 0) || (value == 0xff)) {
1592                 value = param->tRC;
1593         }
1594         clocks = ((value << 1) + param->divisor - 1)/param->divisor;
1595         if (clocks < DTL_TRC_MIN) {
1596                 clocks = DTL_TRC_MIN;
1597         }
1598         if (clocks > DTL_TRC_MAX) {
1599                 return 0;
1600         }
1601
1602         dtl = pci_read_config32(ctrl->f2, DRAM_TIMING_LOW);
1603         old_clocks = ((dtl >> DTL_TRC_SHIFT) & DTL_TRC_MASK) + DTL_TRC_BASE;
1604         if (old_clocks > clocks) {
1605                 clocks = old_clocks;
1606         }
1607         dtl &= ~(DTL_TRC_MASK << DTL_TRC_SHIFT);
1608         dtl |=  ((clocks - DTL_TRC_BASE) << DTL_TRC_SHIFT);
1609         pci_write_config32(ctrl->f2, DRAM_TIMING_LOW, dtl);
1610         return 1;
1611 }
1612
1613 static int update_dimm_Trfc(const struct mem_controller *ctrl, const struct mem_param *param, int i)
1614 {
1615         unsigned clocks, old_clocks;
1616         uint32_t dtl;
1617         int value;
1618         value = spd_read_byte(ctrl->channel0[i], 42);
1619         if (value < 0) return -1;
1620         if ((value == 0) || (value == 0xff)) {
1621                 value = param->tRFC;
1622         }
1623         clocks = ((value << 1) + param->divisor - 1)/param->divisor;
1624         if (clocks < DTL_TRFC_MIN) {
1625                 clocks = DTL_TRFC_MIN;
1626         }
1627         if (clocks > DTL_TRFC_MAX) {
1628                 return 0;
1629         }
1630         dtl = pci_read_config32(ctrl->f2, DRAM_TIMING_LOW);
1631         old_clocks = ((dtl >> DTL_TRFC_SHIFT) & DTL_TRFC_MASK) + DTL_TRFC_BASE;
1632         if (old_clocks > clocks) {
1633                 clocks = old_clocks;
1634         }
1635         dtl &= ~(DTL_TRFC_MASK << DTL_TRFC_SHIFT);
1636         dtl |= ((clocks - DTL_TRFC_BASE) << DTL_TRFC_SHIFT);
1637         pci_write_config32(ctrl->f2, DRAM_TIMING_LOW, dtl);
1638         return 1;
1639 }
1640
1641
1642 static int update_dimm_Trcd(const struct mem_controller *ctrl, const struct mem_param *param, int i)
1643 {
1644         unsigned clocks, old_clocks;
1645         uint32_t dtl;
1646         int value;
1647         value = spd_read_byte(ctrl->channel0[i], 29);
1648         if (value < 0) return -1;
1649         clocks = (value + (param->divisor << 1) -1)/(param->divisor << 1);
1650         if (clocks < DTL_TRCD_MIN) {
1651                 clocks = DTL_TRCD_MIN;
1652         }
1653         if (clocks > DTL_TRCD_MAX) {
1654                 return 0;
1655         }
1656         dtl = pci_read_config32(ctrl->f2, DRAM_TIMING_LOW);
1657         old_clocks = ((dtl >> DTL_TRCD_SHIFT) & DTL_TRCD_MASK) + DTL_TRCD_BASE;
1658         if (old_clocks > clocks) {
1659                 clocks = old_clocks;
1660         }
1661         dtl &= ~(DTL_TRCD_MASK << DTL_TRCD_SHIFT);
1662         dtl |= ((clocks - DTL_TRCD_BASE) << DTL_TRCD_SHIFT);
1663         pci_write_config32(ctrl->f2, DRAM_TIMING_LOW, dtl);
1664         return 1;
1665 }
1666
1667 static int update_dimm_Trrd(const struct mem_controller *ctrl, const struct mem_param *param, int i)
1668 {
1669         unsigned clocks, old_clocks;
1670         uint32_t dtl;
1671         int value;
1672         value = spd_read_byte(ctrl->channel0[i], 28);
1673         if (value < 0) return -1;
1674         clocks = (value + (param->divisor << 1) -1)/(param->divisor << 1);
1675         if (clocks < DTL_TRRD_MIN) {
1676                 clocks = DTL_TRRD_MIN;
1677         }
1678         if (clocks > DTL_TRRD_MAX) {
1679                 return 0;
1680         }
1681         dtl = pci_read_config32(ctrl->f2, DRAM_TIMING_LOW);
1682         old_clocks = ((dtl >> DTL_TRRD_SHIFT) & DTL_TRRD_MASK) + DTL_TRRD_BASE;
1683         if (old_clocks > clocks) {
1684                 clocks = old_clocks;
1685         }
1686         dtl &= ~(DTL_TRRD_MASK << DTL_TRRD_SHIFT);
1687         dtl |= ((clocks - DTL_TRRD_BASE) << DTL_TRRD_SHIFT);
1688         pci_write_config32(ctrl->f2, DRAM_TIMING_LOW, dtl);
1689         return 1;
1690 }
1691
1692 static int update_dimm_Tras(const struct mem_controller *ctrl, const struct mem_param *param, int i)
1693 {
1694         unsigned clocks, old_clocks;
1695         uint32_t dtl;
1696         int value;
1697         value = spd_read_byte(ctrl->channel0[i], 30);
1698         if (value < 0) return -1;
1699         clocks = ((value << 1) + param->divisor - 1)/param->divisor;
1700         if (clocks < DTL_TRAS_MIN) {
1701                 clocks = DTL_TRAS_MIN;
1702         }
1703         if (clocks > DTL_TRAS_MAX) {
1704                 return 0;
1705         }
1706         dtl = pci_read_config32(ctrl->f2, DRAM_TIMING_LOW);
1707         old_clocks = ((dtl >> DTL_TRAS_SHIFT) & DTL_TRAS_MASK) + DTL_TRAS_BASE;
1708         if (old_clocks > clocks) {
1709                 clocks = old_clocks;
1710         }
1711         dtl &= ~(DTL_TRAS_MASK << DTL_TRAS_SHIFT);
1712         dtl |= ((clocks - DTL_TRAS_BASE) << DTL_TRAS_SHIFT);
1713         pci_write_config32(ctrl->f2, DRAM_TIMING_LOW, dtl);
1714         return 1;
1715 }
1716
1717 static int update_dimm_Trp(const struct mem_controller *ctrl, const struct mem_param *param, int i)
1718 {
1719         unsigned clocks, old_clocks;
1720         uint32_t dtl;
1721         int value;
1722         value = spd_read_byte(ctrl->channel0[i], 27);
1723         if (value < 0) return -1;
1724         clocks = (value + (param->divisor << 1) - 1)/(param->divisor << 1);
1725         if (clocks < DTL_TRP_MIN) {
1726                 clocks = DTL_TRP_MIN;
1727         }
1728         if (clocks > DTL_TRP_MAX) {
1729                 return 0;
1730         }
1731         dtl = pci_read_config32(ctrl->f2, DRAM_TIMING_LOW);
1732         old_clocks = ((dtl >> DTL_TRP_SHIFT) & DTL_TRP_MASK) + DTL_TRP_BASE;
1733         if (old_clocks > clocks) {
1734                 clocks = old_clocks;
1735         }
1736         dtl &= ~(DTL_TRP_MASK << DTL_TRP_SHIFT);
1737         dtl |= ((clocks - DTL_TRP_BASE) << DTL_TRP_SHIFT);
1738         pci_write_config32(ctrl->f2, DRAM_TIMING_LOW, dtl);
1739         return 1;
1740 }
1741
1742 static void set_Twr(const struct mem_controller *ctrl, const struct mem_param *param)
1743 {
1744         uint32_t dtl;
1745         dtl = pci_read_config32(ctrl->f2, DRAM_TIMING_LOW);
1746         dtl &= ~(DTL_TWR_MASK << DTL_TWR_SHIFT);
1747         dtl |= (param->dtl_twr - DTL_TWR_BASE) << DTL_TWR_SHIFT;
1748         pci_write_config32(ctrl->f2, DRAM_TIMING_LOW, dtl);
1749 }
1750
1751
1752 static void init_Tref(const struct mem_controller *ctrl, const struct mem_param *param)
1753 {
1754         uint32_t dth;
1755         dth = pci_read_config32(ctrl->f2, DRAM_TIMING_HIGH);
1756         dth &= ~(DTH_TREF_MASK << DTH_TREF_SHIFT);
1757         dth |= (param->dch_tref4k << DTH_TREF_SHIFT);
1758         pci_write_config32(ctrl->f2, DRAM_TIMING_HIGH, dth);
1759 }
1760
1761 static int update_dimm_Tref(const struct mem_controller *ctrl, const struct mem_param *param, int i)
1762 {
1763         uint32_t dth;
1764         int value;
1765         unsigned tref, old_tref;
1766         value = spd_read_byte(ctrl->channel0[i], 3);
1767         if (value < 0) return -1;
1768         value &= 0xf;
1769
1770         tref = param->dch_tref8k;
1771         if (value == 12) {
1772                 tref = param->dch_tref4k;
1773         }
1774
1775         dth = pci_read_config32(ctrl->f2, DRAM_TIMING_HIGH);
1776         old_tref = (dth >> DTH_TREF_SHIFT) & DTH_TREF_MASK;
1777         if ((value == 12) && (old_tref == param->dch_tref4k)) {
1778                 tref = param->dch_tref4k;
1779         } else {
1780                 tref = param->dch_tref8k;
1781         }
1782         dth &= ~(DTH_TREF_MASK << DTH_TREF_SHIFT);
1783         dth |= (tref << DTH_TREF_SHIFT);
1784         pci_write_config32(ctrl->f2, DRAM_TIMING_HIGH, dth);
1785         return 1;
1786 }
1787
1788
1789 static int update_dimm_x4(const struct mem_controller *ctrl, const struct mem_param *param, int i)
1790 {
1791         uint32_t dcl;
1792         int value;
1793 #if K8_4RANK_DIMM_SUPPORT == 1
1794         int rank;
1795 #endif
1796         int dimm;
1797         value = spd_read_byte(ctrl->channel0[i], 13);
1798         if (value < 0) {
1799                 return -1;
1800         }
1801
1802 #if K8_4RANK_DIMM_SUPPORT == 1
1803         rank = spd_read_byte(ctrl->channel0[i], 5);       /* number of physical banks */
1804         if (rank < 0) {
1805                 return -1;      
1806         }
1807 #endif
1808
1809         dimm = 1<<(DCL_x4DIMM_SHIFT+i);
1810 #if K8_4RANK_DIMM_SUPPORT == 1
1811         if(rank==4) {
1812                 dimm |= 1<<(DCL_x4DIMM_SHIFT+i+2);
1813         }
1814 #endif
1815         dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
1816         dcl &= ~dimm;
1817         if (value == 4) {
1818                 dcl |= dimm;
1819         }
1820         pci_write_config32(ctrl->f2, DRAM_CONFIG_LOW, dcl);
1821         return 1;
1822 }
1823
1824 static int update_dimm_ecc(const struct mem_controller *ctrl, const struct mem_param *param, int i)
1825 {
1826         uint32_t dcl;
1827         int value;
1828         value = spd_read_byte(ctrl->channel0[i], 11);
1829         if (value < 0) {
1830                 return -1;
1831         }
1832         if (value != 2) {
1833                 dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
1834                 dcl &= ~DCL_DimmEccEn;
1835                 pci_write_config32(ctrl->f2, DRAM_CONFIG_LOW, dcl);
1836         }
1837         return 1;
1838 }
1839
1840 static int count_dimms(const struct mem_controller *ctrl)
1841 {
1842         int dimms;
1843         unsigned index;
1844         dimms = 0;
1845         for(index = 0; index < 8; index += 2) {
1846                 uint32_t csbase;
1847                 csbase = pci_read_config32(ctrl->f2, (DRAM_CSBASE + (index << 2)));
1848                 if (csbase & 1) {
1849                         dimms += 1;
1850                 }
1851         }
1852         return dimms;
1853 }
1854
1855 static void set_Twtr(const struct mem_controller *ctrl, const struct mem_param *param)
1856 {
1857         uint32_t dth;
1858         unsigned clocks;
1859         clocks = 1; /* AMD says hard code this */
1860         dth = pci_read_config32(ctrl->f2, DRAM_TIMING_HIGH);
1861         dth &= ~(DTH_TWTR_MASK << DTH_TWTR_SHIFT);
1862         dth |= ((clocks - DTH_TWTR_BASE) << DTH_TWTR_SHIFT);
1863         pci_write_config32(ctrl->f2, DRAM_TIMING_HIGH, dth);
1864 }
1865
1866 static void set_Trwt(const struct mem_controller *ctrl, const struct mem_param *param)
1867 {
1868         uint32_t dth, dtl;
1869         unsigned divisor;
1870         unsigned latency;
1871         unsigned clocks;
1872
1873         clocks = 0;
1874         dtl = pci_read_config32(ctrl->f2, DRAM_TIMING_LOW);
1875         latency = (dtl >> DTL_TCL_SHIFT) & DTL_TCL_MASK;
1876         divisor = param->divisor;
1877
1878         if (is_opteron(ctrl)) {
1879                 if (latency == DTL_CL_2) {
1880                         if (divisor == ((6 << 0) + 0)) {
1881                                 /* 166Mhz */
1882                                 clocks = 3;
1883                         }
1884                         else if (divisor > ((6 << 0)+0)) {
1885                                 /* 100Mhz && 133Mhz */
1886                                 clocks = 2;
1887                         }
1888                 }
1889                 else if (latency == DTL_CL_2_5) {
1890                         clocks = 3;
1891                 }
1892                 else if (latency == DTL_CL_3) {
1893                         if (divisor == ((6 << 0)+0)) {
1894                                 /* 166Mhz */
1895                                 clocks = 4;
1896                         }
1897                         else if (divisor > ((6 << 0)+0)) {
1898                                 /* 100Mhz && 133Mhz */
1899                                 clocks = 3;
1900                         }
1901                 }
1902         }
1903         else /* Athlon64 */ {
1904                 if (is_registered(ctrl)) {
1905                         if (latency == DTL_CL_2) {
1906                                 clocks = 2;
1907                         }
1908                         else if (latency == DTL_CL_2_5) {
1909                                 clocks = 3;
1910                         }
1911                         else if (latency == DTL_CL_3) {
1912                                 clocks = 3;
1913                         }
1914                 }
1915                 else /* Unbuffered */{
1916                         if (latency == DTL_CL_2) {
1917                                 clocks = 3;
1918                         }
1919                         else if (latency == DTL_CL_2_5) {
1920                                 clocks = 4;
1921                         }
1922                         else if (latency == DTL_CL_3) {
1923                                 clocks = 4;
1924                         }
1925                 }
1926         }
1927         if ((clocks < DTH_TRWT_MIN) || (clocks > DTH_TRWT_MAX)) {
1928                 die("Unknown Trwt\r\n");
1929         }
1930         
1931         dth = pci_read_config32(ctrl->f2, DRAM_TIMING_HIGH);
1932         dth &= ~(DTH_TRWT_MASK << DTH_TRWT_SHIFT);
1933         dth |= ((clocks - DTH_TRWT_BASE) << DTH_TRWT_SHIFT);
1934         pci_write_config32(ctrl->f2, DRAM_TIMING_HIGH, dth);
1935         return;
1936 }
1937
1938 static void set_Twcl(const struct mem_controller *ctrl, const struct mem_param *param)
1939 {
1940         /* Memory Clocks after CAS# */
1941         uint32_t dth;
1942         unsigned clocks;
1943         if (is_registered(ctrl)) {
1944                 clocks = 2;
1945         } else {
1946                 clocks = 1;
1947         }
1948         dth = pci_read_config32(ctrl->f2, DRAM_TIMING_HIGH);
1949         dth &= ~(DTH_TWCL_MASK << DTH_TWCL_SHIFT);
1950         dth |= ((clocks - DTH_TWCL_BASE) << DTH_TWCL_SHIFT);
1951         pci_write_config32(ctrl->f2, DRAM_TIMING_HIGH, dth);
1952 }
1953
1954
1955 static void set_read_preamble(const struct mem_controller *ctrl, const struct mem_param *param)
1956 {
1957         uint32_t dch;
1958         unsigned divisor;
1959         unsigned rdpreamble;
1960         divisor = param->divisor;
1961         dch = pci_read_config32(ctrl->f2, DRAM_CONFIG_HIGH);
1962         dch &= ~(DCH_RDPREAMBLE_MASK << DCH_RDPREAMBLE_SHIFT);
1963         rdpreamble = 0;
1964         if (is_registered(ctrl)) {
1965                 if (divisor == ((10 << 1)+0)) {
1966                         /* 100Mhz, 9ns */
1967                         rdpreamble = ((9 << 1)+ 0);
1968                 }
1969                 else if (divisor == ((7 << 1)+1)) {
1970                         /* 133Mhz, 8ns */
1971                         rdpreamble = ((8 << 1)+0);
1972                 }
1973                 else if (divisor == ((6 << 1)+0)) {
1974                         /* 166Mhz, 7.5ns */
1975                         rdpreamble = ((7 << 1)+1);
1976                 }
1977                 else if (divisor == ((5 << 1)+0)) {
1978                         /* 200Mhz,  7ns */
1979                         rdpreamble = ((7 << 1)+0);
1980                 }
1981         }
1982         else {
1983                 int slots;
1984                 int i;
1985                 slots = 0;
1986                 for(i = 0; i < 4; i++) {
1987                         if (ctrl->channel0[i]) {
1988                                 slots += 1;
1989                         }
1990                 }
1991                 if (divisor == ((10 << 1)+0)) {
1992                         /* 100Mhz */
1993                         if (slots <= 2) {
1994                                 /* 9ns */
1995                                 rdpreamble = ((9 << 1)+0);
1996                         } else {
1997                                 /* 14ns */
1998                                 rdpreamble = ((14 << 1)+0);
1999                         }
2000                 }
2001                 else if (divisor == ((7 << 1)+1)) {
2002                         /* 133Mhz */
2003                         if (slots <= 2) {
2004                                 /* 7ns */
2005                                 rdpreamble = ((7 << 1)+0);
2006                         } else {
2007                                 /* 11 ns */
2008                                 rdpreamble = ((11 << 1)+0);
2009                         }
2010                 }
2011                 else if (divisor == ((6 << 1)+0)) {
2012                         /* 166Mhz */
2013                         if (slots <= 2) {
2014                                 /* 6ns */
2015                                 rdpreamble = ((7 << 1)+0);
2016                         } else {
2017                                 /* 9ns */
2018                                 rdpreamble = ((9 << 1)+0);
2019                         }
2020                 }
2021                 else if (divisor == ((5 << 1)+0)) {
2022                         /* 200Mhz */
2023                         if (slots <= 2) {
2024                                 /* 5ns */
2025                                 rdpreamble = ((5 << 1)+0);
2026                         } else {
2027                                 /* 7ns */
2028                                 rdpreamble = ((7 << 1)+0);
2029                         }
2030                 }
2031         }
2032         if ((rdpreamble < DCH_RDPREAMBLE_MIN) || (rdpreamble > DCH_RDPREAMBLE_MAX)) {
2033                 die("Unknown rdpreamble");
2034         }
2035         dch |= (rdpreamble - DCH_RDPREAMBLE_BASE) << DCH_RDPREAMBLE_SHIFT;
2036         pci_write_config32(ctrl->f2, DRAM_CONFIG_HIGH, dch);
2037 }
2038
2039 static void set_max_async_latency(const struct mem_controller *ctrl, const struct mem_param *param)
2040 {
2041         uint32_t dch;
2042         unsigned async_lat;
2043         int dimms;
2044
2045         dimms = count_dimms(ctrl);
2046
2047         dch = pci_read_config32(ctrl->f2, DRAM_CONFIG_HIGH);
2048         dch &= ~(DCH_ASYNC_LAT_MASK << DCH_ASYNC_LAT_SHIFT);
2049         async_lat = 0;
2050         if (is_registered(ctrl)) {
2051                 if (dimms == 4) {
2052                         /* 9ns */
2053                         async_lat = 9;
2054                 } 
2055                 else {
2056                         /* 8ns */
2057                         async_lat = 8;
2058                 }
2059         }
2060         else {
2061                 if (dimms > 3) {
2062                         die("Too many unbuffered dimms");
2063                 }
2064                 else if (dimms == 3) {
2065                         /* 7ns */
2066                         async_lat = 7;
2067                 }
2068                 else {
2069                         /* 6ns */
2070                         async_lat = 6;
2071                 }
2072         }
2073         dch |= ((async_lat - DCH_ASYNC_LAT_BASE) << DCH_ASYNC_LAT_SHIFT);
2074         pci_write_config32(ctrl->f2, DRAM_CONFIG_HIGH, dch);
2075 }
2076
2077 static void set_idle_cycle_limit(const struct mem_controller *ctrl, const struct mem_param *param)
2078 {
2079         uint32_t dch;
2080         /* AMD says to Hardcode this */
2081         dch = pci_read_config32(ctrl->f2, DRAM_CONFIG_HIGH);
2082         dch &= ~(DCH_IDLE_LIMIT_MASK << DCH_IDLE_LIMIT_SHIFT);
2083         dch |= DCH_IDLE_LIMIT_16 << DCH_IDLE_LIMIT_SHIFT;
2084         dch |= DCH_DYN_IDLE_CTR_EN;
2085         pci_write_config32(ctrl->f2, DRAM_CONFIG_HIGH, dch);
2086 }
2087
2088 static long spd_set_dram_timing(const struct mem_controller *ctrl, const struct mem_param *param, long dimm_mask)
2089 {
2090         int i;
2091         
2092         init_Tref(ctrl, param);
2093         for(i = 0; i < DIMM_SOCKETS; i++) {
2094                 int rc;
2095                 if (!(dimm_mask & (1 << i))) {
2096                         continue;
2097                 }
2098                 /* DRAM Timing Low Register */
2099                 if ((rc = update_dimm_Trc (ctrl, param, i)) <= 0) goto dimm_err;
2100                 if ((rc = update_dimm_Trfc(ctrl, param, i)) <= 0) goto dimm_err;
2101                 if ((rc = update_dimm_Trcd(ctrl, param, i)) <= 0) goto dimm_err;
2102                 if ((rc = update_dimm_Trrd(ctrl, param, i)) <= 0) goto dimm_err;
2103                 if ((rc = update_dimm_Tras(ctrl, param, i)) <= 0) goto dimm_err;
2104                 if ((rc = update_dimm_Trp (ctrl, param, i)) <= 0) goto dimm_err;
2105
2106                 /* DRAM Timing High Register */
2107                 if ((rc = update_dimm_Tref(ctrl, param, i)) <= 0) goto dimm_err;
2108         
2109
2110                 /* DRAM Config Low */
2111                 if ((rc = update_dimm_x4 (ctrl, param, i)) <= 0) goto dimm_err;
2112                 if ((rc = update_dimm_ecc(ctrl, param, i)) <= 0) goto dimm_err;
2113                 continue;
2114         dimm_err:
2115                 if (rc < 0) {
2116                         return -1;
2117                 }
2118                 dimm_mask = disable_dimm(ctrl, i, dimm_mask);
2119         }
2120         /* DRAM Timing Low Register */
2121         set_Twr(ctrl, param);
2122
2123         /* DRAM Timing High Register */
2124         set_Twtr(ctrl, param);
2125         set_Trwt(ctrl, param);
2126         set_Twcl(ctrl, param);
2127
2128         /* DRAM Config High */
2129         set_read_preamble(ctrl, param);
2130         set_max_async_latency(ctrl, param);
2131         set_idle_cycle_limit(ctrl, param);
2132         return dimm_mask;
2133 }
2134
2135 static void sdram_set_spd_registers(const struct mem_controller *ctrl) 
2136 {
2137         struct spd_set_memclk_result result;
2138         const struct mem_param *param;
2139         long dimm_mask;
2140 #if 1
2141         if (!controller_present(ctrl)) {
2142 //              print_debug("No memory controller present\r\n");
2143                 return;
2144         }
2145 #endif
2146         hw_enable_ecc(ctrl);
2147         activate_spd_rom(ctrl);
2148         dimm_mask = spd_detect_dimms(ctrl);
2149         if (!(dimm_mask & ((1 << DIMM_SOCKETS) - 1))) {
2150                 print_debug("No memory for this cpu\r\n");
2151                 return;
2152         }
2153         dimm_mask = spd_enable_2channels(ctrl, dimm_mask);        
2154         if (dimm_mask < 0) 
2155                 goto hw_spd_err;
2156         dimm_mask = spd_set_ram_size(ctrl , dimm_mask);           
2157         if (dimm_mask < 0) 
2158                 goto hw_spd_err;
2159         dimm_mask = spd_handle_unbuffered_dimms(ctrl, dimm_mask); 
2160         if (dimm_mask < 0) 
2161                 goto hw_spd_err;
2162         result = spd_set_memclk(ctrl, dimm_mask);
2163         param     = result.param;
2164         dimm_mask = result.dimm_mask;
2165         if (dimm_mask < 0) 
2166                 goto hw_spd_err;
2167         dimm_mask = spd_set_dram_timing(ctrl, param , dimm_mask);
2168         if (dimm_mask < 0)
2169                 goto hw_spd_err;
2170         order_dimms(ctrl);
2171         return;
2172  hw_spd_err:
2173         /* Unrecoverable error reading SPD data */
2174         print_err("SPD error - reset\r\n");
2175         hard_reset();
2176         return;
2177 }
2178
2179 #define TIMEOUT_LOOPS 300000
2180 static void sdram_enable(int controllers, const struct mem_controller *ctrl)
2181 {
2182         int i;
2183
2184         /* Error if I don't have memory */
2185         if (memory_end_k(ctrl, controllers) == 0) {
2186                 die("No memory\r\n");
2187         }
2188
2189         /* Before enabling memory start the memory clocks */
2190         for(i = 0; i < controllers; i++) {
2191                 uint32_t dch;
2192                 if (!controller_present(ctrl + i))
2193                         continue;
2194                 dch = pci_read_config32(ctrl[i].f2, DRAM_CONFIG_HIGH);
2195                 if (dch & (DCH_MEMCLK_EN0|DCH_MEMCLK_EN1|DCH_MEMCLK_EN2|DCH_MEMCLK_EN3)) {
2196                         dch |= DCH_MEMCLK_VALID;
2197                         pci_write_config32(ctrl[i].f2, DRAM_CONFIG_HIGH, dch);
2198                 }
2199                 else {
2200                         /* Disable dram receivers */
2201                         uint32_t dcl;
2202                         dcl = pci_read_config32(ctrl[i].f2, DRAM_CONFIG_LOW);
2203                         dcl |= DCL_DisInRcvrs;
2204                         pci_write_config32(ctrl[i].f2, DRAM_CONFIG_LOW, dcl);
2205                 }
2206         }
2207
2208         /* And if necessary toggle the the reset on the dimms by hand */
2209         memreset(controllers, ctrl);
2210
2211         for(i = 0; i < controllers; i++) {
2212                 uint32_t dcl, dch;
2213                 if (!controller_present(ctrl + i))
2214                         continue;
2215                 /* Skip everything if I don't have any memory on this controller */
2216                 dch = pci_read_config32(ctrl[i].f2, DRAM_CONFIG_HIGH);
2217                 if (!(dch & DCH_MEMCLK_VALID)) {
2218                         continue;
2219                 }
2220
2221                 /* Toggle DisDqsHys to get it working */
2222                 dcl = pci_read_config32(ctrl[i].f2, DRAM_CONFIG_LOW);
2223                 if (dcl & DCL_DimmEccEn) {
2224                         uint32_t mnc;
2225                         print_spew("ECC enabled\r\n");
2226                         mnc = pci_read_config32(ctrl[i].f3, MCA_NB_CONFIG);
2227                         mnc |= MNC_ECC_EN;
2228                         if (dcl & DCL_128BitEn) {
2229                                 mnc |= MNC_CHIPKILL_EN;
2230                         }
2231                         pci_write_config32(ctrl[i].f3, MCA_NB_CONFIG, mnc);
2232                 }
2233                 dcl |= DCL_DisDqsHys;
2234                 pci_write_config32(ctrl[i].f2, DRAM_CONFIG_LOW, dcl);
2235                 dcl &= ~DCL_DisDqsHys;
2236                 dcl &= ~DCL_DLL_Disable;
2237                 dcl &= ~DCL_D_DRV;
2238                 dcl &= ~DCL_QFC_EN;
2239                 dcl |= DCL_DramInit;
2240                 pci_write_config32(ctrl[i].f2, DRAM_CONFIG_LOW, dcl);
2241
2242         }
2243         for(i = 0; i < controllers; i++) {
2244                 uint32_t dcl, dch;
2245                 if (!controller_present(ctrl + i))
2246                         continue;
2247                 /* Skip everything if I don't have any memory on this controller */
2248                 dch = pci_read_config32(ctrl[i].f2, DRAM_CONFIG_HIGH);
2249                 if (!(dch & DCH_MEMCLK_VALID)) {
2250                         continue;
2251                 }
2252
2253                 print_debug("Initializing memory: ");
2254                 int loops = 0;
2255                 do {
2256                         dcl = pci_read_config32(ctrl[i].f2, DRAM_CONFIG_LOW);
2257                         loops += 1;
2258                         if ((loops & 1023) == 0) {
2259                                 print_debug(".");
2260                         }
2261                 } while(((dcl & DCL_DramInit) != 0) && (loops < TIMEOUT_LOOPS));
2262                 if (loops >= TIMEOUT_LOOPS) {
2263                         print_debug(" failed\r\n");
2264                         continue;
2265                 }
2266                 if (!is_cpu_pre_c0()) {
2267                         /* Wait until it is safe to touch memory */
2268                         dcl &= ~(DCL_MemClrStatus | DCL_DramEnable);
2269                         pci_write_config32(ctrl[i].f2, DRAM_CONFIG_LOW, dcl);
2270                         do {
2271                                 dcl = pci_read_config32(ctrl[i].f2, DRAM_CONFIG_LOW);
2272                         } while(((dcl & DCL_MemClrStatus) == 0) || ((dcl & DCL_DramEnable) == 0) );
2273                 }
2274
2275                         // init e0 mem hole here
2276 #if K8_E0_MEM_HOLE_SIZEK != 0
2277                 if (!is_cpu_pre_e0()) {
2278                         uint32_t base, limit;
2279                         unsigned base_k, limit_k;
2280                         base  = pci_read_config32(ctrl->f1, 0x40 + (i << 3));
2281                         limit = pci_read_config32(ctrl->f1, 0x44 + (i << 3));
2282                         base_k = (base & 0xffff0000) >> 2;
2283                         limit_k = ((limit + 0x00010000) & 0xffff0000) >> 2;
2284                         if ((base_k <= K8_E0_MEM_HOLE_BASEK) && (limit_k > K8_E0_MEM_HOLE_BASEK)) {
2285                                 set_e0_mem_hole(ctrl+i, base_k);
2286                         }
2287                 }
2288         
2289 #endif  
2290
2291                 print_debug(" done\r\n");
2292         }
2293
2294         //FIXME add enable node interleaving here --yhlu
2295         /*needed?
2296                 1. check how many nodes we have , if not all has ram installed get out
2297                 2. check cs_base lo is 0, node 0 f2 0x40,,,,, if any one is not using lo is CS_BASE, get out
2298                 3. check if other node is the same as node 0 about f2 0x40,,,,, otherwise get out
2299                 4. if all ready enable node_interleaving in f1 0x40..... of every node
2300                 5. for node interleaving we need to set mem hole to every node ( need recalcute hole offset in f0 for every node)
2301         */
2302
2303
2304         /* Make certain the first 1M of memory is intialized */
2305         print_debug("Clearing initial memory region: ");
2306
2307         /* Use write combine caching while we setup the  first 1M */
2308         cache_lbmem(MTRR_TYPE_WRCOMB);
2309
2310         /* clear memory 1meg */
2311         clear_memory((void *)0, CONFIG_LB_MEM_TOPK << 10);
2312
2313         /* The first 1M is now setup, use it */
2314         cache_lbmem(MTRR_TYPE_WRBACK);
2315         
2316         print_debug(" done\r\n");
2317 }