18e2a0762f6f472aa005368358936719515f077c
[coreboot.git] / src / cpu / amd / model_10xxx / fidvid.c
1 /*
2  * This file is part of the coreboot project.
3  *
4  * Copyright (C) 2007 Advanced Micro Devices, Inc.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; version 2 of the License.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  */
19
20 #if CONFIG_SET_FIDVID
21 #include <northbridge/amd/amdht/AsPsDefs.h>
22
23 static inline void print_debug_fv(const char *str, u32 val)
24 {
25 #if CONFIG_SET_FIDVID_DEBUG
26         printk(BIOS_DEBUG, "%s%x\n", str, val);
27 #endif
28 }
29
30 static inline void print_debug_fv_8(const char *str, u8 val)
31 {
32 #if CONFIG_SET_FIDVID_DEBUG
33         printk(BIOS_DEBUG, "%s%02x\n", str, val);
34 #endif
35 }
36
37 static inline void print_debug_fv_64(const char *str, u32 val, u32 val2)
38 {
39 #if CONFIG_SET_FIDVID_DEBUG
40         printk(BIOS_DEBUG, "%s%x%x\n", str, val, val2);
41 #endif
42 }
43
44 struct fidvid_st {
45         u32 common_fid;
46 };
47
48 static void enable_fid_change(u8 fid)
49 {
50         u32 dword;
51         u32 nodes;
52         device_t dev;
53         int i;
54
55         nodes = get_nodes();
56
57         for (i = 0; i < nodes; i++) {
58                 dev = NODE_PCI(i, 3);
59                 dword = pci_read_config32(dev, 0xd4);
60                 dword &= ~0x1F;
61                 dword |= (u32) fid & 0x1F;
62                 dword |= 1 << 5;        // enable
63                 pci_write_config32(dev, 0xd4, dword);
64                 printk(BIOS_DEBUG, "FID Change Node:%02x, F3xD4: %08x \n", i,
65                        dword);
66         }
67 }
68
69 static void applyBoostFIDOffset(  device_t dev ) {
70   // BKDG 2.4.2.8
71   // revision E only, but E is apparently not supported yet, therefore untested
72   if ((cpuid_edx(0x80000007) & CPB_MASK)
73       &&  ((cpuid_ecx(0x80000008) & NC_MASK) ==5) ) {
74       u32 core =  get_node_core_id_x().coreid;
75       u32 asymetricBoostThisCore = ((pci_read_config32(dev, 0x10C) >> (core*2))) & 3;
76       msr_t msr =  rdmsr(PS_REG_BASE);
77       u32 cpuFid = msr.lo & PS_CPU_FID_MASK;
78       cpuFid = cpuFid + asymetricBoostThisCore;
79       msr.lo &=   ~PS_CPU_FID_MASK;
80       msr.lo |= cpuFid ;
81       wrmsr(PS_REG_BASE , msr);
82
83   }
84 }
85
86 static void enableNbPState1( device_t dev ) {
87   u32 cpuRev =  mctGetLogicalCPUID(0xFF);
88   if (cpuRev & AMD_FAM10_C3) {
89     u32 nbPState = (pci_read_config32(dev, 0x1F0) & NB_PSTATE_MASK);
90     if ( nbPState){
91       u32 nbVid1 = (pci_read_config32(dev, 0x1F4) & NB_VID1_MASK) >> NB_VID1_SHIFT;
92       u32 i;
93       for (i = nbPState; i < NM_PS_REG; i++) {
94          msr_t msr =  rdmsr(PS_REG_BASE + i);
95          if (msr.hi &  PS_EN_MASK ) {
96             msr.hi |= NB_DID_M_ON;
97             msr.lo &= NB_VID_MASK_OFF;
98             msr.lo |= ( nbVid1 << NB_VID_POS);
99             wrmsr(PS_REG_BASE + i, msr);
100          }
101       }
102     }
103   }
104 }
105
106 static u8 setPStateMaxVal( device_t dev ) {
107       u8 i,maxpstate=0;
108       for (i = 0; i < NM_PS_REG; i++) {
109          msr_t msr =  rdmsr(PS_REG_BASE + i);
110          if (msr.hi & PS_IDD_VALUE_MASK) {
111            msr.hi |= PS_EN_MASK ;
112              wrmsr(PS_REG_BASE + i, msr);
113          }
114          if (msr.hi | PS_EN_MASK) {
115            maxpstate = i;
116          }
117       }
118       //FIXME: CPTC2 and HTC_REG should get max per node, not per core ?
119       u32 reg = pci_read_config32(dev, CPTC2);
120       reg &= PS_MAX_VAL_MASK;
121       reg |= (maxpstate << PS_MAX_VAL_POS);
122       pci_write_config32(dev, CPTC2,reg);
123       return maxpstate;
124 }
125
126 static void dualPlaneOnly(  device_t dev ) {
127   // BKDG 2.4.2.7
128
129   u32 cpuRev =  mctGetLogicalCPUID(0xFF);
130   if ((mctGetProcessorPackageType() ==  AMD_PKGTYPE_AM3_2r2)
131       && (cpuRev & AMD_DR_Cx)) { // should be rev C or rev E but there's no constant for E
132     if ( (pci_read_config32(dev, 0x1FC) & DUAL_PLANE_ONLY_MASK)
133          && (pci_read_config32(dev, 0xA0) & PVI_MODE) ){
134       if (cpuid_edx(0x80000007) & CPB_MASK) {
135           // revision E only, but E is apparently not supported yet, therefore untested
136          msr_t minPstate = rdmsr(0xC0010065);
137          wrmsr(0xC0010065, rdmsr(0xC0010068) );
138          wrmsr(0xC0010068,minPstate);
139       } else {
140          msr_t msr;
141          msr.lo=0; msr.hi=0;
142          wrmsr(0xC0010064, rdmsr(0xC0010068) );
143          wrmsr(0xC0010068, msr );
144       }
145
146       //FIXME: CPTC2 and HTC_REG should get max per node, not per core ?
147       u8 maxpstate = setPStateMaxVal(dev);
148
149       u32 reg = pci_read_config32(dev, HTC_REG);
150       reg &= HTC_PS_LMT_MASK;
151       reg |= (maxpstate << PS_LIMIT_POS);
152       pci_write_config32(dev, HTC_REG,reg);
153
154     }
155   }
156 }
157
158 static int vidTo100uV(u8 vid)
159 {// returns voltage corresponding to vid in tenths of mV, i.e. hundreds of uV
160  // BKDG #31116 rev 3.48 2.4.1.6
161   int voltage;
162   if (vid >= 0x7c) {
163     voltage = 0;
164   } else {
165     voltage = (15500 - (125*vid));
166   }
167   return voltage;
168 }
169
170 static void setVSRamp(device_t dev) {
171         /* BKDG r31116 2010-04-22  2.4.1.7 step b F3xD8[VSRampTime]
172          * If this field accepts 8 values between 10 and 500 us why
173          * does page 324 say "BIOS should set this field to 001b."
174          * (20 us) ?
175          * Shouldn't it depend on the voltage regulators, mainboard
176          * or something ?
177          */
178         u32 dword;
179         dword = pci_read_config32(dev, 0xd8);
180         dword &= VSRAMP_MASK;
181         dword |= VSRAMP_VALUE;
182         pci_write_config32(dev, 0xd8, dword);
183 }
184
185 static void recalculateVsSlamTimeSettingOnCorePre(device_t dev)
186 {
187         u8 pviModeFlag;
188         u8 highVoltageVid, lowVoltageVid, bValue;
189         u16 minimumSlamTime;
190         u16 vSlamTimes[7] = { 1000, 2000, 3000, 4000, 6000, 10000, 20000 };     /* Reg settings scaled by 100 */
191         u32 dtemp;
192         msr_t msr;
193
194         /* This function calculates the VsSlamTime using the range of possible
195          * voltages instead of a hardcoded 200us.
196          * Note: his function is called only from prep_fid_change,
197          * and that from init_cpus.c finalize_node_setup()
198          * (after set AMD MSRs and init ht )
199          */
200
201         /* BKDG r31116 2010-04-22  2.4.1.7 step b F3xD8[VSSlamTime] */
202         /* Calculate Slam Time
203          * Vslam = (mobileCPU?0.2:0.4)us/mV * (Vp0 - (lowest out of Vpmin or Valt)) mV
204          * In our case, we will scale the values by 100 to avoid
205          * decimals.
206          */
207
208         /* Determine if this is a PVI or SVI system */
209         dtemp = pci_read_config32(dev, 0xA0);
210
211         if (dtemp & PVI_MODE)
212                 pviModeFlag = 1;
213         else
214                 pviModeFlag = 0;
215
216         /* Get P0's voltage */
217         /* MSRC001_00[68:64] are not programmed yet when called from
218            prep_fid_change, one might use F4x1[F0:E0] instead, but
219            theoretically MSRC001_00[68:64] are equal to them after
220            reset. */
221         msr = rdmsr(0xC0010064);
222         highVoltageVid = (u8) ((msr.lo >> PS_CPU_VID_SHFT) & 0x7F);
223         if (!(msr.hi & 0x80000000)) {
224             printk(BIOS_ERR,"P-state info in MSRC001_0064 is invalid !!!\n");
225             highVoltageVid = (u8) ((pci_read_config32(dev, 0x1E0)
226                                      >> PS_CPU_VID_SHFT) & 0x7F);
227         }
228
229         /* If SVI, we only care about CPU VID.
230          * If PVI, determine the higher voltage b/t NB and CPU
231          */
232         if (pviModeFlag) {
233                 bValue = (u8) ((msr.lo >> PS_NB_VID_SHFT) & 0x7F);
234                 if (highVoltageVid > bValue)
235                         highVoltageVid = bValue;
236         }
237
238         /* Get PSmax's index */
239         msr = rdmsr(0xC0010061);
240         bValue = (u8) ((msr.lo >> PS_MAX_VAL_SHFT) & BIT_MASK_3);
241
242         /* Get PSmax's VID */
243         msr = rdmsr(0xC0010064 + bValue);
244         lowVoltageVid = (u8) ((msr.lo >> PS_CPU_VID_SHFT) & 0x7F);
245         if (!(msr.hi & 0x80000000)) {
246             printk(BIOS_ERR,"P-state info in MSR%8x is invalid !!!\n",0xC0010064 + bValue);
247             lowVoltageVid = (u8) ((pci_read_config32(dev, 0x1E0+(bValue*4))
248                                      >> PS_CPU_VID_SHFT) & 0x7F);
249         }
250
251         /* If SVI, we only care about CPU VID.
252          * If PVI, determine the higher voltage b/t NB and CPU
253          * BKDG 2.4.1.7 (a)
254          */
255         if (pviModeFlag) {
256                 bValue = (u8) ((msr.lo >> PS_NB_VID_SHFT) & 0x7F);
257                 if (lowVoltageVid > bValue)
258                         lowVoltageVid = bValue;
259         }
260
261         /* Get AltVID */
262         dtemp = pci_read_config32(dev, 0xDC);
263         bValue = (u8) (dtemp & BIT_MASK_7);
264
265         /* Use the VID with the lowest voltage (higher VID) */
266         if (lowVoltageVid < bValue)
267                 lowVoltageVid = bValue;
268
269         u8 mobileFlag = get_platform_type() & AMD_PTYPE_MOB;
270         minimumSlamTime =  (mobileFlag?2:4) * (vidTo100uV(highVoltageVid) - vidTo100uV(lowVoltageVid)); /* * 0.01 us */
271
272
273         /* Now round up to nearest register setting.
274          * Note that if we don't find a value, we
275          * will fall through to a value of 7
276          */
277         for (bValue = 0; bValue < 7; bValue++) {
278                 if (minimumSlamTime <= vSlamTimes[bValue])
279                         break;
280         }
281
282         /* Apply the value */
283         dtemp = pci_read_config32(dev, 0xD8);
284         dtemp &= VSSLAM_MASK;
285         dtemp |= bValue;
286         pci_write_config32(dev, 0xd8, dtemp);
287 }
288
289 static u32 nb_clk_did(int node, u32 cpuRev,u8 procPkg) {
290         u8 link0isGen3 = 0;
291         u8 offset;
292         if (AMD_CpuFindCapability(node, 0, &offset)) {
293           link0isGen3 = (AMD_checkLinkType(node, 0, offset) & HTPHY_LINKTYPE_HT3 );
294         }
295         /* FIXME: NB_CLKDID should be 101b for AMD_DA_C2 in package
296            S1g3 in link Gen3 mode, but I don't know how to tell
297            package S1g3 from S1g4 */
298         if ((cpuRev & AMD_DA_C2) && (procPkg & AMD_PKGTYPE_S1gX)
299            && link0isGen3) {
300           return 5 ; /* divide clk by 128*/
301         } else {
302           return 4 ; /* divide clk by 16 */
303         }
304 }
305
306
307 static u32 power_up_down(int node, u8 procPkg) {
308        u32 dword=0;
309         /* from CPU rev guide #41322 rev 3.74 June 2010 Table 26 */
310         u8 singleLinkFlag = ((procPkg == AMD_PKGTYPE_AM3_2r2)
311                              || (procPkg == AMD_PKGTYPE_S1gX)
312                              || (procPkg == AMD_PKGTYPE_ASB2));
313
314         if (singleLinkFlag) {
315           /*
316            * PowerStepUp=01000b - 50nS
317            * PowerStepDown=01000b - 50ns
318            */
319           dword |= PW_STP_UP50 | PW_STP_DN50;
320         } else {
321           u32 dispRefModeEn = (pci_read_config32(NODE_PCI(node,0),0x68) >> 24) & 1;
322           u32 isocEn = 0;
323           int j;
324           for(j=0 ; (j<4) && (!isocEn) ; j++ ) {
325             u8 offset;
326             if (AMD_CpuFindCapability(node, j, &offset)) {
327               isocEn = (pci_read_config32(NODE_PCI(node,0),offset+4) >>12) & 1;
328             }
329           }
330
331           if (dispRefModeEn || isocEn) {
332                 dword |= PW_STP_UP50 | PW_STP_DN50 ;
333           } else {
334                 /* get number of cores for PowerStepUp & PowerStepDown in server
335                    1 core - 400nS  - 0000b
336                    2 cores - 200nS - 0010b
337                    3 cores - 133nS -> 100nS - 0011b
338                    4 cores - 100nS - 0011b
339                  */
340                 switch (get_core_num_in_bsp(node)) {
341                 case 0:
342                         dword |= PW_STP_UP400 | PW_STP_DN400;
343                         break;
344                 case 1:
345                 case 2:
346                         dword |= PW_STP_UP200 | PW_STP_DN200;
347                         break;
348                 case 3:
349                         dword |= PW_STP_UP100 | PW_STP_DN100;
350                         break;
351                 default:
352                         dword |= PW_STP_UP100 | PW_STP_DN100;
353                         break;
354                 }
355           }
356         }
357         return dword;
358 }
359
360 static void config_clk_power_ctrl_reg0(int node, u32 cpuRev, u8 procPkg) {
361         device_t dev = NODE_PCI(node, 3);
362
363         /* Program fields in Clock Power/Control register0 (F3xD4) */
364
365         /* set F3xD4 Clock Power/Timing Control 0 Register
366          * NbClkDidApplyAll=1b
367          * NbClkDid=100b or 101b
368          * PowerStepUp= "platform dependent"
369          * PowerStepDown= "platform dependent"
370          * LinkPllLink=01b
371          * ClkRampHystCtl=HW default
372          * ClkRampHystSel=1111b
373          */
374         u32 dword= pci_read_config32(dev, 0xd4);
375         dword &= CPTC0_MASK;
376         dword |= NB_CLKDID_ALL | LNK_PLL_LOCK | CLK_RAMP_HYST_SEL_VAL;
377         dword |= (nb_clk_did(node,cpuRev,procPkg) <<  NB_CLKDID_SHIFT);
378
379         dword |= power_up_down(node, procPkg);
380
381         pci_write_config32(dev, 0xd4, dword);
382
383 }
384
385 static void config_power_ctrl_misc_reg(device_t dev,u32 cpuRev, u8 procPkg) {
386         /* check PVI/SVI */
387         u32 dword = pci_read_config32(dev, 0xA0);
388
389         /* BKDG r31116 2010-04-22  2.4.1.7 step b F3xA0[VSSlamVidMod] */
390         /* PllLockTime and PsiVidEn set in ruleset in defaults.h */
391         if (dword & PVI_MODE) { /* PVI */
392                 /* set slamVidMode to 0 for PVI */
393                 dword &= VID_SLAM_OFF ;
394         } else {        /* SVI */
395                 /* set slamVidMode to 1 for SVI */
396                 dword |= VID_SLAM_ON;
397
398                 u32 dtemp = dword;
399
400                 /* Program F3xD8[PwrPlanes] according F3xA0[DulaVdd]  */
401                 dword = pci_read_config32(dev, 0xD8);
402
403                 if (dtemp & DUAL_VDD_BIT)
404                         dword |= PWR_PLN_ON;
405                 else
406                         dword &= PWR_PLN_OFF;
407                 pci_write_config32(dev, 0xD8, dword);
408
409                 dword = dtemp;
410         }
411         /* set the rest of A0 since we're at it... */
412
413         if (cpuRev & (AMD_DA_Cx | AMD_RB_C3 )) {
414              dword |= NB_PSTATE_FORCE_ON;
415         } // else should we clear it ?
416
417
418         if ((procPkg == AMD_PKGTYPE_G34) || (procPkg == AMD_PKGTYPE_C32) ) {
419           dword |= BP_INS_TRI_EN_ON ;
420         }
421
422            /* TODO: look into C1E state and F3xA0[IdleExitEn]*/
423         #if CONFIG_SVI_HIGH_FREQ
424            if (cpuRev & AMD_FAM10_C3) {
425              dword |= SVI_HIGH_FREQ_ON;
426            }
427         #endif
428         pci_write_config32(dev, 0xA0, dword);
429 }
430
431 static void config_nb_syn_ptr_adj(device_t dev, u32 cpuRev) {
432         /* Note the following settings are additional from the ported
433          * function setFidVidRegs()
434          */
435         /* adjust FIFO between nb and core clocks to max allowed
436            values (min latency) */
437         u32 nbPstate = pci_read_config32(dev,0x1f0) & NB_PSTATE_MASK;
438         u8 nbSynPtrAdj;
439         if ((cpuRev & (AMD_DR_Bx|AMD_DA_Cx) )
440             || ( (cpuRev & AMD_RB_C3) && (nbPstate!=0)))  {
441           nbSynPtrAdj = 5;
442         } else {
443           nbSynPtrAdj = 6;
444         }
445
446         u32 dword = pci_read_config32(dev, 0xDc);
447         dword &= ~ NB_SYN_PTR_ADJ_MASK;
448         dword |= nbSynPtrAdj << NB_SYN_PTR_ADJ_POS;
449         /* NbsynPtrAdj set to 5 or 6 per BKDG (needs reset) */
450         pci_write_config32(dev, 0xdc, dword);
451 }
452
453 static void config_acpi_pwr_state_ctrl_regs(device_t dev, u32 cpuRev, u8 procPkg) {
454                 /* step 1, chapter 2.4.2.6 of AMD Fam 10 BKDG #31116 Rev 3.48 22.4.2010 */
455         u32 dword;
456         u32 c1= 1;
457         if (cpuRev & (AMD_DR_Bx)) {
458             // will coreboot ever enable cache scrubbing ?
459             // if it does, will it be enough to check the current state
460             // or should we configure for what we'll set up later ?
461             dword = pci_read_config32(dev, 0x58);
462             u32 scrubbingCache = dword &
463                                 ( (0x1F << 16) // DCacheScrub
464                                   | (0x1F << 8) ); // L2Scrub
465             if (scrubbingCache) {
466                 c1 = 0x80;
467             } else {
468                 c1 = 0xA0;
469             }
470         } else { // rev C or later
471             // same doubt as cache scrubbing: ok to check current state ?
472             dword = pci_read_config32(dev, 0xDC);
473             u32 cacheFlushOnHalt = dword & (7 << 16);
474             if (!cacheFlushOnHalt) {
475                c1 = 0x80;
476             }
477         }
478         dword = (c1 << 24) | (0xE641E6);
479         pci_write_config32(dev, 0x84, dword);
480
481
482         /* FIXME: BKDG Table 100 says if the link is at a Gen1
483 frequency and the chipset does not support a 10us minimum LDTSTOP
484 assertion time, then { If ASB2 && SVI then smaf001 = F6h else
485 smaf001=87h. } else ...  I hardly know what it means or how to check
486 it from here, so I bluntly assume it is false and code here the else,
487 which is easier  */
488
489         u32 smaf001 = 0xE6;
490         if (cpuRev & AMD_DR_Bx ) {
491             smaf001 = 0xA6;
492         } else {
493             #if CONFIG_SVI_HIGH_FREQ
494                 if (cpuRev & (AMD_RB_C3 | AMD_DA_C3)) {
495                        smaf001 = 0xF6;
496                 }
497             #endif
498         }
499         u32 fidvidChange = 0;
500         if (((cpuRev & AMD_DA_Cx) && (procPkg & AMD_PKGTYPE_S1gX))
501                     || (cpuRev & AMD_RB_C3) ) {
502                        fidvidChange=0x0B;
503         }
504         dword = (0xE6 << 24) | (fidvidChange << 16)
505                         | (smaf001 << 8) | 0x81;
506         pci_write_config32(dev, 0x80, dword);
507 }
508
509 static void prep_fid_change(void)
510 {
511         u32 dword;
512         u32 nodes;
513         device_t dev;
514         int i;
515
516         /* This needs to be run before any Pstate changes are requested */
517
518         nodes = get_nodes();
519
520         for (i = 0; i < nodes; i++) {
521                 printk(BIOS_DEBUG, "Prep FID/VID Node:%02x \n", i);
522                 dev = NODE_PCI(i, 3);
523                 u32 cpuRev = mctGetLogicalCPUID(0xFF) ;
524                 u8 procPkg =  mctGetProcessorPackageType();
525
526                 setVSRamp(dev);
527                 /* BKDG r31116 2010-04-22  2.4.1.7 step b F3xD8[VSSlamTime] */
528                 /* Figure out the value for VsSlamTime and program it */
529                 recalculateVsSlamTimeSettingOnCorePre(dev);
530
531                 config_clk_power_ctrl_reg0(i,cpuRev,procPkg);
532
533                 config_power_ctrl_misc_reg(dev,cpuRev,procPkg);
534                 config_nb_syn_ptr_adj(dev,cpuRev);
535
536                 config_acpi_pwr_state_ctrl_regs(dev,cpuRev,procPkg);
537
538                 dword = pci_read_config32(dev, 0x80);
539                 printk(BIOS_DEBUG, "  F3x80: %08x \n", dword);
540                 dword = pci_read_config32(dev, 0x84);
541                 printk(BIOS_DEBUG, "  F3x84: %08x \n", dword);
542                 dword = pci_read_config32(dev, 0xD4);
543                 printk(BIOS_DEBUG, "  F3xD4: %08x \n", dword);
544                 dword = pci_read_config32(dev, 0xD8);
545                 printk(BIOS_DEBUG, "  F3xD8: %08x \n", dword);
546                 dword = pci_read_config32(dev, 0xDC);
547                 printk(BIOS_DEBUG, "  F3xDC: %08x \n", dword);
548
549
550         }
551 }
552
553 static void waitCurrentPstate(u32 target_pstate){
554   msr_t initial_msr = rdmsr(TSC_MSR);
555   msr_t pstate_msr = rdmsr(CUR_PSTATE_MSR);
556   msr_t tsc_msr;
557   u8 timedout ;
558
559   /* paranoia ? I fear when we run fixPsNbVidBeforeWR we can enter a
560    * P1 that is a copy of P0, therefore has the same NB DID but the
561    * TSC will count twice per tick, so we have to wait for twice the
562    * count to achieve the desired timeout. But I'm likely to
563    * misunderstand this...
564    */
565   u32 corrected_timeout = (    (pstate_msr.lo==1)
566                             && (!(rdmsr(0xC0010065).lo & NB_DID_M_ON)) ) ?
567                           WAIT_PSTATE_TIMEOUT*2 : WAIT_PSTATE_TIMEOUT  ;
568   msr_t timeout;
569
570   timeout.lo = initial_msr.lo + corrected_timeout ;
571   timeout.hi = initial_msr.hi;
572   if ( (((u32)0xffffffff) - initial_msr.lo) < corrected_timeout ) {
573      timeout.hi++;
574   }
575
576   // assuming TSC ticks at 1.25 ns per tick (800 MHz)
577   do {
578       pstate_msr = rdmsr(CUR_PSTATE_MSR);
579       tsc_msr = rdmsr(TSC_MSR);
580       timedout = (tsc_msr.hi > timeout.hi)
581                 || ((tsc_msr.hi == timeout.hi) && (tsc_msr.lo > timeout.lo ));
582   } while ( (pstate_msr.lo != target_pstate) && (! timedout) ) ;
583
584   if (pstate_msr.lo != target_pstate) {
585     msr_t limit_msr = rdmsr(0xc0010061);
586     printk(BIOS_ERR, "*** Time out waiting for P-state %01x. Current P-state %01x P-state current limit MSRC001_0061=%02x\n", target_pstate, pstate_msr.lo, limit_msr.lo);
587
588     do { // should we just go on instead ?
589       pstate_msr = rdmsr(CUR_PSTATE_MSR);
590     } while ( pstate_msr.lo != target_pstate  ) ;
591   }
592 }
593
594 static void set_pstate(u32 nonBoostedPState) {
595         msr_t msr;
596
597         // Transition P0 for calling core.
598         msr = rdmsr(0xC0010062);
599
600         msr.lo = nonBoostedPState;
601         wrmsr(0xC0010062, msr);
602
603         /* Wait for P0 to set. */
604         waitCurrentPstate(nonBoostedPState);
605 }
606
607
608
609
610 static void UpdateSinglePlaneNbVid(void)
611 {
612         u32 nbVid, cpuVid;
613         u8 i;
614         msr_t msr;
615
616         /* copy higher voltage (lower VID) of NBVID & CPUVID to both */
617         for (i = 0; i < 5; i++) {
618                 msr = rdmsr(PS_REG_BASE + i);
619                 nbVid = (msr.lo & PS_CPU_VID_M_ON) >> PS_CPU_VID_SHFT;
620                 cpuVid = (msr.lo & PS_NB_VID_M_ON) >> PS_NB_VID_SHFT;
621
622                 if (nbVid != cpuVid) {
623                         if (nbVid > cpuVid)
624                                 nbVid = cpuVid;
625
626                         msr.lo = msr.lo & PS_BOTH_VID_OFF;
627                         msr.lo = msr.lo | (u32) ((nbVid) << PS_NB_VID_SHFT);
628                         msr.lo = msr.lo | (u32) ((nbVid) << PS_CPU_VID_SHFT);
629                         wrmsr(PS_REG_BASE + i, msr);
630                 }
631         }
632 }
633
634 static void fixPsNbVidBeforeWR(u32 newNbVid, u32 coreid, u32 dev, u8 pviMode)
635  {
636         msr_t msr;
637         u8 startup_pstate;
638
639         /* This function sets NbVid before the warm reset.
640          *       Get StartupPstate from MSRC001_0071.
641          *       Read Pstate register pointed by [StartupPstate].
642          *       and copy its content to P0 and P1 registers.
643          *       Copy newNbVid to P0[NbVid].
644          *       transition to P1 on all cores,
645          *       then transition to P0 on core 0.
646          *       Wait for MSRC001_0063[CurPstate] = 000b on core 0.
647          * see BKDG rev 3.48  2.4.2.9.1 BIOS NB COF and VID Configuration
648          *                              for SVI and Single-Plane PVI Systems
649          */
650
651         msr = rdmsr(0xc0010071);
652         startup_pstate = (msr.hi >> (32 - 32)) & 0x07;
653
654         /* Copy startup pstate to P1 and P0 MSRs. Set the maxvid for
655          * this node in P0.  Then transition to P1 for corex and P0
656          * for core0.  These setting will be cleared by the warm reset
657          */
658         msr = rdmsr(0xC0010064 + startup_pstate);
659         wrmsr(0xC0010065, msr);
660         wrmsr(0xC0010064, msr);
661
662         /* missing step 2 from BDKG , F3xDC[PstateMaxVal] =
663          * max(1,F3xDC[PstateMaxVal] ) because it would take
664          * synchronization between cores and we don't think
665          * PstatMaxVal is going to be 0 on cold reset anyway ?
666          */
667         if ( ! (pci_read_config32(dev, 0xDC) & (~ PS_MAX_VAL_MASK)) ) {
668            printk(BIOS_ERR,"F3xDC[PstateMaxVal] is zero. Northbridge voltage setting will fail. fixPsNbVidBeforeWR in fidvid.c needs fixing. See AMD # 31116 rev 3.48 BKDG 2.4.2.9.1 \n");
669         };
670
671         msr.lo &= ~0xFE000000;  // clear nbvid
672         msr.lo |= (newNbVid << 25);
673         wrmsr(0xC0010064, msr);
674
675         if (pviMode) { /* single plane*/
676           UpdateSinglePlaneNbVid();
677         }
678
679         // Transition to P1 for all APs and P0 for core0.
680         set_pstate(1);
681
682         if (coreid == 0) {
683              set_pstate(0);
684         }
685
686         /* missing step 7 (restore PstateMax to 0 if needed) because
687          * we skipped step 2
688          */
689
690 }
691
692 static u32 needs_NB_COF_VID_update(void)
693 {
694         u8 nb_cof_vid_update;
695         u8 nodes;
696         u8 i;
697
698         /* If any node has nb_cof_vid_update set all nodes need an update. */
699         nodes = get_nodes();
700         nb_cof_vid_update = 0;
701         for (i = 0; i < nodes; i++) {
702                 u32 cpuRev = mctGetLogicalCPUID(i) ;
703                 u32 nbCofVidUpdateDefined = (cpuRev & (AMD_FAM10_LT_D));
704                 if (nbCofVidUpdateDefined
705                     && (pci_read_config32(NODE_PCI(i, 3), 0x1FC)
706                         & NB_COF_VID_UPDATE_MASK)) {
707                         nb_cof_vid_update = 1;
708                         break;
709                 }
710         }
711         return nb_cof_vid_update;
712 }
713
714 static u32 init_fidvid_core(u32 nodeid, u32 coreid)
715 {
716         device_t dev;
717         u32 vid_max;
718         u32 fid_max = 0;
719         u8 nb_cof_vid_update = needs_NB_COF_VID_update();
720         u8 pvimode;
721         u32 reg1fc;
722
723         /* Steps 1-6 of BIOS NB COF and VID Configuration
724          * for SVI and Single-Plane PVI Systems. BKDG 2.4.2.9 #31116 rev 3.48
725          */
726
727         dev = NODE_PCI(nodeid, 3);
728         pvimode = pci_read_config32(dev, PW_CTL_MISC) & PVI_MODE;
729         reg1fc = pci_read_config32(dev, 0x1FC);
730
731         if (nb_cof_vid_update) {
732                 vid_max = (reg1fc &  SINGLE_PLANE_NB_VID_MASK ) >>  SINGLE_PLANE_NB_VID_SHIFT ;
733                 fid_max = (reg1fc &  SINGLE_PLANE_NB_FID_MASK ) >>  SINGLE_PLANE_NB_FID_SHIFT ;
734
735                 if (!pvimode) { /* SVI, dual power plane */
736                         vid_max = vid_max - ((reg1fc &  DUAL_PLANE_NB_VID_OFF_MASK ) >>  DUAL_PLANE_NB_VID_SHIFT );
737                         fid_max = fid_max +  ((reg1fc &  DUAL_PLANE_NB_FID_OFF_MASK ) >>  DUAL_PLANE_NB_FID_SHIFT );
738                 }
739                 /* write newNbVid to P-state Reg's NbVid always if NbVidUpdatedAll=1 */
740                 fixPsNbVidBeforeWR(vid_max, coreid,dev,pvimode);
741
742                 /* fid setup is handled by the BSP at the end. */
743
744         } else {        /* ! nb_cof_vid_update */
745                 /* Use max values */
746                 if (pvimode)
747                         UpdateSinglePlaneNbVid();
748         }
749
750         return ((nb_cof_vid_update << 16) | (fid_max << 8));
751
752 }
753
754 static void init_fidvid_ap(u32 bsp_apicid, u32 apicid, u32 nodeid, u32 coreid)
755 {
756         u32 send;
757
758         printk(BIOS_DEBUG, "FIDVID on AP: %02x\n", apicid);
759
760         send = init_fidvid_core(nodeid,coreid);
761         send |= (apicid << 24); // ap apicid
762
763         // Send signal to BSP about this AP max fid
764         // This also indicates this AP is ready for warm reset (if required).
765         lapic_write(LAPIC_MSG_REG, send | F10_APSTATE_RESET);
766 }
767
768 static u32 calc_common_fid(u32 fid_packed, u32 fid_packed_new)
769 {
770         u32 fidmax;
771         u32 fidmax_new;
772
773         fidmax = (fid_packed >> 8) & 0xFF;
774
775         fidmax_new = (fid_packed_new >> 8) & 0xFF;
776
777         if (fidmax > fidmax_new) {
778                 fidmax = fidmax_new;
779         }
780
781         fid_packed &= 0xFF << 16;
782         fid_packed |= (fidmax << 8);
783         fid_packed |= fid_packed_new & (0xFF << 16);    // set nb_cof_vid_update
784
785         return fid_packed;
786 }
787
788 static void init_fidvid_bsp_stage1(u32 ap_apicid, void *gp)
789 {
790         u32 readback = 0;
791         u32 timeout = 1;
792
793         struct fidvid_st *fvp = gp;
794         int loop;
795
796         print_debug_fv("Wait for AP stage 1: ap_apicid = ", ap_apicid);
797
798         loop = 100000;
799         while (--loop > 0) {
800                 if (lapic_remote_read(ap_apicid, LAPIC_MSG_REG, &readback) != 0)
801                         continue;
802                 if ((readback & 0x3f) == 1) {
803                         timeout = 0;
804                         break;  /* target ap is in stage 1 */
805                 }
806         }
807
808         if (timeout) {
809                 printk(BIOS_DEBUG, "%s: timed out reading from ap %02x\n",
810                        __func__, ap_apicid);
811                 return;
812         }
813
814         print_debug_fv("\treadback = ", readback);
815
816         fvp->common_fid = calc_common_fid(fvp->common_fid, readback);
817
818         print_debug_fv("\tcommon_fid(packed) = ", fvp->common_fid);
819
820 }
821
822 static void fixPsNbVidAfterWR(u32 newNbVid, u8 NbVidUpdatedAll,u8 pviMode)
823 {
824         msr_t msr;
825         u8 i;
826         u8 StartupPstate;
827
828         /* BKDG 2.4.2.9.1 11-12
829          * This function copies newNbVid to NbVid bits in P-state
830          * Registers[4:0] if its NbDid bit=0, and IddValue!=0 in case of
831          * NbVidUpdatedAll =0 or copies newNbVid to NbVid bits in
832          * P-state Registers[4:0] if its IddValue!=0 in case of
833          * NbVidUpdatedAll=1. Then transition to StartPstate.
834          */
835
836         /* write newNbVid to P-state Reg's NbVid if its NbDid=0 */
837         for (i = 0; i < 5; i++) {
838                 msr = rdmsr(0xC0010064 + i);
839                 /*  NbDid (bit 22 of P-state Reg) == 0  or NbVidUpdatedAll = 1 */
840                 if (   (msr.hi & PS_IDD_VALUE_MASK)
841                     && (msr.hi & PS_EN_MASK)
842                     &&(((msr.lo & PS_NB_DID_MASK) == 0) || NbVidUpdatedAll)) {
843                         msr.lo &= PS_NB_VID_M_OFF;
844                         msr.lo |= (newNbVid & 0x7F) << PS_NB_VID_SHFT;
845                         wrmsr(0xC0010064 + i, msr);
846                 }
847         }
848
849         /* Not documented. Would overwrite Nb_Vids just copied
850          * should we just update cpu_vid or nothing at all ?
851          */
852         if (pviMode) { //single plane
853             UpdateSinglePlaneNbVid();
854         }
855         /* For each core in the system, transition all cores to StartupPstate */
856         msr = rdmsr(0xC0010071);
857         StartupPstate = msr.hi & 0x07;
858
859         /* Set and wait for StartupPstate to set. */
860         set_pstate(StartupPstate);
861
862 }
863
864 static void finalPstateChange(void)
865 {
866         /* Enble P0 on all cores for best performance.
867          * Linux can slow them down later if need be.
868          * It is safe since they will be in C1 halt
869          * most of the time anyway.
870          */
871         set_pstate(0);
872 }
873
874 static void init_fidvid_stage2(u32 apicid, u32 nodeid)
875 {
876         msr_t msr;
877         device_t dev;
878         u32 reg1fc;
879         u32 dtemp;
880         u32 nbvid;
881         u8 nb_cof_vid_update = needs_NB_COF_VID_update();
882         u8 NbVidUpdateAll;
883         u8 pvimode;
884
885         /* After warm reset finish the fid/vid setup for all cores. */
886
887         /* If any node has nb_cof_vid_update set all nodes need an update. */
888
889         dev = NODE_PCI(nodeid, 3);
890         pvimode = (pci_read_config32(dev, 0xA0) >> 8) & 1;
891         reg1fc = pci_read_config32(dev, 0x1FC);
892         nbvid = (reg1fc >> 7) & 0x7F;
893         NbVidUpdateAll = (reg1fc >> 1) & 1;
894
895         if (nb_cof_vid_update) {
896                 if (!pvimode) { /* SVI */
897                         nbvid = nbvid - ((reg1fc >> 17) & 0x1F);
898                 }
899                 /* write newNbVid to P-state Reg's NbVid if its NbDid=0 */
900                 fixPsNbVidAfterWR(nbvid, NbVidUpdateAll,pvimode);
901         } else {                /* !nb_cof_vid_update */
902                 if (pvimode)
903                         UpdateSinglePlaneNbVid();
904         }
905         dtemp = pci_read_config32(dev, 0xA0);
906         dtemp &= PLLLOCK_OFF;
907         dtemp |= PLLLOCK_DFT_L;
908         pci_write_config32(dev, 0xA0, dtemp);
909
910         dualPlaneOnly(dev);
911         applyBoostFIDOffset(dev);
912         enableNbPState1(dev);
913
914         finalPstateChange();
915
916         /* Set TSC to tick at the P0 ndfid rate */
917         msr = rdmsr(HWCR);
918         msr.lo |= 1 << 24;
919         wrmsr(HWCR, msr);
920 }
921
922
923 #if CONFIG_SET_FIDVID_STORE_AP_APICID_AT_FIRST
924 struct ap_apicid_st {
925         u32 num;
926         // it could use 256 bytes for 64 node quad core system
927         u8 apicid[NODE_NUMS * 4];
928 };
929
930 static void store_ap_apicid(unsigned ap_apicid, void *gp)
931 {
932         struct ap_apicid_st *p = gp;
933
934         p->apicid[p->num++] = ap_apicid;
935
936 }
937 #endif
938
939
940 static int init_fidvid_bsp(u32 bsp_apicid, u32 nodes)
941 {
942 #if CONFIG_SET_FIDVID_STORE_AP_APICID_AT_FIRST
943         struct ap_apicid_st ap_apicidx;
944         u32 i;
945 #endif
946         struct fidvid_st fv;
947
948         printk(BIOS_DEBUG, "FIDVID on BSP, APIC_id: %02x\n", bsp_apicid);
949
950         /* Steps 1-6 of BIOS NB COF and VID Configuration
951          * for SVI and Single-Plane PVI Systems.
952          */
953
954         fv.common_fid = init_fidvid_core(0,0);
955
956         print_debug_fv("BSP fid = ", fv.common_fid);
957
958 #if CONFIG_SET_FIDVID_STORE_AP_APICID_AT_FIRST && !CONFIG_SET_FIDVID_CORE0_ONLY
959         /* For all APs (We know the APIC ID of all APs even when the APIC ID
960            is lifted) remote read from AP LAPIC_MSG_REG about max fid.
961            Then calculate the common max fid that can be used for all
962            APs and BSP */
963         ap_apicidx.num = 0;
964
965         for_each_ap(bsp_apicid, CONFIG_SET_FIDVID_CORE_RANGE, store_ap_apicid, &ap_apicidx);
966
967         for (i = 0; i < ap_apicidx.num; i++) {
968                 init_fidvid_bsp_stage1(ap_apicidx.apicid[i], &fv);
969         }
970 #else
971         for_each_ap(bsp_apicid, CONFIG_SET_FIDVID_CORE0_ONLY, init_fidvid_bsp_stage1, &fv);
972 #endif
973
974         print_debug_fv("common_fid = ", fv.common_fid);
975
976         if (fv.common_fid & (1 << 16)) {        /* check nb_cof_vid_update */
977
978                 // Enable the common fid and other settings.
979                 enable_fid_change((fv.common_fid >> 8) & 0x1F);
980
981                 // nbfid change need warm reset, so reset at first
982                 return 1;
983         }
984
985         return 0;               // No FID/VID changes. Don't reset
986 }
987 #endif