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