Hardware/Ring0.cs
author moel.mich
Mon, 02 Jul 2012 21:14:40 +0000
changeset 357 fb8dc26f65a4
parent 294 f7f0f3bafbb7
child 361 0a386ef7d5bb
permissions -rw-r--r--
Added mainboard specific configurations for the following Gigabyte mainboards: EX58-UD3R, G41M-Combo, G41MT-S2, G41MT-S2P, GA-MA770T-UD3P, GA-MA785GM-US2H, GA-MA78LM-S2H, GA-MA790X-UD3P, H55-USB3, H55N-USB3, H61M-DS2 REV 1.2, H61M-USB3-B3 REV 2.0, H67A-USB3-B3, P55A-UD3, P67A-UD3-B3, P67A-UD3R-B3, Z68A-D3H-B3, Z68AP-D3, Z68X-UD3H-B3.
moel@236
     1
/*
moel@236
     2
 
moel@344
     3
  This Source Code Form is subject to the terms of the Mozilla Public
moel@344
     4
  License, v. 2.0. If a copy of the MPL was not distributed with this
moel@344
     5
  file, You can obtain one at http://mozilla.org/MPL/2.0/.
moel@236
     6
 
moel@344
     7
  Copyright (C) 2010-2011 Michael Möller <mmoeller@openhardwaremonitor.org>
moel@344
     8
	
moel@236
     9
*/
moel@236
    10
moel@236
    11
using System;
moel@236
    12
using System.IO;
moel@236
    13
using System.Reflection;
moel@236
    14
using System.Runtime.InteropServices;
moel@285
    15
using System.Security.AccessControl;
moel@236
    16
using System.Threading;
moel@254
    17
using System.Text;
moel@236
    18
moel@236
    19
namespace OpenHardwareMonitor.Hardware {
moel@236
    20
  internal static class Ring0 {
moel@236
    21
moel@236
    22
    private static KernelDriver driver;
moel@281
    23
    private static string fileName;
moel@236
    24
    private static Mutex isaBusMutex;
moel@254
    25
    private static readonly StringBuilder report = new StringBuilder();
moel@236
    26
moel@236
    27
    private const uint OLS_TYPE = 40000;
moel@236
    28
    private static IOControlCode
moel@236
    29
      IOCTL_OLS_GET_REFCOUNT = new IOControlCode(OLS_TYPE, 0x801,
moel@236
    30
        IOControlCode.Access.Any),
moel@236
    31
      IOCTL_OLS_GET_DRIVER_VERSION = new IOControlCode(OLS_TYPE, 0x800,
moel@236
    32
        IOControlCode.Access.Any),
moel@236
    33
      IOCTL_OLS_READ_MSR = new IOControlCode(OLS_TYPE, 0x821,
moel@236
    34
        IOControlCode.Access.Any),
moel@236
    35
      IOCTL_OLS_WRITE_MSR = new IOControlCode(OLS_TYPE, 0x822, 
moel@236
    36
        IOControlCode.Access.Any),
moel@236
    37
      IOCTL_OLS_READ_IO_PORT_BYTE = new IOControlCode(OLS_TYPE, 0x833,
moel@236
    38
        IOControlCode.Access.Read),
moel@236
    39
      IOCTL_OLS_WRITE_IO_PORT_BYTE = new IOControlCode(OLS_TYPE, 0x836, 
moel@236
    40
        IOControlCode.Access.Write),
moel@236
    41
      IOCTL_OLS_READ_PCI_CONFIG = new IOControlCode(OLS_TYPE, 0x851, 
moel@236
    42
        IOControlCode.Access.Read),
moel@236
    43
      IOCTL_OLS_WRITE_PCI_CONFIG = new IOControlCode(OLS_TYPE, 0x852,
moel@279
    44
        IOControlCode.Access.Write),
moel@279
    45
      IOCTL_OLS_READ_MEMORY = new IOControlCode(OLS_TYPE, 0x841,
moel@279
    46
        IOControlCode.Access.Read);
moel@236
    47
moel@283
    48
    private static string GetTempFileName() {
moel@283
    49
moel@283
    50
      // try to get a file in the temporary folder
moel@283
    51
      try {
moel@283
    52
        return Path.GetTempFileName();        
moel@293
    53
      } catch (IOException) { 
moel@293
    54
          // some I/O exception
moel@293
    55
        } 
moel@293
    56
        catch (UnauthorizedAccessException) { 
moel@293
    57
          // we do not have the right to create a file in the temp folder
moel@293
    58
        }
moel@293
    59
        catch (NotSupportedException) {
moel@293
    60
          // invalid path format of the TMP system environment variable
moel@293
    61
        }
moel@283
    62
moel@283
    63
      // if this failed, we try to create one in the application folder
moel@283
    64
      string fileName = Path.ChangeExtension(
moel@283
    65
        Assembly.GetExecutingAssembly().Location, ".sys");
moel@283
    66
      try {
moel@283
    67
        using (FileStream stream = File.Create(fileName)) {
moel@283
    68
          return fileName;
moel@283
    69
        }        
moel@283
    70
      } catch (IOException) { } 
moel@283
    71
        catch (UnauthorizedAccessException) { }
moel@283
    72
     
moel@283
    73
      return null;
moel@283
    74
    }
moel@283
    75
moel@236
    76
    private static bool ExtractDriver(string fileName) {
moel@236
    77
      string resourceName = "OpenHardwareMonitor.Hardware." +
moel@236
    78
        (IntPtr.Size == 4 ? "WinRing0.sys" : "WinRing0x64.sys");
moel@236
    79
moel@236
    80
      string[] names =
moel@236
    81
        Assembly.GetExecutingAssembly().GetManifestResourceNames();
moel@236
    82
      byte[] buffer = null;
moel@236
    83
      for (int i = 0; i < names.Length; i++) {
moel@236
    84
        if (names[i].Replace('\\', '.') == resourceName) {
moel@236
    85
          using (Stream stream = Assembly.GetExecutingAssembly().
moel@236
    86
            GetManifestResourceStream(names[i])) 
moel@236
    87
          {
moel@236
    88
              buffer = new byte[stream.Length];
moel@236
    89
              stream.Read(buffer, 0, buffer.Length);
moel@236
    90
          }
moel@236
    91
        }
moel@236
    92
      }
moel@236
    93
moel@236
    94
      if (buffer == null)
moel@236
    95
        return false;
moel@236
    96
moel@294
    97
      try {
moel@294
    98
        using (FileStream target = new FileStream(fileName, FileMode.Create)) {
moel@294
    99
          target.Write(buffer, 0, buffer.Length);
moel@294
   100
        }
moel@294
   101
      } catch (IOException) { 
moel@294
   102
        // for example there is not enough space on the disk
moel@294
   103
        return false; 
moel@236
   104
      }
moel@236
   105
moel@236
   106
      return true;
moel@236
   107
    }
moel@236
   108
moel@236
   109
    public static void Open() {
moel@254
   110
      // no implementation for unix systems
moel@238
   111
      int p = (int)Environment.OSVersion.Platform;
moel@238
   112
      if ((p == 4) || (p == 128))
moel@238
   113
        return;  
moel@238
   114
      
moel@236
   115
      if (driver != null)
moel@236
   116
        return;
moel@254
   117
moel@254
   118
      // clear the current report
moel@254
   119
      report.Length = 0;
moel@236
   120
     
moel@236
   121
      driver = new KernelDriver("WinRing0_1_2_0");
moel@236
   122
      driver.Open();
moel@236
   123
moel@236
   124
      if (!driver.IsOpen) {
moel@255
   125
        // driver is not loaded, try to reinstall and open
moel@255
   126
moel@255
   127
        driver.Delete();
moel@283
   128
        fileName = GetTempFileName();
moel@283
   129
        if (fileName != null && ExtractDriver(fileName)) {
moel@254
   130
          if (driver.Install(fileName)) {
moel@254
   131
            driver.Open();
moel@236
   132
moel@254
   133
            if (!driver.IsOpen) {
moel@254
   134
              driver.Delete();
moel@254
   135
              report.AppendLine("Status: Opening driver failed");
moel@254
   136
            }
moel@254
   137
          } else {
moel@283
   138
            report.AppendLine("Status: Installing driver \"" +
moel@283
   139
              fileName + "\" failed" +
moel@255
   140
              (File.Exists(fileName) ? " and file exists" : ""));
moel@254
   141
            report.AppendLine();
moel@254
   142
            report.Append("Exception: " + Marshal.GetExceptionForHR(
moel@254
   143
              Marshal.GetHRForLastWin32Error()).Message);
moel@254
   144
          }
moel@254
   145
        } else {
moel@283
   146
          report.AppendLine("Status: Extracting driver failed");
moel@236
   147
        }
moel@281
   148
moel@281
   149
        try {
moel@281
   150
          // try to delte the driver file
moel@281
   151
          if (File.Exists(fileName))
moel@281
   152
            File.Delete(fileName);
moel@281
   153
          fileName = null;
moel@281
   154
        } catch (IOException) { } 
moel@281
   155
          catch (UnauthorizedAccessException) { }
moel@236
   156
      }
moel@236
   157
moel@236
   158
      if (!driver.IsOpen) 
moel@236
   159
        driver = null;
moel@236
   160
moel@285
   161
      string mutexName = "Global\\Access_ISABUS.HTP.Method";
moel@285
   162
      try {
moel@285
   163
        isaBusMutex = new Mutex(false, mutexName);
moel@285
   164
      } catch (UnauthorizedAccessException) {
moel@285
   165
        try {
moel@285
   166
          isaBusMutex = Mutex.OpenExisting(mutexName, MutexRights.Synchronize);
moel@285
   167
        } catch { }
moel@285
   168
      }
moel@236
   169
    }
moel@236
   170
moel@236
   171
    public static bool IsOpen {
moel@236
   172
      get { return driver != null; }
moel@236
   173
    }
moel@236
   174
moel@236
   175
    public static void Close() {
moel@236
   176
      if (driver == null)
moel@236
   177
        return;
moel@236
   178
moel@236
   179
      uint refCount = 0;
moel@236
   180
      driver.DeviceIOControl(IOCTL_OLS_GET_REFCOUNT, null, ref refCount);
moel@236
   181
moel@236
   182
      driver.Close();
moel@236
   183
moel@236
   184
      if (refCount <= 1)
moel@236
   185
        driver.Delete();
moel@236
   186
moel@236
   187
      driver = null;
moel@236
   188
moel@285
   189
      if (isaBusMutex != null) {
moel@285
   190
        isaBusMutex.Close();
moel@285
   191
        isaBusMutex = null;
moel@285
   192
      }
moel@281
   193
moel@281
   194
      // try to delete temporary driver file again if failed during open
moel@281
   195
      if (fileName != null && File.Exists(fileName)) {
moel@281
   196
        try {
moel@281
   197
          File.Delete(fileName);
moel@281
   198
          fileName = null;
moel@281
   199
        } catch (IOException) { } 
moel@281
   200
          catch (UnauthorizedAccessException) { }
moel@281
   201
      }
moel@236
   202
    }
moel@236
   203
moel@254
   204
    public static string GetReport() {
moel@254
   205
      if (report.Length > 0) {
moel@256
   206
        StringBuilder r = new StringBuilder();
moel@256
   207
        r.AppendLine("Ring0");
moel@256
   208
        r.AppendLine();
moel@256
   209
        r.Append(report);
moel@256
   210
        r.AppendLine();
moel@256
   211
        return r.ToString();
moel@254
   212
      } else
moel@254
   213
        return null;
moel@254
   214
    }
moel@254
   215
moel@236
   216
    public static bool WaitIsaBusMutex(int millisecondsTimeout) {
moel@285
   217
      if (isaBusMutex == null)
moel@285
   218
        return true;
moel@236
   219
      try {
moel@236
   220
        return isaBusMutex.WaitOne(millisecondsTimeout, false);
moel@236
   221
      } catch (AbandonedMutexException) { return false; } 
moel@236
   222
        catch (InvalidOperationException) { return false; }
moel@236
   223
    }
moel@236
   224
moel@236
   225
    public static void ReleaseIsaBusMutex() {
moel@285
   226
      if (isaBusMutex == null)
moel@285
   227
        return;
moel@236
   228
      isaBusMutex.ReleaseMutex();
moel@236
   229
    }
moel@236
   230
moel@236
   231
    public static bool Rdmsr(uint index, out uint eax, out uint edx) {
moel@236
   232
      if (driver == null) {
moel@236
   233
        eax = 0;
moel@236
   234
        edx = 0;
moel@236
   235
        return false;
moel@236
   236
      }
moel@236
   237
moel@236
   238
      ulong buffer = 0;
moel@236
   239
      bool result = driver.DeviceIOControl(IOCTL_OLS_READ_MSR, index,
moel@236
   240
        ref buffer);
moel@236
   241
moel@236
   242
      edx = (uint)((buffer >> 32) & 0xFFFFFFFF);
moel@236
   243
      eax = (uint)(buffer & 0xFFFFFFFF);
moel@236
   244
      return result;
moel@236
   245
    }
moel@236
   246
moel@236
   247
    public static bool RdmsrTx(uint index, out uint eax, out uint edx,
moel@238
   248
      ulong threadAffinityMask) 
moel@236
   249
    {
moel@238
   250
      ulong mask = ThreadAffinity.Set(threadAffinityMask);
moel@236
   251
moel@236
   252
      bool result = Rdmsr(index, out eax, out edx);
moel@236
   253
moel@238
   254
      ThreadAffinity.Set(mask);
moel@236
   255
      return result;
moel@236
   256
    }
moel@236
   257
moel@236
   258
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@236
   259
    private struct WrmsrInput {
moel@236
   260
      public uint Register;
moel@236
   261
      public ulong Value;
moel@236
   262
    }
moel@236
   263
moel@236
   264
    public static bool Wrmsr(uint index, uint eax, uint edx) {
moel@236
   265
      if (driver == null)
moel@236
   266
        return false;
moel@236
   267
moel@236
   268
      WrmsrInput input = new WrmsrInput();
moel@236
   269
      input.Register = index;
moel@236
   270
      input.Value = ((ulong)edx << 32) | eax;
moel@236
   271
moel@236
   272
      return driver.DeviceIOControl(IOCTL_OLS_WRITE_MSR, input);
moel@236
   273
    }
moel@236
   274
moel@236
   275
    public static byte ReadIoPort(uint port) {
moel@236
   276
      if (driver == null)
moel@236
   277
        return 0;
moel@236
   278
moel@236
   279
      uint value = 0;
moel@236
   280
      driver.DeviceIOControl(IOCTL_OLS_READ_IO_PORT_BYTE, port, ref value);
moel@236
   281
moel@236
   282
      return (byte)(value & 0xFF);
moel@236
   283
    }
moel@236
   284
moel@236
   285
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@236
   286
    private struct WriteIoPortInput {
moel@236
   287
      public uint PortNumber;
moel@236
   288
      public byte Value;
moel@236
   289
    }
moel@236
   290
moel@236
   291
    public static void WriteIoPort(uint port, byte value) {
moel@236
   292
      if (driver == null)
moel@236
   293
        return;
moel@236
   294
moel@236
   295
      WriteIoPortInput input = new WriteIoPortInput();
moel@236
   296
      input.PortNumber = port;
moel@236
   297
      input.Value = value;
moel@236
   298
moel@236
   299
      driver.DeviceIOControl(IOCTL_OLS_WRITE_IO_PORT_BYTE, input);
moel@236
   300
    }
moel@236
   301
moel@236
   302
    public const uint InvalidPciAddress = 0xFFFFFFFF;
moel@236
   303
moel@236
   304
    public static uint GetPciAddress(byte bus, byte device, byte function) {
moel@236
   305
      return
moel@236
   306
        (uint)(((bus & 0xFF) << 8) | ((device & 0x1F) << 3) | (function & 7));
moel@236
   307
    }
moel@236
   308
moel@236
   309
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@236
   310
    private struct ReadPciConfigInput {
moel@236
   311
      public uint PciAddress;
moel@236
   312
      public uint RegAddress;
moel@236
   313
    }
moel@236
   314
moel@236
   315
    public static bool ReadPciConfig(uint pciAddress, uint regAddress, 
moel@236
   316
      out uint value) 
moel@236
   317
    {
moel@236
   318
      if (driver == null || (regAddress & 3) != 0) {
moel@236
   319
        value = 0;
moel@236
   320
        return false;
moel@236
   321
      }
moel@236
   322
moel@236
   323
      ReadPciConfigInput input = new ReadPciConfigInput();
moel@236
   324
      input.PciAddress = pciAddress;
moel@236
   325
      input.RegAddress = regAddress;
moel@236
   326
moel@236
   327
      value = 0;
moel@236
   328
      return driver.DeviceIOControl(IOCTL_OLS_READ_PCI_CONFIG, input, 
moel@236
   329
        ref value);
moel@236
   330
    }
moel@236
   331
moel@236
   332
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@236
   333
    private struct WritePciConfigInput {
moel@236
   334
      public uint PciAddress;
moel@236
   335
      public uint RegAddress;
moel@236
   336
      public uint Value;
moel@236
   337
    }
moel@236
   338
moel@236
   339
    public static bool WritePciConfig(uint pciAddress, uint regAddress, 
moel@236
   340
      uint value) 
moel@236
   341
    {
moel@236
   342
      if (driver == null || (regAddress & 3) != 0)
moel@236
   343
        return false;
moel@236
   344
moel@236
   345
      WritePciConfigInput input = new WritePciConfigInput();
moel@236
   346
      input.PciAddress = pciAddress;
moel@236
   347
      input.RegAddress = regAddress;
moel@236
   348
      input.Value = value;
moel@236
   349
moel@236
   350
      return driver.DeviceIOControl(IOCTL_OLS_WRITE_PCI_CONFIG, input);
moel@236
   351
    }
moel@279
   352
moel@279
   353
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
moel@279
   354
    private struct ReadMemoryInput {
moel@279
   355
      public ulong address;
moel@279
   356
      public uint unitSize;
moel@279
   357
      public uint count;
moel@279
   358
    }
moel@279
   359
moel@279
   360
    public static bool ReadMemory<T>(ulong address, ref T buffer) {
moel@279
   361
      if (driver == null) {
moel@279
   362
        return false;
moel@279
   363
      }
moel@279
   364
moel@279
   365
      ReadMemoryInput input = new ReadMemoryInput();
moel@279
   366
      input.address = address;
moel@279
   367
      input.unitSize = 1;
moel@279
   368
      input.count = (uint)Marshal.SizeOf(buffer);
moel@279
   369
moel@279
   370
      return driver.DeviceIOControl(IOCTL_OLS_READ_MEMORY, input,
moel@279
   371
        ref buffer);
moel@279
   372
    }
moel@236
   373
  }
moel@236
   374
}