Hardware/CPU/GenericCPU.cs
author moel.mich
Wed, 27 Jul 2011 18:27:16 +0000
changeset 317 1ccf99e620a9
parent 279 6bce967ba1b5
child 344 3145aadca3d2
permissions -rw-r--r--
Added support for Intel CPU power sensors (package and cores).
     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) 2010-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 
    46 namespace OpenHardwareMonitor.Hardware.CPU {
    47   internal class GenericCPU : Hardware {
    48 
    49     protected readonly CPUID[][] cpuid;
    50    
    51     protected readonly uint family;
    52     protected readonly uint model;
    53     protected readonly uint stepping;
    54 
    55     protected readonly int processorIndex;
    56     protected readonly int coreCount;
    57 
    58     private readonly bool hasModelSpecificRegisters;
    59 
    60     private readonly bool hasTimeStampCounter;
    61     private readonly bool isInvariantTimeStampCounter;
    62     private readonly double estimatedTimeStampCounterFrequency;
    63     private readonly double estimatedTimeStampCounterFrequencyError;
    64 
    65     private ulong lastTimeStampCount;
    66     private long lastTime;
    67     private double timeStampCounterFrequency;
    68     
    69 
    70     private readonly Vendor vendor;
    71 
    72     private readonly CPULoad cpuLoad;
    73     private readonly Sensor totalLoad;
    74     private readonly Sensor[] coreLoads;
    75 
    76     protected string CoreString(int i) {
    77       if (coreCount == 1)
    78         return "CPU Core";
    79       else
    80         return "CPU Core #" + (i + 1);
    81     }
    82 
    83     public GenericCPU(int processorIndex, CPUID[][] cpuid, ISettings settings)
    84       : base(cpuid[0][0].Name, CreateIdentifier(cpuid[0][0].Vendor, 
    85       processorIndex), settings)
    86     {
    87       this.cpuid = cpuid;
    88 
    89       this.vendor = cpuid[0][0].Vendor;
    90 
    91       this.family = cpuid[0][0].Family;
    92       this.model = cpuid[0][0].Model;
    93       this.stepping = cpuid[0][0].Stepping;
    94 
    95       this.processorIndex = processorIndex;
    96       this.coreCount = cpuid.Length;  
    97   
    98       // check if processor has MSRs
    99       if (cpuid[0][0].Data.GetLength(0) > 1
   100         && (cpuid[0][0].Data[1, 3] & 0x20) != 0)
   101         hasModelSpecificRegisters = true;
   102       else
   103         hasModelSpecificRegisters = false;
   104 
   105       // check if processor has a TSC
   106       if (cpuid[0][0].Data.GetLength(0) > 1
   107         && (cpuid[0][0].Data[1, 3] & 0x10) != 0)
   108         hasTimeStampCounter = true;
   109       else
   110         hasTimeStampCounter = false;
   111 
   112       // check if processor supports an invariant TSC 
   113       if (cpuid[0][0].ExtData.GetLength(0) > 7
   114         && (cpuid[0][0].ExtData[7, 3] & 0x100) != 0)
   115         isInvariantTimeStampCounter = true;
   116       else
   117         isInvariantTimeStampCounter = false;
   118 
   119       if (coreCount > 1)
   120         totalLoad = new Sensor("CPU Total", 0, SensorType.Load, this, settings);
   121       else
   122         totalLoad = null;
   123       coreLoads = new Sensor[coreCount];
   124       for (int i = 0; i < coreLoads.Length; i++)
   125         coreLoads[i] = new Sensor(CoreString(i), i + 1,
   126           SensorType.Load, this, settings);
   127       cpuLoad = new CPULoad(cpuid);
   128       if (cpuLoad.IsAvailable) {
   129         foreach (Sensor sensor in coreLoads)
   130           ActivateSensor(sensor);
   131         if (totalLoad != null)
   132           ActivateSensor(totalLoad);
   133       }
   134 
   135       if (hasTimeStampCounter) {
   136         ulong mask = ThreadAffinity.Set(1UL << cpuid[0][0].Thread);
   137 
   138         EstimateTimeStampCounterFrequency(
   139           out estimatedTimeStampCounterFrequency, 
   140           out estimatedTimeStampCounterFrequencyError);  
   141         
   142         ThreadAffinity.Set(mask);
   143       } else {
   144         estimatedTimeStampCounterFrequency = 0;
   145       }
   146 
   147       timeStampCounterFrequency = estimatedTimeStampCounterFrequency;                  
   148     }
   149 
   150     private static Identifier CreateIdentifier(Vendor vendor,
   151       int processorIndex) 
   152     {
   153       string s;
   154       switch (vendor) {
   155         case Vendor.AMD: s = "amdcpu"; break;
   156         case Vendor.Intel: s = "intelcpu"; break;
   157         default: s = "genericcpu"; break;
   158       }
   159       return new Identifier(s,
   160         processorIndex.ToString(CultureInfo.InvariantCulture));
   161     }
   162 
   163     private void EstimateTimeStampCounterFrequency(out double frequency, 
   164       out double error) 
   165   {     
   166       double f, e;
   167       
   168       // preload the function
   169       EstimateTimeStampCounterFrequency(0, out f, out e);
   170       EstimateTimeStampCounterFrequency(0, out f, out e);
   171 
   172       // estimate the frequency
   173       error = double.MaxValue;
   174       frequency = 0;
   175       for (int i = 0; i < 5; i++) {
   176         EstimateTimeStampCounterFrequency(0.025, out f, out e);
   177         if (e < error) {
   178           error = e;
   179           frequency = f;
   180         }
   181 
   182         if (error < 1e-4)
   183           break;
   184       }                
   185     }
   186 
   187     private void EstimateTimeStampCounterFrequency(double timeWindow, 
   188       out double frequency, out double error) 
   189     {
   190       long ticks = (long)(timeWindow * Stopwatch.Frequency);
   191       ulong countBegin, countEnd;
   192 
   193       long timeBegin = Stopwatch.GetTimestamp() +
   194         (long)Math.Ceiling(0.001 * ticks);
   195       long timeEnd = timeBegin + ticks;
   196 
   197       while (Stopwatch.GetTimestamp() < timeBegin) { }
   198       countBegin = Opcode.Rdtsc();
   199       long afterBegin = Stopwatch.GetTimestamp();
   200 
   201       while (Stopwatch.GetTimestamp() < timeEnd) { }
   202       countEnd = Opcode.Rdtsc();
   203       long afterEnd = Stopwatch.GetTimestamp();
   204 
   205       double delta = (timeEnd - timeBegin);
   206       frequency = 1e-6 * 
   207         (((double)(countEnd - countBegin)) * Stopwatch.Frequency) / delta;
   208 
   209       double beginError = (afterBegin - timeBegin) / delta;
   210       double endError = (afterEnd - timeEnd) / delta;
   211       error = beginError + endError;
   212     }
   213 
   214 
   215     private static void AppendMSRData(StringBuilder r, uint msr, int thread) {
   216       uint eax, edx;
   217       if (Ring0.RdmsrTx(msr, out eax, out edx, 1UL << thread)) {
   218         r.Append(" ");
   219         r.Append((msr).ToString("X8", CultureInfo.InvariantCulture));
   220         r.Append("  ");
   221         r.Append((edx).ToString("X8", CultureInfo.InvariantCulture));
   222         r.Append("  ");
   223         r.Append((eax).ToString("X8", CultureInfo.InvariantCulture));
   224         r.AppendLine();
   225       }
   226     }
   227 
   228     protected virtual uint[] GetMSRs() {
   229       return null;
   230     }
   231 
   232     public override string GetReport() {
   233       StringBuilder r = new StringBuilder();
   234 
   235       switch (vendor) {
   236         case Vendor.AMD: r.AppendLine("AMD CPU"); break;
   237         case Vendor.Intel: r.AppendLine("Intel CPU"); break;
   238         default: r.AppendLine("Generic CPU"); break;
   239       }
   240 
   241       r.AppendLine();
   242       r.AppendFormat("Name: {0}{1}", name, Environment.NewLine);
   243       r.AppendFormat("Number of Cores: {0}{1}", coreCount,
   244         Environment.NewLine);
   245       r.AppendFormat("Threads per Core: {0}{1}", cpuid[0].Length,
   246         Environment.NewLine);
   247       r.AppendLine(string.Format(CultureInfo.InvariantCulture,
   248         "Timer Frequency: {0} MHz", Stopwatch.Frequency * 1e-6));
   249       r.AppendLine("Time Stamp Counter: " + (hasTimeStampCounter ? (
   250         isInvariantTimeStampCounter ? "Invariant" : "Not Invariant") : "None"));
   251       r.AppendLine(string.Format(CultureInfo.InvariantCulture,
   252         "Estimated Time Stamp Counter Frequency: {0} MHz",
   253         Math.Round(estimatedTimeStampCounterFrequency * 100) * 0.01));
   254       r.AppendLine(string.Format(CultureInfo.InvariantCulture,
   255         "Estimated Time Stamp Counter Frequency Error: {0} Mhz",
   256         Math.Round(estimatedTimeStampCounterFrequency *
   257         estimatedTimeStampCounterFrequencyError * 1e5) * 1e-5));
   258       r.AppendLine(string.Format(CultureInfo.InvariantCulture,
   259         "Time Stamp Counter Frequency: {0} MHz",
   260         Math.Round(timeStampCounterFrequency * 100) * 0.01));   
   261       r.AppendLine();
   262 
   263       uint[] msrArray = GetMSRs();
   264       if (msrArray != null && msrArray.Length > 0) {
   265         for (int i = 0; i < cpuid.Length; i++) {
   266           r.AppendLine("MSR Core #" + (i + 1));
   267           r.AppendLine();
   268           r.AppendLine(" MSR       EDX       EAX");
   269           foreach (uint msr in msrArray)
   270             AppendMSRData(r, msr, cpuid[i][0].Thread);
   271           r.AppendLine();
   272         }
   273       }
   274 
   275       return r.ToString();
   276     }
   277 
   278     public override HardwareType HardwareType {
   279       get { return HardwareType.CPU; }
   280     }
   281 
   282     public bool HasModelSpecificRegisters {
   283       get { return hasModelSpecificRegisters; }
   284     }
   285 
   286     public bool HasTimeStampCounter {
   287       get { return hasTimeStampCounter; }
   288     }
   289 
   290     public double TimeStampCounterFrequency {
   291       get { return timeStampCounterFrequency; }
   292     }
   293 
   294     public override void Update() {
   295       if (hasTimeStampCounter && isInvariantTimeStampCounter) {
   296 
   297         // make sure always the same thread is used
   298         ulong mask = ThreadAffinity.Set(1UL << cpuid[0][0].Thread);
   299 
   300         // read time before and after getting the TSC to estimate the error
   301         long firstTime = Stopwatch.GetTimestamp();
   302         ulong timeStampCount = Opcode.Rdtsc();
   303         long time = Stopwatch.GetTimestamp();
   304 
   305         // restore the thread affinity mask
   306         ThreadAffinity.Set(mask);
   307 
   308         double delta = ((double)(time - lastTime)) / Stopwatch.Frequency;
   309         double error = ((double)(time - firstTime)) / Stopwatch.Frequency;
   310 
   311         // only use data if they are measured accuarte enough (max 0.1ms delay)
   312         if (error < 0.0001) {
   313 
   314           // ignore the first reading because there are no initial values 
   315           // ignore readings with too large or too small time window
   316           if (lastTime != 0 && delta > 0.5 && delta < 2) {
   317 
   318             // update the TSC frequency with the new value
   319             timeStampCounterFrequency =
   320               (timeStampCount - lastTimeStampCount) / (1e6 * delta);
   321           }
   322 
   323           lastTimeStampCount = timeStampCount;
   324           lastTime = time;
   325         }        
   326       }
   327 
   328       if (cpuLoad.IsAvailable) {
   329         cpuLoad.Update();
   330         for (int i = 0; i < coreLoads.Length; i++)
   331           coreLoads[i].Value = cpuLoad.GetCoreLoad(i);
   332         if (totalLoad != null)
   333           totalLoad.Value = cpuLoad.GetTotalLoad();
   334       }
   335     }
   336   }
   337 }