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