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