Improving BKDG implementation of P-states,
[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         /* set the rest of A0 since we're at it... */
399
400         if (cpuRev & (AMD_DA_Cx | AMD_RB_C3 )) {
401              dword |= NB_PSTATE_FORCE_ON;
402         } // else should we clear it ?
403
404
405         if ((procPkg == AMD_PKGTYPE_G34) || (procPkg == AMD_PKGTYPE_C32) ) {
406           dword |= BP_INS_TRI_EN_ON ;
407         }
408
409            /* TODO: look into C1E state and F3xA0[IdleExitEn]*/
410         #if CONFIG_SVI_HIGH_FREQ
411            if (cpuRev & AMD_FAM10_C3) {
412              dword |= SVI_HIGH_FREQ_ON;
413            }
414         #endif
415         pci_write_config32(dev, 0xA0, dword);
416 }
417
418 static void config_nb_syn_ptr_adj(device_t dev, u32 cpuRev) {
419         /* Note the following settings are additional from the ported
420          * function setFidVidRegs()
421          */
422         /* adjust FIFO between nb and core clocks to max allowed
423            values (min latency) */
424         u32 nbPstate = pci_read_config32(dev,0x1f0) & NB_PSTATE_MASK;
425         u8 nbSynPtrAdj;
426         if ((cpuRev & (AMD_DR_Bx|AMD_DA_Cx) )
427             || ( (cpuRev & AMD_RB_C3) && (nbPstate!=0)))  {
428           nbSynPtrAdj = 5;
429         } else {
430           nbSynPtrAdj = 6;
431         }
432
433         u32 dword = pci_read_config32(dev, 0xDc);
434         dword &= ~ NB_SYN_PTR_ADJ_MASK;
435         dword |= nbSynPtrAdj << NB_SYN_PTR_ADJ_POS;
436         /* NbsynPtrAdj set to 5 or 6 per BKDG (needs reset) */
437         pci_write_config32(dev, 0xdc, dword);
438 }
439
440 static void config_acpi_pwr_state_ctrl_regs(device_t dev, u32 cpuRev, u8 procPkg) {
441                 /* step 1, chapter 2.4.2.6 of AMD Fam 10 BKDG #31116 Rev 3.48 22.4.2010 */
442         u32 dword;
443         u32 c1= 1;
444         if (cpuRev & (AMD_DR_Bx)) {
445             // will coreboot ever enable cache scrubbing ?
446             // if it does, will it be enough to check the current state
447             // or should we configure for what we'll set up later ?
448             dword = pci_read_config32(dev, 0x58);
449             u32 scrubbingCache = dword &
450                                 ( (0x1F << 16) // DCacheScrub
451                                   | (0x1F << 8) ); // L2Scrub
452             if (scrubbingCache) {
453                 c1 = 0x80;
454             } else {
455                 c1 = 0xA0;
456             }
457         } else { // rev C or later
458             // same doubt as cache scrubbing: ok to check current state ?
459             dword = pci_read_config32(dev, 0xDC);
460             u32 cacheFlushOnHalt = dword & (7 << 16);
461             if (!cacheFlushOnHalt) {
462                c1 = 0x80;
463             }
464         }
465         dword = (c1 << 24) | (0xE641E6);
466         pci_write_config32(dev, 0x84, dword);
467
468
469         /* FIXME: BKDG Table 100 says if the link is at a Gen1
470 frequency and the chipset does not support a 10us minimum LDTSTOP
471 assertion time, then { If ASB2 && SVI then smaf001 = F6h else
472 smaf001=87h. } else ...  I hardly know what it means or how to check
473 it from here, so I bluntly assume it is false and code here the else,
474 which is easier  */
475
476         u32 smaf001 = 0xE6;
477         if (cpuRev & AMD_DR_Bx ) {
478             smaf001 = 0xA6;
479         } else {
480             #if CONFIG_SVI_HIGH_FREQ
481                 if (cpuRev & (AMD_RB_C3 | AMD_DA_C3)) {
482                        smaf001 = 0xF6;
483                 }
484             #endif
485         }
486         u32 fidvidChange = 0;
487         if (((cpuRev & AMD_DA_Cx) && (procPkg & AMD_PKGTYPE_S1gX))
488                     || (cpuRev & AMD_RB_C3) ) {
489                        fidvidChange=0x0B;
490         }
491         dword = (0xE6 << 24) | (fidvidChange << 16)
492                         | (smaf001 << 8) | 0x81;
493         pci_write_config32(dev, 0x80, dword);
494 }
495
496 static void prep_fid_change(void)
497 {
498         u32 dword;
499         u32 nodes;
500         device_t dev;
501         int i;
502
503         /* This needs to be run before any Pstate changes are requested */
504
505         nodes = get_nodes();
506
507         for (i = 0; i < nodes; i++) {
508                 printk(BIOS_DEBUG, "Prep FID/VID Node:%02x \n", i);
509                 dev = NODE_PCI(i, 3);
510                 u32 cpuRev = mctGetLogicalCPUID(0xFF) ;
511                 u8 procPkg =  mctGetProcessorPackageType();
512
513                 setVSRamp(dev);
514                 /* BKDG r31116 2010-04-22  2.4.1.7 step b F3xD8[VSSlamTime] */
515                 /* Figure out the value for VsSlamTime and program it */
516                 recalculateVsSlamTimeSettingOnCorePre(dev);
517
518                 config_clk_power_ctrl_reg0(i,cpuRev,procPkg);
519
520                 config_power_ctrl_misc_reg(dev,cpuRev,procPkg);
521                 config_nb_syn_ptr_adj(dev,cpuRev);
522
523                 config_acpi_pwr_state_ctrl_regs(dev,cpuRev,procPkg);
524
525                 dword = pci_read_config32(dev, 0x80);
526                 printk(BIOS_DEBUG, "  F3x80: %08x \n", dword);
527                 dword = pci_read_config32(dev, 0x84);
528                 printk(BIOS_DEBUG, "  F3x84: %08x \n", dword);
529                 dword = pci_read_config32(dev, 0xD4);
530                 printk(BIOS_DEBUG, "  F3xD4: %08x \n", dword);
531                 dword = pci_read_config32(dev, 0xD8);
532                 printk(BIOS_DEBUG, "  F3xD8: %08x \n", dword);
533                 dword = pci_read_config32(dev, 0xDC);
534                 printk(BIOS_DEBUG, "  F3xDC: %08x \n", dword);
535
536
537         }
538 }
539
540 static void waitCurrentPstate(u32 target_pstate){
541   msr_t initial_msr = rdmsr(TSC_MSR);
542   msr_t pstate_msr = rdmsr(CUR_PSTATE_MSR);
543   msr_t tsc_msr;
544   u8 timedout ;
545
546   /* paranoia ? I fear when we run fixPsNbVidBeforeWR we can enter a
547    * P1 that is a copy of P0, therefore has the same NB DID but the
548    * TSC will count twice per tick, so we have to wait for twice the
549    * count to achieve the desired timeout. But I'm likely to
550    * misunderstand this...
551    */
552   u32 corrected_timeout = (    (pstate_msr.lo==1)
553                             && (!(rdmsr(0xC0010065).lo & NB_DID_M_ON)) ) ?
554                           WAIT_PSTATE_TIMEOUT*2 : WAIT_PSTATE_TIMEOUT  ;
555   msr_t timeout;
556
557   timeout.lo = initial_msr.lo + corrected_timeout ;
558   timeout.hi = initial_msr.hi;
559   if ( (((u32)0xffffffff) - initial_msr.lo) < corrected_timeout ) {
560      timeout.hi++;
561   }
562
563   // assuming TSC ticks at 1.25 ns per tick (800 MHz)
564   do {
565       pstate_msr = rdmsr(CUR_PSTATE_MSR);
566       tsc_msr = rdmsr(TSC_MSR);
567       timedout = (tsc_msr.hi > timeout.hi)
568                 || ((tsc_msr.hi == timeout.hi) && (tsc_msr.lo > timeout.lo ));
569   } while ( (pstate_msr.lo != target_pstate) && (! timedout) ) ;
570
571   if (pstate_msr.lo != target_pstate) {
572     msr_t limit_msr = rdmsr(0xc0010061);
573     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);
574
575     do { // should we just go on instead ?
576       pstate_msr = rdmsr(CUR_PSTATE_MSR);
577     } while ( pstate_msr.lo != target_pstate  ) ;
578   }
579 }
580
581 static void set_pstate(u32 nonBoostedPState) {
582         msr_t msr;
583
584         // Transition P0 for calling core.
585         msr = rdmsr(0xC0010062);
586
587         msr.lo = nonBoostedPState;
588         wrmsr(0xC0010062, msr);
589
590         /* Wait for P0 to set. */
591         waitCurrentPstate(nonBoostedPState);
592 }
593
594
595
596
597 static void UpdateSinglePlaneNbVid(void)
598 {
599         u32 nbVid, cpuVid;
600         u8 i;
601         msr_t msr;
602
603         /* copy higher voltage (lower VID) of NBVID & CPUVID to both */
604         for (i = 0; i < 5; i++) {
605                 msr = rdmsr(PS_REG_BASE + i);
606                 nbVid = (msr.lo & PS_CPU_VID_M_ON) >> PS_CPU_VID_SHFT;
607                 cpuVid = (msr.lo & PS_NB_VID_M_ON) >> PS_NB_VID_SHFT;
608
609                 if (nbVid != cpuVid) {
610                         if (nbVid > cpuVid)
611                                 nbVid = cpuVid;
612
613                         msr.lo = msr.lo & PS_BOTH_VID_OFF;
614                         msr.lo = msr.lo | (u32) ((nbVid) << PS_NB_VID_SHFT);
615                         msr.lo = msr.lo | (u32) ((nbVid) << PS_CPU_VID_SHFT);
616                         wrmsr(PS_REG_BASE + i, msr);
617                 }
618         }
619 }
620
621 static void fixPsNbVidBeforeWR(u32 newNbVid, u32 coreid, u32 dev, u8 pviMode)
622  {
623         msr_t msr;
624         u8 startup_pstate;
625
626         /* This function sets NbVid before the warm reset.
627          *       Get StartupPstate from MSRC001_0071.
628          *       Read Pstate register pointed by [StartupPstate].
629          *       and copy its content to P0 and P1 registers.
630          *       Copy newNbVid to P0[NbVid].
631          *       transition to P1 on all cores,
632          *       then transition to P0 on core 0.
633          *       Wait for MSRC001_0063[CurPstate] = 000b on core 0.
634          * see BKDG rev 3.48  2.4.2.9.1 BIOS NB COF and VID Configuration
635          *                              for SVI and Single-Plane PVI Systems
636          */
637
638         msr = rdmsr(0xc0010071);
639         startup_pstate = (msr.hi >> (32 - 32)) & 0x07;
640
641         /* Copy startup pstate to P1 and P0 MSRs. Set the maxvid for
642          * this node in P0.  Then transition to P1 for corex and P0
643          * for core0.  These setting will be cleared by the warm reset
644          */
645         msr = rdmsr(0xC0010064 + startup_pstate);
646         wrmsr(0xC0010065, msr);
647         wrmsr(0xC0010064, msr);
648
649         /* missing step 2 from BDKG , F3xDC[PstateMaxVal] =
650          * max(1,F3xDC[PstateMaxVal] ) because it would take
651          * synchronization between cores and we don't think
652          * PstatMaxVal is going to be 0 on cold reset anyway ?
653          */
654         if ( ! (pci_read_config32(dev, 0xDC) & (~ PS_MAX_VAL_MASK)) ) {
655            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");
656         };
657
658         msr.lo &= ~0xFE000000;  // clear nbvid
659         msr.lo |= (newNbVid << 25);
660         wrmsr(0xC0010064, msr);
661
662         if (pviMode) { /* single plane*/
663           UpdateSinglePlaneNbVid();
664         }
665
666         // Transition to P1 for all APs and P0 for core0.
667         set_pstate(1);
668
669         if (coreid == 0) {
670              set_pstate(0);
671         }
672
673         /* missing step 7 (restore PstateMax to 0 if needed) because
674          * we skipped step 2
675          */
676
677 }
678
679 static u32 needs_NB_COF_VID_update(void)
680 {
681         u8 nb_cof_vid_update;
682         u8 nodes;
683         u8 i;
684
685         /* If any node has nb_cof_vid_update set all nodes need an update. */
686         nodes = get_nodes();
687         nb_cof_vid_update = 0;
688         for (i = 0; i < nodes; i++) {
689                 u32 cpuRev = mctGetLogicalCPUID(i) ;
690                 u32 nbCofVidUpdateDefined = (cpuRev & (AMD_FAM10_LT_D));
691                 if (nbCofVidUpdateDefined
692                     && (pci_read_config32(NODE_PCI(i, 3), 0x1FC)
693                         & NB_COF_VID_UPDATE_MASK)) {
694                         nb_cof_vid_update = 1;
695                         break;
696                 }
697         }
698         return nb_cof_vid_update;
699 }
700
701 static u32 init_fidvid_core(u32 nodeid, u32 coreid)
702 {
703         device_t dev;
704         u32 vid_max;
705         u32 fid_max = 0;
706         u8 nb_cof_vid_update = needs_NB_COF_VID_update();
707         u8 pvimode;
708         u32 reg1fc;
709
710         /* Steps 1-6 of BIOS NB COF and VID Configuration
711          * for SVI and Single-Plane PVI Systems. BKDG 2.4.2.9 #31116 rev 3.48
712          */
713
714         dev = NODE_PCI(nodeid, 3);
715         pvimode = pci_read_config32(dev, PW_CTL_MISC) & PVI_MODE;
716         reg1fc = pci_read_config32(dev, 0x1FC);
717
718         if (nb_cof_vid_update) {
719                 vid_max = (reg1fc &  SINGLE_PLANE_NB_VID_MASK ) >>  SINGLE_PLANE_NB_VID_SHIFT ;
720                 fid_max = (reg1fc &  SINGLE_PLANE_NB_FID_MASK ) >>  SINGLE_PLANE_NB_FID_SHIFT ;
721
722                 if (!pvimode) { /* SVI, dual power plane */
723                         vid_max = vid_max - ((reg1fc &  DUAL_PLANE_NB_VID_OFF_MASK ) >>  DUAL_PLANE_NB_VID_SHIFT );
724                         fid_max = fid_max +  ((reg1fc &  DUAL_PLANE_NB_FID_OFF_MASK ) >>  DUAL_PLANE_NB_FID_SHIFT );
725                 }
726                 /* write newNbVid to P-state Reg's NbVid always if NbVidUpdatedAll=1 */
727                 fixPsNbVidBeforeWR(vid_max, coreid,dev,pvimode);
728
729                 /* fid setup is handled by the BSP at the end. */
730
731         } else {        /* ! nb_cof_vid_update */
732                 /* Use max values */
733                 if (pvimode)
734                         UpdateSinglePlaneNbVid();
735         }
736
737         return ((nb_cof_vid_update << 16) | (fid_max << 8));
738
739 }
740
741 static void init_fidvid_ap(u32 bsp_apicid, u32 apicid, u32 nodeid, u32 coreid)
742 {
743         u32 send;
744
745         printk(BIOS_DEBUG, "FIDVID on AP: %02x\n", apicid);
746
747         send = init_fidvid_core(nodeid,coreid);
748         send |= (apicid << 24); // ap apicid
749
750         // Send signal to BSP about this AP max fid
751         // This also indicates this AP is ready for warm reset (if required).
752         lapic_write(LAPIC_MSG_REG, send | F10_APSTATE_RESET);
753 }
754
755 static u32 calc_common_fid(u32 fid_packed, u32 fid_packed_new)
756 {
757         u32 fidmax;
758         u32 fidmax_new;
759
760         fidmax = (fid_packed >> 8) & 0xFF;
761
762         fidmax_new = (fid_packed_new >> 8) & 0xFF;
763
764         if (fidmax > fidmax_new) {
765                 fidmax = fidmax_new;
766         }
767
768         fid_packed &= 0xFF << 16;
769         fid_packed |= (fidmax << 8);
770         fid_packed |= fid_packed_new & (0xFF << 16);    // set nb_cof_vid_update
771
772         return fid_packed;
773 }
774
775 static void init_fidvid_bsp_stage1(u32 ap_apicid, void *gp)
776 {
777         u32 readback = 0;
778         u32 timeout = 1;
779
780         struct fidvid_st *fvp = gp;
781         int loop;
782
783         print_debug_fv("Wait for AP stage 1: ap_apicid = ", ap_apicid);
784
785         loop = 100000;
786         while (--loop > 0) {
787                 if (lapic_remote_read(ap_apicid, LAPIC_MSG_REG, &readback) != 0)
788                         continue;
789                 if ((readback & 0x3f) == 1) {
790                         timeout = 0;
791                         break;  /* target ap is in stage 1 */
792                 }
793         }
794
795         if (timeout) {
796                 printk(BIOS_DEBUG, "%s: timed out reading from ap %02x\n",
797                        __func__, ap_apicid);
798                 return;
799         }
800
801         print_debug_fv("\treadback = ", readback);
802
803         fvp->common_fid = calc_common_fid(fvp->common_fid, readback);
804
805         print_debug_fv("\tcommon_fid(packed) = ", fvp->common_fid);
806
807 }
808
809 static void fixPsNbVidAfterWR(u32 newNbVid, u8 NbVidUpdatedAll,u8 pviMode)
810 {
811         msr_t msr;
812         u8 i;
813         u8 StartupPstate;
814
815         /* BKDG 2.4.2.9.1 11-12
816          * This function copies newNbVid to NbVid bits in P-state
817          * Registers[4:0] if its NbDid bit=0, and IddValue!=0 in case of
818          * NbVidUpdatedAll =0 or copies newNbVid to NbVid bits in
819          * P-state Registers[4:0] if its IddValue!=0 in case of
820          * NbVidUpdatedAll=1. Then transition to StartPstate.
821          */
822
823         /* write newNbVid to P-state Reg's NbVid if its NbDid=0 */
824         for (i = 0; i < 5; i++) {
825                 msr = rdmsr(0xC0010064 + i);
826                 /*  NbDid (bit 22 of P-state Reg) == 0  or NbVidUpdatedAll = 1 */
827                 if (   (msr.hi & PS_IDD_VALUE_MASK)
828                     && (msr.hi & PS_EN_MASK)
829                     &&(((msr.lo & PS_NB_DID_MASK) == 0) || NbVidUpdatedAll)) {
830                         msr.lo &= PS_NB_VID_M_OFF;
831                         msr.lo |= (newNbVid & 0x7F) << PS_NB_VID_SHFT;
832                         wrmsr(0xC0010064 + i, msr);
833                 }
834         }
835
836         /* Not documented. Would overwrite Nb_Vids just copied
837          * should we just update cpu_vid or nothing at all ?
838          */
839         if (pviMode) { //single plane
840             UpdateSinglePlaneNbVid();
841         }
842         /* For each core in the system, transition all cores to StartupPstate */
843         msr = rdmsr(0xC0010071);
844         StartupPstate = msr.hi & 0x07;
845
846         /* Set and wait for StartupPstate to set. */
847         set_pstate(StartupPstate);
848
849 }
850
851 static void finalPstateChange(void)
852 {
853         /* Enble P0 on all cores for best performance.
854          * Linux can slow them down later if need be.
855          * It is safe since they will be in C1 halt
856          * most of the time anyway.
857          */
858         set_pstate(0);
859 }
860
861 static void init_fidvid_stage2(u32 apicid, u32 nodeid)
862 {
863         msr_t msr;
864         device_t dev;
865         u32 reg1fc;
866         u32 dtemp;
867         u32 nbvid;
868         u8 nb_cof_vid_update = needs_NB_COF_VID_update();
869         u8 NbVidUpdateAll;
870         u8 pvimode;
871
872         /* After warm reset finish the fid/vid setup for all cores. */
873
874         /* If any node has nb_cof_vid_update set all nodes need an update. */
875
876         dev = NODE_PCI(nodeid, 3);
877         pvimode = (pci_read_config32(dev, 0xA0) >> 8) & 1;
878         reg1fc = pci_read_config32(dev, 0x1FC);
879         nbvid = (reg1fc >> 7) & 0x7F;
880         NbVidUpdateAll = (reg1fc >> 1) & 1;
881
882         if (nb_cof_vid_update) {
883                 if (!pvimode) { /* SVI */
884                         nbvid = nbvid - ((reg1fc >> 17) & 0x1F);
885                 }
886                 /* write newNbVid to P-state Reg's NbVid if its NbDid=0 */
887                 fixPsNbVidAfterWR(nbvid, NbVidUpdateAll,pvimode);
888         } else {                /* !nb_cof_vid_update */
889                 if (pvimode)
890                         UpdateSinglePlaneNbVid();
891         }
892         dtemp = pci_read_config32(dev, 0xA0);
893         dtemp &= PLLLOCK_OFF;
894         dtemp |= PLLLOCK_DFT_L;
895         pci_write_config32(dev, 0xA0, dtemp);
896
897         dualPlaneOnly(dev);
898         applyBoostFIDOffset(dev);
899         enableNbPState1(dev);
900
901         finalPstateChange();
902
903         /* Set TSC to tick at the P0 ndfid rate */
904         msr = rdmsr(HWCR);
905         msr.lo |= 1 << 24;
906         wrmsr(HWCR, msr);
907 }
908
909
910 #if CONFIG_SET_FIDVID_STORE_AP_APICID_AT_FIRST
911 struct ap_apicid_st {
912         u32 num;
913         // it could use 256 bytes for 64 node quad core system
914         u8 apicid[NODE_NUMS * 4];
915 };
916
917 static void store_ap_apicid(unsigned ap_apicid, void *gp)
918 {
919         struct ap_apicid_st *p = gp;
920
921         p->apicid[p->num++] = ap_apicid;
922
923 }
924 #endif
925
926
927 static int init_fidvid_bsp(u32 bsp_apicid, u32 nodes)
928 {
929 #if CONFIG_SET_FIDVID_STORE_AP_APICID_AT_FIRST
930         struct ap_apicid_st ap_apicidx;
931         u32 i;
932 #endif
933         struct fidvid_st fv;
934
935         printk(BIOS_DEBUG, "FIDVID on BSP, APIC_id: %02x\n", bsp_apicid);
936
937         /* Steps 1-6 of BIOS NB COF and VID Configuration
938          * for SVI and Single-Plane PVI Systems.
939          */
940
941         fv.common_fid = init_fidvid_core(0,0);
942
943         print_debug_fv("BSP fid = ", fv.common_fid);
944
945 #if CONFIG_SET_FIDVID_STORE_AP_APICID_AT_FIRST && !CONFIG_SET_FIDVID_CORE0_ONLY
946         /* For all APs (We know the APIC ID of all APs even when the APIC ID
947            is lifted) remote read from AP LAPIC_MSG_REG about max fid.
948            Then calculate the common max fid that can be used for all
949            APs and BSP */
950         ap_apicidx.num = 0;
951
952         for_each_ap(bsp_apicid, CONFIG_SET_FIDVID_CORE_RANGE, store_ap_apicid, &ap_apicidx);
953
954         for (i = 0; i < ap_apicidx.num; i++) {
955                 init_fidvid_bsp_stage1(ap_apicidx.apicid[i], &fv);
956         }
957 #else
958         for_each_ap(bsp_apicid, CONFIG_SET_FIDVID_CORE0_ONLY, init_fidvid_bsp_stage1, &fv);
959 #endif
960
961         print_debug_fv("common_fid = ", fv.common_fid);
962
963         if (fv.common_fid & (1 << 16)) {        /* check nb_cof_vid_update */
964
965                 // Enable the common fid and other settings.
966                 enable_fid_change((fv.common_fid >> 8) & 0x1F);
967
968                 // nbfid change need warm reset, so reset at first
969                 return 1;
970         }
971
972         return 0;               // No FID/VID changes. Don't reset
973 }
974 #endif