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