Repository navigation
Expand file tree
/
Copy pathCpu.cs
More file actions
2129 lines (1833 loc) · 79.2 KB
/
Copy pathCpu.cs
File metadata and controls
2129 lines (1833 loc) · 79.2 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
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 System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Text;
#if !NET20
using System.Globalization;
#endif
using System.Reflection;
using System.Text.RegularExpressions;
using ZenStates.Core.Drivers;
using ZenStates.Core.PawnIo;
using ZenStates.Core.Common;
using ZenStates.Core.Hardware.DRAM;
using ZenStates.Core.OHWM;
using ZenStates.Core.Hardware.Smu.Commands;
using ZenStates.Core.Hardware;
using ZenStates.Core.Hardware.MutexLock;
using ZenStates.Core.Hardware.Apob;
using ZenStates.Core.Hardware.Aod;
using ZenStates.Core.Hardware.Smu;
namespace ZenStates.Core
{
public class Cpu : IDisposable
{
private readonly AmdFamily17 _pawnAmd;
private readonly RyzenSmu _pawnRyzenSmu;
private readonly SmbusDriverBase _smbusPiix4;
private readonly LpcIO _lpcIO;
private bool disposedValue;
private const string InitializationExceptionText = "CPU module initialization failed.";
// Compiled once.
// GetCodeName, and RegexOptions.Compiled needs Reflection.Emit, which NativeAOT lacks.
private static readonly Regex HawkPointModelRegex =
new Regex(@"\b80\d{2}\b", RegexOptions.CultureInvariant);
private static readonly Regex HawkPointSeriesRegex =
new Regex(@"Ryzen [3579](?:\s+PRO)?\s+2\d{2}\s", RegexOptions.CultureInvariant);
public readonly Version Version = Assembly.GetExecutingAssembly().GetName().Version;
public RyzenSmu RyzenSmu => _pawnRyzenSmu;
public enum Family
{
UNSUPPORTED = 0x0,
FAMILY_0FH = 0x0F,
FAMILY_10H = 0x10,
FAMILY_12H = 0x12,
FAMILY_15H = 0x15,
FAMILY_16H = 0x16,
FAMILY_17H = 0x17,
FAMILY_18H = 0x18,
FAMILY_19H = 0x19,
FAMILY_1AH = 0x1A,
};
public enum CodeName
{
Unsupported = 0,
DEBUG,
K8,
K10,
K12,
K16,
Carrizo,
BristolRidge,
StoneyRidge,
Vishera,
SummitRidge,
Whitehaven,
Naples,
RavenRidge,
PinnacleRidge,
Colfax,
Picasso,
FireFlight,
Matisse,
CastlePeak,
Rome,
Dali,
Renoir,
VanGogh,
Vermeer,
Chagall,
Milan,
Cezanne,
Rembrandt,
Lucienne,
Raphael,
Phoenix,
Phoenix2,
Mendocino,
Genoa,
StormPeak,
DragonRange,
Mero,
HawkPoint,
StrixPoint,
GraniteRidge,
KrackanPoint,
KrackanPoint2,
StrixHalo,
Turin,
TurinD,
Bergamo,
ShimadaPeak,
Venice,
Annapurna,
MustangPeak,
};
// CPUID_Fn80000001_EBX [BrandId Identifier] (BrandId)
// [31:28] PkgType: package type.
// Socket FP5/FP6 = 0
// Socket AM4 = 2
// Socket SP3 = 4
// Socket TR4/TRX4 (SP3r2/SP3r3) = 7
public enum PackageType
{
FPX = 0,
AM4 = 2,
SP3 = 4,
TRX = 7,
}
public struct SVI2
{
public uint coreAddress;
public uint socAddress;
}
public struct CpuTopology
{
public uint ccds;
public uint ccxs;
public uint coresPerCcx;
public uint cores;
public uint logicalCores;
public uint physicalCores;
public uint threadsPerCore;
public uint cpuNodes;
public uint[] coreDisableMap;
public uint ccdEnableMap;
public uint ccdDisableMap;
public uint fuse1;
public uint fuse2;
public uint ccdsPresent;
public uint ccdsDown;
public uint[] performanceOfCore;
/// <summary>Cores of each CCX (L3 domain) in APIC ID order; on Strix Point they differ in size. Null when unknown.</summary>
public uint[] ccxCoreCounts;
/// <summary>Core fuse of the first CCD (or die), the bit position of its mask and the raw value per CCD as read.</summary>
public uint coreFuseAddress;
public int coreFuseShift;
public uint[] coreFuseValues;
/// <summary>Why a fuse reading was not used (it disagreed with CPUID or could not be read); null when all was used.</summary>
public string fuseNote;
}
public struct CPUInfo
{
public uint cpuid;
public Family family;
public CodeName codeName;
public string cpuName;
public string vendor;
public PackageType packageType;
public uint baseModel;
public uint extModel;
public uint model;
public uint patchLevel;
public uint stepping;
public CpuTopology topology;
public SVI2 svi2;
public AOD aod;
public Apob apob;
public SMU.SmuType smuType;
}
public readonly IODriver io;
private readonly Mmio mmio;
public readonly CPUInfo info;
public readonly SystemInfo systemInfo;
public readonly SMU smu;
public readonly PowerTable powerTable;
public readonly MemoryConfig memoryConfig;
public CoreOptions Options { get; }
public IODriver.LibStatus Status { get; }
/// <summary>
/// The non-fatal initialization error. When several subsystems failed, an exception whose message lists all
/// of them (see <see cref="InitErrors"/>) and whose InnerException is the first failure.
/// </summary>
public Exception LastError { get; }
/// <summary>Every non-fatal error recorded during initialization, in the order they occurred.</summary>
public ReadOnlyCollection<CpuInitError> InitErrors { get; }
public sealed class CpuInitError
{
public CpuInitError(string subsystem, Exception exception)
{
Subsystem = subsystem;
Exception = exception;
}
public string Subsystem { get; }
public Exception Exception { get; }
public override string ToString()
{
return string.Format("{0}: {1}", Subsystem, Exception != null ? Exception.Message : string.Empty);
}
}
/// <summary>
/// Where a family keeps its CCD and core fuses. Values read from debug reports and checked against the APOB core
/// map of the same machine are marked as verified; the others are kept from earlier versions.
/// </summary>
private sealed class TopologyFuses
{
/// <summary>Several CCDs on the package; their presence is read from the CCD fuses.</summary>
public bool Chiplet;
/// <summary>Zen / Zen+: one die per node (Threadripper and EPYC have several), each counted as a CCD.</summary>
public bool DiePerNode;
/// <summary>CCD fuses: present [23:22] (CCD0/1) and down [31:30], plus CCD2~7 down in [5:0] of the second.</summary>
public uint CcdFuse1;
public uint CcdFuse2;
/// <summary>Packages with up to 8 CCDs (Zen 2/3): the enabled CCDs are the ones not marked down.</summary>
public bool CcdMapFromDown;
/// <summary>Core disable fuse of the first CCD (or the die); 0 when not known.</summary>
public uint CoreFuse;
/// <summary>Bit position of the core disable mask in <see cref="CoreFuse"/>.</summary>
public int CoreFuseShift;
/// <summary>Address step between the core fuses of consecutive CCDs; 0 for a single die.</summary>
public uint CoreFuseCcdStride;
public uint CcxPerCcd;
public uint CoreSlotsPerCcx;
}
private const uint CCD_FUSE_ZEN2 = 0x5D218; // Matisse 3600 / Vermeer 5600X: 0x80400000, 0x3F
private const uint CCD_FUSE_ZEN4 = 0x5D218 + 0x1A4; // 0x5D3BC; Raphael 7950X: 0x00E97051, Granite Ridge 9600X: 0x024BEBA3
private const uint CCD_CORE_FUSE_STRIDE = 1u << 25;
private static TopologyFuses GetTopologyFuses(Family family, CodeName codeName)
{
switch (codeName)
{
// Zen / Zen+ desktop and HEDT: one die per node, 2 CCX of 4 cores. 0x5D25C [7:0], CCX0 in [3:0]
// (verified: 1800X 0x100, 1600 AF 0x188 = cores 3 and 7 down)
case CodeName.SummitRidge:
case CodeName.PinnacleRidge:
case CodeName.Whitehaven:
case CodeName.Colfax:
case CodeName.Naples:
return new TopologyFuses { DiePerNode = true, CoreFuse = 0x5D25C, CcxPerCcd = 2, CoreSlotsPerCcx = 4 };
// Zen 2 chiplets: 2 CCX of 4 per CCD, core fuse per CCD
case CodeName.Matisse:
case CodeName.CastlePeak:
case CodeName.Rome:
return new TopologyFuses
{
Chiplet = true,
CcdFuse1 = CCD_FUSE_ZEN2,
CcdFuse2 = CCD_FUSE_ZEN2 + 4,
CcdMapFromDown = true,
CoreFuse = 0x30081A38,
CoreFuseCcdStride = CCD_CORE_FUSE_STRIDE,
CcxPerCcd = 2,
CoreSlotsPerCcx = 4,
};
// Zen 3 chiplets: 1 CCX of 8 per CCD
case CodeName.Vermeer:
case CodeName.Chagall:
case CodeName.Milan:
return new TopologyFuses
{
Chiplet = true,
CcdFuse1 = CCD_FUSE_ZEN2,
CcdFuse2 = CCD_FUSE_ZEN2 + 4,
CcdMapFromDown = true,
CoreFuse = 0x30081D98,
CoreFuseCcdStride = CCD_CORE_FUSE_STRIDE,
CcxPerCcd = 1,
CoreSlotsPerCcx = 8,
};
// Zen 4 / Zen 5 desktop: up to 2 CCDs
case CodeName.Raphael:
case CodeName.DragonRange:
return new TopologyFuses
{
Chiplet = true,
CcdFuse1 = CCD_FUSE_ZEN4,
CcdFuse2 = CCD_FUSE_ZEN4 + 4,
CoreFuse = 0x30081CD0,
CoreFuseCcdStride = CCD_CORE_FUSE_STRIDE,
CcxPerCcd = 1,
CoreSlotsPerCcx = 8,
};
case CodeName.GraniteRidge:
return new TopologyFuses
{
Chiplet = true,
CcdFuse1 = CCD_FUSE_ZEN4,
CcdFuse2 = CCD_FUSE_ZEN4 + 4,
CoreFuse = 0x304A03DC,
CoreFuseCcdStride = CCD_CORE_FUSE_STRIDE,
CcxPerCcd = 1,
CoreSlotsPerCcx = 8,
};
// Monolithic APUs: one die, no CCD fuses. The core mask sits at a bit offset in an SMUFUSE register.
// Cezanne: 0x5D448 [18:11] (verified: 5300G 0x002D9470 = 0xB2, cores 1, 4, 5, 7 down as in its APOB)
case CodeName.Cezanne:
return new TopologyFuses { CoreFuse = 0x5D448, CoreFuseShift = 11, CcxPerCcd = 1, CoreSlotsPerCcx = 8 };
// Phoenix: 0x5D528 [14:7] (verified: 8400F 0x00002860 = 0x50, cores 4 and 6 down as in its APOB)
case CodeName.Phoenix:
case CodeName.HawkPoint:
return new TopologyFuses { CoreFuse = 0x5D528, CoreFuseShift = 7, CcxPerCcd = 1, CoreSlotsPerCcx = 8 };
// Monolithic APUs whose core fuse layout is not known yet (Raven / Picasso 0x5D254, Renoir 0x5D3E8,
// Rembrandt 0x5D4DC, Strix / Krackan 0x3820AB0 are candidates): counts come from CPUID only
case CodeName.RavenRidge:
case CodeName.Picasso:
case CodeName.Dali:
case CodeName.FireFlight:
case CodeName.Mendocino:
case CodeName.VanGogh:
return new TopologyFuses { CcxPerCcd = 1, CoreSlotsPerCcx = 4 };
case CodeName.Renoir:
case CodeName.Lucienne:
return new TopologyFuses { CcxPerCcd = 2, CoreSlotsPerCcx = 4 };
case CodeName.Rembrandt:
case CodeName.Phoenix2:
case CodeName.Mero:
return new TopologyFuses { CcxPerCcd = 1, CoreSlotsPerCcx = 8 };
// Zen 5 + Zen 5c on one die, no CCDs. The CCXs (L3 domains) come from CPUID; these values are only the
// fallback when it can't be read. Strix Point has two L3s (Zen 5 and Zen 5c); Krackan is not confirmed.
case CodeName.StrixPoint:
return new TopologyFuses { CcxPerCcd = 2 };
case CodeName.KrackanPoint:
case CodeName.KrackanPoint2:
return new TopologyFuses { CcxPerCcd = 1 };
default:
// Server parts and anything newer: CCDs from CPUID, assuming one CCX per CCD
return new TopologyFuses { Chiplet = family >= Family.FAMILY_19H, CcxPerCcd = family >= Family.FAMILY_19H ? 1u : 2u };
}
}
/// <summary>
/// The cores of each CCX, in APIC ID order: the extended APIC ID of every core (CPUID 0x8000001E on its first
/// thread) grouped by the L3 it shares (CPUID 0x8000001D). Null when CPUID can't tell.
/// </summary>
private static List<uint> GetCcxCoreCounts(CpuTopology topology)
{
int shift = -1;
for (uint leaf = 0; leaf < 8; leaf++)
{
if (!Opcode.Cpuid(0x8000001D, leaf, out uint eax, out _, out _, out _) || (eax & 0x1F) == 0)
break;
if (Utils.GetBits(eax, 5, 3) == 3)
{
uint sharing = Utils.GetBits(eax, 14, 12) + 1;
shift = 0;
while ((1u << shift) < sharing)
shift++;
break;
}
}
if (shift < 0 || topology.threadsPerCore == 0)
return null;
List<uint> ccxIds = new List<uint>();
List<uint> counts = new List<uint>();
for (int i = 0; i < topology.logicalCores; i += (int)topology.threadsPerCore)
{
if (!Opcode.CpuidTx(0x8000001E, 0, out uint apicId, out _, out _, out _, GroupAffinity.ForLogicalProcessor(i)))
return null;
uint ccx = apicId >> shift;
int index = ccxIds.IndexOf(ccx);
if (index < 0)
{
ccxIds.Add(ccx);
counts.Add(1);
}
else
{
counts[index]++;
}
}
return counts;
}
private CpuTopology GetCpuTopology(Family family, CodeName codeName, uint model)
{
CpuTopology topology = new CpuTopology();
if (Opcode.Cpuid(0x00000001, 0, out uint eax, out uint ebx, out uint ecx, out uint edx))
topology.logicalCores = Utils.GetBits(ebx, 16, 8);
else
throw new ApplicationException(InitializationExceptionText);
if (Opcode.Cpuid(0x8000001E, 0, out eax, out ebx, out ecx, out edx))
{
topology.threadsPerCore = Utils.GetBits(ebx, 8, 4) + 1;
topology.cpuNodes = ((ecx >> 8) & 0x7) + 1;
if (topology.threadsPerCore == 0)
topology.cores = topology.logicalCores;
else
topology.cores = topology.logicalCores / topology.threadsPerCore;
}
else
{
throw new ApplicationException(InitializationExceptionText);
}
try
{
topology.performanceOfCore = new uint[topology.cores];
for (int i = 0; i < topology.logicalCores; i += (int)topology.threadsPerCore)
{
uint _eax = default; uint _edx = default;
if (ReadMsrTx(0xC00102B3, ref _eax, ref _edx, GroupAffinity.ForLogicalProcessor(i)))
topology.performanceOfCore[i / topology.threadsPerCore] = _eax & 0xff;
else
topology.performanceOfCore[i / topology.threadsPerCore] = 0;
}
}
catch { }
TopologyFuses fuses = GetTopologyFuses(family, codeName);
// CCX and core counts from CPUID: what the OS sees, whatever the fuse layout
List<uint> ccxCores = null;
try
{
ccxCores = GetCcxCoreCounts(topology);
}
catch (Exception ex)
{
Debug.WriteLine($"CPU topology: CCX enumeration failed. {ex.Message}");
}
if (ccxCores != null && ccxCores.Count > 0)
{
topology.ccxCoreCounts = ccxCores.ToArray();
topology.ccxs = (uint)ccxCores.Count;
foreach (uint count in ccxCores)
topology.coresPerCcx = Math.Max(topology.coresPerCcx, count);
}
uint ccxPerCcd = Math.Max(1, fuses.CcxPerCcd);
uint ccdsFromCcx = topology.ccxs > 0 ? Math.Max(1, topology.ccxs / ccxPerCcd) : 1;
if (!fuses.Chiplet)
{
// A single die, or one per node on Zen / Zen+ multi-die parts
topology.ccds = fuses.DiePerNode ? Math.Max(1, topology.cpuNodes) : 1;
topology.ccdEnableMap = (1u << (int)topology.ccds) - 1;
}
if (Mutexes.WaitPciBus(5000))
{
try
{
if (fuses.Chiplet && fuses.CcdFuse1 != 0)
ReadCcdFusesNoLock(fuses, ccdsFromCcx, ref topology);
// The core fuses are read per enabled CCD, so the CCDs have to be known first
if (topology.ccds == 0)
{
topology.ccds = ccdsFromCcx;
topology.ccdEnableMap = (1u << (int)Math.Min(topology.ccds, 31)) - 1;
}
if (fuses.CoreFuse != 0)
ReadCoreFusesNoLock(fuses, ref topology);
}
catch (Exception ex)
{
Debug.WriteLine($"Error retrieving CPU topology. {ex}");
}
finally
{
Mutexes.ReleasePciBus();
}
}
if (topology.ccds == 0)
{
topology.ccds = ccdsFromCcx;
topology.ccdEnableMap = (1u << (int)Math.Min(topology.ccds, 31)) - 1;
}
if (topology.ccxs == 0)
topology.ccxs = topology.ccds * ccxPerCcd;
if (topology.coresPerCcx == 0)
topology.coresPerCcx = Math.Max(1, topology.cores / Math.Max(1, topology.ccxs));
topology.physicalCores = fuses.CoreSlotsPerCcx > 0
? topology.ccds * ccxPerCcd * fuses.CoreSlotsPerCcx
: topology.cores;
return topology;
}
private static void AddFuseNote(ref CpuTopology topology, string note)
{
topology.fuseNote = topology.fuseNote == null ? note : topology.fuseNote + "; " + note;
}
private static uint CcdDisableMap(uint ccdsPresent, uint ccdsDown)
{
return Utils.BitSlice(ccdsPresent, 31, 30) | (Utils.BitSlice(ccdsDown, 5, 0) << 2);
}
private static uint CcdEnableMap(TopologyFuses fuses, uint ccdsPresent, uint ccdsDown)
{
uint down = CcdDisableMap(ccdsPresent, ccdsDown);
return fuses.CcdMapFromDown ? ~down & 0xFF : Utils.BitSlice(ccdsPresent, 23, 22) & ~down;
}
/// <summary>Disabled core slots of one CCD (or die) from its core fuse value.</summary>
private static uint CoreDisableMask(TopologyFuses fuses, uint value)
{
uint slots = fuses.CcxPerCcd * fuses.CoreSlotsPerCcx;
uint slotMask = slots >= 32 ? 0xFFFFFFFF : (1u << (int)slots) - 1;
return (value >> fuses.CoreFuseShift) & slotMask;
}
/// <summary>
/// The enabled CCDs from the CCD fuses. Kept only when their number matches the CCXs CPUID reports.
/// </summary>
private void ReadCcdFusesNoLock(TopologyFuses fuses, uint ccdsFromCcx, ref CpuTopology topology)
{
uint ccdsPresent = 0, ccdsDown = 0;
if (!ReadDwordExNoLock(fuses.CcdFuse1, ref ccdsPresent) || !ReadDwordExNoLock(fuses.CcdFuse2, ref ccdsDown) ||
ccdsPresent == 0xFFFFFFFF)
{
Debug.WriteLine("Could not read CCD fuse!");
AddFuseNote(ref topology, string.Format("CCD fuse 0x{0:X5} could not be read; CCDs from CPUID", fuses.CcdFuse1));
return;
}
uint ccdDisableMap = CcdDisableMap(ccdsPresent, ccdsDown);
uint ccdEnableMap = CcdEnableMap(fuses, ccdsPresent, ccdsDown);
topology.fuse1 = fuses.CcdFuse1;
topology.fuse2 = fuses.CcdFuse2;
topology.ccdsPresent = ccdsPresent;
topology.ccdsDown = ccdsDown;
uint enabled = Utils.CountSetBits(ccdEnableMap);
if (enabled == 0 || (topology.ccxs > 0 && enabled != ccdsFromCcx))
{
string note = $"CCD fuses (0x{ccdsPresent:X8}, 0x{ccdsDown:X8}) give {enabled} CCD(s), CPUID {ccdsFromCcx}; CPUID is used";
Debug.WriteLine(note);
AddFuseNote(ref topology, note);
return;
}
topology.ccds = enabled;
topology.ccdEnableMap = ccdEnableMap;
topology.ccdDisableMap = ccdDisableMap;
}
/// <summary>
/// The disabled cores of each CCD (or die), one bit per core slot, in logical CCD order. The map is dropped when
/// the cores it leaves enabled don't add up to the cores CPUID reports.
/// </summary>
private void ReadCoreFusesNoLock(TopologyFuses fuses, ref CpuTopology topology)
{
uint ccds = topology.ccds > 0 ? topology.ccds : 1;
uint slots = fuses.CcxPerCcd * fuses.CoreSlotsPerCcx;
uint[] map = new uint[ccds];
uint enabledCores = 0;
uint enableMap = topology.ccdEnableMap != 0 ? topology.ccdEnableMap : 1;
uint[] values = new uint[ccds];
topology.coreFuseAddress = fuses.CoreFuse;
topology.coreFuseShift = fuses.CoreFuseShift;
topology.coreFuseValues = values;
int logical = 0;
for (int physical = 0; physical < 32 && logical < ccds; physical++)
{
if ((enableMap & (1u << physical)) == 0)
continue;
// Zen / Zen+ multi-die parts: only the fuse of the first die is reachable here; the dies match
uint address = fuses.CoreFuse + fuses.CoreFuseCcdStride * (uint)physical;
uint value = 0;
bool read = ReadDwordExNoLock(address, ref value);
values[logical] = read ? value : 0xFFFFFFFF;
if (!read || value == 0xFFFFFFFF)
{
Debug.WriteLine($"Could not read core fuse for CCD{physical}!");
AddFuseNote(ref topology, string.Format("Core fuse 0x{0:X8} of CCD{1} could not be read; no core map", address, physical));
return;
}
map[logical] = CoreDisableMask(fuses, value);
enabledCores += slots - Utils.CountSetBits(map[logical]);
logical++;
}
if (enabledCores != topology.cores)
{
string note = $"Core fuses give {enabledCores} core(s), CPUID {topology.cores}; the core map is not used";
Debug.WriteLine(note);
AddFuseNote(ref topology, note);
return;
}
topology.coreDisableMap = map;
if (topology.ccxs == 0)
{
// No CPUID enumeration: cores per CCX from the first CCD's fuse
topology.coresPerCcx = (slots - Utils.CountSetBits(map[0])) / fuses.CcxPerCcd;
}
}
public Cpu(CoreOptions options = null)
{
Options = options ?? new CoreOptions();
CoreOptions.Current = Options;
#if !NET20
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
#endif
if (!PawnIo.PawnIo.IsInstalled)
{
ApplicationException notInstalled = new ApplicationException("PawnIO is not installed.");
WriteCrashLog(notInstalled, null);
throw notInstalled;
}
// Non-fatal errors are collected here and reported through InitErrors/LastError/Status.
List<CpuInitError> errors = new List<CpuInitError>();
try
{
Opcode.Open();
info.vendor = GetVendor();
if (info.vendor != Constants.VENDOR_AMD && info.vendor != Constants.VENDOR_HYGON)
throw new Exception("Not an AMD CPU");
ReportProgress("CPUID");
if (Opcode.Cpuid(0x00000001, 0, out uint eax, out uint ebx, out uint ecx, out uint edx))
{
info.cpuid = eax;
info.family = (Family)(((eax & 0xf00) >> 8) + ((eax & 0xff00000) >> 20));
info.baseModel = (eax & 0xf0) >> 4;
info.extModel = (eax & 0xf0000) >> 16;
info.model = info.baseModel + info.extModel * 0x10;
info.stepping = eax & 0xf;
// info.logicalCores = Utils.GetBits(ebx, 16, 8);
}
else
{
throw new ApplicationException(InitializationExceptionText);
}
Mutexes.Open();
ReportProgress("PawnIO modules");
try
{
_pawnAmd = new AmdFamily17();
_pawnRyzenSmu = new RyzenSmu();
_smbusPiix4 = SmbusProvider.Instance;
_lpcIO = new LpcIO();
}
catch (Exception ex)
{
throw new ApplicationException("Error initializing PawnIO AMD module.", ex);
}
if (info.family >= Family.FAMILY_17H && !_pawnAmd.IsLoaded)
{
throw new ApplicationException(
"PawnIO Ryzen SMN module could not be loaded. Make sure the PawnIO driver is installed and running, and that the application runs as administrator.");
}
if (!_pawnRyzenSmu.IsLoaded)
{
throw new ApplicationException(
"PawnIO Ryzen SMU module could not be loaded. Make sure the PawnIO driver is installed and running, and that the application runs as administrator.");
}
try
{
io = new IODriver();
}
catch (Exception ex)
{
io = null;
RecordError(errors, ex, "IODriver");
}
info.cpuName = GetCpuName();
// Package type
if (Opcode.Cpuid(0x80000001, 0, out eax, out ebx, out ecx, out edx))
{
info.packageType = (PackageType)(ebx >> 28);
info.codeName = GetCodeName(info);
ReportProgress("SMU");
SMU.SetRyzenSmu(_pawnRyzenSmu);
smu = GetMaintainedSettings.GetByType(info.codeName);
smu.Hsmp.Init(this);
smu.Version = GetSmuVersion();
var tableVersionResult = GetTableVersion();
smu.TableVersion = tableVersionResult.TableVersion;
// Temporary workaround for pmt not refreshing with PawnIO module
// TODO: Fix in PawnIO RyzenSmu module and remove this
if (smu.SMU_TYPE <= SMU.SmuType.TYPE_CPU1)
{
var result = new CmdResult(6);
smu.SendRsmuCommand(0xE, ref result.args);
}
info.smuType = smu.SMU_TYPE;
}
else
{
throw new ApplicationException(InitializationExceptionText);
}
mmio = new Mmio(info.family);
}
catch (Exception ex)
{
WriteCrashLog(ex, errors);
Dispose(true);
throw;
}
// Non-critical block
ReportProgress("CPU topology");
try
{
info.topology = GetCpuTopology(info.family, info.codeName, info.model);
}
catch (Exception ex)
{
RecordError(errors, ex, "CPU topology");
}
ReportProgress("Memory configuration");
try
{
memoryConfig = new MemoryConfig(this);
}
catch (Exception ex)
{
RecordError(errors, ex, "MemoryConfig");
}
try
{
info.patchLevel = GetPatchLevel();
info.svi2 = GetSVI2Info(info.codeName);
}
catch (Exception ex)
{
RecordError(errors, ex, "Patch level/SVI2");
}
ReportProgress("AOD");
try
{
info.aod = new AOD(io, this);
}
catch (Exception ex)
{
RecordError(errors, ex, "AOD");
}
ReportProgress("APOB");
try
{
info.apob = new Apob(info, memoryConfig);
// Soldered LPDDR5 has no SPD device; the APOB keeps the copy the BIOS used
memoryConfig?.UseApobSpd(info.apob.DimmSpd);
}
catch (Exception ex)
{
RecordError(errors, ex, "APOB");
}
ReportProgress("System info");
try
{
systemInfo = new SystemInfo(info, smu, GetAgesaVersion());
}
catch (Exception ex)
{
RecordError(errors, ex, "SystemInfo");
}
ReportProgress("Power table");
try
{
powerTable = new PowerTable(_pawnRyzenSmu, info.codeName);
systemInfo?.AddHardware(new Svi3Hardware(powerTable));
}
catch (Exception ex)
{
RecordError(errors, ex, "PowerTable");
}
ReportProgress("SMU test");
try
{
if (!SendTestMessage())
RecordError(errors, new ApplicationException("SMU is not responding to test message!"), "SMU");
}
catch (Exception ex)
{
RecordError(errors, ex, "SMU test message");
}
try
{
powerTable?.Refresh();
}
catch (Exception ex)
{
RecordError(errors, ex, "PowerTable refresh");
}
InitErrors = errors.AsReadOnly();
LastError = BuildInitException(errors);
Status = errors.Count > 0 ? IODriver.LibStatus.PARTIALLY_OK : IODriver.LibStatus.OK;
}
private void ReportProgress(string stage)
{
Action<string> callback = Options?.InitProgress;
if (callback == null)
return;
try
{
callback(stage);
}
catch (Exception ex)
{
// Progress is informational only; never let it break initialization.
Debug.WriteLine($"InitProgress callback failed: {ex.Message}");
}
}
private const string CrashLogFileName = "zenstates-core.crash.log";
// Appends a fatal initialization error (and any non-fatal errors recorded before it) to the crash log.
private static void WriteCrashLog(Exception ex, List<CpuInitError> errors)
{
try
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("[{0:yyyy-MM-dd HH:mm:ss}] ZenStates-Core fatal initialization error", DateTime.Now).AppendLine();
sb.AppendFormat("Version: {0}", Assembly.GetExecutingAssembly().GetName().Version).AppendLine();
sb.AppendFormat("OS: {0}", Environment.OSVersion).AppendLine();
sb.AppendLine(ex != null ? ex.ToString() : "Unknown error");
if (errors != null && errors.Count > 0)
{
sb.AppendLine("Errors recorded before the failure:");
foreach (CpuInitError error in errors)
sb.Append("- ").AppendLine(error.Exception != null ? error.Subsystem + ": " + error.Exception : error.ToString());
}
sb.AppendLine();
string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CrashLogFileName);
System.IO.File.AppendAllText(path, sb.ToString());
}
catch (Exception logEx)
{
// Logging must never mask the original error.
Debug.WriteLine($"Could not write crash log: {logEx.Message}");
}
}
private static void RecordError(List<CpuInitError> errors, Exception ex, string subsystem)
{
Debug.WriteLine($"{subsystem} initialization failed: {ex?.Message}");
errors.Add(new CpuInitError(subsystem, ex));
}
private static Exception BuildInitException(List<CpuInitError> errors)
{
if (errors.Count == 0)
return null;
if (errors.Count == 1)
return errors[0].Exception;
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0} subsystems failed to initialize:", errors.Count);
foreach (CpuInitError error in errors)
sb.Append(Environment.NewLine).Append("- ").Append(error.ToString());
return new ApplicationException(sb.ToString(), errors[0].Exception);
}
// [31-28] ccd index
// [27-24] ccx index (always 0 for Zen3 where each ccd has just one ccx)
// [23-20] core index
public uint MakeCoreMask(uint core = 0, uint ccd = 0, uint ccx = 0)
{
if (info.family > Family.FAMILY_17H)
{
return (ccd << 28) | ((core % 8) << 20);
}
return (ccd << 28) | ((ccx % 2) << 24) | ((core % 4) << 20);
}
/// <summary>
/// The core mask (see <see cref="MakeCoreMask"/>) of a core given by its logical index: the logical processor
/// number divided by the threads per core, in the order the OS enumerates them. The physical CCD, CCX and
/// core come from the APOB core map, so disabled CCDs and cores are skipped the way the firmware did.
/// Returns null when the APOB has no core map or the index is out of range.
/// </summary>
public uint? MakeCoreMaskForLogicalCore(int logicalCore)
{
ApobCoreMapCore core = info.apob?.CoreMap?.GetLogicalCore(logicalCore);
if (core == null)
return null;
return MakeCoreMask((uint)core.PhysicalCore, (uint)core.PhysicalCcd, (uint)core.PhysicalCcx);
}
public bool ReadDwordExNoLock(uint addr, ref uint data, int maxRetries = 10)
{
if (maxRetries < 1)
maxRetries = 1;
for (int retry = 0; retry < maxRetries; retry++)
{
try
{
return _pawnAmd.ReadSmnNoLock(addr, out data);
}
catch (Exception ex)
{
Debug.WriteLine($"ReadSmnNoLock(0x{addr:X8}) attempt {retry + 1} threw: {ex.Message}");
}
}
data = 0;
return false;
}
public bool ReadDwordEx(uint addr, ref uint data, int maxRetries = 10)
{
using (new PciBusLock())
{
return ReadDwordExNoLock(addr, ref data, maxRetries);
}
}
public bool IoReadDwordEx(uint addr, ref uint data, int maxRetries = 10)
{
if (io == null)
return false;
if (!Mutexes.WaitPciBus(5000))
return false;
try
{
io.DlPortWritePortUlong(0x0CF8, addr);
data = unchecked((uint)(io.DlPortReadPortUlong(0x0CFC)));
return true;
}
catch