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