Hardware/CPU/AMD10CPU.cs
author moel.mich
Sun, 10 Oct 2010 16:57:11 +0000
changeset 219 ce04404774d6
parent 201 958e9fe8afdf
child 236 763675f19ff4
permissions -rw-r--r--
Reading the timeStampCounterMultiplier right at the beginning when the time stamp counter is estimated instead of reading it at each update. Refactored the IntelCPU code a bit.
     1 /*
     2   
     3   Version: MPL 1.1/GPL 2.0/LGPL 2.1
     4 
     5   The contents of this file are subject to the Mozilla Public License Version
     6   1.1 (the "License"); you may not use this file except in compliance with
     7   the License. You may obtain a copy of the License at
     8  
     9   http://www.mozilla.org/MPL/
    10 
    11   Software distributed under the License is distributed on an "AS IS" basis,
    12   WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
    13   for the specific language governing rights and limitations under the License.
    14 
    15   The Original Code is the Open Hardware Monitor code.
    16 
    17   The Initial Developer of the Original Code is 
    18   Michael Möller <m.moeller@gmx.ch>.
    19   Portions created by the Initial Developer are Copyright (C) 2009-2010
    20   the Initial Developer. All Rights Reserved.
    21 
    22   Contributor(s):
    23 
    24   Alternatively, the contents of this file may be used under the terms of
    25   either the GNU General Public License Version 2 or later (the "GPL"), or
    26   the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
    27   in which case the provisions of the GPL or the LGPL are applicable instead
    28   of those above. If you wish to allow use of your version of this file only
    29   under the terms of either the GPL or the LGPL, and not to allow others to
    30   use your version of this file under the terms of the MPL, indicate your
    31   decision by deleting the provisions above and replace them with the notice
    32   and other provisions required by the GPL or the LGPL. If you do not delete
    33   the provisions above, a recipient may use your version of this file under
    34   the terms of any one of the MPL, the GPL or the LGPL.
    35  
    36 */
    37 
    38 using System;
    39 using System.Collections.Generic;
    40 using System.Diagnostics;
    41 using System.Globalization;
    42 using System.Runtime.InteropServices;
    43 using System.Text;
    44 using System.Threading;
    45 
    46 namespace OpenHardwareMonitor.Hardware.CPU {
    47 
    48   internal sealed class AMD10CPU : AMDCPU {
    49 
    50     private readonly Sensor coreTemperature;
    51     private readonly Sensor[] coreClocks;
    52     private readonly Sensor busClock;
    53       
    54     private const uint PERF_CTL_0 = 0xC0010000;
    55     private const uint PERF_CTR_0 = 0xC0010004;
    56     private const uint P_STATE_0 = 0xC0010064;
    57     private const uint COFVID_STATUS = 0xC0010071;
    58 
    59     private const byte MISCELLANEOUS_CONTROL_FUNCTION = 3;
    60     private const ushort MISCELLANEOUS_CONTROL_DEVICE_ID = 0x1203;
    61     private const uint REPORTED_TEMPERATURE_CONTROL_REGISTER = 0xA4;
    62 
    63     private readonly uint miscellaneousControlAddress;
    64 
    65     private double timeStampCounterMultiplier;
    66 
    67     public AMD10CPU(int processorIndex, CPUID[][] cpuid, ISettings settings)
    68       : base(processorIndex, cpuid, settings) 
    69     {            
    70       // AMD family 10h processors support only one temperature sensor
    71       coreTemperature = new Sensor(
    72         "Core" + (coreCount > 1 ? " #1 - #" + coreCount : ""), 0,
    73         SensorType.Temperature, this, new [] {
    74             new ParameterDescription("Offset [°C]", "Temperature offset.", 0)
    75           }, settings);
    76 
    77       // get the pci address for the Miscellaneous Control registers 
    78       miscellaneousControlAddress = GetPciAddress(
    79         MISCELLANEOUS_CONTROL_FUNCTION, MISCELLANEOUS_CONTROL_DEVICE_ID);
    80 
    81       busClock = new Sensor("Bus Speed", 0, SensorType.Clock, this, settings);
    82       coreClocks = new Sensor[coreCount];
    83       for (int i = 0; i < coreClocks.Length; i++) {
    84         coreClocks[i] = new Sensor(CoreString(i), i + 1, SensorType.Clock,
    85           this, settings);
    86         if (HasTimeStampCounter)
    87           ActivateSensor(coreClocks[i]);
    88       }
    89 
    90       // set affinity to the first thread for all frequency estimations
    91       IntPtr thread = NativeMethods.GetCurrentThread();
    92       UIntPtr mask = NativeMethods.SetThreadAffinityMask(thread,
    93         (UIntPtr)(1L << cpuid[0][0].Thread));
    94 
    95       uint ctlEax, ctlEdx;
    96       WinRing0.Rdmsr(PERF_CTL_0, out ctlEax, out ctlEdx);
    97       uint ctrEax, ctrEdx;
    98       WinRing0.Rdmsr(PERF_CTR_0, out ctrEax, out ctrEdx);
    99 
   100       timeStampCounterMultiplier = estimateTimeStampCounterMultiplier();
   101 
   102       // restore the performance counter registers
   103       WinRing0.Wrmsr(PERF_CTL_0, ctlEax, ctlEdx);
   104       WinRing0.Wrmsr(PERF_CTR_0, ctrEax, ctrEdx);
   105 
   106       // restore the thread affinity.
   107       NativeMethods.SetThreadAffinityMask(thread, mask);
   108 
   109       Update();                   
   110     }
   111 
   112     private double estimateTimeStampCounterMultiplier() {
   113       // preload the function
   114       estimateTimeStampCounterMultiplier(0);
   115       estimateTimeStampCounterMultiplier(0);
   116 
   117       // estimate the multiplier
   118       List<double> estimate = new List<double>(3);
   119       for (int i = 0; i < 3; i++)
   120         estimate.Add(estimateTimeStampCounterMultiplier(0.025));
   121       estimate.Sort();
   122       return estimate[1];
   123     }
   124 
   125     private double estimateTimeStampCounterMultiplier(double timeWindow) {
   126       uint eax, edx;
   127      
   128       // select event "076h CPU Clocks not Halted" and enable the counter
   129       WinRing0.Wrmsr(PERF_CTL_0,
   130         (1 << 22) | // enable performance counter
   131         (1 << 17) | // count events in user mode
   132         (1 << 16) | // count events in operating-system mode
   133         0x76, 0x00000000);
   134 
   135       // set the counter to 0
   136       WinRing0.Wrmsr(PERF_CTR_0, 0, 0);
   137 
   138       long ticks = (long)(timeWindow * Stopwatch.Frequency);
   139       uint lsbBegin, msbBegin, lsbEnd, msbEnd;
   140 
   141       long timeBegin = Stopwatch.GetTimestamp() +
   142         (long)Math.Ceiling(0.001 * ticks);
   143       long timeEnd = timeBegin + ticks;
   144       while (Stopwatch.GetTimestamp() < timeBegin) { }
   145       WinRing0.Rdmsr(PERF_CTR_0, out lsbBegin, out msbBegin);
   146       while (Stopwatch.GetTimestamp() < timeEnd) { }
   147       WinRing0.Rdmsr(PERF_CTR_0, out lsbEnd, out msbEnd);
   148 
   149       WinRing0.Rdmsr(COFVID_STATUS, out eax, out edx);
   150       uint cpuDid = (eax >> 6) & 7;
   151       uint cpuFid = eax & 0x1F;
   152       double coreMultiplier = MultiplierFromIDs(cpuDid, cpuFid);
   153 
   154       ulong countBegin = ((ulong)msbBegin << 32) | lsbBegin;
   155       ulong countEnd = ((ulong)msbEnd << 32) | lsbEnd;
   156 
   157       double coreFrequency = 1e-6 * 
   158         (((double)(countEnd - countBegin)) * Stopwatch.Frequency) /
   159         (timeEnd - timeBegin);
   160 
   161       double busFrequency = coreFrequency / coreMultiplier;
   162       return 0.5 * Math.Round(2 * TimeStampCounterFrequency / busFrequency);
   163     }
   164 
   165     protected override uint[] GetMSRs() {
   166       return new uint[] { PERF_CTL_0, PERF_CTR_0, P_STATE_0, COFVID_STATUS };
   167     }
   168 
   169     public override string GetReport() {
   170       StringBuilder r = new StringBuilder();
   171       r.Append(base.GetReport());
   172 
   173       r.Append("Miscellaneous Control Address: 0x");
   174       r.AppendLine((miscellaneousControlAddress).ToString("X",
   175         CultureInfo.InvariantCulture));
   176       r.Append("Time Stamp Counter Multiplier: ");
   177       r.AppendLine(timeStampCounterMultiplier.ToString(
   178         CultureInfo.InvariantCulture));
   179       r.AppendLine();
   180 
   181       return r.ToString();
   182     }
   183 
   184     private static double MultiplierFromIDs(uint divisorID, uint frequencyID) {
   185       return 0.5 * (frequencyID + 0x10) / (1 << (int)divisorID);
   186     }
   187 
   188     public override void Update() {
   189       base.Update();
   190 
   191       if (miscellaneousControlAddress != WinRing0.InvalidPciAddress) {
   192         uint value;
   193         if (WinRing0.ReadPciConfigDwordEx(miscellaneousControlAddress,
   194           REPORTED_TEMPERATURE_CONTROL_REGISTER, out value)) {
   195           coreTemperature.Value = ((value >> 21) & 0x7FF) / 8.0f +
   196             coreTemperature.Parameters[0].Value;
   197           ActivateSensor(coreTemperature);
   198         } else {
   199           DeactivateSensor(coreTemperature);
   200         }
   201       }
   202 
   203       if (HasTimeStampCounter) {
   204         double newBusClock = 0;
   205 
   206         for (int i = 0; i < coreClocks.Length; i++) {
   207           Thread.Sleep(1);
   208 
   209           uint curEax, curEdx;
   210           if (WinRing0.RdmsrTx(COFVID_STATUS, out curEax, out curEdx,
   211             (UIntPtr)(1L << cpuid[i][0].Thread))) 
   212           {
   213             // 8:6 CpuDid: current core divisor ID
   214             // 5:0 CpuFid: current core frequency ID
   215             uint cpuDid = (curEax >> 6) & 7;
   216             uint cpuFid = curEax & 0x1F;
   217             double multiplier = MultiplierFromIDs(cpuDid, cpuFid);
   218 
   219             coreClocks[i].Value = 
   220               (float)(multiplier * TimeStampCounterFrequency / 
   221               timeStampCounterMultiplier);
   222             newBusClock = 
   223               (float)(TimeStampCounterFrequency / timeStampCounterMultiplier);
   224           } else {
   225             coreClocks[i].Value = (float)TimeStampCounterFrequency;
   226           }
   227         }
   228 
   229         if (newBusClock > 0) {
   230           this.busClock.Value = (float)newBusClock;
   231           ActivateSensor(this.busClock);
   232         }
   233       }
   234     }
   235 
   236     private static class NativeMethods {
   237       private const string KERNEL = "kernel32.dll";
   238 
   239       [DllImport(KERNEL, CallingConvention = CallingConvention.Winapi)]
   240       public static extern UIntPtr
   241         SetThreadAffinityMask(IntPtr handle, UIntPtr mask);
   242 
   243       [DllImport(KERNEL, CallingConvention = CallingConvention.Winapi)]
   244       public static extern IntPtr GetCurrentThread();
   245     }
   246   }
   247 }