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