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