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