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