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