Chameleon

Chameleon Svn Source Tree

Root/branches/ErmaC/Enoch/i386/libsaio/cpu.c

1/*
2 * Copyright 2008 Islam Ahmed Zaid. All rights reserved. <azismed@gmail.com>
3 * AsereBLN: 2009: cleanup and bugfix
4 * Bronya: 2015 Improve AMD support, cleanup and bugfix
5 */
6
7#include "libsaio.h"
8#include "platform.h"
9#include "cpu.h"
10#include "bootstruct.h"
11#include "boot.h"
12
13#ifndef DEBUG_CPU
14#define DEBUG_CPU 0
15#endif
16
17#if DEBUG_CPU
18#define DBG(x...)printf(x)
19#else
20#define DBG(x...)
21#endif
22
23
24#define UI_CPUFREQ_ROUNDING_FACTOR10000000
25
26clock_frequency_info_t gPEClockFrequencyInfo;
27
28static __unused uint64_t rdtsc32(void)
29{
30unsigned int lo,hi;
31__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
32return ((uint64_t)hi << 32) | lo;
33}
34
35/*
36 * timeRDTSC()
37 * This routine sets up PIT counter 2 to count down 1/20 of a second.
38 * It pauses until the value is latched in the counter
39 * and then reads the time stamp counter to return to the caller.
40 */
41static uint64_t timeRDTSC(void)
42{
43intattempts = 0;
44uint32_t latchTime;
45uint64_tsaveTime,intermediate;
46unsigned inttimerValue, lastValue;
47//boolean_tint_enabled;
48/*
49 * Table of correction factors to account for
50 * - timer counter quantization errors, and
51 * - undercounts 0..5
52 */
53#define SAMPLE_CLKS_EXACT(((double) CLKNUM) / 20.0)
54#define SAMPLE_CLKS_INT((int) CLKNUM / 20)
55#define SAMPLE_NSECS(2000000000LL)
56#define SAMPLE_MULTIPLIER(((double)SAMPLE_NSECS)*SAMPLE_CLKS_EXACT)
57#define ROUND64(x)((uint64_t)((x) + 0.5))
58uint64_tscale[6] = {
59ROUND64(SAMPLE_MULTIPLIER/(double)(SAMPLE_CLKS_INT-0)),
60ROUND64(SAMPLE_MULTIPLIER/(double)(SAMPLE_CLKS_INT-1)),
61ROUND64(SAMPLE_MULTIPLIER/(double)(SAMPLE_CLKS_INT-2)),
62ROUND64(SAMPLE_MULTIPLIER/(double)(SAMPLE_CLKS_INT-3)),
63ROUND64(SAMPLE_MULTIPLIER/(double)(SAMPLE_CLKS_INT-4)),
64ROUND64(SAMPLE_MULTIPLIER/(double)(SAMPLE_CLKS_INT-5))
65};
66
67//int_enabled = ml_set_interrupts_enabled(false);
68
69restart:
70if (attempts >= 3) // increase to up to 9 attempts.
71{
72// This will flash-reboot. TODO: Use tscPanic instead.
73//printf("Timestamp counter calibation failed with %d attempts\n", attempts);
74}
75attempts++;
76enable_PIT2();// turn on PIT2
77set_PIT2(0);// reset timer 2 to be zero
78latchTime = rdtsc32();// get the time stamp to time
79latchTime = get_PIT2(&timerValue) - latchTime; // time how long this takes
80set_PIT2(SAMPLE_CLKS_INT);// set up the timer for (almost) 1/20th a second
81saveTime = rdtsc32();// now time how long a 20th a second is...
82get_PIT2(&lastValue);
83get_PIT2(&lastValue);// read twice, first value may be unreliable
84do {
85intermediate = get_PIT2(&timerValue);
86if (timerValue > lastValue)
87{
88// Timer wrapped
89set_PIT2(0);
90disable_PIT2();
91goto restart;
92}
93lastValue = timerValue;
94} while (timerValue > 5);
95//printf("timerValue %d\n",timerValue);
96//printf("intermediate 0x%016llX\n",intermediate);
97//printf("saveTime 0x%016llX\n",saveTime);
98
99intermediate -= saveTime;// raw count for about 1/20 second
100intermediate *= scale[timerValue];// rescale measured time spent
101intermediate /= SAMPLE_NSECS;// so its exactly 1/20 a second
102intermediate += latchTime;// add on our save fudge
103
104set_PIT2(0);// reset timer 2 to be zero
105disable_PIT2();// turn off PIT 2
106
107//ml_set_interrupts_enabled(int_enabled);
108return intermediate;
109}
110
111/*
112 * DFE: Measures the TSC frequency in Hz (64-bit) using the ACPI PM timer
113 */
114static uint64_t __unused measure_tsc_frequency(void)
115{
116uint64_t tscStart;
117uint64_t tscEnd;
118uint64_t tscDelta = 0xffffffffffffffffULL;
119unsigned long pollCount;
120uint64_t retval = 0;
121int i;
122
123/* Time how many TSC ticks elapse in 30 msec using the 8254 PIT
124 * counter 2. We run this loop 3 times to make sure the cache
125 * is hot and we take the minimum delta from all of the runs.
126 * That is to say that we're biased towards measuring the minimum
127 * number of TSC ticks that occur while waiting for the timer to
128 * expire. That theoretically helps avoid inconsistencies when
129 * running under a VM if the TSC is not virtualized and the host
130 * steals time. The TSC is normally virtualized for VMware.
131 */
132for(i = 0; i < 10; ++i)
133{
134enable_PIT2();
135set_PIT2_mode0(CALIBRATE_LATCH);
136tscStart = rdtsc64();
137pollCount = poll_PIT2_gate();
138tscEnd = rdtsc64();
139/* The poll loop must have run at least a few times for accuracy */
140if (pollCount <= 1)
141{
142continue;
143}
144/* The TSC must increment at LEAST once every millisecond.
145 * We should have waited exactly 30 msec so the TSC delta should
146 * be >= 30. Anything less and the processor is way too slow.
147 */
148if ((tscEnd - tscStart) <= CALIBRATE_TIME_MSEC)
149{
150continue;
151}
152// tscDelta = MIN(tscDelta, (tscEnd - tscStart))
153if ( (tscEnd - tscStart) < tscDelta )
154{
155tscDelta = tscEnd - tscStart;
156}
157}
158/* tscDelta is now the least number of TSC ticks the processor made in
159 * a timespan of 0.03 s (e.g. 30 milliseconds)
160 * Linux thus divides by 30 which gives the answer in kiloHertz because
161 * 1 / ms = kHz. But we're xnu and most of the rest of the code uses
162 * Hz so we need to convert our milliseconds to seconds. Since we're
163 * dividing by the milliseconds, we simply multiply by 1000.
164 */
165
166/* Unlike linux, we're not limited to 32-bit, but we do need to take care
167 * that we're going to multiply by 1000 first so we do need at least some
168 * arithmetic headroom. For now, 32-bit should be enough.
169 * Also unlike Linux, our compiler can do 64-bit integer arithmetic.
170 */
171if (tscDelta > (1ULL<<32))
172{
173retval = 0;
174}
175else
176{
177retval = tscDelta * 1000 / 30;
178}
179disable_PIT2();
180return retval;
181}
182
183static uint64_trtc_set_cyc_per_sec(uint64_t cycles);
184#define RTC_FAST_DENOM0xFFFFFFFF
185
186inline static uint32_t
187create_mul_quant_GHZ(int shift, uint32_t quant)
188{
189return (uint32_t)((((uint64_t)NSEC_PER_SEC/20) << shift) / quant);
190}
191
192struct{
193mach_timespec_tcalend_offset;
194boolean_tcalend_is_set;
195
196int64_tcalend_adjtotal;
197int32_tcalend_adjdelta;
198
199uint32_tboottime;
200
201mach_timebase_info_data_ttimebase_const;
202
203decl_simple_lock_data(,lock)/* real-time clock device lock */
204} rtclock;
205
206uint32_trtc_quant_shift;/* clock to nanos right shift */
207uint32_trtc_quant_scale;/* clock to nanos multiplier */
208uint64_trtc_cyc_per_sec;/* processor cycles per sec */
209uint64_trtc_cycle_count;/* clocks in 1/20th second */
210
211static uint64_t rtc_set_cyc_per_sec(uint64_t cycles)
212{
213
214if (cycles > (NSEC_PER_SEC/20))
215{
216// we can use just a "fast" multiply to get nanos
217rtc_quant_shift = 32;
218rtc_quant_scale = create_mul_quant_GHZ(rtc_quant_shift, (uint32_t)cycles);
219rtclock.timebase_const.numer = rtc_quant_scale; // timeRDTSC is 1/20
220rtclock.timebase_const.denom = (uint32_t)RTC_FAST_DENOM;
221}
222else
223{
224rtc_quant_shift = 26;
225rtc_quant_scale = create_mul_quant_GHZ(rtc_quant_shift, (uint32_t)cycles);
226rtclock.timebase_const.numer = NSEC_PER_SEC/20; // timeRDTSC is 1/20
227rtclock.timebase_const.denom = (uint32_t)cycles;
228}
229rtc_cyc_per_sec = cycles*20;// multiply it by 20 and we are done..
230// BUT we also want to calculate...
231
232cycles = ((rtc_cyc_per_sec + (UI_CPUFREQ_ROUNDING_FACTOR/2))
233 / UI_CPUFREQ_ROUNDING_FACTOR)
234* UI_CPUFREQ_ROUNDING_FACTOR;
235
236/*
237 * Set current measured speed.
238 */
239if (cycles >= 0x100000000ULL)
240{
241gPEClockFrequencyInfo.cpu_clock_rate_hz = 0xFFFFFFFFUL;
242}
243else
244{
245gPEClockFrequencyInfo.cpu_clock_rate_hz = (unsigned long)cycles;
246}
247gPEClockFrequencyInfo.cpu_frequency_hz = cycles;
248
249//printf("[RTCLOCK_1] frequency %llu (%llu) %llu\n", cycles, rtc_cyc_per_sec,timeRDTSC() * 20);
250return(rtc_cyc_per_sec);
251}
252
253/*
254 * Calculates the FSB and CPU frequencies using specific MSRs for each CPU
255 * - multi. is read from a specific MSR. In the case of Intel, there is:
256 * a max multi. (used to calculate the FSB freq.),
257 * and a current multi. (used to calculate the CPU freq.)
258 * - busFrequency = tscFrequency / multi
259 * - cpuFrequency = busFrequency * multi
260 */
261
262/* Decimal powers: */
263#define kilo (1000ULL)
264#define Mega (kilo * kilo)
265#define Giga (kilo * Mega)
266#define Tera (kilo * Giga)
267#define Peta (kilo * Tera)
268
269#define quad(hi,lo)(((uint64_t)(hi)) << 32 | (lo))
270
271void get_cpuid(PlatformInfo_t *p)
272{
273
274charstr[128];
275uint32_treg[4];
276char*s= 0;
277
278
279do_cpuid(0x00000000, p->CPU.CPUID[CPUID_0]); // MaxFn, Vendor
280do_cpuid(0x00000001, p->CPU.CPUID[CPUID_1]); // Signature, stepping, features
281do_cpuid(0x00000002, p->CPU.CPUID[CPUID_2]); // TLB/Cache/Prefetch
282
283do_cpuid(0x00000003, p->CPU.CPUID[CPUID_3]); // S/N
284do_cpuid(0x80000000, p->CPU.CPUID[CPUID_80]); // Get the max extended cpuid
285
286if ((p->CPU.CPUID[CPUID_80][0] & 0x0000000f) >= 8)
287{
288do_cpuid(0x80000008, p->CPU.CPUID[CPUID_88]);
289do_cpuid(0x80000001, p->CPU.CPUID[CPUID_81]);
290}
291else if ((p->CPU.CPUID[CPUID_80][0] & 0x0000000f) >= 1)
292{
293do_cpuid(0x80000001, p->CPU.CPUID[CPUID_81]);
294}
295
296// ==============================================================
297
298/* get BrandString (if supported) */
299/* Copyright: from Apple's XNU cpuid.c */
300if (p->CPU.CPUID[CPUID_80][0] > 0x80000004)
301{
302bzero(str, 128);
303/*
304 * The BrandString 48 bytes (max), guaranteed to
305 * be NULL terminated.
306 */
307do_cpuid(0x80000002, reg);
308memcpy(&str[0], (char *)reg, 16);
309do_cpuid(0x80000003, reg);
310memcpy(&str[16], (char *)reg, 16);
311do_cpuid(0x80000004, reg);
312memcpy(&str[32], (char *)reg, 16);
313for (s = str; *s != '\0'; s++)
314{
315if (*s != ' ')
316{
317break;
318}
319}
320strlcpy(p->CPU.BrandString, s, 48);
321
322if (!strncmp(p->CPU.BrandString, CPU_STRING_UNKNOWN, MIN(sizeof(p->CPU.BrandString), (unsigned)strlen(CPU_STRING_UNKNOWN) + 1)))
323{
324/*
325 * This string means we have a firmware-programmable brand string,
326 * and the firmware couldn't figure out what sort of CPU we have.
327 */
328p->CPU.BrandString[0] = '\0';
329}
330p->CPU.BrandString[47] = '\0';
331//DBG("\tBrandstring = %s\n", p->CPU.BrandString);
332}
333
334// ==============================================================
335
336switch(p->CPU.BrandString[0])
337{
338case 'A':
339/* AMD Processors */
340// The cache information is only in ecx and edx so only save
341// those registers
342
343do_cpuid(5, p->CPU.CPUID[CPUID_5]); // Monitor/Mwait
344
345do_cpuid(0x80000005, p->CPU.CPUID[CPUID_85]); // TLB/Cache/Prefetch
346do_cpuid(0x80000006, p->CPU.CPUID[CPUID_86]); // TLB/Cache/Prefetch
347do_cpuid(0x80000008, p->CPU.CPUID[CPUID_88]);
348
349break;
350
351case 'G':
352/* Intel Processors */
353do_cpuid2(0x00000004, 0, p->CPU.CPUID[CPUID_4]); // Cache Index for Inte
354
355if (p->CPU.CPUID[CPUID_0][0] >= 0x5)// Monitor/Mwait
356{
357do_cpuid(5, p->CPU.CPUID[CPUID_5]);
358}
359
360if (p->CPU.CPUID[CPUID_0][0] >= 6)// Thermal/Power
361{
362do_cpuid(6, p->CPU.CPUID[CPUID_6]);
363}
364
365break;
366}
367}
368void scan_cpu(PlatformInfo_t *p)
369{
370verbose("[ CPU INFO ]\n");
371get_cpuid(p);
372
373uint64_tbusFCvtt2n;
374uint64_ttscFCvtt2n;
375uint64_ttscFreq= 0;
376uint64_tbusFrequency= 0;
377uint64_tcpuFrequency= 0;
378uint64_tmsr= 0;
379uint64_tflex_ratio= 0;
380uint64_tcpuid_features;
381
382uint32_tmax_ratio= 0;
383uint32_tmin_ratio= 0;
384uint32_treg[4];
385uint32_tcores_per_package= 0;
386uint32_tlogical_per_package= 1;
387uint32_tthreads_per_core= 1;
388
389uint8_tbus_ratio_max= 0;
390uint8_tbus_ratio_min= 0;
391uint8_tcurrdiv= 0;
392uint8_tcurrcoef= 0;
393uint8_tmaxdiv= 0;
394uint8_tmaxcoef= 0;
395uint8_tpic0_mask;
396uint8_tcpuMultN2= 0;
397
398const char*newratio;
399
400intlen= 0;
401intmyfsb= 0;
402inti= 0;
403
404
405/* http://www.flounder.com/cpuid_explorer2.htm
406 EAX (Intel):
407 31 28 27 20 19 16 1514 1312 11 8 7 4 3 0
408 +--------+----------------+--------+----+----+--------+--------+--------+
409 |########|Extended family |Extmodel|####|type|familyid| model |stepping|
410 +--------+----------------+--------+----+----+--------+--------+--------+
411
412 EAX (AMD):
413 31 28 27 20 19 16 1514 1312 11 8 7 4 3 0
414 +--------+----------------+--------+----+----+--------+--------+--------+
415 |########|Extended family |Extmodel|####|####|familyid| model |stepping|
416 +--------+----------------+--------+----+----+--------+--------+--------+
417*/
418///////////////////-- MaxFn,Vendor --////////////////////////
419p->CPU.Vendor= p->CPU.CPUID[CPUID_0][1];
420
421///////////////////-- Signature, stepping, features -- //////
422cpuid_features = quad(p->CPU.CPUID[CPUID_1][ecx], p->CPU.CPUID[CPUID_1][edx]);
423if (bit(28) & p->CPU.CPUID[CPUID_1][edx]) // HTT/Multicore
424{
425logical_per_package = bitfield(p->CPU.CPUID[CPUID_1][ebx], 23, 16);
426}
427else
428{
429logical_per_package = 1;
430}
431
432p->CPU.Signature= p->CPU.CPUID[CPUID_1][0];
433p->CPU.Stepping= (uint8_t)bitfield(p->CPU.CPUID[CPUID_1][0], 3, 0);// stepping = cpu_feat_eax & 0xF;
434p->CPU.Model= (uint8_t)bitfield(p->CPU.CPUID[CPUID_1][0], 7, 4);// model = (cpu_feat_eax >> 4) & 0xF;
435p->CPU.Family= (uint8_t)bitfield(p->CPU.CPUID[CPUID_1][0], 11, 8);// family = (cpu_feat_eax >> 8) & 0xF;
436//p->CPU.Type= (uint8_t)bitfield(p->CPU.CPUID[CPUID_1][0], 13, 12);// type = (cpu_feat_eax >> 12) & 0x3;
437p->CPU.ExtModel= (uint8_t)bitfield(p->CPU.CPUID[CPUID_1][0], 19, 16);// ext_model = (cpu_feat_eax >> 16) & 0xF;
438p->CPU.ExtFamily= (uint8_t)bitfield(p->CPU.CPUID[CPUID_1][0], 27, 20);// ext_family = (cpu_feat_eax >> 20) & 0xFF;
439
440if (p->CPU.Family == 0x0f)
441{
442p->CPU.Family += p->CPU.ExtFamily;
443}
444
445if (p->CPU.Family == 0x0f || p->CPU.Family == 0x06)
446{
447p->CPU.Model += (p->CPU.ExtModel << 4);
448}
449
450switch (p->CPU.Vendor)
451{
452case CPUID_VENDOR_INTEL:
453{
454/* Based on Apple's XNU cpuid.c - Deterministic cache parameters */
455if ((p->CPU.CPUID[CPUID_0][eax] > 3) && (p->CPU.CPUID[CPUID_0][eax] < 0x80000000))
456{
457for (i = 0; i < 0xFF; i++) // safe loop
458{
459do_cpuid2(0x00000004, i, reg); // AX=4: Fn, CX=i: cache index
460if (bitfield(reg[eax], 4, 0) == 0)
461{
462break;
463}
464cores_per_package = bitfield(reg[eax], 31, 26) + 1;
465}
466}
467
468if (i > 0)
469{
470cores_per_package = bitfield(p->CPU.CPUID[CPUID_4][eax], 31, 26) + 1; // i = cache index
471threads_per_core = bitfield(p->CPU.CPUID[CPUID_4][eax], 25, 14) + 1;
472}
473
474if (cores_per_package == 0)
475{
476cores_per_package = 1;
477}
478
479switch (p->CPU.Model)
480{
481case CPUID_MODEL_NEHALEM:
482case CPUID_MODEL_FIELDS:
483case CPUID_MODEL_CLARKDALE:
484case CPUID_MODEL_NEHALEM_EX:
485case CPUID_MODEL_JAKETOWN:
486case CPUID_MODEL_SANDYBRIDGE:
487case CPUID_MODEL_IVYBRIDGE:
488case CPUID_MODEL_HASWELL_U5:
489case CPUID_MODEL_HASWELL:
490case CPUID_MODEL_HASWELL_SVR:
491//case CPUID_MODEL_HASWELL_H:
492case CPUID_MODEL_HASWELL_ULT:
493case CPUID_MODEL_HASWELL_ULX:
494case CPUID_MODEL_BROADWELL_HQ:
495case CPUID_MODEL_SKYLAKE_S:
496//case CPUID_MODEL_:
497msr = rdmsr64(MSR_CORE_THREAD_COUNT); // 0x35
498p->CPU.NoCores= (uint32_t)bitfield((uint32_t)msr, 31, 16);
499p->CPU.NoThreads= (uint32_t)bitfield((uint32_t)msr, 15, 0);
500break;
501
502case CPUID_MODEL_DALES:
503case CPUID_MODEL_WESTMERE: // Intel Core i7 LGA1366 (32nm) 6 Core
504case CPUID_MODEL_WESTMERE_EX:
505msr = rdmsr64(MSR_CORE_THREAD_COUNT);
506p->CPU.NoCores= (uint32_t)bitfield((uint32_t)msr, 19, 16);
507p->CPU.NoThreads= (uint32_t)bitfield((uint32_t)msr, 15, 0);
508break;
509case CPUID_MODEL_ATOM_3700:
510p->CPU.NoCores= 4;
511p->CPU.NoThreads= 4;
512break;
513}
514
515if (p->CPU.NoCores == 0)
516{
517p->CPU.NoCores= cores_per_package;
518p->CPU.NoThreads= logical_per_package;
519}
520
521// MSR is *NOT* available on the Intel Atom CPU
522//workaround for N270. I don't know why it detected wrong
523if ((p->CPU.Model == CPUID_MODEL_ATOM) && (strstr(p->CPU.BrandString, "270")))
524{
525p->CPU.NoCores= 1;
526p->CPU.NoThreads= 2;
527}
528
529//workaround for Quad
530if ( strstr(p->CPU.BrandString, "Quad") )
531{
532p->CPU.NoCores= 4;
533p->CPU.NoThreads= 4;
534}
535
536//workaround for Xeon Harpertown
537
538if ( strstr(p->CPU.BrandString, "E5405") )
539{
540p->CPU.NoCores= 4;
541p->CPU.NoThreads= 4;
542}
543}
544
545break;
546
547case CPUID_VENDOR_AMD:
548{
549
550cores_per_package = bitfield(p->CPU.CPUID[CPUID_88][ecx], 7, 0) + 1;
551threads_per_core = cores_per_package;
552
553if (cores_per_package == 0)
554{
555cores_per_package = 1;
556}
557
558p->CPU.NoCores= cores_per_package;
559p->CPU.NoThreads= logical_per_package;
560
561if (p->CPU.NoCores == 0)
562{
563p->CPU.NoCores = 1;
564p->CPU.NoThreads= 1;
565}
566}
567break;
568
569default :
570stop("Unsupported CPU detected! System halted.");
571}
572
573/* setup features */
574if ((bit(23) & p->CPU.CPUID[CPUID_1][3]) != 0)
575{
576p->CPU.Features |= CPU_FEATURE_MMX;
577}
578
579if ((bit(25) & p->CPU.CPUID[CPUID_1][3]) != 0)
580{
581p->CPU.Features |= CPU_FEATURE_SSE;
582}
583
584if ((bit(26) & p->CPU.CPUID[CPUID_1][3]) != 0)
585{
586p->CPU.Features |= CPU_FEATURE_SSE2;
587}
588
589if ((bit(0) & p->CPU.CPUID[CPUID_1][2]) != 0)
590{
591p->CPU.Features |= CPU_FEATURE_SSE3;
592}
593
594if ((bit(19) & p->CPU.CPUID[CPUID_1][2]) != 0)
595{
596p->CPU.Features |= CPU_FEATURE_SSE41;
597}
598
599if ((bit(20) & p->CPU.CPUID[CPUID_1][2]) != 0)
600{
601p->CPU.Features |= CPU_FEATURE_SSE42;
602}
603
604if ((bit(29) & p->CPU.CPUID[CPUID_81][3]) != 0)
605{
606p->CPU.Features |= CPU_FEATURE_EM64T;
607}
608
609if ((bit(5) & p->CPU.CPUID[CPUID_1][3]) != 0)
610{
611p->CPU.Features |= CPU_FEATURE_MSR;
612}
613
614if ((p->CPU.NoThreads > p->CPU.NoCores))
615{
616p->CPU.Features |= CPU_FEATURE_HTT;
617}
618
619pic0_mask = inb(0x21U);
620outb(0x21U, 0xFFU); // mask PIC0 interrupts for duration of timing tests
621
622uint64_t cycles;
623cycles = timeRDTSC();
624tscFreq = rtc_set_cyc_per_sec(cycles);
625DBG("cpu freq classic = 0x%016llx\n", tscFreq);
626// if usual method failed
627if ( tscFreq < 1000 )//TEST
628{
629tscFreq = measure_tsc_frequency();//timeRDTSC() * 20;//measure_tsc_frequency();
630// DBG("cpu freq timeRDTSC = 0x%016llx\n", tscFrequency);
631}
632
633if (p->CPU.Vendor==CPUID_VENDOR_INTEL && ((p->CPU.Family == 0x06 && p->CPU.Model >= 0x0c) || (p->CPU.Family == 0x0f && p->CPU.Model >= 0x03)))
634{
635int intelCPU = p->CPU.Model;
636if (p->CPU.Family == 0x06)
637{
638/* Nehalem CPU model */
639switch (p->CPU.Model)
640{
641case CPUID_MODEL_NEHALEM:
642case CPUID_MODEL_FIELDS:
643case CPUID_MODEL_CLARKDALE:
644case CPUID_MODEL_DALES:
645case CPUID_MODEL_WESTMERE:
646case CPUID_MODEL_NEHALEM_EX:
647case CPUID_MODEL_WESTMERE_EX:
648/* --------------------------------------------------------- */
649case CPUID_MODEL_SANDYBRIDGE:
650case CPUID_MODEL_JAKETOWN:
651case CPUID_MODEL_IVYBRIDGE_XEON:
652case CPUID_MODEL_IVYBRIDGE:
653case CPUID_MODEL_ATOM_3700:
654case CPUID_MODEL_HASWELL:
655case CPUID_MODEL_HASWELL_U5:
656case CPUID_MODEL_HASWELL_SVR:
657
658case CPUID_MODEL_HASWELL_ULT:
659case CPUID_MODEL_HASWELL_ULX:
660case CPUID_MODEL_BROADWELL_HQ:
661case CPUID_MODEL_SKYLAKE_S:
662/* --------------------------------------------------------- */
663msr = rdmsr64(MSR_PLATFORM_INFO);
664DBG("msr(%d): platform_info %08x\n", __LINE__, bitfield(msr, 31, 0));
665bus_ratio_max = bitfield(msr, 15, 8);
666bus_ratio_min = bitfield(msr, 47, 40); //valv: not sure about this one (Remarq.1)
667msr = rdmsr64(MSR_FLEX_RATIO);
668DBG("msr(%d): flex_ratio %08x\n", __LINE__, bitfield(msr, 31, 0));
669if (bitfield(msr, 16, 16))
670{
671flex_ratio = bitfield(msr, 15, 8);
672// bcc9: at least on the gigabyte h67ma-ud2h,
673// where the cpu multipler can't be changed to
674// allow overclocking, the flex_ratio msr has unexpected (to OSX)
675// contents.These contents cause mach_kernel to
676// fail to compute the bus ratio correctly, instead
677// causing the system to crash since tscGranularity
678// is inadvertently set to 0.
679
680if (flex_ratio == 0)
681{
682// Clear bit 16 (evidently the presence bit)
683wrmsr64(MSR_FLEX_RATIO, (msr & 0xFFFFFFFFFFFEFFFFULL));
684msr = rdmsr64(MSR_FLEX_RATIO);
685DBG("CPU: Unusable flex ratio detected. Patched MSR now %08x\n", bitfield(msr, 31, 0));
686}
687else
688{
689if (bus_ratio_max > flex_ratio)
690{
691bus_ratio_max = flex_ratio;
692}
693}
694}
695
696if (bus_ratio_max)
697{
698busFrequency = (tscFreq / bus_ratio_max);
699}
700
701//valv: Turbo Ratio Limit
702if ((intelCPU != 0x2e) && (intelCPU != 0x2f))
703{
704msr = rdmsr64(MSR_TURBO_RATIO_LIMIT);
705
706cpuFrequency = bus_ratio_max * busFrequency;
707max_ratio = bus_ratio_max * 10;
708}
709else
710{
711cpuFrequency = tscFreq;
712}
713
714if ((getValueForKey(kbusratio, &newratio, &len, &bootInfo->chameleonConfig)) && (len <= 4))
715{
716max_ratio = atoi(newratio);
717max_ratio = (max_ratio * 10);
718if (len >= 3)
719{
720max_ratio = (max_ratio + 5);
721}
722
723verbose("\tBus-Ratio: min=%d, max=%s\n", bus_ratio_min, newratio);
724
725// extreme overclockers may love 320 ;)
726if ((max_ratio >= min_ratio) && (max_ratio <= 320))
727{
728cpuFrequency = (busFrequency * max_ratio) / 10;
729if (len >= 3)
730{
731maxdiv = 1;
732}
733else
734{
735maxdiv = 0;
736}
737}
738else
739{
740max_ratio = (bus_ratio_max * 10);
741}
742}
743//valv: to be uncommented if Remarq.1 didn't stick
744//if (bus_ratio_max > 0) bus_ratio = flex_ratio;
745p->CPU.MaxRatio = max_ratio;
746p->CPU.MinRatio = min_ratio;
747
748myfsb = busFrequency / 1000000;
749verbose("\tSticking with [BCLK: %dMhz, Bus-Ratio: %d]\n", myfsb, max_ratio/10); // Bungo: fixed wrong Bus-Ratio readout
750currcoef = bus_ratio_max;
751
752break;
753
754default:
755msr = rdmsr64(MSR_IA32_PERF_STATUS);
756DBG("msr(%d): ia32_perf_stat 0x%08x\n", __LINE__, bitfield(msr, 31, 0));
757currcoef = bitfield(msr, 12, 8); // Bungo: reverted to 2263 state because of wrong old CPUs freq. calculating
758// Non-integer bus ratio for the max-multi
759maxdiv = bitfield(msr, 46, 46);
760// Non-integer bus ratio for the current-multi (undocumented)
761currdiv = bitfield(msr, 14, 14);
762
763// This will always be model >= 3
764if ((p->CPU.Family == 0x06 && p->CPU.Model >= 0x0e) || (p->CPU.Family == 0x0f))
765{
766/* On these models, maxcoef defines TSC freq */
767maxcoef = bitfield(msr, 44, 40);
768}
769else
770{
771// On lower models, currcoef defines TSC freq
772// XXX
773maxcoef = currcoef;
774}
775
776if (!currcoef)
777{
778currcoef = maxcoef;
779}
780
781if (maxcoef)
782{
783if (maxdiv)
784{
785busFrequency = ((tscFreq * 2) / ((maxcoef * 2) + 1));
786}
787else
788{
789busFrequency = (tscFreq / maxcoef);
790}
791
792if (currdiv)
793{
794cpuFrequency = (busFrequency * ((currcoef * 2) + 1) / 2);
795}
796else
797{
798cpuFrequency = (busFrequency * currcoef);
799}
800
801DBG("max: %d%s current: %d%s\n", maxcoef, maxdiv ? ".5" : "",currcoef, currdiv ? ".5" : "");
802}
803break;
804}
805}
806// Mobile CPU
807if (rdmsr64(MSR_IA32_PLATFORM_ID) & (1<<28))
808{
809p->CPU.Features |= CPU_FEATURE_MOBILE;
810}
811}
812
813else if (p->CPU.Vendor==CPUID_VENDOR_AMD)
814{
815switch(p->CPU.Family)
816{
817case 0xF: /* K8 */
818{
819uint64_t fidvid = 0;
820uint64_t cpuMult;
821uint64_t fid;
822
823fidvid = rdmsr64(K8_FIDVID_STATUS);
824fid = bitfield(fidvid, 5, 0);
825
826cpuMult = (fid + 8) / 2;
827currcoef = cpuMult;
828
829cpuMultN2 = (fidvid & (uint64_t)bit(0));
830currdiv = cpuMultN2;
831/****** Addon END ******/
832}
833break;
834
835case 0x10: /*** AMD Family 10h ***/
836{
837uint64_t cofvid = 0;
838uint64_t cpuMult;
839uint64_t divisor = 0;
840uint64_t did;
841uint64_t fid;
842
843cofvid = rdmsr64(K10_COFVID_STATUS);
844did = bitfield(cofvid, 8, 6);
845fid = bitfield(cofvid, 5, 0);
846if (did == 0) divisor = 2;
847else if (did == 1) divisor = 4;
848else if (did == 2) divisor = 8;
849else if (did == 3) divisor = 16;
850else if (did == 4) divisor = 32;
851
852cpuMult = (fid + 16) / divisor;
853currcoef = cpuMult;
854
855cpuMultN2 = (cofvid & (uint64_t)bit(0));
856currdiv = cpuMultN2;
857
858/****** Addon END ******/
859}
860break;
861
862case 0x11: /*** AMD Family 11h ***/
863{
864uint64_t cofvid = 0;
865uint64_t cpuMult;
866uint64_t divisor = 0;
867uint64_t did;
868uint64_t fid;
869
870cofvid = rdmsr64(K10_COFVID_STATUS);
871did = bitfield(cofvid, 8, 6);
872fid = bitfield(cofvid, 5, 0);
873if (did == 0) divisor = 2;
874else if (did == 1) divisor = 4;
875else if (did == 2) divisor = 8;
876else if (did == 3) divisor = 16;
877else if (did == 4) divisor = 32;
878
879cpuMult = (fid + 8) / divisor;
880currcoef = cpuMult;
881
882cpuMultN2 = (cofvid & (uint64_t)bit(0));
883currdiv = cpuMultN2;
884
885/****** Addon END ******/
886}
887 break;
888
889case 0x12: /*** AMD Family 12h ***/
890{
891// 8:4 CpuFid: current CPU core frequency ID
892// 3:0 CpuDid: current CPU core divisor ID
893uint64_t prfsts,CpuFid,CpuDid;
894prfsts = rdmsr64(K10_COFVID_STATUS);
895
896CpuDid = bitfield(prfsts, 3, 0) ;
897CpuFid = bitfield(prfsts, 8, 4) ;
898uint64_t divisor;
899switch (CpuDid)
900{
901case 0: divisor = 1; break;
902case 1: divisor = (3/2); break;
903case 2: divisor = 2; break;
904case 3: divisor = 3; break;
905case 4: divisor = 4; break;
906case 5: divisor = 6; break;
907case 6: divisor = 8; break;
908case 7: divisor = 12; break;
909case 8: divisor = 16; break;
910default: divisor = 1; break;
911}
912currcoef = (CpuFid + 0x10) / divisor;
913
914cpuMultN2 = (prfsts & (uint64_t)bit(0));
915currdiv = cpuMultN2;
916
917}
918break;
919
920case 0x14: /* K14 */
921
922{
923// 8:4: current CPU core divisor ID most significant digit
924// 3:0: current CPU core divisor ID least significant digit
925uint64_t prfsts;
926prfsts = rdmsr64(K10_COFVID_STATUS);
927
928uint64_t CpuDidMSD,CpuDidLSD;
929CpuDidMSD = bitfield(prfsts, 8, 4) ;
930CpuDidLSD = bitfield(prfsts, 3, 0) ;
931
932uint64_t frequencyId = 0x10;
933currcoef = (frequencyId + 0x10) /
934(CpuDidMSD + (CpuDidLSD * 0.25) + 1);
935currdiv = ((CpuDidMSD) + 1) << 2;
936currdiv += bitfield(msr, 3, 0);
937
938cpuMultN2 = (prfsts & (uint64_t)bit(0));
939currdiv = cpuMultN2;
940}
941
942break;
943
944case 0x15: /*** AMD Family 15h ***/
945case 0x06: /*** AMD Family 06h ***/
946{
947
948uint64_t cofvid = 0;
949uint64_t cpuMult;
950uint64_t divisor = 0;
951uint64_t did;
952uint64_t fid;
953
954cofvid = rdmsr64(K10_COFVID_STATUS);
955did = bitfield(cofvid, 8, 6);
956fid = bitfield(cofvid, 5, 0);
957if (did == 0) divisor = 2;
958else if (did == 1) divisor = 4;
959else if (did == 2) divisor = 8;
960else if (did == 3) divisor = 16;
961else if (did == 4) divisor = 32;
962
963cpuMult = (fid + 16) / divisor;
964currcoef = cpuMult;
965
966cpuMultN2 = (cofvid & (uint64_t)bit(0));
967currdiv = cpuMultN2;
968}
969break;
970
971case 0x16: /*** AMD Family 16h kabini ***/
972{
973uint64_t cofvid = 0;
974uint64_t cpuMult;
975uint64_t divisor = 0;
976uint64_t did;
977uint64_t fid;
978
979cofvid = rdmsr64(K10_COFVID_STATUS);
980did = bitfield(cofvid, 8, 6);
981fid = bitfield(cofvid, 5, 0);
982if (did == 0) divisor = 1;
983else if (did == 1) divisor = 2;
984else if (did == 2) divisor = 4;
985else if (did == 3) divisor = 8;
986else if (did == 4) divisor = 16;
987
988cpuMult = (fid + 16) / divisor;
989currcoef = cpuMult;
990
991cpuMultN2 = (cofvid & (uint64_t)bit(0));
992currdiv = cpuMultN2;
993/****** Addon END ******/
994}
995break;
996
997default:
998{
999typedef unsigned long long vlong;
1000uint64_t prfsts;
1001prfsts = rdmsr64(K10_COFVID_STATUS);
1002uint64_t r;
1003vlong hz;
1004r = (prfsts>>6) & 0x07;
1005hz = (((prfsts & 0x3f)+0x10)*100000000ll)/(1<<r);
1006
1007currcoef = hz / (200 * Mega);
1008}
1009}
1010
1011if (currcoef)
1012{
1013if (currdiv)
1014{
1015busFrequency = ((tscFreq * 2) / ((currcoef * 2) + 1));
1016busFCvtt2n = ((1 * Giga) << 32) / busFrequency;
1017tscFCvtt2n = busFCvtt2n * 2 / (1 + (2 * currcoef));
1018cpuFrequency = ((1 * Giga) << 32) / tscFCvtt2n;
1019
1020DBG("%d.%d\n", currcoef / currdiv, ((currcoef % currdiv) * 100) / currdiv);
1021}
1022else
1023{
1024busFrequency = (tscFreq / currcoef);
1025busFCvtt2n = ((1 * Giga) << 32) / busFrequency;
1026tscFCvtt2n = busFCvtt2n / currcoef;
1027cpuFrequency = ((1 * Giga) << 32) / tscFCvtt2n;
1028DBG("%d\n", currcoef);
1029}
1030}
1031else if (!cpuFrequency)
1032{
1033cpuFrequency = tscFreq;
1034}
1035}
1036
1037#if 0
1038if (!busFrequency)
1039{
1040busFrequency = (DEFAULT_FSB * 1000);
1041DBG("\tCPU: busFrequency = 0! using the default value for FSB!\n");
1042cpuFrequency = tscFreq;
1043}
1044
1045DBG("\tcpu freq = 0x%016llxn", timeRDTSC() * 20);
1046
1047#endif
1048
1049outb(0x21U, pic0_mask); // restore PIC0 interrupts
1050
1051p->CPU.MaxCoef = maxcoef = currcoef;
1052p->CPU.MaxDiv = maxdiv = currdiv;
1053p->CPU.CurrCoef = currcoef;
1054p->CPU.CurrDiv = currdiv;
1055p->CPU.TSCFrequency = tscFreq;
1056p->CPU.FSBFrequency = busFrequency;
1057p->CPU.CPUFrequency = cpuFrequency;
1058
1059// keep formatted with spaces instead of tabs
1060
1061DBG("\tCPUID Raw Values:\n");
1062for (i = 0; i < CPUID_MAX; i++)
1063{
1064DBG("\t%02d: %08X-%08X-%08X-%08X\n", i, p->CPU.CPUID[i][eax], p->CPU.CPUID[i][ebx], p->CPU.CPUID[i][ecx], p->CPU.CPUID[i][edx]);
1065}
1066DBG("\n");
1067DBG("\tBrand String: %s\n",p->CPU.BrandString);// Processor name (BIOS)
1068DBG("\tVendor: 0x%X\n",p->CPU.Vendor);// Vendor ex: GenuineIntel
1069DBG("\tFamily: 0x%X\n",p->CPU.Family);// Family ex: 6 (06h)
1070DBG("\tExtFamily: 0x%X\n",p->CPU.ExtFamily);
1071DBG("\tSignature: 0x%08X\n",p->CPU.Signature);// CPUID signature
1072/*switch (p->CPU.Type) {
1073case PT_OEM:
1074DBG("\tProcessor type: Intel Original OEM Processor\n");
1075break;
1076case PT_OD:
1077DBG("\tProcessor type: Intel Over Drive Processor\n");
1078break;
1079case PT_DUAL:
1080DBG("\tProcessor type: Intel Dual Processor\n");
1081break;
1082case PT_RES:
1083DBG("\tProcessor type: Intel Reserved\n");
1084break;
1085default:
1086break;
1087}*/
1088DBG("\tModel: 0x%X\n",p->CPU.Model);// Model ex: 37 (025h)
1089DBG("\tExtModel: 0x%X\n",p->CPU.ExtModel);
1090DBG("\tStepping: 0x%X\n",p->CPU.Stepping);// Stepping ex: 5 (05h)
1091DBG("\tMaxCoef: %d\n",p->CPU.MaxCoef);
1092DBG("\tCurrCoef: %d\n",p->CPU.CurrCoef);
1093DBG("\tMaxDiv: %d\n",p->CPU.MaxDiv);
1094DBG("\tCurrDiv: %d\n",p->CPU.CurrDiv);
1095DBG("\tTSCFreq: %dMHz\n",p->CPU.TSCFrequency / 1000000);
1096DBG("\tFSBFreq: %dMHz\n",(p->CPU.FSBFrequency + 500000) / 1000000);
1097DBG("\tCPUFreq: %dMHz\n",p->CPU.CPUFrequency / 1000000);
1098DBG("\tCores: %d\n",p->CPU.NoCores);// Cores
1099DBG("\tLogical processor: %d\n",p->CPU.NoThreads);// Logical procesor
1100DBG("\tFeatures: 0x%08x\n",p->CPU.Features);
1101//DBG("\tMicrocode version: %d\n",p->CPU.MCodeVersion);// CPU microcode version
1102
1103verbose("\n");
1104#if DEBUG_CPU
1105pause();
1106#endif
1107}
1108

Archive Download this file

Revision: 2789