"no warnings day"
[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 static 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.
722          * FIXME Testing dual channel capability is correct for now
723          * but a better test is probably required.
724          * m2 and s1g1 support dual channel too. but only support unbuffered dimm
725          */
726 #warning "FIXME implement a better test for opterons"
727         uint32_t nbcap;
728         nbcap = pci_read_config32(ctrl->f3, NORTHBRIDGE_CAP);
729         return !!(nbcap & NBCAP_128Bit);
730 }
731
732 #if 0
733 static int is_registered(const struct mem_controller *ctrl)
734 {
735         /* Test to see if we are dealing with registered SDRAM.
736          * If we are not registered we are unbuffered.
737          * This function must be called after spd_handle_unbuffered_dimms.
738          */
739         uint32_t dcl;
740         dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
741         return !(dcl & DCL_UnBuffDimm);
742 }
743 #endif
744
745 static void spd_get_dimm_size(unsigned device, struct dimm_size *sz)
746 {
747         /* Calculate the log base 2 size of a DIMM in bits */
748         int value;
749         sz->per_rank = 0;
750         sz->rows = 0;
751         sz->col = 0;
752         sz->rank = 0;
753
754         value = spd_read_byte(device, SPD_ROW_NUM);     /* rows */
755         if (value < 0) goto hw_err;
756         if ((value & 0xff) == 0) goto val_err; /* max is 16 ? */
757         sz->per_rank += value & 0xff;
758         sz->rows = value & 0xff;
759
760         value = spd_read_byte(device, SPD_COL_NUM);     /* columns */
761         if (value < 0) goto hw_err;
762         if ((value & 0xff) == 0) goto val_err;  /* max is 11 */
763         sz->per_rank += value & 0xff;
764         sz->col = value & 0xff;
765
766         value = spd_read_byte(device, SPD_BANK_NUM);    /* banks */
767         if (value < 0) goto hw_err;
768         if ((value & 0xff) == 0) goto val_err;
769         sz->bank = log2(value & 0xff);  // convert 4 to 2, and 8 to 3
770         sz->per_rank += sz->bank;
771
772         /* Get the module data width and convert it to a power of two */
773         value = spd_read_byte(device, SPD_DATA_WIDTH);
774         if (value < 0) goto hw_err;
775         value &= 0xff;
776         if ((value != 72) && (value != 64)) goto val_err;
777         sz->per_rank += log2(value) - 3; //64 bit So another 3 lines
778
779         /* How many ranks? */
780         /* number of physical banks */
781         value = spd_read_byte(device, SPD_MOD_ATTRIB_RANK);
782         if (value < 0) goto hw_err;
783 /*      value >>= SPD_MOD_ATTRIB_RANK_NUM_SHIFT; */
784         value &= SPD_MOD_ATTRIB_RANK_NUM_MASK;
785         value += SPD_MOD_ATTRIB_RANK_NUM_BASE; // 0-->1, 1-->2, 3-->4
786         /*
787           rank == 1 only one rank or say one side
788           rank == 2 two side , and two ranks
789           rank == 4 two side , and four ranks total
790           Some one side two ranks, because of stacked
791         */
792         if ((value != 1) && (value != 2) && (value != 4 )) {
793                 goto val_err;
794         }
795         sz->rank = value;
796
797         /* verify if per_rank is equal byte 31
798           it has the DIMM size as a multiple of 128MB.
799           */
800         value = spd_read_byte(device, SPD_RANK_SIZE);
801         if (value < 0) goto hw_err;
802         value &= 0xff;
803         value = log2(value);
804         if (value <=4 ) value += 8; // add back to 1G to high
805         value += (27-5); // make 128MB to the real lines
806         if ( value != (sz->per_rank)) {
807                 printk(BIOS_ERR, "Bad RANK Size --\n");
808                 goto val_err;
809         }
810
811         goto out;
812
813  val_err:
814         die("Bad SPD value\n");
815         /* If an hw_error occurs report that I have no memory */
816  hw_err:
817         sz->per_rank = 0;
818         sz->rows = 0;
819         sz->col = 0;
820         sz->bank = 0;
821         sz->rank = 0;
822  out:
823         return;
824 }
825
826
827 static void set_dimm_size(const struct mem_controller *ctrl,
828                           struct dimm_size *sz, unsigned index,
829                           struct mem_info *meminfo)
830 {
831         uint32_t base0, base1;
832
833         /* For each base register.
834          * Place the dimm size in 32 MB quantities in the bits 31 - 21.
835          * The initialize dimm size is in bits.
836          * Set the base enable bit0.
837          */
838
839         base0 = base1 = 0;
840
841         /* Make certain side1 of the dimm is at least 128MB */
842         if (sz->per_rank >= 27) {
843                 base0 = (1 << ((sz->per_rank - 27 ) + 19)) | 1;
844         }
845
846         /* Make certain side2 of the dimm is at least 128MB */
847         if (sz->rank > 1) { // 2 ranks or 4 ranks
848                 base1 = (1 << ((sz->per_rank - 27 ) + 19)) | 1;
849         }
850
851         /* Double the size if we are using dual channel memory */
852         if (meminfo->is_Width128) {
853                 base0 = (base0 << 1) | (base0 & 1);
854                 base1 = (base1 << 1) | (base1 & 1);
855         }
856
857         /* Clear the reserved bits */
858         base0 &= ~0xe007fffe;
859         base1 &= ~0xe007fffe;
860
861         if (!(meminfo->dimm_mask & 0x0F) && (meminfo->dimm_mask & 0xF0)) { /* channelB only? */
862                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1) + 4) << 2), base0);
863                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1) + 5) << 2), base1);
864         } else {
865                 /* Set the appropriate DIMM base address register */
866                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1) + 0) << 2), base0);
867                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1) + 1) << 2), base1);
868 #if QRANK_DIMM_SUPPORT == 1
869                 if (sz->rank == 4) {
870                         pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1) + 4) << 2), base0);
871                         pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1) + 5) << 2), base1);
872                 }
873 #endif
874         }
875
876         /* Enable the memory clocks for this DIMM by Clear the MemClkDis bit*/
877         if (base0) {
878                 uint32_t dword;
879                 uint32_t ClkDis0;
880 #if CONFIG_CPU_SOCKET_TYPE == 0x10 /* L1 */
881                 ClkDis0 = DTL_MemClkDis0;
882 #elif CONFIG_CPU_SOCKET_TYPE == 0x11 /* AM2 */
883                 ClkDis0 = DTL_MemClkDis0_AM2;
884 #elif CONFIG_CPU_SOCKET_TYPE == 0x12    /* S1G1 */
885                 ClkDis0 = DTL_MemClkDis0_S1g1;
886 #endif
887
888                 if (!(meminfo->dimm_mask & 0x0F) && (meminfo->dimm_mask & 0xF0)) { /* channelB only? */
889                         dword = pci_read_config32(ctrl->f2, DRAM_CTRL_MISC);
890                         dword &= ~(ClkDis0 >> index);
891                         pci_write_config32(ctrl->f2, DRAM_CTRL_MISC, dword);
892
893                 } else {
894                         dword = pci_read_config32(ctrl->f2, DRAM_TIMING_LOW); //Channel A
895                         dword &= ~(ClkDis0 >> index);
896 #if QRANK_DIMM_SUPPORT == 1
897                         if (sz->rank == 4) {
898                                 dword &= ~(ClkDis0 >> (index+2));
899                         }
900 #endif
901                         pci_write_config32(ctrl->f2, DRAM_TIMING_LOW, dword);
902
903                         if (meminfo->is_Width128) { // ChannelA+B
904                                 dword = pci_read_config32(ctrl->f2, DRAM_CTRL_MISC);
905                                 dword &= ~(ClkDis0 >> index);
906 #if QRANK_DIMM_SUPPORT == 1
907                                 if (sz->rank == 4) {
908                                         dword &= ~(ClkDis0 >> (index+2));
909                                 }
910 #endif
911                                 pci_write_config32(ctrl->f2, DRAM_CTRL_MISC, dword);
912                         }
913                 }
914
915         }
916 }
917
918 /*    row    col   bank  for 64 bit
919   0:  13     9      2    :128M
920   1:  13     10     2    :256M
921   2:  14     10     2    :512M
922   3:  13     11     2    :512M
923   4:  13     10     3    :512M
924   5:  14     10     3    :1G
925   6:  14     11     2    :1G
926   7:  15     10     3    :2G
927   8:  14     11     3    :2G
928   9:  15     11     3    :4G
929  10:  16     10     3    :4G
930  11:  16     11     3    :8G
931 */
932
933
934 static void set_dimm_cs_map(const struct mem_controller *ctrl,
935                              struct dimm_size *sz, unsigned index,
936                              struct mem_info *meminfo)
937 {
938         static const uint8_t cs_map_aaa[24] = {
939                 /* (bank=2, row=13, col=9)(3, 16, 11) ---> (0, 0, 0) (1, 3, 2) */
940         //Bank2
941                 0, 1, 3,
942                 0, 2, 6,
943                 0, 0, 0,
944                 0, 0, 0,
945         //Bank3
946                 0, 4, 0,
947                 0, 5, 8,
948                 0, 7, 9,
949                 0,10,11,
950         };
951
952         uint32_t map;
953
954         if (!(meminfo->dimm_mask & 0x0F) && (meminfo->dimm_mask & 0xF0)) { /* channelB only? */
955                 index += 2;
956         }
957         map = pci_read_config32(ctrl->f2, DRAM_BANK_ADDR_MAP);
958         map &= ~(0xf << (index * 4));
959 #if QRANK_DIMM_SUPPORT == 1
960         if (sz->rank == 4) {
961                 map &= ~(0xf << ( (index + 2) * 4));
962         }
963 #endif
964
965         /* Make certain side1 of the dimm is at least 128MB */
966         if (sz->per_rank >= 27) {
967                 unsigned temp_map;
968                 temp_map = cs_map_aaa[(sz->bank-2)*3*4 + (sz->rows - 13)*3 + (sz->col - 9) ];
969                 map |= temp_map << (index*4);
970 #if QRANK_DIMM_SUPPORT == 1
971                 if (sz->rank == 4) {
972                         map |=  temp_map << ( (index + 2) * 4);
973                 }
974 #endif
975         }
976
977         pci_write_config32(ctrl->f2, DRAM_BANK_ADDR_MAP, map);
978
979 }
980
981
982 static long spd_set_ram_size(const struct mem_controller *ctrl,
983                               struct mem_info *meminfo)
984 {
985         int i;
986
987         for (i = 0; i < DIMM_SOCKETS; i++) {
988                 struct dimm_size *sz = &(meminfo->sz[i]);
989                 u32 spd_device = ctrl->channel0[i];
990
991                 if (!(meminfo->dimm_mask & (1 << i))) {
992                         if (meminfo->dimm_mask & (1 << (DIMM_SOCKETS + i))) { /* channelB only? */
993                                 spd_device = ctrl->channel1[i];
994                         } else {
995                                 continue;
996                         }
997                 }
998
999                 spd_get_dimm_size(spd_device, sz);
1000                 if (sz->per_rank == 0) {
1001                         return -1; /* Report SPD error */
1002                 }
1003                 set_dimm_size(ctrl, sz, i, meminfo);
1004                 set_dimm_cs_map(ctrl, sz, i, meminfo);
1005         }
1006         return meminfo->dimm_mask;
1007 }
1008
1009 static void route_dram_accesses(const struct mem_controller *ctrl,
1010                                 unsigned long base_k, unsigned long limit_k)
1011 {
1012         /* Route the addresses to the controller node */
1013         unsigned node_id;
1014         unsigned limit;
1015         unsigned base;
1016         unsigned index;
1017         unsigned limit_reg, base_reg;
1018         device_t device;
1019
1020         node_id = ctrl->node_id;
1021         index = (node_id << 3);
1022         limit = (limit_k << 2);
1023         limit &= 0xffff0000;
1024         limit -= 0x00010000;
1025         limit |= ( 0 << 8) | (node_id << 0);
1026         base = (base_k << 2);
1027         base &= 0xffff0000;
1028         base |= (0 << 8) | (1<<1) | (1<<0);
1029
1030         limit_reg = 0x44 + index;
1031         base_reg = 0x40 + index;
1032         for (device = PCI_DEV(0, 0x18, 1); device <= PCI_DEV(0, 0x1f, 1);
1033              device += PCI_DEV(0, 1, 0)) {
1034                 pci_write_config32(device, limit_reg, limit);
1035                 pci_write_config32(device, base_reg, base);
1036         }
1037 }
1038
1039 static void set_top_mem(unsigned tom_k, unsigned hole_startk)
1040 {
1041         /* Error if I don't have memory */
1042         if (!tom_k) {
1043                 die("No memory?");
1044         }
1045
1046         /* Report the amount of memory. */
1047         printk(BIOS_DEBUG, "RAM end at 0x%08x kB\n", tom_k);
1048
1049         /* Now set top of memory */
1050         msr_t msr;
1051         if (tom_k > (4*1024*1024)) {
1052                 printk_raminit("Handling memory mapped above 4 GB\n");
1053                 printk_raminit("Upper RAM end at 0x%08x kB\n", tom_k);
1054                 msr.lo = (tom_k & 0x003fffff) << 10;
1055                 msr.hi = (tom_k & 0xffc00000) >> 22;
1056                 wrmsr(TOP_MEM2, msr);
1057                 printk_raminit("Correcting memory amount mapped below 4 GB\n");
1058         }
1059
1060         /* Leave a 64M hole between TOP_MEM and TOP_MEM2
1061          * so I can see my rom chip and other I/O devices.
1062          */
1063         if (tom_k >= 0x003f0000) {
1064 #if CONFIG_HW_MEM_HOLE_SIZEK != 0
1065                 if (hole_startk != 0) {
1066                         tom_k = hole_startk;
1067                 } else
1068 #endif
1069                 tom_k = 0x3f0000;
1070                 printk_raminit("Adjusting lower RAM end\n");
1071         }
1072         printk_raminit("Lower RAM end at 0x%08x kB\n", tom_k);
1073         msr.lo = (tom_k & 0x003fffff) << 10;
1074         msr.hi = (tom_k & 0xffc00000) >> 22;
1075         wrmsr(TOP_MEM, msr);
1076 }
1077
1078 static unsigned long interleave_chip_selects(const struct mem_controller *ctrl, int is_Width128)
1079 {
1080         /* 35 - 27 */
1081
1082         static const uint8_t csbase_low_f0_shift[] = {
1083          /* 128MB */       (14 - (13-5)),
1084          /* 256MB */       (15 - (13-5)),
1085          /* 512MB */       (15 - (13-5)),
1086          /* 512MB */       (16 - (13-5)),
1087          /* 512MB */       (16 - (13-5)),
1088          /* 1GB   */       (16 - (13-5)),
1089          /* 1GB   */       (16 - (13-5)),
1090          /* 2GB   */       (16 - (13-5)),
1091          /* 2GB   */       (17 - (13-5)),
1092          /* 4GB   */       (17 - (13-5)),
1093          /* 4GB   */       (16 - (13-5)),
1094          /* 8GB   */       (17 - (13-5)),
1095         };
1096
1097         /* cs_base_high is not changed */
1098
1099         uint32_t csbase_inc;
1100         int chip_selects, index;
1101         int bits;
1102         unsigned common_size;
1103         unsigned common_cs_mode;
1104         uint32_t csbase, csmask;
1105
1106         /* See if all of the memory chip selects are the same size
1107          * and if so count them.
1108          */
1109         chip_selects = 0;
1110         common_size = 0;
1111         common_cs_mode = 0xff;
1112         for (index = 0; index < 8; index++) {
1113                 unsigned size;
1114                 unsigned cs_mode;
1115                 uint32_t value;
1116
1117                 value = pci_read_config32(ctrl->f2, DRAM_CSBASE + (index << 2));
1118
1119                 /* Is it enabled? */
1120                 if (!(value & 1)) {
1121                         continue;
1122                 }
1123                 chip_selects++;
1124                 size = (value >> 19) & 0x3ff;
1125                 if (common_size == 0) {
1126                         common_size = size;
1127                 }
1128                 /* The size differed fail */
1129                 if (common_size != size) {
1130                         return 0;
1131                 }
1132
1133                 value = pci_read_config32(ctrl->f2, DRAM_BANK_ADDR_MAP);
1134                 cs_mode =( value >> ((index>>1)*4)) & 0xf;
1135                 if (common_cs_mode == 0xff) {
1136                         common_cs_mode = cs_mode;
1137                 }
1138                 /* The cs_mode differed fail */
1139                 if (common_cs_mode != cs_mode) {
1140                         return 0;
1141                 }
1142         }
1143
1144         /* Chip selects can only be interleaved when there is
1145          * more than one and their is a power of two of them.
1146          */
1147         bits = log2(chip_selects);
1148         if (((1 << bits) != chip_selects) || (bits < 1) || (bits > 3)) {
1149                 //chip_selects max = 8
1150                 return 0;
1151         }
1152
1153         /* Find the bits of csbase that we need to interleave on */
1154         csbase_inc = 1 << (csbase_low_f0_shift[common_cs_mode]);
1155         if (is_Width128) {
1156                 csbase_inc <<=1;
1157         }
1158
1159         /* Compute the initial values for csbase and csbask.
1160          * In csbase just set the enable bit and the base to zero.
1161          * In csmask set the mask bits for the size and page level interleave.
1162          */
1163         csbase = 0 | 1;
1164         csmask = (((common_size  << bits) - 1) << 19);
1165         csmask |= 0x3fe0 & ~((csbase_inc << bits) - csbase_inc);
1166         for (index = 0; index < 8; index++) {
1167                 uint32_t value;
1168
1169                 value = pci_read_config32(ctrl->f2, DRAM_CSBASE + (index << 2));
1170                 /* Is it enabled? */
1171                 if (!(value & 1)) {
1172                         continue;
1173                 }
1174                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (index << 2), csbase);
1175                 if ((index & 1) == 0) {  //only have 4 CSMASK
1176                         pci_write_config32(ctrl->f2, DRAM_CSMASK + ((index>>1) << 2), csmask);
1177                 }
1178                 csbase += csbase_inc;
1179         }
1180
1181         printk(BIOS_DEBUG, "Interleaved\n");
1182
1183         /* Return the memory size in K */
1184         return common_size << ((27-10) + bits);
1185 }
1186
1187 static unsigned long order_chip_selects(const struct mem_controller *ctrl)
1188 {
1189         unsigned long tom;
1190
1191         /* Remember which registers we have used in the high 8 bits of tom */
1192         tom = 0;
1193         for (;;) {
1194                 /* Find the largest remaining canidate */
1195                 unsigned index, canidate;
1196                 uint32_t csbase, csmask;
1197                 unsigned size;
1198                 csbase = 0;
1199                 canidate = 0;
1200                 for (index = 0; index < 8; index++) {
1201                         uint32_t value;
1202                         value = pci_read_config32(ctrl->f2, DRAM_CSBASE + (index << 2));
1203
1204                         /* Is it enabled? */
1205                         if (!(value & 1)) {
1206                                 continue;
1207                         }
1208
1209                         /* Is it greater? */
1210                         if (value <= csbase) {
1211                                 continue;
1212                         }
1213
1214                         /* Has it already been selected */
1215                         if (tom & (1 << (index + 24))) {
1216                                 continue;
1217                         }
1218                         /* I have a new canidate */
1219                         csbase = value;
1220                         canidate = index;
1221                 }
1222                 
1223                 /* See if I have found a new canidate */
1224                 if (csbase == 0) {
1225                         break;
1226                 }
1227
1228                 /* Remember the dimm size */
1229                 size = csbase >> 19;
1230
1231                 /* Remember I have used this register */
1232                 tom |= (1 << (canidate + 24));
1233
1234                 /* Recompute the cs base register value */
1235                 csbase = (tom << 19) | 1;
1236
1237                 /* Increment the top of memory */
1238                 tom += size;
1239
1240                 /* Compute the memory mask */
1241                 csmask = ((size -1) << 19);
1242                 csmask |= 0x3fe0;               /* For now don't optimize */
1243
1244                 /* Write the new base register */
1245                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (canidate << 2), csbase);
1246                 /* Write the new mask register */
1247                 if ((canidate & 1) == 0) {  //only have 4 CSMASK
1248                         pci_write_config32(ctrl->f2, DRAM_CSMASK + ((canidate >> 1) << 2), csmask);
1249                 }
1250
1251         }
1252         /* Return the memory size in K */
1253         return (tom & ~0xff000000) << (27-10);
1254 }
1255
1256 static unsigned long memory_end_k(const struct mem_controller *ctrl, int max_node_id)
1257 {
1258         unsigned node_id;
1259         unsigned end_k;
1260         /* Find the last memory address used */
1261         end_k = 0;
1262         for (node_id = 0; node_id < max_node_id; node_id++) {
1263                 uint32_t limit, base;
1264                 unsigned index;
1265                 index = node_id << 3;
1266                 base = pci_read_config32(ctrl->f1, 0x40 + index);
1267                 /* Only look at the limit if the base is enabled */
1268                 if ((base & 3) == 3) {
1269                         limit = pci_read_config32(ctrl->f1, 0x44 + index);
1270                         end_k = ((limit + 0x00010000) & 0xffff0000) >> 2;
1271                 }
1272         }
1273         return end_k;
1274 }
1275
1276 static void order_dimms(const struct mem_controller *ctrl,
1277                          struct mem_info *meminfo)
1278 {
1279         unsigned long tom_k, base_k;
1280
1281         if (read_option(CMOS_VSTART_interleave_chip_selects,
1282             CMOS_VLEN_interleave_chip_selects, 1) != 0) {
1283                 tom_k = interleave_chip_selects(ctrl, meminfo->is_Width128);
1284         } else {
1285                 printk(BIOS_DEBUG, "Interleaving disabled\n");
1286                 tom_k = 0;
1287         }
1288
1289         if (!tom_k) {
1290                 tom_k = order_chip_selects(ctrl);
1291         }
1292
1293         /* Compute the memory base address */
1294         base_k = memory_end_k(ctrl, ctrl->node_id);
1295         tom_k += base_k;
1296         route_dram_accesses(ctrl, base_k, tom_k);
1297         set_top_mem(tom_k, 0);
1298 }
1299
1300 static long disable_dimm(const struct mem_controller *ctrl, unsigned index,
1301                           struct mem_info *meminfo)
1302 {
1303         printk(BIOS_DEBUG, "disabling dimm %02x\n", index);
1304         if (!(meminfo->dimm_mask & 0x0F) && (meminfo->dimm_mask & 0xF0)) { /* channelB only? */
1305                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1) + 4) << 2), 0);
1306                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1) + 5) << 2), 0);
1307         } else {
1308                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1) + 0) << 2), 0);
1309                 pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1) + 1) << 2), 0);
1310 #if QRANK_DIMM_SUPPORT == 1
1311                 if (meminfo->sz[index].rank == 4) {
1312                         pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1) + 4) << 2), 0);
1313                         pci_write_config32(ctrl->f2, DRAM_CSBASE + (((index << 1) + 5) << 2), 0);
1314                 }
1315 #endif
1316         }
1317
1318         meminfo->dimm_mask &= ~(1 << index);
1319         return meminfo->dimm_mask;
1320 }
1321
1322 static long spd_handle_unbuffered_dimms(const struct mem_controller *ctrl,
1323                                          struct mem_info *meminfo)
1324 {
1325         int i;
1326         uint32_t registered;
1327         uint32_t dcl;
1328         registered = 0;
1329         for (i = 0; (i < DIMM_SOCKETS); i++) {
1330                 int value;
1331                 u32 spd_device = ctrl->channel0[i];
1332                 if (!(meminfo->dimm_mask & (1 << i))) {
1333                         if (meminfo->dimm_mask & (1 << (DIMM_SOCKETS + i))) { /* channelB only? */
1334                                 spd_device = ctrl->channel1[i];
1335                         } else {
1336                                 continue;
1337                         }
1338                 }
1339                 value = spd_read_byte(spd_device, SPD_DIMM_TYPE);
1340                 if (value < 0) {
1341                         return -1;
1342                 }
1343
1344                 /* Registered dimm ? */
1345                 value &= 0x3f;
1346                 if ((value == SPD_DIMM_TYPE_RDIMM) || (value == SPD_DIMM_TYPE_mRDIMM)) {
1347                         //check SPD_MOD_ATTRIB to verify it is SPD_MOD_ATTRIB_REGADC (0x11)?
1348                         registered |= (1<<i);
1349                 }
1350         }
1351
1352         if (is_opteron(ctrl)) {
1353 #if 0
1354                 if ( registered != (meminfo->dimm_mask & ((1<<DIMM_SOCKETS)-1)) ) {
1355                         meminfo->dimm_mask &= (registered | (registered << DIMM_SOCKETS) ); //disable unbuffed dimm
1356 //                      die("Mixed buffered and registered dimms not supported");
1357                 }
1358                 //By yhlu for debug M2, s1g1 can do dual channel, but it use unbuffer DIMM
1359                 if (!registered) {
1360                         die("Unbuffered Dimms not supported on Opteron");
1361                 }
1362 #endif
1363         }
1364
1365
1366         dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
1367         dcl &= ~DCL_UnBuffDimm;
1368         meminfo->is_registered = 1;
1369         if (!registered) {
1370                 dcl |= DCL_UnBuffDimm;
1371                 meminfo->is_registered = 0;
1372         }
1373         pci_write_config32(ctrl->f2, DRAM_CONFIG_LOW, dcl);
1374
1375         if (meminfo->is_registered) {
1376                 printk(BIOS_SPEW, "Registered\n");
1377         } else {
1378                 printk(BIOS_SPEW, "Unbuffered\n");
1379         }
1380         return meminfo->dimm_mask;
1381 }
1382
1383 static unsigned int spd_detect_dimms(const struct mem_controller *ctrl)
1384 {
1385         unsigned dimm_mask;
1386         int i;
1387         dimm_mask = 0;
1388         for (i = 0; i < DIMM_SOCKETS; i++) {
1389                 int byte;
1390                 unsigned device;
1391                 device = ctrl->channel0[i];
1392                 printk_raminit("DIMM socket %i, channel 0 SPD device is 0x%02x\n", i, device);
1393                 if (device) {
1394                         byte = spd_read_byte(ctrl->channel0[i], SPD_MEM_TYPE);  /* Type */
1395                         if (byte == SPD_MEM_TYPE_SDRAM_DDR2) {
1396                                 dimm_mask |= (1 << i);
1397                         }
1398                 }
1399                 device = ctrl->channel1[i];
1400                 printk_raminit("DIMM socket %i, channel 1 SPD device is 0x%02x\n", i, device);
1401                 if (device) {
1402                         byte = spd_read_byte(ctrl->channel1[i], SPD_MEM_TYPE);
1403                         if (byte == SPD_MEM_TYPE_SDRAM_DDR2) {
1404                                 dimm_mask |= (1 << (i + DIMM_SOCKETS));
1405                         }
1406                 }
1407         }
1408         return dimm_mask;
1409 }
1410
1411 static long spd_enable_2channels(const struct mem_controller *ctrl, struct mem_info *meminfo)
1412 {
1413         int i;
1414         uint32_t nbcap;
1415         /* SPD addresses to verify are identical */
1416         static const uint8_t addresses[] = {
1417                 2,      /* Type should be DDR2 SDRAM */
1418                 3,      /* *Row addresses */
1419                 4,      /* *Column addresses */
1420                 5,      /* *Number of DIMM Ranks */
1421                 6,      /* *Module Data Width*/
1422                 11,     /* *DIMM Conf Type */
1423                 13,     /* *Pri SDRAM Width */
1424                 17,     /* *Logical Banks */
1425                 20,     /* *DIMM Type Info */
1426                 21,     /* *SDRAM Module Attributes */
1427                 27,     /* *tRP Row precharge time */
1428                 28,     /* *Minimum Row Active to Row Active Delay (tRRD) */
1429                 29,     /* *tRCD RAS to CAS */
1430                 30,     /* *tRAS Activate to Precharge */
1431                 36,     /* *Write recovery time (tWR) */
1432                 37,     /* *Internal write to read command delay (tRDP) */
1433                 38,     /* *Internal read to precharge command delay (tRTP) */
1434                 40,     /* *Extension of Byte 41 tRC and Byte 42 tRFC */
1435                 41,     /* *Minimum Active to Active/Auto Refresh Time(Trc) */
1436                 42,     /* *Minimum Auto Refresh Command Time(Trfc) */
1437                 /* The SPD addresses 18, 9, 23, 26 need special treatment like
1438                  * in spd_set_memclk. Right now they cause many false negatives.
1439                  * Keep them at the end to see other mismatches (if any).
1440                  */
1441                 18,     /* *Supported CAS Latencies */
1442                 9,      /* *Cycle time at highest CAS Latency CL=X */
1443                 23,     /* *Cycle time at CAS Latency (CLX - 1) */
1444                 26,     /* *Cycle time at CAS Latency (CLX - 2) */
1445         };
1446         u32 dcl, dcm;
1447         u8 common_cl;
1448
1449 /* S1G1 and AM2 sockets are Mod64BitMux capable. */
1450 #if CONFIG_CPU_SOCKET_TYPE == 0x11 || CONFIG_CPU_SOCKET_TYPE == 0x12
1451         u8 mux_cap = 1;
1452 #else
1453         u8 mux_cap = 0;
1454 #endif
1455
1456         /* If the dimms are not in pairs do not do dual channels */
1457         if ((meminfo->dimm_mask & ((1 << DIMM_SOCKETS) - 1)) !=
1458                 ((meminfo->dimm_mask >> DIMM_SOCKETS) & ((1 << DIMM_SOCKETS) - 1))) {
1459                 goto single_channel;
1460         }
1461         /* If the cpu is not capable of doing dual channels don't do dual channels */
1462         nbcap = pci_read_config32(ctrl->f3, NORTHBRIDGE_CAP);
1463         if (!(nbcap & NBCAP_128Bit)) {
1464                 goto single_channel;
1465         }
1466         for (i = 0; (i < 4) && (ctrl->channel0[i]); i++) {
1467                 unsigned device0, device1;
1468                 int value0, value1;
1469                 int j;
1470                 /* If I don't have a dimm skip this one */
1471                 if (!(meminfo->dimm_mask & (1 << i))) {
1472                         continue;
1473                 }
1474                 device0 = ctrl->channel0[i];
1475                 device1 = ctrl->channel1[i];
1476                 /* Abort if the chips don't support a common CAS latency. */
1477                 common_cl = spd_read_byte(device0, 18) & spd_read_byte(device1, 18);
1478                 if (!common_cl) {
1479                         printk(BIOS_DEBUG, "No common CAS latency supported\n");
1480                         goto single_channel;
1481                 } else {
1482                         printk_raminit("Common CAS latency bitfield: 0x%02x\n", common_cl);
1483                 }
1484                 for (j = 0; j < ARRAY_SIZE(addresses); j++) {
1485                         unsigned addr;
1486                         addr = addresses[j];
1487                         value0 = spd_read_byte(device0, addr);
1488                         if (value0 < 0) {
1489                                 return -1;
1490                         }
1491                         value1 = spd_read_byte(device1, addr);
1492                         if (value1 < 0) {
1493                                 return -1;
1494                         }
1495                         if (value0 != value1) {
1496                                 printk_raminit("SPD values differ between channel 0/1 for byte %i\n", addr);
1497                                 goto single_channel;
1498                         }
1499                 }
1500         }
1501         printk(BIOS_SPEW, "Enabling dual channel memory\n");
1502         dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
1503         dcl &= ~DCL_BurstLength32;  /*  32byte mode may be preferred in platforms that include graphics controllers that generate a lot of 32-bytes system memory accesses
1504                                         32byte mode is not supported when the DRAM interface is 128 bits wides, even 32byte mode is set, system still use 64 byte mode  */
1505         dcl |= DCL_Width128;
1506         pci_write_config32(ctrl->f2, DRAM_CONFIG_LOW, dcl);
1507         meminfo->is_Width128 = 1;
1508         return meminfo->dimm_mask;
1509
1510  single_channel:
1511         meminfo->is_Width128 = 0;
1512         meminfo->is_64MuxMode = 0;
1513
1514         /* single dimm */
1515         if ((meminfo->dimm_mask & ((1 << DIMM_SOCKETS) - 1)) !=
1516            ((meminfo->dimm_mask >> DIMM_SOCKETS) & ((1 << DIMM_SOCKETS) - 1))) {
1517                 if (((meminfo->dimm_mask >> DIMM_SOCKETS) & ((1 << DIMM_SOCKETS) - 1))) {
1518                         /* mux capable and single dimm in channelB */
1519                         if (mux_cap) {
1520                                 printk(BIOS_SPEW, "Enable 64MuxMode & BurstLength32\n");
1521                                 dcm = pci_read_config32(ctrl->f2, DRAM_CTRL_MISC);
1522                                 dcm |= DCM_Mode64BitMux;
1523                                 pci_write_config32(ctrl->f2, DRAM_CTRL_MISC, dcm);
1524                                 dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
1525                                 //dcl |= DCL_BurstLength32; /* 32byte mode for channelB only */
1526                                 pci_write_config32(ctrl->f2, DRAM_CONFIG_LOW, dcl);
1527                                 meminfo->is_64MuxMode = 1;
1528                         } else {
1529                                 meminfo->dimm_mask &= ~((1 << (DIMM_SOCKETS * 2)) - (1 << DIMM_SOCKETS));
1530                         }
1531                 }
1532         } else { /* unmatched dual dimms ? */
1533                 /* unmatched dual dimms not supported by meminit code. Use single channelA dimm. */
1534                 meminfo->dimm_mask &= ~((1 << (DIMM_SOCKETS * 2)) - (1 << DIMM_SOCKETS));
1535                 printk(BIOS_SPEW, "Unmatched dual dimms. Use single channelA dimm.\n");
1536         }
1537         return meminfo->dimm_mask;
1538 }
1539
1540 struct mem_param {
1541         uint16_t cycle_time;
1542         uint8_t divisor; /* In 1/40 ns increments */
1543         uint8_t TrwtTO;
1544         uint8_t Twrrd;
1545         uint8_t Twrwr;
1546         uint8_t Trdrd;
1547         uint8_t DcqByPassMax;
1548         uint32_t dch_memclk;
1549         char name[9];
1550 };
1551
1552         static const struct mem_param speed[] = {
1553                 {
1554                         .name       = "200MHz",
1555                         .cycle_time = 0x500,
1556                         .divisor    = 200, // how many 1/40ns per clock
1557                         .dch_memclk = DCH_MemClkFreq_200MHz, //0
1558                         .TrwtTO     = 7,
1559                         .Twrrd      = 2,
1560                         .Twrwr      = 2,
1561                         .Trdrd      = 3,
1562                         .DcqByPassMax = 4,
1563
1564                 },
1565                 {
1566                         .name       = "266MHz",
1567                         .cycle_time = 0x375,
1568                         .divisor    = 150, //????
1569                         .dch_memclk = DCH_MemClkFreq_266MHz, //1
1570                         .TrwtTO     = 7,
1571                         .Twrrd      = 2,
1572                         .Twrwr      = 2,
1573                         .Trdrd      = 3,
1574                         .DcqByPassMax = 4,
1575                 },
1576                  {
1577                         .name       = "333MHz",
1578                         .cycle_time = 0x300,
1579                         .divisor    = 120,
1580                         .dch_memclk = DCH_MemClkFreq_333MHz, //2
1581                         .TrwtTO     = 7,
1582                         .Twrrd      = 2,
1583                         .Twrwr      = 2,
1584                         .Trdrd      = 3,
1585                         .DcqByPassMax = 4,
1586
1587                  },
1588                 {
1589                         .name       = "400MHz",
1590                         .cycle_time = 0x250,
1591                         .divisor    = 100,
1592                         .dch_memclk = DCH_MemClkFreq_400MHz,//3
1593                         .TrwtTO     = 7,
1594                         .Twrrd      = 2,
1595                         .Twrwr      = 2,
1596                         .Trdrd      = 3,
1597                         .DcqByPassMax = 4,
1598                 },
1599                 {
1600                         .cycle_time = 0x000,
1601                 },
1602         };
1603
1604 static const struct mem_param *get_mem_param(unsigned min_cycle_time)
1605 {
1606
1607         const struct mem_param *param;
1608         for (param = &speed[0]; param->cycle_time ; param++) {
1609                 if (min_cycle_time > (param+1)->cycle_time) {
1610                         break;
1611                 }
1612         }
1613         if (!param->cycle_time) {
1614                 die("min_cycle_time to low");
1615         }
1616         printk(BIOS_SPEW, "%s\n", param->name);
1617         return param;
1618 }
1619
1620 static uint8_t get_exact_divisor(int i, uint8_t divisor)
1621 {
1622         //input divisor could be 200(200), 150(266), 120(333), 100 (400)
1623         static const uint8_t dv_a[] = {
1624                /* 200  266  333  400 */
1625          /*4 */   250, 250, 250, 250,
1626          /*5 */   200, 200, 200, 100,
1627          /*6 */   200, 166, 166, 100,
1628          /*7 */   200, 171, 142, 100,
1629
1630           /*8 */   200, 150, 125, 100,
1631           /*9 */   200, 156, 133, 100,
1632           /*10*/   200, 160, 120, 100,
1633           /*11*/   200, 163, 127, 100,
1634
1635           /*12*/   200, 150, 133, 100,
1636           /*13*/   200, 153, 123, 100,
1637           /*14*/   200, 157, 128, 100,
1638           /*15*/   200, 160, 120, 100,
1639         };
1640
1641         
1642         int index;
1643         msr_t msr;
1644
1645         /* Check for FID control support */
1646         struct cpuid_result cpuid1;
1647         cpuid1 = cpuid(0x80000007);
1648         if( cpuid1.edx & 0x02 ) {
1649                 /* Use current FID */
1650                 unsigned fid_cur;
1651                 msr = rdmsr(0xc0010042);
1652                 fid_cur = msr.lo & 0x3f;
1653
1654                 index = fid_cur>>1;
1655         } else {
1656                 /* Use startup FID */
1657                 unsigned fid_start;
1658                 msr = rdmsr(0xc0010015);
1659                 fid_start = (msr.lo & (0x3f << 24));
1660                 
1661                 index = fid_start>>25;
1662         }
1663
1664         if (index>12) return divisor;
1665
1666         if (i>3) return divisor;
1667
1668         return dv_a[index * 4+i];
1669
1670 }
1671
1672
1673 struct spd_set_memclk_result {
1674         const struct mem_param *param;
1675         long dimm_mask;
1676 };
1677
1678
1679 static unsigned convert_to_linear(unsigned value)
1680 {
1681         static const unsigned fraction[] = { 0x25, 0x33, 0x66, 0x75 };
1682         unsigned valuex;
1683
1684         /* We need to convert value to more readable */
1685         if ((value & 0xf) < 10) { //no .25, .33, .66, .75
1686                 value <<= 4;
1687         } else {
1688                 valuex = ((value & 0xf0) << 4) | fraction [(value & 0xf)-10];
1689                 value = valuex;
1690         }
1691         return value;
1692 }
1693
1694 static const uint8_t latency_indicies[] = { 25, 23, 9 };
1695
1696 static int find_optimum_spd_latency(u32 spd_device, unsigned *min_latency, unsigned *min_cycle_time)
1697 {
1698         int new_cycle_time, new_latency;
1699         int index;
1700         int latencies;
1701         int latency;
1702
1703         /* First find the supported CAS latencies
1704          * Byte 18 for DDR SDRAM is interpreted:
1705          * bit 3 == CAS Latency = 3
1706          * bit 4 == CAS Latency = 4
1707          * bit 5 == CAS Latency = 5
1708          * bit 6 == CAS Latency = 6
1709          */
1710         new_cycle_time = 0x500;
1711         new_latency = 6;
1712
1713         latencies = spd_read_byte(spd_device, SPD_CAS_LAT);
1714         if (latencies <= 0)
1715                 return 1;
1716
1717         printk_raminit("\tlatencies: %08x\n", latencies);
1718         /* Compute the lowest cas latency which can be expressed in this
1719          * particular SPD EEPROM. You can store at most settings for 3
1720          * contiguous CAS latencies, so by taking the highest CAS
1721          * latency maked as supported in the SPD and subtracting 2 you
1722          * get the lowest expressable CAS latency. That latency is not
1723          * necessarily supported, but a (maybe invalid) entry exists
1724          * for it.
1725          */
1726         latency = log2(latencies) - 2;
1727
1728         /* Loop through and find a fast clock with a low latency */
1729         for (index = 0; index < 3; index++, latency++) {
1730                 int value;
1731                 if ((latency < 3) || (latency > 6) ||
1732                         (!(latencies & (1 << latency)))) {
1733                         continue;
1734                 }
1735                 value = spd_read_byte(spd_device, latency_indicies[index]);
1736                 if (value < 0) {
1737                         return -1;
1738                 }
1739
1740                 printk_raminit("\tindex: %08x\n", index);
1741                 printk_raminit("\t\tlatency: %08x\n", latency);
1742                 printk_raminit("\t\tvalue1: %08x\n", value);
1743
1744                 value = convert_to_linear(value);
1745
1746                 printk_raminit("\t\tvalue2: %08x\n", value);
1747
1748                 /* Only increase the latency if we decrease the clock */
1749                 if (value >= *min_cycle_time ) {
1750                         if (value < new_cycle_time) {
1751                                 new_cycle_time = value;
1752                                 new_latency = latency;
1753                         } else if (value == new_cycle_time) {
1754                                 if (new_latency > latency) {
1755                                         new_latency = latency;
1756                                 }
1757                         }
1758                 }
1759                 printk_raminit("\t\tnew_cycle_time: %08x\n", new_cycle_time);
1760                 printk_raminit("\t\tnew_latency: %08x\n", new_latency);
1761
1762         }
1763
1764         if (new_latency > 6){
1765                 return 1;
1766         }
1767
1768         /* Does min_latency need to be increased? */
1769         if (new_cycle_time > *min_cycle_time) {
1770                 *min_cycle_time = new_cycle_time;
1771         }
1772
1773         /* Does min_cycle_time need to be increased? */
1774         if (new_latency > *min_latency) {
1775                 *min_latency = new_latency;
1776         }
1777
1778         printk_raminit("2 min_cycle_time: %08x\n", *min_cycle_time);
1779         printk_raminit("2 min_latency: %08x\n", *min_latency);
1780
1781         return 0;
1782 }
1783
1784 static struct spd_set_memclk_result spd_set_memclk(const struct mem_controller *ctrl, struct mem_info *meminfo)
1785 {
1786         /* Compute the minimum cycle time for these dimms */
1787         struct spd_set_memclk_result result;
1788         unsigned min_cycle_time, min_latency, bios_cycle_time;
1789         int i;
1790         uint32_t value;
1791
1792         static const uint16_t min_cycle_times[] = { // use full speed to compare
1793                 [NBCAP_MEMCLK_NOLIMIT] = 0x250, /*2.5ns */
1794                 [NBCAP_MEMCLK_333MHZ] = 0x300, /* 3.0ns */
1795                 [NBCAP_MEMCLK_266MHZ] = 0x375, /* 3.75ns */
1796                 [NBCAP_MEMCLK_200MHZ] = 0x500, /* 5.0s */
1797         };
1798
1799
1800         value = pci_read_config32(ctrl->f3, NORTHBRIDGE_CAP);
1801         min_cycle_time = min_cycle_times[(value >> NBCAP_MEMCLK_SHIFT) & NBCAP_MEMCLK_MASK];
1802         bios_cycle_time = min_cycle_times[
1803                 read_option(CMOS_VSTART_max_mem_clock, CMOS_VLEN_max_mem_clock, 0)];
1804         if (bios_cycle_time > min_cycle_time) {
1805                 min_cycle_time = bios_cycle_time;
1806         }
1807         min_latency = 3;
1808
1809         printk_raminit("1 min_cycle_time: %08x\n", min_cycle_time);
1810
1811         /* Compute the least latency with the fastest clock supported
1812          * by both the memory controller and the dimms.
1813          */
1814         for (i = 0; i < DIMM_SOCKETS; i++) {
1815                 u32 spd_device;
1816
1817                 printk_raminit("1.1 dimm_mask: %08x\n", meminfo->dimm_mask);
1818                 printk_raminit("i: %08x\n",i);
1819
1820                 if (meminfo->dimm_mask & (1 << i)) {
1821                         spd_device = ctrl->channel0[i];
1822                         printk_raminit("Channel 0 settings:\n");
1823
1824                         switch (find_optimum_spd_latency(spd_device, &min_latency, &min_cycle_time)) {
1825                         case -1:
1826                                 goto hw_error;
1827                                 break;
1828                         case 1:
1829                                 continue;
1830                         }
1831                 }
1832                 if (meminfo->dimm_mask & (1 << (DIMM_SOCKETS + i))) {
1833                         spd_device = ctrl->channel1[i];
1834                         printk_raminit("Channel 1 settings:\n");
1835
1836                         switch (find_optimum_spd_latency(spd_device, &min_latency, &min_cycle_time)) {
1837                         case -1:
1838                                 goto hw_error;
1839                                 break;
1840                         case 1:
1841                                 continue;
1842                         }
1843                 }
1844                 
1845         }
1846         /* Make a second pass through the dimms and disable
1847          * any that cannot support the selected memclk and cas latency.
1848          */
1849
1850         printk_raminit("3 min_cycle_time: %08x\n", min_cycle_time);
1851         printk_raminit("3 min_latency: %08x\n", min_latency);
1852
1853         for (i = 0; (i < DIMM_SOCKETS); i++) {
1854                 int latencies;
1855                 int latency;
1856                 int index;
1857                 int val;
1858                 u32 spd_device = ctrl->channel0[i];
1859
1860                 if (!(meminfo->dimm_mask & (1 << i))) {
1861                         if (meminfo->dimm_mask & (1 << (DIMM_SOCKETS + i))) { /* channelB only? */
1862                                 spd_device = ctrl->channel1[i];
1863                         } else {
1864                                 continue;
1865                         }
1866                 }
1867
1868                 latencies = spd_read_byte(spd_device, SPD_CAS_LAT);
1869                 if (latencies < 0) goto hw_error;
1870                 if (latencies == 0) {
1871                         continue;
1872                 }
1873
1874                 /* Compute the lowest cas latency supported */
1875                 latency = log2(latencies) -2;
1876
1877                 /* Walk through searching for the selected latency */
1878                 for (index = 0; index < 3; index++, latency++) {
1879                         if (!(latencies & (1 << latency))) {
1880                                 continue;
1881                         }
1882                         if (latency == min_latency)
1883                                 break;
1884                 }
1885                 /* If I can't find the latency or my index is bad error */
1886                 if ((latency != min_latency) || (index >= 3)) {
1887                         goto dimm_err;
1888                 }
1889
1890                 /* Read the min_cycle_time for this latency */
1891                 val = spd_read_byte(spd_device, latency_indicies[index]);
1892                 if (val < 0) goto hw_error;
1893
1894                 val = convert_to_linear(val);
1895                 /* All is good if the selected clock speed
1896                  * is what I need or slower.
1897                  */
1898                 if (val <= min_cycle_time) {
1899                         continue;
1900                 }
1901                 /* Otherwise I have an error, disable the dimm */
1902         dimm_err:
1903                 meminfo->dimm_mask = disable_dimm(ctrl, i, meminfo);
1904         }
1905
1906         printk_raminit("4 min_cycle_time: %08x\n", min_cycle_time);
1907
1908         /* Now that I know the minimum cycle time lookup the memory parameters */
1909         result.param = get_mem_param(min_cycle_time);
1910
1911         /* Update DRAM Config High with our selected memory speed */
1912         value = pci_read_config32(ctrl->f2, DRAM_CONFIG_HIGH);
1913         value &= ~(DCH_MemClkFreq_MASK << DCH_MemClkFreq_SHIFT);
1914
1915         value |= result.param->dch_memclk << DCH_MemClkFreq_SHIFT;
1916         pci_write_config32(ctrl->f2, DRAM_CONFIG_HIGH, value);
1917
1918         printk(BIOS_DEBUG, "%s\n", result.param->name);
1919
1920         /* Update DRAM Timing Low with our selected cas latency */
1921         value = pci_read_config32(ctrl->f2, DRAM_TIMING_LOW);
1922         value &= ~(DTL_TCL_MASK << DTL_TCL_SHIFT);
1923         value |= (min_latency - DTL_TCL_BASE)  << DTL_TCL_SHIFT;
1924         pci_write_config32(ctrl->f2, DRAM_TIMING_LOW, value);
1925
1926         result.dimm_mask = meminfo->dimm_mask;
1927         return result;
1928  hw_error:
1929         result.param = (const struct mem_param *)0;
1930         result.dimm_mask = -1;
1931         return result;
1932 }
1933
1934 static unsigned convert_to_1_4(unsigned value)
1935 {
1936         static const uint8_t fraction[] = { 0, 1, 2, 2, 3, 3, 0 };
1937         unsigned valuex;
1938
1939         /* We need to convert value to more readable */
1940         valuex =  fraction [value & 0x7];
1941         return valuex;
1942 }
1943
1944 static int get_dimm_Trc_clocks(u32 spd_device, const struct mem_param *param)
1945 {
1946         int value;
1947         int value2;
1948         int clocks;
1949         value = spd_read_byte(spd_device, SPD_TRC);
1950         if (value < 0)
1951                 return -1;
1952         printk_raminit("update_dimm_Trc: tRC (41) = %08x\n", value);
1953
1954         value2 = spd_read_byte(spd_device, SPD_TRC -1);
1955         value <<= 2;
1956         value += convert_to_1_4(value2>>4);
1957
1958         value *= 10;
1959         printk_raminit("update_dimm_Trc: tRC final value = %i\n", value);
1960
1961         clocks = (value + param->divisor - 1)/param->divisor;
1962         printk_raminit("update_dimm_Trc: clocks = %i\n", clocks);
1963
1964         if (clocks < DTL_TRC_MIN) {
1965 #warning We should die here or at least disable this bank.
1966                 printk(BIOS_NOTICE, "update_dimm_Trc: can't refresh fast enough, "
1967                         "want %i clocks, can %i clocks\n", clocks, DTL_TRC_MIN);
1968                 clocks = DTL_TRC_MIN;
1969         }
1970         return clocks;
1971 }
1972
1973 static int update_dimm_Trc(const struct mem_controller *ctrl,
1974                             const struct mem_param *param,
1975                             int i, long dimm_mask)
1976 {
1977         int clocks, old_clocks;
1978         uint32_t dtl;
1979         u32 spd_device = ctrl->channel0[i];
1980
1981         if (!(dimm_mask & (1 << i)) && (dimm_mask & (1 << (DIMM_SOCKETS + i)))) { /* channelB only? */
1982                 spd_device = ctrl->channel1[i];
1983         }
1984
1985         clocks = get_dimm_Trc_clocks(spd_device, param);
1986         if (clocks == -1)
1987                 return clocks;
1988         if (clocks > DTL_TRC_MAX) {
1989                 return 0;
1990         }
1991         printk_raminit("update_dimm_Trc: clocks after adjustment = %i\n", clocks);
1992
1993         dtl = pci_read_config32(ctrl->f2, DRAM_TIMING_LOW);
1994         old_clocks = ((dtl >> DTL_TRC_SHIFT) & DTL_TRC_MASK) + DTL_TRC_BASE;
1995         if (old_clocks >= clocks) {  //?? someone did it
1996                 // clocks = old_clocks;
1997                 return 1;
1998         }
1999         dtl &= ~(DTL_TRC_MASK << DTL_TRC_SHIFT);
2000         dtl |=  ((clocks - DTL_TRC_BASE) << DTL_TRC_SHIFT);
2001         pci_write_config32(ctrl->f2, DRAM_TIMING_LOW, dtl);
2002         return 1;
2003 }
2004
2005 static int update_dimm_Trfc(const struct mem_controller *ctrl, const struct mem_param *param, int i, struct mem_info *meminfo)
2006 {
2007         unsigned clocks, old_clocks;
2008         uint32_t dth;
2009         int value;
2010         u8 ch_b = 0;
2011         u32 spd_device = ctrl->channel0[i];
2012
2013         if (!(meminfo->dimm_mask & (1 << i)) && (meminfo->dimm_mask & (1 << (DIMM_SOCKETS + i)))) { /* channelB only? */
2014                 spd_device = ctrl->channel1[i];
2015                 ch_b = 2; /* offset to channelB trfc setting */
2016         }
2017
2018         //get the cs_size --> logic dimm size
2019         value = spd_read_byte(spd_device, SPD_PRI_WIDTH);
2020         if (value < 0) {
2021                 return -1;
2022         }
2023
2024         value = 6 - log2(value); //4-->4, 8-->3, 16-->2
2025
2026         clocks = meminfo->sz[i].per_rank - 27 + 2 - value;
2027
2028         dth = pci_read_config32(ctrl->f2, DRAM_TIMING_HIGH);
2029
2030         old_clocks = ((dth >> (DTH_TRFC0_SHIFT + ((i + ch_b) * 3))) & DTH_TRFC_MASK);
2031
2032         if (old_clocks >= clocks) { // some one did it?
2033                 return 1;
2034         }
2035         dth &= ~(DTH_TRFC_MASK << (DTH_TRFC0_SHIFT + ((i + ch_b) * 3)));
2036         dth |= clocks  << (DTH_TRFC0_SHIFT + ((i + ch_b) * 3));
2037         pci_write_config32(ctrl->f2, DRAM_TIMING_HIGH, dth);
2038         return 1;
2039 }
2040
2041 static int update_dimm_TT_1_4(const struct mem_controller *ctrl, const struct mem_param *param, int i, long dimm_mask,
2042                                         unsigned TT_REG,
2043                                         unsigned SPD_TT, unsigned TT_SHIFT, unsigned TT_MASK, unsigned TT_BASE, unsigned TT_MIN, unsigned TT_MAX )
2044 {
2045         unsigned clocks, old_clocks;
2046         uint32_t dtl;
2047         int value;
2048         u32 spd_device = ctrl->channel0[i];
2049
2050         if (!(dimm_mask & (1 << i)) && (dimm_mask & (1 << (DIMM_SOCKETS + i)))) { /* channelB only? */
2051                 spd_device = ctrl->channel1[i];
2052         }
2053
2054         value = spd_read_byte(spd_device, SPD_TT); //already in 1/4 ns
2055         if (value < 0) return -1;
2056         value *=10;
2057         clocks = (value + param->divisor -1)/param->divisor;
2058         if (clocks < TT_MIN) {
2059                 clocks = TT_MIN;
2060         }
2061         
2062         if (clocks > TT_MAX) {
2063                 printk(BIOS_INFO, "warning spd byte : %x = %x > TT_MAX: %x, setting TT_MAX", SPD_TT, value, TT_MAX);
2064                 clocks = TT_MAX;
2065         }
2066
2067         dtl = pci_read_config32(ctrl->f2, TT_REG);
2068
2069         old_clocks = ((dtl >> TT_SHIFT) & TT_MASK) + TT_BASE;
2070         if (old_clocks >= clocks) { //some one did it?
2071 //              clocks = old_clocks;
2072                 return 1;
2073         }
2074         dtl &= ~(TT_MASK << TT_SHIFT);
2075         dtl |= ((clocks - TT_BASE) << TT_SHIFT);
2076         pci_write_config32(ctrl->f2, TT_REG, dtl);
2077         return 1;
2078 }
2079
2080 static int update_dimm_Trcd(const struct mem_controller *ctrl,
2081                              const struct mem_param *param, int i, long dimm_mask)
2082 {
2083         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);
2084 }
2085
2086 static int update_dimm_Trrd(const struct mem_controller *ctrl, const struct mem_param *param, int i, long dimm_mask)
2087 {
2088         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);
2089 }
2090
2091 static int update_dimm_Tras(const struct mem_controller *ctrl, const struct mem_param *param, int i, long dimm_mask)
2092 {
2093         unsigned clocks, old_clocks;
2094         uint32_t dtl;
2095         int value;
2096         u32 spd_device = ctrl->channel0[i];
2097
2098         if (!(dimm_mask & (1 << i)) && (dimm_mask & (1 << (DIMM_SOCKETS + i)))) { /* channelB only? */
2099                 spd_device = ctrl->channel1[i];
2100         }
2101
2102         value = spd_read_byte(spd_device, SPD_TRAS); //in 1 ns
2103         if (value < 0) return -1;
2104         printk_raminit("update_dimm_Tras: 0 value= %08x\n", value);
2105
2106         value <<= 2; //convert it to in 1/4ns
2107
2108         value *= 10;
2109         printk_raminit("update_dimm_Tras:  1 value= %08x\n", value);
2110
2111         clocks = (value  + param->divisor - 1)/param->divisor;
2112         printk_raminit("update_dimm_Tras: divisor= %08x\n", param->divisor);
2113         printk_raminit("update_dimm_Tras: clocks= %08x\n", clocks);
2114         if (clocks < DTL_TRAS_MIN) {
2115                 clocks = DTL_TRAS_MIN;
2116         }
2117         if (clocks > DTL_TRAS_MAX) {
2118                 return 0;
2119         }
2120         dtl = pci_read_config32(ctrl->f2, DRAM_TIMING_LOW);
2121         old_clocks = ((dtl >> DTL_TRAS_SHIFT) & DTL_TRAS_MASK) + DTL_TRAS_BASE;
2122         if (old_clocks >= clocks) { // someone did it?
2123                 return 1;
2124         }
2125         dtl &= ~(DTL_TRAS_MASK << DTL_TRAS_SHIFT);
2126         dtl |= ((clocks - DTL_TRAS_BASE) << DTL_TRAS_SHIFT);
2127         pci_write_config32(ctrl->f2, DRAM_TIMING_LOW, dtl);
2128         return 1;
2129 }
2130
2131 static int update_dimm_Trp(const struct mem_controller *ctrl,
2132                             const struct mem_param *param, int i, long dimm_mask)
2133 {
2134         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);
2135 }
2136
2137
2138 static int update_dimm_Trtp(const struct mem_controller *ctrl,
2139                 const struct mem_param *param, int i, struct mem_info *meminfo)
2140 {
2141         /* need to figure if it is 32 byte burst or 64 bytes burst */
2142         int offset = 2;
2143         if (!meminfo->is_Width128) {
2144                 uint32_t dword;
2145                 dword = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
2146                 if ((dword &  DCL_BurstLength32)) offset = 0;
2147         }
2148         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);
2149 }
2150
2151
2152 static int update_dimm_Twr(const struct mem_controller *ctrl, const struct mem_param *param, int i, long dimm_mask)
2153 {
2154         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);
2155 }
2156
2157
2158 static int update_dimm_Tref(const struct mem_controller *ctrl,
2159                              const struct mem_param *param, int i, long dimm_mask)
2160 {
2161         uint32_t dth, dth_old;
2162         int value;
2163         u32 spd_device = ctrl->channel0[i];
2164
2165         if (!(dimm_mask & (1 << i)) && (dimm_mask & (1 << (DIMM_SOCKETS + i)))) { /* channelB only? */
2166                 spd_device = ctrl->channel1[i];
2167         }
2168
2169         value = spd_read_byte(spd_device, SPD_TREF); // 0: 15.625us, 1: 3.9us 2: 7.8 us....
2170         if (value < 0) return -1;
2171
2172         if (value == 1 ) {
2173                 value = 3;
2174         } else {
2175                 value = 2;
2176         }
2177
2178         dth = pci_read_config32(ctrl->f2, DRAM_TIMING_HIGH);
2179
2180         dth_old = dth;
2181         dth &= ~(DTH_TREF_MASK << DTH_TREF_SHIFT);
2182         dth |= (value << DTH_TREF_SHIFT);
2183         if (dth_old != dth) {
2184                 pci_write_config32(ctrl->f2, DRAM_TIMING_HIGH, dth);
2185         }
2186         return 1;
2187 }
2188
2189 static void set_4RankRDimm(const struct mem_controller *ctrl,
2190                         const struct mem_param *param, struct mem_info *meminfo)
2191 {
2192 #if QRANK_DIMM_SUPPORT == 1
2193         int value;
2194         int i;
2195         long dimm_mask = meminfo->dimm_mask;
2196
2197
2198         if (!(meminfo->is_registered)) return;
2199
2200         value = 0;
2201
2202         for (i = 0; i < DIMM_SOCKETS; i++) {
2203                 if (!(dimm_mask & (1 << i))) {
2204                         continue;
2205                 }
2206
2207                 if (meminfo->sz[i].rank == 4) {
2208                         value = 1;
2209                         break;
2210                 }
2211         }
2212
2213         if (value == 1) {
2214                 uint32_t dch;
2215                 dch = pci_read_config32(ctrl->f2, DRAM_CONFIG_HIGH);
2216                 dch |= DCH_FourRankRDimm;
2217                 pci_write_config32(ctrl->f2, DRAM_CONFIG_HIGH, dch);
2218         }
2219 #endif
2220 }
2221
2222 static uint32_t get_extra_dimm_mask(const struct mem_controller *ctrl,
2223                                      struct mem_info *meminfo)
2224 {
2225         int i;
2226
2227         uint32_t mask_x4;
2228         uint32_t mask_x16;
2229         uint32_t mask_single_rank;
2230         uint32_t mask_page_1k;
2231         int value;
2232 #if QRANK_DIMM_SUPPORT == 1
2233         int rank;
2234 #endif
2235
2236         long dimm_mask = meminfo->dimm_mask;
2237
2238
2239         mask_x4 = 0;
2240         mask_x16 = 0;
2241         mask_single_rank = 0;
2242         mask_page_1k = 0;
2243
2244         for (i = 0; i < DIMM_SOCKETS; i++) {
2245                 u32 spd_device = ctrl->channel0[i];
2246                 if (!(dimm_mask & (1 << i))) {
2247                         if (dimm_mask & (1 << (DIMM_SOCKETS + i))) { /* channelB only? */
2248                                 spd_device = ctrl->channel1[i];
2249                         } else {
2250                                 continue;
2251                         }
2252                 }
2253
2254                 if (meminfo->sz[i].rank == 1) {
2255                         mask_single_rank |= 1<<i;
2256                 }
2257
2258                 if (meminfo->sz[i].col==10) {
2259                         mask_page_1k |= 1<<i;
2260                 }
2261
2262
2263                 value = spd_read_byte(spd_device, SPD_PRI_WIDTH);
2264
2265                 #if QRANK_DIMM_SUPPORT == 1
2266                         rank = meminfo->sz[i].rank;
2267                 #endif
2268
2269                 if (value==4) {
2270                         mask_x4 |= (1<<i);
2271                         #if QRANK_DIMM_SUPPORT == 1
2272                         if (rank==4) {
2273                                 mask_x4 |= 1<<(i+2);
2274                         }
2275                         #endif
2276                 } else if (value==16) {
2277                         mask_x16 |= (1<<i);
2278                         #if QRANK_DIMM_SUPPORT == 1
2279                          if (rank==4) {
2280                                  mask_x16 |= 1<<(i+2);
2281                          }
2282                         #endif
2283                 }
2284
2285         }
2286
2287         meminfo->x4_mask= mask_x4;
2288         meminfo->x16_mask = mask_x16;
2289
2290         meminfo->single_rank_mask = mask_single_rank;
2291         meminfo->page_1k_mask = mask_page_1k;
2292
2293         return mask_x4;
2294
2295 }
2296
2297
2298 static void set_dimm_x4(const struct mem_controller *ctrl, const struct mem_param *param, struct mem_info *meminfo)
2299 {
2300         uint32_t dcl;
2301         dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
2302         dcl &= ~(DCL_X4Dimm_MASK<<DCL_X4Dimm_SHIFT);
2303         dcl |= ((meminfo->x4_mask) & 0xf) << (DCL_X4Dimm_SHIFT);
2304         pci_write_config32(ctrl->f2, DRAM_CONFIG_LOW, dcl);
2305 }
2306
2307
2308 static int count_ones(uint32_t dimm_mask)
2309 {
2310         int dimms;
2311         unsigned index;
2312         dimms = 0;
2313         for (index = 0; index < (2 * DIMM_SOCKETS); index++, dimm_mask >>= 1) {
2314                 if (dimm_mask & 1) {
2315                         dimms++;
2316                 }
2317         }
2318         return dimms;
2319 }
2320
2321
2322 static void set_DramTerm(const struct mem_controller *ctrl,
2323                         const struct mem_param *param, struct mem_info *meminfo)
2324 {
2325         uint32_t dcl;
2326         unsigned odt;
2327         odt = 1; // 75 ohms
2328
2329         if (param->divisor == 100) { //DDR2 800
2330                 if (meminfo->is_Width128) {
2331                         if (count_ones(meminfo->dimm_mask & 0x0f)==2) {
2332                                 odt = 3;  //50 ohms
2333                         }
2334                 }
2335
2336         }
2337
2338
2339 #if CONFIG_DIMM_SUPPORT == 0x0204
2340         odt = 0x2;              /* 150 ohms */
2341 #endif
2342
2343         dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
2344         dcl &= ~(DCL_DramTerm_MASK<<DCL_DramTerm_SHIFT);
2345         dcl |= (odt & DCL_DramTerm_MASK) << (DCL_DramTerm_SHIFT);
2346         pci_write_config32(ctrl->f2, DRAM_CONFIG_LOW, dcl);
2347 }
2348
2349 static void set_ecc(const struct mem_controller *ctrl,
2350         const struct mem_param *param, struct mem_info *meminfo)
2351 {
2352         int i;
2353         int value;
2354
2355         uint32_t dcl, nbcap;
2356         nbcap = pci_read_config32(ctrl->f3, NORTHBRIDGE_CAP);
2357         dcl = pci_read_config32(ctrl->f2, DRAM_CONFIG_LOW);
2358         dcl &= ~DCL_DimmEccEn;
2359         if (nbcap & NBCAP_ECC) {
2360                 dcl |= DCL_DimmEccEn;
2361         }
2362         if (read_option(CMOS_VSTART_ECC_memory, CMOS_VLEN_ECC_memory, 1) == 0) {
2363                 dcl &= ~DCL_DimmEccEn;
2364         }
2365         pci_write_config32(ctrl->f2, DRAM_CONFIG_LOW, dcl);
2366
2367         meminfo->is_ecc = 1;
2368         if (!(dcl & DCL_DimmEccEn)) {
2369                 meminfo->is_ecc = 0;
2370                 return; // already disabled the ECC, so don't need to read SPD any more
2371         }
2372
2373         for (i = 0; i < DIMM_SOCKETS; i++) {
2374                 u32 spd_device = ctrl->channel0[i];
2375                 if (!(meminfo->dimm_mask & (1 << i))) {
2376                         if (meminfo->dimm_mask & (1 << (DIMM_SOCKETS + i))) { /* channelB only? */
2377                                 spd_device = ctrl->channel1[i];
2378                                 printk(BIOS_DEBUG, "set_ecc spd_device: 0x%x\n", spd_device);
2379                         } else {
2380                                 continue;
2381                         }
2382                 }
2383
2384                 value = spd_read_byte(ctrl->channel0[i], SPD_DIMM_CONF_TYPE);
2385
2386                 if (!(value & SPD_DIMM_CONF_TYPE_ECC)) {
2387                         dcl &= ~DCL_DimmEccEn;
2388                         pci_write_config32(ctrl->f2, DRAM_CONFIG_LOW, dcl);
2389                         meminfo->is_ecc = 0;
2390                         return;
2391                 }
2392
2393         }
2394 }
2395
2396
2397 static int update_dimm_Twtr(const struct mem_controller *ctrl,
2398                              const struct mem_param *param, int i, long dimm_mask)
2399 {
2400         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);
2401 }
2402
2403 static void set_TT(const struct mem_controller *ctrl,
2404         const struct mem_param *param, unsigned TT_REG, unsigned TT_SHIFT,
2405         unsigned TT_MASK, unsigned TT_BASE, unsigned TT_MIN, unsigned TT_MAX,
2406         unsigned val, const char *str)
2407 {
2408         uint32_t reg;
2409
2410         if ((val < TT_MIN) || (val > TT_MAX)) {
2411                 printk(BIOS_ERR, str);
2412                 die(" Unknown\n");
2413         }
2414
2415         reg = pci_read_config32(ctrl->f2, TT_REG);
2416         reg &= ~(TT_MASK << TT_SHIFT);
2417         reg |= ((val - TT_BASE) << TT_SHIFT);
2418         pci_write_config32(ctrl->f2, TT_REG, reg);
2419         return;
2420 }
2421
2422
2423 static void set_TrwtTO(const struct mem_controller *ctrl,
2424                         const struct mem_param *param)
2425 {
2426         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");
2427 }
2428
2429
2430 static void set_Twrrd(const struct mem_controller *ctrl, const struct mem_param *param)
2431 {
2432         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");
2433 }
2434
2435
2436 static void set_Twrwr(const struct mem_controller *ctrl, const struct mem_param *param)
2437 {
2438         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");
2439 }
2440
2441 static void set_Trdrd(const struct mem_controller *ctrl, const struct mem_param *param)
2442 {
2443         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");
2444 }
2445
2446 static void set_DcqBypassMax(const struct mem_controller *ctrl, const struct mem_param *param)
2447 {
2448         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
2449 }
2450
2451 static void set_Tfaw(const struct mem_controller *ctrl, const struct mem_param *param, struct mem_info *meminfo)
2452 {
2453         static const uint8_t faw_1k[] = {8, 10, 13, 14};
2454         static const uint8_t faw_2k[] = {10, 14, 17, 18};
2455         unsigned memclkfreq_index;
2456         unsigned faw;
2457
2458
2459         memclkfreq_index = param->dch_memclk;
2460
2461         if (meminfo->page_1k_mask != 0) { //1k page
2462                 faw = faw_1k[memclkfreq_index];
2463         } else {
2464                 faw = faw_2k[memclkfreq_index];
2465         }
2466
2467         set_TT(ctrl, param, DRAM_CONFIG_HIGH, DCH_FourActWindow_SHIFT, DCH_FourActWindow_MASK, DCH_FourActWindow_BASE, DCH_FourActWindow_MIN, DCH_FourActWindow_MAX, faw, "FourActWindow");
2468 }
2469
2470 static void set_max_async_latency(const struct mem_controller *ctrl, const struct mem_param *param)
2471 {
2472         uint32_t dch;
2473         unsigned async_lat;
2474
2475
2476         dch = pci_read_config32(ctrl->f2, DRAM_CONFIG_HIGH);
2477         dch &= ~(DCH_MaxAsyncLat_MASK << DCH_MaxAsyncLat_SHIFT);
2478
2479         //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
2480         async_lat = 6 + 6;
2481
2482
2483         dch |= ((async_lat - DCH_MaxAsyncLat_BASE) << DCH_MaxAsyncLat_SHIFT);
2484         pci_write_config32(ctrl->f2, DRAM_CONFIG_HIGH, dch);
2485 }
2486
2487 #if (CONFIG_DIMM_SUPPORT & 0x0100)==0x0000 /* 2T mode only used for unbuffered DIMM */
2488 static void set_SlowAccessMode(const struct mem_controller *ctrl)
2489 {
2490         uint32_t dch;
2491
2492         dch = pci_read_config32(ctrl->f2, DRAM_CONFIG_HIGH);
2493
2494         dch |= (1<<20);
2495
2496         pci_write_config32(ctrl->f2, DRAM_CONFIG_HIGH, dch);
2497 }
2498 #endif
2499
2500 /*
2501         DRAM_OUTPUT_DRV_COMP_CTRL 0, 0x20
2502         DRAM_ADDR_TIMING_CTRL 04, 0x24
2503 */
2504 static void set_misc_timing(const struct mem_controller *ctrl, struct mem_info *meminfo)
2505 {
2506         uint32_t dword;
2507         uint32_t dwordx;
2508 #if (CONFIG_DIMM_SUPPORT & 0x0100)==0x0000 /* 2T mode only used for unbuffered DIMM */
2509         unsigned SlowAccessMode = 0;
2510 #endif
2511
2512         long dimm_mask = meminfo->dimm_mask & 0x0f;
2513
2514 #if CONFIG_DIMM_SUPPORT==0x0104   /* DDR2 and REG */
2515         /* for REG DIMM */
2516         dword = 0x00111222;
2517         dwordx = 0x002f0000;
2518         switch (meminfo->memclk_set) {
2519         case DCH_MemClkFreq_266MHz:
2520                 if ( (dimm_mask == 0x03) || (dimm_mask == 0x02) || (dimm_mask == 0x01)) {
2521                         dwordx = 0x002f2700;
2522                 }
2523                 break;
2524         case DCH_MemClkFreq_333MHz:
2525                 if ( (dimm_mask == 0x03) || (dimm_mask == 0x02) || (dimm_mask == 0x01)) {
2526                         if ((meminfo->single_rank_mask & 0x03)!=0x03) { //any double rank there?
2527                                 dwordx = 0x002f2f00;
2528                         }
2529                 }
2530                 break;
2531         case DCH_MemClkFreq_400MHz:
2532                 dwordx = 0x002f3300;
2533                 break;
2534         }
2535
2536 #endif
2537
2538 #if CONFIG_DIMM_SUPPORT==0x0204 /* DDR2 and SO-DIMM, S1G1 */
2539         dword = 0x00111222;
2540         dwordx = 0x002F2F00;
2541
2542         switch (meminfo->memclk_set) {
2543         case DCH_MemClkFreq_200MHz:     /* nothing to be set here */
2544                 break;
2545         case DCH_MemClkFreq_266MHz:
2546                 if ((meminfo->single_rank_mask == 0)
2547                     && (meminfo->x4_mask == 0) && (meminfo->x16_mask))
2548                         dwordx = 0x002C2C00;    /* Double rank x8 */
2549                 /* else SRx16, SRx8, DRx16 == 0x002F2F00 */
2550                 break;
2551         case DCH_MemClkFreq_333MHz:
2552                 if ((meminfo->single_rank_mask == 1)
2553                    && (meminfo->x16_mask == 1)) /* SR x16 */
2554                         dwordx = 0x00272700;
2555                 else if ((meminfo->x4_mask == 0) && (meminfo->x16_mask == 0)
2556                          && (meminfo->single_rank_mask == 0)) { /* DR x8 */
2557                         SlowAccessMode = 1;
2558                         dwordx = 0x00002800;
2559                 } else {        /* SR x8, DR x16 */
2560                         dwordx = 0x002A2A00;
2561                 }
2562                 break;
2563         case DCH_MemClkFreq_400MHz:
2564                 if ((meminfo->single_rank_mask == 1)
2565                    && (meminfo->x16_mask == 1)) /* SR x16 */
2566                         dwordx = 0x00292900;
2567                 else if ((meminfo->x4_mask == 0) && (meminfo->x16_mask == 0)
2568                          && (meminfo->single_rank_mask == 0)) { /* DR x8 */
2569                         SlowAccessMode = 1;
2570                         dwordx = 0x00002A00;
2571                 } else {        /* SR x8, DR x16 */
2572                         dwordx = 0x002A2A00;
2573                 }
2574                 break;
2575         }
2576 #endif
2577
2578 #if CONFIG_DIMM_SUPPORT==0x0004  /* DDR2 and unbuffered */
2579         /* for UNBUF DIMM */
2580         dword = 0x00111222;
2581         dwordx = 0x002f2f00;
2582         switch (meminfo->memclk_set) {
2583         case DCH_MemClkFreq_200MHz:
2584                 if (dimm_mask == 0x03) {
2585                         SlowAccessMode = 1;
2586                         dword = 0x00111322;
2587                 }
2588                 break;
2589         case DCH_MemClkFreq_266MHz:
2590                 if (dimm_mask == 0x03) {
2591                         SlowAccessMode = 1;
2592                         dword = 0x00111322;
2593                         if ((meminfo->x4_mask == 0 ) && (meminfo->x16_mask == 0)) {
2594                                 switch (meminfo->single_rank_mask) {
2595                                 case 0x03:
2596                                         dwordx = 0x00002f00; //x8 single Rank
2597                                         break;
2598                                 case 0x00:
2599                                         dwordx = 0x00342f00; //x8 double Rank
2600                                         break;
2601                                 default:
2602                                         dwordx = 0x00372f00; //x8 single Rank and double Rank mixed
2603                                 }
2604                         } else if ((meminfo->x4_mask == 0 ) && (meminfo->x16_mask == 0x01) && (meminfo->single_rank_mask == 0x01)) {
2605                                          dwordx = 0x00382f00; //x8 Double Rank and x16 single Rank mixed
2606                          } else if ((meminfo->x4_mask == 0 ) && (meminfo->x16_mask == 0x02) && (meminfo->single_rank_mask == 0x02)) {
2607                                          dwordx = 0x00382f00; //x16 single Rank and x8 double Rank mixed
2608                         }
2609
2610                 } else {
2611                         if ((meminfo->x4_mask == 0 ) && (meminfo->x16_mask == 0x00) && ((meminfo->single_rank_mask == 0x01)||(meminfo->single_rank_mask == 0x02)))  { //x8 single rank
2612                                 dwordx = 0x002f2f00;
2613                         } else {
2614                                 dwordx = 0x002b2f00;
2615                         }
2616                 }
2617                 break;
2618         case DCH_MemClkFreq_333MHz:
2619                 dwordx = 0x00202220;
2620                 if (dimm_mask == 0x03) {
2621                         SlowAccessMode = 1;
2622                         dword = 0x00111322;
2623                         if ((meminfo->x4_mask == 0 ) && (meminfo->x16_mask == 0)) {
2624                                 switch (meminfo->single_rank_mask) {
2625                                 case 0x03:
2626                                         dwordx = 0x00302220; //x8 single Rank
2627                                         break;
2628                                 case 0x00:
2629                                         dwordx = 0x002b2220; //x8 double Rank
2630                                         break;
2631                                 default:
2632                                         dwordx = 0x002a2220; //x8 single Rank and double Rank mixed
2633                                 }
2634                         } else if ((meminfo->x4_mask == 0) && (meminfo->x16_mask == 0x01) && (meminfo->single_rank_mask == 0x01)) {
2635                                         dwordx = 0x002c2220; //x8 Double Rank and x16 single Rank mixed
2636                         } else if ((meminfo->x4_mask == 0) && (meminfo->x16_mask == 0x02) && (meminfo->single_rank_mask == 0x02)) {
2637                                         dwordx = 0x002c2220; //x16 single Rank and x8 double Rank mixed
2638                         }
2639                 }
2640                 break;
2641         case DCH_MemClkFreq_400MHz:
2642                 dwordx = 0x00202520;
2643                 SlowAccessMode = 1;
2644                 if (dimm_mask == 0x03) {
2645                         dword = 0x00113322;
2646                 } else {
2647                         dword = 0x00113222;
2648                 }
2649                 break;
2650         }
2651
2652         printk_raminit("\tdimm_mask = %08x\n", meminfo->dimm_mask);
2653         printk_raminit("\tx4_mask = %08x\n", meminfo->x4_mask);
2654         printk_raminit("\tx16_mask = %08x\n", meminfo->x16_mask);
2655         printk_raminit("\tsingle_rank_mask = %08x\n", meminfo->single_rank_mask);
2656         printk_raminit("\tODC = %08x\n", dword);
2657         printk_raminit("\tAddr Timing= %08x\n", dwordx);
2658 #endif
2659
2660 #if (CONFIG_DIMM_SUPPORT & 0x0100)==0x0000 /* 2T mode only used for unbuffered DIMM */
2661         if (SlowAccessMode) {
2662                 set_SlowAccessMode(ctrl);
2663         }
2664 #endif
2665
2666         if (!(meminfo->dimm_mask & 0x0F) && (meminfo->dimm_mask & 0xF0)) { /* channelB only? */
2667                 /* Program the Output Driver Compensation Control Registers (Function 2:Offset 0x9c, index 0, 0x20) */
2668                 pci_write_config32_index_wait(ctrl->f2, 0x98, 0x20, dword);
2669
2670                 /* Program the Address Timing Control Registers (Function 2:Offset 0x9c, index 4, 0x24) */
2671                 pci_write_config32_index_wait(ctrl->f2, 0x98, 0x24, dwordx);
2672         } else {
2673                 /* Program the Output Driver Compensation Control Registers (Function 2:Offset 0x9c, index 0, 0x20) */
2674                 pci_write_config32_index_wait(ctrl->f2, 0x98, 0, dword);
2675                 if (meminfo->is_Width128) {
2676                         pci_write_config32_index_wait(ctrl->f2, 0x98, 0x20, dword);
2677                 }
2678
2679                 /* Program the Address Timing Control Registers (Function 2:Offset 0x9c, index 4, 0x24) */
2680                 pci_write_config32_index_wait(ctrl->f2, 0x98, 4, dwordx);
2681                 if (meminfo->is_Width128) {
2682                         pci_write_config32_index_wait(ctrl->f2, 0x98, 0x24, dwordx);
2683                 }
2684         }
2685 }
2686
2687
2688 static void set_RDqsEn(const struct mem_controller *ctrl,
2689                         const struct mem_param *param, struct mem_info *meminfo)
2690 {
2691 #if CONFIG_CPU_SOCKET_TYPE==0x10
2692         //only need to set for reg and x8
2693         uint32_t dch;
2694
2695         dch = pci_read_config32(ctrl->f2, DRAM_CONFIG_HIGH);
2696
2697         dch &= ~DCH_RDqsEn;
2698         if ((!meminfo->x4_mask) && (!meminfo->x16_mask)) {
2699                 dch |= DCH_RDqsEn;
2700         }
2701
2702         pci_write_config32(ctrl->f2, DRAM_CONFIG_HIGH, dch);
2703 #endif
2704 }
2705
2706 static void set_idle_cycle_limit(const struct mem_controller *ctrl,
2707                                   const struct mem_param *param)
2708 {
2709         uint32_t dcm;
2710         /* AMD says to Hardcode this */
2711         dcm = pci_read_config32(ctrl->f2, DRAM_CTRL_MISC);
2712         dcm &= ~(DCM_ILD_lmt_MASK << DCM_ILD_lmt_SHIFT);
2713         dcm |= DCM_ILD_lmt_16 << DCM_ILD_lmt_SHIFT;
2714         dcm |= DCM_DCC_EN;
2715         pci_write_config32(ctrl->f2, DRAM_CTRL_MISC, dcm);
2716 }
2717
2718 static void set_RdWrQByp(const struct mem_controller *ctrl,
2719                           const struct mem_param *param)
2720 {
2721         set_TT(ctrl, param, DRAM_CTRL_MISC, DCM_RdWrQByp_SHIFT, DCM_RdWrQByp_MASK,0, 0, 3, 2, "RdWrQByp");
2722 }
2723
2724 static long spd_set_dram_timing(const struct mem_controller *ctrl,
2725                                  const struct mem_param *param,
2726                                  struct mem_info *meminfo)
2727 {
2728         int i;
2729
2730         for (i = 0; i < DIMM_SOCKETS; i++) {
2731                 int rc;
2732                 if (!(meminfo->dimm_mask & (1 << i)) &&
2733                     !(meminfo->dimm_mask & (1 << (DIMM_SOCKETS + i))) ) {
2734                         continue;
2735                 }
2736                 printk_raminit("spd_set_dram_timing dimm socket:  %08x\n", i);
2737                 /* DRAM Timing Low Register */
2738                 printk_raminit("\ttrc\n");
2739                 if ((rc = update_dimm_Trc (ctrl, param, i, meminfo->dimm_mask)) <= 0) goto dimm_err;
2740
2741                 printk_raminit("\ttrcd\n");
2742                 if ((rc = update_dimm_Trcd(ctrl, param, i, meminfo->dimm_mask)) <= 0) goto dimm_err;
2743
2744                 printk_raminit("\ttrrd\n");
2745                 if ((rc = update_dimm_Trrd(ctrl, param, i, meminfo->dimm_mask)) <= 0) goto dimm_err;
2746
2747                 printk_raminit("\ttras\n");
2748                 if ((rc = update_dimm_Tras(ctrl, param, i, meminfo->dimm_mask)) <= 0) goto dimm_err;
2749
2750                 printk_raminit("\ttrp\n");
2751                 if ((rc = update_dimm_Trp (ctrl, param, i, meminfo->dimm_mask)) <= 0) goto dimm_err;
2752
2753                 printk_raminit("\ttrtp\n");
2754                 if ((rc = update_dimm_Trtp(ctrl, param, i, meminfo)) <= 0) goto dimm_err;
2755
2756                 printk_raminit("\ttwr\n");
2757                 if ((rc = update_dimm_Twr (ctrl, param, i, meminfo->dimm_mask)) <= 0) goto dimm_err;
2758
2759                 /* DRAM Timing High Register */
2760                 printk_raminit("\ttref\n");
2761                 if ((rc = update_dimm_Tref(ctrl, param, i, meminfo->dimm_mask)) <= 0) goto dimm_err;
2762
2763                 printk_raminit("\ttwtr\n");
2764                 if ((rc = update_dimm_Twtr(ctrl, param, i, meminfo->dimm_mask)) <= 0) goto dimm_err;
2765
2766                 printk_raminit("\ttrfc\n");
2767                 if ((rc = update_dimm_Trfc(ctrl, param, i, meminfo)) <= 0) goto dimm_err;
2768
2769                 /* DRAM Config Low */
2770
2771                 continue;
2772         dimm_err:
2773                 printk(BIOS_DEBUG, "spd_set_dram_timing dimm_err!\n");
2774                 if (rc < 0) {
2775                         return -1;
2776                 }
2777                 meminfo->dimm_mask = disable_dimm(ctrl, i, meminfo);
2778         }
2779
2780         get_extra_dimm_mask(ctrl, meminfo); // will be used by RDqsEn and dimm_x4
2781         /* DRAM Timing Low Register */
2782
2783         /* DRAM Timing High Register */
2784         set_TrwtTO(ctrl, param);
2785         set_Twrrd (ctrl, param);
2786         set_Twrwr (ctrl, param);
2787         set_Trdrd (ctrl, param);
2788
2789         set_4RankRDimm(ctrl, param, meminfo);
2790
2791         /* DRAM Config High */
2792         set_Tfaw(ctrl, param, meminfo);
2793         set_DcqBypassMax(ctrl, param);
2794         set_max_async_latency(ctrl, param);
2795         set_RDqsEn(ctrl, param, meminfo);
2796
2797         /* DRAM Config Low */
2798         set_ecc(ctrl, param, meminfo);
2799         set_dimm_x4(ctrl, param, meminfo);
2800         set_DramTerm(ctrl, param, meminfo);
2801
2802         /* DRAM Control Misc */
2803         set_idle_cycle_limit(ctrl, param);
2804         set_RdWrQByp(ctrl, param);
2805
2806         return meminfo->dimm_mask;
2807 }
2808
2809 static void sdram_set_spd_registers(const struct mem_controller *ctrl,
2810                                      struct sys_info *sysinfo)
2811 {
2812         struct spd_set_memclk_result result;
2813         const struct mem_param *param;
2814         struct mem_param paramx;
2815         struct mem_info *meminfo;
2816 #if 1
2817         if (!sysinfo->ctrl_present[ctrl->node_id]) {
2818                 return;
2819         }
2820 #endif
2821         meminfo = &sysinfo->meminfo[ctrl->node_id];
2822
2823         printk(BIOS_DEBUG, "sdram_set_spd_registers: paramx :%p\n", &paramx);
2824
2825         activate_spd_rom(ctrl);
2826         meminfo->dimm_mask = spd_detect_dimms(ctrl);
2827
2828         printk_raminit("sdram_set_spd_registers: dimm_mask=0x%x\n", meminfo->dimm_mask);
2829
2830         if (!(meminfo->dimm_mask & ((1 << 2*DIMM_SOCKETS) - 1)))
2831         {
2832                 printk(BIOS_DEBUG, "No memory for this cpu\n");
2833                 return;
2834         }
2835         meminfo->dimm_mask = spd_enable_2channels(ctrl, meminfo);
2836         printk_raminit("spd_enable_2channels: dimm_mask=0x%x\n", meminfo->dimm_mask);
2837         if (meminfo->dimm_mask == -1)
2838                 goto hw_spd_err;
2839
2840         meminfo->dimm_mask = spd_set_ram_size(ctrl, meminfo);
2841         printk_raminit("spd_set_ram_size: dimm_mask=0x%x\n", meminfo->dimm_mask);
2842         if (meminfo->dimm_mask == -1)
2843                 goto hw_spd_err;
2844
2845         meminfo->dimm_mask = spd_handle_unbuffered_dimms(ctrl, meminfo);
2846         printk_raminit("spd_handle_unbuffered_dimms: dimm_mask=0x%x\n", meminfo->dimm_mask);
2847         if (meminfo->dimm_mask == -1)
2848                 goto hw_spd_err;
2849
2850         result = spd_set_memclk(ctrl, meminfo);
2851         param     = result.param;
2852         meminfo->dimm_mask = result.dimm_mask;
2853         printk_raminit("spd_set_memclk: dimm_mask=0x%x\n", meminfo->dimm_mask);
2854         if (meminfo->dimm_mask == -1)
2855                 goto hw_spd_err;
2856
2857         //store memclk set to sysinfo, incase we need rebuilt param again
2858         meminfo->memclk_set = param->dch_memclk;
2859
2860         memcpy(&paramx, param, sizeof(paramx));
2861
2862         paramx.divisor = get_exact_divisor(param->dch_memclk, paramx.divisor);
2863
2864         meminfo->dimm_mask = spd_set_dram_timing(ctrl, &paramx, meminfo);
2865         printk_raminit("spd_set_dram_timing: dimm_mask=0x%x\n", meminfo->dimm_mask);
2866         if (meminfo->dimm_mask == -1)
2867                 goto hw_spd_err;
2868
2869         order_dimms(ctrl, meminfo);
2870
2871         return;
2872  hw_spd_err:
2873         /* Unrecoverable error reading SPD data */
2874         die("Unrecoverable error reading SPD data. No qualified DIMMs?");
2875         return;
2876 }
2877
2878 #define TIMEOUT_LOOPS 300000
2879
2880 #include "raminit_f_dqs.c"
2881
2882 #if CONFIG_HW_MEM_HOLE_SIZEK != 0
2883 static uint32_t hoist_memory(int controllers, const struct mem_controller *ctrl,unsigned hole_startk, int i)
2884 {
2885         int ii;
2886         uint32_t carry_over;
2887         device_t dev;
2888         uint32_t base, limit;
2889         uint32_t basek;
2890         uint32_t hoist;
2891         int j;
2892
2893         carry_over = (4*1024*1024) - hole_startk;
2894
2895         for (ii=controllers - 1;ii>i;ii--) {
2896                 base  = pci_read_config32(ctrl[0].f1, 0x40 + (ii << 3));
2897                 if ((base & ((1<<1)|(1<<0))) != ((1<<1)|(1<<0))) {
2898                         continue;
2899                 }
2900                 limit = pci_read_config32(ctrl[0].f1, 0x44 + (ii << 3));
2901                 limit += (carry_over << 2 );
2902                 base  += (carry_over << 2 );
2903                 for (j = 0; j < controllers; j++) {
2904                         pci_write_config32(ctrl[j].f1, 0x44 + (ii << 3), limit);
2905                         pci_write_config32(ctrl[j].f1, 0x40 + (ii << 3), base );
2906                 }
2907         }
2908         limit = pci_read_config32(ctrl[0].f1, 0x44 + (i << 3));
2909         limit += (carry_over << 2);
2910         for (j = 0; j < controllers; j++) {
2911                 pci_write_config32(ctrl[j].f1, 0x44 + (i << 3), limit);
2912         }
2913         dev = ctrl[i].f1;
2914         base  = pci_read_config32(dev, 0x40 + (i << 3));
2915         basek  = (base & 0xffff0000) >> 2;
2916         if (basek == hole_startk) {
2917                 //don't need set memhole here, because hole off set will be 0, overflow
2918                 //so need to change base reg instead, new basek will be 4*1024*1024
2919                 base &= 0x0000ffff;
2920                 base |= (4*1024*1024)<<2;
2921                 for (j = 0; j < controllers; j++) {
2922                         pci_write_config32(ctrl[j].f1, 0x40 + (i<<3), base);
2923                 }
2924         }  else  {
2925                 hoist = /* hole start address */
2926                         ((hole_startk << 10) & 0xff000000) +
2927                         /* hole address to memory controller address */
2928                         (((basek + carry_over) >> 6) & 0x0000ff00) +
2929                         /* enable */
2930                         1;
2931                 pci_write_config32(dev, 0xf0, hoist);
2932         }
2933
2934         return carry_over;
2935 }
2936
2937 static void set_hw_mem_hole(int controllers, const struct mem_controller *ctrl)
2938 {
2939
2940         uint32_t hole_startk;
2941         int i;
2942
2943         hole_startk = 4*1024*1024 - CONFIG_HW_MEM_HOLE_SIZEK;
2944
2945         printk_raminit("Handling memory hole at 0x%08x (default)\n", hole_startk);
2946 #if CONFIG_HW_MEM_HOLE_SIZE_AUTO_INC == 1
2947         /* We need to double check if the hole_startk is valid, if it is equal
2948            to basek, we need to decrease it some */
2949         uint32_t basek_pri;
2950         for (i=0; i<controllers; i++) {
2951                         uint32_t base;
2952                         unsigned base_k;
2953                         base  = pci_read_config32(ctrl[0].f1, 0x40 + (i << 3));
2954                         if ((base & ((1<<1)|(1<<0))) != ((1<<1)|(1<<0))) {
2955                                 continue;
2956                         }
2957                         base_k = (base & 0xffff0000) >> 2;
2958                         if (base_k == hole_startk) {
2959                                 /* decrease mem hole startk to make sure it is
2960                                    on middle of previous node */
2961                                 hole_startk -= (base_k - basek_pri) >> 1;
2962                                 break; //only one hole
2963                         }
2964                         basek_pri = base_k;
2965         }
2966         printk_raminit("Handling memory hole at 0x%08x (adjusted)\n", hole_startk);
2967 #endif
2968         /* find node index that need do set hole */
2969         for (i=0; i < controllers; i++) {
2970                 uint32_t base, limit;
2971                 unsigned base_k, limit_k;
2972                 base  = pci_read_config32(ctrl[0].f1, 0x40 + (i << 3));
2973                 if ((base & ((1 << 1) | (1 << 0))) != ((1 << 1) | (1 << 0))) {
2974                         continue;
2975                 }
2976                 limit = pci_read_config32(ctrl[0].f1, 0x44 + (i << 3));
2977                 base_k = (base & 0xffff0000) >> 2;
2978                 limit_k = ((limit + 0x00010000) & 0xffff0000) >> 2;
2979                 if ((base_k <= hole_startk) && (limit_k > hole_startk)) {
2980                         unsigned end_k;
2981                         hoist_memory(controllers, ctrl, hole_startk, i);
2982                         end_k = memory_end_k(ctrl, controllers);
2983                         set_top_mem(end_k, hole_startk);
2984                         break; //only one hole
2985                 }
2986         }
2987
2988 }
2989 #endif
2990
2991 #include "exit_from_self.c"
2992
2993 static void sdram_enable(int controllers, const struct mem_controller *ctrl,
2994                           struct sys_info *sysinfo)
2995 {
2996         int i;
2997 #ifdef ACPI_IS_WAKEUP_EARLY
2998         int suspend = acpi_is_wakeup_early();
2999 #else
3000         int suspend = 0;
3001 #endif
3002  
3003 #if K8_REV_F_SUPPORT_F0_F1_WORKAROUND == 1
3004          unsigned cpu_f0_f1[8];
3005         /* FIXME: How about 32 node machine later? */
3006         tsc_t tsc, tsc0[8];
3007
3008         printk(BIOS_DEBUG, "sdram_enable: tsc0[8]: %p", &tsc0[0]);
3009         uint32_t dword;
3010 #endif
3011
3012         /* Error if I don't have memory */
3013         if (memory_end_k(ctrl, controllers) == 0) {
3014                 die("No memory\n");
3015         }
3016
3017         /* Before enabling memory start the memory clocks */
3018         for (i = 0; i < controllers; i++) {
3019                 uint32_t dch;
3020                 if (!sysinfo->ctrl_present[ i ])
3021                         continue;
3022                 dch = pci_read_config32(ctrl[i].f2, DRAM_CONFIG_HIGH);
3023
3024                 /* if no memory installed, disabled the interface */
3025                 if (sysinfo->meminfo[i].dimm_mask==0x00){
3026                         dch |= DCH_DisDramInterface;
3027                         pci_write_config32(ctrl[i].f2, DRAM_CONFIG_HIGH, dch);
3028
3029                 } else {
3030                         dch |= DCH_MemClkFreqVal;
3031                         pci_write_config32(ctrl[i].f2, DRAM_CONFIG_HIGH, dch);
3032                         /* address timing and Output driver comp Control */
3033                         set_misc_timing(ctrl+i, sysinfo->meminfo+i );
3034                 }
3035         }
3036
3037         /* We need to wait a minimum of 20 MEMCLKS to enable the InitDram */
3038         memreset(controllers, ctrl);
3039
3040         /* lets override the rest of the routine */
3041         if (suspend) {
3042                 printk(BIOS_DEBUG, "Wakeup!\n");
3043                 exit_from_self(controllers, ctrl, sysinfo);
3044                 printk(BIOS_DEBUG, "Mem running !\n");
3045                 return;
3046         }
3047
3048         for (i = 0; i < controllers; i++) {
3049                 uint32_t dcl, dch;
3050                 if (!sysinfo->ctrl_present[ i ])
3051                         continue;
3052                 /* Skip everything if I don't have any memory on this controller */
3053                 dch = pci_read_config32(ctrl[i].f2, DRAM_CONFIG_HIGH);
3054                 if (!(dch & DCH_MemClkFreqVal)) {
3055                         continue;
3056                 }
3057
3058                 /* ChipKill */
3059                 dcl = pci_read_config32(ctrl[i].f2, DRAM_CONFIG_LOW);
3060                 if (dcl & DCL_DimmEccEn) {
3061                         uint32_t mnc;
3062                         printk(BIOS_SPEW, "ECC enabled\n");
3063                         mnc = pci_read_config32(ctrl[i].f3, MCA_NB_CONFIG);
3064                         mnc |= MNC_ECC_EN;
3065                         if (dcl & DCL_Width128) {
3066                                 mnc |= MNC_CHIPKILL_EN;
3067                         }
3068                         pci_write_config32(ctrl[i].f3, MCA_NB_CONFIG, mnc);
3069                 }
3070
3071 #if K8_REV_F_SUPPORT_F0_F1_WORKAROUND == 1
3072                 cpu_f0_f1[i] = is_cpu_pre_f2_in_bsp(i);
3073                 if (cpu_f0_f1[i]) {
3074                         //Rev F0/F1 workaround
3075 #if 1
3076                                 /* Set the DqsRcvEnTrain bit */
3077                         dword = pci_read_config32(ctrl[i].f2, DRAM_CTRL);
3078                         dword |= DC_DqsRcvEnTrain;
3079                         pci_write_config32(ctrl[i].f2, DRAM_CTRL, dword);
3080 #endif
3081                         tsc0[i] = rdtsc();
3082                 }
3083 #endif
3084
3085                 pci_write_config32(ctrl[i].f2, DRAM_CONFIG_LOW, dcl);
3086                 dcl |= DCL_InitDram;
3087                 pci_write_config32(ctrl[i].f2, DRAM_CONFIG_LOW, dcl);
3088         }
3089
3090         for (i = 0; i < controllers; i++) {
3091                 uint32_t dcl, dcm;
3092                 if (!sysinfo->ctrl_present[ i ])
3093                         continue;
3094                 /* Skip everything if I don't have any memory on this controller */
3095                 if (sysinfo->meminfo[i].dimm_mask==0x00) continue;
3096
3097                 printk(BIOS_DEBUG, "Initializing memory: ");
3098                 int loops = 0;
3099                 do {
3100                         dcl = pci_read_config32(ctrl[i].f2, DRAM_CONFIG_LOW);
3101                         loops++;
3102                         if ((loops & 1023) == 0) {
3103                                 printk(BIOS_DEBUG, ".");
3104                         }
3105                 } while(((dcl & DCL_InitDram) != 0) && (loops < TIMEOUT_LOOPS));
3106                 if (loops >= TIMEOUT_LOOPS) {
3107                         printk(BIOS_DEBUG, " failed\n");
3108                         continue;
3109                 }
3110
3111                 /* Wait until it is safe to touch memory */
3112                 do {
3113                         dcm = pci_read_config32(ctrl[i].f2, DRAM_CTRL_MISC);
3114                 } while(((dcm & DCM_MemClrStatus) == 0) /* || ((dcm & DCM_DramEnabled) == 0)*/ );
3115
3116 #if K8_REV_F_SUPPORT_F0_F1_WORKAROUND == 1
3117                 if (cpu_f0_f1[i]) {
3118                         tsc= rdtsc();
3119
3120                         print_debug_dqs_tsc("\nbegin tsc0", i, tsc0[i].hi, tsc0[i].lo, 2);
3121                         print_debug_dqs_tsc("end   tsc ", i, tsc.hi, tsc.lo, 2);
3122
3123                         if (tsc.lo<tsc0[i].lo) {
3124                                 tsc.hi--;
3125                         }
3126                         tsc.lo -= tsc0[i].lo;
3127                         tsc.hi -= tsc0[i].hi;
3128
3129                         tsc0[i].lo = tsc.lo;
3130                         tsc0[i].hi = tsc.hi;
3131
3132                         print_debug_dqs_tsc("     dtsc0", i, tsc0[i].hi, tsc0[i].lo, 2);
3133                 }
3134 #endif
3135                 printk(BIOS_DEBUG, " done\n");
3136         }
3137
3138 #if CONFIG_HW_MEM_HOLE_SIZEK != 0
3139         /* init hw mem hole here */
3140         /* DramHoleValid bit only can be set after MemClrStatus is set by Hardware */
3141         set_hw_mem_hole(controllers, ctrl);
3142 #endif
3143
3144         /* store tom to sysinfo, and it will be used by dqs_timing */
3145         {
3146                 msr_t msr;
3147                 //[1M, TOM)
3148                 msr = rdmsr(TOP_MEM);
3149                 sysinfo->tom_k = ((msr.hi<<24) | (msr.lo>>8))>>2;
3150
3151                 //[4G, TOM2)
3152                 msr = rdmsr(TOP_MEM2);
3153                 sysinfo->tom2_k = ((msr.hi<<24)| (msr.lo>>8))>>2;
3154         }
3155
3156         for (i = 0; i < controllers; i++) {
3157                 sysinfo->mem_trained[i] = 0;
3158
3159                 if (!sysinfo->ctrl_present[ i ])
3160                         continue;
3161
3162                 /* Skip everything if I don't have any memory on this controller */
3163                 if (sysinfo->meminfo[i].dimm_mask==0x00)
3164                         continue;
3165
3166                 sysinfo->mem_trained[i] = 0x80; // mem need to be trained
3167         }
3168
3169
3170 #if CONFIG_MEM_TRAIN_SEQ ==  0
3171    #if K8_REV_F_SUPPORT_F0_F1_WORKAROUND == 1
3172         dqs_timing(controllers, ctrl, tsc0, sysinfo);
3173    #else
3174         dqs_timing(controllers, ctrl, sysinfo);
3175    #endif
3176 #else
3177
3178 #if CONFIG_MEM_TRAIN_SEQ == 2
3179         /* need to enable mtrr, so dqs training could access the test address  */
3180         setup_mtrr_dqs(sysinfo->tom_k, sysinfo->tom2_k);
3181 #endif
3182
3183         for (i = 0; i < controllers; i++) {
3184                 /* Skip everything if I don't have any memory on this controller */
3185                 if (sysinfo->mem_trained[i]!=0x80)
3186                         continue;
3187
3188                 dqs_timing(i, &ctrl[i], sysinfo, 1);
3189
3190 #if CONFIG_MEM_TRAIN_SEQ == 1
3191                 break; // only train the first node with ram
3192 #endif
3193         }
3194
3195 #if CONFIG_MEM_TRAIN_SEQ == 2
3196         clear_mtrr_dqs(sysinfo->tom2_k);
3197 #endif
3198
3199 #endif
3200
3201 #if CONFIG_MEM_TRAIN_SEQ != 1
3202         wait_all_core0_mem_trained(sysinfo);
3203 #endif
3204
3205 }
3206
3207 static void fill_mem_ctrl(int controllers, struct mem_controller *ctrl_a,
3208                           const uint16_t *spd_addr)
3209 {
3210         int i;
3211         int j;
3212         struct mem_controller *ctrl;
3213         for (i=0;i<controllers; i++) {
3214                 ctrl = &ctrl_a[i];
3215                 ctrl->node_id = i;
3216                 ctrl->f0 = PCI_DEV(0, 0x18+i, 0);
3217                 ctrl->f1 = PCI_DEV(0, 0x18+i, 1);
3218                 ctrl->f2 = PCI_DEV(0, 0x18+i, 2);
3219                 ctrl->f3 = PCI_DEV(0, 0x18+i, 3);
3220
3221                 if (spd_addr == (void *)0) continue;
3222
3223                 for (j=0;j<DIMM_SOCKETS;j++) {
3224                         ctrl->channel0[j] = spd_addr[(i*2+0)*DIMM_SOCKETS + j];
3225                         ctrl->channel1[j] = spd_addr[(i*2+1)*DIMM_SOCKETS + j];
3226                 }
3227         }
3228 }