Hardware/Ring0.cs
author moel.mich
Sun, 15 May 2011 15:37:50 +0000
changeset 281 1c301069cfce
parent 279 6bce967ba1b5
child 283 fb88cac4a9aa
permissions -rw-r--r--
Fixed Issue 216.
moel@236
     1
/*
moel@236
     2
  
moel@236
     3
  Version: MPL 1.1/GPL 2.0/LGPL 2.1
moel@236
     4
moel@236
     5
  The contents of this file are subject to the Mozilla Public License Version
moel@236
     6
  1.1 (the "License"); you may not use this file except in compliance with
moel@236
     7
  the License. You may obtain a copy of the License at
moel@236
     8
 
moel@236
     9
  http://www.mozilla.org/MPL/
moel@236
    10
moel@236
    11
  Software distributed under the License is distributed on an "AS IS" basis,
moel@236
    12
  WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
moel@236
    13
  for the specific language governing rights and limitations under the License.
moel@236
    14
moel@236
    15
  The Original Code is the Open Hardware Monitor code.
moel@236
    16
moel@236
    17
  The Initial Developer of the Original Code is 
moel@236
    18
  Michael Möller <m.moeller@gmx.ch>.
moel@254
    19
  Portions created by the Initial Developer are Copyright (C) 2010-2011
moel@236
    20
  the Initial Developer. All Rights Reserved.
moel@236
    21
moel@236
    22
  Contributor(s):
moel@236
    23
moel@236
    24
  Alternatively, the contents of this file may be used under the terms of
moel@236
    25
  either the GNU General Public License Version 2 or later (the "GPL"), or
moel@236
    26
  the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
moel@236
    27
  in which case the provisions of the GPL or the LGPL are applicable instead
moel@236
    28
  of those above. If you wish to allow use of your version of this file only
moel@236
    29
  under the terms of either the GPL or the LGPL, and not to allow others to
moel@236
    30
  use your version of this file under the terms of the MPL, indicate your
moel@236
    31
  decision by deleting the provisions above and replace them with the notice
moel@236
    32
  and other provisions required by the GPL or the LGPL. If you do not delete
moel@236
    33
  the provisions above, a recipient may use your version of this file under
moel@236
    34
  the terms of any one of the MPL, the GPL or the LGPL.
moel@236
    35
 
moel@236
    36
*/
moel@236
    37
moel@236
    38
using System;
moel@236
    39
using System.IO;
moel@236
    40
using System.Reflection;
moel@236
    41
using System.Runtime.InteropServices;
moel@236
    42
using System.Threading;
moel@254
    43
using System.Text;
moel@236
    44
moel@236
    45
namespace OpenHardwareMonitor.Hardware {
moel@236
    46
  internal static class Ring0 {
moel@236
    47
moel@236
    48
    private static KernelDriver driver;
moel@281
    49
    private static string fileName;
moel@236
    50
    private static Mutex isaBusMutex;
moel@254
    51
    private static readonly StringBuilder report = new StringBuilder();
moel@236
    52
moel@236
    53
    private const uint OLS_TYPE = 40000;
moel@236
    54
    private static IOControlCode
moel@236
    55
      IOCTL_OLS_GET_REFCOUNT = new IOControlCode(OLS_TYPE, 0x801,
moel@236
    56
        IOControlCode.Access.Any),
moel@236
    57
      IOCTL_OLS_GET_DRIVER_VERSION = new IOControlCode(OLS_TYPE, 0x800,
moel@236
    58
        IOControlCode.Access.Any),
moel@236
    59
      IOCTL_OLS_READ_MSR = new IOControlCode(OLS_TYPE, 0x821,
moel@236
    60
        IOControlCode.Access.Any),
moel@236
    61
      IOCTL_OLS_WRITE_MSR = new IOControlCode(OLS_TYPE, 0x822, 
moel@236
    62
        IOControlCode.Access.Any),
moel@236
    63
      IOCTL_OLS_READ_IO_PORT_BYTE = new IOControlCode(OLS_TYPE, 0x833,
moel@236
    64
        IOControlCode.Access.Read),
moel@236
    65
      IOCTL_OLS_WRITE_IO_PORT_BYTE = new IOControlCode(OLS_TYPE, 0x836, 
moel@236
    66
        IOControlCode.Access.Write),
moel@236
    67
      IOCTL_OLS_READ_PCI_CONFIG = new IOControlCode(OLS_TYPE, 0x851, 
moel@236
    68
        IOControlCode.Access.Read),
moel@236
    69
      IOCTL_OLS_WRITE_PCI_CONFIG = new IOControlCode(OLS_TYPE, 0x852,
moel@279
    70
        IOControlCode.Access.Write),
moel@279
    71
      IOCTL_OLS_READ_MEMORY = new IOControlCode(OLS_TYPE, 0x841,
moel@279
    72
        IOControlCode.Access.Read);
moel@236
    73
moel@236
    74
    private static bool ExtractDriver(string fileName) {
moel@236
    75
      string resourceName = "OpenHardwareMonitor.Hardware." +
moel@236
    76
        (IntPtr.Size == 4 ? "WinRing0.sys" : "WinRing0x64.sys");
moel@236
    77
moel@236
    78
      string[] names =
moel@236
    79
        Assembly.GetExecutingAssembly().GetManifestResourceNames();
moel@236
    80
      byte[] buffer = null;
moel@236
    81
      for (int i = 0; i < names.Length; i++) {
moel@236
    82
        if (names[i].Replace('\\', '.') == resourceName) {
moel@236
    83
          using (Stream stream = Assembly.GetExecutingAssembly().
moel@236
    84
            GetManifestResourceStream(names[i])) 
moel@236
    85
          {
moel@236
    86
              buffer = new byte[stream.Length];
moel@236
    87
              stream.Read(buffer, 0, buffer.Length);
moel@236
    88
          }
moel@236
    89
        }
moel@236
    90
      }
moel@236
    91
moel@236
    92
      if (buffer == null)
moel@236
    93
        return false;
moel@236
    94
moel@236
    95
      using (FileStream target = new FileStream(fileName, FileMode.Create)) {
moel@236
    96
        target.Write(buffer, 0, buffer.Length);
moel@236
    97
      }
moel@236
    98
moel@236
    99
      return true;
moel@236
   100
    }
moel@236
   101
moel@236
   102
    public static void Open() {
moel@254
   103
      // no implementation for unix systems
moel@238
   104
      int p = (int)Environment.OSVersion.Platform;
moel@238
   105
      if ((p == 4) || (p == 128))
moel@238
   106
        return;  
moel@238
   107
      
moel@236
   108
      if (driver != null)
moel@236
   109
        return;
moel@254
   110
moel@254
   111
      // clear the current report
moel@254
   112
      report.Length = 0;
moel@236
   113
     
moel@236
   114
      driver = new KernelDriver("WinRing0_1_2_0");
moel@236
   115
      driver.Open();
moel@236
   116
moel@236
   117
      if (!driver.IsOpen) {
moel@255
   118
        // driver is not loaded, try to reinstall and open
moel@255
   119
moel@255
   120
        driver.Delete();
moel@281
   121
        fileName = Path.GetTempFileName();
moel@236
   122
        if (ExtractDriver(fileName)) {
moel@254
   123
          if (driver.Install(fileName)) {
moel@254
   124
            driver.Open();
moel@236
   125
moel@254
   126
            if (!driver.IsOpen) {
moel@254
   127
              driver.Delete();
moel@254
   128
              report.AppendLine("Status: Opening driver failed");
moel@254
   129
            }
moel@254
   130
          } else {
moel@255
   131
            report.AppendLine("Status: Installing driver \"" + 
moel@255
   132
              fileName + "\" failed" + 
moel@255
   133
              (File.Exists(fileName) ? " and file exists" : ""));
moel@254
   134
            report.AppendLine();
moel@254
   135
            report.Append("Exception: " + Marshal.GetExceptionForHR(
moel@254
   136
              Marshal.GetHRForLastWin32Error()).Message);
moel@254
   137
          }
moel@281
   138
          
moel@254
   139
        } else {
moel@254
   140
          report.AppendLine(
moel@254
   141
            "Status: Extracting driver to \"" + fileName + "\" failed");
moel@236
   142
        }
moel@281
   143
moel@281
   144
        try {
moel@281
   145
          // try to delte the driver file
moel@281
   146
          if (File.Exists(fileName))
moel@281
   147
            File.Delete(fileName);
moel@281
   148
          fileName = null;
moel@281
   149
        } catch (IOException) { } 
moel@281
   150
          catch (UnauthorizedAccessException) { }
moel@236
   151
      }
moel@236
   152
moel@236
   153
      if (!driver.IsOpen) 
moel@236
   154
        driver = null;
moel@236
   155
moel@259
   156
      isaBusMutex = new Mutex(false, "Global\\Access_ISABUS.HTP.Method");
moel@236
   157
    }
moel@236
   158
moel@236
   159
    public static bool IsOpen {
moel@236
   160
      get { return driver != null; }
moel@236
   161
    }
moel@236
   162
moel@236
   163
    public static void Close() {
moel@236
   164
      if (driver == null)
moel@236
   165
        return;
moel@236
   166
moel@236
   167
      uint refCount = 0;
moel@236
   168
      driver.DeviceIOControl(IOCTL_OLS_GET_REFCOUNT, null, ref refCount);
moel@236
   169
moel@236
   170
      driver.Close();
moel@236
   171
moel@236
   172
      if (refCount <= 1)
moel@236
   173
        driver.Delete();
moel@236
   174
moel@236
   175
      driver = null;
moel@236
   176
moel@281
   177
      isaBusMutex.Close();
moel@281
   178
moel@281
   179
      // try to delete temporary driver file again if failed during open
moel@281
   180
      if (fileName != null && File.Exists(fileName)) {
moel@281
   181
        try {
moel@281
   182
          File.Delete(fileName);
moel@281
   183
          fileName = null;
moel@281
   184
        } catch (IOException) { } 
moel@281
   185
          catch (UnauthorizedAccessException) { }
moel@281
   186
      }
moel@236
   187
    }
moel@236
   188
moel@254
   189
    public static string GetReport() {
moel@254
   190
      if (report.Length > 0) {
moel@256
   191
        StringBuilder r = new StringBuilder();
moel@256
   192
        r.AppendLine("Ring0");
moel@256
   193
        r.AppendLine();
moel@256
   194
        r.Append(report);
moel@256
   195
        r.AppendLine();
moel@256
   196
        return r.ToString();
moel@254
   197
      } else
moel@254
   198
        return null;
moel@254
   199
    }
moel@254
   200
moel@236
   201
    public static bool WaitIsaBusMutex(int millisecondsTimeout) {
moel@236
   202
      try {
moel@236
   203
        return isaBusMutex.WaitOne(millisecondsTimeout, false);
moel@236
   204
      } catch (AbandonedMutexException) { return false; } 
moel@236
   205
        catch (InvalidOperationException) { return false; }
moel@236
   206
    }
moel@236
   207
moel@236
   208
    public static void ReleaseIsaBusMutex() {
moel@236
   209
      isaBusMutex.ReleaseMutex();
moel@236
   210
    }
moel@236
   211
moel@236
   212
    public static bool Rdmsr(uint index, out uint eax, out uint edx) {
moel@236
   213
      if (driver == null) {
moel@236
   214
        eax = 0;
moel@236
   215
        edx = 0;
moel@236
   216
        return false;
moel@236
   217
      }
moel@236
   218
moel@236
   219
      ulong buffer = 0;
moel@236
   220
      bool result = driver.DeviceIOControl(IOCTL_OLS_READ_MSR, index,
moel@236
   221
        ref buffer);
moel@236
   222
moel@236
   223
      edx = (uint)((buffer >> 32) & 0xFFFFFFFF);
moel@236
   224
      eax = (uint)(buffer & 0xFFFFFFFF);
moel@236
   225
      return result;
moel@236
   226
    }
moel@236
   227
moel@236
   228
    public static bool RdmsrTx(uint index, out uint eax, out uint edx,
moel@238
   229
      ulong threadAffinityMask) 
moel@236
   230
    {
moel@238
   231
      ulong mask = ThreadAffinity.Set(threadAffinityMask);
moel@236
   232
moel@236
   233
      bool result = Rdmsr(index, out eax, out edx);
moel@236
   234
moel@238
   235
      ThreadAffinity.Set(mask);
moel@236
   236
      return result;
moel@236
   237
    }
moel@236
   238
moel@236
   239
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@236
   240
    private struct WrmsrInput {
moel@236
   241
      public uint Register;
moel@236
   242
      public ulong Value;
moel@236
   243
    }
moel@236
   244
moel@236
   245
    public static bool Wrmsr(uint index, uint eax, uint edx) {
moel@236
   246
      if (driver == null)
moel@236
   247
        return false;
moel@236
   248
moel@236
   249
      WrmsrInput input = new WrmsrInput();
moel@236
   250
      input.Register = index;
moel@236
   251
      input.Value = ((ulong)edx << 32) | eax;
moel@236
   252
moel@236
   253
      return driver.DeviceIOControl(IOCTL_OLS_WRITE_MSR, input);
moel@236
   254
    }
moel@236
   255
moel@236
   256
    public static byte ReadIoPort(uint port) {
moel@236
   257
      if (driver == null)
moel@236
   258
        return 0;
moel@236
   259
moel@236
   260
      uint value = 0;
moel@236
   261
      driver.DeviceIOControl(IOCTL_OLS_READ_IO_PORT_BYTE, port, ref value);
moel@236
   262
moel@236
   263
      return (byte)(value & 0xFF);
moel@236
   264
    }
moel@236
   265
moel@236
   266
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@236
   267
    private struct WriteIoPortInput {
moel@236
   268
      public uint PortNumber;
moel@236
   269
      public byte Value;
moel@236
   270
    }
moel@236
   271
moel@236
   272
    public static void WriteIoPort(uint port, byte value) {
moel@236
   273
      if (driver == null)
moel@236
   274
        return;
moel@236
   275
moel@236
   276
      WriteIoPortInput input = new WriteIoPortInput();
moel@236
   277
      input.PortNumber = port;
moel@236
   278
      input.Value = value;
moel@236
   279
moel@236
   280
      driver.DeviceIOControl(IOCTL_OLS_WRITE_IO_PORT_BYTE, input);
moel@236
   281
    }
moel@236
   282
moel@236
   283
    public const uint InvalidPciAddress = 0xFFFFFFFF;
moel@236
   284
moel@236
   285
    public static uint GetPciAddress(byte bus, byte device, byte function) {
moel@236
   286
      return
moel@236
   287
        (uint)(((bus & 0xFF) << 8) | ((device & 0x1F) << 3) | (function & 7));
moel@236
   288
    }
moel@236
   289
moel@236
   290
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@236
   291
    private struct ReadPciConfigInput {
moel@236
   292
      public uint PciAddress;
moel@236
   293
      public uint RegAddress;
moel@236
   294
    }
moel@236
   295
moel@236
   296
    public static bool ReadPciConfig(uint pciAddress, uint regAddress, 
moel@236
   297
      out uint value) 
moel@236
   298
    {
moel@236
   299
      if (driver == null || (regAddress & 3) != 0) {
moel@236
   300
        value = 0;
moel@236
   301
        return false;
moel@236
   302
      }
moel@236
   303
moel@236
   304
      ReadPciConfigInput input = new ReadPciConfigInput();
moel@236
   305
      input.PciAddress = pciAddress;
moel@236
   306
      input.RegAddress = regAddress;
moel@236
   307
moel@236
   308
      value = 0;
moel@236
   309
      return driver.DeviceIOControl(IOCTL_OLS_READ_PCI_CONFIG, input, 
moel@236
   310
        ref value);
moel@236
   311
    }
moel@236
   312
moel@236
   313
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@236
   314
    private struct WritePciConfigInput {
moel@236
   315
      public uint PciAddress;
moel@236
   316
      public uint RegAddress;
moel@236
   317
      public uint Value;
moel@236
   318
    }
moel@236
   319
moel@236
   320
    public static bool WritePciConfig(uint pciAddress, uint regAddress, 
moel@236
   321
      uint value) 
moel@236
   322
    {
moel@236
   323
      if (driver == null || (regAddress & 3) != 0)
moel@236
   324
        return false;
moel@236
   325
moel@236
   326
      WritePciConfigInput input = new WritePciConfigInput();
moel@236
   327
      input.PciAddress = pciAddress;
moel@236
   328
      input.RegAddress = regAddress;
moel@236
   329
      input.Value = value;
moel@236
   330
moel@236
   331
      return driver.DeviceIOControl(IOCTL_OLS_WRITE_PCI_CONFIG, input);
moel@236
   332
    }
moel@279
   333
moel@279
   334
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@279
   335
    private struct ReadMemoryInput {
moel@279
   336
      public ulong address;
moel@279
   337
      public uint unitSize;
moel@279
   338
      public uint count;
moel@279
   339
    }
moel@279
   340
moel@279
   341
    public static bool ReadMemory<T>(ulong address, ref T buffer) {
moel@279
   342
      if (driver == null) {
moel@279
   343
        return false;
moel@279
   344
      }
moel@279
   345
moel@279
   346
      ReadMemoryInput input = new ReadMemoryInput();
moel@279
   347
      input.address = address;
moel@279
   348
      input.unitSize = 1;
moel@279
   349
      input.count = (uint)Marshal.SizeOf(buffer);
moel@279
   350
moel@279
   351
      return driver.DeviceIOControl(IOCTL_OLS_READ_MEMORY, input,
moel@279
   352
        ref buffer);
moel@279
   353
    }
moel@236
   354
  }
moel@236
   355
}