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