Repository navigation
Expand file tree
/
Copy pathSystemTuning.cs
More file actions
938 lines (853 loc) · 35.3 KB
/
Copy pathSystemTuning.cs
File metadata and controls
938 lines (853 loc) · 35.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using Microsoft.Win32;
namespace MHelper.Hardware
{
public enum WindowsPowerMode
{
BestPowerEfficiency = 0,
Balanced = 1,
BestPerformance = 2
}
public enum CpuBoostMode
{
Disabled = 0,
Enabled = 1,
Aggressive = 2,
EfficientEnabled = 3,
EfficientAggressive = 4
}
public sealed class RyzenSnapshotSettings
{
public bool AutoApplyOnStartup;
public bool CoEnabled;
public int CoAllCore;
public bool TdpEnabled;
public int TdpWatts;
public bool TempEnabled;
public int TempLimitC;
public bool CrashGuardTriggered;
}
public sealed class KeyboardRgbSettings
{
public KeyboardRgbMode Mode;
public int ColorRgb;
public int BrightnessPct;
public KeyboardRgbSpeed Speed;
}
public sealed class UiCategorySettings
{
public bool ShowLiveTelemetry = true;
public bool ShowPerformanceModes = true;
public bool ShowFansCooling = true;
public bool ShowGpuMux = true;
public bool ShowBatteryLimit = true;
public bool ShowKeyboardRgb = true;
public bool ShowRyzenTuning = true;
public bool ShowWindowsPower = true;
public bool ShowCustomFanCurves = true;
public bool ShowHardwareSwitches = true;
public bool ShowMsiServices = true;
public bool AnyFansPower
{
get { return ShowRyzenTuning || ShowWindowsPower || ShowCustomFanCurves; }
}
public bool AnyExtra
{
get { return ShowHardwareSwitches || ShowMsiServices; }
}
public bool AnyEcPollingNeeded
{
get { return ShowLiveTelemetry || ShowPerformanceModes || ShowFansCooling || ShowBatteryLimit || ShowCustomFanCurves; }
}
public UiCategorySettings Clone()
{
return (UiCategorySettings)MemberwiseClone();
}
}
public sealed class AppSettings : IDisposable
{
public const int StabilityGuardWindowMs = 60000;
private readonly object _gate = new object();
private readonly string _settingsPath;
private readonly Dictionary<string, int> _msiServiceOriginalStart = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
private UiCategorySettings _categories = new UiCategorySettings();
private Timer _stabilityTimer;
private bool _disposed;
private bool _ryzenAutoApplyOnStartup;
private bool _ryzenApplyPending;
private bool _crashGuardTriggered;
private bool _ryzenCoEnabled;
private int _ryzenCoAllCore = -25;
private bool _ryzenTdpEnabled;
private int _ryzenTdpWatts = 35;
private bool _ryzenTempEnabled;
private int _ryzenTempLimitC = 75;
private KeyboardRgbMode _rgbMode = KeyboardRgbMode.Static;
private int _rgbColor = 0xE11D48;
private int _rgbBrightness = 100;
private KeyboardRgbSpeed _rgbSpeed = KeyboardRgbSpeed.Medium;
private bool _uiLargeText;
public AppSettings(string customSettingsPath = null)
{
_settingsPath = !string.IsNullOrEmpty(customSettingsPath) ? customSettingsPath : DefaultSettingsPath;
}
public static string ProtectedConfigDir
{
// Stored under %ProgramFiles%\M-Helper so standard users can NEVER pre-create the folder,
// plant NTFS directory junctions, or retain Creator-Owner WRITE_DAC rights.
get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "M-Helper"); }
}
public static string DefaultSettingsPath
{
get { return Path.Combine(ProtectedConfigDir, "m-helper.ini"); }
}
public static bool IsReparsePointOrSymlink(string path)
{
if (string.IsNullOrEmpty(path)) return false;
try
{
if (!File.Exists(path) && !Directory.Exists(path)) return false;
FileAttributes attr = File.GetAttributes(path);
return (attr & FileAttributes.ReparsePoint) != 0;
}
catch
{
return true;
}
}
internal static void EnsureProtectedConfigDirectory(string dirPath)
{
if (string.IsNullOrEmpty(dirPath)) return;
if (IsReparsePointOrSymlink(dirPath))
throw new InvalidOperationException("Refusing to use reparse point / junction at '" + dirPath + "'.");
var sec = new DirectorySecurity();
sec.SetOwner(new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null));
sec.SetAccessRuleProtection(true, false);
sec.AddAccessRule(new FileSystemAccessRule(
new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null),
FileSystemRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Allow));
sec.AddAccessRule(new FileSystemAccessRule(
new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null),
FileSystemRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Allow));
sec.AddAccessRule(new FileSystemAccessRule(
new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null),
FileSystemRights.ReadAndExecute,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Allow));
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath, sec);
else
Directory.SetAccessControl(dirPath, sec);
}
public bool CrashGuardTriggered
{
get { lock (_gate) return _crashGuardTriggered; }
}
public RyzenSnapshotSettings GetSnapshot()
{
lock (_gate)
{
return new RyzenSnapshotSettings
{
AutoApplyOnStartup = _ryzenAutoApplyOnStartup,
CoEnabled = _ryzenCoEnabled,
CoAllCore = _ryzenCoAllCore,
TdpEnabled = _ryzenTdpEnabled,
TdpWatts = _ryzenTdpWatts,
TempEnabled = _ryzenTempEnabled,
TempLimitC = _ryzenTempLimitC,
CrashGuardTriggered = _crashGuardTriggered
};
}
}
public void UpdateRyzenPreferences(bool autoApply, bool coEn, int co, bool tdpEn, int tdp, bool tempEn, int temp)
{
lock (_gate)
{
_ryzenAutoApplyOnStartup = autoApply && _categories.ShowRyzenTuning;
_ryzenCoEnabled = coEn;
_ryzenCoAllCore = co;
_ryzenTdpEnabled = tdpEn;
_ryzenTdpWatts = tdp;
_ryzenTempEnabled = tempEn;
_ryzenTempLimitC = temp;
if (_ryzenAutoApplyOnStartup) _crashGuardTriggered = false;
}
}
public KeyboardRgbSettings GetRgbSettings()
{
lock (_gate)
{
return new KeyboardRgbSettings
{
Mode = _rgbMode,
ColorRgb = _rgbColor,
BrightnessPct = _rgbBrightness,
Speed = _rgbSpeed
};
}
}
public void UpdateRgbPreferences(KeyboardRgbMode mode, int colorRgb, int brightnessPct, KeyboardRgbSpeed speed)
{
lock (_gate)
{
_rgbMode = (KeyboardRgbMode)Math.Max(0, Math.Min(4, (int)mode));
_rgbColor = colorRgb & 0xFFFFFF;
_rgbBrightness = Math.Max(0, Math.Min(100, brightnessPct));
_rgbSpeed = (KeyboardRgbSpeed)Math.Max(0, Math.Min(2, (int)speed));
}
}
public bool GetLargeText()
{
lock (_gate)
{
return _uiLargeText;
}
}
public void SetLargeText(bool large)
{
lock (_gate)
{
_uiLargeText = large;
}
}
public UiCategorySettings GetCategories()
{
lock (_gate)
{
return _categories.Clone();
}
}
public void UpdateCategories(UiCategorySettings updated)
{
lock (_gate)
{
_categories = updated != null ? updated.Clone() : new UiCategorySettings();
// Never run background SMU startup/wake auto-apply if Ryzen Tuning category is disabled
if (!_categories.ShowRyzenTuning)
{
_ryzenAutoApplyOnStartup = false;
}
}
}
public void SetServiceOriginalStart(string serviceName, int startType)
{
if (string.IsNullOrEmpty(serviceName)) return;
if (startType != 2 && startType != 3) return;
lock (_gate)
{
_msiServiceOriginalStart[serviceName] = startType;
}
}
public int GetServiceOriginalStart(string serviceName, int fallback)
{
lock (_gate)
{
int val;
return _msiServiceOriginalStart.TryGetValue(serviceName, out val) ? val : fallback;
}
}
public static AppSettings Load()
{
return LoadFrom(null);
}
public static AppSettings LoadFrom(string explicitPath)
{
var s = new AppSettings(explicitPath);
try
{
string path = null;
if (!string.IsNullOrEmpty(explicitPath))
{
if (File.Exists(explicitPath) && !IsReparsePointOrSymlink(explicitPath))
path = explicitPath;
}
else
{
// Zero-trust config loading: ONLY load from Admin-protected %ProgramFiles%\M-Helper\m-helper.ini
if (File.Exists(DefaultSettingsPath) &&
!IsReparsePointOrSymlink(DefaultSettingsPath) &&
!IsReparsePointOrSymlink(ProtectedConfigDir))
{
path = DefaultSettingsPath;
}
}
if (path == null) return s;
var lineList = new List<string>();
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
if (fs.Length > 65536) return s;
byte[] rawBytes = new byte[65537];
int total = 0;
int n;
while (total < rawBytes.Length && (n = fs.Read(rawBytes, total, rawBytes.Length - total)) > 0)
{
total += n;
}
if (total > 65536) return s;
using (var ms = new MemoryStream(rawBytes, 0, total, false))
using (var sr = new StreamReader(ms, Encoding.UTF8, true))
{
string line;
while ((line = sr.ReadLine()) != null)
lineList.Add(line);
}
}
foreach (string rawLine in lineList)
{
int eq = rawLine.IndexOf('=');
if (eq <= 0) continue;
string k = rawLine.Substring(0, eq).Trim();
string v = rawLine.Substring(eq + 1).Trim();
int iv;
bool bv;
if (k.StartsWith("MsiSvcStart_", StringComparison.Ordinal))
{
string svcName = k.Substring("MsiSvcStart_".Length);
if (SystemTuning.IsKnownMsiServiceName(svcName) && int.TryParse(v, out iv) && (iv == 2 || iv == 3))
s._msiServiceOriginalStart[svcName] = iv;
continue;
}
switch (k)
{
case "RyzenAutoApplyOnStartup": if (bool.TryParse(v, out bv)) s._ryzenAutoApplyOnStartup = bv; break;
case "RyzenApplyPending": if (bool.TryParse(v, out bv)) s._ryzenApplyPending = bv; break;
case "RyzenCoEnabled": if (bool.TryParse(v, out bv)) s._ryzenCoEnabled = bv; break;
case "RyzenCoAllCore":
if (int.TryParse(v, out iv))
s._ryzenCoAllCore = Math.Max(RyzenSmuController.MinCo, Math.Min(RyzenSmuController.MaxCo, iv));
break;
case "RyzenTdpEnabled": if (bool.TryParse(v, out bv)) s._ryzenTdpEnabled = bv; break;
case "RyzenTdpWatts":
if (int.TryParse(v, out iv))
s._ryzenTdpWatts = Math.Max(RyzenSmuController.MinTdpW, Math.Min(RyzenSmuController.MaxTdpW, iv));
break;
case "RyzenTempEnabled": if (bool.TryParse(v, out bv)) s._ryzenTempEnabled = bv; break;
case "RyzenTempLimitC":
if (int.TryParse(v, out iv))
s._ryzenTempLimitC = Math.Max(RyzenSmuController.MinTempC, Math.Min(RyzenSmuController.MaxTempC, iv));
break;
case "CatLiveTelemetry": if (bool.TryParse(v, out bv)) s._categories.ShowLiveTelemetry = bv; break;
case "CatPerformanceModes": if (bool.TryParse(v, out bv)) s._categories.ShowPerformanceModes = bv; break;
case "CatFansCooling": if (bool.TryParse(v, out bv)) s._categories.ShowFansCooling = bv; break;
case "CatGpuMux": if (bool.TryParse(v, out bv)) s._categories.ShowGpuMux = bv; break;
case "CatBatteryLimit": if (bool.TryParse(v, out bv)) s._categories.ShowBatteryLimit = bv; break;
case "CatKeyboardRgb": if (bool.TryParse(v, out bv)) s._categories.ShowKeyboardRgb = bv; break;
case "RgbMode":
if (int.TryParse(v, out iv))
s._rgbMode = (KeyboardRgbMode)Math.Max(0, Math.Min(4, iv));
break;
case "RgbColor":
if (int.TryParse(v.TrimStart('#'), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out iv))
s._rgbColor = iv & 0xFFFFFF;
break;
case "RgbBrightness":
if (int.TryParse(v, out iv))
s._rgbBrightness = Math.Max(0, Math.Min(100, iv));
break;
case "RgbSpeed":
if (int.TryParse(v, out iv))
s._rgbSpeed = (KeyboardRgbSpeed)Math.Max(0, Math.Min(2, iv));
break;
case "CatRyzenTuning": if (bool.TryParse(v, out bv)) s._categories.ShowRyzenTuning = bv; break;
case "CatWindowsPower": if (bool.TryParse(v, out bv)) s._categories.ShowWindowsPower = bv; break;
case "CatCustomFanCurves": if (bool.TryParse(v, out bv)) s._categories.ShowCustomFanCurves = bv; break;
case "CatHardwareSwitches": if (bool.TryParse(v, out bv)) s._categories.ShowHardwareSwitches = bv; break;
case "CatMsiServices": if (bool.TryParse(v, out bv)) s._categories.ShowMsiServices = bv; break;
case "UiLargeText": if (bool.TryParse(v, out bv)) s._uiLargeText = bv; break;
}
}
if (!s._categories.ShowRyzenTuning)
{
s._ryzenAutoApplyOnStartup = false;
}
// H4 Crash Guard: if RyzenApplyPending is still True on startup, clear pending & auto-apply
if (s._ryzenApplyPending)
{
s._crashGuardTriggered = true;
s._ryzenApplyPending = false;
s._ryzenAutoApplyOnStartup = false;
string ignoreErr;
s.Save(out ignoreErr);
}
}
catch { }
return s;
}
public bool Save(out string error)
{
lock (_gate)
{
return SaveLocked(out error);
}
}
private bool SaveLocked(out string error)
{
string target = _settingsPath;
string dir = Path.GetDirectoryName(target);
string tmp = target + "." + Guid.NewGuid().ToString("N") + ".tmp";
try
{
if (string.Equals(dir, ProtectedConfigDir, StringComparison.OrdinalIgnoreCase))
{
EnsureProtectedConfigDirectory(dir);
}
else if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
var sb = new StringBuilder();
sb.AppendLine("RyzenAutoApplyOnStartup=" + _ryzenAutoApplyOnStartup);
sb.AppendLine("RyzenApplyPending=" + _ryzenApplyPending);
sb.AppendLine("RyzenCoEnabled=" + _ryzenCoEnabled);
sb.AppendLine("RyzenCoAllCore=" + _ryzenCoAllCore);
sb.AppendLine("RyzenTdpEnabled=" + _ryzenTdpEnabled);
sb.AppendLine("RyzenTdpWatts=" + _ryzenTdpWatts);
sb.AppendLine("RyzenTempEnabled=" + _ryzenTempEnabled);
sb.AppendLine("RyzenTempLimitC=" + _ryzenTempLimitC);
sb.AppendLine("CatLiveTelemetry=" + _categories.ShowLiveTelemetry);
sb.AppendLine("CatPerformanceModes=" + _categories.ShowPerformanceModes);
sb.AppendLine("CatFansCooling=" + _categories.ShowFansCooling);
sb.AppendLine("CatGpuMux=" + _categories.ShowGpuMux);
sb.AppendLine("CatBatteryLimit=" + _categories.ShowBatteryLimit);
sb.AppendLine("CatKeyboardRgb=" + _categories.ShowKeyboardRgb);
sb.AppendLine("RgbMode=" + (int)_rgbMode);
sb.AppendLine("RgbColor=" + _rgbColor.ToString("X6", CultureInfo.InvariantCulture));
sb.AppendLine("RgbBrightness=" + _rgbBrightness);
sb.AppendLine("RgbSpeed=" + (int)_rgbSpeed);
sb.AppendLine("CatRyzenTuning=" + _categories.ShowRyzenTuning);
sb.AppendLine("CatWindowsPower=" + _categories.ShowWindowsPower);
sb.AppendLine("CatCustomFanCurves=" + _categories.ShowCustomFanCurves);
sb.AppendLine("CatHardwareSwitches=" + _categories.ShowHardwareSwitches);
sb.AppendLine("CatMsiServices=" + _categories.ShowMsiServices);
sb.AppendLine("UiLargeText=" + _uiLargeText);
foreach (KeyValuePair<string, int> kv in _msiServiceOriginalStart)
{
sb.AppendLine("MsiSvcStart_" + kv.Key + "=" + kv.Value);
}
if (IsReparsePointOrSymlink(target))
throw new InvalidOperationException("Refusing to overwrite reparse point / symlink at '" + target + "'.");
byte[] bytes = Encoding.UTF8.GetBytes(sb.ToString());
using (var fs = new FileStream(tmp, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
fs.Write(bytes, 0, bytes.Length);
fs.Flush(true);
}
if (File.Exists(target))
{
try
{
File.Replace(tmp, target, null, true);
}
catch
{
File.Copy(tmp, target, true);
File.Delete(tmp);
}
}
else
{
File.Move(tmp, target);
}
error = null;
return true;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
finally
{
try { if (File.Exists(tmp)) File.Delete(tmp); } catch { }
}
}
public RyzenApplyResult ApplyWithCrashGuard(RyzenSmuController smu, int? co, int? tdp, int? temp)
{
if (smu == null)
return new RyzenApplyResult { Ok = false, Summary = "SMU controller unavailable." };
string saveErr;
lock (_gate)
{
_ryzenApplyPending = true;
if (!SaveLocked(out saveErr))
{
_ryzenApplyPending = false;
return new RyzenApplyResult
{
Ok = false,
Summary = "Cannot persist crash-guard marker (" + saveErr + "); SMU apply aborted."
};
}
}
RyzenApplyResult res = smu.ApplyTuning(co, tdp, temp);
lock (_gate)
{
if (!res.Ok)
{
_ryzenApplyPending = false;
if (_stabilityTimer != null)
{
_stabilityTimer.Change(Timeout.Infinite, Timeout.Infinite);
}
string ignoreErr;
SaveLocked(out ignoreErr);
return res;
}
if (!_disposed)
{
if (_stabilityTimer == null)
{
_stabilityTimer = new Timer(OnStabilityWindowElapsed, null, StabilityGuardWindowMs, Timeout.Infinite);
}
else
{
_stabilityTimer.Change(StabilityGuardWindowMs, Timeout.Infinite);
}
}
}
return res;
}
private void OnStabilityWindowElapsed(object state)
{
lock (_gate)
{
if (_disposed || !_ryzenApplyPending) return;
_ryzenApplyPending = false;
string ignoreErr;
SaveLocked(out ignoreErr);
}
}
public void Dispose()
{
lock (_gate)
{
if (_disposed) return;
_disposed = true;
if (_stabilityTimer != null)
{
_stabilityTimer.Dispose();
_stabilityTimer = null;
}
}
}
}
public static class SystemTuning
{
private static readonly Guid OverlayEfficiency = new Guid("961cc777-2547-4f9d-8174-7d86181b8a7a");
private static readonly Guid OverlayBalanced = Guid.Empty;
private static readonly Guid OverlayPerformance = new Guid("ded574b5-45a0-4f42-8737-46345c09c238");
private static readonly Guid SubProcessor = new Guid("54533251-82be-4824-96c1-47b60b740d00");
private static readonly Guid SettingPerfBoostMode = new Guid("be337238-0d82-4146-a960-4f3749d470c7");
private static readonly string[] MsiServiceNames =
{
"MSI_Center_Service",
"MSI Foundation Service",
"Micro Star SCM",
"MSI Sendevsvc"
};
private static readonly string[] MsiUserProcessNames =
{
"MSI.CentralServer",
"MSI.TerminalServer",
"MSI Center",
"DCv2",
"NVChecker",
"OmApSvcBroker"
};
[DllImport("powrprof.dll")]
private static extern uint PowerGetEffectiveOverlayScheme(out Guid effectiveOverlayGuid);
[DllImport("powrprof.dll")]
private static extern uint PowerSetActiveOverlayScheme(Guid overlaySchemeGuid);
[DllImport("powrprof.dll")]
private static extern uint PowerGetActiveScheme(IntPtr userRootPowerKey, out IntPtr activePolicyGuid);
[DllImport("powrprof.dll")]
private static extern uint PowerReadACValueIndex(IntPtr rootPowerKey, ref Guid schemeGuid, ref Guid subGroupGuid, ref Guid powerSettingGuid, out uint acValueIndex);
[DllImport("powrprof.dll")]
private static extern uint PowerWriteACValueIndex(IntPtr rootPowerKey, ref Guid schemeGuid, ref Guid subGroupGuid, ref Guid powerSettingGuid, uint acValueIndex);
[DllImport("powrprof.dll")]
private static extern uint PowerWriteDCValueIndex(IntPtr rootPowerKey, ref Guid schemeGuid, ref Guid subGroupGuid, ref Guid powerSettingGuid, uint dcValueIndex);
[DllImport("powrprof.dll")]
private static extern uint PowerSetActiveScheme(IntPtr userRootPowerKey, ref Guid schemeGuid);
[DllImport("kernel32.dll")]
private static extern IntPtr LocalFree(IntPtr hMem);
public static WindowsPowerMode GetWindowsPowerMode()
{
try
{
Guid g;
if (PowerGetEffectiveOverlayScheme(out g) == 0)
{
if (g == OverlayEfficiency) return WindowsPowerMode.BestPowerEfficiency;
if (g == OverlayPerformance) return WindowsPowerMode.BestPerformance;
}
}
catch { }
return WindowsPowerMode.Balanced;
}
public static bool SetWindowsPowerMode(WindowsPowerMode mode)
{
try
{
Guid g = mode == WindowsPowerMode.BestPowerEfficiency ? OverlayEfficiency
: mode == WindowsPowerMode.BestPerformance ? OverlayPerformance
: OverlayBalanced;
return PowerSetActiveOverlayScheme(g) == 0;
}
catch
{
return false;
}
}
public static CpuBoostMode GetCpuBoostMode()
{
IntPtr pScheme = IntPtr.Zero;
try
{
if (PowerGetActiveScheme(IntPtr.Zero, out pScheme) != 0 || pScheme == IntPtr.Zero)
return CpuBoostMode.Aggressive;
Guid scheme = (Guid)Marshal.PtrToStructure(pScheme, typeof(Guid));
Guid sub = SubProcessor;
Guid set = SettingPerfBoostMode;
uint val;
if (PowerReadACValueIndex(IntPtr.Zero, ref scheme, ref sub, ref set, out val) == 0)
{
if (val <= 4) return (CpuBoostMode)val;
}
}
catch { }
finally
{
if (pScheme != IntPtr.Zero) LocalFree(pScheme);
}
return CpuBoostMode.Aggressive;
}
public static bool SetCpuBoostMode(CpuBoostMode mode)
{
IntPtr pScheme = IntPtr.Zero;
try
{
if (PowerGetActiveScheme(IntPtr.Zero, out pScheme) != 0 || pScheme == IntPtr.Zero)
return false;
Guid scheme = (Guid)Marshal.PtrToStructure(pScheme, typeof(Guid));
Guid sub = SubProcessor;
Guid set = SettingPerfBoostMode;
uint v = (uint)mode;
uint rcAc = PowerWriteACValueIndex(IntPtr.Zero, ref scheme, ref sub, ref set, v);
uint rcDc = PowerWriteDCValueIndex(IntPtr.Zero, ref scheme, ref sub, ref set, v);
uint rcSet = PowerSetActiveScheme(IntPtr.Zero, ref scheme);
return rcAc == 0 && rcDc == 0 && rcSet == 0;
}
catch
{
return false;
}
finally
{
if (pScheme != IntPtr.Zero) LocalFree(pScheme);
}
}
internal static bool IsKnownMsiServiceName(string candidate)
{
if (string.IsNullOrEmpty(candidate)) return false;
foreach (string s in MsiServiceNames)
{
if (string.Equals(s, candidate, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
public static int CountRunningMsiServices(out int installedCount)
{
installedCount = 0;
int running = 0;
foreach (string name in MsiServiceNames)
{
try
{
using (var sc = new ServiceController(name))
{
var st = sc.Status;
installedCount++;
if (st == ServiceControllerStatus.Running || st == ServiceControllerStatus.StartPending)
running++;
}
}
catch { }
}
return running;
}
private static int ReadRegistryServiceStartType(string serviceName)
{
try
{
using (var key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\" + serviceName))
{
if (key != null && key.GetValue("Start") != null)
return Convert.ToInt32(key.GetValue("Start"));
}
}
catch { }
return -1;
}
internal static bool IsVerifiedMsiProcessPath(string path)
{
if (string.IsNullOrEmpty(path)) return false;
string[] trustedRoots =
{
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
Environment.GetEnvironmentVariable("ProgramW6432")
};
foreach (string root in trustedRoots)
{
if (string.IsNullOrEmpty(root)) continue;
string cleanRoot = root.TrimEnd('\\');
if (path.StartsWith(cleanRoot + @"\MSI\", StringComparison.OrdinalIgnoreCase))
return true;
if (path.StartsWith(cleanRoot + @"\WindowsApps\MICRO-STARINTERNATION.MSICenter", StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
private static bool IsVerifiedMsiProcess(Process p)
{
try
{
string path = p.MainModule != null ? p.MainModule.FileName : null;
return IsVerifiedMsiProcessPath(path);
}
catch
{
return false;
}
}
public static int StopAndDisableMsiServices(AppSettings settings)
{
int affected = 0;
foreach (string name in MsiServiceNames)
{
try
{
using (var sc = new ServiceController(name))
{
ServiceControllerStatus st = sc.Status;
int curStart = ReadRegistryServiceStartType(name);
if (settings != null && (curStart == 2 || curStart == 3))
{
settings.SetServiceOriginalStart(name, curStart);
}
if (st != ServiceControllerStatus.Stopped && st != ServiceControllerStatus.StopPending)
{
try
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(5));
}
catch { }
}
if (RunSc("config \"" + name + "\" start= disabled") == 0)
{
affected++;
}
}
}
catch { }
}
if (settings != null)
{
string ignoreErr;
settings.Save(out ignoreErr);
}
// Terminate MSI Center companion/GPU-polling processes (verified by MSI path)
foreach (string procName in MsiUserProcessNames)
{
try
{
foreach (Process p in Process.GetProcessesByName(procName))
{
using (p)
{
try
{
if (IsVerifiedMsiProcess(p)) p.Kill();
}
catch { }
}
}
}
catch { }
}
return affected;
}
public static int EnableAndStartMsiServices(AppSettings settings)
{
int affected = 0;
foreach (string name in MsiServiceNames)
{
try
{
using (var sc = new ServiceController(name))
{
ServiceControllerStatus st = sc.Status;
int origStart = settings != null ? settings.GetServiceOriginalStart(name, 2) : 2;
string startMode = origStart == 3 ? "demand" : "auto";
if (RunSc("config \"" + name + "\" start= " + startMode) == 0)
{
affected++;
}
if (origStart == 2 && st == ServiceControllerStatus.Stopped)
{
try { sc.Start(); } catch { }
}
}
}
catch { }
}
return affected;
}
private static int RunSc(string args)
{
try
{
using (var p = Process.Start(new ProcessStartInfo(
Path.Combine(Environment.SystemDirectory, "sc.exe"), args)
{
CreateNoWindow = true,
UseShellExecute = false,
WorkingDirectory = Environment.SystemDirectory
}))
{
if (p == null) return -1;
if (!p.WaitForExit(5000))
{
try { p.Kill(); } catch { }
return -1;
}
return p.ExitCode;
}
}
catch
{
return -1;
}
}
}
}