Changed the license to the Mozilla Public License 2.0 and update the licensing information.
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-2011 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 (IntPtr.Size == 4 ? "WinRing0.sys" : "WinRing0x64.sys");
81 Assembly.GetExecutingAssembly().GetManifestResourceNames();
83 for (int i = 0; i < names.Length; i++) {
84 if (names[i].Replace('\\', '.') == resourceName) {
85 using (Stream stream = Assembly.GetExecutingAssembly().
86 GetManifestResourceStream(names[i]))
88 buffer = new byte[stream.Length];
89 stream.Read(buffer, 0, buffer.Length);
98 using (FileStream target = new FileStream(fileName, FileMode.Create)) {
99 target.Write(buffer, 0, buffer.Length);
101 } catch (IOException) {
102 // for example there is not enough space on the disk
109 public static void Open() {
110 // no implementation for unix systems
111 int p = (int)Environment.OSVersion.Platform;
112 if ((p == 4) || (p == 128))
118 // clear the current report
121 driver = new KernelDriver("WinRing0_1_2_0");
124 if (!driver.IsOpen) {
125 // driver is not loaded, try to reinstall and open
128 fileName = GetTempFileName();
129 if (fileName != null && ExtractDriver(fileName)) {
130 if (driver.Install(fileName)) {
133 if (!driver.IsOpen) {
135 report.AppendLine("Status: Opening driver failed");
138 report.AppendLine("Status: Installing driver \"" +
139 fileName + "\" failed" +
140 (File.Exists(fileName) ? " and file exists" : ""));
142 report.Append("Exception: " + Marshal.GetExceptionForHR(
143 Marshal.GetHRForLastWin32Error()).Message);
146 report.AppendLine("Status: Extracting driver failed");
150 // try to delte the driver file
151 if (File.Exists(fileName))
152 File.Delete(fileName);
154 } catch (IOException) { }
155 catch (UnauthorizedAccessException) { }
161 string mutexName = "Global\\Access_ISABUS.HTP.Method";
163 isaBusMutex = new Mutex(false, mutexName);
164 } catch (UnauthorizedAccessException) {
166 isaBusMutex = Mutex.OpenExisting(mutexName, MutexRights.Synchronize);
171 public static bool IsOpen {
172 get { return driver != null; }
175 public static void Close() {
180 driver.DeviceIOControl(IOCTL_OLS_GET_REFCOUNT, null, ref refCount);
189 if (isaBusMutex != null) {
194 // try to delete temporary driver file again if failed during open
195 if (fileName != null && File.Exists(fileName)) {
197 File.Delete(fileName);
199 } catch (IOException) { }
200 catch (UnauthorizedAccessException) { }
204 public static string GetReport() {
205 if (report.Length > 0) {
206 StringBuilder r = new StringBuilder();
207 r.AppendLine("Ring0");
216 public static bool WaitIsaBusMutex(int millisecondsTimeout) {
217 if (isaBusMutex == null)
220 return isaBusMutex.WaitOne(millisecondsTimeout, false);
221 } catch (AbandonedMutexException) { return false; }
222 catch (InvalidOperationException) { return false; }
225 public static void ReleaseIsaBusMutex() {
226 if (isaBusMutex == null)
228 isaBusMutex.ReleaseMutex();
231 public static bool Rdmsr(uint index, out uint eax, out uint edx) {
232 if (driver == null) {
239 bool result = driver.DeviceIOControl(IOCTL_OLS_READ_MSR, index,
242 edx = (uint)((buffer >> 32) & 0xFFFFFFFF);
243 eax = (uint)(buffer & 0xFFFFFFFF);
247 public static bool RdmsrTx(uint index, out uint eax, out uint edx,
248 ulong threadAffinityMask)
250 ulong mask = ThreadAffinity.Set(threadAffinityMask);
252 bool result = Rdmsr(index, out eax, out edx);
254 ThreadAffinity.Set(mask);
258 [StructLayout(LayoutKind.Sequential, Pack = 1)]
259 private struct WrmsrInput {
260 public uint Register;
264 public static bool Wrmsr(uint index, uint eax, uint edx) {
268 WrmsrInput input = new WrmsrInput();
269 input.Register = index;
270 input.Value = ((ulong)edx << 32) | eax;
272 return driver.DeviceIOControl(IOCTL_OLS_WRITE_MSR, input);
275 public static byte ReadIoPort(uint port) {
280 driver.DeviceIOControl(IOCTL_OLS_READ_IO_PORT_BYTE, port, ref value);
282 return (byte)(value & 0xFF);
285 [StructLayout(LayoutKind.Sequential, Pack = 1)]
286 private struct WriteIoPortInput {
287 public uint PortNumber;
291 public static void WriteIoPort(uint port, byte value) {
295 WriteIoPortInput input = new WriteIoPortInput();
296 input.PortNumber = port;
299 driver.DeviceIOControl(IOCTL_OLS_WRITE_IO_PORT_BYTE, input);
302 public const uint InvalidPciAddress = 0xFFFFFFFF;
304 public static uint GetPciAddress(byte bus, byte device, byte function) {
306 (uint)(((bus & 0xFF) << 8) | ((device & 0x1F) << 3) | (function & 7));
309 [StructLayout(LayoutKind.Sequential, Pack = 1)]
310 private struct ReadPciConfigInput {
311 public uint PciAddress;
312 public uint RegAddress;
315 public static bool ReadPciConfig(uint pciAddress, uint regAddress,
318 if (driver == null || (regAddress & 3) != 0) {
323 ReadPciConfigInput input = new ReadPciConfigInput();
324 input.PciAddress = pciAddress;
325 input.RegAddress = regAddress;
328 return driver.DeviceIOControl(IOCTL_OLS_READ_PCI_CONFIG, input,
332 [StructLayout(LayoutKind.Sequential, Pack = 1)]
333 private struct WritePciConfigInput {
334 public uint PciAddress;
335 public uint RegAddress;
339 public static bool WritePciConfig(uint pciAddress, uint regAddress,
342 if (driver == null || (regAddress & 3) != 0)
345 WritePciConfigInput input = new WritePciConfigInput();
346 input.PciAddress = pciAddress;
347 input.RegAddress = regAddress;
350 return driver.DeviceIOControl(IOCTL_OLS_WRITE_PCI_CONFIG, input);
353 [StructLayout(LayoutKind.Sequential, Pack = 1)]
354 private struct ReadMemoryInput {
355 public ulong address;
356 public uint unitSize;
360 public static bool ReadMemory<T>(ulong address, ref T buffer) {
361 if (driver == null) {
365 ReadMemoryInput input = new ReadMemoryInput();
366 input.address = address;
368 input.count = (uint)Marshal.SizeOf(buffer);
370 return driver.DeviceIOControl(IOCTL_OLS_READ_MEMORY, input,