private bool SetTdp(double tdpPerc, uint defaultLimit)
        {
            uint currentLimit = (uint)(tdpPerc * (double)defaultLimit) / 100;
            var  ret          = NvmlNativeMethods.nvmlDeviceSetPowerManagementLimit(_nvmlDevice, currentLimit);

            if (ret != nvmlReturn.Success)
            {
                throw new Exception($"NVML nvmlDeviceGetPowerManagementLimitConstraints failed with status: {ret}");
            }

            return(true);
        }
        private bool SetTdp(nvmlDevice nvmlDevice, double tdpPerc, uint defaultLimit)
        {
            // TODO we limit to 100%
            uint currentLimit = (uint)(tdpPerc * (double)defaultLimit) / 100;
            var  ret          = NvmlNativeMethods.nvmlDeviceSetPowerManagementLimit(nvmlDevice, currentLimit);

            if (ret != nvmlReturn.Success)
            {
                throw new NvmlException("nvmlDeviceSetPowerManagementLimit", ret);
            }

            return(true);
        }
Example #3
0
        private static bool NvmlInit()
        {
            if (_isNvmlInited)
            {
                return(_isNvmlInited);
            }
            lock (_locker) {
                if (_isNvmlInited)
                {
                    return(_isNvmlInited);
                }
                try {
#if DEBUG
                    NTStopwatch.Start();
#endif
                    if (!Directory.Exists(_nvsmiDir))
                    {
                        Directory.CreateDirectory(_nvsmiDir);
                    }
                    if (!File.Exists(_nvmlDllFileFullName) && File.Exists(_nvmlDllFileFullName2))
                    {
                        File.Copy(_nvmlDllFileFullName2, _nvmlDllFileFullName);
                    }
                    NvmlNativeMethods.SetDllDirectory(_nvsmiDir);
                    var nvmlReturn = NvmlNativeMethods.nvmlInit();
                    NvmlNativeMethods.SetDllDirectory(null);
                    _isNvmlInited = nvmlReturn == nvmlReturn.Success;
                    // 没什么用,做个防御
                    if (!_isNvmlInited)
                    {
                        _nvmlInitFailCount++;
                        if (_nvmlInitFailCount >= 10)
                        {
                            _isNvmlInited = true;
                        }
                    }
#if DEBUG
                    var elapsedMilliseconds = NTStopwatch.Stop();
                    if (elapsedMilliseconds.ElapsedMilliseconds > NTStopwatch.ElapsedMilliseconds)
                    {
                        NTMinerConsole.DevTimeSpan($"耗时{elapsedMilliseconds} {nameof(NvmlHelper)}.{nameof(NvmlInit)}()");
                    }
#endif
                    return(_isNvmlInited);
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                }
                return(false);
            }
        }
Example #4
0
        public NVIDIAGpuSet(INTMinerRoot root)
        {
            _root           = root;
            this.Properties = new List <GpuSetProperty>();
            if (Design.IsInDesignMode)
            {
                return;
            }
            string nvsmiDir = Path.Combine(Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles), "NVIDIA Corporation", "NVSMI");

            if (Directory.Exists(nvsmiDir))
            {
                Windows.DllDirectory.SetDllDirectory(nvsmiDir);
                NvmlNativeMethods.nvmlInit();
                _isNvmlInited = true;
                uint deviceCount = 0;
                NvmlNativeMethods.nvmlDeviceGetCount(ref deviceCount);
                _nvmlDevices = new nvmlDevice[deviceCount];
                for (int i = 0; i < deviceCount; i++)
                {
                    NvmlNativeMethods.nvmlDeviceGetHandleByIndex((uint)i, ref _nvmlDevices[i]);
                    string name;
                    uint   gClock = 0, mClock = 0;
                    NvmlNativeMethods.nvmlDeviceGetName(_nvmlDevices[i], out name);
                    NvmlNativeMethods.nvmlDeviceGetMaxClockInfo(_nvmlDevices[i], nvmlClockType.Graphics, ref gClock);
                    NvmlNativeMethods.nvmlDeviceGetMaxClockInfo(_nvmlDevices[i], nvmlClockType.Mem, ref mClock);
                    _gpus.Add(i, new Gpu {
                        Index = i,
                        Name  = name
                    });
                }
                string driverVersion;
                NvmlNativeMethods.nvmlSystemGetDriverVersion(out driverVersion);
                string nvmlVersion;
                NvmlNativeMethods.nvmlSystemGetNVMLVersion(out nvmlVersion);
                this.Properties.Add(new GpuSetProperty("DriverVersion", "driver version", driverVersion));
                this.Properties.Add(new GpuSetProperty("NVMLVersion", "NVML version", nvmlVersion));
            }
            Global.Access <Per5SecondEvent>(
                Guid.Parse("7C379223-D494-4213-9659-A086FFDE36DF"),
                "周期刷新显卡状态",
                LogEnum.None,
                action: message => {
                Task.Factory.StartNew(() => {
                    LoadGpuState();
                });
            });
        }
        private bool SetTdpPercentage(double tdpPerc)
        {
            var execRet = ExecNvmlProcedure(false, $"{nameof(SetTdpPercentage)}({tdpPerc})", () => {
                var nvmlDevice    = GetNvmlDevice();
                uint defaultLimit = 0;
                var ret           = NvmlNativeMethods.nvmlDeviceGetPowerManagementDefaultLimit(nvmlDevice, ref defaultLimit);
                if (ret != nvmlReturn.Success)
                {
                    throw new NvmlException($"nvmlDeviceGetPowerManagementDefaultLimit", ret);
                }

                return(SetTdp(nvmlDevice, tdpPerc, defaultLimit));
            });

            return(execRet);
        }
Example #6
0
        public uint GetTemperature(int gpuIndex)
        {
            if (!NvmlInit() || !TryGetNvmlDevice(gpuIndex, out nvmlDevice nvmlDevice))
            {
                return(0);
            }
            uint temp = 0;

            try {
                var r = NvmlNativeMethods.nvmlDeviceGetTemperature(nvmlDevice, nvmlTemperatureSensors.Gpu, ref temp);
                CheckResult(r, () => $"{nameof(NvmlNativeMethods.nvmlDeviceGetTemperature)} {r.ToString()}");
            }
            catch {
            }
            return(temp);
        }
        private nvmlDevice GetNvmlDevice()
        {
            if (_nvmlDevice.HasValue)
            {
                return(_nvmlDevice.Value);
            }
            var nvmlHandle = new nvmlDevice();
            var nvmlRet    = NvmlNativeMethods.nvmlDeviceGetHandleByUUID(UUID, ref nvmlHandle);

            if (nvmlRet != nvmlReturn.Success)
            {
                throw new NvmlException("nvmlDeviceGetHandleByUUID", nvmlRet);
            }
            _nvmlDevice = nvmlHandle;
            return(nvmlHandle);
        }
Example #8
0
 internal static bool ShutdownNvml()
 {
     try
     {
         var ret = NvmlNativeMethods.nvmlShutdown();
         if (ret != nvmlReturn.Success)
         {
             throw new Exception($"NVML shutdown failed with code {ret}");
         }
         return(true);
     }
     catch (Exception e)
     {
         Logger.Error(Tag, e.Message);
         return(false);
     }
 }
Example #9
0
        public List <NvGpu> GetGpus()
        {
            List <NvGpu> results = new List <NvGpu>();

            try {
                if (NvmlInit())
                {
                    _nvmlDevices.Clear();
                    uint deviceCount = 0;
                    var  r           = NvmlNativeMethods.nvmlDeviceGetCount(ref deviceCount);
                    CheckResult(r, () => $"{nameof(NvmlNativeMethods.nvmlDeviceGetCount)} {r.ToString()}");
                    for (int i = 0; i < deviceCount; i++)
                    {
                        NvGpu gpu = new NvGpu {
                            GpuIndex = i
                        };
                        nvmlDevice nvmlDevice = new nvmlDevice();
                        r = NvmlNativeMethods.nvmlDeviceGetHandleByIndex((uint)i, ref nvmlDevice);
                        _nvmlDevices.Add(nvmlDevice);
                        CheckResult(r, () => $"{nameof(NvmlNativeMethods.nvmlDeviceGetHandleByIndex)}({((uint)i).ToString()}) {r.ToString()}");
                        r = NvmlNativeMethods.nvmlDeviceGetName(nvmlDevice, out string name);
                        CheckResult(r, () => $"{nameof(NvmlNativeMethods.nvmlDeviceGetName)} {r.ToString()}");
                        nvmlMemory memory = new nvmlMemory();
                        r = NvmlNativeMethods.nvmlDeviceGetMemoryInfo(nvmlDevice, ref memory);
                        CheckResult(r, () => $"{nameof(NvmlNativeMethods.nvmlDeviceGetMemoryInfo)} {r.ToString()}");
                        // short gpu name
                        if (!string.IsNullOrEmpty(name))
                        {
                            name = name.Replace("GeForce GTX ", string.Empty);
                            name = name.Replace("GeForce ", string.Empty);
                        }
                        nvmlPciInfo pci = new nvmlPciInfo();
                        r = NvmlNativeMethods.nvmlDeviceGetPciInfo(nvmlDevice, ref pci);
                        CheckResult(r, () => $"{nameof(NvmlNativeMethods.nvmlDeviceGetPciInfo)} {r.ToString()}");
                        gpu.Name        = name;
                        gpu.BusId       = (int)pci.bus;
                        gpu.TotalMemory = memory.total;
                        results.Add(gpu);
                    }
                }
            }
            catch {
            }

            return(results);
        }
Example #10
0
        public uint GetTemperature(int gpuIndex)
        {
            if (!NvmlInit() || !TryGetNvmlDevice(gpuIndex, out nvmlDevice nvmlDevice))
            {
                return(0);
            }
            uint temp = 0;

            try {
                var r = NvmlNativeMethods.nvmlDeviceGetTemperature(nvmlDevice, nvmlTemperatureSensors.Gpu, ref temp);
                if (r != nvmlReturn.Success)
                {
                    NTMinerConsole.DevError(() => $"{nameof(NvmlNativeMethods.nvmlDeviceGetTemperature)} {r.ToString()}");
                }
            }
            catch {
            }
            return(temp);
        }
Example #11
0
        public uint GetFanSpeed(int gpuIndex)
        {
            if (!NvmlInit() || !TryGetNvmlDevice(gpuIndex, out nvmlDevice nvmlDevice))
            {
                return(0);
            }
            uint fanSpeed = 0;

            try {
                var r = NvmlNativeMethods.nvmlDeviceGetFanSpeed(nvmlDevice, ref fanSpeed);
                if (r != nvmlReturn.Success)
                {
                    Write.DevError($"{nameof(NvmlNativeMethods.nvmlDeviceGetFanSpeed)} {r}");
                }
            }
            catch {
            }
            return(fanSpeed);
        }
Example #12
0
        public uint GetFanSpeed(int gpuIndex)
        {
            if (!NvmlInit() || !TryGetNvmlDevice(gpuIndex, out nvmlDevice nvmlDevice))
            {
                return(0);
            }
            uint fanSpeed = 0;

            try {
                var r = NvmlNativeMethods.nvmlDeviceGetFanSpeed(nvmlDevice, ref fanSpeed);
                if (!_isFirstGetFanSpeed.Contains(gpuIndex))
                {
                    _isFirstGetFanSpeed.Add(gpuIndex);
                    CheckResult(r, () => $"{nameof(NvmlNativeMethods.nvmlDeviceGetFanSpeed)} {r.ToString()}");
                }
            }
            catch {
            }
            return(fanSpeed);
        }
Example #13
0
        public uint GetPowerUsage(int gpuIndex)
        {
            if (!NvmlInit() || !TryGetNvmlDevice(gpuIndex, out nvmlDevice nvmlDevice))
            {
                return(0);
            }
            uint power = 0;

            try {
                var r = NvmlNativeMethods.nvmlDeviceGetPowerUsage(nvmlDevice, ref power);
                power = (uint)(power / 1000.0);
                if (r != nvmlReturn.Success)
                {
                    Write.DevError($"{nameof(NvmlNativeMethods.nvmlDeviceGetPowerUsage)} {r}");
                }
            }
            catch {
            }
            return(power);
        }
Example #14
0
        private bool ExecNvmlSetTDP(string calledFrom, double percentage)
        {
            var execRet = ExecNvmlProcedure(false, calledFrom, () => {
                var nvmlDevice = GetNvmlDevice();
                uint minLimit  = 0;
                uint maxLimit  = 0;
                var ret        = NvmlNativeMethods.nvmlDeviceGetPowerManagementLimitConstraints(nvmlDevice, ref minLimit, ref maxLimit);
                if (ret != nvmlReturn.Success)
                {
                    throw new NvmlException($"nvmlDeviceGetPowerManagementLimitConstraints", ret);
                }

                uint defaultLimit = 0;
                ret = NvmlNativeMethods.nvmlDeviceGetPowerManagementDefaultLimit(nvmlDevice, ref defaultLimit);
                if (ret != nvmlReturn.Success)
                {
                    throw new NvmlException($"nvmlDeviceGetPowerManagementDefaultLimit", ret);
                }

                // We limit 100% to the default as max
                var limit    = RangeCalculator.CalculateValueNVIDIA(percentage, defaultLimit);
                var setLimit = (uint)limit;
                if (setLimit > maxLimit)
                {
                    setLimit = maxLimit;
                }
                if (setLimit < minLimit)
                {
                    setLimit = minLimit;
                }
                ret = NvmlNativeMethods.nvmlDeviceSetPowerManagementLimit(nvmlDevice, setLimit);
                if (ret != nvmlReturn.Success)
                {
                    throw new NvmlException("nvmlDeviceSetPowerManagementLimit", ret);
                }

                return(true);
            });

            return(execRet);
        }
Example #15
0
 // 注意:因为转化为Version对象时会将457.09格式的字符串变成457.9格式的Version,为了保留前缀0这里输出原始字符串
 public void GetVersion(out string driverVersion, out string nvmlVersion)
 {
     driverVersion = "0.0";
     nvmlVersion   = "0.0";
     if (!NvmlInit())
     {
         return;
     }
     try {
         var r = NvmlNativeMethods.nvmlSystemGetDriverVersion(out driverVersion);
         CheckResult(r, () => $"{nameof(NvmlNativeMethods.nvmlSystemGetDriverVersion)} {r.ToString()}");
         r = NvmlNativeMethods.nvmlSystemGetNVMLVersion(out nvmlVersion);
         CheckResult(r, () => $"{nameof(NvmlNativeMethods.nvmlSystemGetNVMLVersion)} {r.ToString()}");
         if (string.IsNullOrEmpty(nvmlVersion))
         {
             nvmlVersion = "0.0";
         }
     }
     catch {
     }
 }
Example #16
0
        // NVAPI貌似没有读取功耗的接口,所以只能使用NVML
        public uint GetPowerUsage(int gpuIndex)
        {
            if (!NvmlInit() || !TryGetNvmlDevice(gpuIndex, out nvmlDevice nvmlDevice))
            {
                return(0);
            }
            uint power = 0;

            try {
                var r = NvmlNativeMethods.nvmlDeviceGetPowerUsage(nvmlDevice, ref power);
                power = (uint)(power / 1000.0);
                if (!_isFirstGetPowerUsage.Contains(gpuIndex))
                {
                    _isFirstGetPowerUsage.Add(gpuIndex);
                    CheckResult(r, () => $"{nameof(NvmlNativeMethods.nvmlDeviceGetPowerUsage)} {r.ToString()}");
                }
            }
            catch {
            }
            return(power);
        }
        public static List <NvapiNvmlInfo> Init(Dictionary <string, int> nvidiaUUIDAndBusIds, bool useNvmlFallback)
        {
            // Enumerate NVAPI handles and map to busid
            var idHandles = InitNvapi();

            if (!useNvmlFallback)
            {
                Logger.Info(Tag, "tryAddNvmlToEnvPath");
                tryAddNvmlToEnvPath();
            }
            else
            {
                Logger.Info(Tag, "tryAddNvmlToEnvPathFallback");
                tryAddNvmlToEnvPathFallback();
            }
            var nvmlInit = InitNvml();
            var ret      = new List <NvapiNvmlInfo>();

            foreach (var pair in nvidiaUUIDAndBusIds)
            {
                var uuid  = pair.Key;
                var busID = pair.Value;

                var nvmlHandle = new nvmlDevice();
                if (nvmlInit)
                {
                    var nvmlRet = NvmlNativeMethods.nvmlDeviceGetHandleByUUID(uuid, ref nvmlHandle);
                    Logger.Info(Tag, "NVML HANDLE:" + $"{(nvmlRet == nvmlReturn.Success ? nvmlHandle.Pointer.ToString() : $"Failed with code ret {ret}")}");
                }
                idHandles.TryGetValue(busID, out var handle);
                var info = new NvapiNvmlInfo
                {
                    UUID       = uuid,
                    BusID      = busID,
                    nvHandle   = handle,
                    nvmlHandle = nvmlHandle
                };
                ret.Add(info);
            }
Example #18
0
        public static bool NvmlInit()
        {
            if (_isNvmlInited)
            {
                return(_isNvmlInited);
            }
            lock (_nvmlInitLocker) {
                if (_isNvmlInited)
                {
                    return(_isNvmlInited);
                }
                try {
#if DEBUG
                    VirtualRoot.Stopwatch.Restart();
#endif
                    if (!Directory.Exists(_nvsmiDir))
                    {
                        Directory.CreateDirectory(_nvsmiDir);
                    }
                    if (!File.Exists(_nvmlDllFileFullName) && File.Exists(_nvmlDllFileFullName2))
                    {
                        File.Copy(_nvmlDllFileFullName2, _nvmlDllFileFullName);
                    }
                    Windows.NativeMethods.SetDllDirectory(_nvsmiDir);
                    var nvmlReturn = NvmlNativeMethods.nvmlInit();
                    Windows.NativeMethods.SetDllDirectory(null);
                    SetGpuStatus(Gpu.GpuAll, nvmlReturn);
                    _isNvmlInited = nvmlReturn == nvmlReturn.Success;
#if DEBUG
                    Write.DevWarn($"耗时{VirtualRoot.Stopwatch.ElapsedMilliseconds}毫秒 {nameof(NVIDIAGpuSet)}.{nameof(NvmlInit)}()");
#endif
                    return(_isNvmlInited);
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                }
                return(false);
            }
        }
Example #19
0
        public void LoadGpuState()
        {
            foreach (Gpu gpu in _gpus.Values)
            {
                int i = gpu.Index;
                if (i == NTMinerRoot.GpuAllId)
                {
                    continue;
                }
                nvmlDevice nvmlDevice = new nvmlDevice();
                var        nvmlReturn = NvmlNativeMethods.nvmlDeviceGetHandleByIndex((uint)i, ref nvmlDevice);
                // 显卡重启了,此时nvmlReturn是Unknown
                if (nvmlReturn == nvmlReturn.Unknown && nvmlShutdownRestartCount < 20)
                {
                    nvmlShutdownRestartCount++;
                    NvmlNativeMethods.nvmlShutdown();
                    _isNvmlInited = false;
                    NvmlInit();
                }
                nvmlReturn = NvmlNativeMethods.nvmlDeviceGetHandleByIndex((uint)i, ref nvmlDevice);
                SetGpuStatus(gpu, nvmlReturn);
                uint power = 0;
                NvmlNativeMethods.nvmlDeviceGetPowerUsage(nvmlDevice, ref power);
                power = (uint)(power / 1000.0);
                uint temp = 0;
                NvmlNativeMethods.nvmlDeviceGetTemperature(nvmlDevice, nvmlTemperatureSensors.Gpu, ref temp);
                uint speed = 0;
                NvmlNativeMethods.nvmlDeviceGetFanSpeed(nvmlDevice, ref speed);
                bool isChanged = gpu.Temperature != temp || gpu.PowerUsage != power || gpu.FanSpeed != speed;
                gpu.Temperature = (int)temp;
                gpu.PowerUsage  = power;
                gpu.FanSpeed    = speed;

                if (isChanged)
                {
                    VirtualRoot.Happened(new GpuStateChangedEvent(gpu));
                }
            }
        }
        public bool SetTDPRaw(double raw)
        {
            if (DeviceMonitorManager.DisableDevicePowerModeSettings)
            {
                Logger.InfoDelayed(LogTag, $"SetTDPRaw Disabled DeviceMonitorManager.DisableDevicePowerModeSettings==true", TimeSpan.FromSeconds(30));
                return(false);
            }
            var execRet = ExecNvmlProcedure(false, $"{nameof(SetTDPRaw)}({raw})", () => {
                var nvmlDevice = GetNvmlDevice();
                uint minLimit  = 0;
                uint maxLimit  = 0;
                var ret        = NvmlNativeMethods.nvmlDeviceGetPowerManagementLimitConstraints(nvmlDevice, ref minLimit, ref maxLimit);
                if (ret != nvmlReturn.Success)
                {
                    throw new NvmlException($"nvmlDeviceGetPowerManagementLimitConstraints", ret);
                }

                uint defaultLimit = 0;
                ret = NvmlNativeMethods.nvmlDeviceGetPowerManagementDefaultLimit(nvmlDevice, ref defaultLimit);
                if (ret != nvmlReturn.Success)
                {
                    throw new NvmlException($"nvmlDeviceGetPowerManagementDefaultLimit", ret);
                }

                // We limit 100% to the default as max
                var limit    = Math.Max((uint)raw, minLimit);
                var setLimit = Math.Min(limit, defaultLimit);
                ret          = NvmlNativeMethods.nvmlDeviceSetPowerManagementLimit(nvmlDevice, setLimit);
                if (ret != nvmlReturn.Success)
                {
                    throw new NvmlException("nvmlDeviceSetPowerManagementLimit", ret);
                }

                return(true);
            });

            return(execRet);
        }
Example #21
0
        private static bool NvmlInit()
        {
            if (_isNvmlInited)
            {
                return(_isNvmlInited);
            }
            lock (_nvmlInitLocker) {
                if (_isNvmlInited)
                {
                    return(_isNvmlInited);
                }
                try {
#if DEBUG
                    Write.Stopwatch.Restart();
#endif
                    if (!Directory.Exists(_nvsmiDir))
                    {
                        Directory.CreateDirectory(_nvsmiDir);
                    }
                    if (!File.Exists(_nvmlDllFileFullName) && File.Exists(_nvmlDllFileFullName2))
                    {
                        File.Copy(_nvmlDllFileFullName2, _nvmlDllFileFullName);
                    }
                    NvmlNativeMethods.SetDllDirectory(_nvsmiDir);
                    var nvmlReturn = NvmlNativeMethods.nvmlInit();
                    NvmlNativeMethods.SetDllDirectory(null);
                    _isNvmlInited = nvmlReturn == nvmlReturn.Success;
#if DEBUG
                    Write.DevTimeSpan($"耗时{Write.Stopwatch.ElapsedMilliseconds}毫秒 {nameof(NvmlHelper)}.{nameof(NvmlInit)}()");
#endif
                    return(_isNvmlInited);
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                }
                return(false);
            }
        }
Example #22
0
        private static Nvidia[] DetectNvidiaGPUS()
        {
            if (NvmlNativeMethods.nvmlInit() == nvmlReturn.Success && NVAPI.IsAvailable)
            {
                uint deviceCount = 0;
                if (NvmlNativeMethods.nvmlDeviceGetCount(ref deviceCount) == nvmlReturn.Success)
                {
                    Nvidia[] nvgpu = new Nvidia[deviceCount];
                    for (uint i = 0; i < deviceCount; ++i)
                    {
                        nvmlDevice device = new nvmlDevice();
                        if (NvmlNativeMethods.nvmlDeviceGetHandleByIndex((uint)i, ref device) == nvmlReturn.Success)
                        {
                            nvgpu[i] = new Nvidia(i, device);
                        }
                    }

                    return(nvgpu);
                }
            }

            return(new Nvidia[0]);
        }
Example #23
0
 public void GetVersion(out string driverVersion, out string nvmlVersion)
 {
     driverVersion = string.Empty;
     nvmlVersion   = string.Empty;
     if (!NvmlInit())
     {
         return;
     }
     try {
         var r = NvmlNativeMethods.nvmlSystemGetDriverVersion(out driverVersion);
         if (r != nvmlReturn.Success)
         {
             Write.DevError($"{nameof(NvmlNativeMethods.nvmlSystemGetDriverVersion)} {r}");
         }
         r = NvmlNativeMethods.nvmlSystemGetNVMLVersion(out nvmlVersion);
         if (r != nvmlReturn.Success)
         {
             Write.DevError($"{nameof(NvmlNativeMethods.nvmlSystemGetNVMLVersion)} {r}");
         }
     }
     catch {
     }
 }
Example #24
0
        private static bool NvmlInit()
        {
            if (_isNvmlInited)
            {
                return(_isNvmlInited);
            }
            lock (_locker) {
                if (_isNvmlInited)
                {
                    return(_isNvmlInited);
                }
                try {
#if DEBUG
                    NTStopwatch.Start();
#endif
                    if (!File.Exists(_system32nvmlDllFileFullName) && File.Exists(_nvmlDllFileFullName))
                    {
                        File.Copy(_nvmlDllFileFullName, _system32nvmlDllFileFullName);
                    }
                    var nvmlReturn = NvmlNativeMethods.NvmlInit();
                    _isNvmlInited = nvmlReturn == nvmlReturn.Success;
#if DEBUG
                    var elapsedMilliseconds = NTStopwatch.Stop();
                    if (elapsedMilliseconds.ElapsedMilliseconds > NTStopwatch.ElapsedMilliseconds)
                    {
                        NTMinerConsole.DevTimeSpan($"耗时{elapsedMilliseconds} {nameof(NvmlHelper)}.{nameof(NvmlInit)}()");
                    }
#endif
                    return(_isNvmlInited);
                }
                catch (Exception e) {
                    Logger.ErrorDebugLine(e);
                    _isNvmlInited = true;
                }
                return(false);
            }
        }
Example #25
0
        public uint GetFanSpeed(int gpuIndex)
        {
            if (!NvmlInit() || !TryGetNvmlDevice(gpuIndex, out nvmlDevice nvmlDevice))
            {
                return(0);
            }
            if (_nvmlDeviceGetFanSpeedNotSupporteds.Contains(gpuIndex))
            {
                return(0);
            }
            uint fanSpeed = 0;

            try {
                var r = NvmlNativeMethods.nvmlDeviceGetFanSpeed(nvmlDevice, ref fanSpeed);
                if (r == nvmlReturn.NotSupported)
                {
                    _nvmlDeviceGetFanSpeedNotSupporteds.Add(gpuIndex);
                }
                CheckResult(r, () => $"{nameof(NvmlNativeMethods.nvmlDeviceGetFanSpeed)} {r.ToString()}");
            }
            catch {
            }
            return(fanSpeed);
        }
Example #26
0
        private void LoadGpuState()
        {
            for (int i = 0; i < _nvmlDevices.Length; i++)
            {
                var  nvmlDevice = _nvmlDevices[i];
                uint power      = 0;
                NvmlNativeMethods.nvmlDeviceGetPowerUsage(nvmlDevice, ref power);
                uint temp = 0;
                NvmlNativeMethods.nvmlDeviceGetTemperature(nvmlDevice, nvmlTemperatureSensors.Gpu, ref temp);
                uint speed = 0;
                NvmlNativeMethods.nvmlDeviceGetFanSpeed(nvmlDevice, ref speed);

                Gpu  gpu       = (Gpu)_gpus[i];
                bool isChanged = gpu.Temperature != temp || gpu.PowerUsage != power || gpu.FanSpeed != speed;
                gpu.Temperature = temp;
                gpu.PowerUsage  = power;
                gpu.FanSpeed    = speed;

                if (isChanged)
                {
                    Global.Happened(new GpuStateChangedEvent(gpu));
                }
            }
        }
Example #27
0
                public static void QueryCudaDevices()
                {
                    Helpers.ConsolePrint(Tag, "QueryCudaDevices START");
                    QueryCudaDevices(ref _cudaDevices);

                    if (_cudaDevices != null && _cudaDevices.Count != 0)
                    {
                        Available.HasNvidia = true;
                        var stringBuilder = new StringBuilder();
                        stringBuilder.AppendLine("");
                        stringBuilder.AppendLine("CudaDevicesDetection:");

                        // Enumerate NVAPI handles and map to busid
                        var idHandles = new Dictionary <int, NvPhysicalGpuHandle>();
                        if (NVAPI.IsAvailable)
                        {
                            var handles = new NvPhysicalGpuHandle[NVAPI.MAX_PHYSICAL_GPUS];
                            if (NVAPI.NvAPI_EnumPhysicalGPUs == null)
                            {
                                Helpers.ConsolePrint("NVAPI", "NvAPI_EnumPhysicalGPUs unavailable");
                            }
                            else
                            {
                                var status = NVAPI.NvAPI_EnumPhysicalGPUs(handles, out var _);
                                if (status != NvStatus.OK)
                                {
                                    Helpers.ConsolePrint("NVAPI", "Enum physical GPUs failed with status: " + status);
                                }
                                else
                                {
                                    foreach (var handle in handles)
                                    {
                                        var idStatus = NVAPI.NvAPI_GPU_GetBusID(handle, out var id);
                                        if (idStatus != NvStatus.EXPECTED_PHYSICAL_GPU_HANDLE)
                                        {
                                            if (idStatus != NvStatus.OK)
                                            {
                                                Helpers.ConsolePrint("NVAPI",
                                                                     "Bus ID get failed with status: " + idStatus);
                                            }
                                            else
                                            {
                                                Helpers.ConsolePrint("NVAPI", "Found handle for busid " + id);
                                                idHandles[id] = handle;
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        var nvmlInit = false;
                        try
                        {
                            var ret = NvmlNativeMethods.nvmlInit();
                            if (ret != nvmlReturn.Success)
                            {
                                throw new Exception($"NVML init failed with code {ret}");
                            }
                            nvmlInit = true;
                        }
                        catch (Exception e)
                        {
                            Helpers.ConsolePrint("NVML", e.ToString());
                        }

                        foreach (var cudaDev in _cudaDevices)
                        {
                            // check sm vesrions
                            bool isUnderSM21;
                            {
                                var isUnderSM2Major = cudaDev.SM_major < 2;
                                var isUnderSM1Minor = cudaDev.SM_minor < 1;
                                isUnderSM21 = isUnderSM2Major && isUnderSM1Minor;
                            }
                            //bool isOverSM6 = cudaDev.SM_major > 6;
                            var          skip               = isUnderSM21;
                            var          skipOrAdd          = skip ? "SKIPED" : "ADDED";
                            const string isDisabledGroupStr = ""; // TODO remove
                            var          etherumCapableStr  = cudaDev.IsEtherumCapable() ? "YES" : "NO";
                            stringBuilder.AppendLine($"\t{skipOrAdd} device{isDisabledGroupStr}:");
                            stringBuilder.AppendLine($"\t\tID: {cudaDev.DeviceID}");
                            stringBuilder.AppendLine($"\t\tBusID: {cudaDev.pciBusID}");
                            stringBuilder.AppendLine($"\t\tNAME: {cudaDev.GetName()}");
                            stringBuilder.AppendLine($"\t\tVENDOR: {cudaDev.VendorName}");
                            stringBuilder.AppendLine($"\t\tUUID: {cudaDev.UUID}");
                            stringBuilder.AppendLine($"\t\tSM: {cudaDev.SMVersionString}");
                            stringBuilder.AppendLine($"\t\tMEMORY: {cudaDev.DeviceGlobalMemory}");
                            stringBuilder.AppendLine($"\t\tETHEREUM: {etherumCapableStr}");

                            if (!skip)
                            {
                                DeviceGroupType group;
                                switch (cudaDev.SM_major)
                                {
                                case 2:
                                    group = DeviceGroupType.NVIDIA_2_1;
                                    break;

                                case 3:
                                    group = DeviceGroupType.NVIDIA_3_x;
                                    break;

                                case 5:
                                    group = DeviceGroupType.NVIDIA_5_x;
                                    break;

                                case 6:
                                    group = DeviceGroupType.NVIDIA_6_x;
                                    break;

                                default:
                                    group = DeviceGroupType.NVIDIA_6_x;
                                    break;
                                }

                                var nvmlHandle = new nvmlDevice();

                                if (nvmlInit)
                                {
                                    var ret = NvmlNativeMethods.nvmlDeviceGetHandleByUUID(cudaDev.UUID, ref nvmlHandle);
                                    stringBuilder.AppendLine(
                                        "\t\tNVML HANDLE: " +
                                        $"{(ret == nvmlReturn.Success ? nvmlHandle.Pointer.ToString() : $"Failed with code ret {ret}")}");
                                }

                                idHandles.TryGetValue(cudaDev.pciBusID, out var handle);
                                Available.Devices.Add(
                                    new CudaComputeDevice(cudaDev, group, ++GpuCount, handle, nvmlHandle)
                                    );
                            }
                        }
                        Helpers.ConsolePrint(Tag, stringBuilder.ToString());
                    }
Example #28
0
        public List <CudaComputeDevice> QueryCudaDevices()
        {
            Helpers.ConsolePrint(Tag, "QueryCudaDevices START");

            var compDevs = new List <CudaComputeDevice>();

            if (!CudaQuery.TryQueryCudaDevices(out var cudaDevs))
            {
                Helpers.ConsolePrint(Tag, "QueryCudaDevices END");
                return(compDevs);
            }

            var stringBuilder = new StringBuilder();

            stringBuilder.AppendLine("");
            stringBuilder.AppendLine("CudaDevicesDetection:");

            // Enumerate NVAPI handles and map to busid
            var idHandles = InitNvapi();

            tryAddNvmlToEnvPath();
            var nvmlInit = InitNvml();

            var numDevs = 0;

            foreach (var cudaDev in cudaDevs)
            {
                // We support SM3.0+
                var skip      = cudaDev.SM_major < 3;
                var skipOrAdd = skip ? "SKIPED" : "ADDED";
                stringBuilder.AppendLine($"\t{skipOrAdd} device:");
                stringBuilder.AppendLine($"\t\tID: {cudaDev.DeviceID}");
                stringBuilder.AppendLine($"\t\tBusID: {cudaDev.pciBusID}");
                stringBuilder.AppendLine($"\t\tNAME: {cudaDev.GetName()}");
                stringBuilder.AppendLine($"\t\tVENDOR: {cudaDev.VendorName}");
                stringBuilder.AppendLine($"\t\tUUID: {cudaDev.UUID}");
                stringBuilder.AppendLine($"\t\tSM: {cudaDev.SM_major}.{cudaDev.SM_minor}");
                stringBuilder.AppendLine($"\t\tMEMORY: {cudaDev.DeviceGlobalMemory}");

                if (skip)
                {
                    continue;
                }

                DeviceGroupType group;
                switch (cudaDev.SM_major)
                {
                case 3:
                    group = DeviceGroupType.NVIDIA_3_x;
                    break;

                case 5:
                    group = DeviceGroupType.NVIDIA_5_x;
                    break;

                case 6:
                    group = DeviceGroupType.NVIDIA_6_x;
                    break;

                default:
                    group = DeviceGroupType.NVIDIA_6_x;
                    break;
                }

                var nvmlHandle = new nvmlDevice();

                if (nvmlInit)
                {
                    var ret = NvmlNativeMethods.nvmlDeviceGetHandleByUUID(cudaDev.UUID, ref nvmlHandle);
                    stringBuilder.AppendLine(
                        "\t\tNVML HANDLE: " +
                        $"{(ret == nvmlReturn.Success ? nvmlHandle.Pointer.ToString() : $"Failed with code ret {ret}")}");
                }

                idHandles.TryGetValue(cudaDev.pciBusID, out var handle);
                compDevs.Add(new CudaComputeDevice(cudaDev, group, ++numDevs, handle, nvmlHandle));
            }
Example #29
0
 public NVIDIAGpuSet(INTMinerRoot root)
 {
     _root           = root;
     this.Properties = new List <GpuSetProperty>();
     if (NvmlInit())
     {
         NvmlNativeMethods.nvmlDeviceGetCount(ref deviceCount);
         for (int i = 0; i < deviceCount; i++)
         {
             Gpu        gpu        = Gpu.Create(i, string.Empty);
             nvmlDevice nvmlDevice = new nvmlDevice();
             var        nvmlReturn = NvmlNativeMethods.nvmlDeviceGetHandleByIndex((uint)i, ref nvmlDevice);
             SetGpuStatus(gpu, nvmlReturn);
             NvmlNativeMethods.nvmlDeviceGetName(nvmlDevice, out string name);
             nvmlMemory memory = new nvmlMemory();
             NvmlNativeMethods.nvmlDeviceGetMemoryInfo(nvmlDevice, ref memory);
             // short gpu name
             if (!string.IsNullOrEmpty(name))
             {
                 name = name.Replace("GeForce GTX ", string.Empty);
                 name = name.Replace("GeForce ", string.Empty);
             }
             gpu.Name        = name;
             gpu.TotalMemory = memory.total;
             _gpus.Add(i, gpu);
         }
         if (deviceCount > 0)
         {
             NvmlNativeMethods.nvmlSystemGetDriverVersion(out _driverVersion);
             NvmlNativeMethods.nvmlSystemGetNVMLVersion(out string nvmlVersion);
             this.Properties.Add(new GpuSetProperty(GpuSetProperty.DRIVER_VERSION, "驱动版本", _driverVersion));
             try {
                 double driverVersionNum;
                 if (double.TryParse(_driverVersion, out driverVersionNum))
                 {
                     var item = root.SysDicItemSet.GetSysDicItems("CudaVersion")
                                .Select(a => new { Version = double.Parse(a.Value), a })
                                .OrderByDescending(a => a.Version)
                                .FirstOrDefault(a => driverVersionNum >= a.Version);
                     if (item != null)
                     {
                         this.Properties.Add(new GpuSetProperty("CudaVersion", "Cuda版本", item.a.Code));
                     }
                 }
             }
             catch (Exception e) {
                 Logger.ErrorDebugLine(e);
             }
             this.Properties.Add(new GpuSetProperty("NVMLVersion", "NVML版本", nvmlVersion));
             Dictionary <string, string> kvs = new Dictionary <string, string> {
                 { "CUDA_DEVICE_ORDER", "PCI_BUS_ID" }
             };
             foreach (var kv in kvs)
             {
                 var property = new GpuSetProperty(kv.Key, kv.Key, kv.Value);
                 this.Properties.Add(property);
             }
             Task.Factory.StartNew(() => {
                 foreach (var gpu in _gpus.Values)
                 {
                     NVIDIAOverClock.RefreshGpuState(gpu);
                 }
                 // 这里会耗时5秒
                 foreach (var kv in kvs)
                 {
                     Environment.SetEnvironmentVariable(kv.Key, kv.Value);
                 }
             });
         }
     }
 }
Example #30
0
        public NVIDIAGpuSet(INTMinerRoot root) : this()
        {
            _root = root;
            if (Design.IsInDesignMode)
            {
                return;
            }
            string nvsmiDir = Path.Combine(Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles), "NVIDIA Corporation", "NVSMI");

            if (Directory.Exists(nvsmiDir))
            {
                Windows.NativeMethods.SetDllDirectory(nvsmiDir);
                NvmlNativeMethods.nvmlInit();
                _isNvmlInited = true;
                NvmlNativeMethods.nvmlDeviceGetCount(ref deviceCount);
                for (int i = 0; i < deviceCount; i++)
                {
                    nvmlDevice nvmlDevice = new nvmlDevice();
                    NvmlNativeMethods.nvmlDeviceGetHandleByIndex((uint)i, ref nvmlDevice);
                    uint gClock = 0, mClock = 0;
                    NvmlNativeMethods.nvmlDeviceGetName(nvmlDevice, out string name);
                    NvmlNativeMethods.nvmlDeviceGetMaxClockInfo(nvmlDevice, nvmlClockType.Graphics, ref gClock);
                    NvmlNativeMethods.nvmlDeviceGetMaxClockInfo(nvmlDevice, nvmlClockType.Mem, ref mClock);
                    if (!string.IsNullOrEmpty(name))
                    {
                        name = name.Replace("GeForce ", string.Empty);
                    }
                    Gpu gpu = new Gpu {
                        Index       = i,
                        Name        = name,
                        Temperature = 0,
                        PowerUsage  = 0,
                        FanSpeed    = 0,
                        OverClock   = new NVIDIAOverClock()
                    };
                    _gpus.Add(i, gpu);
                }
                if (deviceCount > 0)
                {
                    NvmlNativeMethods.nvmlSystemGetDriverVersion(out string driverVersion);
                    NvmlNativeMethods.nvmlSystemGetNVMLVersion(out string nvmlVersion);
                    this.Properties.Add(new GpuSetProperty("DriverVersion", "driver version", driverVersion));
                    this.Properties.Add(new GpuSetProperty("NVMLVersion", "NVML version", nvmlVersion));
                    Dictionary <string, string> kvs = new Dictionary <string, string> {
                        { "CUDA_DEVICE_ORDER", "PCI_BUS_ID" }
                    };
                    foreach (var kv in kvs)
                    {
                        var property = new GpuSetProperty(kv.Key, kv.Key, kv.Value);
                        this.Properties.Add(property);
                    }
                    Task.Factory.StartNew(() => {
                        // 这里会耗时5秒
                        foreach (var kv in kvs)
                        {
                            Environment.SetEnvironmentVariable(kv.Key, kv.Value);
                        }
                        foreach (var gpu in _gpus.Values)
                        {
                            NVIDIAOverClock.RefreshGpuState(gpu);
                        }
                    });
                }
            }
        }