YhLu's patch from January 18th. This part is mostly cleaning up
[coreboot.git] / src / northbridge / amd / amdk8 / raminit_f.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         2005.10 yhlu make it support DDR2 only
6 */
7
8 #include <cpu/x86/mem.h>
9 #include <cpu/x86/cache.h>
10 #include <cpu/x86/mtrr.h>
11 #include <cpu/x86/tsc.h>
12
13 #include "raminit.h"
14 #include "amdk8_f.h"
15 #include "spd_ddr2.h"
16
17 #ifndef QRANK_DIMM_SUPPORT
18 #define QRANK_DIMM_SUPPORT 0
19 #endif
20
21 static inline void print_raminit(const char *strval, uint32_t val)
22 {
23 #if CONFIG_USE_PRINTK_IN_CAR
24         printk_debug("%s%08x\r\n", strval, val);
25 #else
26         print_debug(strval); print_debug_hex32(val); print_debug("\r\n");
27 #endif
28 }
29
30 #define RAM_TIMING_DEBUG 0
31
32 static inline void print_tx(const char *strval, uint32_t val)
33 {
34 #if RAM_TIMING_DEBUG == 1
35         print_raminit(strval, val);
36 #endif
37 }
38
39
40 static inline void print_t(const char *strval)
41 {
42 #if RAM_TIMING_DEBUG == 1
43         print_debug(strval); 
44 #endif
45 }
46
47
48
49 #if (CONFIG_LB_MEM_TOPK & (CONFIG_LB_MEM_TOPK -1)) != 0
50 # error "CONFIG_LB_MEM_TOPK must be a power of 2"
51 #endif
52
53 #include "amdk8_f_pci.c"
54
55
56         // for PCI_ADDR(0, 0x18, 2, 0x98) index, and PCI_ADDR(0x, 0x18, 2, 0x9c) data
57         /*
58                 index: 
59                 [29: 0] DctOffset (Dram Controller Offset)
60                 [30:30] DctAccessWrite (Dram Controller Read/Write Select)      
61                         0 = read access
62                         1 = write access
63                 [31:31] DctAccessDone (Dram Controller Access Done)
64                         0 = Access in progress
65                         1 = No access is progress
66
67                 Data:
68                 [31: 0] DctOffsetData (Dram Controller Offset Data)
69                 
70                 Read:
71                         - Write the register num to DctOffset with DctAccessWrite = 0
72                         - poll the DctAccessDone until it = 1
73                         - Read the data from DctOffsetData
74                 Write:
75                         - Write the data to DctOffsetData
76                         - Write register num to DctOffset with DctAccessWrite = 1
77                         - poll the DctAccessDone untio it = 1
78                 
79         */
80
81
82 static void setup_resource_map(const unsigned int *register_values, int max)
83 {
84         int i;
85         for(i = 0; i < max; i += 3) {
86                 device_t dev;
87                 unsigned where;
88                 unsigned long reg;
89                 dev = register_values[i] & ~0xff;
90                 where = register_values[i] & 0xff;
91                 reg = pci_read_config32(dev, where);
92                 reg &= register_values[i+1];
93                 reg |= register_values[i+2];
94                 pci_write_config32(dev, where, reg);
95         }
96 }
97
98 static int controller_present(const struct mem_controller *ctrl)
99 {
100         return pci_read_config32(ctrl->f0, 0) == 0x11001022;
101 }
102
103 static void sdram_set_registers(const struct mem_controller *ctrl, struct sys_info *sysinfo)
104 {
105         static const unsigned int register_values[] = {
106
107         /* Careful set limit registers before base registers which contain the enables */
108         /* DRAM Limit i Registers
109          * F1:0x44 i = 0
110          * F1:0x4C i = 1
111          * F1:0x54 i = 2
112          * F1:0x5C i = 3
113          * F1:0x64 i = 4
114          * F1:0x6C i = 5
115          * F1:0x74 i = 6
116          * F1:0x7C i = 7
117          * [ 2: 0] Destination Node ID
118          *         000 = Node 0
119          *         001 = Node 1
120          *         010 = Node 2
121          *         011 = Node 3
122          *         100 = Node 4
123          *         101 = Node 5
124          *         110 = Node 6
125          *         111 = Node 7
126          * [ 7: 3] Reserved
127          * [10: 8] Interleave select
128          *         specifies the values of A[14:12] to use with interleave enable.
129          * [15:11] Reserved
130          * [31:16] DRAM Limit Address i Bits 39-24
131          *         This field defines the upper address bits of a 40 bit  address
132          *         that define the end of the DRAM region.
133          */
134         PCI_ADDR(0, 0x18, 1, 0x44), 0x0000f8f8, 0x00000000,
135         PCI_ADDR(0, 0x18, 1, 0x4C), 0x0000f8f8, 0x00000001,
136         PCI_ADDR(0, 0x18, 1, 0x54), 0x0000f8f8, 0x00000002,
137         PCI_ADDR(0, 0x18, 1, 0x5C), 0x0000f8f8, 0x00000003,
138         PCI_ADDR(0, 0x18, 1, 0x64), 0x0000f8f8, 0x00000004,
139         PCI_ADDR(0, 0x18, 1, 0x6C), 0x0000f8f8, 0x00000005,
140         PCI_ADDR(0, 0x18, 1, 0x74), 0x0000f8f8, 0x00000006,
141         PCI_ADDR(0, 0x18, 1, 0x7C), 0x0000f8f8, 0x00000007,
142         /* DRAM Base i Registers
143          * F1:0x40 i = 0
144          * F1:0x48 i = 1
145          * F1:0x50 i = 2
146          * F1:0x58 i = 3
147          * F1:0x60 i = 4
148          * F1:0x68 i = 5
149          * F1:0x70 i = 6
150          * F1:0x78 i = 7
151          * [ 0: 0] Read Enable
152          *         0 = Reads Disabled
153          *         1 = Reads Enabled
154          * [ 1: 1] Write Enable
155          *         0 = Writes Disabled
156          *         1 = Writes Enabled
157          * [ 7: 2] Reserved
158          * [10: 8] Interleave Enable
159          *         000 = No interleave
160          *         001 = Interleave on A[12] (2 nodes)
161          *         010 = reserved
162          *         011 = Interleave on A[12] and A[14] (4 nodes)
163          *         100 = reserved
164          *         101 = reserved
165          *         110 = reserved
166          *         111 = Interleve on A[12] and A[13] and A[14] (8 nodes)
167          * [15:11] Reserved
168          * [13:16] DRAM Base Address i Bits 39-24
169          *         This field defines the upper address bits of a 40-bit address
170          *         that define the start of the DRAM region.
171          */
172         PCI_ADDR(0, 0x18, 1, 0x40), 0x0000f8fc, 0x00000000,
173         PCI_ADDR(0, 0x18, 1, 0x48), 0x0000f8fc, 0x00000000,
174         PCI_ADDR(0, 0x18, 1, 0x50), 0x0000f8fc, 0x00000000,
175         PCI_ADDR(0, 0x18, 1, 0x58), 0x0000f8fc, 0x00000000,
176         PCI_ADDR(0, 0x18, 1, 0x60), 0x0000f8fc, 0x00000000,
177         PCI_ADDR(0, 0x18, 1, 0x68), 0x0000f8fc, 0x00000000,
178         PCI_ADDR(0, 0x18, 1, 0x70), 0x0000f8fc, 0x00000000,
179         PCI_ADDR(0, 0x18, 1, 0x78), 0x0000f8fc, 0x00000000,
180
181         /* DRAM CS Base Address i Registers
182          * F2:0x40 i = 0
183          * F2:0x44 i = 1
184          * F2:0x48 i = 2
185          * F2:0x4C i = 3
186          * F2:0x50 i = 4
187          * F2:0x54 i = 5
188          * F2:0x58 i = 6
189          * F2:0x5C i = 7
190          * [ 0: 0] Chip-Select Bank Enable
191          *         0 = Bank Disabled
192          *         1 = Bank Enabled
193          * [ 1: 1] Spare Rank
194          * [ 2: 2] Memory Test Failed
195          * [ 4: 3] Reserved
196          * [13: 5] Base Address (21-13)
197          *         An optimization used when all DIMM are the same size...
198          * [18:14] Reserved
199          * [28:19] Base Address (36-27)
200          *         This field defines the top 11 addresses bit of a 40-bit
201          *         address that define the memory address space.  These
202          *         bits decode 32-MByte blocks of memory.
203          * [31:29] Reserved
204          */
205         PCI_ADDR(0, 0x18, 2, 0x40), 0xe007c018, 0x00000000,
206         PCI_ADDR(0, 0x18, 2, 0x44), 0xe007c018, 0x00000000,
207         PCI_ADDR(0, 0x18, 2, 0x48), 0xe007c018, 0x00000000,
208         PCI_ADDR(0, 0x18, 2, 0x4C), 0xe007c018, 0x00000000,
209         PCI_ADDR(0, 0x18, 2, 0x50), 0xe007c018, 0x00000000,
210         PCI_ADDR(0, 0x18, 2, 0x54), 0xe007c018, 0x00000000,
211         PCI_ADDR(0, 0x18, 2, 0x58), 0xe007c018, 0x00000000,
212         PCI_ADDR(0, 0x18, 2, 0x5C), 0xe007c018, 0x00000000,
213         /* DRAM CS Mask Address i Registers
214          * F2:0x60 i = 0,1
215          * F2:0x64 i = 2,3
216          * F2:0x68 i = 4,5
217          * F2:0x6C i = 6,7
218          * Select bits to exclude from comparison with the DRAM Base address register.
219          * [ 4: 0] Reserved
220          * [13: 5] Address Mask (21-13)
221          *         Address to be excluded from the optimized case
222          * [18:14] Reserved
223          * [28:19] Address Mask (36-27)
224          *         The bits with an address mask of 1 are excluded from address comparison
225          * [31:29] Reserved
226          * 
227          */
228         PCI_ADDR(0, 0x18, 2, 0x60), 0xe007c01f, 0x00000000,
229         PCI_ADDR(0, 0x18, 2, 0x64), 0xe007c01f, 0x00000000,
230         PCI_ADDR(0, 0x18, 2, 0x68), 0xe007c01f, 0x00000000,
231         PCI_ADDR(0, 0x18, 2, 0x6C), 0xe007c01f, 0x00000000,
232
233         /* DRAM Control Register
234          * F2:0x78
235          * [ 3: 0] RdPtrInit ( Read Pointer Initial Value)
236          *      0x03-0x00: reserved
237          * [ 6: 4] RdPadRcvFifoDly (Read Delay from Pad Receive FIFO)
238          *      000 = reserved
239          *      001 = reserved
240          *      010 = 1.5 Memory Clocks
241          *      011 = 2 Memory Clocks
242          *      100 = 2.5 Memory Clocks
243          *      101 = 3 Memory Clocks
244          *      110 = 3.5 Memory Clocks
245          *      111 = Reseved
246          * [15: 7] Reserved
247          * [16:16] AltVidC3MemClkTriEn (AltVID Memory Clock Tristate Enable)
248          *      Enables the DDR memory clocks to be tristated when alternate VID mode is enabled. This bit has no effect if the DisNbClkRamp bit (F3, 0x88) is set
249          * [17:17] DllTempAdjTime (DLL Temperature Adjust Cycle Time)
250          *      0 = 5 ms
251          *      1 = 1 ms
252          * [18:18] DqsRcvEnTrain (DQS Receiver Enable Training Mode)
253          *      0 = Normal DQS Receiver enable operation
254          *      1 = DQS receiver enable training mode
255          * [31:19] reverved
256         */
257         PCI_ADDR(0, 0x18, 2, 0x78), 0xfff80000, (6<<4)|(6<<0),
258
259         /* DRAM Initialization Register
260          * F2:0x7C
261          * [15: 0] MrsAddress (Address for MRS/EMRS Commands)
262          *      this field specifies the dsata driven on the DRAM address pins 15-0 for MRS and EMRS commands
263          * [18:16] MrsBank (Bank Address for MRS/EMRS Commands)
264          *      this files specifies the data driven on the DRAM bank pins for the MRS and EMRS commands
265          * [23:19] reverved
266          * [24:24] SendPchgAll (Send Precharge All Command)
267          *      Setting this bit causes the DRAM controller to send a precharge all command. This bit is cleared by the hardware after the command completes
268          * [25:25] SendAutoRefresh (Send Auto Refresh Command)
269          *      Setting this bit causes the DRAM controller to send an auto refresh command. This bit is cleared by the hardware after the command completes
270          * [26:26] SendMrsCmd (Send MRS/EMRS Command)
271          *      Setting this bit causes the DRAM controller to send the MRS or EMRS command defined by the MrsAddress and MrsBank fields. This bit is cleared by the hardware adter the commmand completes
272          * [27:27] DeassertMemRstX (De-assert Memory Reset)
273          *      Setting this bit causes the DRAM controller to de-assert the memory reset pin. This bit cannot be used to assert the memory reset pin
274          * [28:28] AssertCke (Assert CKE)
275          *      setting this bit causes the DRAM controller to assert the CKE pins. This bit cannot be used to de-assert the CKE pins
276          * [30:29] reverved
277          * [31:31] EnDramInit (Enable DRAM Initialization)
278          *      Setting this bit puts the DRAM controller in a BIOS controlled DRAM initialization mode. BIOS must clear this bit aster DRAM initialization is complete.
279         */
280 //        PCI_ADDR(0, 0x18, 2, 0x7C), 0x60f80000, 0, 
281
282
283         /* DRAM Bank Address Mapping Register
284          * F2:0x80
285          * Specify the memory module size
286          * [ 3: 0] CS1/0 
287          * [ 7: 4] CS3/2
288          * [11: 8] CS5/4
289          * [15:12] CS7/6
290          * [31:16]
291               row    col   bank
292           0:  13     9      2    :128M
293           1:  13     10     2    :256M
294           2:  14     10     2    :512M
295           3:  13     11     2    :512M
296           4:  13     10     3    :512M
297           5:  14     10     3    :1G
298           6:  14     11     2    :1G
299           7:  15     10     3    :2G
300           8:  14     11     3    :2G
301           9:  15     11     3    :4G
302          10:  16     10     3    :4G
303          11:  16     11     3    :8G
304         */
305         PCI_ADDR(0, 0x18, 2, 0x80), 0xffff0000, 0x00000000,
306         /* DRAM Timing Low Register
307          * F2:0x88
308          * [ 2: 0] Tcl (Cas# Latency, Cas# to read-data-valid)
309          *         000 = reserved
310          *         001 = reserved
311          *         010 = CL 3
312          *         011 = CL 4
313          *         100 = CL 5
314          *         101 = CL 6
315          *         110 = reserved
316          *         111 = reserved
317          * [ 3: 3] Reserved
318          * [ 5: 4] Trcd (Ras#-active to Cas# read/write delay)
319          *         00 = 3 clocks
320          *         01 = 4 clocks
321          *         10 = 5 clocks
322          *         11 = 6 clocks
323          * [ 7: 6] Reserved
324          * [ 9: 8] Trp (Row Precharge Time, Precharge-to-Active or Auto-Refresh)
325          *         00 = 3 clocks
326          *         01 = 4 clocks
327          *         10 = 5 clocks
328          *         11 = 6 clocks
329          * [10:10] Reserved
330          * [11:11] Trtp (Read to Precharge Time, read Cas# to precharge time)
331          *         0 = 2 clocks for Burst Length of 32 Bytes
332          *             4 clocks for Burst Length of 64 Bytes
333          *         1 = 3 clocks for Burst Length of 32 Bytes
334          *             5 clocks for Burst Length of 64 Bytes
335          * [15:12] Tras (Minimum Ras# Active Time)
336          *         0000 = reserved
337          *         0001 = reserved
338          *         0010 = 5 bus clocks
339          *         ...
340          *         1111 = 18 bus clocks
341          * [19:16] Trc (Row Cycle Time, Ras#-active to Ras#-active or auto refresh of the same bank)
342          *         0000 = 11 bus clocks
343          *         0010 = 12 bus clocks
344          *         ...
345          *         1110 = 25 bus clocks
346          *         1111 = 26 bus clocks
347          * [21:20] Twr (Write Recovery Time, From the last data to precharge, writes can go back-to-back) 
348          *         00 = 3 bus clocks
349          *         01 = 4 bus clocks
350          *         10 = 5 bus clocks
351          *         11 = 6 bus clocks
352          * [23:22] Trrd (Active-to-active (Ras#-to-Ras#) Delay of different banks)
353          *         00 = 2 bus clocks
354          *         01 = 3 bus clocks
355          *         10 = 4 bus clocks
356          *         11 = 5 bus clocks
357          * [31:24] MemClkDis ( Disable the MEMCLK outputs for DRAM channel A, BIOS should set it to reduce the power consumption)
358          *         Bit          F(1207)         M2 Package      S1g1 Package
359          *          0           N/A             MA1_CLK1        N/A
360          *          1           N/A             MA0_CLK1        MA0_CLK1
361          *          2           MA3_CLK         N/A             N/A
362          *          3           MA2_CLK         N/A             N/A
363          *          4           MA1_CLK         MA1_CLK0        N/A
364          *          5           MA0_CLK         MA0_CLK0        MA0_CLK0
365          *          6           N/A             MA1_CLK2        N/A
366          *          7           N/A             MA0_CLK2        MA0_CLK2
367          */
368         PCI_ADDR(0, 0x18, 2, 0x88), 0x000004c8, 0xff000002 /* 0x03623125 */ ,
369         /* DRAM Timing High Register
370          * F2:0x8C
371          * [ 3: 0] Reserved
372          * [ 6: 4] TrwtTO (Read-to-Write Turnaround for Data, DQS Contention)
373          *         000 = 2 bus clocks
374          *         001 = 3 bus clocks
375          *         010 = 4 bus clocks
376          *         011 = 5 bus clocks
377          *         100 = 6 bus clocks
378          *         101 = 7 bus clocks
379          *         110 = 8 bus clocks
380          *         111 = 9 bus clocks
381          * [ 7: 7] Reserved
382          * [ 9: 8] Twtr (Internal DRAM Write-to-Read Command Delay, minium write-to-read delay when both access the same chip select)
383          *         00 = Reserved
384          *         01 = 1 bus clocks
385          *         10 = 2 bus clocks
386          *         11 = 3 bus clocks
387          * [11:10] Twrrd (Write to Read DIMM Termination Turnaround, minimum write-to-read delay when accessing two different DIMMs)
388          *         00 = 0 bus clocks
389          *         01 = 1 bus clocks
390          *         10 = 2 bus clocks
391          *         11 = 3 bus clocks
392          * [13:12] Twrwr (Write to Write Timing)
393          *         00 = 1 bus clocks ( 0 idle cycle on the bus)
394          *         01 = 2 bus clocks ( 1 idle cycle on the bus)
395          *         10 = 3 bus clocks ( 2 idle cycles on the bus)
396          *         11 = Reserved
397          * [15:14] Trdrd ( Read to Read Timing)
398          *         00 = 2 bus clocks ( 1 idle cycle on the bus)
399          *         01 = 3 bus clocks ( 2 idle cycles on the bus)
400          *         10 = 4 bus clocks ( 3 idle cycles on the bus)
401          *         11 = 5 bus clocks ( 4 idel cycles on the bus)
402          * [17:16] Tref (Refresh Rate)
403          *         00 = Undefined behavior
404          *         01 = Reserved
405          *         10 = Refresh interval of 7.8 microseconds
406          *         11 = Refresh interval of 3.9 microseconds
407          * [19:18] Reserved
408          * [22:20] Trfc0 ( Auto-Refresh Row Cycle Time for the Logical DIMM0, based on DRAM density and speed)
409          *         000 = 75 ns (all speeds, 256Mbit)
410          *         001 = 105 ns (all speeds, 512Mbit)
411          *         010 = 127.5 ns (all speeds, 1Gbit)
412          *         011 = 195 ns (all speeds, 2Gbit)
413          *         100 = 327.5 ns (all speeds, 4Gbit)
414          *         101 = reserved
415          *         110 = reserved
416          *         111 = reserved
417          * [25:23] Trfc1 ( Auto-Refresh Row Cycle Time for the Logical DIMM1, based on DRAM density and speed)
418          * [28:26] Trfc2 ( Auto-Refresh Row Cycle Time for the Logical DIMM2, based on DRAM density and speed)
419          * [31:29] Trfc3 ( Auto-Refresh Row Cycle Time for the Logical DIMM3, based on DRAM density and speed)
420          */
421         PCI_ADDR(0, 0x18, 2, 0x8c), 0x000c008f, (2 << 16)|(1 << 8),
422         /* DRAM Config Low Register
423          * F2:0x90
424          * [ 0: 0] InitDram (Initialize DRAM)
425          *         1 = write 1 cause DRAM controller to execute the DRAM initialization, when done it read to 0
426          * [ 1: 1] ExitSelfRef ( Exit Self Refresh Command )
427          *         1 = write 1 causes the DRAM controller to bring the DRAMs out fo self refresh mode
428          * [ 3: 2] Reserved
429          * [ 5: 4] DramTerm (DRAM Termination)
430          *         00 = On die termination disabled
431          *         01 = 75 ohms
432          *         10 = 150 ohms
433          *         11 = 50 ohms
434          * [ 6: 6] Reserved
435          * [ 7: 7] DramDrvWeak ( DRAM Drivers Weak Mode)
436          *         0 = Normal drive strength mode.
437          *         1 = Weak drive strength mode
438          * [ 8: 8] ParEn (Parity Enable)
439          *         1 = Enable address parity computation output, PAR, and enables the parity error input, ERR
440          * [ 9: 9] SelfRefRateEn (Faster Self Refresh Rate Enable)
441          *         1 = Enable high temperature ( two times normal ) self refresh rate
442          * [10:10] BurstLength32 ( DRAM Burst Length Set for 32 Bytes)
443          *         0 = 64-byte mode
444          *         1 = 32-byte mode
445          * [11:11] Width128 ( Width of DRAM interface) 
446          *         0 = the controller DRAM interface is 64-bits wide
447          *         1 = the controller DRAM interface is 128-bits wide
448          * [12:12] X4Dimm (DIMM 0 is x4)
449          * [13:13] X4Dimm (DIMM 1 is x4)
450          * [14:14] X4Dimm (DIMM 2 is x4)
451          * [15:15] X4Dimm (DIMM 3 is x4)
452          *         0 = DIMM is not x4
453          *         1 = x4 DIMM present
454          * [16:16] UnBuffDimm ( Unbuffered DIMMs)
455          *         0 = Buffered DIMMs
456          *         1 = Unbuffered DIMMs
457          * [18:17] Reserved
458          * [19:19] DimmEccEn ( DIMM ECC Enable )
459                    1 =  ECC checking is being enabled for all DIMMs on the DRAM controller ( Through F3 0x44[EccEn])
460          * [31:20] Reserved
461          */
462         PCI_ADDR(0, 0x18, 2, 0x90), 0xfff6004c, 0x00000010,
463         /* DRAM Config High Register
464          * F2:0x94
465          * [ 0: 2] MemClkFreq ( Memory Clock Frequency)
466          *         000 = 200MHz
467          *         001 = 266MHz
468          *         010 = 333MHz
469          *         011 = reserved
470          *         1xx = reserved
471          * [ 3: 3] MemClkFreqVal (Memory Clock Freqency Valid)
472          *         1 = BIOS need to set the bit when setting up MemClkFreq to the proper value  
473          * [ 7: 4] MaxAsyncLat ( Maximum Asynchronous Latency)
474          *         0000 = 0 ns
475          *         ...
476          *         1111 = 15 ns
477          * [11: 8] Reserved
478          * [12:12] RDqsEn ( Read DQS Enable) This bit is only be set if x8 registered DIMMs are present in the system
479          *         0 = DM pins function as data mask pins
480          *         1 = DM pins function as read DQS pins
481          * [13:13] Reserved
482          * [14:14] DisDramInterface ( Disable the DRAM interface ) When this bit is set, the DRAM controller is disabled, and interface in low power state
483          *         0 = Enabled (default)
484          *         1 = Disabled
485          * [15:15] PowerDownEn ( Power Down Mode Enable ) 
486          *         0 = Disabled (default)
487          *         1 = Enabled
488          * [16:16] PowerDown ( Power Down Mode )
489          *         0 = Channel CKE Control
490          *         1 = Chip Select CKE Control
491          * [17:17] FourRankSODimm (Four Rank SO-DIMM) 
492          *         1 = this bit is set by BIOS to indicate that a four rank SO-DIMM is present
493          * [18:18] FourRankRDimm (Four Rank Registered DIMM)
494          *         1 = this bit is set by BIOS to indicate that a four rank registered DIMM is present
495          * [19:19] Reserved
496          * [20:20] SlowAccessMode (Slow Access Mode (2T Mode))
497          *         0 = DRAM address and control signals are driven for one MEMCLK cycle
498          *         1 = One additional MEMCLK of setup time is provided on all DRAM address and control signals except CS, CKE, and ODT; i.e., these signals are drivern for two MEMCLK cycles rather than one
499          * [21:21] Reserved
500          * [22:22] BankSwizzleMode ( Bank Swizzle Mode), 
501          *         0 = Disabled (default)
502          *         1 = Enabled
503          * [23:23] Reserved
504          * [27:24] DcqBypassMax ( DRAM Controller Queue Bypass Maximum)
505          *         0000 = No bypass; the oldest request is never bypassed
506          *         0001 = The oldest request may be bypassed no more than 1 time
507          *         ...
508          *         1111 = The oldest request may be bypassed no more than 15 times
509          * [31:28] FourActWindow ( Four Bank Activate Window) , not more than 4 banks in a 8 bank device are activated
510          *         0000 = No tFAW window restriction 
511          *         0001 = 8 MEMCLK cycles
512          *         0010 = 9 MEMCLK cycles
513          *         ...
514          *         1101 = 20 MEMCLK cycles
515          *         111x = reserved
516          */
517         PCI_ADDR(0, 0x18, 2, 0x94), 0x00a82f00,0x00008000,
518         /* DRAM Delay Line Register
519          * F2:0xa0
520          * [ 0: 0] MemClrStatus (Memory Clear Status) :    ---------Readonly 
521          *         when set, this bit indicates that the memory clear function is complete. Only clear by reset. BIOS should not write or read the DRAM until this bit is set by hardware
522          * [ 1: 1] DisableJitter ( Disable Jitter)
523          *         When set the DDR compensation circuit will not change the values unless the change is more than one step from the current value 
524          * [ 3: 2] RdWrQByp ( Read/Write Queue Bypass Count)
525          *         00 = 2
526          *         01 = 4
527          *         10 = 8
528          *         11 = 16
529          * [ 4: 4] Mode64BitMux (Mismatched DIMM Support Enable)
530          *         1 When bit enables support for mismatched DIMMs when using 128-bit DRAM interface, the Width128 no effect, only for M2 and s1g1
531          * [ 5: 5] DCC_EN ( Dynamica Idle Cycle Counter Enable)
532          *         When set to 1, indicates that each entry in the page tables dynamically adjusts the idle cycle limit based on page Conflict/Page Miss (PC/PM) traffic
533          * [ 8: 6] ILD_lmt ( Idle Cycle Limit)
534          *         000 = 0 cycles
535          *         001 = 4 cycles
536          *         010 = 8 cycles
537          *         011 = 16 cycles
538          *         100 = 32 cycles
539          *         101 = 64 cycles
540          *         110 = 128 cycles
541          *         111 = 256 cycles 
542          * [ 9: 9] DramEnabled ( DRAM Enabled)
543          *         When Set, this bit indicates that the DRAM is enabled, this bit is set by hardware after DRAM initialization or on an exit from self refresh. The DRAM controller is intialized after the
544          *         hardware-controlled initialization process ( initiated by the F2 0x90[DramInit]) completes or when the BIOS-controlled initialization process completes (F2 0x7c(EnDramInit] is 
545          *         written from 1 to 0)
546          * [23:10] Reserved
547          * [31:24] MemClkDis ( Disable the MEMCLK outputs for DRAM channel B, BIOS should set it to reduce the power consumption)
548          *         Bit          F(1207)         M2 Package      S1g1 Package
549          *          0           N/A             MA1_CLK1        N/A
550          *          1           N/A             MA0_CLK1        MA0_CLK1
551          *          2           MA3_CLK         N/A             N/A
552          *          3           MA2_CLK         N/A             N/A
553          *          4           MA1_CLK         MA1_CLK0        N/A
554          *          5           MA0_CLK         MA0_CLK0        MA0_CLK0
555          *          6           N/A             MA1_CLK2        N/A
556          *          7           N/A             MA0_CLK2        MA0_CLK2
557          */
558         PCI_ADDR(0, 0x18, 2, 0xa0), 0x00fffc00, 0xff000000, 
559
560         /* DRAM Scrub Control Register
561          * F3:0x58
562          * [ 4: 0] DRAM Scrube Rate
563          * [ 7: 5] reserved
564          * [12: 8] L2 Scrub Rate
565          * [15:13] reserved
566          * [20:16] Dcache Scrub
567          * [31:21] reserved
568          *         Scrub Rates
569          *         00000 = Do not scrub
570          *         00001 =  40.00 ns
571          *         00010 =  80.00 ns
572          *         00011 = 160.00 ns
573          *         00100 = 320.00 ns
574          *         00101 = 640.00 ns
575          *         00110 =   1.28 us
576          *         00111 =   2.56 us
577          *         01000 =   5.12 us
578          *         01001 =  10.20 us
579          *         01011 =  41.00 us
580          *         01100 =  81.90 us
581          *         01101 = 163.80 us
582          *         01110 = 327.70 us
583          *         01111 = 655.40 us
584          *         10000 =   1.31 ms
585          *         10001 =   2.62 ms
586          *         10010 =   5.24 ms
587          *         10011 =  10.49 ms
588          *         10100 =  20.97 ms
589          *         10101 =  42.00 ms
590          *         10110 =  84.00 ms
591          *         All Others = Reserved
592          */
593         PCI_ADDR(0, 0x18, 3, 0x58), 0xffe0e0e0, 0x00000000,
594         /* DRAM Scrub Address Low Register
595          * F3:0x5C
596          * [ 0: 0] DRAM Scrubber Redirect Enable
597          *         0 = Do nothing
598          *         1 = Scrubber Corrects errors found in normal operation
599          * [ 5: 1] Reserved
600          * [31: 6] DRAM Scrub Address 31-6
601          */
602         PCI_ADDR(0, 0x18, 3, 0x5C), 0x0000003e, 0x00000000,
603         /* DRAM Scrub Address High Register
604          * F3:0x60
605          * [ 7: 0] DRAM Scrubb Address 39-32
606          * [31: 8] Reserved
607          */
608         PCI_ADDR(0, 0x18, 3, 0x60), 0xffffff00, 0x00000000,
609         };
610         // for PCI_ADDR(0, 0x18, 2, 0x98) index, and PCI_ADDR(0x, 0x18, 2, 0x9c) data
611         /*
612                 index: 
613                 [29: 0] DctOffset (Dram Controller Offset)
614                 [30:30] DctAccessWrite (Dram Controller Read/Write Select)      
615                         0 = read access
616                         1 = write access
617                 [31:31] DctAccessDone (Dram Controller Access Done)
618                         0 = Access in progress
619                         1 = No access is progress
620
621                 Data:
622                 [31: 0] DctOffsetData (Dram Controller Offset Data)
623                 
624                 Read:
625                         - Write the register num to DctOffset with DctAccessWrite = 0
626                         - poll the DctAccessDone until it = 1
627                         - Read the data from DctOffsetData
628                 Write:
629                         - Write the data to DctOffsetData
630                         - Write register num to DctOffset with DctAccessWrite = 1
631                         - poll the DctAccessDone untio it = 1
632                 
633         */
634         int i;
635         int max;
636
637         if (!controller_present(ctrl)) {
638                 sysinfo->ctrl_present[ctrl->node_id] = 0;
639                 return;
640         }
641         sysinfo->ctrl_present[ctrl->node_id] = 1;
642         
643         print_spew("setting up CPU");
644         print_spew_hex8(ctrl->node_id);
645         print_spew(" northbridge registers\r\n");
646         max = sizeof(register_values)/sizeof(register_values[0]);
647         for(i = 0; i < max; i += 3) {
648                 device_t dev;
649                 unsigned where;
650                 unsigned long reg;
651                 dev = (register_values[i] & ~0xff) - PCI_DEV(0, 0x18, 0) + ctrl->f0;
652                 where = register_values[i] & 0xff;
653                 reg = pci_read_config32(dev, where);
654                 reg &= register_values[i+1];
655                 reg |= register_values[i+2];
656                 pci_write_config32(dev, where, reg);
657         }
658
659         print_spew("done.\r\n");
660 }
661
662 static int is_dual_channel(const struct mem_controller *ctrl)
663 {
664         uint32_t dcl;
665         dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
666         return dcl & DCL_Width128;
667 }
668
669 static int is_opteron(const struct mem_controller *ctrl)
670 {
671         /* Test to see if I am an Opteron.  
672          * FIXME Testing dual channel capability is correct for now
673          * but a beter test is probably required.
674          * m2 and s1g1 support dual channel too. but only support unbuffered dimm
675          */
676 #warning "FIXME implement a better test for opterons"
677         uint32_t nbcap;
678         nbcap = pci_read_config32(ctrl->f3, NORTHBRIDGE_CAP);
679         return !!(nbcap & NBCAP_128Bit);
680 }
681
682 static int is_registered(const struct mem_controller *ctrl)
683 {
684         /* Test to see if we are dealing with registered SDRAM.
685          * If we are not registered we are unbuffered.
686          * This function must be called after spd_handle_unbuffered_dimms.
687          */
688         uint32_t dcl;
689         dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
690         return !(dcl & DCL_UnBuffDimm);
691 }
692
693 static void spd_get_dimm_size(unsigned device, struct dimm_size *sz)
694 {
695         /* Calculate the log base 2 size of a DIMM in bits */
696         int value;
697         sz->per_rank = 0;
698         sz->rows = 0;
699         sz->col = 0;
700         sz->rank = 0;
701
702         value = spd_read_byte(device, SPD_ROW_NUM);     /* rows */
703         if (value < 0) goto hw_err;
704         if ((value & 0xff) == 0) goto val_err; // max is 16 ?
705         sz->per_rank += value & 0xff;
706         sz->rows = value & 0xff;
707
708         value = spd_read_byte(device, SPD_COL_NUM);     /* columns */
709         if (value < 0) goto hw_err;
710         if ((value & 0xff) == 0) goto val_err;  //max is 11
711         sz->per_rank += value & 0xff;
712         sz->col = value & 0xff;
713
714         value = spd_read_byte(device, SPD_BANK_NUM);    /* banks */
715         if (value < 0) goto hw_err;
716         if ((value & 0xff) == 0) goto val_err;
717         sz->bank = log2(value & 0xff);  // convert 4 to 2, and 8 to 3
718         sz->per_rank += sz->bank;
719
720         /* Get the module data width and convert it to a power of two */
721         value = spd_read_byte(device, SPD_DATA_WIDTH);  
722         if (value < 0) goto hw_err;
723         value &= 0xff;
724         if ((value != 72) && (value != 64)) goto val_err;
725         sz->per_rank += log2(value) - 3; //64 bit So another 3 lines
726
727         /* How many ranks? */
728         value = spd_read_byte(device, SPD_MOD_ATTRIB_RANK);     /* number of physical banks */
729         if (value < 0) goto hw_err;
730 //      value >>= SPD_MOD_ATTRIB_RANK_NUM_SHIFT;
731         value &= SPD_MOD_ATTRIB_RANK_NUM_MASK;
732         value += SPD_MOD_ATTRIB_RANK_NUM_BASE; // 0-->1, 1-->2, 3-->4
733         /*
734           rank == 1 only one rank or say one side
735           rank == 2 two side , and two ranks
736           rank == 4 two side , and four ranks total
737           Some one side two ranks, because of stacked
738         */
739         if ((value != 1) && (value != 2) && (value != 4 )) {
740                 goto val_err;
741         }
742         sz->rank = value;
743
744         /* verify if per_rank is equal byte 31 
745           it has the DIMM size as a multiple of 128MB.
746          */
747         value = spd_read_byte(device, SPD_RANK_SIZE);
748         if (value < 0) goto hw_err;
749         value &= 0xff;
750         value = log2(value);
751         if(value <=4 ) value += 8; // add back to 1G to high
752         value += (27-5); // make 128MB to the real lines
753         if( value != (sz->per_rank)) { 
754                 print_err("Bad RANK Size --\r\n");
755                 goto val_err;
756         }
757
758         goto out;
759
760  val_err:
761         die("Bad SPD value\r\n");
762         /* If an hw_error occurs report that I have no memory */
763 hw_err:
764         sz->per_rank = 0;
765         sz->rows = 0;
766         sz->col = 0;
767         sz->bank = 0;
768         sz->rank = 0;
769  out:
770         return;
771 }
772
773 static void set_dimm_size(const struct mem_controller *ctrl, struct dimm_size *sz, unsigned index, int is_Width128)
774 {
775         uint32_t base0, base1;
776
777
778         /* For each base register.
779          * Place the dimm size in 32 MB quantities in the bits 31 - 21.
780          * The initialize dimm size is in bits.
781          * Set the base enable bit0.
782          */
783         
784         base0 = base1 = 0;
785
786         /* Make certain side1 of the dimm is at least 128MB */
787         if (sz->per_rank >= 27) {
788                 base0 = (1 << ((sz->per_rank - 27 ) + 19)) | 1;
789         }
790         
791         /* Make certain side2 of the dimm is at least 128MB */
792         if (sz->rank > 1) { // 2 ranks or 4 ranks
793                 base1 = (1 << ((sz->per_rank - 27 ) + 19)) | 1;
794         }
795
796         /* Double the size if we are using dual channel memory */
797         if (is_Width128) {
798                 base0 = (base0 << 1) | (base0 & 1);
799                 base1 = (base1 << 1) | (base1 & 1);
800         }
801
802         /* Clear the reserved bits */
803         base0 &= ~0xe007fffe;
804         base1 &= ~0xe007fffe;
805
806         /* Set the appropriate DIMM base address register */
807         pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1)+0)<<2), base0);
808         pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1)+1)<<2), base1);
809 #if QRANK_DIMM_SUPPORT == 1
810         if(sz->rank == 4) {
811                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1)+4)<<2), base0);
812                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1)+5)<<2), base1);
813         }
814 #endif
815
816         /* Enable the memory clocks for this DIMM by Clear the MemClkDis bit*/
817         if (base0) {
818                 uint32_t dword;
819                 uint32_t ClkDis0;
820 #if CPU_SOCKET_TYPE == 0x10 /* L1 */
821                 ClkDis0 = DTL_MemClkDis0;
822 #else 
823         #if CPU_SOCKET_TYPE == 0x11 /* AM2 */
824                 ClkDis0 = DTL_MemClkDis0_AM2;
825         #endif
826 #endif 
827
828                 dword = pci_read_config32(ctrl->f2, DRAM_TIMING_LOW); //Channel A
829                 dword &= ~(ClkDis0 >> index);
830 #if QRANK_DIMM_SUPPORT == 1
831                 if(sz->rank == 4) {
832                         dword &= ~(ClkDis0 >> (index+2));
833                 }
834 #endif
835                 pci_write_config32(ctrl->f2, DRAM_TIMING_LOW, dword);
836         
837                 if (is_Width128) { //Channel B  
838                         dword = pci_read_config32(ctrl->f2, DRAM_CTRL_MISC);
839                         dword &= ~(ClkDis0 >> index);
840 #if QRANK_DIMM_SUPPORT == 1
841                         if(sz->rank == 4) {
842                                 dword &= ~(ClkDis0 >> (index+2));
843                         }
844 #endif
845                         pci_write_config32(ctrl->f2, DRAM_CTRL_MISC, dword);
846                 }
847
848         }
849 }
850
851 /*    row    col   bank  for 64 bit
852   0:  13     9      2    :128M
853   1:  13     10     2    :256M
854   2:  14     10     2    :512M
855   3:  13     11     2    :512M
856   4:  13     10     3    :512M
857   5:  14     10     3    :1G
858   6:  14     11     2    :1G
859   7:  15     10     3    :2G
860   8:  14     11     3    :2G
861   9:  15     11     3    :4G
862  10:  16     10     3    :4G
863  11:  16     11     3    :8G
864 */
865
866 static void set_dimm_cs_map(const struct mem_controller *ctrl, struct dimm_size *sz, unsigned index)
867 {
868         static const uint8_t cs_map_aaa[24] = {
869                 /* (bank=2, row=13, col=9)(3, 16, 11) ---> (0, 0, 0) (1, 3, 2) */
870         //Bank2
871                 0, 1, 3,
872                 0, 2, 6,
873                 0, 0, 0,
874                 0, 0, 0,
875         //Bank3
876                 0, 4, 0,
877                 0, 5, 8,
878                 0, 7, 9,
879                 0,10,11,
880         };
881
882         uint32_t map;
883
884         map = pci_read_config32(ctrl->f2, DRAM_BANK_ADDR_MAP);
885         map &= ~(0xf << (index * 4));
886 #if QRANK_DIMM_SUPPORT == 1
887         if(sz->rank == 4) {
888                 map &= ~(0xf << ( (index + 2) * 4));
889         }
890 #endif
891
892         /* Make certain side1 of the dimm is at least 128MB */
893         if (sz->per_rank >= 27) {
894                 unsigned temp_map;
895                 temp_map = cs_map_aaa[(sz->bank-2)*3*4 + (sz->rows - 13)*3 + (sz->col - 9) ];
896                 map |= temp_map << (index*4);
897 #if QRANK_DIMM_SUPPORT == 1
898                 if(sz->rank == 4) {
899                        map |=  temp_map << ( (index + 2) * 4);
900                 }
901 #endif
902         }
903
904         pci_write_config32(ctrl->f2, DRAM_BANK_ADDR_MAP, map);
905
906 }
907
908 static long spd_set_ram_size(const struct mem_controller *ctrl, long dimm_mask, struct mem_info *meminfo)
909 {
910         int i;
911         
912         for(i = 0; i < DIMM_SOCKETS; i++) {
913                 struct dimm_size *sz = &(meminfo->sz[i]);
914                 if (!(dimm_mask & (1 << i))) {
915                         continue;
916                 }
917                 spd_get_dimm_size(ctrl->channel0[i], sz);
918                 if (sz->per_rank == 0) {
919                         return -1; /* Report SPD error */
920                 }
921                 set_dimm_size(ctrl, sz, i, meminfo->is_Width128);
922                 set_dimm_cs_map (ctrl, sz, i);
923         }
924         return dimm_mask;
925 }
926
927 static void route_dram_accesses(const struct mem_controller *ctrl,
928         unsigned long base_k, unsigned long limit_k)
929 {
930         /* Route the addresses to the controller node */
931         unsigned node_id;
932         unsigned limit;
933         unsigned base;
934         unsigned index;
935         unsigned limit_reg, base_reg;
936         device_t device;
937
938         node_id = ctrl->node_id;
939         index = (node_id << 3);
940         limit = (limit_k << 2);
941         limit &= 0xffff0000;
942         limit -= 0x00010000;
943         limit |= ( 0 << 8) | (node_id << 0);
944         base = (base_k << 2);
945         base &= 0xffff0000;
946         base |= (0 << 8) | (1<<1) | (1<<0);
947
948         limit_reg = 0x44 + index;
949         base_reg = 0x40 + index;
950         for(device = PCI_DEV(0, 0x18, 1); device <= PCI_DEV(0, 0x1f, 1); device += PCI_DEV(0, 1, 0)) {
951                 pci_write_config32(device, limit_reg, limit);
952                 pci_write_config32(device, base_reg, base);
953         }
954 }
955
956 static void set_top_mem(unsigned tom_k, unsigned hole_startk)
957 {
958         /* Error if I don't have memory */
959         if (!tom_k) {
960                 die("No memory?");
961         }
962
963         /* Report the amount of memory. */
964         print_debug("RAM: 0x");
965         print_debug_hex32(tom_k);
966         print_debug(" KB\r\n");
967
968         msr_t msr;
969         if(tom_k > (4*1024*1024)) {
970                 /* Now set top of memory */
971                 msr.lo = (tom_k & 0x003fffff) << 10;
972                 msr.hi = (tom_k & 0xffc00000) >> 22;
973                 wrmsr(TOP_MEM2, msr);
974         }
975
976         /* Leave a 64M hole between TOP_MEM and TOP_MEM2
977          * so I can see my rom chip and other I/O devices.
978          */
979         if (tom_k >= 0x003f0000) {
980 #if HW_MEM_HOLE_SIZEK != 0
981                 if(hole_startk != 0) {
982                         tom_k = hole_startk;
983                 } else
984 #endif
985                 tom_k = 0x3f0000;
986         }
987         msr.lo = (tom_k & 0x003fffff) << 10;
988         msr.hi = (tom_k & 0xffc00000) >> 22;
989         wrmsr(TOP_MEM, msr);
990 }
991
992 static unsigned long interleave_chip_selects(const struct mem_controller *ctrl, int is_Width128)
993 {
994         /* 35 - 27 */
995
996         static const uint8_t csbase_low_f0_shift[] = {
997         /* 128MB */       (14 - (13-5)),
998         /* 256MB */       (15 - (13-5)),
999         /* 512MB */       (15 - (13-5)),
1000         /* 512MB */       (16 - (13-5)),
1001         /* 512MB */       (16 - (13-5)),
1002         /* 1GB   */       (16 - (13-5)),
1003         /* 1GB   */       (16 - (13-5)),
1004         /* 2GB   */       (16 - (13-5)),
1005         /* 2GB   */       (17 - (13-5)),
1006         /* 4GB   */       (17 - (13-5)),
1007         /* 4GB   */       (16 - (13-5)),
1008         /* 8GB   */       (17 - (13-5)),
1009         };
1010
1011         /* cs_base_high is not changed */
1012
1013         uint32_t csbase_inc;
1014         int chip_selects, index;
1015         int bits;
1016         unsigned common_size;
1017         unsigned common_cs_mode;
1018         uint32_t csbase, csmask;
1019
1020         /* See if all of the memory chip selects are the same size
1021          * and if so count them.
1022          */
1023         chip_selects = 0;
1024         common_size = 0;
1025         common_cs_mode = 0xff;
1026         for(index = 0; index < 8; index++) {
1027                 unsigned size;
1028                 unsigned cs_mode;
1029                 uint32_t value;
1030                 
1031                 value = pci_read_config32(ctrl->f2, DRAM_CSBASE + (index << 2));
1032                 
1033                 /* Is it enabled? */
1034                 if (!(value & 1)) {
1035                         continue;
1036                 }
1037                 chip_selects++;
1038                 size = (value >> 19) & 0x3ff;
1039                 if (common_size == 0) {
1040                         common_size = size;
1041                 }
1042                 /* The size differed fail */
1043                 if (common_size != size) {
1044                         return 0;
1045                 }
1046
1047                 value = pci_read_config32(ctrl->f2, DRAM_BANK_ADDR_MAP);
1048                 cs_mode =( value >> ((index>>1)*4)) & 0xf;
1049                 if(common_cs_mode == 0xff) {
1050                         common_cs_mode = cs_mode;
1051                 }
1052                 /* The cs_mode differed fail */
1053                 if(common_cs_mode != cs_mode) {
1054                         return 0;
1055                 }
1056         }
1057
1058         /* Chip selects can only be interleaved when there is
1059          * more than one and their is a power of two of them.
1060          */
1061         bits = log2(chip_selects);
1062         if (((1 << bits) != chip_selects) || (bits < 1) || (bits > 3)) { //chip_selects max = 8
1063                 return 0;
1064         }
1065
1066         /* Find the bits of csbase that we need to interleave on */
1067         csbase_inc = 1 << (csbase_low_f0_shift[common_cs_mode]);
1068         if(is_Width128) {
1069                 csbase_inc <<=1;
1070         }   
1071         
1072
1073         /* Compute the initial values for csbase and csbask. 
1074          * In csbase just set the enable bit and the base to zero.
1075          * In csmask set the mask bits for the size and page level interleave.
1076          */
1077         csbase = 0 | 1;
1078         csmask = (((common_size  << bits) - 1) << 19);
1079         csmask |= 0x3fe0 & ~((csbase_inc << bits) - csbase_inc);
1080         for(index = 0; index < 8; index++) {
1081                 uint32_t value;
1082
1083                 value = pci_read_config32(ctrl->f2, DRAM_CSBASE + (index << 2));
1084                 /* Is it enabled? */
1085                 if (!(value & 1)) {
1086                         continue;
1087                 }
1088                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (index << 2), csbase);
1089                 if((index & 1) == 0) {  //only have 4 CSMASK
1090                         pci_write_config32(ctrl->f2, DRAM_CSMASK + ((index>>1) << 2), csmask);
1091                 }
1092                 csbase += csbase_inc;
1093         }
1094         
1095         print_debug("Interleaved\r\n");
1096
1097         /* Return the memory size in K */ 
1098         return common_size << ((27-10) + bits);
1099 }
1100 static unsigned long order_chip_selects(const struct mem_controller *ctrl)
1101 {
1102         unsigned long tom;
1103
1104         /* Remember which registers we have used in the high 8 bits of tom */
1105         tom = 0;
1106         for(;;) {
1107                 /* Find the largest remaining canidate */
1108                 unsigned index, canidate;
1109                 uint32_t csbase, csmask;
1110                 unsigned size;
1111                 csbase = 0;
1112                 canidate = 0;
1113                 for(index = 0; index < 8; index++) {
1114                         uint32_t value;
1115                         value = pci_read_config32(ctrl->f2, DRAM_CSBASE + (index << 2));
1116
1117                         /* Is it enabled? */
1118                         if (!(value & 1)) {
1119                                 continue;
1120                         }
1121                         
1122                         /* Is it greater? */
1123                         if (value <= csbase) {
1124                                 continue;
1125                         }
1126                         
1127                         /* Has it already been selected */
1128                         if (tom & (1 << (index + 24))) {
1129                                 continue;
1130                         }
1131                         /* I have a new canidate */
1132                         csbase = value;
1133                         canidate = index;
1134                 }
1135                 /* See if I have found a new canidate */
1136                 if (csbase == 0) {
1137                         break;
1138                 }
1139
1140                 /* Remember the dimm size */
1141                 size = csbase >> 19;
1142
1143                 /* Remember I have used this register */
1144                 tom |= (1 << (canidate + 24));
1145
1146                 /* Recompute the cs base register value */
1147                 csbase = (tom << 19) | 1;
1148
1149                 /* Increment the top of memory */
1150                 tom += size;
1151
1152                 /* Compute the memory mask */
1153                 csmask = ((size -1) << 19);
1154                 csmask |= 0x3fe0;               /* For now don't optimize */
1155
1156                 /* Write the new base register */
1157                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (canidate << 2), csbase);
1158                 /* Write the new mask register */
1159                 if((canidate & 1) == 0) {  //only have 4 CSMASK
1160                         pci_write_config32(ctrl->f2, DRAM_CSMASK + ((canidate>>1) << 2), csmask);
1161                 }
1162                 
1163         }
1164         /* Return the memory size in K */ 
1165         return (tom & ~0xff000000) << (27-10);
1166 }
1167
1168 unsigned long memory_end_k(const struct mem_controller *ctrl, int max_node_id)
1169 {
1170         unsigned node_id;
1171         unsigned end_k;
1172         /* Find the last memory address used */
1173         end_k = 0;
1174         for(node_id = 0; node_id < max_node_id; node_id++) {
1175                 uint32_t limit, base;
1176                 unsigned index;
1177                 index = node_id << 3;
1178                 base = pci_read_config32(ctrl->f1, 0x40 + index);
1179                 /* Only look at the limit if the base is enabled */
1180                 if ((base & 3) == 3) {
1181                         limit = pci_read_config32(ctrl->f1, 0x44 + index);
1182                         end_k = ((limit + 0x00010000) & 0xffff0000) >> 2;
1183                 }
1184         }
1185         return end_k;
1186 }
1187
1188 static void order_dimms(const struct mem_controller *ctrl, struct mem_info *meminfo)
1189 {
1190         unsigned long tom_k, base_k;
1191
1192         if (read_option(CMOS_VSTART_interleave_chip_selects, CMOS_VLEN_interleave_chip_selects, 1) != 0) {
1193                 tom_k = interleave_chip_selects(ctrl, meminfo->is_Width128);
1194         } else {
1195                 print_debug("Interleaving disabled\r\n");
1196                 tom_k = 0;
1197         }
1198         if (!tom_k) {
1199                 tom_k = order_chip_selects(ctrl);
1200         }
1201         /* Compute the memory base address */
1202         base_k = memory_end_k(ctrl, ctrl->node_id);
1203         tom_k += base_k;
1204         route_dram_accesses(ctrl, base_k, tom_k);
1205         set_top_mem(tom_k, 0);
1206 }
1207
1208 static long disable_dimm(const struct mem_controller *ctrl, unsigned index, long dimm_mask, struct mem_info *meminfo)
1209 {
1210         print_debug("disabling dimm"); 
1211         print_debug_hex8(index); 
1212         print_debug("\r\n");
1213         pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1)+0)<<2), 0);
1214         pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1)+1)<<2), 0);
1215 #if QRANK_DIMM_SUPPORT == 1
1216         if(meminfo->sz[index].rank == 4) {
1217                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1)+4)<<2), 0);
1218                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1)+5)<<2), 0);
1219         }
1220 #endif
1221
1222         dimm_mask &= ~(1 << index);
1223         return dimm_mask;
1224 }
1225
1226 static long spd_handle_unbuffered_dimms(const struct mem_controller *ctrl, long dimm_mask, struct mem_info *meminfo)
1227 {
1228         int i;
1229         uint32_t registered;
1230         uint32_t dcl;
1231         registered = 0;
1232         for(i = 0; (i < DIMM_SOCKETS); i++) {
1233                 int value;
1234                 if (!(dimm_mask & (1 << i))) {
1235                         continue;
1236                 }
1237                 value = spd_read_byte(ctrl->channel0[i], SPD_DIMM_TYPE);
1238                 if (value < 0) {
1239                         return -1;
1240                 }
1241                 /* Registered dimm ? */
1242                 value &= 0x3f;
1243                 if ((value == SPD_DIMM_TYPE_RDIMM) || (value == SPD_DIMM_TYPE_mRDIMM)) {
1244                         //check SPD_MOD_ATTRIB to verify it is SPD_MOD_ATTRIB_REGADC (0x11)?
1245                         registered |= (1<<i);
1246                 } 
1247         }
1248
1249         if (is_opteron(ctrl)) {
1250 #if 0
1251                 if ( registered != (dimm_mask & ((1<<DIMM_SOCKETS)-1)) ) {
1252                         dimm_mask &= (registered | (registered << DIMM_SOCKETS) ); //disable unbuffed dimm
1253         //              die("Mixed buffered and registered dimms not supported");
1254                 }
1255                 //By yhlu for debug M2, s1g1 can do dual channel, but it use unbuffer DIMM
1256                 if (!registered) {
1257                         die("Unbuffered Dimms not supported on Opteron");
1258                 }
1259 #endif
1260         }
1261
1262
1263         dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
1264         dcl &= ~DCL_UnBuffDimm;
1265         meminfo->is_registered = 1;
1266         if (!registered) {
1267                 dcl |= DCL_UnBuffDimm;
1268                 meminfo->is_registered = 0;
1269         }
1270         pci_write_config32(ctrl->f2, DRAM_CONFIG_LOW, dcl);
1271         
1272 #if 1
1273         if (meminfo->is_registered) {
1274                 print_debug("Registered\r\n");
1275         } else {
1276                 print_debug("Unbuffered\r\n");
1277         }
1278 #endif
1279         return dimm_mask;
1280 }
1281
1282 static unsigned int spd_detect_dimms(const struct mem_controller *ctrl)
1283 {
1284         unsigned dimm_mask;
1285         int i;
1286         dimm_mask = 0;
1287         for(i = 0; i < DIMM_SOCKETS; i++) {
1288                 int byte;
1289                 unsigned device;
1290                 device = ctrl->channel0[i];
1291                 if (device) {
1292                         byte = spd_read_byte(ctrl->channel0[i], SPD_MEM_TYPE);  /* Type */
1293                         if (byte == SPD_MEM_TYPE_SDRAM_DDR2) {
1294                                 dimm_mask |= (1 << i);
1295                         }
1296                 }
1297                 device = ctrl->channel1[i];
1298                 if (device) {
1299                         byte = spd_read_byte(ctrl->channel1[i], SPD_MEM_TYPE);
1300                         if (byte == SPD_MEM_TYPE_SDRAM_DDR2) {
1301                                 dimm_mask |= (1 << (i + DIMM_SOCKETS));
1302                         }
1303                 }
1304         }
1305         return dimm_mask;
1306 }
1307
1308 static long spd_enable_2channels(const struct mem_controller *ctrl, long dimm_mask, struct mem_info *meminfo)
1309 {
1310         int i;
1311         uint32_t nbcap;
1312         /* SPD addresses to verify are identical */
1313         static const uint8_t addresses[] = {
1314                 2,      /* Type should be DDR2 SDRAM */
1315                 3,      /* *Row addresses */
1316                 4,      /* *Column addresses */
1317                 5,      /* *Number of DIMM Ranks */
1318                 6,      /* *Module Data Width*/
1319                 9,      /* *Cycle time at highest CAS Latency CL=X */
1320                 11,     /* *DIMM Conf Type */
1321                 13,     /* *Pri SDRAM Width */
1322                 17,     /* *Logical Banks */
1323                 18,     /* *Supported CAS Latencies */
1324                 20,     /* *DIMM Type Info */
1325                 21,     /* *SDRAM Module Attributes */
1326                 23,     /* *Cycle time at CAS Latnecy (CLX - 1) */
1327                 26,     /* *Cycle time at CAS Latnecy (CLX - 2) */
1328                 27,     /* *tRP Row precharge time */
1329                 28,     /* *Minimum Row Active to Row Active Delay (tRRD) */
1330                 29,     /* *tRCD RAS to CAS */
1331                 30,     /* *tRAS Activate to Precharge */
1332                 36,     /* *Write recovery time (tWR) */
1333                 37,     /* *Internal write to read command delay (tRDP) */
1334                 38,     /* *Internal read to precharge commanfd delay (tRTP) */
1335                 41,     /* *Extension of Byte 41 tRC and Byte 42 tRFC */
1336                 41,     /* *Minimum Active to Active/Auto Refresh Time(Trc) */
1337                 42,     /* *Minimum Auto Refresh Command Time(Trfc) */
1338         };
1339         /* If the dimms are not in pairs do not do dual channels */
1340         if ((dimm_mask & ((1 << DIMM_SOCKETS) - 1)) !=
1341                 ((dimm_mask >> DIMM_SOCKETS) & ((1 << DIMM_SOCKETS) - 1))) { 
1342                 goto single_channel;
1343         }
1344         /* If the cpu is not capable of doing dual channels don't do dual channels */
1345         nbcap = pci_read_config32(ctrl->f3, NORTHBRIDGE_CAP);
1346         if (!(nbcap & NBCAP_128Bit)) {
1347                 goto single_channel;
1348         }
1349         for(i = 0; (i < 4) && (ctrl->channel0[i]); i++) {
1350                 unsigned device0, device1;
1351                 int value0, value1;
1352                 int j;
1353                 /* If I don't have a dimm skip this one */
1354                 if (!(dimm_mask & (1 << i))) {
1355                         continue;
1356                 }
1357                 device0 = ctrl->channel0[i];
1358                 device1 = ctrl->channel1[i];
1359                 for(j = 0; j < sizeof(addresses)/sizeof(addresses[0]); j++) {
1360                         unsigned addr;
1361                         addr = addresses[j];
1362                         value0 = spd_read_byte(device0, addr);
1363                         if (value0 < 0) {
1364                                 return -1;
1365                         }
1366                         value1 = spd_read_byte(device1, addr);
1367                         if (value1 < 0) {
1368                                 return -1;
1369                         }
1370                         if (value0 != value1) {
1371                                 goto single_channel;
1372                         }
1373                 }
1374         }
1375         print_spew("Enabling dual channel memory\r\n");
1376         uint32_t dcl;
1377         dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
1378         dcl &= ~DCL_BurstLength32;  /*  32byte mode may be preferred in platforms that include graphics controllers that generate a lot of 32-bytes system memory accesses
1379                                         32byte mode is not supported when the DRAM interface is 128 bits wides, even 32byte mode is set, system still use 64 byte mode  */
1380         dcl |= DCL_Width128;
1381         pci_write_config32(ctrl->f2, DRAM_CONFIG_LOW, dcl);
1382         meminfo->is_Width128 = 1;
1383         return dimm_mask;
1384  single_channel:
1385         dimm_mask &= ~((1 << (DIMM_SOCKETS *2)) - (1 << DIMM_SOCKETS));
1386         meminfo->is_Width128 = 0;
1387         return dimm_mask;
1388 }
1389
1390 struct mem_param {
1391         uint16_t cycle_time;
1392         uint8_t divisor; /* In 1/40 ns increments */
1393         uint8_t TrwtTO;
1394         uint8_t Twrrd;
1395         uint8_t Twrwr;
1396         uint8_t Trdrd;
1397         uint8_t DcqByPassMax;
1398         uint32_t dch_memclk;
1399         char name[9];
1400 };
1401
1402         static const struct mem_param speed[] = {
1403                 {
1404                         .name       = "200Mhz\r\n",
1405                         .cycle_time = 0x500,
1406                         .divisor    = 200, // how many 1/40ns per clock 
1407                         .dch_memclk = DCH_MemClkFreq_200MHz, //0
1408                         .TrwtTO     = 7,
1409                         .Twrrd      = 2,
1410                         .Twrwr      = 2,
1411                         .Trdrd      = 3,
1412                         .DcqByPassMax = 4,
1413
1414                 },
1415                 {
1416                         .name       = "266Mhz\r\n",
1417                         .cycle_time = 0x375,
1418                         .divisor    = 150, //????
1419                         .dch_memclk = DCH_MemClkFreq_266MHz, //1
1420                         .TrwtTO     = 7,
1421                         .Twrrd      = 2,
1422                         .Twrwr      = 2,
1423                         .Trdrd      = 3,
1424                         .DcqByPassMax = 4,
1425                 },
1426                 {
1427                         .name       = "333Mhz\r\n",
1428                         .cycle_time = 0x300,
1429                         .divisor    = 120,
1430                         .dch_memclk = DCH_MemClkFreq_333MHz, //2
1431                         .TrwtTO     = 7,
1432                         .Twrrd      = 2,
1433                         .Twrwr      = 2,
1434                         .Trdrd      = 3,
1435                         .DcqByPassMax = 4,
1436
1437                 },
1438                 {
1439                         .name       = "400Mhz\r\n",
1440                         .cycle_time = 0x250,
1441                         .divisor    = 100,
1442                         .dch_memclk = DCH_MemClkFreq_400MHz,//3
1443                         .TrwtTO     = 7,
1444                         .Twrrd      = 2,
1445                         .Twrwr      = 2,
1446                         .Trdrd      = 3,
1447                         .DcqByPassMax = 4,
1448                 },
1449                 {
1450                         .cycle_time = 0x000,
1451                 },
1452         };
1453
1454 static const struct mem_param *get_mem_param(unsigned min_cycle_time)
1455 {
1456
1457         const struct mem_param *param;
1458         for(param = &speed[0]; param->cycle_time ; param++) {
1459                 if (min_cycle_time > (param+1)->cycle_time) {
1460                         break;
1461                 }
1462         }
1463         if (!param->cycle_time) {
1464                 die("min_cycle_time to low");
1465         }
1466         print_spew(param->name);
1467 #ifdef DRAM_MIN_CYCLE_TIME
1468         print_debug(param->name);
1469 #endif
1470         return param;
1471 }
1472
1473 static uint8_t get_exact_divisor(int i, uint8_t divisor)
1474 {
1475         //input divisor could be 200(200), 150(266), 120(333), 100 (400)
1476         static const uint8_t dv_a[] = {
1477                /* 200  266  333  400 */
1478          /*4 */   250, 250, 250, 250,
1479          /*5 */   200, 200, 200, 100,
1480          /*6 */   200, 166, 166, 100,
1481          /*7 */   200, 171, 142, 100,
1482
1483          /*8 */   200, 150, 125, 100,
1484          /*9 */   200, 156, 133, 100,
1485          /*10*/   200, 160, 120, 100,
1486          /*11*/   200, 163, 127, 100,
1487
1488          /*12*/   200, 150, 133, 100,
1489          /*13*/   200, 153, 123, 100,
1490          /*14*/   200, 157, 128, 100,
1491          /*15*/   200, 160, 120, 100,
1492         }; 
1493         
1494         unsigned fid_cur;
1495         int index;
1496         
1497         msr_t msr;
1498         msr = rdmsr(0xc0010042);
1499         fid_cur = msr.lo & 0x3f;
1500
1501         index = fid_cur>>1;
1502
1503         if(index>12) return divisor;
1504
1505         if(i>3) return divisor;
1506
1507         return dv_a[index * 4+i];
1508
1509 }
1510
1511 struct spd_set_memclk_result {
1512         const struct mem_param *param;
1513         long dimm_mask;
1514 };
1515
1516 static unsigned convert_to_linear(unsigned value)
1517 {
1518          static const unsigned fraction[] = { 0x25, 0x33, 0x66, 0x75 };
1519          unsigned valuex;
1520
1521          /* We need to convert value to more readable */
1522          if((value & 0xf) < 10) { //no .25, .33, .66, .75
1523                 value <<= 4;
1524          } else {
1525                 valuex = ((value & 0xf0) << 4) | fraction [(value & 0xf)-10];
1526                 value = valuex;
1527          }
1528          return value;
1529 }
1530
1531 static struct spd_set_memclk_result spd_set_memclk(const struct mem_controller *ctrl, long dimm_mask, struct mem_info *meminfo)
1532 {
1533         /* Compute the minimum cycle time for these dimms */
1534         struct spd_set_memclk_result result;
1535         unsigned min_cycle_time, min_latency, bios_cycle_time;
1536         int i;
1537         uint32_t value;
1538
1539         static const uint8_t latency_indicies[] = { 25, 23, 9 };
1540
1541         static const uint16_t min_cycle_times[] = { // use full speed to compare
1542                 [NBCAP_MEMCLK_NOLIMIT] = 0x250, /*2.5ns */
1543                 [NBCAP_MEMCLK_333MHZ] = 0x300, /* 3.0ns */
1544                 [NBCAP_MEMCLK_266MHZ] = 0x375, /* 3.75ns */
1545                 [NBCAP_MEMCLK_200MHZ] = 0x500, /* 5.0s */
1546         };
1547
1548
1549         value = pci_read_config32(ctrl->f3, NORTHBRIDGE_CAP);
1550         min_cycle_time = min_cycle_times[(value >> NBCAP_MEMCLK_SHIFT) & NBCAP_MEMCLK_MASK];
1551         bios_cycle_time = min_cycle_times[
1552                 read_option(CMOS_VSTART_max_mem_clock, CMOS_VLEN_max_mem_clock, 0)];
1553         if (bios_cycle_time > min_cycle_time) {
1554                 min_cycle_time = bios_cycle_time;
1555         }
1556         min_latency = 3; 
1557
1558         print_tx("1 min_cycle_time:", min_cycle_time); 
1559
1560         /* Compute the least latency with the fastest clock supported
1561          * by both the memory controller and the dimms.
1562          */
1563         for(i = 0; i < DIMM_SOCKETS; i++) {
1564                 int new_cycle_time, new_latency;
1565                 int index;
1566                 int latencies;
1567                 int latency;
1568
1569                 if (!(dimm_mask & (1 << i))) {
1570                         continue;
1571                 }
1572
1573                 /* First find the supported CAS latencies
1574                  * Byte 18 for DDR SDRAM is interpreted:
1575                  * bit 3 == CAS Latency = 3
1576                  * bit 4 == CAS Latency = 4
1577                  * bit 5 == CAS Latency = 5
1578                  * bit 6 == CAS Latency = 6
1579                  */
1580                 new_cycle_time = 0x500;
1581                 new_latency = 6;
1582
1583                 latencies = spd_read_byte(ctrl->channel0[i], SPD_CAS_LAT);
1584                 if (latencies <= 0) continue;
1585
1586                 print_tx("i:",i);
1587                 print_tx("\tlatencies:", latencies);
1588                 /* Compute the lowest cas latency supported */
1589                 latency = log2(latencies) - 2;
1590
1591                 /* Loop through and find a fast clock with a low latency */
1592                 for(index = 0; index < 3; index++, latency++) {
1593                         int value;
1594                         if ((latency < 3) || (latency > 6) ||
1595                                 (!(latencies & (1 << latency)))) {
1596                                 continue;
1597                         }
1598                         value = spd_read_byte(ctrl->channel0[i], latency_indicies[index]);
1599                         if (value < 0) {
1600                                 goto hw_error;
1601                         }
1602                         print_tx("\tindex:", index);    
1603                         print_tx("\t\tlatency:", latency); 
1604                         print_tx("\t\tvalue1:", value);         
1605
1606                         value = convert_to_linear(value);
1607
1608                         print_tx("\t\tvalue2:", value); 
1609
1610                         /* Only increase the latency if we decreas the clock */
1611                         if (value >= min_cycle_time ) {
1612                                 if(value < new_cycle_time) {
1613                                         new_cycle_time = value;
1614                                         new_latency = latency;
1615                                 } else if (value == new_cycle_time) {
1616                                         if(new_latency > latency) {
1617                                                 new_latency = latency;
1618                                         }
1619                                 }
1620                         }
1621                         print_tx("\t\tnew_cycle_time:", new_cycle_time);
1622                         print_tx("\t\tnew_latency:", new_latency);
1623
1624                 }
1625                 if (new_latency > 6){
1626                         continue;
1627                 }
1628                 /* Does min_latency need to be increased? */
1629                 if (new_cycle_time > min_cycle_time) {
1630                         min_cycle_time = new_cycle_time;
1631                 }
1632                 /* Does min_cycle_time need to be increased? */
1633                 if (new_latency > min_latency) {
1634                         min_latency = new_latency;
1635                 }
1636
1637                 print_tx("2 min_cycle_time:", min_cycle_time); 
1638                 print_tx("2 min_latency:", min_latency); 
1639         }
1640         /* Make a second pass through the dimms and disable
1641          * any that cannot support the selected memclk and cas latency.
1642          */
1643
1644         print_tx("3 min_cycle_time:", min_cycle_time); 
1645         print_tx("3 min_latency:", min_latency); 
1646         
1647         for(i = 0; (i < DIMM_SOCKETS) && (ctrl->channel0[i]); i++) {
1648                 int latencies;
1649                 int latency;
1650                 int index;
1651                 int value;
1652                 if (!(dimm_mask & (1 << i))) {
1653                         continue;
1654                 }
1655                 latencies = spd_read_byte(ctrl->channel0[i], SPD_CAS_LAT);
1656                 if (latencies < 0) goto hw_error;
1657                 if (latencies == 0) {
1658                         continue;
1659                 }
1660
1661                 /* Compute the lowest cas latency supported */
1662                 latency = log2(latencies) -2;
1663
1664                 /* Walk through searching for the selected latency */
1665                 for(index = 0; index < 3; index++, latency++) {
1666                         if (!(latencies & (1 << latency))) {
1667                                 continue;
1668                         }
1669                         if (latency == min_latency)
1670                                 break;
1671                 }
1672                 /* If I can't find the latency or my index is bad error */
1673                 if ((latency != min_latency) || (index >= 3)) {
1674                         goto dimm_err;
1675                 }
1676         
1677                 /* Read the min_cycle_time for this latency */
1678                 value = spd_read_byte(ctrl->channel0[i], latency_indicies[index]);
1679                 if (value < 0) goto hw_error;
1680         
1681                 value = convert_to_linear(value);       
1682                 /* All is good if the selected clock speed 
1683                  * is what I need or slower.
1684                  */
1685                 if (value <= min_cycle_time) {
1686                         continue;
1687                 }
1688                 /* Otherwise I have an error, disable the dimm */
1689         dimm_err:
1690                 dimm_mask = disable_dimm(ctrl, i, dimm_mask, meminfo);
1691         }
1692
1693         print_tx("4 min_cycle_time:", min_cycle_time); 
1694         
1695         /* Now that I know the minimum cycle time lookup the memory parameters */
1696         result.param = get_mem_param(min_cycle_time);
1697
1698         /* Update DRAM Config High with our selected memory speed */
1699         value = pci_read_config32(ctrl->f2, DRAM_CONFIG_HIGH);
1700         value &= ~(DCH_MemClkFreq_MASK << DCH_MemClkFreq_SHIFT);
1701
1702         value |= result.param->dch_memclk << DCH_MemClkFreq_SHIFT;
1703         pci_write_config32(ctrl->f2, DRAM_CONFIG_HIGH, value);
1704
1705         print_debug(result.param->name);
1706
1707         /* Update DRAM Timing Low with our selected cas latency */
1708         value = pci_read_config32(ctrl->f2, DRAM_TIMING_LOW);
1709         value &= ~(DTL_TCL_MASK << DTL_TCL_SHIFT);
1710         value |= (min_latency - DTL_TCL_BASE)  << DTL_TCL_SHIFT;
1711         pci_write_config32(ctrl->f2, DRAM_TIMING_LOW, value);
1712         
1713         result.dimm_mask = dimm_mask;
1714         return result;
1715  hw_error:
1716         result.param = (const struct mem_param *)0;
1717         result.dimm_mask = -1;
1718         return result;
1719 }
1720
1721 static unsigned convert_to_1_4(unsigned value)
1722 {
1723          static const uint8_t fraction[] = { 0, 1, 2, 2, 3, 3, 0 };
1724          unsigned valuex;
1725
1726          /* We need to convert value to more readable */
1727          valuex =  fraction [value & 0x7];
1728          return valuex;
1729 }
1730 static int update_dimm_Trc(const struct mem_controller *ctrl, const struct mem_param *param, int i)
1731 {
1732         unsigned clocks, old_clocks;
1733         uint32_t dtl;
1734         int value;
1735         int value2;
1736         value = spd_read_byte(ctrl->channel0[i], SPD_TRC);
1737         if (value < 0) return -1;
1738
1739                 value2 = spd_read_byte(ctrl->channel0[i], SPD_TRC -1);
1740                 value <<= 2;
1741                 value += convert_to_1_4(value2>>4);
1742
1743         value *=10;
1744
1745         clocks = (value + param->divisor - 1)/param->divisor;
1746         
1747         if (clocks < DTL_TRC_MIN) {
1748                 clocks = DTL_TRC_MIN;
1749         }
1750         if (clocks > DTL_TRC_MAX) {
1751                 return 0;
1752         }
1753
1754         dtl = pci_read_config32(ctrl->f2, DRAM_TIMING_LOW);
1755         old_clocks = ((dtl >> DTL_TRC_SHIFT) & DTL_TRC_MASK) + DTL_TRC_BASE;
1756         if (old_clocks >= clocks) {  //?? someone did it 
1757                 // clocks = old_clocks;
1758                 return 1;
1759         }
1760         dtl &= ~(DTL_TRC_MASK << DTL_TRC_SHIFT);
1761         dtl |=  ((clocks - DTL_TRC_BASE) << DTL_TRC_SHIFT);
1762         pci_write_config32(ctrl->f2, DRAM_TIMING_LOW, dtl);
1763         return 1;
1764 }
1765
1766 static int update_dimm_Trfc(const struct mem_controller *ctrl, const struct mem_param *param, int i, struct mem_info *meminfo)
1767 {
1768         unsigned clocks, old_clocks;
1769         uint32_t dth;
1770         int value;
1771
1772         //get the cs_size --> logic dimm size
1773         value = spd_read_byte(ctrl->channel0[i], SPD_PRI_WIDTH);
1774         if (value < 0) {
1775                 return -1;
1776         }
1777
1778         value = 6 - log2(value); //4-->4, 8-->3, 16-->2
1779
1780         clocks = meminfo->sz[i].per_rank - 27 + 2 - value;
1781
1782         dth = pci_read_config32(ctrl->f2, DRAM_TIMING_HIGH);
1783
1784         old_clocks = ((dth >> (DTH_TRFC0_SHIFT+i*3)) & DTH_TRFC_MASK);
1785         if (old_clocks >= clocks) { // some one did it?
1786                 return 1;
1787         }
1788         dth &= ~(DTH_TRFC_MASK << (DTH_TRFC0_SHIFT+i*3));
1789         dth |= clocks  << (DTH_TRFC0_SHIFT+i*3);
1790         pci_write_config32(ctrl->f2, DRAM_TIMING_HIGH, dth);
1791         return 1;
1792 }
1793
1794 static int update_dimm_TT_1_4(const struct mem_controller *ctrl, const struct mem_param *param, int i, 
1795                                         unsigned TT_REG, 
1796                                         unsigned SPD_TT, unsigned TT_SHIFT, unsigned TT_MASK, unsigned TT_BASE, unsigned TT_MIN, unsigned TT_MAX )
1797 {
1798         unsigned clocks, old_clocks;
1799         uint32_t dtl;
1800         int value;
1801         value = spd_read_byte(ctrl->channel0[i], SPD_TT); //already in 1/4 ns
1802         if (value < 0) return -1;
1803         value *=10;
1804         clocks = (value + param->divisor -1)/param->divisor;
1805         if (clocks < TT_MIN) {
1806                 clocks = TT_MIN;
1807         }
1808         if (clocks > TT_MAX) {
1809                 return 0;
1810         }
1811         dtl = pci_read_config32(ctrl->f2, TT_REG);
1812
1813         old_clocks = ((dtl >> TT_SHIFT) & TT_MASK) + TT_BASE;
1814         if (old_clocks >= clocks) { //some one did it?
1815 //              clocks = old_clocks;
1816                 return 1;
1817         }
1818         dtl &= ~(TT_MASK << TT_SHIFT);
1819         dtl |= ((clocks - TT_BASE) << TT_SHIFT);
1820         pci_write_config32(ctrl->f2, TT_REG, dtl);
1821         return 1;
1822 }
1823
1824 static int update_dimm_Trcd(const struct mem_controller *ctrl, const struct mem_param *param, int i)
1825 {
1826         return update_dimm_TT_1_4(ctrl, param, i, DRAM_TIMING_LOW, SPD_TRCD, DTL_TRCD_SHIFT, DTL_TRCD_MASK, DTL_TRCD_BASE, DTL_TRCD_MIN, DTL_TRCD_MAX);
1827 }
1828
1829 static int update_dimm_Trrd(const struct mem_controller *ctrl, const struct mem_param *param, int i)
1830 {
1831         return update_dimm_TT_1_4(ctrl, param, i, DRAM_TIMING_LOW, SPD_TRRD, DTL_TRRD_SHIFT, DTL_TRRD_MASK, DTL_TRRD_BASE, DTL_TRRD_MIN, DTL_TRRD_MAX);
1832 }
1833
1834 static int update_dimm_Tras(const struct mem_controller *ctrl, const struct mem_param *param, int i)
1835 {
1836         unsigned clocks, old_clocks;
1837         uint32_t dtl;
1838         int value;
1839         value = spd_read_byte(ctrl->channel0[i], SPD_TRAS); //in 1 ns
1840         if (value < 0) return -1;
1841         print_tx("update_dimm_Tras: 0 value=", value); 
1842         
1843         value<<=2; //convert it to in 1/4ns
1844
1845         value *= 10;
1846         print_tx("update_dimm_Tras:  1 value=", value); 
1847
1848         clocks = (value  + param->divisor - 1)/param->divisor;
1849         print_tx("update_dimm_Tras: divisor=", param->divisor); 
1850         print_tx("update_dimm_Tras: clocks=", clocks); 
1851         if (clocks < DTL_TRAS_MIN) {
1852                 clocks = DTL_TRAS_MIN;
1853         }
1854         if (clocks > DTL_TRAS_MAX) {
1855                 return 0;
1856         }
1857         dtl = pci_read_config32(ctrl->f2, DRAM_TIMING_LOW);
1858         old_clocks = ((dtl >> DTL_TRAS_SHIFT) & DTL_TRAS_MASK) + DTL_TRAS_BASE;
1859         if (old_clocks >= clocks) { // someone did it?
1860                 return 1;
1861         }
1862         dtl &= ~(DTL_TRAS_MASK << DTL_TRAS_SHIFT);
1863         dtl |= ((clocks - DTL_TRAS_BASE) << DTL_TRAS_SHIFT);
1864         pci_write_config32(ctrl->f2, DRAM_TIMING_LOW, dtl);
1865         return 1;
1866 }
1867
1868 static int update_dimm_Trp(const struct mem_controller *ctrl, const struct mem_param *param, int i)
1869 {
1870         return update_dimm_TT_1_4(ctrl, param, i, DRAM_TIMING_LOW, SPD_TRP, DTL_TRP_SHIFT, DTL_TRP_MASK, DTL_TRP_BASE, DTL_TRP_MIN, DTL_TRP_MAX);
1871 }
1872
1873 static int update_dimm_Trtp(const struct mem_controller *ctrl, const struct mem_param *param, int i, struct mem_info *meminfo)
1874 {
1875         //need to figure if it is 32 byte burst or 64 bytes burst
1876         int offset = 2;
1877         if(!meminfo->is_Width128) {
1878                 uint32_t dword;
1879                 dword = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
1880                 if((dword &  DCL_BurstLength32)) offset = 0;
1881         }
1882         return update_dimm_TT_1_4(ctrl, param, i, DRAM_TIMING_LOW, SPD_TRTP, DTL_TRTP_SHIFT, DTL_TRTP_MASK, DTL_TRTP_BASE+offset, DTL_TRTP_MIN+offset, DTL_TRTP_MAX+offset);
1883 }
1884
1885
1886 static int update_dimm_Twr(const struct mem_controller *ctrl, const struct mem_param *param, int i)
1887 {
1888         return update_dimm_TT_1_4(ctrl, param, i, DRAM_TIMING_LOW, SPD_TWR, DTL_TWR_SHIFT, DTL_TWR_MASK, DTL_TWR_BASE, DTL_TWR_MIN, DTL_TWR_MAX);
1889 }
1890
1891
1892 static int update_dimm_Tref(const struct mem_controller *ctrl, const struct mem_param *param, int i)
1893 {
1894         uint32_t dth, dth_old;
1895         int value;
1896         value = spd_read_byte(ctrl->channel0[i], SPD_TREF); // 0: 15.625us, 1: 3.9us 2: 7.8 us....
1897         if (value < 0) return -1;
1898
1899         if(value == 1 ) {
1900                 value = 3;
1901         } else {
1902                 value = 2;
1903         }
1904
1905         dth = pci_read_config32(ctrl->f2, DRAM_TIMING_HIGH);
1906
1907         dth_old = dth;
1908         dth &= ~(DTH_TREF_MASK << DTH_TREF_SHIFT);
1909         dth |= (value << DTH_TREF_SHIFT);
1910         if(dth_old != dth) {
1911                 pci_write_config32(ctrl->f2, DRAM_TIMING_HIGH, dth);
1912         }
1913         return 1;
1914 }
1915
1916 static void set_4RankRDimm(const struct mem_controller *ctrl, const struct mem_param *param, struct mem_info *meminfo)
1917 {
1918 #if QRANK_DIMM_SUPPRT == 1
1919         int value;
1920         int i;
1921         
1922
1923         if(!(meminfo->is_registered)) return; 
1924
1925         value = 0;
1926
1927         for(i = 0; i < DIMM_SOCKETS; i++) {
1928                 if (!(dimm_mask & (1 << i))) {
1929                         continue;
1930                 }
1931
1932                 if(meminfo->sz.rank == 4) {
1933                         value = 1;
1934                         break;
1935                 }
1936         }
1937
1938         if(value == 1) {
1939                 uint32_t dch;
1940                 dch = pci_read_config32(ctrl->f2, DRAM_CONFIG_HIGH);
1941                 dch |= DCH_FourRankRDimm;
1942                 pci_write_config32(ctrl->f2, DRAM_CONFIG_HIGH, dch);
1943         }
1944 #endif
1945 }
1946
1947
1948 static uint32_t get_extra_dimm_mask(const struct mem_controller *ctrl, struct mem_info *meminfo)
1949 {
1950         int i;
1951
1952         uint32_t mask_x4;
1953         uint32_t mask_x16;
1954         uint32_t mask_single_rank;
1955         uint32_t mask_page_1k;
1956         int value;
1957 #if QRANK_DIMM_SUPPORT == 1
1958         int rank;
1959 #endif
1960
1961         long dimm_mask = meminfo->dimm_mask;
1962
1963
1964         mask_x4 = 0;
1965         mask_x16 = 0;
1966         mask_single_rank = 0;
1967         mask_page_1k = 0;
1968
1969         for(i = 0; i < DIMM_SOCKETS; i++) {
1970                 
1971                 if (!(dimm_mask & (1 << i))) {
1972                         continue;
1973                 }
1974
1975                 if(meminfo->sz[i].rank == 1) {
1976                         mask_single_rank |= 1<<i;
1977                 }
1978
1979                 if(meminfo->sz[i].col==10) {
1980                         mask_page_1k |= 1<<i;
1981                 }
1982
1983
1984                 value = spd_read_byte(ctrl->channel0[i], SPD_PRI_WIDTH);
1985
1986                 #if QRANK_DIMM_SUPPORT == 1
1987                 rank = meminfo->sz[i].rank;
1988                 #endif
1989
1990                 if(value==4) {
1991                         mask_x4 |= (1<<i);
1992                         #if QRANK_DIMM_SUPPORT == 1
1993                         if(rank==4) {
1994                                 mask_x4 |= 1<<(i+2);
1995                         }
1996                         #endif
1997                 } else if(value==16) {
1998                         mask_x16 |= (1<<i);
1999                         #if QRANK_DIMM_SUPPORT == 1
2000                         if(rank==4) {
2001                                 mask_x16 |= 1<<(i+2);
2002                         }
2003                         #endif
2004                 }
2005                 
2006         }
2007         
2008         meminfo->x4_mask= mask_x4;
2009         meminfo->x16_mask = mask_x16;
2010         
2011         meminfo->single_rank_mask = mask_single_rank;
2012         meminfo->page_1k_mask = mask_page_1k;
2013
2014         return mask_x4;
2015
2016 }
2017
2018
2019 static void set_dimm_x4(const struct mem_controller *ctrl, const struct mem_param *param, struct mem_info *meminfo)
2020 {
2021         uint32_t dcl;
2022         dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
2023         dcl &= ~(DCL_X4Dimm_MASK<<DCL_X4Dimm_SHIFT);
2024         dcl |= ((meminfo->x4_mask) & 0xf) << (DCL_X4Dimm_SHIFT);
2025         pci_write_config32(ctrl->f2, DRAM_CONFIG_LOW, dcl);
2026 }
2027
2028 static int count_ones(uint32_t dimm_mask)
2029 {
2030         int dimms;
2031         unsigned index;
2032         dimms = 0;
2033         for(index = 0; index < DIMM_SOCKETS; index++, dimm_mask>>=1) {
2034                 if (dimm_mask & 1) {
2035                         dimms++;
2036                 }
2037         }
2038         return dimms;
2039 }
2040
2041
2042 static void set_DramTerm(const struct mem_controller *ctrl, const struct mem_param *param, struct mem_info *meminfo)
2043 {
2044         uint32_t dcl;
2045         unsigned odt;
2046         odt = 1; // 75 ohms
2047
2048         if(param->divisor == 100) { //DDR2 800
2049                 if(meminfo->is_Width128) {
2050                         if(count_ones(meminfo->dimm_mask & 0x0f)==2) {
2051                                 odt = 3;  //50 ohms
2052                         }
2053                 }
2054
2055         }       
2056         dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
2057         dcl &= ~(DCL_DramTerm_MASK<<DCL_DramTerm_SHIFT);
2058         dcl |= (odt & DCL_DramTerm_MASK) << (DCL_DramTerm_SHIFT);
2059         pci_write_config32(ctrl->f2, DRAM_CONFIG_LOW, dcl);
2060 }
2061
2062
2063 static void set_ecc(const struct mem_controller *ctrl,const struct mem_param *param, long dimm_mask, struct mem_info *meminfo)
2064 {
2065         int i;
2066         int value;
2067         
2068         uint32_t dcl, nbcap;
2069         nbcap = pci_read_config32(ctrl->f3, NORTHBRIDGE_CAP);
2070         dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
2071         dcl &= ~DCL_DimmEccEn;
2072         if (nbcap & NBCAP_ECC) {
2073                 dcl |= DCL_DimmEccEn;
2074         }
2075         if (read_option(CMOS_VSTART_ECC_memory, CMOS_VLEN_ECC_memory, 1) == 0) {
2076                 dcl &= ~DCL_DimmEccEn;
2077         }
2078         pci_write_config32(ctrl->f2, DRAM_CONFIG_LOW, dcl);
2079
2080         meminfo->is_ecc = 1;
2081         if(!(dcl & DCL_DimmEccEn)) {
2082                 meminfo->is_ecc = 0;
2083                 return; // already disabled the ECC, so don't need to read SPD any more
2084         }
2085
2086         for(i = 0; i < DIMM_SOCKETS; i++) {
2087                 
2088                 if (!(dimm_mask & (1 << i))) {
2089                         continue;
2090                 }
2091
2092                 value = spd_read_byte(ctrl->channel0[i], SPD_DIMM_CONF_TYPE);
2093
2094                 if(!(value & SPD_DIMM_CONF_TYPE_ECC)) {
2095                         dcl &= ~DCL_DimmEccEn;
2096                         pci_write_config32(ctrl->f2, DRAM_CONFIG_LOW, dcl);
2097                         meminfo->is_ecc = 0;
2098                         return;
2099                 }
2100
2101         }
2102 }
2103
2104 static int update_dimm_Twtr(const struct mem_controller *ctrl, const struct mem_param *param, int i)
2105 {
2106
2107         return update_dimm_TT_1_4(ctrl, param, i, DRAM_TIMING_HIGH, SPD_TWTR, DTH_TWTR_SHIFT, DTH_TWTR_MASK, DTH_TWTR_BASE, DTH_TWTR_MIN, DTH_TWTR_MAX);
2108
2109 }
2110
2111 static void set_TT(const struct mem_controller *ctrl, const struct mem_param *param, unsigned TT_REG,
2112                 unsigned TT_SHIFT, unsigned TT_MASK, unsigned TT_BASE, unsigned TT_MIN, unsigned TT_MAX, unsigned val, const char *str)
2113 {
2114         uint32_t reg;
2115
2116         if ((val < TT_MIN) || (val > TT_MAX)) {
2117                 print_err(str);
2118                 die(" Unknown\r\n");
2119         }
2120
2121         reg = pci_read_config32(ctrl->f2, TT_REG);
2122         reg &= ~(TT_MASK << TT_SHIFT);
2123         reg |= ((val - TT_BASE) << TT_SHIFT);
2124         pci_write_config32(ctrl->f2, TT_REG, reg);
2125         return;
2126 }
2127
2128 static void set_TrwtTO(const struct mem_controller *ctrl, const struct mem_param *param)
2129 {
2130         set_TT(ctrl, param, DRAM_TIMING_HIGH, DTH_TRWTTO_SHIFT, DTH_TRWTTO_MASK,DTH_TRWTTO_BASE, DTH_TRWTTO_MIN, DTH_TRWTTO_MAX, param->TrwtTO, "TrwtTO");
2131 }
2132
2133 static void set_Twrrd(const struct mem_controller *ctrl, const struct mem_param *param)
2134 {
2135         set_TT(ctrl, param, DRAM_TIMING_HIGH, DTH_TWRRD_SHIFT, DTH_TWRRD_MASK,DTH_TWRRD_BASE, DTH_TWRRD_MIN, DTH_TWRRD_MAX, param->Twrrd, "Twrrd");
2136 }
2137
2138 static void set_Twrwr(const struct mem_controller *ctrl, const struct mem_param *param)
2139 {
2140         set_TT(ctrl, param, DRAM_TIMING_HIGH, DTH_TWRWR_SHIFT, DTH_TWRWR_MASK,DTH_TWRWR_BASE, DTH_TWRWR_MIN, DTH_TWRWR_MAX, param->Twrwr, "Twrwr");
2141 }
2142
2143 static void set_Trdrd(const struct mem_controller *ctrl, const struct mem_param *param)
2144 {
2145         set_TT(ctrl, param, DRAM_TIMING_HIGH, DTH_TRDRD_SHIFT, DTH_TRDRD_MASK,DTH_TRDRD_BASE, DTH_TRDRD_MIN, DTH_TRDRD_MAX, param->Trdrd, "Trdrd");
2146 }
2147
2148 static void set_DcqBypassMax(const struct mem_controller *ctrl, const struct mem_param *param)
2149 {
2150         set_TT(ctrl, param, DRAM_CONFIG_HIGH, DCH_DcqBypassMax_SHIFT, DCH_DcqBypassMax_MASK,DCH_DcqBypassMax_BASE, DCH_DcqBypassMax_MIN, DCH_DcqBypassMax_MAX, param->DcqByPassMax, "DcqBypassMax"); // value need to be in CMOS
2151 }
2152
2153 static void set_Tfaw(const struct mem_controller *ctrl, const struct mem_param *param, struct mem_info *meminfo)
2154 {
2155         static const uint8_t faw_1k[] = {8, 10, 13, 14};
2156         static const uint8_t faw_2k[] = {10, 14, 17, 18};
2157         unsigned memclkfreq_index;
2158         unsigned faw;
2159
2160
2161         memclkfreq_index = param->dch_memclk;
2162
2163         if(meminfo->page_1k_mask != 0) { //1k page
2164                 faw = faw_1k[memclkfreq_index];
2165         }
2166         else {
2167                 faw = faw_2k[memclkfreq_index];
2168         }
2169
2170         set_TT(ctrl, param, DRAM_CONFIG_HIGH, DCH_FourActWindow_SHIFT, DCH_FourActWindow_MASK, DCH_FourActWindow_BASE, DCH_FourActWindow_MIN, DCH_FourActWindow_MAX, faw, "FourActWindow");
2171
2172 }
2173
2174
2175 static void set_max_async_latency(const struct mem_controller *ctrl, const struct mem_param *param)
2176 {
2177         uint32_t dch;
2178         unsigned async_lat;
2179
2180
2181         dch = pci_read_config32(ctrl->f2, DRAM_CONFIG_HIGH);
2182         dch &= ~(DCH_MaxAsyncLat_MASK << DCH_MaxAsyncLat_SHIFT);
2183
2184         //FIXME: We need to use Max of DqsRcvEnDelay + 6ns here: After trainning and get that from index reg 0x10, 0x13, 0x16, 0x19, 0x30, 0x33, 0x36, 0x39
2185         async_lat = 6+6;
2186         
2187         
2188         dch |= ((async_lat - DCH_MaxAsyncLat_BASE) << DCH_MaxAsyncLat_SHIFT);
2189         pci_write_config32(ctrl->f2, DRAM_CONFIG_HIGH, dch);
2190 }
2191
2192 static void set_SlowAccessMode(const struct mem_controller *ctrl)
2193 {
2194         uint32_t dch;
2195
2196         dch = pci_read_config32(ctrl->f2, DRAM_CONFIG_HIGH);
2197
2198         dch |= (1<<20);
2199
2200         pci_write_config32(ctrl->f2, DRAM_CONFIG_HIGH, dch);
2201 }
2202
2203
2204 /*
2205         DRAM_OUTPUT_DRV_COMP_CTRL 0, 0x20
2206         DRAM_ADDR_TIMING_CTRL 04, 0x24
2207 */
2208 static void set_misc_timing(const struct mem_controller *ctrl, struct mem_info *meminfo)
2209 {
2210         uint32_t dword;
2211         uint32_t dwordx;
2212         unsigned SlowAccessMode = 0;
2213
2214         long dimm_mask = meminfo->dimm_mask & 0x0f;
2215
2216 #if DIMM_SUPPORT==0x0104   /* DDR2 and REG */
2217         /* for REG DIMM */      
2218         dword = 0x00111222;
2219         dwordx = 0x002f0000;
2220         switch (meminfo->memclk_set) {
2221         case DCH_MemClkFreq_266MHz:
2222                 if( (dimm_mask == 0x03) || (dimm_mask == 0x02) || (dimm_mask == 0x01)) { 
2223                         dwordx = 0x002f2700; 
2224                 }
2225                 break;
2226         case DCH_MemClkFreq_333MHz:
2227                 if( (dimm_mask == 0x03) || (dimm_mask == 0x02) || (dimm_mask == 0x01)) {
2228                         if ((meminfo->single_rank_mask & 0x03)!=0x03) { //any double rank there?
2229                                 dwordx = 0x002f2f00;
2230                         }
2231                 }
2232                 break;
2233         case DCH_MemClkFreq_400MHz:
2234                 dwordx = 0x002f3300;
2235                 break;
2236         }
2237
2238 #endif
2239
2240 #if DIMM_SUPPORT==0x0004  /* DDR2 and unbuffered */
2241         /* for UNBUF DIMM */
2242         dword = 0x00111222;
2243         dwordx = 0x002f2f00;
2244         switch (meminfo->memclk_set) {
2245         case DCH_MemClkFreq_200MHz:
2246                 if(dimm_mask == 0x03) {
2247                         SlowAccessMode = 1;
2248                         dword = 0x00111322;
2249                 }
2250                 break;
2251         case DCH_MemClkFreq_266MHz:
2252                 if(dimm_mask == 0x03) {
2253                         SlowAccessMode = 1;
2254                         dword = 0x00111322;
2255                         if((meminfo->x4_mask == 0 ) && (meminfo->x16_mask == 0)) {
2256                                 switch (meminfo->single_rank_mask) {
2257                                 case 0x03:
2258                                         dwordx = 0x00002f00; //x8 single Rank
2259                                         break;
2260                                 case 0x00:
2261                                         dwordx = 0x00342f00; //x8 double Rank
2262                                         break;
2263                                 default: 
2264                                         dwordx = 0x00372f00; //x8 single Rank and double Rank mixed
2265                                 }
2266                         } else if((meminfo->x4_mask == 0 ) && (meminfo->x16_mask == 0x01) && (meminfo->single_rank_mask == 0x01)) {
2267                                         dwordx = 0x00382f00; //x8 Double Rank and x16 single Rank mixed
2268                         } else if((meminfo->x4_mask == 0 ) && (meminfo->x16_mask == 0x02) && (meminfo->single_rank_mask == 0x02)) {
2269                                         dwordx = 0x00382f00; //x16 single Rank and x8 double Rank mixed
2270                         }
2271
2272                 }
2273                 else {
2274                         if((meminfo->x4_mask == 0 ) && (meminfo->x16_mask == 0x00) && ((meminfo->single_rank_mask == 0x01)||(meminfo->single_rank_mask == 0x02)))  { //x8 single rank
2275                                 dwordx = 0x002f2f00;
2276                         } else {
2277                                 dwordx = 0x002b2f00;
2278                         }
2279                 }
2280                 break;
2281         case DCH_MemClkFreq_333MHz:
2282                 dwordx = 0x00202220;
2283                 if(dimm_mask == 0x03) {
2284                         SlowAccessMode = 1;
2285                         dword = 0x00111322;
2286                         if((meminfo->x4_mask == 0 ) && (meminfo->x16_mask == 0)) {
2287                                 switch (meminfo->single_rank_mask) {
2288                                 case 0x03:
2289                                         dwordx = 0x00302220; //x8 single Rank
2290                                         break;
2291                                 case 0x00:
2292                                         dwordx = 0x002b2220; //x8 double Rank
2293                                         break;
2294                                 default:
2295                                         dwordx = 0x002a2220; //x8 single Rank and double Rank mixed
2296                                 }
2297                         } else if((meminfo->x4_mask == 0) && (meminfo->x16_mask == 0x01) && (meminfo->single_rank_mask == 0x01)) {
2298                                         dwordx = 0x002c2220; //x8 Double Rank and x16 single Rank mixed
2299                         } else if((meminfo->x4_mask == 0) && (meminfo->x16_mask == 0x02) && (meminfo->single_rank_mask == 0x02)) {
2300                                         dwordx = 0x002c2220; //x16 single Rank and x8 double Rank mixed
2301                         }
2302                 }
2303                 break;
2304         case DCH_MemClkFreq_400MHz:
2305                 dwordx = 0x00202520;
2306                 SlowAccessMode = 1;
2307                 if(dimm_mask == 0x03) {
2308                         dword = 0x00113322;
2309                 } else {
2310                         dword = 0x00113222;
2311                 }
2312                 break;
2313         } 
2314
2315         print_raminit("\tdimm_mask = ", meminfo->dimm_mask);
2316         print_raminit("\tx4_mask = ", meminfo->x4_mask);
2317         print_raminit("\tx16_mask = ", meminfo->x16_mask);
2318         print_raminit("\tsingle_rank_mask = ", meminfo->single_rank_mask);
2319         print_raminit("\tODC = ", dword);
2320         print_raminit("\tAddr Timing= ", dwordx);
2321 #endif
2322
2323 #if (DIMM_SUPPORT & 0x0100)==0x0000 /* 2T mode only used for unbuffered DIMM */
2324         if(SlowAccessMode) {
2325                 set_SlowAccessMode(ctrl);
2326         }
2327 #endif
2328
2329         /* Program the Output Driver Compensation Control Registers (Function 2:Offset 0x9c, index 0, 0x20) */
2330         pci_write_config32_index_wait(ctrl->f2, 0x98, 0, dword);
2331         if(meminfo->is_Width128) {      
2332                 pci_write_config32_index_wait(ctrl->f2, 0x98, 0x20, dword);
2333         }
2334
2335         /* Program the Address Timing Control Registers (Function 2:Offset 0x9c, index 4, 0x24) */
2336         pci_write_config32_index_wait(ctrl->f2, 0x98, 4, dwordx);
2337         if(meminfo->is_Width128) {
2338                 pci_write_config32_index_wait(ctrl->f2, 0x98, 0x24, dwordx);
2339         }
2340
2341 }
2342
2343
2344 static void set_RDqsEn(const struct mem_controller *ctrl, const struct mem_param *param, struct mem_info *meminfo)
2345 {
2346 #if CPU_SOCKET_TYPE==0x10
2347         //only need to set for reg and x8
2348         uint32_t dch;
2349
2350         dch = pci_read_config32(ctrl->f2, DRAM_CONFIG_HIGH);
2351
2352         dch &= ~DCH_RDqsEn;
2353         if((!meminfo->x4_mask) && (!meminfo->x16_mask)) {
2354                 dch |= DCH_RDqsEn;
2355         }
2356
2357         pci_write_config32(ctrl->f2, DRAM_CONFIG_HIGH, dch);
2358 #endif
2359 }
2360
2361
2362 static void set_idle_cycle_limit(const struct mem_controller *ctrl, const struct mem_param *param)
2363 {
2364         uint32_t dcm;
2365         /* AMD says to Hardcode this */
2366         dcm = pci_read_config32(ctrl->f2, DRAM_CTRL_MISC);
2367         dcm &= ~(DCM_ILD_lmt_MASK << DCM_ILD_lmt_SHIFT);
2368         dcm |= DCM_ILD_lmt_16 << DCM_ILD_lmt_SHIFT;
2369         dcm |= DCM_DCC_EN;
2370         pci_write_config32(ctrl->f2, DRAM_CTRL_MISC, dcm);
2371 }
2372
2373 static void set_RdWrQByp(const struct mem_controller *ctrl, const struct mem_param *param)
2374 {
2375         set_TT(ctrl, param, DRAM_CTRL_MISC, DCM_RdWrQByp_SHIFT, DCM_RdWrQByp_MASK,0, 0, 3, 2, "RdWrQByp");
2376 }
2377
2378
2379
2380 static long spd_set_dram_timing(const struct mem_controller *ctrl, const struct mem_param *param, long dimm_mask, struct mem_info *meminfo)
2381 {
2382         int i;
2383
2384         for(i = 0; i < DIMM_SOCKETS; i++) {
2385                 int rc;
2386                 if (!(dimm_mask & (1 << i))) {
2387                         continue;
2388                 }
2389                 print_tx("dimm socket: ", i);
2390                 /* DRAM Timing Low Register */
2391                 print_t("\ttrc\r\n");
2392                 if ((rc = update_dimm_Trc (ctrl, param, i)) <= 0) goto dimm_err;
2393
2394                 print_t("\ttrcd\r\n");
2395                 if ((rc = update_dimm_Trcd(ctrl, param, i)) <= 0) goto dimm_err;
2396
2397                 print_t("\ttrrd\r\n");
2398                 if ((rc = update_dimm_Trrd(ctrl, param, i)) <= 0) goto dimm_err;
2399
2400                 print_t("\ttras\r\n");
2401                 if ((rc = update_dimm_Tras(ctrl, param, i)) <= 0) goto dimm_err;
2402
2403                 print_t("\ttrp\r\n");
2404                 if ((rc = update_dimm_Trp (ctrl, param, i)) <= 0) goto dimm_err;
2405
2406                 print_t("\ttrtp\r\n");
2407                 if ((rc = update_dimm_Trtp(ctrl, param, i, meminfo)) <= 0) goto dimm_err;
2408
2409                 print_t("\ttwr\r\n");
2410                 if ((rc = update_dimm_Twr (ctrl, param, i)) <= 0) goto dimm_err;
2411
2412                 /* DRAM Timing High Register */
2413                 print_t("\ttref\r\n");
2414                 if ((rc = update_dimm_Tref(ctrl, param, i)) <= 0) goto dimm_err;
2415
2416                 print_t("\ttwtr\r\n");
2417                 if ((rc = update_dimm_Twtr(ctrl, param, i)) <= 0) goto dimm_err;
2418
2419                 print_t("\ttrfc\r\n");
2420                 if ((rc = update_dimm_Trfc(ctrl, param, i, meminfo)) <= 0) goto dimm_err;
2421
2422                 /* DRAM Config Low */
2423
2424                 continue;
2425         dimm_err:
2426                 if (rc < 0) {
2427                         return -1;
2428                 }
2429                 dimm_mask = disable_dimm(ctrl, i, dimm_mask, meminfo);
2430         }
2431
2432         meminfo->dimm_mask = dimm_mask; // store final dimm_mask
2433
2434         get_extra_dimm_mask(ctrl, meminfo); // will be used by RDqsEn and dimm_x4
2435         /* DRAM Timing Low Register */
2436
2437         /* DRAM Timing High Register */
2438         set_TrwtTO(ctrl, param);
2439         set_Twrrd (ctrl, param);
2440         set_Twrwr (ctrl, param);
2441         set_Trdrd (ctrl, param);
2442         
2443         set_4RankRDimm(ctrl, param, meminfo);
2444
2445         /* DRAM Config High */
2446         set_Tfaw(ctrl, param, meminfo);
2447         set_DcqBypassMax(ctrl, param);
2448         set_max_async_latency(ctrl, param);
2449         set_RDqsEn(ctrl, param, meminfo);
2450
2451         /* DRAM Config Low */
2452         set_ecc(ctrl, param, dimm_mask, meminfo);
2453         set_dimm_x4(ctrl, param, meminfo);
2454         set_DramTerm(ctrl, param, meminfo);
2455         
2456         /* DRAM Control Misc */
2457         set_idle_cycle_limit(ctrl, param);
2458         set_RdWrQByp(ctrl, param);
2459
2460         return dimm_mask;
2461 }
2462
2463 static void sdram_set_spd_registers(const struct mem_controller *ctrl, struct sys_info *sysinfo) 
2464 {
2465         struct spd_set_memclk_result result;
2466         const struct mem_param *param;
2467         struct mem_param paramx;
2468         struct mem_info *meminfo;
2469         long dimm_mask;
2470 #if 1
2471         if (!sysinfo->ctrl_present[ctrl->node_id]) {
2472                 return;
2473         }
2474 #endif
2475         meminfo = &sysinfo->meminfo[ctrl->node_id];
2476
2477         print_debug_addr("sdram_set_spd_registers: paramx :", &paramx);
2478         
2479         activate_spd_rom(ctrl);
2480         dimm_mask = spd_detect_dimms(ctrl);
2481         if (!(dimm_mask & ((1 << DIMM_SOCKETS) - 1))) {
2482                 print_debug("No memory for this cpu\r\n");
2483                 return;
2484         }
2485         dimm_mask = spd_enable_2channels(ctrl, dimm_mask, meminfo);        
2486         if (dimm_mask < 0) 
2487                 goto hw_spd_err;
2488         dimm_mask = spd_set_ram_size(ctrl , dimm_mask, meminfo);           
2489         if (dimm_mask < 0) 
2490                 goto hw_spd_err;
2491         dimm_mask = spd_handle_unbuffered_dimms(ctrl, dimm_mask, meminfo); 
2492         if (dimm_mask < 0) 
2493                 goto hw_spd_err;
2494         result = spd_set_memclk(ctrl, dimm_mask, meminfo);
2495         param     = result.param;
2496         dimm_mask = result.dimm_mask;
2497         if (dimm_mask < 0) 
2498                 goto hw_spd_err;
2499
2500         //store memclk set to sysinfo, incase we need rebuilt param again
2501         meminfo->memclk_set = param->dch_memclk;
2502
2503         memcpy(&paramx, param, sizeof(paramx));
2504         
2505         paramx.divisor = get_exact_divisor(param->dch_memclk, paramx.divisor);
2506
2507         dimm_mask = spd_set_dram_timing(ctrl, &paramx , dimm_mask, meminfo); // dimm_mask will be stored to meminfo->dimm_mask
2508         if (dimm_mask < 0)
2509                 goto hw_spd_err;
2510         
2511         order_dimms(ctrl, meminfo);
2512
2513         return;
2514  hw_spd_err:
2515         /* Unrecoverable error reading SPD data */
2516         print_err("SPD error - reset\r\n");
2517         hard_reset();
2518         return;
2519 }
2520
2521 #define TIMEOUT_LOOPS 300000
2522
2523 #include "raminit_f_dqs.c"
2524
2525 #if HW_MEM_HOLE_SIZEK != 0
2526 static uint32_t hoist_memory(int controllers, const struct mem_controller *ctrl,unsigned hole_startk, int i)
2527 {
2528         int ii;
2529         uint32_t carry_over;
2530         device_t dev;
2531         uint32_t base, limit;
2532         uint32_t basek;
2533         uint32_t hoist;
2534         int j;
2535
2536         carry_over = (4*1024*1024) - hole_startk;
2537
2538         for(ii=controllers - 1;ii>i;ii--) {
2539                 base  = pci_read_config32(ctrl[0].f1, 0x40 + (ii << 3));
2540                 if ((base & ((1<<1)|(1<<0))) != ((1<<1)|(1<<0))) {
2541                         continue;
2542                 }
2543                 limit = pci_read_config32(ctrl[0].f1, 0x44 + (ii << 3));
2544                 limit += (carry_over << 2 );
2545                 base  += (carry_over << 2 );
2546                 for(j = 0; j < controllers; j++) {      
2547                         pci_write_config32(ctrl[j].f1, 0x44 + (ii << 3), limit);
2548                         pci_write_config32(ctrl[j].f1, 0x40 + (ii << 3), base );
2549                 }
2550         }
2551         limit = pci_read_config32(ctrl[0].f1, 0x44 + (i << 3));
2552         limit += (carry_over << 2);
2553         for(j = 0; j < controllers; j++) {
2554                 pci_write_config32(ctrl[j].f1, 0x44 + (i << 3), limit);
2555         }
2556         dev = ctrl[i].f1;
2557         base  = pci_read_config32(dev, 0x40 + (i << 3));
2558         basek  = (base & 0xffff0000) >> 2;
2559         if(basek == hole_startk) {
2560                 //don't need set memhole here, because hole off set will be 0, overflow
2561                 //so need to change base reg instead, new basek will be 4*1024*1024
2562                 base &= 0x0000ffff;
2563                 base |= (4*1024*1024)<<2;
2564                 for(j = 0; j < controllers; j++) {
2565                         pci_write_config32(ctrl[j].f1, 0x40 + (i<<3), base);
2566                 }
2567         }
2568         else
2569         {
2570                 hoist = /* hole start address */
2571                         ((hole_startk << 10) & 0xff000000) +
2572                         /* hole address to memory controller address */
2573                         (((basek + carry_over) >> 6) & 0x0000ff00) +
2574                         /* enable */
2575                         1;
2576                 pci_write_config32(dev, 0xf0, hoist);
2577         }       
2578
2579         return carry_over;
2580 }
2581
2582 static void set_hw_mem_hole(int controllers, const struct mem_controller *ctrl)
2583 {
2584
2585         uint32_t hole_startk;
2586         int i;
2587
2588         hole_startk = 4*1024*1024 - HW_MEM_HOLE_SIZEK;
2589
2590 #if HW_MEM_HOLE_SIZE_AUTO_INC == 1
2591         //We need to double check if the hole_startk is valid, if it is equal to basek, we need to decrease it some
2592         uint32_t basek_pri;
2593         for(i=0; i<controllers; i++) {
2594                         uint32_t base;
2595                         unsigned base_k;
2596                         base  = pci_read_config32(ctrl[0].f1, 0x40 + (i << 3));
2597                         if ((base & ((1<<1)|(1<<0))) != ((1<<1)|(1<<0))) {
2598                                 continue;
2599                         }
2600                         base_k = (base & 0xffff0000) >> 2;
2601                         if(base_k == hole_startk) {
2602                                 hole_startk -= (base_k - basek_pri)>>1; // decrease mem hole startk to make sure it is on middle of previous node
2603                                 break; //only one hole
2604                         }
2605                         basek_pri = base_k;
2606         }
2607 #endif
2608         //find node index that need do set hole
2609         for(i=0; i<controllers; i++) {
2610                         uint32_t base, limit;
2611                         unsigned base_k, limit_k;
2612                         base  = pci_read_config32(ctrl[0].f1, 0x40 + (i << 3));
2613                         if ((base & ((1<<1)|(1<<0))) != ((1<<1)|(1<<0))) {
2614                                 continue;
2615                         }
2616                         limit = pci_read_config32(ctrl[0].f1, 0x44 + (i << 3));
2617                         base_k = (base & 0xffff0000) >> 2;
2618                         limit_k = ((limit + 0x00010000) & 0xffff0000) >> 2;
2619                         if ((base_k <= hole_startk) && (limit_k > hole_startk)) {
2620                                 unsigned end_k;
2621                                 hoist_memory(controllers, ctrl, hole_startk, i);
2622                                 end_k = memory_end_k(ctrl, controllers);
2623                                 set_top_mem(end_k, hole_startk);
2624                                 break; //only one hole
2625                         }
2626         }
2627
2628 }
2629
2630 #endif
2631
2632 static void sdram_enable(int controllers, const struct mem_controller *ctrl, struct sys_info *sysinfo)
2633 {
2634         int i;
2635
2636
2637 #if K8_REV_F_SUPPORT_F0_F1_WORKAROUND == 1
2638         unsigned cpu_f0_f1[8];
2639         /* FIXME: How about 32 node machine later? */
2640         tsc_t tsc, tsc0[8];
2641         
2642         print_debug_addr("sdram_enable: tsc0[8]: ", &tsc0[0]);
2643 #endif
2644         uint32_t dword;
2645
2646         /* Error if I don't have memory */
2647         if (memory_end_k(ctrl, controllers) == 0) {
2648                 die("No memory\r\n");
2649         }
2650
2651         /* Before enabling memory start the memory clocks */
2652         for(i = 0; i < controllers; i++) {
2653                 uint32_t dtl, dch;
2654                 if (!sysinfo->ctrl_present[ i ])
2655                         continue;
2656                 dch = pci_read_config32(ctrl[i].f2, DRAM_CONFIG_HIGH);
2657
2658                 // if no memory installed, disabled the interface
2659                 if(sysinfo->meminfo[i].dimm_mask==0x00){
2660                         dch |= DCH_DisDramInterface;
2661                         pci_write_config32(ctrl[i].f2, DRAM_CONFIG_HIGH, dch);
2662
2663                 }
2664                 else {
2665                         dch |= DCH_MemClkFreqVal;
2666                         pci_write_config32(ctrl[i].f2, DRAM_CONFIG_HIGH, dch);
2667                         /* address timing and Output driver comp Control */
2668                         set_misc_timing(ctrl+i, sysinfo->meminfo+i );
2669                 }
2670         }
2671
2672         /* We need to wait a mimmium of 20 MEMCLKS to enable the  InitDram */
2673         memreset(controllers, ctrl);
2674 #if 0
2675         print_debug("prepare to InitDram:");
2676         for(i=0; i<10; i++) {
2677                 print_debug_hex32(i);
2678                 print_debug("\b\b\b\b\b\b\b\b");
2679         }
2680         print_debug("\r\n");
2681 #endif
2682
2683         for(i = 0; i < controllers; i++) {
2684                 uint32_t dcl, dch;
2685                 if (!sysinfo->ctrl_present[ i ])
2686                         continue;
2687                 /* Skip everything if I don't have any memory on this controller */
2688                 dch = pci_read_config32(ctrl[i].f2, DRAM_CONFIG_HIGH);
2689                 if (!(dch & DCH_MemClkFreqVal)) {
2690                         continue;
2691                 }
2692
2693                 /* ChipKill */
2694                 dcl = pci_read_config32(ctrl[i].f2, DRAM_CONFIG_LOW);
2695                 if (dcl & DCL_DimmEccEn) {
2696                         uint32_t mnc;
2697                         print_spew("ECC enabled\r\n");
2698                         mnc = pci_read_config32(ctrl[i].f3, MCA_NB_CONFIG);
2699                         mnc |= MNC_ECC_EN;
2700                         if (dcl & DCL_Width128) {
2701                                 mnc |= MNC_CHIPKILL_EN;
2702                         }
2703                         pci_write_config32(ctrl[i].f3, MCA_NB_CONFIG, mnc);
2704                 }
2705
2706 #if K8_REV_F_SUPPORT_F0_F1_WORKAROUND == 1
2707                 cpu_f0_f1[i] = is_cpu_pre_f2_in_bsp(i);
2708                 if(cpu_f0_f1[i]) {
2709                         //Rev F0/F1 workaround
2710 #if 1
2711                                 /* Set the DqsRcvEnTrain bit */
2712                         dword = pci_read_config32(ctrl[i].f2, DRAM_CTRL);
2713                         dword |= DC_DqsRcvEnTrain;
2714                         pci_write_config32(ctrl[i].f2, DRAM_CTRL, dword);
2715 #endif
2716                         tsc0[i] = rdtsc();                      
2717                 }
2718 #endif
2719
2720 #if 0
2721                                /* Set the DqsRcvEnTrain bit */
2722                         dword = pci_read_config32(ctrl[i].f2, DRAM_CTRL);
2723                         dword |= DC_DqsRcvEnTrain;
2724                         pci_write_config32(ctrl[i].f2, DRAM_CTRL, dword);
2725 #endif
2726
2727                 pci_write_config32(ctrl[i].f2, DRAM_CONFIG_LOW, dcl);
2728                 dcl |= DCL_InitDram;
2729                 pci_write_config32(ctrl[i].f2, DRAM_CONFIG_LOW, dcl);
2730
2731         }
2732
2733         for(i = 0; i < controllers; i++) {
2734                 uint32_t dcl, dch, dcm;
2735                 if (!sysinfo->ctrl_present[ i ])
2736                         continue;
2737                 /* Skip everything if I don't have any memory on this controller */
2738                 if(sysinfo->meminfo[i].dimm_mask==0x00) continue;
2739
2740                 print_debug("Initializing memory: ");
2741                 int loops = 0;
2742                 do {
2743                         dcl = pci_read_config32(ctrl[i].f2, DRAM_CONFIG_LOW);
2744                         loops++;
2745                         if ((loops & 1023) == 0) {
2746                                 print_debug(".");
2747                         }
2748                 } while(((dcl & DCL_InitDram) != 0) && (loops < TIMEOUT_LOOPS));
2749                 if (loops >= TIMEOUT_LOOPS) {
2750                         print_debug(" failed\r\n");
2751                         continue;
2752                 }
2753
2754                 /* Wait until it is safe to touch memory */
2755                 do {
2756                         dcm = pci_read_config32(ctrl[i].f2, DRAM_CTRL_MISC);
2757                 } while(((dcm & DCM_MemClrStatus) == 0) /* || ((dcm & DCM_DramEnabled) == 0)*/ );
2758
2759 #if K8_REV_F_SUPPORT_F0_F1_WORKAROUND == 1
2760                 if(cpu_f0_f1[i]) {
2761                         tsc= rdtsc();
2762
2763                         print_debug_dqs_tsc("\r\nbegin tsc0", i, tsc0[i].hi, tsc0[i].lo, 2); 
2764                         print_debug_dqs_tsc("end   tsc ", i, tsc.hi, tsc.lo, 2); 
2765
2766                         if(tsc.lo<tsc0[i].lo) {
2767                                 tsc.hi--;
2768                         }
2769                         tsc.lo -= tsc0[i].lo;
2770                         tsc.hi -= tsc0[i].hi;
2771
2772                         tsc0[i].lo = tsc.lo;
2773                         tsc0[i].hi = tsc.hi;
2774
2775                         print_debug_dqs_tsc("     dtsc0", i, tsc0[i].hi, tsc0[i].lo, 2);
2776                 }
2777 #endif
2778                 print_debug(" done\r\n");
2779         }
2780
2781 #if HW_MEM_HOLE_SIZEK != 0
2782          // init hw mem hole here
2783         /* DramHoleValid bit only can be set after MemClrStatus is set by Hardware */
2784         set_hw_mem_hole(controllers, ctrl);
2785 #endif
2786         
2787         //store tom to sysinfo, and it will be used by dqs_timing
2788         {
2789                 msr_t msr;
2790                 //[1M, TOM)
2791                 msr = rdmsr(TOP_MEM);
2792                 sysinfo->tom_k = ((msr.hi<<24) | (msr.lo>>8))>>2;
2793
2794                 //[4G, TOM2)
2795                 msr = rdmsr(TOP_MEM2);
2796                 sysinfo->tom2_k = ((msr.hi<<24)| (msr.lo>>8))>>2;
2797         }
2798
2799         for(i = 0; i < controllers; i++) {
2800                 sysinfo->mem_trained[i] = 0;
2801
2802                 if (!sysinfo->ctrl_present[ i ])
2803                         continue;
2804
2805                 /* Skip everything if I don't have any memory on this controller */
2806                 if(sysinfo->meminfo[i].dimm_mask==0x00) 
2807                         continue;
2808
2809                 sysinfo->mem_trained[i] = 0x80; // mem need to be trained
2810         }
2811
2812
2813 #if MEM_TRAIN_SEQ ==  0
2814    #if K8_REV_F_SUPPORT_F0_F1_WORKAROUND == 1
2815         dqs_timing(controllers, ctrl, tsc0, sysinfo);
2816    #else
2817         dqs_timing(controllers, ctrl, sysinfo);
2818    #endif
2819 #else
2820
2821    #if MEM_TRAIN_SEQ == 2
2822            //need to enable mtrr, so dqs training could access the test address
2823         setup_mtrr_dqs(sysinfo->tom_k, sysinfo->tom2_k);
2824    #endif
2825
2826         for(i = 0; i < controllers; i++) {
2827                 /* Skip everything if I don't have any memory on this controller */
2828                 if(sysinfo->mem_trained[i]!=0x80) 
2829                         continue;
2830
2831                 dqs_timing(i, &ctrl[i], sysinfo, 1);
2832
2833    #if MEM_TRAIN_SEQ == 1
2834                 break; // only train the first node with ram
2835    #endif
2836         }
2837
2838    #if MEM_TRAIN_SEQ == 2
2839         clear_mtrr_dqs(sysinfo->tom2_k);
2840    #endif
2841
2842 #endif
2843
2844 #if MEM_TRAIN_SEQ != 1
2845         wait_all_core0_mem_trained(sysinfo);
2846 #endif
2847
2848 }
2849 static void fill_mem_ctrl(int controllers, struct mem_controller *ctrl_a, const uint16_t *spd_addr)
2850 {
2851         int i; 
2852         int j;
2853         struct mem_controller *ctrl;
2854         for(i=0;i<controllers; i++) {
2855                 ctrl = &ctrl_a[i];
2856                 ctrl->node_id = i;
2857                 ctrl->f0 = PCI_DEV(0, 0x18+i, 0);
2858                 ctrl->f1 = PCI_DEV(0, 0x18+i, 1);
2859                 ctrl->f2 = PCI_DEV(0, 0x18+i, 2);
2860                 ctrl->f3 = PCI_DEV(0, 0x18+i, 3);
2861
2862                 if(spd_addr == (void *)0) continue;
2863
2864                 for(j=0;j<DIMM_SOCKETS;j++) {
2865                         ctrl->channel0[j] = spd_addr[(i*2+0)*DIMM_SOCKETS + j];
2866                         ctrl->channel1[j] = spd_addr[(i*2+1)*DIMM_SOCKETS + j];
2867                 }
2868         }
2869 }