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