-
Notifications
You must be signed in to change notification settings - Fork 5
/
SettingsForm.cs
1776 lines (1523 loc) · 64.9 KB
/
SettingsForm.cs
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
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Microsoft.VisualBasic.Devices;
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using ZenStates.Core;
using ZenStatesDebugTool.Properties;
using Application = System.Windows.Forms.Application;
using static ZenStates.Core.Cpu;
using Microsoft.Win32.TaskScheduler;
using System.Security.Principal;
namespace ZenStatesDebugTool
{
public partial class SettingsForm : Form
{
//private static readonly int Threads = Convert.ToInt32(Environment.GetEnvironmentVariable("NUMBER_OF_PROCESSORS"));
private BackgroundWorker backgroundWorker1;
private readonly NUMAUtil _numaUtil;
private readonly Cpu cpu;
List<SmuAddressSet> matches;
private readonly Mailbox testMailbox = new Mailbox();
private readonly string wmiAMDACPI = "AMD_ACPI";
private readonly string wmiScope = "root\\wmi";
private ManagementObject classInstance;
private string instanceName;
private ManagementBaseObject pack;
private const string filename = "co_profile.txt";
private const string profilesFolderName = "profiles";
private const string defaultsPath = profilesFolderName + @"\" + filename;
private readonly string[] args;
private readonly bool isApplyProfile;
public SettingsForm()
{
InitializeComponent();
_numaUtil = new NUMAUtil();
textBoxResult.Text = $@"Detected NUMA nodes. ({_numaUtil.HighestNumaNode + 1})" + textBoxResult.Text;
try
{
args = Environment.GetCommandLineArgs();
foreach (string arg in args)
{
isApplyProfile |= (arg.ToLower() == "--applyprofile");
}
cpu = new Cpu();
InitForm();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Resources.Error);
Dispose();
ExitApplication();
}
}
private void ExitApplication()
{
cpu?.Dispose();
if (Application.MessageLoop)
Application.Exit();
else
Environment.Exit(1);
}
private void InitTestMailbox(uint msgAddr, uint rspAddr, uint argAddr)
{
testMailbox.SMU_ADDR_MSG = msgAddr;
testMailbox.SMU_ADDR_RSP = rspAddr;
testMailbox.SMU_ADDR_ARG = argAddr;
ResetSmuAddresses();
}
private void InitTestMailbox(Mailbox mailbox)
{
testMailbox.SMU_ADDR_MSG = mailbox.SMU_ADDR_MSG;
testMailbox.SMU_ADDR_RSP = mailbox.SMU_ADDR_RSP;
testMailbox.SMU_ADDR_ARG = mailbox.SMU_ADDR_ARG;
ResetSmuAddresses();
}
private void ResetSmuAddresses()
{
textBoxCMDAddress.Text = $"0x{Convert.ToString(testMailbox.SMU_ADDR_MSG, 16).ToUpper()}";
textBoxRSPAddress.Text = $"0x{Convert.ToString(testMailbox.SMU_ADDR_RSP, 16).ToUpper()}";
textBoxARGAddress.Text = $"0x{Convert.ToString(testMailbox.SMU_ADDR_ARG, 16).ToUpper()}";
}
private void DisplaySystemInfo()
{
try
{
cpuInfoLabel.Text = cpu.systemInfo.CpuName;
modelInfoLabel.Text = $"{cpu.systemInfo.Model:X2}";
packageTypeInfoLabel.Text = cpu.info.packageType.ToString();
mbVendorInfoLabel.Text = cpu.systemInfo.MbVendor;
mbModelInfoLabel.Text = cpu.systemInfo.MbName;
biosInfoLabel.Text = cpu.systemInfo.BiosVersion;
smuInfoLabel.Text = cpu.systemInfo.GetSmuVersionString();
firmwareInfoLabel.Text = $"{cpu.systemInfo.PatchLevel:X8}";
cpuIdLabel.Text = $"{cpu.systemInfo.GetCpuIdString()} ({cpu.info.codeName})";
configInfoLabel.Text = $"{cpu.info.topology.ccds} CCD / {cpu.info.topology.ccxs} CCX / {cpu.systemInfo.PhysicalCoreCount} physical cores";
}
catch { }
}
private void InitForm()
{
/*if (cpu.Status == Utils.LibStatus.PARTIALLY_OK)
{
if (cpu.LastError != null)
MessageBox.Show(cpu.LastError.Message, Resources.Error);
}*/
if (cpu.smu.Version == 0)
{
MessageBox.Show("Error getting SMU version!\n" +
"Default SMU addresses are not responding to commands.",
"Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (!Directory.Exists(profilesFolderName))
{
MessageBox.Show("Profiles directory does not exist, created one for you.");
Directory.CreateDirectory(profilesFolderName);
}
InitTestMailbox(cpu.smu.Rsmu);
DisplaySystemInfo();
pstateIdBox.SelectedIndex = 0;
pstateDid.KeyDown += PstateFidDid_KeyDown;
pstateDid.KeyPress += PstateFidDid_KeyPress;
pstateDid.KeyUp += PstateFidDid_KeyUp;
pstateFid.KeyDown += PstateFidDid_KeyDown;
pstateFid.KeyPress += PstateFidDid_KeyPress;
pstateFid.KeyUp += PstateFidDid_KeyUp;
PopulateFrequencyList(comboBoxACF.Items);
PopulateFrequencyList(comboBoxSCF.Items);
PopulateCCDList(comboBoxCore.Items);
PopulateMailboxesList(comboBoxMailboxSelect.Items);
comboBoxCore.SelectedIndex = 0;
double multi = GetCurrentMulti();
if (multi >= 5.50)
{
int index = (int)((multi - 5.50) / 0.25);
if (index > -1 && index < comboBoxACF.Items.Count && index < comboBoxSCF.Items.Count)
{
comboBoxACF.SelectedIndex = index;
comboBoxSCF.SelectedIndex = index;
}
}
InitPBO();
PopulateWmiFunctions();
double? currentBclk = cpu.GetBclk();
labelBCLK.Text = currentBclk + " MHz";
numericUpDownBclk.Text = $"{currentBclk}";
var prochotEnabled = cpu.IsProchotEnabled();
checkBoxPROCHOT.Checked = prochotEnabled;
//checkBoxPROCHOT.Enabled = prochotEnabled;
//buttonApplyPROCHOT.Enabled = prochotEnabled;
comboBoxMailboxSelect.SelectedIndex = 0;
ToolTip toolTip = new ToolTip();
toolTip.SetToolTip(checkBoxPROCHOT, "Disables temperature throttling. Can be useful on extreme cooling.");
if (isApplyProfile)
{
tabControl1.SelectedTab = tabPagePbo;
BtnLoadCOProfile_Click(null, null);
ButtonApplyCO_Click(null, null);
}
SetStatusText($"{cpu.info.codeName}. Ready.");
}
// TODO: Detect OC Mode and return PState freq if on auto
private double GetCurrentMulti()
{
double multi = cpu.GetCoreMulti();
if (multi == 0)
SetStatusText($@"Error getting current frequency!");
return multi;
}
private void PopulateFrequencyList(ComboBox.ObjectCollection l)
{
for (double multi = 5.5; multi <= 70; multi += 0.25)
{
l.Add((object)new FrequencyListItem(multi, string.Format("x{0:0.00}", multi)));
}
}
private void PopulateCCDList(ComboBox.ObjectCollection l)
{
int ccxInCcd = cpu.info.family == Cpu.Family.FAMILY_19H ? 1 : 2;
int coresInCcx = 8 / ccxInCcd;
for (int core = 0; core < cpu.info.topology.cores; ++core)
l.Add(new CoreListItem(core / 8, core / coresInCcx, core));
}
private void PopulateMailboxesList(ComboBox.ObjectCollection l)
{
l.Clear();
l.Add(new MailboxListItem("RSMU", cpu.smu.Rsmu));
l.Add(new MailboxListItem("MP1", cpu.smu.Mp1Smu));
l.Add(new MailboxListItem("HSMP", cpu.smu.Hsmp));
}
private void AddMailboxToList(string label, SmuAddressSet addressSet)
{
comboBoxMailboxSelect.Items.Add(new MailboxListItem(label, addressSet));
}
private void InitPBO()
{
if (cpu.smu.Rsmu.SMU_MSG_SetDldoPsmMargin != 0)
{
uint cores = cpu.info.topology.physicalCores;
for (var i = 0; i < cores; i++)
{
int mapIndex = i < 8 ? 0 : 1;
if ((~cpu.info.topology.coreDisableMap[mapIndex] >> i % 8 & 1) == 1)
{
try
{
NumericUpDown control = (NumericUpDown)Controls.Find($"numericUpDownCO_{i}", true)[0];
if (control != null)
{
control.Enabled = true;
uint coreMask = cpu.MakeCoreMask((uint)i);
uint? margin = cpu.GetPsmMarginSingleCore((uint)(((mapIndex << 8) | i % 8 & 0xF) << 20));
if (margin != null)
control.Value = Convert.ToDecimal((int)margin);
}
} catch (Exception e) {
Console.WriteLine(e);
}
}
}
}
/*using (RegistryKey key = Registry.CurrentUser.OpenSubKey
("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
if (key != null)
{
checkBoxApplyCOStartup.Checked = key.GetValue("RyzenSDT") != null;
}
}*/
checkBoxApplyCOStartup.Checked = TaskExists("RyzenSDT");
}
private void ApplyFrequencyAllCoreSetting(int frequency)
{
if (cpu.SetFrequencyAllCore(Convert.ToUInt32(frequency)))
SetStatusText(string.Format("Set frequency to {0} MHz!", frequency));
else
HandleError("Error setting frequency!");
}
private void ApplyFrequencySingleCoreSetting(CoreListItem i, int frequency)
{
uint coreMask = Convert.ToUInt32(((i.CCD << 4 | i.CCX % 2 & 15) << 4 | i.CORE % 4 & 15) << 20);
if (cpu.SetFrequencySingleCore(coreMask, Convert.ToUInt32(frequency)))
SetStatusText(string.Format("Set core {0} frequency to {1} MHz!", i, frequency));
else
HandleError("Error setting frequency!");
}
private void EnableOCMode(bool prochotEnabled = true)
{
if (cpu.smu.SendSmuCommand(cpu.smu.Rsmu, cpu.smu.Rsmu.SMU_MSG_EnableOcMode, prochotEnabled ? 0U : 0x1000000))
SetStatusText(prochotEnabled ? "PROCHOT enabled." : "PROCHOT disabled.");
else
HandleError("Error setting OC Mode!");
}
private void DisableOCMode()
{
if (cpu.DisableOcMode() == SMU.Status.OK)
SetStatusText(string.Format("Set OK!"));
else
HandleError("Error disabling OC Mode!");
}
private void SetStatusText(string status)
{
labelStatus.Text = status;
Console.WriteLine($"CMD Status: {status}");
}
private void SetButtonsState(bool enabled = true)
{
buttonApply.Enabled = enabled;
buttonDefaults.Enabled = enabled;
buttonProbe.Enabled = enabled;
buttonPciRead.Enabled = enabled;
buttonPciScan.Enabled = enabled;
buttonExport.Enabled = enabled;
buttonMsrRead.Enabled = enabled;
buttonMsrScan.Enabled = enabled;
buttonMsrWrite.Enabled = enabled;
buttonPMTable.Enabled = enabled;
buttonSmuLog.Enabled = enabled;
textBoxCMDAddress.Enabled = enabled;
textBoxRSPAddress.Enabled = enabled;
textBoxARGAddress.Enabled = enabled;
textBoxCMD.Enabled = enabled;
textBoxARG0.Enabled = enabled;
textBoxPciAddress.Enabled = enabled;
textBoxPciValue.Enabled = enabled;
textBoxPciStartReg.Enabled = enabled;
textBoxPciEndReg.Enabled = enabled;
textBoxMsrAddress.Enabled = enabled;
textBoxMsrEdx.Enabled = enabled;
textBoxMsrEax.Enabled = enabled;
textBoxMsrStart.Enabled = enabled;
textBoxMsrEnd.Enabled = enabled;
comboBoxMailboxSelect.Enabled = enabled;
// textBoxResult.Enabled = enabled;
}
private void TryConvertToUint(string text, out uint address)
{
try
{
address = Convert.ToUInt32(text.Trim().ToLower(), 16);
}
catch
{
throw new ApplicationException("Invalid hexadecimal value.");
}
}
private void HandleError(string message, string title = "Error")
{
SetStatusText(Resources.Error);
MessageBox.Show(message, title);
}
private void ShowResultMessageBox(uint data)
{
uint[] d = { data };
ShowResultMessageBox(d);
}
private void ShowResultMessageBox(uint[] data)
{
string responseString = "";
string[] hexArray = new string[data.Length];
string[] decArray = new string[data.Length];
string[] binArray = new string[data.Length];
for (var i = 0; i < data.Length; i++)
{
hexArray[i] = $"0x{Convert.ToString(data[i], 16).ToUpper()}";
decArray[i] = $"{Convert.ToString(data[i], 10).ToUpper()}";
binArray[i] = $"{Convert.ToString(data[i], 2).ToUpper()}";
}
responseString += "HEX: " + string.Join(", ", hexArray);
responseString += Environment.NewLine;
responseString += "DEC: " + string.Join(", ", decArray);
responseString += Environment.NewLine;
responseString += "BIN: " + string.Join(", ", binArray);
responseString += Environment.NewLine;
responseString += Environment.NewLine;
Console.WriteLine($"Response: {responseString}");
textBoxResult.Text = responseString + textBoxResult.Text;
}
private void ShowResult(uint data)
{
string responseString =
$"REG: {textBoxPciAddress.Text.Trim()}" +
Environment.NewLine +
$"HEX: 0x{Convert.ToString(data, 16).ToUpper()}" +
Environment.NewLine +
$"INT: {Convert.ToString(data, 10).ToUpper()}" +
Environment.NewLine +
$"BIN: {Convert.ToString(data, 2).ToUpper().PadLeft(32, '0')}" +
Environment.NewLine +
Environment.NewLine;
Console.WriteLine($"Response: {responseString}");
textBoxResult.Text = responseString + textBoxResult.Text;
}
private void ShowResultForm(string title="Result", string result="No result")
{
Invoke(new MethodInvoker(delegate
{
var resultForm = new ResultForm();
resultForm.textBoxFormResult.Text = result;
resultForm.Text = title;
resultForm.Show();
}));
}
// TODO: Show all args
private void ApplySettings()
{
try
{
uint[] args = ZenStates.Core.Utils.MakeCmdArgs();
string[] userArgs = textBoxARG0.Text.Trim().Split(',');
TryConvertToUint(textBoxCMDAddress.Text, out uint addrMsg);
TryConvertToUint(textBoxRSPAddress.Text, out uint addrRsp);
TryConvertToUint(textBoxARGAddress.Text, out uint addrArg);
TryConvertToUint(textBoxCMD.Text, out uint command);
testMailbox.SMU_ADDR_MSG = addrMsg;
testMailbox.SMU_ADDR_RSP = addrRsp;
testMailbox.SMU_ADDR_ARG = addrArg;
for (var i = 0; i < userArgs.Length; i++)
{
if (i == args.Length)
break;
TryConvertToUint(userArgs[i], out uint temp);
args[i] = temp;
}
Console.WriteLine("MSG Address: 0x" + Convert.ToString(testMailbox.SMU_ADDR_MSG, 16).ToUpper());
Console.WriteLine("RSP Address: 0x" + Convert.ToString(testMailbox.SMU_ADDR_RSP, 16).ToUpper());
Console.WriteLine("ARG0 Address: 0x" + Convert.ToString(testMailbox.SMU_ADDR_ARG, 16).ToUpper());
Console.WriteLine("ARG0 : 0x" + Convert.ToString(args[0], 16).ToUpper());
SMU.Status status = cpu.smu.SendSmuCommand(testMailbox, command, ref args);
if (status == SMU.Status.OK)
{
ShowResultMessageBox(args);
}
SetStatusText(GetSMUStatus.GetByType(status));
}
catch (ApplicationException ex)
{
HandleError(ex.Message);
}
}
private void ButtonDefaults_Click(object sender, EventArgs e)
{
InitTestMailbox(cpu.smu.Rsmu);
comboBoxMailboxSelect.SelectedIndex = 0;
textBoxCMD.Value = 1;
textBoxARG0.Text = "0";
}
private void ButtonApply_Click(object sender, EventArgs e)
{
try
{
ApplySettings();
}
catch (ApplicationException ex)
{
HandleError(ex.Message, "Error reading response");
}
}
private void HandlePciReadBtnClick()
{
try
{
SetStatusText("Reading, please wait...");
SetButtonsState(false);
TryConvertToUint(textBoxPciAddress.Text, out uint address);
uint data = cpu.ReadDword(address);
textBoxPciValue.Text = $"0x{data:X8}";
SetButtonsState();
SetStatusText(GetSMUStatus.GetByType(SMU.Status.OK));
ShowResult(data);
}
catch (ApplicationException ex)
{
SetButtonsState();
HandleError(ex.Message);
}
}
private void HandlePciWriteBtnClick()
{
try
{
SetStatusText("Writing, please wait...");
SetButtonsState(false);
TryConvertToUint(textBoxPciAddress.Text, out uint address);
TryConvertToUint(textBoxPciValue.Text, out uint data);
bool res = false;
if (cpu.WriteDwordEx(cpu.smu.SMU_OFFSET_ADDR, address))
res = cpu.WriteDwordEx(cpu.smu.SMU_OFFSET_DATA, data);
if (res)
SetStatusText("Write OK.");
else
SetStatusText(Resources.Error);
SetButtonsState();
}
catch (ApplicationException ex)
{
SetButtonsState();
HandleError(ex.Message);
}
}
private void ButtonPciRead_Click(object sender, EventArgs e)
{
HandlePciReadBtnClick();
}
private void TextBoxPciAddress_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
HandlePciReadBtnClick();
}
private void ButtonPciWrite_Click(object sender, EventArgs e)
{
HandlePciWriteBtnClick();
}
private void TextBoxPciValue_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
HandlePciWriteBtnClick();
}
private SMU.Status TrySettings(uint msgAddr, uint rspAddr, uint argAddr, uint cmd, uint value)
{
uint[] args = new uint[6];
args[0] = value;
testMailbox.SMU_ADDR_MSG = msgAddr;
testMailbox.SMU_ADDR_RSP = rspAddr;
testMailbox.SMU_ADDR_ARG = argAddr;
return cpu.smu.SendSmuCommand(testMailbox, cmd, ref args);
}
private void ScanSmuRange(uint start, uint end, uint step, uint offset)
{
matches = new List<SmuAddressSet>();
List<KeyValuePair<uint, uint>> temp = new List<KeyValuePair<uint, uint>>();
while (start <= end)
{
uint smuRspAddress = start + offset;
if (cpu.ReadDword(start) != 0xFFFFFFFF)
{
// Send unknown command 0xFF to each pair of this start and possible response addresses
if (cpu.WriteDwordEx(start, 0xFF))
{
Thread.Sleep(10);
while (smuRspAddress <= end)
{
// Expect UNKNOWN_CMD status to be returned if the mailbox works
if (cpu.ReadDword(smuRspAddress) == 0xFE)
{
// Send Get_SMU_Version command
if (cpu.WriteDwordEx(start, 0x2))
{
Thread.Sleep(10);
if (cpu.ReadDword(smuRspAddress) == 0x1)
temp.Add(new KeyValuePair<uint, uint>(start, smuRspAddress));
}
}
smuRspAddress += step;
}
}
}
start += step;
}
if (temp.Count > 0)
{
for (var i = 0; i < temp.Count; i++)
{
Console.WriteLine($"{temp[i].Key:X8}: {temp[i].Value:X8}");
}
Console.WriteLine();
}
List<uint> possibleArgAddresses = new List<uint>();
foreach (var pair in temp)
{
Console.WriteLine($"Testing {pair.Key:X8}: {pair.Value:X8}");
if (TrySettings(pair.Key, pair.Value, 0xFFFFFFFF, 0x2, 0xFF) == SMU.Status.OK)
{
var smuArgAddress = pair.Value + 4;
while (smuArgAddress <= end)
{
if (cpu.ReadDword(smuArgAddress) == cpu.smu.Version)
{
possibleArgAddresses.Add(smuArgAddress);
}
smuArgAddress += step;
}
}
// Verify the arg address returns correct value (should be test argument + 1)
foreach (var address in possibleArgAddresses)
{
uint testArg = 0xFAFAFAFA;
var retries = 3;
while (retries > 0)
{
testArg++;
retries--;
// Send test command
if (TrySettings(pair.Key, pair.Value, address, 0x1, testArg) == SMU.Status.OK)
if (cpu.ReadDword(address) != testArg + 1)
retries = -1;
}
if (retries == 0)
{
matches.Add(new SmuAddressSet(pair.Key, pair.Value, address));
string responseString =
$"CMD: 0x{pair.Key:X8}" +
Environment.NewLine +
$"RSP: 0x{pair.Value:X8}" +
Environment.NewLine +
$"ARG: 0x{address:X8}" +
Environment.NewLine +
Environment.NewLine;
Invoke(new MethodInvoker(delegate
{
textBoxResult.Text += responseString;
}));
break;
}
}
}
}
/*private void ScanSmuRange_old(uint start, uint end, int step, byte offset)
{
matches = new List<SmuAddressSet>();
while (start <= end)
{
uint smuRspAddress = start + offset;
uint smuArgAddress = 0xFFFFFFFF;
if (cpu.ReadDword(start) != 0xFFFFFFFF)
{
// Check if CMD-RSP pair returns correct status, while using a placeholder ARG address
if (TrySettings(start, smuRspAddress, smuArgAddress, testMailbox.SMU_MSG_TestMessage, 0x0) == SMU.Status.OK)
{
// Send smu version command, so the corresponding ARG0 address changes its value
TrySettings(start, smuRspAddress, smuArgAddress, testMailbox.SMU_MSG_GetSmuVersion, 0x0);
bool match = false;
smuArgAddress = smuRspAddress + 4;
// Scan for ARG address
while ((smuArgAddress <= end) && !match)
{
// Check if smu version major is in range
var currentRegValue = (cpu.ReadDword(smuArgAddress) & 0x00FF0000) >> 16;
Console.WriteLine($"REG: 0x{smuArgAddress:X8} Value: 0x{currentRegValue:X8}");
if (currentRegValue > 1 && currentRegValue <= 99)
{
// Send test message with an argument, using the potential ARG0 address
var argValue = (uint)matches.Count * 2 + 99;
TrySettings(start, smuRspAddress, smuArgAddress, testMailbox.SMU_MSG_TestMessage, argValue);
currentRegValue = cpu.ReadDword(smuArgAddress);
Console.WriteLine($"REG: 0x{smuArgAddress:X8} Value: 0x{currentRegValue:X8}");
// Check the address for expected value (argument + 1)
if (currentRegValue == argValue + 1)
{
match = true;
matches.Add(new SmuAddressSet(start, smuRspAddress, smuArgAddress));
string responseString =
$"CMD: 0x{start:X8}" +
Environment.NewLine +
$"RSP: 0x{smuRspAddress:X8}" +
Environment.NewLine +
$"ARG: 0x{smuArgAddress:X8}" +
Environment.NewLine +
Environment.NewLine;
smuArgAddress += 20;
Invoke(new MethodInvoker(delegate
{
textBoxResult.Text += responseString;
}));
}
}
smuArgAddress += 0x4;
}
}
}
start += (uint)step;
}
}*/
private void RunBackgroundTask(DoWorkEventHandler task, RunWorkerCompletedEventHandler completedHandler)
{
try
{
SetButtonsState(false);
textBoxResult.Clear();
backgroundWorker1 = new BackgroundWorker();
backgroundWorker1.DoWork += task;
backgroundWorker1.RunWorkerCompleted += completedHandler;
backgroundWorker1.RunWorkerAsync();
}
catch (ApplicationException ex)
{
SetStatusText(Resources.Error);
SetButtonsState();
HandleError(ex.Message);
}
}
private void BackgroundWorkerTrySettings_DoWork(object sender, DoWorkEventArgs e)
{
try
{
Invoke(new MethodInvoker(delegate
{
SetStatusText("Scanning SMU addresses, please wait...");
}));
switch (cpu.info.codeName)
{
case Cpu.CodeName.BristolRidge:
//ScanSmuRange(0x13000000, 0x13000F00, 4, 0x10);
break;
case Cpu.CodeName.RavenRidge:
case Cpu.CodeName.Picasso:
case Cpu.CodeName.FireFlight:
case Cpu.CodeName.Dali:
case Cpu.CodeName.Renoir:
ScanSmuRange(0x03B10500, 0x03B10998, 8, 0x3C);
ScanSmuRange(0x03B10A00, 0x03B10AFF, 4, 0x60);
break;
case Cpu.CodeName.PinnacleRidge:
case Cpu.CodeName.SummitRidge:
case Cpu.CodeName.Matisse:
case Cpu.CodeName.Whitehaven:
case Cpu.CodeName.Naples:
case Cpu.CodeName.Colfax:
case Cpu.CodeName.Vermeer:
//case Cpu.CodeName.Raphael:
ScanSmuRange(0x03B10500, 0x03B10998, 8, 0x3C);
ScanSmuRange(0x03B10500, 0x03B10AFF, 4, 0x4C);
break;
case Cpu.CodeName.Raphael:
ScanSmuRange(0x03B10500, 0x03B10998, 8, 0x3C);
// ScanSmuRange(0x03B10500, 0x03B10AFF, 4, 0x4C);
break;
case Cpu.CodeName.Rome:
ScanSmuRange(0x03B10500, 0x03B10AFF, 4, 0x4C);
break;
default:
break;
}
}
catch (ApplicationException)
{
Invoke(new MethodInvoker(delegate
{
SetButtonsState();
SetStatusText(Resources.Error);
}));
}
}
private void ButtonScan_Click(object sender, EventArgs e)
{
var confirmResult = MessageBox.Show(
"The scan process might crash your system or have other unexpected results. " +
Environment.NewLine +
"It could take up to 1 minute, depending on the system and current workload." +
Environment.NewLine +
"Do you want to continue?",
"Confirm Scan",
MessageBoxButtons.OKCancel
);
if (confirmResult == DialogResult.OK)
RunBackgroundTask(BackgroundWorkerTrySettings_DoWork, SmuScan_WorkerCompleted);
}
private void TabControl1_Selected(object sender, TabControlEventArgs e)
{
if (e.TabPage == tabPageInfo)
splitContainer1.Panel2Collapsed = true;
else if (splitContainer1.Panel2Collapsed)
splitContainer1.Panel2Collapsed = false;
}
public string GenerateReportJson()
{
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw)
{
Formatting = Formatting.Indented
};
// {
writer.WriteStartObject();
writer.WritePropertyName("AppVersion");
writer.WriteValue(Application.ProductVersion);
writer.WritePropertyName("OSVersion");
writer.WriteValue(new ComputerInfo().OSFullName);
Type type = cpu.systemInfo.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
writer.WritePropertyName(property.Name);
if (property.Name == "CpuId" || property.Name == "PatchLevel")
writer.WriteValue($"{property.GetValue(cpu.systemInfo, null):X8}");
else if (property.Name == "SmuVersion")
writer.WriteValue(cpu.systemInfo.GetSmuVersionString());
else
writer.WriteValue(property.GetValue(cpu.systemInfo, null));
}
// "SmuAddresses:"
writer.WritePropertyName("Mailboxes");
writer.WriteStartArray();
foreach (SmuAddressSet set in matches)
{
writer.WriteStartObject();
writer.WritePropertyName("MsgAddress");
writer.WriteValue($"0x{set.MsgAddress:X8}");
writer.WritePropertyName("RspAddress");
writer.WriteValue($"0x{set.RspAddress:X8}");
writer.WritePropertyName("ArgAddress");
writer.WriteValue($"0x{set.ArgAddress:X8}");
writer.WriteEndObject();
}
writer.WriteEndArray();
// }
writer.WriteEndObject();
sw.Close();
return sw.ToString();
}
private void BackgroundWorkerReport_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
string unixTimestamp = Convert.ToString((DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMinutes);
string fileName = $@"SMUDebug_{unixTimestamp}.json";
if (File.Exists(fileName))
File.Delete(fileName);
using (var sw = new StreamWriter(fileName, true))
{
sw.WriteLine(GenerateReportJson());
}
//ResetSmuAddresses();
SetButtonsState();
SetStatusText("Report Complete.");
MessageBox.Show($"Report saved as {fileName}");
}
public static void CalculatePstateDetails(uint eax, ref uint IddDiv, ref uint IddVal, ref uint CpuVid, ref uint CpuDfsId, ref uint CpuFid)
{
IddDiv = eax >> 30;
IddVal = eax >> 22 & 0xFF;
CpuVid = eax >> 14 & 0xFF;
CpuDfsId = eax >> 8 & 0x3F;
CpuFid = eax & 0xFF;
}
private void ButtonExport_Click(object sender, EventArgs e)
{
RunBackgroundTask(BackgroundWorkerTrySettings_DoWork, BackgroundWorkerReport_RunWorkerCompleted);
}
private bool nonNumberEntered;
private void PstateFidDid_KeyDown(object sender, KeyEventArgs e)
{
nonNumberEntered = false;
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
if (e.KeyCode != Keys.Back)
{
nonNumberEntered = true;
}
}
}
if (ModifierKeys == Keys.Shift)
{
nonNumberEntered = true;
}
}
private void PstateFidDid_KeyPress(object sender, KeyPressEventArgs e)
{
if (nonNumberEntered)
{
e.Handled = true;
}
}
private void PstateFidDid_KeyUp(object sender, KeyEventArgs e)
{
var fid = string.IsNullOrEmpty(pstateFid.Text) ? 0 : int.Parse(pstateFid.Text);
var did = string.IsNullOrEmpty(pstateDid.Text) ? 1 : int.Parse(pstateDid.Text);
pstateFrequency.Text = (fid * 25 / (did * 12.5)) * 100 + "MHz";
}
private void BtnPstateRead_Click(object sender, EventArgs e)
{
uint eax = default, edx = default;
var pstateId = pstateIdBox.SelectedIndex;
if (!cpu.ReadMsr(Convert.ToUInt32(Convert.ToInt64(0xC0010064) + pstateId), ref eax, ref edx))
{
SetStatusText($@"Error reading PState {pstateId}!");
return;
}
uint IddDiv = 0x0;
uint IddVal = 0x0;
uint CpuVid = 0x0;
uint CpuDfsId = 0x0;
uint CpuFid = 0x0;
CalculatePstateDetails(eax, ref IddDiv, ref IddVal, ref CpuVid, ref CpuDfsId, ref CpuFid);
pstateDid.Text = Convert.ToString(CpuDfsId, 10);
pstateFid.Text = Convert.ToString(CpuFid, 10);
pstateFrequency.Text = (CpuFid * 25 / (CpuDfsId * 12.5)) * 100 + "MHz";
SetStatusText($@"PState {pstateId} successfully read.");
pstateDid.ReadOnly = false;