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