Hardware/CPU/AMD10CPU.cs
author moel.mich
Sat, 16 Apr 2011 19:26:20 +0000
changeset 273 2054d5dcb680
parent 271 8635fa73eacc
child 279 6bce967ba1b5
permissions -rw-r--r--
A first correction for reading core and bus clocks on AMD family 14h CPUs.
     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-2011
    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.IO;
    43 using System.Runtime.InteropServices;
    44 using System.Text;
    45 using System.Threading;
    46 
    47 namespace OpenHardwareMonitor.Hardware.CPU {
    48 
    49   internal sealed class AMD10CPU : AMDCPU {
    50 
    51     private readonly Sensor coreTemperature;
    52     private readonly Sensor[] coreClocks;
    53     private readonly Sensor busClock;
    54       
    55     private const uint PERF_CTL_0 = 0xC0010000;
    56     private const uint PERF_CTR_0 = 0xC0010004;
    57     private const uint P_STATE_0 = 0xC0010064;
    58     private const uint COFVID_STATUS = 0xC0010071;
    59 
    60     private const byte MISCELLANEOUS_CONTROL_FUNCTION = 3;
    61     private const ushort FAMILY_10H_MISCELLANEOUS_CONTROL_DEVICE_ID = 0x1203;
    62     private const ushort FAMILY_11H_MISCELLANEOUS_CONTROL_DEVICE_ID = 0x1303;
    63     private const ushort FAMILY_14H_MISCELLANEOUS_CONTROL_DEVICE_ID = 0x1703; 
    64     private const uint REPORTED_TEMPERATURE_CONTROL_REGISTER = 0xA4;
    65     private const uint CLOCK_POWER_TIMING_CONTROL_0_REGISTER = 0xD4;
    66 
    67     private readonly uint miscellaneousControlAddress;
    68     private readonly ushort miscellaneousControlDeviceId;
    69 
    70     private readonly FileStream temperatureStream;
    71 
    72     private double timeStampCounterMultiplier;
    73 
    74     public AMD10CPU(int processorIndex, CPUID[][] cpuid, ISettings settings)
    75       : base(processorIndex, cpuid, settings) 
    76     {            
    77       // AMD family 10h/11h processors support only one temperature sensor
    78       coreTemperature = new Sensor(
    79         "Core" + (coreCount > 1 ? " #1 - #" + coreCount : ""), 0,
    80         SensorType.Temperature, this, new [] {
    81             new ParameterDescription("Offset [°C]", "Temperature offset.", 0)
    82           }, settings);
    83 
    84       switch (family) {
    85         case 0x10: miscellaneousControlDeviceId =
    86           FAMILY_10H_MISCELLANEOUS_CONTROL_DEVICE_ID; break;
    87         case 0x11: miscellaneousControlDeviceId =
    88           FAMILY_11H_MISCELLANEOUS_CONTROL_DEVICE_ID; break;
    89         case 0x14: miscellaneousControlDeviceId = 
    90           FAMILY_14H_MISCELLANEOUS_CONTROL_DEVICE_ID; break;
    91         default: miscellaneousControlDeviceId = 0; break;
    92       }
    93 
    94       // get the pci address for the Miscellaneous Control registers 
    95       miscellaneousControlAddress = GetPciAddress(
    96         MISCELLANEOUS_CONTROL_FUNCTION, miscellaneousControlDeviceId);        
    97 
    98       busClock = new Sensor("Bus Speed", 0, SensorType.Clock, this, settings);
    99       coreClocks = new Sensor[coreCount];
   100       for (int i = 0; i < coreClocks.Length; i++) {
   101         coreClocks[i] = new Sensor(CoreString(i), i + 1, SensorType.Clock,
   102           this, settings);
   103         if (HasTimeStampCounter)
   104           ActivateSensor(coreClocks[i]);
   105       }
   106 
   107       // set affinity to the first thread for all frequency estimations     
   108       ulong mask = ThreadAffinity.Set(1UL << cpuid[0][0].Thread);
   109 
   110       uint ctlEax, ctlEdx;
   111       Ring0.Rdmsr(PERF_CTL_0, out ctlEax, out ctlEdx);
   112       uint ctrEax, ctrEdx;
   113       Ring0.Rdmsr(PERF_CTR_0, out ctrEax, out ctrEdx);
   114 
   115       timeStampCounterMultiplier = estimateTimeStampCounterMultiplier();
   116 
   117       // restore the performance counter registers
   118       Ring0.Wrmsr(PERF_CTL_0, ctlEax, ctlEdx);
   119       Ring0.Wrmsr(PERF_CTR_0, ctrEax, ctrEdx);
   120 
   121       // restore the thread affinity.
   122       ThreadAffinity.Set(mask);
   123 
   124       // the file reader for lm-sensors support on Linux
   125       temperatureStream = null;
   126       int p = (int)Environment.OSVersion.Platform;
   127       if ((p == 4) || (p == 128)) {
   128         string[] devicePaths = Directory.GetDirectories("/sys/class/hwmon/");
   129         foreach (string path in devicePaths) {
   130           string name = null;
   131           try {
   132             using (StreamReader reader = new StreamReader(path + "/device/name"))
   133               name = reader.ReadLine();
   134           } catch (IOException) { }
   135           switch (name) {
   136             case "k10temp":
   137               temperatureStream = new FileStream(path + "/device/temp1_input", 
   138                 FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
   139               break;
   140           }
   141         }
   142       }
   143 
   144       Update();                   
   145     }
   146 
   147     private double estimateTimeStampCounterMultiplier() {
   148       // preload the function
   149       estimateTimeStampCounterMultiplier(0);
   150       estimateTimeStampCounterMultiplier(0);
   151 
   152       // estimate the multiplier
   153       List<double> estimate = new List<double>(3);
   154       for (int i = 0; i < 3; i++)
   155         estimate.Add(estimateTimeStampCounterMultiplier(0.025));
   156       estimate.Sort();
   157       return estimate[1];
   158     }
   159 
   160     private double estimateTimeStampCounterMultiplier(double timeWindow) {
   161       uint eax, edx;
   162      
   163       // select event "076h CPU Clocks not Halted" and enable the counter
   164       Ring0.Wrmsr(PERF_CTL_0,
   165         (1 << 22) | // enable performance counter
   166         (1 << 17) | // count events in user mode
   167         (1 << 16) | // count events in operating-system mode
   168         0x76, 0x00000000);
   169 
   170       // set the counter to 0
   171       Ring0.Wrmsr(PERF_CTR_0, 0, 0);
   172 
   173       long ticks = (long)(timeWindow * Stopwatch.Frequency);
   174       uint lsbBegin, msbBegin, lsbEnd, msbEnd;      
   175 
   176       long timeBegin = Stopwatch.GetTimestamp() +
   177         (long)Math.Ceiling(0.001 * ticks);
   178       long timeEnd = timeBegin + ticks;
   179       while (Stopwatch.GetTimestamp() < timeBegin) { }
   180       Ring0.Rdmsr(PERF_CTR_0, out lsbBegin, out msbBegin);
   181       while (Stopwatch.GetTimestamp() < timeEnd) { }
   182       Ring0.Rdmsr(PERF_CTR_0, out lsbEnd, out msbEnd);
   183 
   184       Ring0.Rdmsr(COFVID_STATUS, out eax, out edx);
   185       double coreMultiplier;
   186       if (family == 0x14) {               
   187         uint divisorIdMSD = (eax >> 4) & 0x1F;
   188         uint divisorIdLSD = eax & 0xF;
   189         uint value = 0;
   190         Ring0.ReadPciConfig(miscellaneousControlAddress,
   191           CLOCK_POWER_TIMING_CONTROL_0_REGISTER, out value);
   192         uint frequencyId = value & 0x1F;
   193 
   194         coreMultiplier = 
   195           MultiplierFromIDs(divisorIdMSD, divisorIdLSD, frequencyId);
   196       } else {
   197         uint cpuDid = (eax >> 6) & 7;
   198         uint cpuFid = eax & 0x1F;
   199         coreMultiplier = MultiplierFromIDs(cpuDid, cpuFid);
   200       }
   201       ulong countBegin = ((ulong)msbBegin << 32) | lsbBegin;
   202       ulong countEnd = ((ulong)msbEnd << 32) | lsbEnd;
   203 
   204       double coreFrequency = 1e-6 * 
   205         (((double)(countEnd - countBegin)) * Stopwatch.Frequency) /
   206         (timeEnd - timeBegin);
   207 
   208       double busFrequency = coreFrequency / coreMultiplier;
   209       return 0.25 * Math.Round(4 * TimeStampCounterFrequency / busFrequency);
   210     }
   211 
   212     protected override uint[] GetMSRs() {
   213       return new uint[] { PERF_CTL_0, PERF_CTR_0, P_STATE_0, COFVID_STATUS };
   214     }
   215 
   216     public override string GetReport() {
   217       StringBuilder r = new StringBuilder();
   218       r.Append(base.GetReport());
   219 
   220       r.Append("Miscellaneous Control Address: 0x");
   221       r.AppendLine((miscellaneousControlAddress).ToString("X",
   222         CultureInfo.InvariantCulture));
   223       r.Append("Time Stamp Counter Multiplier: ");
   224       r.AppendLine(timeStampCounterMultiplier.ToString(
   225         CultureInfo.InvariantCulture));
   226       if (family == 0x14) {
   227         uint value = 0;
   228         Ring0.ReadPciConfig(miscellaneousControlAddress,
   229           CLOCK_POWER_TIMING_CONTROL_0_REGISTER, out value);
   230         r.Append("PCI Register D18F3xD4: ");
   231         r.AppendLine(value.ToString("X8", CultureInfo.InvariantCulture));
   232       }
   233       r.AppendLine();
   234 
   235       return r.ToString();
   236     }
   237 
   238     // calculate the multiplier for family 10h based on Did and Fid
   239     private static double MultiplierFromIDs(uint divisorID, uint frequencyID) {
   240       return 0.5 * (frequencyID + 0x10) / (1 << (int)divisorID);
   241     }
   242 
   243     // calculate the multiplier for family 14h based on DidMSD, DidLSD and Fid
   244     private static double MultiplierFromIDs(uint divisorIdMSD, 
   245       uint divisorIdLSD, uint frequencyId) 
   246     {
   247       return (frequencyId + 0x10) / (divisorIdMSD + (divisorIdLSD * 0.25) + 1);
   248     }
   249 
   250     private string ReadFirstLine(Stream stream) {
   251       StringBuilder sb = new StringBuilder();
   252       try {
   253         stream.Seek(0, SeekOrigin.Begin);
   254         int b = stream.ReadByte();
   255         while (b != -1 && b != 10) {
   256           sb.Append((char)b);
   257           b = stream.ReadByte();
   258         }
   259       } catch { }
   260       return sb.ToString();
   261     }
   262 
   263     public override void Update() {
   264       base.Update();
   265 
   266       if (temperatureStream == null) {
   267         if (miscellaneousControlAddress != Ring0.InvalidPciAddress) {
   268           uint value;
   269           if (Ring0.ReadPciConfig(miscellaneousControlAddress,
   270             REPORTED_TEMPERATURE_CONTROL_REGISTER, out value)) {
   271             coreTemperature.Value = ((value >> 21) & 0x7FF) / 8.0f +
   272               coreTemperature.Parameters[0].Value;
   273             ActivateSensor(coreTemperature);
   274           } else {
   275             DeactivateSensor(coreTemperature);
   276           }
   277         }
   278       } else {
   279         string s = ReadFirstLine(temperatureStream);
   280         try {
   281           coreTemperature.Value = 0.001f *
   282             long.Parse(s, CultureInfo.InvariantCulture);
   283           ActivateSensor(coreTemperature);
   284         } catch {
   285           DeactivateSensor(coreTemperature);
   286         }        
   287       }
   288 
   289       if (HasTimeStampCounter) {
   290         double newBusClock = 0;
   291 
   292         for (int i = 0; i < coreClocks.Length; i++) {
   293           Thread.Sleep(1);
   294 
   295           uint curEax, curEdx;
   296           if (Ring0.RdmsrTx(COFVID_STATUS, out curEax, out curEdx,
   297             1UL << cpuid[i][0].Thread)) 
   298           {
   299             double multiplier;
   300             if (family == 0x14) {
   301               uint divisorIdMSD = (curEax >> 4) & 0x1F;
   302               uint divisorIdLSD = curEax & 0xF;
   303               uint value = 0;
   304               Ring0.ReadPciConfig(miscellaneousControlAddress,
   305                 CLOCK_POWER_TIMING_CONTROL_0_REGISTER, out value);
   306               uint frequencyId = value & 0x1F;
   307               multiplier =
   308                 MultiplierFromIDs(divisorIdMSD, divisorIdLSD, frequencyId);
   309             } else {
   310               // 8:6 CpuDid: current core divisor ID
   311               // 5:0 CpuFid: current core frequency ID
   312               uint cpuDid = (curEax >> 6) & 7;
   313               uint cpuFid = curEax & 0x1F;
   314               multiplier = MultiplierFromIDs(cpuDid, cpuFid);
   315             }
   316 
   317             coreClocks[i].Value = 
   318               (float)(multiplier * TimeStampCounterFrequency / 
   319               timeStampCounterMultiplier);
   320             newBusClock = 
   321               (float)(TimeStampCounterFrequency / timeStampCounterMultiplier);
   322           } else {
   323             coreClocks[i].Value = (float)TimeStampCounterFrequency;
   324           }
   325         }
   326 
   327         if (newBusClock > 0) {
   328           this.busClock.Value = (float)newBusClock;
   329           ActivateSensor(this.busClock);
   330         }
   331       }
   332     }
   333 
   334     public override void Close() {
   335       if (temperatureStream != null) {
   336         temperatureStream.Close();
   337       }
   338     }
   339   }
   340 }