Fixed Issue 274. Fixed Issue 107.
3 This Source Code Form is subject to the terms of the Mozilla Public
4 License, v. 2.0. If a copy of the MPL was not distributed with this
5 file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 Copyright (C) 2010-2012 Michael Möller <mmoeller@openhardwaremonitor.org>
13 using System.Reflection;
14 using System.Runtime.InteropServices;
15 using System.Security.AccessControl;
16 using System.Threading;
19 namespace OpenHardwareMonitor.Hardware {
20 internal static class Ring0 {
22 private static KernelDriver driver;
23 private static string fileName;
24 private static Mutex isaBusMutex;
25 private static readonly StringBuilder report = new StringBuilder();
27 private const uint OLS_TYPE = 40000;
28 private static IOControlCode
29 IOCTL_OLS_GET_REFCOUNT = new IOControlCode(OLS_TYPE, 0x801,
30 IOControlCode.Access.Any),
31 IOCTL_OLS_GET_DRIVER_VERSION = new IOControlCode(OLS_TYPE, 0x800,
32 IOControlCode.Access.Any),
33 IOCTL_OLS_READ_MSR = new IOControlCode(OLS_TYPE, 0x821,
34 IOControlCode.Access.Any),
35 IOCTL_OLS_WRITE_MSR = new IOControlCode(OLS_TYPE, 0x822,
36 IOControlCode.Access.Any),
37 IOCTL_OLS_READ_IO_PORT_BYTE = new IOControlCode(OLS_TYPE, 0x833,
38 IOControlCode.Access.Read),
39 IOCTL_OLS_WRITE_IO_PORT_BYTE = new IOControlCode(OLS_TYPE, 0x836,
40 IOControlCode.Access.Write),
41 IOCTL_OLS_READ_PCI_CONFIG = new IOControlCode(OLS_TYPE, 0x851,
42 IOControlCode.Access.Read),
43 IOCTL_OLS_WRITE_PCI_CONFIG = new IOControlCode(OLS_TYPE, 0x852,
44 IOControlCode.Access.Write),
45 IOCTL_OLS_READ_MEMORY = new IOControlCode(OLS_TYPE, 0x841,
46 IOControlCode.Access.Read);
48 private static string GetTempFileName() {
50 // try to get a file in the temporary folder
52 return Path.GetTempFileName();
53 } catch (IOException) {
56 catch (UnauthorizedAccessException) {
57 // we do not have the right to create a file in the temp folder
59 catch (NotSupportedException) {
60 // invalid path format of the TMP system environment variable
63 // if this failed, we try to create one in the application folder
64 string fileName = Path.ChangeExtension(
65 Assembly.GetExecutingAssembly().Location, ".sys");
67 using (FileStream stream = File.Create(fileName)) {
70 } catch (IOException) { }
71 catch (UnauthorizedAccessException) { }
76 private static bool ExtractDriver(string fileName) {
77 string resourceName = "OpenHardwareMonitor.Hardware." +
78 (OperatingSystem.Is64BitOperatingSystem() ? "WinRing0x64.sys" :
82 Assembly.GetExecutingAssembly().GetManifestResourceNames();
84 for (int i = 0; i < names.Length; i++) {
85 if (names[i].Replace('\\', '.') == resourceName) {
86 using (Stream stream = Assembly.GetExecutingAssembly().
87 GetManifestResourceStream(names[i]))
89 buffer = new byte[stream.Length];
90 stream.Read(buffer, 0, buffer.Length);
99 using (FileStream target = new FileStream(fileName, FileMode.Create)) {
100 target.Write(buffer, 0, buffer.Length);
102 } catch (IOException) {
103 // for example there is not enough space on the disk
110 public static void Open() {
111 // no implementation for unix systems
112 int p = (int)Environment.OSVersion.Platform;
113 if ((p == 4) || (p == 128))
119 // clear the current report
122 driver = new KernelDriver("WinRing0_1_2_0");
125 if (!driver.IsOpen) {
126 // driver is not loaded, try to reinstall and open
129 fileName = GetTempFileName();
130 if (fileName != null && ExtractDriver(fileName)) {
131 if (driver.Install(fileName)) {
134 if (!driver.IsOpen) {
136 report.AppendLine("Status: Opening driver failed");
139 report.AppendLine("Status: Installing driver \"" +
140 fileName + "\" failed" +
141 (File.Exists(fileName) ? " and file exists" : ""));
143 report.Append("Exception: " + Marshal.GetExceptionForHR(
144 Marshal.GetHRForLastWin32Error()).Message);
147 report.AppendLine("Status: Extracting driver failed");
151 // try to delte the driver file
152 if (File.Exists(fileName))
153 File.Delete(fileName);
155 } catch (IOException) { }
156 catch (UnauthorizedAccessException) { }
162 string mutexName = "Global\\Access_ISABUS.HTP.Method";
164 isaBusMutex = new Mutex(false, mutexName);
165 } catch (UnauthorizedAccessException) {
167 isaBusMutex = Mutex.OpenExisting(mutexName, MutexRights.Synchronize);
172 public static bool IsOpen {
173 get { return driver != null; }
176 public static void Close() {
181 driver.DeviceIOControl(IOCTL_OLS_GET_REFCOUNT, null, ref refCount);
190 if (isaBusMutex != null) {
195 // try to delete temporary driver file again if failed during open
196 if (fileName != null && File.Exists(fileName)) {
198 File.Delete(fileName);
200 } catch (IOException) { }
201 catch (UnauthorizedAccessException) { }
205 public static string GetReport() {
206 if (report.Length > 0) {
207 StringBuilder r = new StringBuilder();
208 r.AppendLine("Ring0");
217 public static bool WaitIsaBusMutex(int millisecondsTimeout) {
218 if (isaBusMutex == null)
221 return isaBusMutex.WaitOne(millisecondsTimeout, false);
222 } catch (AbandonedMutexException) { return false; }
223 catch (InvalidOperationException) { return false; }
226 public static void ReleaseIsaBusMutex() {
227 if (isaBusMutex == null)
229 isaBusMutex.ReleaseMutex();
232 public static bool Rdmsr(uint index, out uint eax, out uint edx) {
233 if (driver == null) {
240 bool result = driver.DeviceIOControl(IOCTL_OLS_READ_MSR, index,
243 edx = (uint)((buffer >> 32) & 0xFFFFFFFF);
244 eax = (uint)(buffer & 0xFFFFFFFF);
248 public static bool RdmsrTx(uint index, out uint eax, out uint edx,
249 ulong threadAffinityMask)
251 ulong mask = ThreadAffinity.Set(threadAffinityMask);
253 bool result = Rdmsr(index, out eax, out edx);
255 ThreadAffinity.Set(mask);
259 [StructLayout(LayoutKind.Sequential, Pack = 1)]
260 private struct WrmsrInput {
261 public uint Register;
265 public static bool Wrmsr(uint index, uint eax, uint edx) {
269 WrmsrInput input = new WrmsrInput();
270 input.Register = index;
271 input.Value = ((ulong)edx << 32) | eax;
273 return driver.DeviceIOControl(IOCTL_OLS_WRITE_MSR, input);
276 public static byte ReadIoPort(uint port) {
281 driver.DeviceIOControl(IOCTL_OLS_READ_IO_PORT_BYTE, port, ref value);
283 return (byte)(value & 0xFF);
286 [StructLayout(LayoutKind.Sequential, Pack = 1)]
287 private struct WriteIoPortInput {
288 public uint PortNumber;
292 public static void WriteIoPort(uint port, byte value) {
296 WriteIoPortInput input = new WriteIoPortInput();
297 input.PortNumber = port;
300 driver.DeviceIOControl(IOCTL_OLS_WRITE_IO_PORT_BYTE, input);
303 public const uint InvalidPciAddress = 0xFFFFFFFF;
305 public static uint GetPciAddress(byte bus, byte device, byte function) {
307 (uint)(((bus & 0xFF) << 8) | ((device & 0x1F) << 3) | (function & 7));
310 [StructLayout(LayoutKind.Sequential, Pack = 1)]
311 private struct ReadPciConfigInput {
312 public uint PciAddress;
313 public uint RegAddress;
316 public static bool ReadPciConfig(uint pciAddress, uint regAddress,
319 if (driver == null || (regAddress & 3) != 0) {
324 ReadPciConfigInput input = new ReadPciConfigInput();
325 input.PciAddress = pciAddress;
326 input.RegAddress = regAddress;
329 return driver.DeviceIOControl(IOCTL_OLS_READ_PCI_CONFIG, input,
333 [StructLayout(LayoutKind.Sequential, Pack = 1)]
334 private struct WritePciConfigInput {
335 public uint PciAddress;
336 public uint RegAddress;
340 public static bool WritePciConfig(uint pciAddress, uint regAddress,
343 if (driver == null || (regAddress & 3) != 0)
346 WritePciConfigInput input = new WritePciConfigInput();
347 input.PciAddress = pciAddress;
348 input.RegAddress = regAddress;
351 return driver.DeviceIOControl(IOCTL_OLS_WRITE_PCI_CONFIG, input);
354 [StructLayout(LayoutKind.Sequential, Pack = 1)]
355 private struct ReadMemoryInput {
356 public ulong address;
357 public uint unitSize;
361 public static bool ReadMemory<T>(ulong address, ref T buffer) {
362 if (driver == null) {
366 ReadMemoryInput input = new ReadMemoryInput();
367 input.address = address;
369 input.count = (uint)Marshal.SizeOf(buffer);
371 return driver.DeviceIOControl(IOCTL_OLS_READ_MEMORY, input,