Hardware/CPU/AMD10CPU.cs
author moel.mich
Sun, 10 Apr 2011 23:36:07 +0000
changeset 268 844ba72c11de
parent 266 2687ac753d90
child 271 8635fa73eacc
permissions -rw-r--r--
Replaced the StreamReader based lm-sensors access with an implementation using the FileStream class in order to avoid buffering problems when seeking.
     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 uint REPORTED_TEMPERATURE_CONTROL_REGISTER = 0xA4;
    64 
    65     private readonly uint miscellaneousControlAddress;
    66     private readonly ushort miscellaneousControlDeviceId;
    67 
    68     private readonly FileStream temperatureStream;
    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       temperatureStream = 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               temperatureStream = new FileStream(path + "/device/temp1_input", 
   134                 FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
   135               break;
   136           }
   137         }
   138       }
   139 
   140       Update();                   
   141     }
   142 
   143     private double estimateTimeStampCounterMultiplier() {
   144       // preload the function
   145       estimateTimeStampCounterMultiplier(0);
   146       estimateTimeStampCounterMultiplier(0);
   147 
   148       // estimate the multiplier
   149       List<double> estimate = new List<double>(3);
   150       for (int i = 0; i < 3; i++)
   151         estimate.Add(estimateTimeStampCounterMultiplier(0.025));
   152       estimate.Sort();
   153       return estimate[1];
   154     }
   155 
   156     private double estimateTimeStampCounterMultiplier(double timeWindow) {
   157       uint eax, edx;
   158      
   159       // select event "076h CPU Clocks not Halted" and enable the counter
   160       Ring0.Wrmsr(PERF_CTL_0,
   161         (1 << 22) | // enable performance counter
   162         (1 << 17) | // count events in user mode
   163         (1 << 16) | // count events in operating-system mode
   164         0x76, 0x00000000);
   165 
   166       // set the counter to 0
   167       Ring0.Wrmsr(PERF_CTR_0, 0, 0);
   168 
   169       long ticks = (long)(timeWindow * Stopwatch.Frequency);
   170       uint lsbBegin, msbBegin, lsbEnd, msbEnd;
   171 
   172       long timeBegin = Stopwatch.GetTimestamp() +
   173         (long)Math.Ceiling(0.001 * ticks);
   174       long timeEnd = timeBegin + ticks;
   175       while (Stopwatch.GetTimestamp() < timeBegin) { }
   176       Ring0.Rdmsr(PERF_CTR_0, out lsbBegin, out msbBegin);
   177       while (Stopwatch.GetTimestamp() < timeEnd) { }
   178       Ring0.Rdmsr(PERF_CTR_0, out lsbEnd, out msbEnd);
   179 
   180       Ring0.Rdmsr(COFVID_STATUS, out eax, out edx);
   181       uint cpuDid = (eax >> 6) & 7;
   182       uint cpuFid = eax & 0x1F;
   183       double coreMultiplier = MultiplierFromIDs(cpuDid, cpuFid);
   184 
   185       ulong countBegin = ((ulong)msbBegin << 32) | lsbBegin;
   186       ulong countEnd = ((ulong)msbEnd << 32) | lsbEnd;
   187 
   188       double coreFrequency = 1e-6 * 
   189         (((double)(countEnd - countBegin)) * Stopwatch.Frequency) /
   190         (timeEnd - timeBegin);
   191 
   192       double busFrequency = coreFrequency / coreMultiplier;
   193       return 0.5 * Math.Round(2 * TimeStampCounterFrequency / busFrequency);
   194     }
   195 
   196     protected override uint[] GetMSRs() {
   197       return new uint[] { PERF_CTL_0, PERF_CTR_0, P_STATE_0, COFVID_STATUS };
   198     }
   199 
   200     public override string GetReport() {
   201       StringBuilder r = new StringBuilder();
   202       r.Append(base.GetReport());
   203 
   204       r.Append("Miscellaneous Control Address: 0x");
   205       r.AppendLine((miscellaneousControlAddress).ToString("X",
   206         CultureInfo.InvariantCulture));
   207       r.Append("Time Stamp Counter Multiplier: ");
   208       r.AppendLine(timeStampCounterMultiplier.ToString(
   209         CultureInfo.InvariantCulture));
   210       r.AppendLine();
   211 
   212       return r.ToString();
   213     }
   214 
   215     private static double MultiplierFromIDs(uint divisorID, uint frequencyID) {
   216       return 0.5 * (frequencyID + 0x10) / (1 << (int)divisorID);
   217     }
   218 
   219     private string ReadFirstLine(Stream stream) {
   220       StringBuilder sb = new StringBuilder();
   221       try {
   222         stream.Seek(0, SeekOrigin.Begin);
   223         int b = stream.ReadByte();
   224         while (b != -1 && b != 10) {
   225           sb.Append((char)b);
   226           b = stream.ReadByte();
   227         }
   228       } catch { }
   229       return sb.ToString();
   230     }
   231 
   232     public override void Update() {
   233       base.Update();
   234 
   235       if (temperatureStream == null) {
   236         if (miscellaneousControlAddress != Ring0.InvalidPciAddress) {
   237           uint value;
   238           if (Ring0.ReadPciConfig(miscellaneousControlAddress,
   239             REPORTED_TEMPERATURE_CONTROL_REGISTER, out value)) {
   240             coreTemperature.Value = ((value >> 21) & 0x7FF) / 8.0f +
   241               coreTemperature.Parameters[0].Value;
   242             ActivateSensor(coreTemperature);
   243           } else {
   244             DeactivateSensor(coreTemperature);
   245           }
   246         }
   247       } else {
   248         string s = ReadFirstLine(temperatureStream);
   249         try {
   250           coreTemperature.Value = 0.001f *
   251             long.Parse(s, CultureInfo.InvariantCulture);
   252           ActivateSensor(coreTemperature);
   253         } catch {
   254           DeactivateSensor(coreTemperature);
   255         }        
   256       }
   257 
   258       if (HasTimeStampCounter) {
   259         double newBusClock = 0;
   260 
   261         for (int i = 0; i < coreClocks.Length; i++) {
   262           Thread.Sleep(1);
   263 
   264           uint curEax, curEdx;
   265           if (Ring0.RdmsrTx(COFVID_STATUS, out curEax, out curEdx,
   266             1UL << cpuid[i][0].Thread)) 
   267           {
   268             // 8:6 CpuDid: current core divisor ID
   269             // 5:0 CpuFid: current core frequency ID
   270             uint cpuDid = (curEax >> 6) & 7;
   271             uint cpuFid = curEax & 0x1F;
   272             double multiplier = MultiplierFromIDs(cpuDid, cpuFid);
   273 
   274             coreClocks[i].Value = 
   275               (float)(multiplier * TimeStampCounterFrequency / 
   276               timeStampCounterMultiplier);
   277             newBusClock = 
   278               (float)(TimeStampCounterFrequency / timeStampCounterMultiplier);
   279           } else {
   280             coreClocks[i].Value = (float)TimeStampCounterFrequency;
   281           }
   282         }
   283 
   284         if (newBusClock > 0) {
   285           this.busClock.Value = (float)newBusClock;
   286           ActivateSensor(this.busClock);
   287         }
   288       }
   289     }
   290 
   291     public override void Close() {
   292       if (temperatureStream != null) {
   293         temperatureStream.Close();
   294       }
   295     }
   296   }
   297 }