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