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