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