OSDN Git Service

tools/power turbostat: fix -S on UP systems
[sagit-ice-cold/kernel_xiaomi_msm8998.git] / tools / power / x86 / turbostat / turbostat.c
1 /*
2  * turbostat -- show CPU frequency and C-state residency
3  * on modern Intel turbo-capable processors.
4  *
5  * Copyright (c) 2013 Intel Corporation.
6  * Len Brown <len.brown@intel.com>
7  *
8  * This program is free software; you can redistribute it and/or modify it
9  * under the terms and conditions of the GNU General Public License,
10  * version 2, as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
15  * more details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21
22 #define _GNU_SOURCE
23 #include MSRHEADER
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <err.h>
27 #include <unistd.h>
28 #include <sys/types.h>
29 #include <sys/wait.h>
30 #include <sys/stat.h>
31 #include <sys/resource.h>
32 #include <fcntl.h>
33 #include <signal.h>
34 #include <sys/time.h>
35 #include <stdlib.h>
36 #include <getopt.h>
37 #include <dirent.h>
38 #include <string.h>
39 #include <ctype.h>
40 #include <sched.h>
41 #include <cpuid.h>
42 #include <linux/capability.h>
43 #include <errno.h>
44
45 char *proc_stat = "/proc/stat";
46 unsigned int interval_sec = 5;
47 unsigned int debug;
48 unsigned int rapl_joules;
49 unsigned int summary_only;
50 unsigned int dump_only;
51 unsigned int skip_c0;
52 unsigned int skip_c1;
53 unsigned int do_nhm_cstates;
54 unsigned int do_snb_cstates;
55 unsigned int do_knl_cstates;
56 unsigned int do_pc2;
57 unsigned int do_pc3;
58 unsigned int do_pc6;
59 unsigned int do_pc7;
60 unsigned int do_c8_c9_c10;
61 unsigned int do_skl_residency;
62 unsigned int do_slm_cstates;
63 unsigned int use_c1_residency_msr;
64 unsigned int has_aperf;
65 unsigned int has_epb;
66 unsigned int units = 1000000;   /* MHz etc */
67 unsigned int genuine_intel;
68 unsigned int has_invariant_tsc;
69 unsigned int do_nhm_platform_info;
70 unsigned int extra_msr_offset32;
71 unsigned int extra_msr_offset64;
72 unsigned int extra_delta_offset32;
73 unsigned int extra_delta_offset64;
74 unsigned int aperf_mperf_multiplier = 1;
75 int do_smi;
76 double bclk;
77 double base_hz;
78 unsigned int has_base_hz;
79 double tsc_tweak = 1.0;
80 unsigned int show_pkg;
81 unsigned int show_core;
82 unsigned int show_cpu;
83 unsigned int show_pkg_only;
84 unsigned int show_core_only;
85 char *output_buffer, *outp;
86 unsigned int do_rapl;
87 unsigned int do_dts;
88 unsigned int do_ptm;
89 unsigned int tcc_activation_temp;
90 unsigned int tcc_activation_temp_override;
91 double rapl_power_units, rapl_time_units;
92 double rapl_dram_energy_units, rapl_energy_units;
93 double rapl_joule_counter_range;
94 unsigned int do_core_perf_limit_reasons;
95 unsigned int do_gfx_perf_limit_reasons;
96 unsigned int do_ring_perf_limit_reasons;
97 unsigned int crystal_hz;
98 unsigned long long tsc_hz;
99 int base_cpu;
100 double discover_bclk(unsigned int family, unsigned int model);
101
102 #define RAPL_PKG                (1 << 0)
103                                         /* 0x610 MSR_PKG_POWER_LIMIT */
104                                         /* 0x611 MSR_PKG_ENERGY_STATUS */
105 #define RAPL_PKG_PERF_STATUS    (1 << 1)
106                                         /* 0x613 MSR_PKG_PERF_STATUS */
107 #define RAPL_PKG_POWER_INFO     (1 << 2)
108                                         /* 0x614 MSR_PKG_POWER_INFO */
109
110 #define RAPL_DRAM               (1 << 3)
111                                         /* 0x618 MSR_DRAM_POWER_LIMIT */
112                                         /* 0x619 MSR_DRAM_ENERGY_STATUS */
113 #define RAPL_DRAM_PERF_STATUS   (1 << 4)
114                                         /* 0x61b MSR_DRAM_PERF_STATUS */
115 #define RAPL_DRAM_POWER_INFO    (1 << 5)
116                                         /* 0x61c MSR_DRAM_POWER_INFO */
117
118 #define RAPL_CORES              (1 << 6)
119                                         /* 0x638 MSR_PP0_POWER_LIMIT */
120                                         /* 0x639 MSR_PP0_ENERGY_STATUS */
121 #define RAPL_CORE_POLICY        (1 << 7)
122                                         /* 0x63a MSR_PP0_POLICY */
123
124 #define RAPL_GFX                (1 << 8)
125                                         /* 0x640 MSR_PP1_POWER_LIMIT */
126                                         /* 0x641 MSR_PP1_ENERGY_STATUS */
127                                         /* 0x642 MSR_PP1_POLICY */
128 #define TJMAX_DEFAULT   100
129
130 #define MAX(a, b) ((a) > (b) ? (a) : (b))
131
132 int aperf_mperf_unstable;
133 int backwards_count;
134 char *progname;
135
136 cpu_set_t *cpu_present_set, *cpu_affinity_set;
137 size_t cpu_present_setsize, cpu_affinity_setsize;
138
139 struct thread_data {
140         unsigned long long tsc;
141         unsigned long long aperf;
142         unsigned long long mperf;
143         unsigned long long c1;
144         unsigned long long extra_msr64;
145         unsigned long long extra_delta64;
146         unsigned long long extra_msr32;
147         unsigned long long extra_delta32;
148         unsigned int smi_count;
149         unsigned int cpu_id;
150         unsigned int flags;
151 #define CPU_IS_FIRST_THREAD_IN_CORE     0x2
152 #define CPU_IS_FIRST_CORE_IN_PACKAGE    0x4
153 } *thread_even, *thread_odd;
154
155 struct core_data {
156         unsigned long long c3;
157         unsigned long long c6;
158         unsigned long long c7;
159         unsigned int core_temp_c;
160         unsigned int core_id;
161 } *core_even, *core_odd;
162
163 struct pkg_data {
164         unsigned long long pc2;
165         unsigned long long pc3;
166         unsigned long long pc6;
167         unsigned long long pc7;
168         unsigned long long pc8;
169         unsigned long long pc9;
170         unsigned long long pc10;
171         unsigned long long pkg_wtd_core_c0;
172         unsigned long long pkg_any_core_c0;
173         unsigned long long pkg_any_gfxe_c0;
174         unsigned long long pkg_both_core_gfxe_c0;
175         unsigned int package_id;
176         unsigned int energy_pkg;        /* MSR_PKG_ENERGY_STATUS */
177         unsigned int energy_dram;       /* MSR_DRAM_ENERGY_STATUS */
178         unsigned int energy_cores;      /* MSR_PP0_ENERGY_STATUS */
179         unsigned int energy_gfx;        /* MSR_PP1_ENERGY_STATUS */
180         unsigned int rapl_pkg_perf_status;      /* MSR_PKG_PERF_STATUS */
181         unsigned int rapl_dram_perf_status;     /* MSR_DRAM_PERF_STATUS */
182         unsigned int pkg_temp_c;
183
184 } *package_even, *package_odd;
185
186 #define ODD_COUNTERS thread_odd, core_odd, package_odd
187 #define EVEN_COUNTERS thread_even, core_even, package_even
188
189 #define GET_THREAD(thread_base, thread_no, core_no, pkg_no) \
190         (thread_base + (pkg_no) * topo.num_cores_per_pkg * \
191                 topo.num_threads_per_core + \
192                 (core_no) * topo.num_threads_per_core + (thread_no))
193 #define GET_CORE(core_base, core_no, pkg_no) \
194         (core_base + (pkg_no) * topo.num_cores_per_pkg + (core_no))
195 #define GET_PKG(pkg_base, pkg_no) (pkg_base + pkg_no)
196
197 struct system_summary {
198         struct thread_data threads;
199         struct core_data cores;
200         struct pkg_data packages;
201 } sum, average;
202
203
204 struct topo_params {
205         int num_packages;
206         int num_cpus;
207         int num_cores;
208         int max_cpu_num;
209         int num_cores_per_pkg;
210         int num_threads_per_core;
211 } topo;
212
213 struct timeval tv_even, tv_odd, tv_delta;
214
215 void setup_all_buffers(void);
216
217 int cpu_is_not_present(int cpu)
218 {
219         return !CPU_ISSET_S(cpu, cpu_present_setsize, cpu_present_set);
220 }
221 /*
222  * run func(thread, core, package) in topology order
223  * skip non-present cpus
224  */
225
226 int for_all_cpus(int (func)(struct thread_data *, struct core_data *, struct pkg_data *),
227         struct thread_data *thread_base, struct core_data *core_base, struct pkg_data *pkg_base)
228 {
229         int retval, pkg_no, core_no, thread_no;
230
231         for (pkg_no = 0; pkg_no < topo.num_packages; ++pkg_no) {
232                 for (core_no = 0; core_no < topo.num_cores_per_pkg; ++core_no) {
233                         for (thread_no = 0; thread_no <
234                                 topo.num_threads_per_core; ++thread_no) {
235                                 struct thread_data *t;
236                                 struct core_data *c;
237                                 struct pkg_data *p;
238
239                                 t = GET_THREAD(thread_base, thread_no, core_no, pkg_no);
240
241                                 if (cpu_is_not_present(t->cpu_id))
242                                         continue;
243
244                                 c = GET_CORE(core_base, core_no, pkg_no);
245                                 p = GET_PKG(pkg_base, pkg_no);
246
247                                 retval = func(t, c, p);
248                                 if (retval)
249                                         return retval;
250                         }
251                 }
252         }
253         return 0;
254 }
255
256 int cpu_migrate(int cpu)
257 {
258         CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
259         CPU_SET_S(cpu, cpu_affinity_setsize, cpu_affinity_set);
260         if (sched_setaffinity(0, cpu_affinity_setsize, cpu_affinity_set) == -1)
261                 return -1;
262         else
263                 return 0;
264 }
265
266 int get_msr(int cpu, off_t offset, unsigned long long *msr)
267 {
268         ssize_t retval;
269         char pathname[32];
270         int fd;
271
272         sprintf(pathname, "/dev/cpu/%d/msr", cpu);
273         fd = open(pathname, O_RDONLY);
274         if (fd < 0)
275                 err(-1, "%s open failed, try chown or chmod +r /dev/cpu/*/msr, or run as root", pathname);
276
277         retval = pread(fd, msr, sizeof *msr, offset);
278         close(fd);
279
280         if (retval != sizeof *msr)
281                 err(-1, "%s offset 0x%llx read failed", pathname, (unsigned long long)offset);
282
283         return 0;
284 }
285
286 /*
287  * Example Format w/ field column widths:
288  *
289  *  Package    Core     CPU Avg_MHz Bzy_MHz TSC_MHz     SMI   %Busy CPU_%c1 CPU_%c3 CPU_%c6 CPU_%c7 CoreTmp  PkgTmp Pkg%pc2 Pkg%pc3 Pkg%pc6 Pkg%pc7 PkgWatt CorWatt GFXWatt
290  * 123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678
291  */
292
293 void print_header(void)
294 {
295         if (show_pkg)
296                 outp += sprintf(outp, " Package");
297         if (show_core)
298                 outp += sprintf(outp, "    Core");
299         if (show_cpu)
300                 outp += sprintf(outp, "     CPU");
301         if (has_aperf)
302                 outp += sprintf(outp, " Avg_MHz");
303         if (has_aperf)
304                 outp += sprintf(outp, "   %%Busy");
305         if (has_aperf)
306                 outp += sprintf(outp, " Bzy_MHz");
307         outp += sprintf(outp, " TSC_MHz");
308
309         if (extra_delta_offset32)
310                 outp += sprintf(outp, "  count 0x%03X", extra_delta_offset32);
311         if (extra_delta_offset64)
312                 outp += sprintf(outp, "  COUNT 0x%03X", extra_delta_offset64);
313         if (extra_msr_offset32)
314                 outp += sprintf(outp, "   MSR 0x%03X", extra_msr_offset32);
315         if (extra_msr_offset64)
316                 outp += sprintf(outp, "           MSR 0x%03X", extra_msr_offset64);
317
318         if (!debug)
319                 goto done;
320
321         if (do_smi)
322                 outp += sprintf(outp, "     SMI");
323
324         if (do_nhm_cstates)
325                 outp += sprintf(outp, "  CPU%%c1");
326         if (do_nhm_cstates && !do_slm_cstates && !do_knl_cstates)
327                 outp += sprintf(outp, "  CPU%%c3");
328         if (do_nhm_cstates)
329                 outp += sprintf(outp, "  CPU%%c6");
330         if (do_snb_cstates)
331                 outp += sprintf(outp, "  CPU%%c7");
332
333         if (do_dts)
334                 outp += sprintf(outp, " CoreTmp");
335         if (do_ptm)
336                 outp += sprintf(outp, "  PkgTmp");
337
338         if (do_skl_residency) {
339                 outp += sprintf(outp, " Totl%%C0");
340                 outp += sprintf(outp, "  Any%%C0");
341                 outp += sprintf(outp, "  GFX%%C0");
342                 outp += sprintf(outp, " CPUGFX%%");
343         }
344
345         if (do_pc2)
346                 outp += sprintf(outp, " Pkg%%pc2");
347         if (do_pc3)
348                 outp += sprintf(outp, " Pkg%%pc3");
349         if (do_pc6)
350                 outp += sprintf(outp, " Pkg%%pc6");
351         if (do_pc7)
352                 outp += sprintf(outp, " Pkg%%pc7");
353         if (do_c8_c9_c10) {
354                 outp += sprintf(outp, " Pkg%%pc8");
355                 outp += sprintf(outp, " Pkg%%pc9");
356                 outp += sprintf(outp, " Pk%%pc10");
357         }
358
359         if (do_rapl && !rapl_joules) {
360                 if (do_rapl & RAPL_PKG)
361                         outp += sprintf(outp, " PkgWatt");
362                 if (do_rapl & RAPL_CORES)
363                         outp += sprintf(outp, " CorWatt");
364                 if (do_rapl & RAPL_GFX)
365                         outp += sprintf(outp, " GFXWatt");
366                 if (do_rapl & RAPL_DRAM)
367                         outp += sprintf(outp, " RAMWatt");
368                 if (do_rapl & RAPL_PKG_PERF_STATUS)
369                         outp += sprintf(outp, "   PKG_%%");
370                 if (do_rapl & RAPL_DRAM_PERF_STATUS)
371                         outp += sprintf(outp, "   RAM_%%");
372         } else if (do_rapl && rapl_joules) {
373                 if (do_rapl & RAPL_PKG)
374                         outp += sprintf(outp, "   Pkg_J");
375                 if (do_rapl & RAPL_CORES)
376                         outp += sprintf(outp, "   Cor_J");
377                 if (do_rapl & RAPL_GFX)
378                         outp += sprintf(outp, "   GFX_J");
379                 if (do_rapl & RAPL_DRAM)
380                         outp += sprintf(outp, "   RAM_J");
381                 if (do_rapl & RAPL_PKG_PERF_STATUS)
382                         outp += sprintf(outp, "   PKG_%%");
383                 if (do_rapl & RAPL_DRAM_PERF_STATUS)
384                         outp += sprintf(outp, "   RAM_%%");
385                 outp += sprintf(outp, "   time");
386
387         }
388     done:
389         outp += sprintf(outp, "\n");
390 }
391
392 int dump_counters(struct thread_data *t, struct core_data *c,
393         struct pkg_data *p)
394 {
395         outp += sprintf(outp, "t %p, c %p, p %p\n", t, c, p);
396
397         if (t) {
398                 outp += sprintf(outp, "CPU: %d flags 0x%x\n",
399                         t->cpu_id, t->flags);
400                 outp += sprintf(outp, "TSC: %016llX\n", t->tsc);
401                 outp += sprintf(outp, "aperf: %016llX\n", t->aperf);
402                 outp += sprintf(outp, "mperf: %016llX\n", t->mperf);
403                 outp += sprintf(outp, "c1: %016llX\n", t->c1);
404                 outp += sprintf(outp, "msr0x%x: %08llX\n",
405                         extra_delta_offset32, t->extra_delta32);
406                 outp += sprintf(outp, "msr0x%x: %016llX\n",
407                         extra_delta_offset64, t->extra_delta64);
408                 outp += sprintf(outp, "msr0x%x: %08llX\n",
409                         extra_msr_offset32, t->extra_msr32);
410                 outp += sprintf(outp, "msr0x%x: %016llX\n",
411                         extra_msr_offset64, t->extra_msr64);
412                 if (do_smi)
413                         outp += sprintf(outp, "SMI: %08X\n", t->smi_count);
414         }
415
416         if (c) {
417                 outp += sprintf(outp, "core: %d\n", c->core_id);
418                 outp += sprintf(outp, "c3: %016llX\n", c->c3);
419                 outp += sprintf(outp, "c6: %016llX\n", c->c6);
420                 outp += sprintf(outp, "c7: %016llX\n", c->c7);
421                 outp += sprintf(outp, "DTS: %dC\n", c->core_temp_c);
422         }
423
424         if (p) {
425                 outp += sprintf(outp, "package: %d\n", p->package_id);
426
427                 outp += sprintf(outp, "Weighted cores: %016llX\n", p->pkg_wtd_core_c0);
428                 outp += sprintf(outp, "Any cores: %016llX\n", p->pkg_any_core_c0);
429                 outp += sprintf(outp, "Any GFX: %016llX\n", p->pkg_any_gfxe_c0);
430                 outp += sprintf(outp, "CPU + GFX: %016llX\n", p->pkg_both_core_gfxe_c0);
431
432                 outp += sprintf(outp, "pc2: %016llX\n", p->pc2);
433                 if (do_pc3)
434                         outp += sprintf(outp, "pc3: %016llX\n", p->pc3);
435                 if (do_pc6)
436                         outp += sprintf(outp, "pc6: %016llX\n", p->pc6);
437                 if (do_pc7)
438                         outp += sprintf(outp, "pc7: %016llX\n", p->pc7);
439                 outp += sprintf(outp, "pc8: %016llX\n", p->pc8);
440                 outp += sprintf(outp, "pc9: %016llX\n", p->pc9);
441                 outp += sprintf(outp, "pc10: %016llX\n", p->pc10);
442                 outp += sprintf(outp, "Joules PKG: %0X\n", p->energy_pkg);
443                 outp += sprintf(outp, "Joules COR: %0X\n", p->energy_cores);
444                 outp += sprintf(outp, "Joules GFX: %0X\n", p->energy_gfx);
445                 outp += sprintf(outp, "Joules RAM: %0X\n", p->energy_dram);
446                 outp += sprintf(outp, "Throttle PKG: %0X\n",
447                         p->rapl_pkg_perf_status);
448                 outp += sprintf(outp, "Throttle RAM: %0X\n",
449                         p->rapl_dram_perf_status);
450                 outp += sprintf(outp, "PTM: %dC\n", p->pkg_temp_c);
451         }
452
453         outp += sprintf(outp, "\n");
454
455         return 0;
456 }
457
458 /*
459  * column formatting convention & formats
460  */
461 int format_counters(struct thread_data *t, struct core_data *c,
462         struct pkg_data *p)
463 {
464         double interval_float;
465         char *fmt8;
466
467          /* if showing only 1st thread in core and this isn't one, bail out */
468         if (show_core_only && !(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
469                 return 0;
470
471          /* if showing only 1st thread in pkg and this isn't one, bail out */
472         if (show_pkg_only && !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
473                 return 0;
474
475         interval_float = tv_delta.tv_sec + tv_delta.tv_usec/1000000.0;
476
477         /* topo columns, print blanks on 1st (average) line */
478         if (t == &average.threads) {
479                 if (show_pkg)
480                         outp += sprintf(outp, "       -");
481                 if (show_core)
482                         outp += sprintf(outp, "       -");
483                 if (show_cpu)
484                         outp += sprintf(outp, "       -");
485         } else {
486                 if (show_pkg) {
487                         if (p)
488                                 outp += sprintf(outp, "%8d", p->package_id);
489                         else
490                                 outp += sprintf(outp, "       -");
491                 }
492                 if (show_core) {
493                         if (c)
494                                 outp += sprintf(outp, "%8d", c->core_id);
495                         else
496                                 outp += sprintf(outp, "       -");
497                 }
498                 if (show_cpu)
499                         outp += sprintf(outp, "%8d", t->cpu_id);
500         }
501
502         /* Avg_MHz */
503         if (has_aperf)
504                 outp += sprintf(outp, "%8.0f",
505                         1.0 / units * t->aperf / interval_float);
506
507         /* %Busy */
508         if (has_aperf) {
509                 if (!skip_c0)
510                         outp += sprintf(outp, "%8.2f", 100.0 * t->mperf/t->tsc/tsc_tweak);
511                 else
512                         outp += sprintf(outp, "********");
513         }
514
515         /* Bzy_MHz */
516         if (has_aperf) {
517                 if (has_base_hz)
518                         outp += sprintf(outp, "%8.0f", base_hz / units * t->aperf / t->mperf);
519                 else
520                         outp += sprintf(outp, "%8.0f",
521                                 1.0 * t->tsc / units * t->aperf / t->mperf / interval_float);
522         }
523
524         /* TSC_MHz */
525         outp += sprintf(outp, "%8.0f", 1.0 * t->tsc/units/interval_float);
526
527         /* delta */
528         if (extra_delta_offset32)
529                 outp += sprintf(outp, "  %11llu", t->extra_delta32);
530
531         /* DELTA */
532         if (extra_delta_offset64)
533                 outp += sprintf(outp, "  %11llu", t->extra_delta64);
534         /* msr */
535         if (extra_msr_offset32)
536                 outp += sprintf(outp, "  0x%08llx", t->extra_msr32);
537
538         /* MSR */
539         if (extra_msr_offset64)
540                 outp += sprintf(outp, "  0x%016llx", t->extra_msr64);
541
542         if (!debug)
543                 goto done;
544
545         /* SMI */
546         if (do_smi)
547                 outp += sprintf(outp, "%8d", t->smi_count);
548
549         if (do_nhm_cstates) {
550                 if (!skip_c1)
551                         outp += sprintf(outp, "%8.2f", 100.0 * t->c1/t->tsc);
552                 else
553                         outp += sprintf(outp, "********");
554         }
555
556         /* print per-core data only for 1st thread in core */
557         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
558                 goto done;
559
560         if (do_nhm_cstates && !do_slm_cstates && !do_knl_cstates)
561                 outp += sprintf(outp, "%8.2f", 100.0 * c->c3/t->tsc);
562         if (do_nhm_cstates)
563                 outp += sprintf(outp, "%8.2f", 100.0 * c->c6/t->tsc);
564         if (do_snb_cstates)
565                 outp += sprintf(outp, "%8.2f", 100.0 * c->c7/t->tsc);
566
567         if (do_dts)
568                 outp += sprintf(outp, "%8d", c->core_temp_c);
569
570         /* print per-package data only for 1st core in package */
571         if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
572                 goto done;
573
574         /* PkgTmp */
575         if (do_ptm)
576                 outp += sprintf(outp, "%8d", p->pkg_temp_c);
577
578         /* Totl%C0, Any%C0 GFX%C0 CPUGFX% */
579         if (do_skl_residency) {
580                 outp += sprintf(outp, "%8.2f", 100.0 * p->pkg_wtd_core_c0/t->tsc);
581                 outp += sprintf(outp, "%8.2f", 100.0 * p->pkg_any_core_c0/t->tsc);
582                 outp += sprintf(outp, "%8.2f", 100.0 * p->pkg_any_gfxe_c0/t->tsc);
583                 outp += sprintf(outp, "%8.2f", 100.0 * p->pkg_both_core_gfxe_c0/t->tsc);
584         }
585
586         if (do_pc2)
587                 outp += sprintf(outp, "%8.2f", 100.0 * p->pc2/t->tsc);
588         if (do_pc3)
589                 outp += sprintf(outp, "%8.2f", 100.0 * p->pc3/t->tsc);
590         if (do_pc6)
591                 outp += sprintf(outp, "%8.2f", 100.0 * p->pc6/t->tsc);
592         if (do_pc7)
593                 outp += sprintf(outp, "%8.2f", 100.0 * p->pc7/t->tsc);
594         if (do_c8_c9_c10) {
595                 outp += sprintf(outp, "%8.2f", 100.0 * p->pc8/t->tsc);
596                 outp += sprintf(outp, "%8.2f", 100.0 * p->pc9/t->tsc);
597                 outp += sprintf(outp, "%8.2f", 100.0 * p->pc10/t->tsc);
598         }
599
600         /*
601          * If measurement interval exceeds minimum RAPL Joule Counter range,
602          * indicate that results are suspect by printing "**" in fraction place.
603          */
604         if (interval_float < rapl_joule_counter_range)
605                 fmt8 = "%8.2f";
606         else
607                 fmt8 = " %6.0f**";
608
609         if (do_rapl && !rapl_joules) {
610                 if (do_rapl & RAPL_PKG)
611                         outp += sprintf(outp, fmt8, p->energy_pkg * rapl_energy_units / interval_float);
612                 if (do_rapl & RAPL_CORES)
613                         outp += sprintf(outp, fmt8, p->energy_cores * rapl_energy_units / interval_float);
614                 if (do_rapl & RAPL_GFX)
615                         outp += sprintf(outp, fmt8, p->energy_gfx * rapl_energy_units / interval_float);
616                 if (do_rapl & RAPL_DRAM)
617                         outp += sprintf(outp, fmt8, p->energy_dram * rapl_dram_energy_units / interval_float);
618                 if (do_rapl & RAPL_PKG_PERF_STATUS)
619                         outp += sprintf(outp, fmt8, 100.0 * p->rapl_pkg_perf_status * rapl_time_units / interval_float);
620                 if (do_rapl & RAPL_DRAM_PERF_STATUS)
621                         outp += sprintf(outp, fmt8, 100.0 * p->rapl_dram_perf_status * rapl_time_units / interval_float);
622         } else if (do_rapl && rapl_joules) {
623                 if (do_rapl & RAPL_PKG)
624                         outp += sprintf(outp, fmt8,
625                                         p->energy_pkg * rapl_energy_units);
626                 if (do_rapl & RAPL_CORES)
627                         outp += sprintf(outp, fmt8,
628                                         p->energy_cores * rapl_energy_units);
629                 if (do_rapl & RAPL_GFX)
630                         outp += sprintf(outp, fmt8,
631                                         p->energy_gfx * rapl_energy_units);
632                 if (do_rapl & RAPL_DRAM)
633                         outp += sprintf(outp, fmt8,
634                                         p->energy_dram * rapl_dram_energy_units);
635                 if (do_rapl & RAPL_PKG_PERF_STATUS)
636                         outp += sprintf(outp, fmt8, 100.0 * p->rapl_pkg_perf_status * rapl_time_units / interval_float);
637                 if (do_rapl & RAPL_DRAM_PERF_STATUS)
638                         outp += sprintf(outp, fmt8, 100.0 * p->rapl_dram_perf_status * rapl_time_units / interval_float);
639
640                 outp += sprintf(outp, fmt8, interval_float);
641         }
642 done:
643         outp += sprintf(outp, "\n");
644
645         return 0;
646 }
647
648 void flush_stdout()
649 {
650         fputs(output_buffer, stdout);
651         fflush(stdout);
652         outp = output_buffer;
653 }
654 void flush_stderr()
655 {
656         fputs(output_buffer, stderr);
657         outp = output_buffer;
658 }
659 void format_all_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
660 {
661         static int printed;
662
663         if (!printed || !summary_only)
664                 print_header();
665
666         format_counters(&average.threads, &average.cores, &average.packages);
667
668         printed = 1;
669
670         if (summary_only)
671                 return;
672
673         for_all_cpus(format_counters, t, c, p);
674 }
675
676 #define DELTA_WRAP32(new, old)                  \
677         if (new > old) {                        \
678                 old = new - old;                \
679         } else {                                \
680                 old = 0x100000000 + new - old;  \
681         }
682
683 void
684 delta_package(struct pkg_data *new, struct pkg_data *old)
685 {
686
687         if (do_skl_residency) {
688                 old->pkg_wtd_core_c0 = new->pkg_wtd_core_c0 - old->pkg_wtd_core_c0;
689                 old->pkg_any_core_c0 = new->pkg_any_core_c0 - old->pkg_any_core_c0;
690                 old->pkg_any_gfxe_c0 = new->pkg_any_gfxe_c0 - old->pkg_any_gfxe_c0;
691                 old->pkg_both_core_gfxe_c0 = new->pkg_both_core_gfxe_c0 - old->pkg_both_core_gfxe_c0;
692         }
693         old->pc2 = new->pc2 - old->pc2;
694         if (do_pc3)
695                 old->pc3 = new->pc3 - old->pc3;
696         if (do_pc6)
697                 old->pc6 = new->pc6 - old->pc6;
698         if (do_pc7)
699                 old->pc7 = new->pc7 - old->pc7;
700         old->pc8 = new->pc8 - old->pc8;
701         old->pc9 = new->pc9 - old->pc9;
702         old->pc10 = new->pc10 - old->pc10;
703         old->pkg_temp_c = new->pkg_temp_c;
704
705         DELTA_WRAP32(new->energy_pkg, old->energy_pkg);
706         DELTA_WRAP32(new->energy_cores, old->energy_cores);
707         DELTA_WRAP32(new->energy_gfx, old->energy_gfx);
708         DELTA_WRAP32(new->energy_dram, old->energy_dram);
709         DELTA_WRAP32(new->rapl_pkg_perf_status, old->rapl_pkg_perf_status);
710         DELTA_WRAP32(new->rapl_dram_perf_status, old->rapl_dram_perf_status);
711 }
712
713 void
714 delta_core(struct core_data *new, struct core_data *old)
715 {
716         old->c3 = new->c3 - old->c3;
717         old->c6 = new->c6 - old->c6;
718         old->c7 = new->c7 - old->c7;
719         old->core_temp_c = new->core_temp_c;
720 }
721
722 /*
723  * old = new - old
724  */
725 void
726 delta_thread(struct thread_data *new, struct thread_data *old,
727         struct core_data *core_delta)
728 {
729         old->tsc = new->tsc - old->tsc;
730
731         /* check for TSC < 1 Mcycles over interval */
732         if (old->tsc < (1000 * 1000))
733                 errx(-3, "Insanely slow TSC rate, TSC stops in idle?\n"
734                      "You can disable all c-states by booting with \"idle=poll\"\n"
735                      "or just the deep ones with \"processor.max_cstate=1\"");
736
737         old->c1 = new->c1 - old->c1;
738
739         if (has_aperf) {
740                 if ((new->aperf > old->aperf) && (new->mperf > old->mperf)) {
741                         old->aperf = new->aperf - old->aperf;
742                         old->mperf = new->mperf - old->mperf;
743                 } else {
744
745                         if (!aperf_mperf_unstable) {
746                                 fprintf(stderr, "%s: APERF or MPERF went backwards *\n", progname);
747                                 fprintf(stderr, "* Frequency results do not cover entire interval *\n");
748                                 fprintf(stderr, "* fix this by running Linux-2.6.30 or later *\n");
749
750                                 aperf_mperf_unstable = 1;
751                         }
752                         /*
753                          * mperf delta is likely a huge "positive" number
754                          * can not use it for calculating c0 time
755                          */
756                         skip_c0 = 1;
757                         skip_c1 = 1;
758                 }
759         }
760
761
762         if (use_c1_residency_msr) {
763                 /*
764                  * Some models have a dedicated C1 residency MSR,
765                  * which should be more accurate than the derivation below.
766                  */
767         } else {
768                 /*
769                  * As counter collection is not atomic,
770                  * it is possible for mperf's non-halted cycles + idle states
771                  * to exceed TSC's all cycles: show c1 = 0% in that case.
772                  */
773                 if ((old->mperf + core_delta->c3 + core_delta->c6 + core_delta->c7) > old->tsc)
774                         old->c1 = 0;
775                 else {
776                         /* normal case, derive c1 */
777                         old->c1 = old->tsc - old->mperf - core_delta->c3
778                                 - core_delta->c6 - core_delta->c7;
779                 }
780         }
781
782         if (old->mperf == 0) {
783                 if (debug > 1) fprintf(stderr, "cpu%d MPERF 0!\n", old->cpu_id);
784                 old->mperf = 1; /* divide by 0 protection */
785         }
786
787         old->extra_delta32 = new->extra_delta32 - old->extra_delta32;
788         old->extra_delta32 &= 0xFFFFFFFF;
789
790         old->extra_delta64 = new->extra_delta64 - old->extra_delta64;
791
792         /*
793          * Extra MSR is just a snapshot, simply copy latest w/o subtracting
794          */
795         old->extra_msr32 = new->extra_msr32;
796         old->extra_msr64 = new->extra_msr64;
797
798         if (do_smi)
799                 old->smi_count = new->smi_count - old->smi_count;
800 }
801
802 int delta_cpu(struct thread_data *t, struct core_data *c,
803         struct pkg_data *p, struct thread_data *t2,
804         struct core_data *c2, struct pkg_data *p2)
805 {
806         /* calculate core delta only for 1st thread in core */
807         if (t->flags & CPU_IS_FIRST_THREAD_IN_CORE)
808                 delta_core(c, c2);
809
810         /* always calculate thread delta */
811         delta_thread(t, t2, c2);        /* c2 is core delta */
812
813         /* calculate package delta only for 1st core in package */
814         if (t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE)
815                 delta_package(p, p2);
816
817         return 0;
818 }
819
820 void clear_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
821 {
822         t->tsc = 0;
823         t->aperf = 0;
824         t->mperf = 0;
825         t->c1 = 0;
826
827         t->smi_count = 0;
828         t->extra_delta32 = 0;
829         t->extra_delta64 = 0;
830
831         /* tells format_counters to dump all fields from this set */
832         t->flags = CPU_IS_FIRST_THREAD_IN_CORE | CPU_IS_FIRST_CORE_IN_PACKAGE;
833
834         c->c3 = 0;
835         c->c6 = 0;
836         c->c7 = 0;
837         c->core_temp_c = 0;
838
839         p->pkg_wtd_core_c0 = 0;
840         p->pkg_any_core_c0 = 0;
841         p->pkg_any_gfxe_c0 = 0;
842         p->pkg_both_core_gfxe_c0 = 0;
843
844         p->pc2 = 0;
845         if (do_pc3)
846                 p->pc3 = 0;
847         if (do_pc6)
848                 p->pc6 = 0;
849         if (do_pc7)
850                 p->pc7 = 0;
851         p->pc8 = 0;
852         p->pc9 = 0;
853         p->pc10 = 0;
854
855         p->energy_pkg = 0;
856         p->energy_dram = 0;
857         p->energy_cores = 0;
858         p->energy_gfx = 0;
859         p->rapl_pkg_perf_status = 0;
860         p->rapl_dram_perf_status = 0;
861         p->pkg_temp_c = 0;
862 }
863 int sum_counters(struct thread_data *t, struct core_data *c,
864         struct pkg_data *p)
865 {
866         average.threads.tsc += t->tsc;
867         average.threads.aperf += t->aperf;
868         average.threads.mperf += t->mperf;
869         average.threads.c1 += t->c1;
870
871         average.threads.extra_delta32 += t->extra_delta32;
872         average.threads.extra_delta64 += t->extra_delta64;
873
874         /* sum per-core values only for 1st thread in core */
875         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
876                 return 0;
877
878         average.cores.c3 += c->c3;
879         average.cores.c6 += c->c6;
880         average.cores.c7 += c->c7;
881
882         average.cores.core_temp_c = MAX(average.cores.core_temp_c, c->core_temp_c);
883
884         /* sum per-pkg values only for 1st core in pkg */
885         if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
886                 return 0;
887
888         if (do_skl_residency) {
889                 average.packages.pkg_wtd_core_c0 += p->pkg_wtd_core_c0;
890                 average.packages.pkg_any_core_c0 += p->pkg_any_core_c0;
891                 average.packages.pkg_any_gfxe_c0 += p->pkg_any_gfxe_c0;
892                 average.packages.pkg_both_core_gfxe_c0 += p->pkg_both_core_gfxe_c0;
893         }
894
895         average.packages.pc2 += p->pc2;
896         if (do_pc3)
897                 average.packages.pc3 += p->pc3;
898         if (do_pc6)
899                 average.packages.pc6 += p->pc6;
900         if (do_pc7)
901                 average.packages.pc7 += p->pc7;
902         average.packages.pc8 += p->pc8;
903         average.packages.pc9 += p->pc9;
904         average.packages.pc10 += p->pc10;
905
906         average.packages.energy_pkg += p->energy_pkg;
907         average.packages.energy_dram += p->energy_dram;
908         average.packages.energy_cores += p->energy_cores;
909         average.packages.energy_gfx += p->energy_gfx;
910
911         average.packages.pkg_temp_c = MAX(average.packages.pkg_temp_c, p->pkg_temp_c);
912
913         average.packages.rapl_pkg_perf_status += p->rapl_pkg_perf_status;
914         average.packages.rapl_dram_perf_status += p->rapl_dram_perf_status;
915         return 0;
916 }
917 /*
918  * sum the counters for all cpus in the system
919  * compute the weighted average
920  */
921 void compute_average(struct thread_data *t, struct core_data *c,
922         struct pkg_data *p)
923 {
924         clear_counters(&average.threads, &average.cores, &average.packages);
925
926         for_all_cpus(sum_counters, t, c, p);
927
928         average.threads.tsc /= topo.num_cpus;
929         average.threads.aperf /= topo.num_cpus;
930         average.threads.mperf /= topo.num_cpus;
931         average.threads.c1 /= topo.num_cpus;
932
933         average.threads.extra_delta32 /= topo.num_cpus;
934         average.threads.extra_delta32 &= 0xFFFFFFFF;
935
936         average.threads.extra_delta64 /= topo.num_cpus;
937
938         average.cores.c3 /= topo.num_cores;
939         average.cores.c6 /= topo.num_cores;
940         average.cores.c7 /= topo.num_cores;
941
942         if (do_skl_residency) {
943                 average.packages.pkg_wtd_core_c0 /= topo.num_packages;
944                 average.packages.pkg_any_core_c0 /= topo.num_packages;
945                 average.packages.pkg_any_gfxe_c0 /= topo.num_packages;
946                 average.packages.pkg_both_core_gfxe_c0 /= topo.num_packages;
947         }
948
949         average.packages.pc2 /= topo.num_packages;
950         if (do_pc3)
951                 average.packages.pc3 /= topo.num_packages;
952         if (do_pc6)
953                 average.packages.pc6 /= topo.num_packages;
954         if (do_pc7)
955                 average.packages.pc7 /= topo.num_packages;
956
957         average.packages.pc8 /= topo.num_packages;
958         average.packages.pc9 /= topo.num_packages;
959         average.packages.pc10 /= topo.num_packages;
960 }
961
962 static unsigned long long rdtsc(void)
963 {
964         unsigned int low, high;
965
966         asm volatile("rdtsc" : "=a" (low), "=d" (high));
967
968         return low | ((unsigned long long)high) << 32;
969 }
970
971
972 /*
973  * get_counters(...)
974  * migrate to cpu
975  * acquire and record local counters for that cpu
976  */
977 int get_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
978 {
979         int cpu = t->cpu_id;
980         unsigned long long msr;
981
982         if (cpu_migrate(cpu)) {
983                 fprintf(stderr, "Could not migrate to CPU %d\n", cpu);
984                 return -1;
985         }
986
987         t->tsc = rdtsc();       /* we are running on local CPU of interest */
988
989         if (has_aperf) {
990                 if (get_msr(cpu, MSR_IA32_APERF, &t->aperf))
991                         return -3;
992                 if (get_msr(cpu, MSR_IA32_MPERF, &t->mperf))
993                         return -4;
994                 t->aperf = t->aperf * aperf_mperf_multiplier;
995                 t->mperf = t->mperf * aperf_mperf_multiplier;
996         }
997
998         if (do_smi) {
999                 if (get_msr(cpu, MSR_SMI_COUNT, &msr))
1000                         return -5;
1001                 t->smi_count = msr & 0xFFFFFFFF;
1002         }
1003         if (extra_delta_offset32) {
1004                 if (get_msr(cpu, extra_delta_offset32, &msr))
1005                         return -5;
1006                 t->extra_delta32 = msr & 0xFFFFFFFF;
1007         }
1008
1009         if (extra_delta_offset64)
1010                 if (get_msr(cpu, extra_delta_offset64, &t->extra_delta64))
1011                         return -5;
1012
1013         if (extra_msr_offset32) {
1014                 if (get_msr(cpu, extra_msr_offset32, &msr))
1015                         return -5;
1016                 t->extra_msr32 = msr & 0xFFFFFFFF;
1017         }
1018
1019         if (extra_msr_offset64)
1020                 if (get_msr(cpu, extra_msr_offset64, &t->extra_msr64))
1021                         return -5;
1022
1023         if (use_c1_residency_msr) {
1024                 if (get_msr(cpu, MSR_CORE_C1_RES, &t->c1))
1025                         return -6;
1026         }
1027
1028         /* collect core counters only for 1st thread in core */
1029         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
1030                 return 0;
1031
1032         if (do_nhm_cstates && !do_slm_cstates && !do_knl_cstates) {
1033                 if (get_msr(cpu, MSR_CORE_C3_RESIDENCY, &c->c3))
1034                         return -6;
1035         }
1036
1037         if (do_nhm_cstates && !do_knl_cstates) {
1038                 if (get_msr(cpu, MSR_CORE_C6_RESIDENCY, &c->c6))
1039                         return -7;
1040         } else if (do_knl_cstates) {
1041                 if (get_msr(cpu, MSR_KNL_CORE_C6_RESIDENCY, &c->c6))
1042                         return -7;
1043         }
1044
1045         if (do_snb_cstates)
1046                 if (get_msr(cpu, MSR_CORE_C7_RESIDENCY, &c->c7))
1047                         return -8;
1048
1049         if (do_dts) {
1050                 if (get_msr(cpu, MSR_IA32_THERM_STATUS, &msr))
1051                         return -9;
1052                 c->core_temp_c = tcc_activation_temp - ((msr >> 16) & 0x7F);
1053         }
1054
1055
1056         /* collect package counters only for 1st core in package */
1057         if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
1058                 return 0;
1059
1060         if (do_skl_residency) {
1061                 if (get_msr(cpu, MSR_PKG_WEIGHTED_CORE_C0_RES, &p->pkg_wtd_core_c0))
1062                         return -10;
1063                 if (get_msr(cpu, MSR_PKG_ANY_CORE_C0_RES, &p->pkg_any_core_c0))
1064                         return -11;
1065                 if (get_msr(cpu, MSR_PKG_ANY_GFXE_C0_RES, &p->pkg_any_gfxe_c0))
1066                         return -12;
1067                 if (get_msr(cpu, MSR_PKG_BOTH_CORE_GFXE_C0_RES, &p->pkg_both_core_gfxe_c0))
1068                         return -13;
1069         }
1070         if (do_pc3)
1071                 if (get_msr(cpu, MSR_PKG_C3_RESIDENCY, &p->pc3))
1072                         return -9;
1073         if (do_pc6)
1074                 if (get_msr(cpu, MSR_PKG_C6_RESIDENCY, &p->pc6))
1075                         return -10;
1076         if (do_pc2)
1077                 if (get_msr(cpu, MSR_PKG_C2_RESIDENCY, &p->pc2))
1078                         return -11;
1079         if (do_pc7)
1080                 if (get_msr(cpu, MSR_PKG_C7_RESIDENCY, &p->pc7))
1081                         return -12;
1082         if (do_c8_c9_c10) {
1083                 if (get_msr(cpu, MSR_PKG_C8_RESIDENCY, &p->pc8))
1084                         return -13;
1085                 if (get_msr(cpu, MSR_PKG_C9_RESIDENCY, &p->pc9))
1086                         return -13;
1087                 if (get_msr(cpu, MSR_PKG_C10_RESIDENCY, &p->pc10))
1088                         return -13;
1089         }
1090         if (do_rapl & RAPL_PKG) {
1091                 if (get_msr(cpu, MSR_PKG_ENERGY_STATUS, &msr))
1092                         return -13;
1093                 p->energy_pkg = msr & 0xFFFFFFFF;
1094         }
1095         if (do_rapl & RAPL_CORES) {
1096                 if (get_msr(cpu, MSR_PP0_ENERGY_STATUS, &msr))
1097                         return -14;
1098                 p->energy_cores = msr & 0xFFFFFFFF;
1099         }
1100         if (do_rapl & RAPL_DRAM) {
1101                 if (get_msr(cpu, MSR_DRAM_ENERGY_STATUS, &msr))
1102                         return -15;
1103                 p->energy_dram = msr & 0xFFFFFFFF;
1104         }
1105         if (do_rapl & RAPL_GFX) {
1106                 if (get_msr(cpu, MSR_PP1_ENERGY_STATUS, &msr))
1107                         return -16;
1108                 p->energy_gfx = msr & 0xFFFFFFFF;
1109         }
1110         if (do_rapl & RAPL_PKG_PERF_STATUS) {
1111                 if (get_msr(cpu, MSR_PKG_PERF_STATUS, &msr))
1112                         return -16;
1113                 p->rapl_pkg_perf_status = msr & 0xFFFFFFFF;
1114         }
1115         if (do_rapl & RAPL_DRAM_PERF_STATUS) {
1116                 if (get_msr(cpu, MSR_DRAM_PERF_STATUS, &msr))
1117                         return -16;
1118                 p->rapl_dram_perf_status = msr & 0xFFFFFFFF;
1119         }
1120         if (do_ptm) {
1121                 if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_STATUS, &msr))
1122                         return -17;
1123                 p->pkg_temp_c = tcc_activation_temp - ((msr >> 16) & 0x7F);
1124         }
1125         return 0;
1126 }
1127
1128 /*
1129  * MSR_PKG_CST_CONFIG_CONTROL decoding for pkg_cstate_limit:
1130  * If you change the values, note they are used both in comparisons
1131  * (>= PCL__7) and to index pkg_cstate_limit_strings[].
1132  */
1133
1134 #define PCLUKN 0 /* Unknown */
1135 #define PCLRSV 1 /* Reserved */
1136 #define PCL__0 2 /* PC0 */
1137 #define PCL__1 3 /* PC1 */
1138 #define PCL__2 4 /* PC2 */
1139 #define PCL__3 5 /* PC3 */
1140 #define PCL__4 6 /* PC4 */
1141 #define PCL__6 7 /* PC6 */
1142 #define PCL_6N 8 /* PC6 No Retention */
1143 #define PCL_6R 9 /* PC6 Retention */
1144 #define PCL__7 10 /* PC7 */
1145 #define PCL_7S 11 /* PC7 Shrink */
1146 #define PCL__8 12 /* PC8 */
1147 #define PCL__9 13 /* PC9 */
1148 #define PCLUNL 14 /* Unlimited */
1149
1150 int pkg_cstate_limit = PCLUKN;
1151 char *pkg_cstate_limit_strings[] = { "reserved", "unknown", "pc0", "pc1", "pc2",
1152         "pc3", "pc4", "pc6", "pc6n", "pc6r", "pc7", "pc7s", "pc8", "pc9", "unlimited"};
1153
1154 int nhm_pkg_cstate_limits[16] = {PCL__0, PCL__1, PCL__3, PCL__6, PCL__7, PCLRSV, PCLRSV, PCLUNL, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV};
1155 int snb_pkg_cstate_limits[16] = {PCL__0, PCL__2, PCL_6N, PCL_6R, PCL__7, PCL_7S, PCLRSV, PCLUNL, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV};
1156 int hsw_pkg_cstate_limits[16] = {PCL__0, PCL__2, PCL__3, PCL__6, PCL__7, PCL_7S, PCL__8, PCL__9, PCLUNL, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV};
1157 int slv_pkg_cstate_limits[16] = {PCL__0, PCL__1, PCLRSV, PCLRSV, PCL__4, PCLRSV, PCL__6, PCL__7, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV};
1158 int amt_pkg_cstate_limits[16] = {PCL__0, PCL__1, PCL__2, PCLRSV, PCLRSV, PCLRSV, PCL__6, PCL__7, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV};
1159 int phi_pkg_cstate_limits[16] = {PCL__0, PCL__2, PCL_6N, PCL_6R, PCLRSV, PCLRSV, PCLRSV, PCLUNL, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV, PCLRSV};
1160
1161
1162 static void
1163 calculate_tsc_tweak()
1164 {
1165         tsc_tweak = base_hz / tsc_hz;
1166 }
1167
1168 static void
1169 dump_nhm_platform_info(void)
1170 {
1171         unsigned long long msr;
1172         unsigned int ratio;
1173
1174         get_msr(base_cpu, MSR_PLATFORM_INFO, &msr);
1175
1176         fprintf(stderr, "cpu%d: MSR_PLATFORM_INFO: 0x%08llx\n", base_cpu, msr);
1177
1178         ratio = (msr >> 40) & 0xFF;
1179         fprintf(stderr, "%d * %.0f = %.0f MHz max efficiency frequency\n",
1180                 ratio, bclk, ratio * bclk);
1181
1182         ratio = (msr >> 8) & 0xFF;
1183         fprintf(stderr, "%d * %.0f = %.0f MHz base frequency\n",
1184                 ratio, bclk, ratio * bclk);
1185
1186         get_msr(base_cpu, MSR_IA32_POWER_CTL, &msr);
1187         fprintf(stderr, "cpu%d: MSR_IA32_POWER_CTL: 0x%08llx (C1E auto-promotion: %sabled)\n",
1188                 base_cpu, msr, msr & 0x2 ? "EN" : "DIS");
1189
1190         return;
1191 }
1192
1193 static void
1194 dump_hsw_turbo_ratio_limits(void)
1195 {
1196         unsigned long long msr;
1197         unsigned int ratio;
1198
1199         get_msr(base_cpu, MSR_TURBO_RATIO_LIMIT2, &msr);
1200
1201         fprintf(stderr, "cpu%d: MSR_TURBO_RATIO_LIMIT2: 0x%08llx\n", base_cpu, msr);
1202
1203         ratio = (msr >> 8) & 0xFF;
1204         if (ratio)
1205                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 18 active cores\n",
1206                         ratio, bclk, ratio * bclk);
1207
1208         ratio = (msr >> 0) & 0xFF;
1209         if (ratio)
1210                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 17 active cores\n",
1211                         ratio, bclk, ratio * bclk);
1212         return;
1213 }
1214
1215 static void
1216 dump_ivt_turbo_ratio_limits(void)
1217 {
1218         unsigned long long msr;
1219         unsigned int ratio;
1220
1221         get_msr(base_cpu, MSR_TURBO_RATIO_LIMIT1, &msr);
1222
1223         fprintf(stderr, "cpu%d: MSR_TURBO_RATIO_LIMIT1: 0x%08llx\n", base_cpu, msr);
1224
1225         ratio = (msr >> 56) & 0xFF;
1226         if (ratio)
1227                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 16 active cores\n",
1228                         ratio, bclk, ratio * bclk);
1229
1230         ratio = (msr >> 48) & 0xFF;
1231         if (ratio)
1232                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 15 active cores\n",
1233                         ratio, bclk, ratio * bclk);
1234
1235         ratio = (msr >> 40) & 0xFF;
1236         if (ratio)
1237                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 14 active cores\n",
1238                         ratio, bclk, ratio * bclk);
1239
1240         ratio = (msr >> 32) & 0xFF;
1241         if (ratio)
1242                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 13 active cores\n",
1243                         ratio, bclk, ratio * bclk);
1244
1245         ratio = (msr >> 24) & 0xFF;
1246         if (ratio)
1247                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 12 active cores\n",
1248                         ratio, bclk, ratio * bclk);
1249
1250         ratio = (msr >> 16) & 0xFF;
1251         if (ratio)
1252                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 11 active cores\n",
1253                         ratio, bclk, ratio * bclk);
1254
1255         ratio = (msr >> 8) & 0xFF;
1256         if (ratio)
1257                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 10 active cores\n",
1258                         ratio, bclk, ratio * bclk);
1259
1260         ratio = (msr >> 0) & 0xFF;
1261         if (ratio)
1262                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 9 active cores\n",
1263                         ratio, bclk, ratio * bclk);
1264         return;
1265 }
1266
1267 static void
1268 dump_nhm_turbo_ratio_limits(void)
1269 {
1270         unsigned long long msr;
1271         unsigned int ratio;
1272
1273         get_msr(base_cpu, MSR_TURBO_RATIO_LIMIT, &msr);
1274
1275         fprintf(stderr, "cpu%d: MSR_TURBO_RATIO_LIMIT: 0x%08llx\n", base_cpu, msr);
1276
1277         ratio = (msr >> 56) & 0xFF;
1278         if (ratio)
1279                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 8 active cores\n",
1280                         ratio, bclk, ratio * bclk);
1281
1282         ratio = (msr >> 48) & 0xFF;
1283         if (ratio)
1284                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 7 active cores\n",
1285                         ratio, bclk, ratio * bclk);
1286
1287         ratio = (msr >> 40) & 0xFF;
1288         if (ratio)
1289                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 6 active cores\n",
1290                         ratio, bclk, ratio * bclk);
1291
1292         ratio = (msr >> 32) & 0xFF;
1293         if (ratio)
1294                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 5 active cores\n",
1295                         ratio, bclk, ratio * bclk);
1296
1297         ratio = (msr >> 24) & 0xFF;
1298         if (ratio)
1299                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 4 active cores\n",
1300                         ratio, bclk, ratio * bclk);
1301
1302         ratio = (msr >> 16) & 0xFF;
1303         if (ratio)
1304                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 3 active cores\n",
1305                         ratio, bclk, ratio * bclk);
1306
1307         ratio = (msr >> 8) & 0xFF;
1308         if (ratio)
1309                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 2 active cores\n",
1310                         ratio, bclk, ratio * bclk);
1311
1312         ratio = (msr >> 0) & 0xFF;
1313         if (ratio)
1314                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 1 active cores\n",
1315                         ratio, bclk, ratio * bclk);
1316         return;
1317 }
1318
1319 static void
1320 dump_knl_turbo_ratio_limits(void)
1321 {
1322         int cores;
1323         unsigned int ratio;
1324         unsigned long long msr;
1325         int delta_cores;
1326         int delta_ratio;
1327         int i;
1328
1329         get_msr(base_cpu, MSR_NHM_TURBO_RATIO_LIMIT, &msr);
1330
1331         fprintf(stderr, "cpu%d: MSR_NHM_TURBO_RATIO_LIMIT: 0x%08llx\n",
1332                 base_cpu, msr);
1333
1334         /**
1335          * Turbo encoding in KNL is as follows:
1336          * [7:0] -- Base value of number of active cores of bucket 1.
1337          * [15:8] -- Base value of freq ratio of bucket 1.
1338          * [20:16] -- +ve delta of number of active cores of bucket 2.
1339          * i.e. active cores of bucket 2 =
1340          * active cores of bucket 1 + delta
1341          * [23:21] -- Negative delta of freq ratio of bucket 2.
1342          * i.e. freq ratio of bucket 2 =
1343          * freq ratio of bucket 1 - delta
1344          * [28:24]-- +ve delta of number of active cores of bucket 3.
1345          * [31:29]-- -ve delta of freq ratio of bucket 3.
1346          * [36:32]-- +ve delta of number of active cores of bucket 4.
1347          * [39:37]-- -ve delta of freq ratio of bucket 4.
1348          * [44:40]-- +ve delta of number of active cores of bucket 5.
1349          * [47:45]-- -ve delta of freq ratio of bucket 5.
1350          * [52:48]-- +ve delta of number of active cores of bucket 6.
1351          * [55:53]-- -ve delta of freq ratio of bucket 6.
1352          * [60:56]-- +ve delta of number of active cores of bucket 7.
1353          * [63:61]-- -ve delta of freq ratio of bucket 7.
1354          */
1355         cores = msr & 0xFF;
1356         ratio = (msr >> 8) && 0xFF;
1357         if (ratio > 0)
1358                 fprintf(stderr,
1359                         "%d * %.0f = %.0f MHz max turbo %d active cores\n",
1360                         ratio, bclk, ratio * bclk, cores);
1361
1362         for (i = 16; i < 64; i = i + 8) {
1363                 delta_cores = (msr >> i) & 0x1F;
1364                 delta_ratio = (msr >> (i + 5)) && 0x7;
1365                 if (!delta_cores || !delta_ratio)
1366                         return;
1367                 cores = cores + delta_cores;
1368                 ratio = ratio - delta_ratio;
1369
1370                 /** -ve ratios will make successive ratio calculations
1371                  * negative. Hence return instead of carrying on.
1372                  */
1373                 if (ratio > 0)
1374                         fprintf(stderr,
1375                                 "%d * %.0f = %.0f MHz max turbo %d active cores\n",
1376                                 ratio, bclk, ratio * bclk, cores);
1377         }
1378 }
1379
1380 static void
1381 dump_nhm_cst_cfg(void)
1382 {
1383         unsigned long long msr;
1384
1385         get_msr(base_cpu, MSR_NHM_SNB_PKG_CST_CFG_CTL, &msr);
1386
1387 #define SNB_C1_AUTO_UNDEMOTE              (1UL << 27)
1388 #define SNB_C3_AUTO_UNDEMOTE              (1UL << 28)
1389
1390         fprintf(stderr, "cpu%d: MSR_NHM_SNB_PKG_CST_CFG_CTL: 0x%08llx", base_cpu, msr);
1391
1392         fprintf(stderr, " (%s%s%s%s%slocked: pkg-cstate-limit=%d: %s)\n",
1393                 (msr & SNB_C3_AUTO_UNDEMOTE) ? "UNdemote-C3, " : "",
1394                 (msr & SNB_C1_AUTO_UNDEMOTE) ? "UNdemote-C1, " : "",
1395                 (msr & NHM_C3_AUTO_DEMOTE) ? "demote-C3, " : "",
1396                 (msr & NHM_C1_AUTO_DEMOTE) ? "demote-C1, " : "",
1397                 (msr & (1 << 15)) ? "" : "UN",
1398                 (unsigned int)msr & 7,
1399                 pkg_cstate_limit_strings[pkg_cstate_limit]);
1400         return;
1401 }
1402
1403 static void
1404 dump_config_tdp(void)
1405 {
1406         unsigned long long msr;
1407
1408         get_msr(base_cpu, MSR_CONFIG_TDP_NOMINAL, &msr);
1409         fprintf(stderr, "cpu%d: MSR_CONFIG_TDP_NOMINAL: 0x%08llx", base_cpu, msr);
1410         fprintf(stderr, " (base_ratio=%d)\n", (unsigned int)msr & 0xEF);
1411
1412         get_msr(base_cpu, MSR_CONFIG_TDP_LEVEL_1, &msr);
1413         fprintf(stderr, "cpu%d: MSR_CONFIG_TDP_LEVEL_1: 0x%08llx (", base_cpu, msr);
1414         if (msr) {
1415                 fprintf(stderr, "PKG_MIN_PWR_LVL1=%d ", (unsigned int)(msr >> 48) & 0xEFFF);
1416                 fprintf(stderr, "PKG_MAX_PWR_LVL1=%d ", (unsigned int)(msr >> 32) & 0xEFFF);
1417                 fprintf(stderr, "LVL1_RATIO=%d ", (unsigned int)(msr >> 16) & 0xEF);
1418                 fprintf(stderr, "PKG_TDP_LVL1=%d", (unsigned int)(msr) & 0xEFFF);
1419         }
1420         fprintf(stderr, ")\n");
1421
1422         get_msr(base_cpu, MSR_CONFIG_TDP_LEVEL_2, &msr);
1423         fprintf(stderr, "cpu%d: MSR_CONFIG_TDP_LEVEL_2: 0x%08llx (", base_cpu, msr);
1424         if (msr) {
1425                 fprintf(stderr, "PKG_MIN_PWR_LVL2=%d ", (unsigned int)(msr >> 48) & 0xEFFF);
1426                 fprintf(stderr, "PKG_MAX_PWR_LVL2=%d ", (unsigned int)(msr >> 32) & 0xEFFF);
1427                 fprintf(stderr, "LVL2_RATIO=%d ", (unsigned int)(msr >> 16) & 0xEF);
1428                 fprintf(stderr, "PKG_TDP_LVL2=%d", (unsigned int)(msr) & 0xEFFF);
1429         }
1430         fprintf(stderr, ")\n");
1431
1432         get_msr(base_cpu, MSR_CONFIG_TDP_CONTROL, &msr);
1433         fprintf(stderr, "cpu%d: MSR_CONFIG_TDP_CONTROL: 0x%08llx (", base_cpu, msr);
1434         if ((msr) & 0x3)
1435                 fprintf(stderr, "TDP_LEVEL=%d ", (unsigned int)(msr) & 0x3);
1436         fprintf(stderr, " lock=%d", (unsigned int)(msr >> 31) & 1);
1437         fprintf(stderr, ")\n");
1438         
1439         get_msr(base_cpu, MSR_TURBO_ACTIVATION_RATIO, &msr);
1440         fprintf(stderr, "cpu%d: MSR_TURBO_ACTIVATION_RATIO: 0x%08llx (", base_cpu, msr);
1441         fprintf(stderr, "MAX_NON_TURBO_RATIO=%d", (unsigned int)(msr) & 0x7F);
1442         fprintf(stderr, " lock=%d", (unsigned int)(msr >> 31) & 1);
1443         fprintf(stderr, ")\n");
1444 }
1445
1446 void free_all_buffers(void)
1447 {
1448         CPU_FREE(cpu_present_set);
1449         cpu_present_set = NULL;
1450         cpu_present_set = 0;
1451
1452         CPU_FREE(cpu_affinity_set);
1453         cpu_affinity_set = NULL;
1454         cpu_affinity_setsize = 0;
1455
1456         free(thread_even);
1457         free(core_even);
1458         free(package_even);
1459
1460         thread_even = NULL;
1461         core_even = NULL;
1462         package_even = NULL;
1463
1464         free(thread_odd);
1465         free(core_odd);
1466         free(package_odd);
1467
1468         thread_odd = NULL;
1469         core_odd = NULL;
1470         package_odd = NULL;
1471
1472         free(output_buffer);
1473         output_buffer = NULL;
1474         outp = NULL;
1475 }
1476
1477 /*
1478  * Open a file, and exit on failure
1479  */
1480 FILE *fopen_or_die(const char *path, const char *mode)
1481 {
1482         FILE *filep = fopen(path, "r");
1483         if (!filep)
1484                 err(1, "%s: open failed", path);
1485         return filep;
1486 }
1487
1488 /*
1489  * Parse a file containing a single int.
1490  */
1491 int parse_int_file(const char *fmt, ...)
1492 {
1493         va_list args;
1494         char path[PATH_MAX];
1495         FILE *filep;
1496         int value;
1497
1498         va_start(args, fmt);
1499         vsnprintf(path, sizeof(path), fmt, args);
1500         va_end(args);
1501         filep = fopen_or_die(path, "r");
1502         if (fscanf(filep, "%d", &value) != 1)
1503                 err(1, "%s: failed to parse number from file", path);
1504         fclose(filep);
1505         return value;
1506 }
1507
1508 /*
1509  * get_cpu_position_in_core(cpu)
1510  * return the position of the CPU among its HT siblings in the core
1511  * return -1 if the sibling is not in list
1512  */
1513 int get_cpu_position_in_core(int cpu)
1514 {
1515         char path[64];
1516         FILE *filep;
1517         int this_cpu;
1518         char character;
1519         int i;
1520
1521         sprintf(path,
1522                 "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list",
1523                 cpu);
1524         filep = fopen(path, "r");
1525         if (filep == NULL) {
1526                 perror(path);
1527                 exit(1);
1528         }
1529
1530         for (i = 0; i < topo.num_threads_per_core; i++) {
1531                 fscanf(filep, "%d", &this_cpu);
1532                 if (this_cpu == cpu) {
1533                         fclose(filep);
1534                         return i;
1535                 }
1536
1537                 /* Account for no separator after last thread*/
1538                 if (i != (topo.num_threads_per_core - 1))
1539                         fscanf(filep, "%c", &character);
1540         }
1541
1542         fclose(filep);
1543         return -1;
1544 }
1545
1546 /*
1547  * cpu_is_first_core_in_package(cpu)
1548  * return 1 if given CPU is 1st core in package
1549  */
1550 int cpu_is_first_core_in_package(int cpu)
1551 {
1552         return cpu == parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_siblings_list", cpu);
1553 }
1554
1555 int get_physical_package_id(int cpu)
1556 {
1557         return parse_int_file("/sys/devices/system/cpu/cpu%d/topology/physical_package_id", cpu);
1558 }
1559
1560 int get_core_id(int cpu)
1561 {
1562         return parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_id", cpu);
1563 }
1564
1565 int get_num_ht_siblings(int cpu)
1566 {
1567         char path[80];
1568         FILE *filep;
1569         int sib1;
1570         int matches = 0;
1571         char character;
1572         char str[100];
1573         char *ch;
1574
1575         sprintf(path, "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", cpu);
1576         filep = fopen_or_die(path, "r");
1577
1578         /*
1579          * file format:
1580          * A ',' separated or '-' separated set of numbers
1581          * (eg 1-2 or 1,3,4,5)
1582          */
1583         fscanf(filep, "%d%c\n", &sib1, &character);
1584         fseek(filep, 0, SEEK_SET);
1585         fgets(str, 100, filep);
1586         ch = strchr(str, character);
1587         while (ch != NULL) {
1588                 matches++;
1589                 ch = strchr(ch+1, character);
1590         }
1591
1592         fclose(filep);
1593         return matches+1;
1594 }
1595
1596 /*
1597  * run func(thread, core, package) in topology order
1598  * skip non-present cpus
1599  */
1600
1601 int for_all_cpus_2(int (func)(struct thread_data *, struct core_data *,
1602         struct pkg_data *, struct thread_data *, struct core_data *,
1603         struct pkg_data *), struct thread_data *thread_base,
1604         struct core_data *core_base, struct pkg_data *pkg_base,
1605         struct thread_data *thread_base2, struct core_data *core_base2,
1606         struct pkg_data *pkg_base2)
1607 {
1608         int retval, pkg_no, core_no, thread_no;
1609
1610         for (pkg_no = 0; pkg_no < topo.num_packages; ++pkg_no) {
1611                 for (core_no = 0; core_no < topo.num_cores_per_pkg; ++core_no) {
1612                         for (thread_no = 0; thread_no <
1613                                 topo.num_threads_per_core; ++thread_no) {
1614                                 struct thread_data *t, *t2;
1615                                 struct core_data *c, *c2;
1616                                 struct pkg_data *p, *p2;
1617
1618                                 t = GET_THREAD(thread_base, thread_no, core_no, pkg_no);
1619
1620                                 if (cpu_is_not_present(t->cpu_id))
1621                                         continue;
1622
1623                                 t2 = GET_THREAD(thread_base2, thread_no, core_no, pkg_no);
1624
1625                                 c = GET_CORE(core_base, core_no, pkg_no);
1626                                 c2 = GET_CORE(core_base2, core_no, pkg_no);
1627
1628                                 p = GET_PKG(pkg_base, pkg_no);
1629                                 p2 = GET_PKG(pkg_base2, pkg_no);
1630
1631                                 retval = func(t, c, p, t2, c2, p2);
1632                                 if (retval)
1633                                         return retval;
1634                         }
1635                 }
1636         }
1637         return 0;
1638 }
1639
1640 /*
1641  * run func(cpu) on every cpu in /proc/stat
1642  * return max_cpu number
1643  */
1644 int for_all_proc_cpus(int (func)(int))
1645 {
1646         FILE *fp;
1647         int cpu_num;
1648         int retval;
1649
1650         fp = fopen_or_die(proc_stat, "r");
1651
1652         retval = fscanf(fp, "cpu %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n");
1653         if (retval != 0)
1654                 err(1, "%s: failed to parse format", proc_stat);
1655
1656         while (1) {
1657                 retval = fscanf(fp, "cpu%u %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n", &cpu_num);
1658                 if (retval != 1)
1659                         break;
1660
1661                 retval = func(cpu_num);
1662                 if (retval) {
1663                         fclose(fp);
1664                         return(retval);
1665                 }
1666         }
1667         fclose(fp);
1668         return 0;
1669 }
1670
1671 void re_initialize(void)
1672 {
1673         free_all_buffers();
1674         setup_all_buffers();
1675         printf("turbostat: re-initialized with num_cpus %d\n", topo.num_cpus);
1676 }
1677
1678
1679 /*
1680  * count_cpus()
1681  * remember the last one seen, it will be the max
1682  */
1683 int count_cpus(int cpu)
1684 {
1685         if (topo.max_cpu_num < cpu)
1686                 topo.max_cpu_num = cpu;
1687
1688         topo.num_cpus += 1;
1689         return 0;
1690 }
1691 int mark_cpu_present(int cpu)
1692 {
1693         CPU_SET_S(cpu, cpu_present_setsize, cpu_present_set);
1694         return 0;
1695 }
1696
1697 void turbostat_loop()
1698 {
1699         int retval;
1700         int restarted = 0;
1701
1702 restart:
1703         restarted++;
1704
1705         retval = for_all_cpus(get_counters, EVEN_COUNTERS);
1706         if (retval < -1) {
1707                 exit(retval);
1708         } else if (retval == -1) {
1709                 if (restarted > 1) {
1710                         exit(retval);
1711                 }
1712                 re_initialize();
1713                 goto restart;
1714         }
1715         restarted = 0;
1716         gettimeofday(&tv_even, (struct timezone *)NULL);
1717
1718         while (1) {
1719                 if (for_all_proc_cpus(cpu_is_not_present)) {
1720                         re_initialize();
1721                         goto restart;
1722                 }
1723                 sleep(interval_sec);
1724                 retval = for_all_cpus(get_counters, ODD_COUNTERS);
1725                 if (retval < -1) {
1726                         exit(retval);
1727                 } else if (retval == -1) {
1728                         re_initialize();
1729                         goto restart;
1730                 }
1731                 gettimeofday(&tv_odd, (struct timezone *)NULL);
1732                 timersub(&tv_odd, &tv_even, &tv_delta);
1733                 for_all_cpus_2(delta_cpu, ODD_COUNTERS, EVEN_COUNTERS);
1734                 compute_average(EVEN_COUNTERS);
1735                 format_all_counters(EVEN_COUNTERS);
1736                 flush_stdout();
1737                 sleep(interval_sec);
1738                 retval = for_all_cpus(get_counters, EVEN_COUNTERS);
1739                 if (retval < -1) {
1740                         exit(retval);
1741                 } else if (retval == -1) {
1742                         re_initialize();
1743                         goto restart;
1744                 }
1745                 gettimeofday(&tv_even, (struct timezone *)NULL);
1746                 timersub(&tv_even, &tv_odd, &tv_delta);
1747                 for_all_cpus_2(delta_cpu, EVEN_COUNTERS, ODD_COUNTERS);
1748                 compute_average(ODD_COUNTERS);
1749                 format_all_counters(ODD_COUNTERS);
1750                 flush_stdout();
1751         }
1752 }
1753
1754 void check_dev_msr()
1755 {
1756         struct stat sb;
1757         char pathname[32];
1758
1759         sprintf(pathname, "/dev/cpu/%d/msr", base_cpu);
1760         if (stat(pathname, &sb))
1761                 if (system("/sbin/modprobe msr > /dev/null 2>&1"))
1762                         err(-5, "no /dev/cpu/0/msr, Try \"# modprobe msr\" ");
1763 }
1764
1765 void check_permissions()
1766 {
1767         struct __user_cap_header_struct cap_header_data;
1768         cap_user_header_t cap_header = &cap_header_data;
1769         struct __user_cap_data_struct cap_data_data;
1770         cap_user_data_t cap_data = &cap_data_data;
1771         extern int capget(cap_user_header_t hdrp, cap_user_data_t datap);
1772         int do_exit = 0;
1773         char pathname[32];
1774
1775         /* check for CAP_SYS_RAWIO */
1776         cap_header->pid = getpid();
1777         cap_header->version = _LINUX_CAPABILITY_VERSION;
1778         if (capget(cap_header, cap_data) < 0)
1779                 err(-6, "capget(2) failed");
1780
1781         if ((cap_data->effective & (1 << CAP_SYS_RAWIO)) == 0) {
1782                 do_exit++;
1783                 warnx("capget(CAP_SYS_RAWIO) failed,"
1784                         " try \"# setcap cap_sys_rawio=ep %s\"", progname);
1785         }
1786
1787         /* test file permissions */
1788         sprintf(pathname, "/dev/cpu/%d/msr", base_cpu);
1789         if (euidaccess(pathname, R_OK)) {
1790                 do_exit++;
1791                 warn("/dev/cpu/0/msr open failed, try chown or chmod +r /dev/cpu/*/msr");
1792         }
1793
1794         /* if all else fails, thell them to be root */
1795         if (do_exit)
1796                 if (getuid() != 0)
1797                         warnx("... or simply run as root");
1798
1799         if (do_exit)
1800                 exit(-6);
1801 }
1802
1803 /*
1804  * NHM adds support for additional MSRs:
1805  *
1806  * MSR_SMI_COUNT                   0x00000034
1807  *
1808  * MSR_PLATFORM_INFO               0x000000ce
1809  * MSR_NHM_SNB_PKG_CST_CFG_CTL     0x000000e2
1810  *
1811  * MSR_PKG_C3_RESIDENCY            0x000003f8
1812  * MSR_PKG_C6_RESIDENCY            0x000003f9
1813  * MSR_CORE_C3_RESIDENCY           0x000003fc
1814  * MSR_CORE_C6_RESIDENCY           0x000003fd
1815  *
1816  * Side effect:
1817  * sets global pkg_cstate_limit to decode MSR_NHM_SNB_PKG_CST_CFG_CTL
1818  */
1819 int probe_nhm_msrs(unsigned int family, unsigned int model)
1820 {
1821         unsigned long long msr;
1822         unsigned int base_ratio;
1823         int *pkg_cstate_limits;
1824
1825         if (!genuine_intel)
1826                 return 0;
1827
1828         if (family != 6)
1829                 return 0;
1830
1831         bclk = discover_bclk(family, model);
1832
1833         switch (model) {
1834         case 0x1A:      /* Core i7, Xeon 5500 series - Bloomfield, Gainstown NHM-EP */
1835         case 0x1E:      /* Core i7 and i5 Processor - Clarksfield, Lynnfield, Jasper Forest */
1836         case 0x1F:      /* Core i7 and i5 Processor - Nehalem */
1837         case 0x25:      /* Westmere Client - Clarkdale, Arrandale */
1838         case 0x2C:      /* Westmere EP - Gulftown */
1839         case 0x2E:      /* Nehalem-EX Xeon - Beckton */
1840         case 0x2F:      /* Westmere-EX Xeon - Eagleton */
1841                 pkg_cstate_limits = nhm_pkg_cstate_limits;
1842                 break;
1843         case 0x2A:      /* SNB */
1844         case 0x2D:      /* SNB Xeon */
1845         case 0x3A:      /* IVB */
1846         case 0x3E:      /* IVB Xeon */
1847                 pkg_cstate_limits = snb_pkg_cstate_limits;
1848                 break;
1849         case 0x3C:      /* HSW */
1850         case 0x3F:      /* HSX */
1851         case 0x45:      /* HSW */
1852         case 0x46:      /* HSW */
1853         case 0x3D:      /* BDW */
1854         case 0x47:      /* BDW */
1855         case 0x4F:      /* BDX */
1856         case 0x56:      /* BDX-DE */
1857         case 0x4E:      /* SKL */
1858         case 0x5E:      /* SKL */
1859                 pkg_cstate_limits = hsw_pkg_cstate_limits;
1860                 break;
1861         case 0x37:      /* BYT */
1862         case 0x4D:      /* AVN */
1863                 pkg_cstate_limits = slv_pkg_cstate_limits;
1864                 break;
1865         case 0x4C:      /* AMT */
1866                 pkg_cstate_limits = amt_pkg_cstate_limits;
1867                 break;
1868         case 0x57:      /* PHI */
1869                 pkg_cstate_limits = phi_pkg_cstate_limits;
1870                 break;
1871         default:
1872                 return 0;
1873         }
1874         get_msr(base_cpu, MSR_NHM_SNB_PKG_CST_CFG_CTL, &msr);
1875         pkg_cstate_limit = pkg_cstate_limits[msr & 0xF];
1876
1877         get_msr(base_cpu, MSR_PLATFORM_INFO, &msr);
1878         base_ratio = (msr >> 8) & 0xFF;
1879
1880         base_hz = base_ratio * bclk * 1000000;
1881         has_base_hz = 1;
1882         return 1;
1883 }
1884 int has_nhm_turbo_ratio_limit(unsigned int family, unsigned int model)
1885 {
1886         switch (model) {
1887         /* Nehalem compatible, but do not include turbo-ratio limit support */
1888         case 0x2E:      /* Nehalem-EX Xeon - Beckton */
1889         case 0x2F:      /* Westmere-EX Xeon - Eagleton */
1890                 return 0;
1891         default:
1892                 return 1;
1893         }
1894 }
1895 int has_ivt_turbo_ratio_limit(unsigned int family, unsigned int model)
1896 {
1897         if (!genuine_intel)
1898                 return 0;
1899
1900         if (family != 6)
1901                 return 0;
1902
1903         switch (model) {
1904         case 0x3E:      /* IVB Xeon */
1905         case 0x3F:      /* HSW Xeon */
1906                 return 1;
1907         default:
1908                 return 0;
1909         }
1910 }
1911 int has_hsw_turbo_ratio_limit(unsigned int family, unsigned int model)
1912 {
1913         if (!genuine_intel)
1914                 return 0;
1915
1916         if (family != 6)
1917                 return 0;
1918
1919         switch (model) {
1920         case 0x3F:      /* HSW Xeon */
1921                 return 1;
1922         default:
1923                 return 0;
1924         }
1925 }
1926
1927 int has_knl_turbo_ratio_limit(unsigned int family, unsigned int model)
1928 {
1929         if (!genuine_intel)
1930                 return 0;
1931
1932         if (family != 6)
1933                 return 0;
1934
1935         switch (model) {
1936         case 0x57:      /* Knights Landing */
1937                 return 1;
1938         default:
1939                 return 0;
1940         }
1941 }
1942 int has_config_tdp(unsigned int family, unsigned int model)
1943 {
1944         if (!genuine_intel)
1945                 return 0;
1946
1947         if (family != 6)
1948                 return 0;
1949
1950         switch (model) {
1951         case 0x3A:      /* IVB */
1952         case 0x3C:      /* HSW */
1953         case 0x3F:      /* HSX */
1954         case 0x45:      /* HSW */
1955         case 0x46:      /* HSW */
1956         case 0x3D:      /* BDW */
1957         case 0x47:      /* BDW */
1958         case 0x4F:      /* BDX */
1959         case 0x56:      /* BDX-DE */
1960         case 0x4E:      /* SKL */
1961         case 0x5E:      /* SKL */
1962
1963         case 0x57:      /* Knights Landing */
1964                 return 1;
1965         default:
1966                 return 0;
1967         }
1968 }
1969
1970 static void
1971 dump_cstate_pstate_config_info(family, model)
1972 {
1973         if (!do_nhm_platform_info)
1974                 return;
1975
1976         dump_nhm_platform_info();
1977
1978         if (has_hsw_turbo_ratio_limit(family, model))
1979                 dump_hsw_turbo_ratio_limits();
1980
1981         if (has_ivt_turbo_ratio_limit(family, model))
1982                 dump_ivt_turbo_ratio_limits();
1983
1984         if (has_nhm_turbo_ratio_limit(family, model))
1985                 dump_nhm_turbo_ratio_limits();
1986
1987         if (has_knl_turbo_ratio_limit(family, model))
1988                 dump_knl_turbo_ratio_limits();
1989
1990         if (has_config_tdp(family, model))
1991                 dump_config_tdp();
1992
1993         dump_nhm_cst_cfg();
1994 }
1995
1996
1997 /*
1998  * print_epb()
1999  * Decode the ENERGY_PERF_BIAS MSR
2000  */
2001 int print_epb(struct thread_data *t, struct core_data *c, struct pkg_data *p)
2002 {
2003         unsigned long long msr;
2004         char *epb_string;
2005         int cpu;
2006
2007         if (!has_epb)
2008                 return 0;
2009
2010         cpu = t->cpu_id;
2011
2012         /* EPB is per-package */
2013         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
2014                 return 0;
2015
2016         if (cpu_migrate(cpu)) {
2017                 fprintf(stderr, "Could not migrate to CPU %d\n", cpu);
2018                 return -1;
2019         }
2020
2021         if (get_msr(cpu, MSR_IA32_ENERGY_PERF_BIAS, &msr))
2022                 return 0;
2023
2024         switch (msr & 0xF) {
2025         case ENERGY_PERF_BIAS_PERFORMANCE:
2026                 epb_string = "performance";
2027                 break;
2028         case ENERGY_PERF_BIAS_NORMAL:
2029                 epb_string = "balanced";
2030                 break;
2031         case ENERGY_PERF_BIAS_POWERSAVE:
2032                 epb_string = "powersave";
2033                 break;
2034         default:
2035                 epb_string = "custom";
2036                 break;
2037         }
2038         fprintf(stderr, "cpu%d: MSR_IA32_ENERGY_PERF_BIAS: 0x%08llx (%s)\n", cpu, msr, epb_string);
2039
2040         return 0;
2041 }
2042
2043 /*
2044  * print_perf_limit()
2045  */
2046 int print_perf_limit(struct thread_data *t, struct core_data *c, struct pkg_data *p)
2047 {
2048         unsigned long long msr;
2049         int cpu;
2050
2051         cpu = t->cpu_id;
2052
2053         /* per-package */
2054         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
2055                 return 0;
2056
2057         if (cpu_migrate(cpu)) {
2058                 fprintf(stderr, "Could not migrate to CPU %d\n", cpu);
2059                 return -1;
2060         }
2061
2062         if (do_core_perf_limit_reasons) {
2063                 get_msr(cpu, MSR_CORE_PERF_LIMIT_REASONS, &msr);
2064                 fprintf(stderr, "cpu%d: MSR_CORE_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
2065                 fprintf(stderr, " (Active: %s%s%s%s%s%s%s%s%s%s%s%s%s%s)",
2066                         (msr & 1 << 15) ? "bit15, " : "",
2067                         (msr & 1 << 14) ? "bit14, " : "",
2068                         (msr & 1 << 13) ? "Transitions, " : "",
2069                         (msr & 1 << 12) ? "MultiCoreTurbo, " : "",
2070                         (msr & 1 << 11) ? "PkgPwrL2, " : "",
2071                         (msr & 1 << 10) ? "PkgPwrL1, " : "",
2072                         (msr & 1 << 9) ? "CorePwr, " : "",
2073                         (msr & 1 << 8) ? "Amps, " : "",
2074                         (msr & 1 << 6) ? "VR-Therm, " : "",
2075                         (msr & 1 << 5) ? "Auto-HWP, " : "",
2076                         (msr & 1 << 4) ? "Graphics, " : "",
2077                         (msr & 1 << 2) ? "bit2, " : "",
2078                         (msr & 1 << 1) ? "ThermStatus, " : "",
2079                         (msr & 1 << 0) ? "PROCHOT, " : "");
2080                 fprintf(stderr, " (Logged: %s%s%s%s%s%s%s%s%s%s%s%s%s%s)\n",
2081                         (msr & 1 << 31) ? "bit31, " : "",
2082                         (msr & 1 << 30) ? "bit30, " : "",
2083                         (msr & 1 << 29) ? "Transitions, " : "",
2084                         (msr & 1 << 28) ? "MultiCoreTurbo, " : "",
2085                         (msr & 1 << 27) ? "PkgPwrL2, " : "",
2086                         (msr & 1 << 26) ? "PkgPwrL1, " : "",
2087                         (msr & 1 << 25) ? "CorePwr, " : "",
2088                         (msr & 1 << 24) ? "Amps, " : "",
2089                         (msr & 1 << 22) ? "VR-Therm, " : "",
2090                         (msr & 1 << 21) ? "Auto-HWP, " : "",
2091                         (msr & 1 << 20) ? "Graphics, " : "",
2092                         (msr & 1 << 18) ? "bit18, " : "",
2093                         (msr & 1 << 17) ? "ThermStatus, " : "",
2094                         (msr & 1 << 16) ? "PROCHOT, " : "");
2095
2096         }
2097         if (do_gfx_perf_limit_reasons) {
2098                 get_msr(cpu, MSR_GFX_PERF_LIMIT_REASONS, &msr);
2099                 fprintf(stderr, "cpu%d: MSR_GFX_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
2100                 fprintf(stderr, " (Active: %s%s%s%s%s%s%s%s)",
2101                         (msr & 1 << 0) ? "PROCHOT, " : "",
2102                         (msr & 1 << 1) ? "ThermStatus, " : "",
2103                         (msr & 1 << 4) ? "Graphics, " : "",
2104                         (msr & 1 << 6) ? "VR-Therm, " : "",
2105                         (msr & 1 << 8) ? "Amps, " : "",
2106                         (msr & 1 << 9) ? "GFXPwr, " : "",
2107                         (msr & 1 << 10) ? "PkgPwrL1, " : "",
2108                         (msr & 1 << 11) ? "PkgPwrL2, " : "");
2109                 fprintf(stderr, " (Logged: %s%s%s%s%s%s%s%s)\n",
2110                         (msr & 1 << 16) ? "PROCHOT, " : "",
2111                         (msr & 1 << 17) ? "ThermStatus, " : "",
2112                         (msr & 1 << 20) ? "Graphics, " : "",
2113                         (msr & 1 << 22) ? "VR-Therm, " : "",
2114                         (msr & 1 << 24) ? "Amps, " : "",
2115                         (msr & 1 << 25) ? "GFXPwr, " : "",
2116                         (msr & 1 << 26) ? "PkgPwrL1, " : "",
2117                         (msr & 1 << 27) ? "PkgPwrL2, " : "");
2118         }
2119         if (do_ring_perf_limit_reasons) {
2120                 get_msr(cpu, MSR_RING_PERF_LIMIT_REASONS, &msr);
2121                 fprintf(stderr, "cpu%d: MSR_RING_PERF_LIMIT_REASONS, 0x%08llx", cpu, msr);
2122                 fprintf(stderr, " (Active: %s%s%s%s%s%s)",
2123                         (msr & 1 << 0) ? "PROCHOT, " : "",
2124                         (msr & 1 << 1) ? "ThermStatus, " : "",
2125                         (msr & 1 << 6) ? "VR-Therm, " : "",
2126                         (msr & 1 << 8) ? "Amps, " : "",
2127                         (msr & 1 << 10) ? "PkgPwrL1, " : "",
2128                         (msr & 1 << 11) ? "PkgPwrL2, " : "");
2129                 fprintf(stderr, " (Logged: %s%s%s%s%s%s)\n",
2130                         (msr & 1 << 16) ? "PROCHOT, " : "",
2131                         (msr & 1 << 17) ? "ThermStatus, " : "",
2132                         (msr & 1 << 22) ? "VR-Therm, " : "",
2133                         (msr & 1 << 24) ? "Amps, " : "",
2134                         (msr & 1 << 26) ? "PkgPwrL1, " : "",
2135                         (msr & 1 << 27) ? "PkgPwrL2, " : "");
2136         }
2137         return 0;
2138 }
2139
2140 #define RAPL_POWER_GRANULARITY  0x7FFF  /* 15 bit power granularity */
2141 #define RAPL_TIME_GRANULARITY   0x3F /* 6 bit time granularity */
2142
2143 double get_tdp(model)
2144 {
2145         unsigned long long msr;
2146
2147         if (do_rapl & RAPL_PKG_POWER_INFO)
2148                 if (!get_msr(base_cpu, MSR_PKG_POWER_INFO, &msr))
2149                         return ((msr >> 0) & RAPL_POWER_GRANULARITY) * rapl_power_units;
2150
2151         switch (model) {
2152         case 0x37:
2153         case 0x4D:
2154                 return 30.0;
2155         default:
2156                 return 135.0;
2157         }
2158 }
2159
2160 /*
2161  * rapl_dram_energy_units_probe()
2162  * Energy units are either hard-coded, or come from RAPL Energy Unit MSR.
2163  */
2164 static double
2165 rapl_dram_energy_units_probe(int  model, double rapl_energy_units)
2166 {
2167         /* only called for genuine_intel, family 6 */
2168
2169         switch (model) {
2170         case 0x3F:      /* HSX */
2171         case 0x4F:      /* BDX */
2172         case 0x56:      /* BDX-DE */
2173         case 0x57:      /* KNL */
2174                 return (rapl_dram_energy_units = 15.3 / 1000000);
2175         default:
2176                 return (rapl_energy_units);
2177         }
2178 }
2179
2180
2181 /*
2182  * rapl_probe()
2183  *
2184  * sets do_rapl, rapl_power_units, rapl_energy_units, rapl_time_units
2185  */
2186 void rapl_probe(unsigned int family, unsigned int model)
2187 {
2188         unsigned long long msr;
2189         unsigned int time_unit;
2190         double tdp;
2191
2192         if (!genuine_intel)
2193                 return;
2194
2195         if (family != 6)
2196                 return;
2197
2198         switch (model) {
2199         case 0x2A:
2200         case 0x3A:
2201         case 0x3C:      /* HSW */
2202         case 0x45:      /* HSW */
2203         case 0x46:      /* HSW */
2204         case 0x3D:      /* BDW */
2205         case 0x47:      /* BDW */
2206                 do_rapl = RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_GFX | RAPL_PKG_POWER_INFO;
2207                 break;
2208         case 0x4E:      /* SKL */
2209         case 0x5E:      /* SKL */
2210                 do_rapl = RAPL_PKG | RAPL_DRAM | RAPL_DRAM_PERF_STATUS | RAPL_PKG_PERF_STATUS | RAPL_PKG_POWER_INFO;
2211                 break;
2212         case 0x3F:      /* HSX */
2213         case 0x4F:      /* BDX */
2214         case 0x56:      /* BDX-DE */
2215         case 0x57:      /* KNL */
2216                 do_rapl = RAPL_PKG | RAPL_DRAM | RAPL_DRAM_POWER_INFO | RAPL_DRAM_PERF_STATUS | RAPL_PKG_PERF_STATUS | RAPL_PKG_POWER_INFO;
2217                 break;
2218         case 0x2D:
2219         case 0x3E:
2220                 do_rapl = RAPL_PKG | RAPL_CORES | RAPL_CORE_POLICY | RAPL_DRAM | RAPL_DRAM_POWER_INFO | RAPL_PKG_PERF_STATUS | RAPL_DRAM_PERF_STATUS | RAPL_PKG_POWER_INFO;
2221                 break;
2222         case 0x37:      /* BYT */
2223         case 0x4D:      /* AVN */
2224                 do_rapl = RAPL_PKG | RAPL_CORES ;
2225                 break;
2226         default:
2227                 return;
2228         }
2229
2230         /* units on package 0, verify later other packages match */
2231         if (get_msr(base_cpu, MSR_RAPL_POWER_UNIT, &msr))
2232                 return;
2233
2234         rapl_power_units = 1.0 / (1 << (msr & 0xF));
2235         if (model == 0x37)
2236                 rapl_energy_units = 1.0 * (1 << (msr >> 8 & 0x1F)) / 1000000;
2237         else
2238                 rapl_energy_units = 1.0 / (1 << (msr >> 8 & 0x1F));
2239
2240         rapl_dram_energy_units = rapl_dram_energy_units_probe(model, rapl_energy_units);
2241
2242         time_unit = msr >> 16 & 0xF;
2243         if (time_unit == 0)
2244                 time_unit = 0xA;
2245
2246         rapl_time_units = 1.0 / (1 << (time_unit));
2247
2248         tdp = get_tdp(model);
2249
2250         rapl_joule_counter_range = 0xFFFFFFFF * rapl_energy_units / tdp;
2251         if (debug)
2252                 fprintf(stderr, "RAPL: %.0f sec. Joule Counter Range, at %.0f Watts\n", rapl_joule_counter_range, tdp);
2253
2254         return;
2255 }
2256
2257 void perf_limit_reasons_probe(family, model)
2258 {
2259         if (!genuine_intel)
2260                 return;
2261
2262         if (family != 6)
2263                 return;
2264
2265         switch (model) {
2266         case 0x3C:      /* HSW */
2267         case 0x45:      /* HSW */
2268         case 0x46:      /* HSW */
2269                 do_gfx_perf_limit_reasons = 1;
2270         case 0x3F:      /* HSX */
2271                 do_core_perf_limit_reasons = 1;
2272                 do_ring_perf_limit_reasons = 1;
2273         default:
2274                 return;
2275         }
2276 }
2277
2278 int print_thermal(struct thread_data *t, struct core_data *c, struct pkg_data *p)
2279 {
2280         unsigned long long msr;
2281         unsigned int dts;
2282         int cpu;
2283
2284         if (!(do_dts || do_ptm))
2285                 return 0;
2286
2287         cpu = t->cpu_id;
2288
2289         /* DTS is per-core, no need to print for each thread */
2290         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE)) 
2291                 return 0;
2292
2293         if (cpu_migrate(cpu)) {
2294                 fprintf(stderr, "Could not migrate to CPU %d\n", cpu);
2295                 return -1;
2296         }
2297
2298         if (do_ptm && (t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE)) {
2299                 if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_STATUS, &msr))
2300                         return 0;
2301
2302                 dts = (msr >> 16) & 0x7F;
2303                 fprintf(stderr, "cpu%d: MSR_IA32_PACKAGE_THERM_STATUS: 0x%08llx (%d C)\n",
2304                         cpu, msr, tcc_activation_temp - dts);
2305
2306 #ifdef  THERM_DEBUG
2307                 if (get_msr(cpu, MSR_IA32_PACKAGE_THERM_INTERRUPT, &msr))
2308                         return 0;
2309
2310                 dts = (msr >> 16) & 0x7F;
2311                 dts2 = (msr >> 8) & 0x7F;
2312                 fprintf(stderr, "cpu%d: MSR_IA32_PACKAGE_THERM_INTERRUPT: 0x%08llx (%d C, %d C)\n",
2313                         cpu, msr, tcc_activation_temp - dts, tcc_activation_temp - dts2);
2314 #endif
2315         }
2316
2317
2318         if (do_dts) {
2319                 unsigned int resolution;
2320
2321                 if (get_msr(cpu, MSR_IA32_THERM_STATUS, &msr))
2322                         return 0;
2323
2324                 dts = (msr >> 16) & 0x7F;
2325                 resolution = (msr >> 27) & 0xF;
2326                 fprintf(stderr, "cpu%d: MSR_IA32_THERM_STATUS: 0x%08llx (%d C +/- %d)\n",
2327                         cpu, msr, tcc_activation_temp - dts, resolution);
2328
2329 #ifdef THERM_DEBUG
2330                 if (get_msr(cpu, MSR_IA32_THERM_INTERRUPT, &msr))
2331                         return 0;
2332
2333                 dts = (msr >> 16) & 0x7F;
2334                 dts2 = (msr >> 8) & 0x7F;
2335                 fprintf(stderr, "cpu%d: MSR_IA32_THERM_INTERRUPT: 0x%08llx (%d C, %d C)\n",
2336                         cpu, msr, tcc_activation_temp - dts, tcc_activation_temp - dts2);
2337 #endif
2338         }
2339
2340         return 0;
2341 }
2342         
2343 void print_power_limit_msr(int cpu, unsigned long long msr, char *label)
2344 {
2345         fprintf(stderr, "cpu%d: %s: %sabled (%f Watts, %f sec, clamp %sabled)\n",
2346                 cpu, label,
2347                 ((msr >> 15) & 1) ? "EN" : "DIS",
2348                 ((msr >> 0) & 0x7FFF) * rapl_power_units,
2349                 (1.0 + (((msr >> 22) & 0x3)/4.0)) * (1 << ((msr >> 17) & 0x1F)) * rapl_time_units,
2350                 (((msr >> 16) & 1) ? "EN" : "DIS"));
2351
2352         return;
2353 }
2354
2355 int print_rapl(struct thread_data *t, struct core_data *c, struct pkg_data *p)
2356 {
2357         unsigned long long msr;
2358         int cpu;
2359
2360         if (!do_rapl)
2361                 return 0;
2362
2363         /* RAPL counters are per package, so print only for 1st thread/package */
2364         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
2365                 return 0;
2366
2367         cpu = t->cpu_id;
2368         if (cpu_migrate(cpu)) {
2369                 fprintf(stderr, "Could not migrate to CPU %d\n", cpu);
2370                 return -1;
2371         }
2372
2373         if (get_msr(cpu, MSR_RAPL_POWER_UNIT, &msr))
2374                 return -1;
2375
2376         if (debug) {
2377                 fprintf(stderr, "cpu%d: MSR_RAPL_POWER_UNIT: 0x%08llx "
2378                         "(%f Watts, %f Joules, %f sec.)\n", cpu, msr,
2379                         rapl_power_units, rapl_energy_units, rapl_time_units);
2380         }
2381         if (do_rapl & RAPL_PKG_POWER_INFO) {
2382
2383                 if (get_msr(cpu, MSR_PKG_POWER_INFO, &msr))
2384                         return -5;
2385
2386
2387                 fprintf(stderr, "cpu%d: MSR_PKG_POWER_INFO: 0x%08llx (%.0f W TDP, RAPL %.0f - %.0f W, %f sec.)\n",
2388                         cpu, msr,
2389                         ((msr >>  0) & RAPL_POWER_GRANULARITY) * rapl_power_units,
2390                         ((msr >> 16) & RAPL_POWER_GRANULARITY) * rapl_power_units,
2391                         ((msr >> 32) & RAPL_POWER_GRANULARITY) * rapl_power_units,
2392                         ((msr >> 48) & RAPL_TIME_GRANULARITY) * rapl_time_units);
2393
2394         }
2395         if (do_rapl & RAPL_PKG) {
2396
2397                 if (get_msr(cpu, MSR_PKG_POWER_LIMIT, &msr))
2398                         return -9;
2399
2400                 fprintf(stderr, "cpu%d: MSR_PKG_POWER_LIMIT: 0x%08llx (%slocked)\n",
2401                         cpu, msr, (msr >> 63) & 1 ? "": "UN");
2402
2403                 print_power_limit_msr(cpu, msr, "PKG Limit #1");
2404                 fprintf(stderr, "cpu%d: PKG Limit #2: %sabled (%f Watts, %f* sec, clamp %sabled)\n",
2405                         cpu,
2406                         ((msr >> 47) & 1) ? "EN" : "DIS",
2407                         ((msr >> 32) & 0x7FFF) * rapl_power_units,
2408                         (1.0 + (((msr >> 54) & 0x3)/4.0)) * (1 << ((msr >> 49) & 0x1F)) * rapl_time_units,
2409                         ((msr >> 48) & 1) ? "EN" : "DIS");
2410         }
2411
2412         if (do_rapl & RAPL_DRAM_POWER_INFO) {
2413                 if (get_msr(cpu, MSR_DRAM_POWER_INFO, &msr))
2414                         return -6;
2415
2416                 fprintf(stderr, "cpu%d: MSR_DRAM_POWER_INFO,: 0x%08llx (%.0f W TDP, RAPL %.0f - %.0f W, %f sec.)\n",
2417                         cpu, msr,
2418                         ((msr >>  0) & RAPL_POWER_GRANULARITY) * rapl_power_units,
2419                         ((msr >> 16) & RAPL_POWER_GRANULARITY) * rapl_power_units,
2420                         ((msr >> 32) & RAPL_POWER_GRANULARITY) * rapl_power_units,
2421                         ((msr >> 48) & RAPL_TIME_GRANULARITY) * rapl_time_units);
2422         }
2423         if (do_rapl & RAPL_DRAM) {
2424                 if (get_msr(cpu, MSR_DRAM_POWER_LIMIT, &msr))
2425                         return -9;
2426                 fprintf(stderr, "cpu%d: MSR_DRAM_POWER_LIMIT: 0x%08llx (%slocked)\n",
2427                                 cpu, msr, (msr >> 31) & 1 ? "": "UN");
2428
2429                 print_power_limit_msr(cpu, msr, "DRAM Limit");
2430         }
2431         if (do_rapl & RAPL_CORE_POLICY) {
2432                 if (debug) {
2433                         if (get_msr(cpu, MSR_PP0_POLICY, &msr))
2434                                 return -7;
2435
2436                         fprintf(stderr, "cpu%d: MSR_PP0_POLICY: %lld\n", cpu, msr & 0xF);
2437                 }
2438         }
2439         if (do_rapl & RAPL_CORES) {
2440                 if (debug) {
2441
2442                         if (get_msr(cpu, MSR_PP0_POWER_LIMIT, &msr))
2443                                 return -9;
2444                         fprintf(stderr, "cpu%d: MSR_PP0_POWER_LIMIT: 0x%08llx (%slocked)\n",
2445                                         cpu, msr, (msr >> 31) & 1 ? "": "UN");
2446                         print_power_limit_msr(cpu, msr, "Cores Limit");
2447                 }
2448         }
2449         if (do_rapl & RAPL_GFX) {
2450                 if (debug) {
2451                         if (get_msr(cpu, MSR_PP1_POLICY, &msr))
2452                                 return -8;
2453
2454                         fprintf(stderr, "cpu%d: MSR_PP1_POLICY: %lld\n", cpu, msr & 0xF);
2455
2456                         if (get_msr(cpu, MSR_PP1_POWER_LIMIT, &msr))
2457                                 return -9;
2458                         fprintf(stderr, "cpu%d: MSR_PP1_POWER_LIMIT: 0x%08llx (%slocked)\n",
2459                                         cpu, msr, (msr >> 31) & 1 ? "": "UN");
2460                         print_power_limit_msr(cpu, msr, "GFX Limit");
2461                 }
2462         }
2463         return 0;
2464 }
2465
2466 /*
2467  * SNB adds support for additional MSRs:
2468  *
2469  * MSR_PKG_C7_RESIDENCY            0x000003fa
2470  * MSR_CORE_C7_RESIDENCY           0x000003fe
2471  * MSR_PKG_C2_RESIDENCY            0x0000060d
2472  */
2473
2474 int has_snb_msrs(unsigned int family, unsigned int model)
2475 {
2476         if (!genuine_intel)
2477                 return 0;
2478
2479         switch (model) {
2480         case 0x2A:
2481         case 0x2D:
2482         case 0x3A:      /* IVB */
2483         case 0x3E:      /* IVB Xeon */
2484         case 0x3C:      /* HSW */
2485         case 0x3F:      /* HSW */
2486         case 0x45:      /* HSW */
2487         case 0x46:      /* HSW */
2488         case 0x3D:      /* BDW */
2489         case 0x47:      /* BDW */
2490         case 0x4F:      /* BDX */
2491         case 0x56:      /* BDX-DE */
2492         case 0x4E:      /* SKL */
2493         case 0x5E:      /* SKL */
2494                 return 1;
2495         }
2496         return 0;
2497 }
2498
2499 /*
2500  * HSW adds support for additional MSRs:
2501  *
2502  * MSR_PKG_C8_RESIDENCY            0x00000630
2503  * MSR_PKG_C9_RESIDENCY            0x00000631
2504  * MSR_PKG_C10_RESIDENCY           0x00000632
2505  */
2506 int has_hsw_msrs(unsigned int family, unsigned int model)
2507 {
2508         if (!genuine_intel)
2509                 return 0;
2510
2511         switch (model) {
2512         case 0x45:      /* HSW */
2513         case 0x3D:      /* BDW */
2514         case 0x4E:      /* SKL */
2515         case 0x5E:      /* SKL */
2516                 return 1;
2517         }
2518         return 0;
2519 }
2520
2521 /*
2522  * SKL adds support for additional MSRS:
2523  *
2524  * MSR_PKG_WEIGHTED_CORE_C0_RES    0x00000658
2525  * MSR_PKG_ANY_CORE_C0_RES         0x00000659
2526  * MSR_PKG_ANY_GFXE_C0_RES         0x0000065A
2527  * MSR_PKG_BOTH_CORE_GFXE_C0_RES   0x0000065B
2528  */
2529 int has_skl_msrs(unsigned int family, unsigned int model)
2530 {
2531         if (!genuine_intel)
2532                 return 0;
2533
2534         switch (model) {
2535         case 0x4E:      /* SKL */
2536         case 0x5E:      /* SKL */
2537                 return 1;
2538         }
2539         return 0;
2540 }
2541
2542
2543
2544 int is_slm(unsigned int family, unsigned int model)
2545 {
2546         if (!genuine_intel)
2547                 return 0;
2548         switch (model) {
2549         case 0x37:      /* BYT */
2550         case 0x4D:      /* AVN */
2551                 return 1;
2552         }
2553         return 0;
2554 }
2555
2556 int is_knl(unsigned int family, unsigned int model)
2557 {
2558         if (!genuine_intel)
2559                 return 0;
2560         switch (model) {
2561         case 0x57:      /* KNL */
2562                 return 1;
2563         }
2564         return 0;
2565 }
2566
2567 unsigned int get_aperf_mperf_multiplier(unsigned int family, unsigned int model)
2568 {
2569         if (is_knl(family, model))
2570                 return 1024;
2571         return 1;
2572 }
2573
2574 #define SLM_BCLK_FREQS 5
2575 double slm_freq_table[SLM_BCLK_FREQS] = { 83.3, 100.0, 133.3, 116.7, 80.0};
2576
2577 double slm_bclk(void)
2578 {
2579         unsigned long long msr = 3;
2580         unsigned int i;
2581         double freq;
2582
2583         if (get_msr(base_cpu, MSR_FSB_FREQ, &msr))
2584                 fprintf(stderr, "SLM BCLK: unknown\n");
2585
2586         i = msr & 0xf;
2587         if (i >= SLM_BCLK_FREQS) {
2588                 fprintf(stderr, "SLM BCLK[%d] invalid\n", i);
2589                 msr = 3;
2590         }
2591         freq = slm_freq_table[i];
2592
2593         fprintf(stderr, "SLM BCLK: %.1f Mhz\n", freq);
2594
2595         return freq;
2596 }
2597
2598 double discover_bclk(unsigned int family, unsigned int model)
2599 {
2600         if (has_snb_msrs(family, model))
2601                 return 100.00;
2602         else if (is_slm(family, model))
2603                 return slm_bclk();
2604         else
2605                 return 133.33;
2606 }
2607
2608 /*
2609  * MSR_IA32_TEMPERATURE_TARGET indicates the temperature where
2610  * the Thermal Control Circuit (TCC) activates.
2611  * This is usually equal to tjMax.
2612  *
2613  * Older processors do not have this MSR, so there we guess,
2614  * but also allow cmdline over-ride with -T.
2615  *
2616  * Several MSR temperature values are in units of degrees-C
2617  * below this value, including the Digital Thermal Sensor (DTS),
2618  * Package Thermal Management Sensor (PTM), and thermal event thresholds.
2619  */
2620 int set_temperature_target(struct thread_data *t, struct core_data *c, struct pkg_data *p)
2621 {
2622         unsigned long long msr;
2623         unsigned int target_c_local;
2624         int cpu;
2625
2626         /* tcc_activation_temp is used only for dts or ptm */
2627         if (!(do_dts || do_ptm))
2628                 return 0;
2629
2630         /* this is a per-package concept */
2631         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
2632                 return 0;
2633
2634         cpu = t->cpu_id;
2635         if (cpu_migrate(cpu)) {
2636                 fprintf(stderr, "Could not migrate to CPU %d\n", cpu);
2637                 return -1;
2638         }
2639
2640         if (tcc_activation_temp_override != 0) {
2641                 tcc_activation_temp = tcc_activation_temp_override;
2642                 fprintf(stderr, "cpu%d: Using cmdline TCC Target (%d C)\n",
2643                         cpu, tcc_activation_temp);
2644                 return 0;
2645         }
2646
2647         /* Temperature Target MSR is Nehalem and newer only */
2648         if (!do_nhm_platform_info)
2649                 goto guess;
2650
2651         if (get_msr(base_cpu, MSR_IA32_TEMPERATURE_TARGET, &msr))
2652                 goto guess;
2653
2654         target_c_local = (msr >> 16) & 0xFF;
2655
2656         if (debug)
2657                 fprintf(stderr, "cpu%d: MSR_IA32_TEMPERATURE_TARGET: 0x%08llx (%d C)\n",
2658                         cpu, msr, target_c_local);
2659
2660         if (!target_c_local)
2661                 goto guess;
2662
2663         tcc_activation_temp = target_c_local;
2664
2665         return 0;
2666
2667 guess:
2668         tcc_activation_temp = TJMAX_DEFAULT;
2669         fprintf(stderr, "cpu%d: Guessing tjMax %d C, Please use -T to specify\n",
2670                 cpu, tcc_activation_temp);
2671
2672         return 0;
2673 }
2674 void process_cpuid()
2675 {
2676         unsigned int eax, ebx, ecx, edx, max_level;
2677         unsigned int fms, family, model, stepping;
2678
2679         eax = ebx = ecx = edx = 0;
2680
2681         __get_cpuid(0, &max_level, &ebx, &ecx, &edx);
2682
2683         if (ebx == 0x756e6547 && edx == 0x49656e69 && ecx == 0x6c65746e)
2684                 genuine_intel = 1;
2685
2686         if (debug)
2687                 fprintf(stderr, "CPUID(0): %.4s%.4s%.4s ",
2688                         (char *)&ebx, (char *)&edx, (char *)&ecx);
2689
2690         __get_cpuid(1, &fms, &ebx, &ecx, &edx);
2691         family = (fms >> 8) & 0xf;
2692         model = (fms >> 4) & 0xf;
2693         stepping = fms & 0xf;
2694         if (family == 6 || family == 0xf)
2695                 model += ((fms >> 16) & 0xf) << 4;
2696
2697         if (debug)
2698                 fprintf(stderr, "%d CPUID levels; family:model:stepping 0x%x:%x:%x (%d:%d:%d)\n",
2699                         max_level, family, model, stepping, family, model, stepping);
2700
2701         if (!(edx & (1 << 5)))
2702                 errx(1, "CPUID: no MSR");
2703
2704         /*
2705          * check max extended function levels of CPUID.
2706          * This is needed to check for invariant TSC.
2707          * This check is valid for both Intel and AMD.
2708          */
2709         ebx = ecx = edx = 0;
2710         __get_cpuid(0x80000000, &max_level, &ebx, &ecx, &edx);
2711
2712         if (max_level >= 0x80000007) {
2713
2714                 /*
2715                  * Non-Stop TSC is advertised by CPUID.EAX=0x80000007: EDX.bit8
2716                  * this check is valid for both Intel and AMD
2717                  */
2718                 __get_cpuid(0x80000007, &eax, &ebx, &ecx, &edx);
2719                 has_invariant_tsc = edx & (1 << 8);
2720         }
2721
2722         /*
2723          * APERF/MPERF is advertised by CPUID.EAX=0x6: ECX.bit0
2724          * this check is valid for both Intel and AMD
2725          */
2726
2727         __get_cpuid(0x6, &eax, &ebx, &ecx, &edx);
2728         has_aperf = ecx & (1 << 0);
2729         do_dts = eax & (1 << 0);
2730         do_ptm = eax & (1 << 6);
2731         has_epb = ecx & (1 << 3);
2732
2733         if (debug)
2734                 fprintf(stderr, "CPUID(6): %sAPERF, %sDTS, %sPTM, %sEPB\n",
2735                         has_aperf ? "" : "No ",
2736                         do_dts ? "" : "No ",
2737                         do_ptm ? "" : "No ",
2738                         has_epb ? "" : "No ");
2739
2740         if (max_level > 0x15) {
2741                 unsigned int eax_crystal;
2742                 unsigned int ebx_tsc;
2743
2744                 /*
2745                  * CPUID 15H TSC/Crystal ratio, possibly Crystal Hz
2746                  */
2747                 eax_crystal = ebx_tsc = crystal_hz = edx = 0;
2748                 __get_cpuid(0x15, &eax_crystal, &ebx_tsc, &crystal_hz, &edx);
2749
2750                 if (ebx_tsc != 0) {
2751
2752                         if (debug && (ebx != 0))
2753                                 fprintf(stderr, "CPUID(0x15): eax_crystal: %d ebx_tsc: %d ecx_crystal_hz: %d\n",
2754                                         eax_crystal, ebx_tsc, crystal_hz);
2755
2756                         if (crystal_hz == 0)
2757                                 switch(model) {
2758                                 case 0x4E:      /* SKL */
2759                                 case 0x5E:      /* SKL */
2760                                         crystal_hz = 24000000;  /* 24 MHz */
2761                                         break;
2762                                 default:
2763                                         crystal_hz = 0;
2764                         }
2765
2766                         if (crystal_hz) {
2767                                 tsc_hz =  (unsigned long long) crystal_hz * ebx_tsc / eax_crystal;
2768                                 if (debug)
2769                                         fprintf(stderr, "TSC: %lld MHz (%d Hz * %d / %d / 1000000)\n",
2770                                                 tsc_hz / 1000000, crystal_hz, ebx_tsc,  eax_crystal);
2771                         }
2772                 }
2773         }
2774
2775         if (has_aperf)
2776                 aperf_mperf_multiplier = get_aperf_mperf_multiplier(family, model);
2777
2778         do_nhm_platform_info = do_nhm_cstates = do_smi = probe_nhm_msrs(family, model);
2779         do_snb_cstates = has_snb_msrs(family, model);
2780         do_pc2 = do_snb_cstates && (pkg_cstate_limit >= PCL__2);
2781         do_pc3 = (pkg_cstate_limit >= PCL__3);
2782         do_pc6 = (pkg_cstate_limit >= PCL__6);
2783         do_pc7 = do_snb_cstates && (pkg_cstate_limit >= PCL__7);
2784         do_c8_c9_c10 = has_hsw_msrs(family, model);
2785         do_skl_residency = has_skl_msrs(family, model);
2786         do_slm_cstates = is_slm(family, model);
2787         do_knl_cstates  = is_knl(family, model);
2788
2789         rapl_probe(family, model);
2790         perf_limit_reasons_probe(family, model);
2791
2792         if (debug)
2793                 dump_cstate_pstate_config_info();
2794
2795         if (has_skl_msrs(family, model))
2796                 calculate_tsc_tweak();
2797
2798         return;
2799 }
2800
2801 void help()
2802 {
2803         fprintf(stderr,
2804         "Usage: turbostat [OPTIONS][(--interval seconds) | COMMAND ...]\n"
2805         "\n"
2806         "Turbostat forks the specified COMMAND and prints statistics\n"
2807         "when COMMAND completes.\n"
2808         "If no COMMAND is specified, turbostat wakes every 5-seconds\n"
2809         "to print statistics, until interrupted.\n"
2810         "--debug        run in \"debug\" mode\n"
2811         "--interval sec Override default 5-second measurement interval\n"
2812         "--help         print this help message\n"
2813         "--counter msr  print 32-bit counter at address \"msr\"\n"
2814         "--Counter msr  print 64-bit Counter at address \"msr\"\n"
2815         "--msr msr      print 32-bit value at address \"msr\"\n"
2816         "--MSR msr      print 64-bit Value at address \"msr\"\n"
2817         "--version      print version information\n"
2818         "\n"
2819         "For more help, run \"man turbostat\"\n");
2820 }
2821
2822
2823 /*
2824  * in /dev/cpu/ return success for names that are numbers
2825  * ie. filter out ".", "..", "microcode".
2826  */
2827 int dir_filter(const struct dirent *dirp)
2828 {
2829         if (isdigit(dirp->d_name[0]))
2830                 return 1;
2831         else
2832                 return 0;
2833 }
2834
2835 int open_dev_cpu_msr(int dummy1)
2836 {
2837         return 0;
2838 }
2839
2840 void topology_probe()
2841 {
2842         int i;
2843         int max_core_id = 0;
2844         int max_package_id = 0;
2845         int max_siblings = 0;
2846         struct cpu_topology {
2847                 int core_id;
2848                 int physical_package_id;
2849         } *cpus;
2850
2851         /* Initialize num_cpus, max_cpu_num */
2852         topo.num_cpus = 0;
2853         topo.max_cpu_num = 0;
2854         for_all_proc_cpus(count_cpus);
2855         if (!summary_only && topo.num_cpus > 1)
2856                 show_cpu = 1;
2857
2858         if (debug > 1)
2859                 fprintf(stderr, "num_cpus %d max_cpu_num %d\n", topo.num_cpus, topo.max_cpu_num);
2860
2861         cpus = calloc(1, (topo.max_cpu_num  + 1) * sizeof(struct cpu_topology));
2862         if (cpus == NULL)
2863                 err(1, "calloc cpus");
2864
2865         /*
2866          * Allocate and initialize cpu_present_set
2867          */
2868         cpu_present_set = CPU_ALLOC((topo.max_cpu_num + 1));
2869         if (cpu_present_set == NULL)
2870                 err(3, "CPU_ALLOC");
2871         cpu_present_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
2872         CPU_ZERO_S(cpu_present_setsize, cpu_present_set);
2873         for_all_proc_cpus(mark_cpu_present);
2874
2875         /*
2876          * Allocate and initialize cpu_affinity_set
2877          */
2878         cpu_affinity_set = CPU_ALLOC((topo.max_cpu_num + 1));
2879         if (cpu_affinity_set == NULL)
2880                 err(3, "CPU_ALLOC");
2881         cpu_affinity_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
2882         CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
2883
2884
2885         /*
2886          * For online cpus
2887          * find max_core_id, max_package_id
2888          */
2889         for (i = 0; i <= topo.max_cpu_num; ++i) {
2890                 int siblings;
2891
2892                 if (cpu_is_not_present(i)) {
2893                         if (debug > 1)
2894                                 fprintf(stderr, "cpu%d NOT PRESENT\n", i);
2895                         continue;
2896                 }
2897                 cpus[i].core_id = get_core_id(i);
2898                 if (cpus[i].core_id > max_core_id)
2899                         max_core_id = cpus[i].core_id;
2900
2901                 cpus[i].physical_package_id = get_physical_package_id(i);
2902                 if (cpus[i].physical_package_id > max_package_id)
2903                         max_package_id = cpus[i].physical_package_id;
2904
2905                 siblings = get_num_ht_siblings(i);
2906                 if (siblings > max_siblings)
2907                         max_siblings = siblings;
2908                 if (debug > 1)
2909                         fprintf(stderr, "cpu %d pkg %d core %d\n",
2910                                 i, cpus[i].physical_package_id, cpus[i].core_id);
2911         }
2912         topo.num_cores_per_pkg = max_core_id + 1;
2913         if (debug > 1)
2914                 fprintf(stderr, "max_core_id %d, sizing for %d cores per package\n",
2915                         max_core_id, topo.num_cores_per_pkg);
2916         if (debug && !summary_only && topo.num_cores_per_pkg > 1)
2917                 show_core = 1;
2918
2919         topo.num_packages = max_package_id + 1;
2920         if (debug > 1)
2921                 fprintf(stderr, "max_package_id %d, sizing for %d packages\n",
2922                         max_package_id, topo.num_packages);
2923         if (debug && !summary_only && topo.num_packages > 1)
2924                 show_pkg = 1;
2925
2926         topo.num_threads_per_core = max_siblings;
2927         if (debug > 1)
2928                 fprintf(stderr, "max_siblings %d\n", max_siblings);
2929
2930         free(cpus);
2931 }
2932
2933 void
2934 allocate_counters(struct thread_data **t, struct core_data **c, struct pkg_data **p)
2935 {
2936         int i;
2937
2938         *t = calloc(topo.num_threads_per_core * topo.num_cores_per_pkg *
2939                 topo.num_packages, sizeof(struct thread_data));
2940         if (*t == NULL)
2941                 goto error;
2942
2943         for (i = 0; i < topo.num_threads_per_core *
2944                 topo.num_cores_per_pkg * topo.num_packages; i++)
2945                 (*t)[i].cpu_id = -1;
2946
2947         *c = calloc(topo.num_cores_per_pkg * topo.num_packages,
2948                 sizeof(struct core_data));
2949         if (*c == NULL)
2950                 goto error;
2951
2952         for (i = 0; i < topo.num_cores_per_pkg * topo.num_packages; i++)
2953                 (*c)[i].core_id = -1;
2954
2955         *p = calloc(topo.num_packages, sizeof(struct pkg_data));
2956         if (*p == NULL)
2957                 goto error;
2958
2959         for (i = 0; i < topo.num_packages; i++)
2960                 (*p)[i].package_id = i;
2961
2962         return;
2963 error:
2964         err(1, "calloc counters");
2965 }
2966 /*
2967  * init_counter()
2968  *
2969  * set cpu_id, core_num, pkg_num
2970  * set FIRST_THREAD_IN_CORE and FIRST_CORE_IN_PACKAGE
2971  *
2972  * increment topo.num_cores when 1st core in pkg seen
2973  */
2974 void init_counter(struct thread_data *thread_base, struct core_data *core_base,
2975         struct pkg_data *pkg_base, int thread_num, int core_num,
2976         int pkg_num, int cpu_id)
2977 {
2978         struct thread_data *t;
2979         struct core_data *c;
2980         struct pkg_data *p;
2981
2982         t = GET_THREAD(thread_base, thread_num, core_num, pkg_num);
2983         c = GET_CORE(core_base, core_num, pkg_num);
2984         p = GET_PKG(pkg_base, pkg_num);
2985
2986         t->cpu_id = cpu_id;
2987         if (thread_num == 0) {
2988                 t->flags |= CPU_IS_FIRST_THREAD_IN_CORE;
2989                 if (cpu_is_first_core_in_package(cpu_id))
2990                         t->flags |= CPU_IS_FIRST_CORE_IN_PACKAGE;
2991         }
2992
2993         c->core_id = core_num;
2994         p->package_id = pkg_num;
2995 }
2996
2997
2998 int initialize_counters(int cpu_id)
2999 {
3000         int my_thread_id, my_core_id, my_package_id;
3001
3002         my_package_id = get_physical_package_id(cpu_id);
3003         my_core_id = get_core_id(cpu_id);
3004         my_thread_id = get_cpu_position_in_core(cpu_id);
3005         if (!my_thread_id)
3006                 topo.num_cores++;
3007
3008         init_counter(EVEN_COUNTERS, my_thread_id, my_core_id, my_package_id, cpu_id);
3009         init_counter(ODD_COUNTERS, my_thread_id, my_core_id, my_package_id, cpu_id);
3010         return 0;
3011 }
3012
3013 void allocate_output_buffer()
3014 {
3015         output_buffer = calloc(1, (1 + topo.num_cpus) * 1024);
3016         outp = output_buffer;
3017         if (outp == NULL)
3018                 err(-1, "calloc output buffer");
3019 }
3020
3021 void setup_all_buffers(void)
3022 {
3023         topology_probe();
3024         allocate_counters(&thread_even, &core_even, &package_even);
3025         allocate_counters(&thread_odd, &core_odd, &package_odd);
3026         allocate_output_buffer();
3027         for_all_proc_cpus(initialize_counters);
3028 }
3029
3030 void set_base_cpu(void)
3031 {
3032         base_cpu = sched_getcpu();
3033         if (base_cpu < 0)
3034                 err(-ENODEV, "No valid cpus found");
3035
3036         if (debug > 1)
3037                 fprintf(stderr, "base_cpu = %d\n", base_cpu);
3038 }
3039
3040 void turbostat_init()
3041 {
3042         setup_all_buffers();
3043         set_base_cpu();
3044         check_dev_msr();
3045         check_permissions();
3046         process_cpuid();
3047
3048
3049         if (debug)
3050                 for_all_cpus(print_epb, ODD_COUNTERS);
3051
3052         if (debug)
3053                 for_all_cpus(print_perf_limit, ODD_COUNTERS);
3054
3055         if (debug)
3056                 for_all_cpus(print_rapl, ODD_COUNTERS);
3057
3058         for_all_cpus(set_temperature_target, ODD_COUNTERS);
3059
3060         if (debug)
3061                 for_all_cpus(print_thermal, ODD_COUNTERS);
3062 }
3063
3064 int fork_it(char **argv)
3065 {
3066         pid_t child_pid;
3067         int status;
3068
3069         status = for_all_cpus(get_counters, EVEN_COUNTERS);
3070         if (status)
3071                 exit(status);
3072         /* clear affinity side-effect of get_counters() */
3073         sched_setaffinity(0, cpu_present_setsize, cpu_present_set);
3074         gettimeofday(&tv_even, (struct timezone *)NULL);
3075
3076         child_pid = fork();
3077         if (!child_pid) {
3078                 /* child */
3079                 execvp(argv[0], argv);
3080         } else {
3081
3082                 /* parent */
3083                 if (child_pid == -1)
3084                         err(1, "fork");
3085
3086                 signal(SIGINT, SIG_IGN);
3087                 signal(SIGQUIT, SIG_IGN);
3088                 if (waitpid(child_pid, &status, 0) == -1)
3089                         err(status, "waitpid");
3090         }
3091         /*
3092          * n.b. fork_it() does not check for errors from for_all_cpus()
3093          * because re-starting is problematic when forking
3094          */
3095         for_all_cpus(get_counters, ODD_COUNTERS);
3096         gettimeofday(&tv_odd, (struct timezone *)NULL);
3097         timersub(&tv_odd, &tv_even, &tv_delta);
3098         for_all_cpus_2(delta_cpu, ODD_COUNTERS, EVEN_COUNTERS);
3099         compute_average(EVEN_COUNTERS);
3100         format_all_counters(EVEN_COUNTERS);
3101         flush_stderr();
3102
3103         fprintf(stderr, "%.6f sec\n", tv_delta.tv_sec + tv_delta.tv_usec/1000000.0);
3104
3105         return status;
3106 }
3107
3108 int get_and_dump_counters(void)
3109 {
3110         int status;
3111
3112         status = for_all_cpus(get_counters, ODD_COUNTERS);
3113         if (status)
3114                 return status;
3115
3116         status = for_all_cpus(dump_counters, ODD_COUNTERS);
3117         if (status)
3118                 return status;
3119
3120         flush_stdout();
3121
3122         return status;
3123 }
3124
3125 void print_version() {
3126         fprintf(stderr, "turbostat version 4.8 26-Sep, 2015"
3127                 " - Len Brown <lenb@kernel.org>\n");
3128 }
3129
3130 void cmdline(int argc, char **argv)
3131 {
3132         int opt;
3133         int option_index = 0;
3134         static struct option long_options[] = {
3135                 {"Counter",     required_argument,      0, 'C'},
3136                 {"counter",     required_argument,      0, 'c'},
3137                 {"Dump",        no_argument,            0, 'D'},
3138                 {"debug",       no_argument,            0, 'd'},
3139                 {"interval",    required_argument,      0, 'i'},
3140                 {"help",        no_argument,            0, 'h'},
3141                 {"Joules",      no_argument,            0, 'J'},
3142                 {"MSR",         required_argument,      0, 'M'},
3143                 {"msr",         required_argument,      0, 'm'},
3144                 {"Package",     no_argument,            0, 'p'},
3145                 {"processor",   no_argument,            0, 'p'},
3146                 {"Summary",     no_argument,            0, 'S'},
3147                 {"TCC",         required_argument,      0, 'T'},
3148                 {"version",     no_argument,            0, 'v' },
3149                 {0,             0,                      0,  0 }
3150         };
3151
3152         progname = argv[0];
3153
3154         while ((opt = getopt_long_only(argc, argv, "+C:c:Ddhi:JM:m:PpST:v",
3155                                 long_options, &option_index)) != -1) {
3156                 switch (opt) {
3157                 case 'C':
3158                         sscanf(optarg, "%x", &extra_delta_offset64);
3159                         break;
3160                 case 'c':
3161                         sscanf(optarg, "%x", &extra_delta_offset32);
3162                         break;
3163                 case 'D':
3164                         dump_only++;
3165                         break;
3166                 case 'd':
3167                         debug++;
3168                         break;
3169                 case 'h':
3170                 default:
3171                         help();
3172                         exit(1);
3173                 case 'i':
3174                         interval_sec = atoi(optarg);
3175                         break;
3176                 case 'J':
3177                         rapl_joules++;
3178                         break;
3179                 case 'M':
3180                         sscanf(optarg, "%x", &extra_msr_offset64);
3181                         break;
3182                 case 'm':
3183                         sscanf(optarg, "%x", &extra_msr_offset32);
3184                         break;
3185                 case 'P':
3186                         show_pkg_only++;
3187                         break;
3188                 case 'p':
3189                         show_core_only++;
3190                         break;
3191                 case 'S':
3192                         summary_only++;
3193                         break;
3194                 case 'T':
3195                         tcc_activation_temp_override = atoi(optarg);
3196                         break;
3197                 case 'v':
3198                         print_version();
3199                         exit(0);
3200                         break;
3201                 }
3202         }
3203 }
3204
3205 int main(int argc, char **argv)
3206 {
3207         cmdline(argc, argv);
3208
3209         if (debug)
3210                 print_version();
3211
3212         turbostat_init();
3213
3214         /* dump counters and exit */
3215         if (dump_only)
3216                 return get_and_dump_counters();
3217
3218         /*
3219          * if any params left, it must be a command to fork
3220          */
3221         if (argc - optind)
3222                 return fork_it(argv + optind);
3223         else
3224                 turbostat_loop();
3225
3226         return 0;
3227 }