Hardware/CPU/AMD10CPU.cs
author moel.mich
Sun, 10 Apr 2011 20:22:20 +0000
changeset 267 c26ff31e7b54
parent 251 49c38a2958c8
child 268 844ba72c11de
permissions -rw-r--r--
Fixed the tree view row height on Linux.
     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.Runtime.InteropServices;
    43 using System.Text;
    44 using System.Threading;
    45 using System.IO;
    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 uint REPORTED_TEMPERATURE_CONTROL_REGISTER = 0xA4;
    64 
    65     private readonly uint miscellaneousControlAddress;
    66     private readonly ushort miscellaneousControlDeviceId;
    67 
    68     private readonly StreamReader temperatureReader;
    69 
    70     private double timeStampCounterMultiplier;
    71 
    72     public AMD10CPU(int processorIndex, CPUID[][] cpuid, ISettings settings)
    73       : base(processorIndex, cpuid, settings) 
    74     {            
    75       // AMD family 10h/11h processors support only one temperature sensor
    76       coreTemperature = new Sensor(
    77         "Core" + (coreCount > 1 ? " #1 - #" + coreCount : ""), 0,
    78         SensorType.Temperature, this, new [] {
    79             new ParameterDescription("Offset [°C]", "Temperature offset.", 0)
    80           }, settings);
    81 
    82       switch (family) {
    83         case 0x10: miscellaneousControlDeviceId =
    84           FAMILY_10H_MISCELLANEOUS_CONTROL_DEVICE_ID; break;
    85         case 0x11: miscellaneousControlDeviceId =
    86           FAMILY_11H_MISCELLANEOUS_CONTROL_DEVICE_ID; break;
    87         default: miscellaneousControlDeviceId = 0; break;
    88       }
    89 
    90       // get the pci address for the Miscellaneous Control registers 
    91       miscellaneousControlAddress = GetPciAddress(
    92         MISCELLANEOUS_CONTROL_FUNCTION, miscellaneousControlDeviceId);        
    93 
    94       busClock = new Sensor("Bus Speed", 0, SensorType.Clock, this, settings);
    95       coreClocks = new Sensor[coreCount];
    96       for (int i = 0; i < coreClocks.Length; i++) {
    97         coreClocks[i] = new Sensor(CoreString(i), i + 1, SensorType.Clock,
    98           this, settings);
    99         if (HasTimeStampCounter)
   100           ActivateSensor(coreClocks[i]);
   101       }
   102 
   103       // set affinity to the first thread for all frequency estimations     
   104       ulong mask = ThreadAffinity.Set(1UL << cpuid[0][0].Thread);
   105 
   106       uint ctlEax, ctlEdx;
   107       Ring0.Rdmsr(PERF_CTL_0, out ctlEax, out ctlEdx);
   108       uint ctrEax, ctrEdx;
   109       Ring0.Rdmsr(PERF_CTR_0, out ctrEax, out ctrEdx);
   110 
   111       timeStampCounterMultiplier = estimateTimeStampCounterMultiplier();
   112 
   113       // restore the performance counter registers
   114       Ring0.Wrmsr(PERF_CTL_0, ctlEax, ctlEdx);
   115       Ring0.Wrmsr(PERF_CTR_0, ctrEax, ctrEdx);
   116 
   117       // restore the thread affinity.
   118       ThreadAffinity.Set(mask);
   119 
   120       // the file reader for lm-sensors support on Linux
   121       temperatureReader = null;
   122       int p = (int)Environment.OSVersion.Platform;
   123       if ((p == 4) || (p == 128)) {
   124         string[] devicePaths = Directory.GetDirectories("/sys/class/hwmon/");
   125         foreach (string path in devicePaths) {
   126           string name = null;
   127           try {
   128             using (StreamReader reader = new StreamReader(path + "/device/name"))
   129               name = reader.ReadLine();
   130           } catch (IOException) { }
   131           switch (name) {
   132             case "k10temp":
   133               temperatureReader = new StreamReader(path + "/device/temp1_input");
   134               break;
   135           }
   136         }
   137       }
   138 
   139       Update();                   
   140     }
   141 
   142     private double estimateTimeStampCounterMultiplier() {
   143       // preload the function
   144       estimateTimeStampCounterMultiplier(0);
   145       estimateTimeStampCounterMultiplier(0);
   146 
   147       // estimate the multiplier
   148       List<double> estimate = new List<double>(3);
   149       for (int i = 0; i < 3; i++)
   150         estimate.Add(estimateTimeStampCounterMultiplier(0.025));
   151       estimate.Sort();
   152       return estimate[1];
   153     }
   154 
   155     private double estimateTimeStampCounterMultiplier(double timeWindow) {
   156       uint eax, edx;
   157      
   158       // select event "076h CPU Clocks not Halted" and enable the counter
   159       Ring0.Wrmsr(PERF_CTL_0,
   160         (1 << 22) | // enable performance counter
   161         (1 << 17) | // count events in user mode
   162         (1 << 16) | // count events in operating-system mode
   163         0x76, 0x00000000);
   164 
   165       // set the counter to 0
   166       Ring0.Wrmsr(PERF_CTR_0, 0, 0);
   167 
   168       long ticks = (long)(timeWindow * Stopwatch.Frequency);
   169       uint lsbBegin, msbBegin, lsbEnd, msbEnd;
   170 
   171       long timeBegin = Stopwatch.GetTimestamp() +
   172         (long)Math.Ceiling(0.001 * ticks);
   173       long timeEnd = timeBegin + ticks;
   174       while (Stopwatch.GetTimestamp() < timeBegin) { }
   175       Ring0.Rdmsr(PERF_CTR_0, out lsbBegin, out msbBegin);
   176       while (Stopwatch.GetTimestamp() < timeEnd) { }
   177       Ring0.Rdmsr(PERF_CTR_0, out lsbEnd, out msbEnd);
   178 
   179       Ring0.Rdmsr(COFVID_STATUS, out eax, out edx);
   180       uint cpuDid = (eax >> 6) & 7;
   181       uint cpuFid = eax & 0x1F;
   182       double coreMultiplier = MultiplierFromIDs(cpuDid, cpuFid);
   183 
   184       ulong countBegin = ((ulong)msbBegin << 32) | lsbBegin;
   185       ulong countEnd = ((ulong)msbEnd << 32) | lsbEnd;
   186 
   187       double coreFrequency = 1e-6 * 
   188         (((double)(countEnd - countBegin)) * Stopwatch.Frequency) /
   189         (timeEnd - timeBegin);
   190 
   191       double busFrequency = coreFrequency / coreMultiplier;
   192       return 0.5 * Math.Round(2 * TimeStampCounterFrequency / busFrequency);
   193     }
   194 
   195     protected override uint[] GetMSRs() {
   196       return new uint[] { PERF_CTL_0, PERF_CTR_0, P_STATE_0, COFVID_STATUS };
   197     }
   198 
   199     public override string GetReport() {
   200       StringBuilder r = new StringBuilder();
   201       r.Append(base.GetReport());
   202 
   203       r.Append("Miscellaneous Control Address: 0x");
   204       r.AppendLine((miscellaneousControlAddress).ToString("X",
   205         CultureInfo.InvariantCulture));
   206       r.Append("Time Stamp Counter Multiplier: ");
   207       r.AppendLine(timeStampCounterMultiplier.ToString(
   208         CultureInfo.InvariantCulture));
   209       r.AppendLine();
   210 
   211       return r.ToString();
   212     }
   213 
   214     private static double MultiplierFromIDs(uint divisorID, uint frequencyID) {
   215       return 0.5 * (frequencyID + 0x10) / (1 << (int)divisorID);
   216     }
   217 
   218     public override void Update() {
   219       base.Update();
   220 
   221       if (temperatureReader == null) {
   222         if (miscellaneousControlAddress != Ring0.InvalidPciAddress) {
   223           uint value;
   224           if (Ring0.ReadPciConfig(miscellaneousControlAddress,
   225             REPORTED_TEMPERATURE_CONTROL_REGISTER, out value)) {
   226             coreTemperature.Value = ((value >> 21) & 0x7FF) / 8.0f +
   227               coreTemperature.Parameters[0].Value;
   228             ActivateSensor(coreTemperature);
   229           } else {
   230             DeactivateSensor(coreTemperature);
   231           }
   232         }
   233       } else {
   234         temperatureReader.BaseStream.Seek(0, SeekOrigin.Begin);
   235         string s = temperatureReader.ReadLine();
   236         try {
   237           coreTemperature.Value = 0.001f *
   238             long.Parse(s, CultureInfo.InvariantCulture);
   239           ActivateSensor(coreTemperature);
   240         } catch {
   241           DeactivateSensor(coreTemperature);
   242         }        
   243       }
   244 
   245       if (HasTimeStampCounter) {
   246         double newBusClock = 0;
   247 
   248         for (int i = 0; i < coreClocks.Length; i++) {
   249           Thread.Sleep(1);
   250 
   251           uint curEax, curEdx;
   252           if (Ring0.RdmsrTx(COFVID_STATUS, out curEax, out curEdx,
   253             1UL << cpuid[i][0].Thread)) 
   254           {
   255             // 8:6 CpuDid: current core divisor ID
   256             // 5:0 CpuFid: current core frequency ID
   257             uint cpuDid = (curEax >> 6) & 7;
   258             uint cpuFid = curEax & 0x1F;
   259             double multiplier = MultiplierFromIDs(cpuDid, cpuFid);
   260 
   261             coreClocks[i].Value = 
   262               (float)(multiplier * TimeStampCounterFrequency / 
   263               timeStampCounterMultiplier);
   264             newBusClock = 
   265               (float)(TimeStampCounterFrequency / timeStampCounterMultiplier);
   266           } else {
   267             coreClocks[i].Value = (float)TimeStampCounterFrequency;
   268           }
   269         }
   270 
   271         if (newBusClock > 0) {
   272           this.busClock.Value = (float)newBusClock;
   273           ActivateSensor(this.busClock);
   274         }
   275       }
   276     }
   277 
   278     public override void Close() {
   279       if (temperatureReader != null) {
   280         temperatureReader.Close();
   281       }
   282     }
   283   }
   284 }