]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - tools/power/x86/turbostat/turbostat.c
3c063a00f3bf46f214b94fb8e5c30d525cb6dfe7
[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) 2012 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 summary_only;      /* set with -s */
43 unsigned int skip_c0;
44 unsigned int skip_c1;
45 unsigned int do_nhm_cstates;
46 unsigned int do_snb_cstates;
47 unsigned int has_aperf;
48 unsigned int units = 1000000000;        /* Ghz etc */
49 unsigned int genuine_intel;
50 unsigned int has_invariant_tsc;
51 unsigned int do_nehalem_platform_info;
52 unsigned int do_nehalem_turbo_ratio_limit;
53 unsigned int do_ivt_turbo_ratio_limit;
54 unsigned int extra_msr_offset32;
55 unsigned int extra_msr_offset64;
56 unsigned int extra_delta_offset32;
57 unsigned int extra_delta_offset64;
58 double bclk;
59 unsigned int show_pkg;
60 unsigned int show_core;
61 unsigned int show_cpu;
62 unsigned int show_pkg_only;
63 unsigned int show_core_only;
64 char *output_buffer, *outp;
65
66 int aperf_mperf_unstable;
67 int backwards_count;
68 char *progname;
69
70 cpu_set_t *cpu_present_set, *cpu_affinity_set;
71 size_t cpu_present_setsize, cpu_affinity_setsize;
72
73 struct thread_data {
74         unsigned long long tsc;
75         unsigned long long aperf;
76         unsigned long long mperf;
77         unsigned long long c1;  /* derived */
78         unsigned long long extra_msr64;
79         unsigned long long extra_delta64;
80         unsigned long long extra_msr32;
81         unsigned long long extra_delta32;
82         unsigned int cpu_id;
83         unsigned int flags;
84 #define CPU_IS_FIRST_THREAD_IN_CORE     0x2
85 #define CPU_IS_FIRST_CORE_IN_PACKAGE    0x4
86 } *thread_even, *thread_odd;
87
88 struct core_data {
89         unsigned long long c3;
90         unsigned long long c6;
91         unsigned long long c7;
92         unsigned int core_id;
93 } *core_even, *core_odd;
94
95 struct pkg_data {
96         unsigned long long pc2;
97         unsigned long long pc3;
98         unsigned long long pc6;
99         unsigned long long pc7;
100         unsigned int package_id;
101 } *package_even, *package_odd;
102
103 #define ODD_COUNTERS thread_odd, core_odd, package_odd
104 #define EVEN_COUNTERS thread_even, core_even, package_even
105
106 #define GET_THREAD(thread_base, thread_no, core_no, pkg_no) \
107         (thread_base + (pkg_no) * topo.num_cores_per_pkg * \
108                 topo.num_threads_per_core + \
109                 (core_no) * topo.num_threads_per_core + (thread_no))
110 #define GET_CORE(core_base, core_no, pkg_no) \
111         (core_base + (pkg_no) * topo.num_cores_per_pkg + (core_no))
112 #define GET_PKG(pkg_base, pkg_no) (pkg_base + pkg_no)
113
114 struct system_summary {
115         struct thread_data threads;
116         struct core_data cores;
117         struct pkg_data packages;
118 } sum, average;
119
120
121 struct topo_params {
122         int num_packages;
123         int num_cpus;
124         int num_cores;
125         int max_cpu_num;
126         int num_cores_per_pkg;
127         int num_threads_per_core;
128 } topo;
129
130 struct timeval tv_even, tv_odd, tv_delta;
131
132 void setup_all_buffers(void);
133
134 int cpu_is_not_present(int cpu)
135 {
136         return !CPU_ISSET_S(cpu, cpu_present_setsize, cpu_present_set);
137 }
138 /*
139  * run func(thread, core, package) in topology order
140  * skip non-present cpus
141  */
142
143 int for_all_cpus(int (func)(struct thread_data *, struct core_data *, struct pkg_data *),
144         struct thread_data *thread_base, struct core_data *core_base, struct pkg_data *pkg_base)
145 {
146         int retval, pkg_no, core_no, thread_no;
147
148         for (pkg_no = 0; pkg_no < topo.num_packages; ++pkg_no) {
149                 for (core_no = 0; core_no < topo.num_cores_per_pkg; ++core_no) {
150                         for (thread_no = 0; thread_no <
151                                 topo.num_threads_per_core; ++thread_no) {
152                                 struct thread_data *t;
153                                 struct core_data *c;
154                                 struct pkg_data *p;
155
156                                 t = GET_THREAD(thread_base, thread_no, core_no, pkg_no);
157
158                                 if (cpu_is_not_present(t->cpu_id))
159                                         continue;
160
161                                 c = GET_CORE(core_base, core_no, pkg_no);
162                                 p = GET_PKG(pkg_base, pkg_no);
163
164                                 retval = func(t, c, p);
165                                 if (retval)
166                                         return retval;
167                         }
168                 }
169         }
170         return 0;
171 }
172
173 int cpu_migrate(int cpu)
174 {
175         CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
176         CPU_SET_S(cpu, cpu_affinity_setsize, cpu_affinity_set);
177         if (sched_setaffinity(0, cpu_affinity_setsize, cpu_affinity_set) == -1)
178                 return -1;
179         else
180                 return 0;
181 }
182
183 int get_msr(int cpu, off_t offset, unsigned long long *msr)
184 {
185         ssize_t retval;
186         char pathname[32];
187         int fd;
188
189         sprintf(pathname, "/dev/cpu/%d/msr", cpu);
190         fd = open(pathname, O_RDONLY);
191         if (fd < 0)
192                 return -1;
193
194         retval = pread(fd, msr, sizeof *msr, offset);
195         close(fd);
196
197         if (retval != sizeof *msr) {
198                 fprintf(stderr, "%s offset 0x%zx read failed\n", pathname, offset);
199                 return -1;
200         }
201
202         return 0;
203 }
204
205 void print_header(void)
206 {
207         if (show_pkg)
208                 outp += sprintf(outp, "pk");
209         if (show_pkg)
210                 outp += sprintf(outp, " ");
211         if (show_core)
212                 outp += sprintf(outp, "cor");
213         if (show_cpu)
214                 outp += sprintf(outp, " CPU");
215         if (show_pkg || show_core || show_cpu)
216                 outp += sprintf(outp, " ");
217         if (do_nhm_cstates)
218                 outp += sprintf(outp, "   %%c0");
219         if (has_aperf)
220                 outp += sprintf(outp, "  GHz");
221         outp += sprintf(outp, "  TSC");
222         if (extra_delta_offset32)
223                 outp += sprintf(outp, "  count 0x%03X", extra_delta_offset32);
224         if (extra_delta_offset64)
225                 outp += sprintf(outp, "  COUNT 0x%03X", extra_delta_offset64);
226         if (extra_msr_offset32)
227                 outp += sprintf(outp, "   MSR 0x%03X", extra_msr_offset32);
228         if (extra_msr_offset64)
229                 outp += sprintf(outp, "           MSR 0x%03X", extra_msr_offset64);
230         if (do_nhm_cstates)
231                 outp += sprintf(outp, "    %%c1");
232         if (do_nhm_cstates)
233                 outp += sprintf(outp, "    %%c3");
234         if (do_nhm_cstates)
235                 outp += sprintf(outp, "    %%c6");
236         if (do_snb_cstates)
237                 outp += sprintf(outp, "    %%c7");
238         if (do_snb_cstates)
239                 outp += sprintf(outp, "   %%pc2");
240         if (do_nhm_cstates)
241                 outp += sprintf(outp, "   %%pc3");
242         if (do_nhm_cstates)
243                 outp += sprintf(outp, "   %%pc6");
244         if (do_snb_cstates)
245                 outp += sprintf(outp, "   %%pc7");
246
247         outp += sprintf(outp, "\n");
248 }
249
250 int dump_counters(struct thread_data *t, struct core_data *c,
251         struct pkg_data *p)
252 {
253         fprintf(stderr, "t %p, c %p, p %p\n", t, c, p);
254
255         if (t) {
256                 fprintf(stderr, "CPU: %d flags 0x%x\n", t->cpu_id, t->flags);
257                 fprintf(stderr, "TSC: %016llX\n", t->tsc);
258                 fprintf(stderr, "aperf: %016llX\n", t->aperf);
259                 fprintf(stderr, "mperf: %016llX\n", t->mperf);
260                 fprintf(stderr, "c1: %016llX\n", t->c1);
261                 fprintf(stderr, "msr0x%x: %08llX\n",
262                         extra_delta_offset32, t->extra_delta32);
263                 fprintf(stderr, "msr0x%x: %016llX\n",
264                         extra_delta_offset64, t->extra_delta64);
265                 fprintf(stderr, "msr0x%x: %08llX\n",
266                         extra_msr_offset32, t->extra_msr32);
267                 fprintf(stderr, "msr0x%x: %016llX\n",
268                         extra_msr_offset64, t->extra_msr64);
269         }
270
271         if (c) {
272                 fprintf(stderr, "core: %d\n", c->core_id);
273                 fprintf(stderr, "c3: %016llX\n", c->c3);
274                 fprintf(stderr, "c6: %016llX\n", c->c6);
275                 fprintf(stderr, "c7: %016llX\n", c->c7);
276         }
277
278         if (p) {
279                 fprintf(stderr, "package: %d\n", p->package_id);
280                 fprintf(stderr, "pc2: %016llX\n", p->pc2);
281                 fprintf(stderr, "pc3: %016llX\n", p->pc3);
282                 fprintf(stderr, "pc6: %016llX\n", p->pc6);
283                 fprintf(stderr, "pc7: %016llX\n", p->pc7);
284         }
285         return 0;
286 }
287
288 /*
289  * column formatting convention & formats
290  * package: "pk" 2 columns %2d
291  * core: "cor" 3 columns %3d
292  * CPU: "CPU" 3 columns %3d
293  * GHz: "GHz" 3 columns %3.2
294  * TSC: "TSC" 3 columns %3.2
295  * percentage " %pc3" %6.2
296  */
297 int format_counters(struct thread_data *t, struct core_data *c,
298         struct pkg_data *p)
299 {
300         double interval_float;
301
302          /* if showing only 1st thread in core and this isn't one, bail out */
303         if (show_core_only && !(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
304                 return 0;
305
306          /* if showing only 1st thread in pkg and this isn't one, bail out */
307         if (show_pkg_only && !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
308                 return 0;
309
310         interval_float = tv_delta.tv_sec + tv_delta.tv_usec/1000000.0;
311
312         /* topo columns, print blanks on 1st (average) line */
313         if (t == &average.threads) {
314                 if (show_pkg)
315                         outp += sprintf(outp, "  ");
316                 if (show_pkg && show_core)
317                         outp += sprintf(outp, " ");
318                 if (show_core)
319                         outp += sprintf(outp, "   ");
320                 if (show_cpu)
321                         outp += sprintf(outp, " " "   ");
322         } else {
323                 if (show_pkg) {
324                         if (p)
325                                 outp += sprintf(outp, "%2d", p->package_id);
326                         else
327                                 outp += sprintf(outp, "  ");
328                 }
329                 if (show_pkg && show_core)
330                         outp += sprintf(outp, " ");
331                 if (show_core) {
332                         if (c)
333                                 outp += sprintf(outp, "%3d", c->core_id);
334                         else
335                                 outp += sprintf(outp, "   ");
336                 }
337                 if (show_cpu)
338                         outp += sprintf(outp, " %3d", t->cpu_id);
339         }
340
341         /* %c0 */
342         if (do_nhm_cstates) {
343                 if (show_pkg || show_core || show_cpu)
344                         outp += sprintf(outp, " ");
345                 if (!skip_c0)
346                         outp += sprintf(outp, "%6.2f", 100.0 * t->mperf/t->tsc);
347                 else
348                         outp += sprintf(outp, "  ****");
349         }
350
351         /* GHz */
352         if (has_aperf) {
353                 if (!aperf_mperf_unstable) {
354                         outp += sprintf(outp, " %3.2f",
355                                 1.0 * t->tsc / units * t->aperf /
356                                 t->mperf / interval_float);
357                 } else {
358                         if (t->aperf > t->tsc || t->mperf > t->tsc) {
359                                 outp += sprintf(outp, " ***");
360                         } else {
361                                 outp += sprintf(outp, "%3.1f*",
362                                         1.0 * t->tsc /
363                                         units * t->aperf /
364                                         t->mperf / interval_float);
365                         }
366                 }
367         }
368
369         /* TSC */
370         outp += sprintf(outp, "%5.2f", 1.0 * t->tsc/units/interval_float);
371
372         /* delta */
373         if (extra_delta_offset32)
374                 outp += sprintf(outp, "  %11llu", t->extra_delta32);
375
376         /* DELTA */
377         if (extra_delta_offset64)
378                 outp += sprintf(outp, "  %11llu", t->extra_delta64);
379         /* msr */
380         if (extra_msr_offset32)
381                 outp += sprintf(outp, "  0x%08llx", t->extra_msr32);
382
383         /* MSR */
384         if (extra_msr_offset64)
385                 outp += sprintf(outp, "  0x%016llx", t->extra_msr64);
386
387         if (do_nhm_cstates) {
388                 if (!skip_c1)
389                         outp += sprintf(outp, " %6.2f", 100.0 * t->c1/t->tsc);
390                 else
391                         outp += sprintf(outp, "  ****");
392         }
393
394         /* print per-core data only for 1st thread in core */
395         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
396                 goto done;
397
398         if (do_nhm_cstates)
399                 outp += sprintf(outp, " %6.2f", 100.0 * c->c3/t->tsc);
400         if (do_nhm_cstates)
401                 outp += sprintf(outp, " %6.2f", 100.0 * c->c6/t->tsc);
402         if (do_snb_cstates)
403                 outp += sprintf(outp, " %6.2f", 100.0 * c->c7/t->tsc);
404
405         /* print per-package data only for 1st core in package */
406         if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
407                 goto done;
408
409         if (do_snb_cstates)
410                 outp += sprintf(outp, " %6.2f", 100.0 * p->pc2/t->tsc);
411         if (do_nhm_cstates)
412                 outp += sprintf(outp, " %6.2f", 100.0 * p->pc3/t->tsc);
413         if (do_nhm_cstates)
414                 outp += sprintf(outp, " %6.2f", 100.0 * p->pc6/t->tsc);
415         if (do_snb_cstates)
416                 outp += sprintf(outp, " %6.2f", 100.0 * p->pc7/t->tsc);
417 done:
418         outp += sprintf(outp, "\n");
419
420         return 0;
421 }
422
423 void flush_stdout()
424 {
425         fputs(output_buffer, stdout);
426         outp = output_buffer;
427 }
428 void flush_stderr()
429 {
430         fputs(output_buffer, stderr);
431         outp = output_buffer;
432 }
433 void format_all_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
434 {
435         static int printed;
436
437         if (!printed || !summary_only)
438                 print_header();
439
440         if (topo.num_cpus > 1)
441                 format_counters(&average.threads, &average.cores,
442                         &average.packages);
443
444         printed = 1;
445
446         if (summary_only)
447                 return;
448
449         for_all_cpus(format_counters, t, c, p);
450 }
451
452 void
453 delta_package(struct pkg_data *new, struct pkg_data *old)
454 {
455         old->pc2 = new->pc2 - old->pc2;
456         old->pc3 = new->pc3 - old->pc3;
457         old->pc6 = new->pc6 - old->pc6;
458         old->pc7 = new->pc7 - old->pc7;
459 }
460
461 void
462 delta_core(struct core_data *new, struct core_data *old)
463 {
464         old->c3 = new->c3 - old->c3;
465         old->c6 = new->c6 - old->c6;
466         old->c7 = new->c7 - old->c7;
467 }
468
469 /*
470  * old = new - old
471  */
472 void
473 delta_thread(struct thread_data *new, struct thread_data *old,
474         struct core_data *core_delta)
475 {
476         old->tsc = new->tsc - old->tsc;
477
478         /* check for TSC < 1 Mcycles over interval */
479         if (old->tsc < (1000 * 1000)) {
480                 fprintf(stderr, "Insanely slow TSC rate, TSC stops in idle?\n");
481                 fprintf(stderr, "You can disable all c-states by booting with \"idle=poll\"\n");
482                 fprintf(stderr, "or just the deep ones with \"processor.max_cstate=1\"\n");
483                 exit(-3);
484         }
485
486         old->c1 = new->c1 - old->c1;
487
488         if ((new->aperf > old->aperf) && (new->mperf > old->mperf)) {
489                 old->aperf = new->aperf - old->aperf;
490                 old->mperf = new->mperf - old->mperf;
491         } else {
492
493                 if (!aperf_mperf_unstable) {
494                         fprintf(stderr, "%s: APERF or MPERF went backwards *\n", progname);
495                         fprintf(stderr, "* Frequency results do not cover entire interval *\n");
496                         fprintf(stderr, "* fix this by running Linux-2.6.30 or later *\n");
497
498                         aperf_mperf_unstable = 1;
499                 }
500                 /*
501                  * mperf delta is likely a huge "positive" number
502                  * can not use it for calculating c0 time
503                  */
504                 skip_c0 = 1;
505                 skip_c1 = 1;
506         }
507
508
509         /*
510          * As counter collection is not atomic,
511          * it is possible for mperf's non-halted cycles + idle states
512          * to exceed TSC's all cycles: show c1 = 0% in that case.
513          */
514         if ((old->mperf + core_delta->c3 + core_delta->c6 + core_delta->c7) > old->tsc)
515                 old->c1 = 0;
516         else {
517                 /* normal case, derive c1 */
518                 old->c1 = old->tsc - old->mperf - core_delta->c3
519                                 - core_delta->c6 - core_delta->c7;
520         }
521
522         if (old->mperf == 0) {
523                 if (verbose > 1) fprintf(stderr, "cpu%d MPERF 0!\n", old->cpu_id);
524                 old->mperf = 1; /* divide by 0 protection */
525         }
526
527         old->extra_delta32 = new->extra_delta32 - old->extra_delta32;
528         old->extra_delta32 &= 0xFFFFFFFF;
529
530         old->extra_delta64 = new->extra_delta64 - old->extra_delta64;
531
532         /*
533          * Extra MSR is just a snapshot, simply copy latest w/o subtracting
534          */
535         old->extra_msr32 = new->extra_msr32;
536         old->extra_msr64 = new->extra_msr64;
537 }
538
539 int delta_cpu(struct thread_data *t, struct core_data *c,
540         struct pkg_data *p, struct thread_data *t2,
541         struct core_data *c2, struct pkg_data *p2)
542 {
543         /* calculate core delta only for 1st thread in core */
544         if (t->flags & CPU_IS_FIRST_THREAD_IN_CORE)
545                 delta_core(c, c2);
546
547         /* always calculate thread delta */
548         delta_thread(t, t2, c2);        /* c2 is core delta */
549
550         /* calculate package delta only for 1st core in package */
551         if (t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE)
552                 delta_package(p, p2);
553
554         return 0;
555 }
556
557 void clear_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
558 {
559         t->tsc = 0;
560         t->aperf = 0;
561         t->mperf = 0;
562         t->c1 = 0;
563
564         t->extra_delta32 = 0;
565         t->extra_delta64 = 0;
566
567         /* tells format_counters to dump all fields from this set */
568         t->flags = CPU_IS_FIRST_THREAD_IN_CORE | CPU_IS_FIRST_CORE_IN_PACKAGE;
569
570         c->c3 = 0;
571         c->c6 = 0;
572         c->c7 = 0;
573
574         p->pc2 = 0;
575         p->pc3 = 0;
576         p->pc6 = 0;
577         p->pc7 = 0;
578 }
579 int sum_counters(struct thread_data *t, struct core_data *c,
580         struct pkg_data *p)
581 {
582         average.threads.tsc += t->tsc;
583         average.threads.aperf += t->aperf;
584         average.threads.mperf += t->mperf;
585         average.threads.c1 += t->c1;
586
587         average.threads.extra_delta32 += t->extra_delta32;
588         average.threads.extra_delta64 += t->extra_delta64;
589
590         /* sum per-core values only for 1st thread in core */
591         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
592                 return 0;
593
594         average.cores.c3 += c->c3;
595         average.cores.c6 += c->c6;
596         average.cores.c7 += c->c7;
597
598         /* sum per-pkg values only for 1st core in pkg */
599         if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
600                 return 0;
601
602         average.packages.pc2 += p->pc2;
603         average.packages.pc3 += p->pc3;
604         average.packages.pc6 += p->pc6;
605         average.packages.pc7 += p->pc7;
606
607         return 0;
608 }
609 /*
610  * sum the counters for all cpus in the system
611  * compute the weighted average
612  */
613 void compute_average(struct thread_data *t, struct core_data *c,
614         struct pkg_data *p)
615 {
616         clear_counters(&average.threads, &average.cores, &average.packages);
617
618         for_all_cpus(sum_counters, t, c, p);
619
620         average.threads.tsc /= topo.num_cpus;
621         average.threads.aperf /= topo.num_cpus;
622         average.threads.mperf /= topo.num_cpus;
623         average.threads.c1 /= topo.num_cpus;
624
625         average.threads.extra_delta32 /= topo.num_cpus;
626         average.threads.extra_delta32 &= 0xFFFFFFFF;
627
628         average.threads.extra_delta64 /= topo.num_cpus;
629
630         average.cores.c3 /= topo.num_cores;
631         average.cores.c6 /= topo.num_cores;
632         average.cores.c7 /= topo.num_cores;
633
634         average.packages.pc2 /= topo.num_packages;
635         average.packages.pc3 /= topo.num_packages;
636         average.packages.pc6 /= topo.num_packages;
637         average.packages.pc7 /= topo.num_packages;
638 }
639
640 static unsigned long long rdtsc(void)
641 {
642         unsigned int low, high;
643
644         asm volatile("rdtsc" : "=a" (low), "=d" (high));
645
646         return low | ((unsigned long long)high) << 32;
647 }
648
649
650 /*
651  * get_counters(...)
652  * migrate to cpu
653  * acquire and record local counters for that cpu
654  */
655 int get_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p)
656 {
657         int cpu = t->cpu_id;
658
659         if (cpu_migrate(cpu))
660                 return -1;
661
662         t->tsc = rdtsc();       /* we are running on local CPU of interest */
663
664         if (has_aperf) {
665                 if (get_msr(cpu, MSR_IA32_APERF, &t->aperf))
666                         return -3;
667                 if (get_msr(cpu, MSR_IA32_MPERF, &t->mperf))
668                         return -4;
669         }
670
671         if (extra_delta_offset32) {
672                 if (get_msr(cpu, extra_delta_offset32, &t->extra_delta32))
673                         return -5;
674                 t->extra_delta32 &= 0xFFFFFFFF;
675         }
676
677         if (extra_delta_offset64)
678                 if (get_msr(cpu, extra_delta_offset64, &t->extra_delta64))
679                         return -5;
680
681         if (extra_msr_offset32) {
682                 if (get_msr(cpu, extra_msr_offset32, &t->extra_msr32))
683                         return -5;
684                 t->extra_msr32 &= 0xFFFFFFFF;
685         }
686
687         if (extra_msr_offset64)
688                 if (get_msr(cpu, extra_msr_offset64, &t->extra_msr64))
689                         return -5;
690
691         /* collect core counters only for 1st thread in core */
692         if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE))
693                 return 0;
694
695         if (do_nhm_cstates) {
696                 if (get_msr(cpu, MSR_CORE_C3_RESIDENCY, &c->c3))
697                         return -6;
698                 if (get_msr(cpu, MSR_CORE_C6_RESIDENCY, &c->c6))
699                         return -7;
700         }
701
702         if (do_snb_cstates)
703                 if (get_msr(cpu, MSR_CORE_C7_RESIDENCY, &c->c7))
704                         return -8;
705
706         /* collect package counters only for 1st core in package */
707         if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE))
708                 return 0;
709
710         if (do_nhm_cstates) {
711                 if (get_msr(cpu, MSR_PKG_C3_RESIDENCY, &p->pc3))
712                         return -9;
713                 if (get_msr(cpu, MSR_PKG_C6_RESIDENCY, &p->pc6))
714                         return -10;
715         }
716         if (do_snb_cstates) {
717                 if (get_msr(cpu, MSR_PKG_C2_RESIDENCY, &p->pc2))
718                         return -11;
719                 if (get_msr(cpu, MSR_PKG_C7_RESIDENCY, &p->pc7))
720                         return -12;
721         }
722         return 0;
723 }
724
725 void print_verbose_header(void)
726 {
727         unsigned long long msr;
728         unsigned int ratio;
729
730         if (!do_nehalem_platform_info)
731                 return;
732
733         get_msr(0, MSR_NHM_PLATFORM_INFO, &msr);
734
735         if (verbose > 1)
736                 fprintf(stderr, "MSR_NHM_PLATFORM_INFO: 0x%llx\n", msr);
737
738         ratio = (msr >> 40) & 0xFF;
739         fprintf(stderr, "%d * %.0f = %.0f MHz max efficiency\n",
740                 ratio, bclk, ratio * bclk);
741
742         ratio = (msr >> 8) & 0xFF;
743         fprintf(stderr, "%d * %.0f = %.0f MHz TSC frequency\n",
744                 ratio, bclk, ratio * bclk);
745
746         if (!do_ivt_turbo_ratio_limit)
747                 goto print_nhm_turbo_ratio_limits;
748
749         get_msr(0, MSR_IVT_TURBO_RATIO_LIMIT, &msr);
750
751         if (verbose > 1)
752                 fprintf(stderr, "MSR_IVT_TURBO_RATIO_LIMIT: 0x%llx\n", msr);
753
754         ratio = (msr >> 56) & 0xFF;
755         if (ratio)
756                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 16 active cores\n",
757                         ratio, bclk, ratio * bclk);
758
759         ratio = (msr >> 48) & 0xFF;
760         if (ratio)
761                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 15 active cores\n",
762                         ratio, bclk, ratio * bclk);
763
764         ratio = (msr >> 40) & 0xFF;
765         if (ratio)
766                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 14 active cores\n",
767                         ratio, bclk, ratio * bclk);
768
769         ratio = (msr >> 32) & 0xFF;
770         if (ratio)
771                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 13 active cores\n",
772                         ratio, bclk, ratio * bclk);
773
774         ratio = (msr >> 24) & 0xFF;
775         if (ratio)
776                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 12 active cores\n",
777                         ratio, bclk, ratio * bclk);
778
779         ratio = (msr >> 16) & 0xFF;
780         if (ratio)
781                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 11 active cores\n",
782                         ratio, bclk, ratio * bclk);
783
784         ratio = (msr >> 8) & 0xFF;
785         if (ratio)
786                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 10 active cores\n",
787                         ratio, bclk, ratio * bclk);
788
789         ratio = (msr >> 0) & 0xFF;
790         if (ratio)
791                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 9 active cores\n",
792                         ratio, bclk, ratio * bclk);
793
794 print_nhm_turbo_ratio_limits:
795
796         if (!do_nehalem_turbo_ratio_limit)
797                 return;
798
799         get_msr(0, MSR_NHM_TURBO_RATIO_LIMIT, &msr);
800
801         if (verbose > 1)
802                 fprintf(stderr, "MSR_NHM_TURBO_RATIO_LIMIT: 0x%llx\n", msr);
803
804         ratio = (msr >> 56) & 0xFF;
805         if (ratio)
806                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 8 active cores\n",
807                         ratio, bclk, ratio * bclk);
808
809         ratio = (msr >> 48) & 0xFF;
810         if (ratio)
811                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 7 active cores\n",
812                         ratio, bclk, ratio * bclk);
813
814         ratio = (msr >> 40) & 0xFF;
815         if (ratio)
816                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 6 active cores\n",
817                         ratio, bclk, ratio * bclk);
818
819         ratio = (msr >> 32) & 0xFF;
820         if (ratio)
821                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 5 active cores\n",
822                         ratio, bclk, ratio * bclk);
823
824         ratio = (msr >> 24) & 0xFF;
825         if (ratio)
826                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 4 active cores\n",
827                         ratio, bclk, ratio * bclk);
828
829         ratio = (msr >> 16) & 0xFF;
830         if (ratio)
831                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 3 active cores\n",
832                         ratio, bclk, ratio * bclk);
833
834         ratio = (msr >> 8) & 0xFF;
835         if (ratio)
836                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 2 active cores\n",
837                         ratio, bclk, ratio * bclk);
838
839         ratio = (msr >> 0) & 0xFF;
840         if (ratio)
841                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 1 active cores\n",
842                         ratio, bclk, ratio * bclk);
843 }
844
845 void free_all_buffers(void)
846 {
847         CPU_FREE(cpu_present_set);
848         cpu_present_set = NULL;
849         cpu_present_set = 0;
850
851         CPU_FREE(cpu_affinity_set);
852         cpu_affinity_set = NULL;
853         cpu_affinity_setsize = 0;
854
855         free(thread_even);
856         free(core_even);
857         free(package_even);
858
859         thread_even = NULL;
860         core_even = NULL;
861         package_even = NULL;
862
863         free(thread_odd);
864         free(core_odd);
865         free(package_odd);
866
867         thread_odd = NULL;
868         core_odd = NULL;
869         package_odd = NULL;
870
871         free(output_buffer);
872         output_buffer = NULL;
873         outp = NULL;
874 }
875
876 /*
877  * cpu_is_first_sibling_in_core(cpu)
878  * return 1 if given CPU is 1st HT sibling in the core
879  */
880 int cpu_is_first_sibling_in_core(int cpu)
881 {
882         char path[64];
883         FILE *filep;
884         int first_cpu;
885
886         sprintf(path, "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", cpu);
887         filep = fopen(path, "r");
888         if (filep == NULL) {
889                 perror(path);
890                 exit(1);
891         }
892         fscanf(filep, "%d", &first_cpu);
893         fclose(filep);
894         return (cpu == first_cpu);
895 }
896
897 /*
898  * cpu_is_first_core_in_package(cpu)
899  * return 1 if given CPU is 1st core in package
900  */
901 int cpu_is_first_core_in_package(int cpu)
902 {
903         char path[64];
904         FILE *filep;
905         int first_cpu;
906
907         sprintf(path, "/sys/devices/system/cpu/cpu%d/topology/core_siblings_list", cpu);
908         filep = fopen(path, "r");
909         if (filep == NULL) {
910                 perror(path);
911                 exit(1);
912         }
913         fscanf(filep, "%d", &first_cpu);
914         fclose(filep);
915         return (cpu == first_cpu);
916 }
917
918 int get_physical_package_id(int cpu)
919 {
920         char path[80];
921         FILE *filep;
922         int pkg;
923
924         sprintf(path, "/sys/devices/system/cpu/cpu%d/topology/physical_package_id", cpu);
925         filep = fopen(path, "r");
926         if (filep == NULL) {
927                 perror(path);
928                 exit(1);
929         }
930         fscanf(filep, "%d", &pkg);
931         fclose(filep);
932         return pkg;
933 }
934
935 int get_core_id(int cpu)
936 {
937         char path[80];
938         FILE *filep;
939         int core;
940
941         sprintf(path, "/sys/devices/system/cpu/cpu%d/topology/core_id", cpu);
942         filep = fopen(path, "r");
943         if (filep == NULL) {
944                 perror(path);
945                 exit(1);
946         }
947         fscanf(filep, "%d", &core);
948         fclose(filep);
949         return core;
950 }
951
952 int get_num_ht_siblings(int cpu)
953 {
954         char path[80];
955         FILE *filep;
956         int sib1, sib2;
957         int matches;
958         char character;
959
960         sprintf(path, "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", cpu);
961         filep = fopen(path, "r");
962         if (filep == NULL) {
963                 perror(path);
964                 exit(1);
965         }
966         /*
967          * file format:
968          * if a pair of number with a character between: 2 siblings (eg. 1-2, or 1,4)
969          * otherwinse 1 sibling (self).
970          */
971         matches = fscanf(filep, "%d%c%d\n", &sib1, &character, &sib2);
972
973         fclose(filep);
974
975         if (matches == 3)
976                 return 2;
977         else
978                 return 1;
979 }
980
981 /*
982  * run func(thread, core, package) in topology order
983  * skip non-present cpus
984  */
985
986 int for_all_cpus_2(int (func)(struct thread_data *, struct core_data *,
987         struct pkg_data *, struct thread_data *, struct core_data *,
988         struct pkg_data *), struct thread_data *thread_base,
989         struct core_data *core_base, struct pkg_data *pkg_base,
990         struct thread_data *thread_base2, struct core_data *core_base2,
991         struct pkg_data *pkg_base2)
992 {
993         int retval, pkg_no, core_no, thread_no;
994
995         for (pkg_no = 0; pkg_no < topo.num_packages; ++pkg_no) {
996                 for (core_no = 0; core_no < topo.num_cores_per_pkg; ++core_no) {
997                         for (thread_no = 0; thread_no <
998                                 topo.num_threads_per_core; ++thread_no) {
999                                 struct thread_data *t, *t2;
1000                                 struct core_data *c, *c2;
1001                                 struct pkg_data *p, *p2;
1002
1003                                 t = GET_THREAD(thread_base, thread_no, core_no, pkg_no);
1004
1005                                 if (cpu_is_not_present(t->cpu_id))
1006                                         continue;
1007
1008                                 t2 = GET_THREAD(thread_base2, thread_no, core_no, pkg_no);
1009
1010                                 c = GET_CORE(core_base, core_no, pkg_no);
1011                                 c2 = GET_CORE(core_base2, core_no, pkg_no);
1012
1013                                 p = GET_PKG(pkg_base, pkg_no);
1014                                 p2 = GET_PKG(pkg_base2, pkg_no);
1015
1016                                 retval = func(t, c, p, t2, c2, p2);
1017                                 if (retval)
1018                                         return retval;
1019                         }
1020                 }
1021         }
1022         return 0;
1023 }
1024
1025 /*
1026  * run func(cpu) on every cpu in /proc/stat
1027  * return max_cpu number
1028  */
1029 int for_all_proc_cpus(int (func)(int))
1030 {
1031         FILE *fp;
1032         int cpu_num;
1033         int retval;
1034
1035         fp = fopen(proc_stat, "r");
1036         if (fp == NULL) {
1037                 perror(proc_stat);
1038                 exit(1);
1039         }
1040
1041         retval = fscanf(fp, "cpu %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n");
1042         if (retval != 0) {
1043                 perror("/proc/stat format");
1044                 exit(1);
1045         }
1046
1047         while (1) {
1048                 retval = fscanf(fp, "cpu%u %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n", &cpu_num);
1049                 if (retval != 1)
1050                         break;
1051
1052                 retval = func(cpu_num);
1053                 if (retval) {
1054                         fclose(fp);
1055                         return(retval);
1056                 }
1057         }
1058         fclose(fp);
1059         return 0;
1060 }
1061
1062 void re_initialize(void)
1063 {
1064         free_all_buffers();
1065         setup_all_buffers();
1066         printf("turbostat: re-initialized with num_cpus %d\n", topo.num_cpus);
1067 }
1068
1069
1070 /*
1071  * count_cpus()
1072  * remember the last one seen, it will be the max
1073  */
1074 int count_cpus(int cpu)
1075 {
1076         if (topo.max_cpu_num < cpu)
1077                 topo.max_cpu_num = cpu;
1078
1079         topo.num_cpus += 1;
1080         return 0;
1081 }
1082 int mark_cpu_present(int cpu)
1083 {
1084         CPU_SET_S(cpu, cpu_present_setsize, cpu_present_set);
1085         return 0;
1086 }
1087
1088 void turbostat_loop()
1089 {
1090         int retval;
1091
1092 restart:
1093         retval = for_all_cpus(get_counters, EVEN_COUNTERS);
1094         if (retval < -1) {
1095                 exit(retval);
1096         } else if (retval == -1) {
1097                 re_initialize();
1098                 goto restart;
1099         }
1100         gettimeofday(&tv_even, (struct timezone *)NULL);
1101
1102         while (1) {
1103                 if (for_all_proc_cpus(cpu_is_not_present)) {
1104                         re_initialize();
1105                         goto restart;
1106                 }
1107                 sleep(interval_sec);
1108                 retval = for_all_cpus(get_counters, ODD_COUNTERS);
1109                 if (retval < -1) {
1110                         exit(retval);
1111                 } else if (retval == -1) {
1112                         re_initialize();
1113                         goto restart;
1114                 }
1115                 gettimeofday(&tv_odd, (struct timezone *)NULL);
1116                 timersub(&tv_odd, &tv_even, &tv_delta);
1117                 for_all_cpus_2(delta_cpu, ODD_COUNTERS, EVEN_COUNTERS);
1118                 compute_average(EVEN_COUNTERS);
1119                 format_all_counters(EVEN_COUNTERS);
1120                 flush_stdout();
1121                 sleep(interval_sec);
1122                 retval = for_all_cpus(get_counters, EVEN_COUNTERS);
1123                 if (retval < -1) {
1124                         exit(retval);
1125                 } else if (retval == -1) {
1126                         re_initialize();
1127                         goto restart;
1128                 }
1129                 gettimeofday(&tv_even, (struct timezone *)NULL);
1130                 timersub(&tv_even, &tv_odd, &tv_delta);
1131                 for_all_cpus_2(delta_cpu, EVEN_COUNTERS, ODD_COUNTERS);
1132                 compute_average(ODD_COUNTERS);
1133                 format_all_counters(ODD_COUNTERS);
1134                 flush_stdout();
1135         }
1136 }
1137
1138 void check_dev_msr()
1139 {
1140         struct stat sb;
1141
1142         if (stat("/dev/cpu/0/msr", &sb)) {
1143                 fprintf(stderr, "no /dev/cpu/0/msr\n");
1144                 fprintf(stderr, "Try \"# modprobe msr\"\n");
1145                 exit(-5);
1146         }
1147 }
1148
1149 void check_super_user()
1150 {
1151         if (getuid() != 0) {
1152                 fprintf(stderr, "must be root\n");
1153                 exit(-6);
1154         }
1155 }
1156
1157 int has_nehalem_turbo_ratio_limit(unsigned int family, unsigned int model)
1158 {
1159         if (!genuine_intel)
1160                 return 0;
1161
1162         if (family != 6)
1163                 return 0;
1164
1165         switch (model) {
1166         case 0x1A:      /* Core i7, Xeon 5500 series - Bloomfield, Gainstown NHM-EP */
1167         case 0x1E:      /* Core i7 and i5 Processor - Clarksfield, Lynnfield, Jasper Forest */
1168         case 0x1F:      /* Core i7 and i5 Processor - Nehalem */
1169         case 0x25:      /* Westmere Client - Clarkdale, Arrandale */
1170         case 0x2C:      /* Westmere EP - Gulftown */
1171         case 0x2A:      /* SNB */
1172         case 0x2D:      /* SNB Xeon */
1173         case 0x3A:      /* IVB */
1174         case 0x3E:      /* IVB Xeon */
1175                 return 1;
1176         case 0x2E:      /* Nehalem-EX Xeon - Beckton */
1177         case 0x2F:      /* Westmere-EX Xeon - Eagleton */
1178         default:
1179                 return 0;
1180         }
1181 }
1182 int has_ivt_turbo_ratio_limit(unsigned int family, unsigned int model)
1183 {
1184         if (!genuine_intel)
1185                 return 0;
1186
1187         if (family != 6)
1188                 return 0;
1189
1190         switch (model) {
1191         case 0x3E:      /* IVB Xeon */
1192                 return 1;
1193         default:
1194                 return 0;
1195         }
1196 }
1197
1198
1199 int is_snb(unsigned int family, unsigned int model)
1200 {
1201         if (!genuine_intel)
1202                 return 0;
1203
1204         switch (model) {
1205         case 0x2A:
1206         case 0x2D:
1207         case 0x3A:      /* IVB */
1208         case 0x3E:      /* IVB Xeon */
1209                 return 1;
1210         }
1211         return 0;
1212 }
1213
1214 double discover_bclk(unsigned int family, unsigned int model)
1215 {
1216         if (is_snb(family, model))
1217                 return 100.00;
1218         else
1219                 return 133.33;
1220 }
1221
1222 void check_cpuid()
1223 {
1224         unsigned int eax, ebx, ecx, edx, max_level;
1225         unsigned int fms, family, model, stepping;
1226
1227         eax = ebx = ecx = edx = 0;
1228
1229         asm("cpuid" : "=a" (max_level), "=b" (ebx), "=c" (ecx), "=d" (edx) : "a" (0));
1230
1231         if (ebx == 0x756e6547 && edx == 0x49656e69 && ecx == 0x6c65746e)
1232                 genuine_intel = 1;
1233
1234         if (verbose)
1235                 fprintf(stderr, "%.4s%.4s%.4s ",
1236                         (char *)&ebx, (char *)&edx, (char *)&ecx);
1237
1238         asm("cpuid" : "=a" (fms), "=c" (ecx), "=d" (edx) : "a" (1) : "ebx");
1239         family = (fms >> 8) & 0xf;
1240         model = (fms >> 4) & 0xf;
1241         stepping = fms & 0xf;
1242         if (family == 6 || family == 0xf)
1243                 model += ((fms >> 16) & 0xf) << 4;
1244
1245         if (verbose)
1246                 fprintf(stderr, "%d CPUID levels; family:model:stepping 0x%x:%x:%x (%d:%d:%d)\n",
1247                         max_level, family, model, stepping, family, model, stepping);
1248
1249         if (!(edx & (1 << 5))) {
1250                 fprintf(stderr, "CPUID: no MSR\n");
1251                 exit(1);
1252         }
1253
1254         /*
1255          * check max extended function levels of CPUID.
1256          * This is needed to check for invariant TSC.
1257          * This check is valid for both Intel and AMD.
1258          */
1259         ebx = ecx = edx = 0;
1260         asm("cpuid" : "=a" (max_level), "=b" (ebx), "=c" (ecx), "=d" (edx) : "a" (0x80000000));
1261
1262         if (max_level < 0x80000007) {
1263                 fprintf(stderr, "CPUID: no invariant TSC (max_level 0x%x)\n", max_level);
1264                 exit(1);
1265         }
1266
1267         /*
1268          * Non-Stop TSC is advertised by CPUID.EAX=0x80000007: EDX.bit8
1269          * this check is valid for both Intel and AMD
1270          */
1271         asm("cpuid" : "=a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx) : "a" (0x80000007));
1272         has_invariant_tsc = edx & (1 << 8);
1273
1274         if (!has_invariant_tsc) {
1275                 fprintf(stderr, "No invariant TSC\n");
1276                 exit(1);
1277         }
1278
1279         /*
1280          * APERF/MPERF is advertised by CPUID.EAX=0x6: ECX.bit0
1281          * this check is valid for both Intel and AMD
1282          */
1283
1284         asm("cpuid" : "=a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx) : "a" (0x6));
1285         has_aperf = ecx & (1 << 0);
1286         if (!has_aperf) {
1287                 fprintf(stderr, "No APERF MSR\n");
1288                 exit(1);
1289         }
1290
1291         do_nehalem_platform_info = genuine_intel && has_invariant_tsc;
1292         do_nhm_cstates = genuine_intel; /* all Intel w/ non-stop TSC have NHM counters */
1293         do_snb_cstates = is_snb(family, model);
1294         bclk = discover_bclk(family, model);
1295
1296         do_nehalem_turbo_ratio_limit = has_nehalem_turbo_ratio_limit(family, model);
1297         do_ivt_turbo_ratio_limit = has_ivt_turbo_ratio_limit(family, model);
1298 }
1299
1300
1301 void usage()
1302 {
1303         fprintf(stderr, "%s: [-v][-p|-P|-S][-c MSR# | -s]][-C MSR#][-m MSR#][-M MSR#][-i interval_sec | command ...]\n",
1304                 progname);
1305         exit(1);
1306 }
1307
1308
1309 /*
1310  * in /dev/cpu/ return success for names that are numbers
1311  * ie. filter out ".", "..", "microcode".
1312  */
1313 int dir_filter(const struct dirent *dirp)
1314 {
1315         if (isdigit(dirp->d_name[0]))
1316                 return 1;
1317         else
1318                 return 0;
1319 }
1320
1321 int open_dev_cpu_msr(int dummy1)
1322 {
1323         return 0;
1324 }
1325
1326 void topology_probe()
1327 {
1328         int i;
1329         int max_core_id = 0;
1330         int max_package_id = 0;
1331         int max_siblings = 0;
1332         struct cpu_topology {
1333                 int core_id;
1334                 int physical_package_id;
1335         } *cpus;
1336
1337         /* Initialize num_cpus, max_cpu_num */
1338         topo.num_cpus = 0;
1339         topo.max_cpu_num = 0;
1340         for_all_proc_cpus(count_cpus);
1341         if (!summary_only && topo.num_cpus > 1)
1342                 show_cpu = 1;
1343
1344         if (verbose > 1)
1345                 fprintf(stderr, "num_cpus %d max_cpu_num %d\n", topo.num_cpus, topo.max_cpu_num);
1346
1347         cpus = calloc(1, (topo.max_cpu_num  + 1) * sizeof(struct cpu_topology));
1348         if (cpus == NULL) {
1349                 perror("calloc cpus");
1350                 exit(1);
1351         }
1352
1353         /*
1354          * Allocate and initialize cpu_present_set
1355          */
1356         cpu_present_set = CPU_ALLOC((topo.max_cpu_num + 1));
1357         if (cpu_present_set == NULL) {
1358                 perror("CPU_ALLOC");
1359                 exit(3);
1360         }
1361         cpu_present_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
1362         CPU_ZERO_S(cpu_present_setsize, cpu_present_set);
1363         for_all_proc_cpus(mark_cpu_present);
1364
1365         /*
1366          * Allocate and initialize cpu_affinity_set
1367          */
1368         cpu_affinity_set = CPU_ALLOC((topo.max_cpu_num + 1));
1369         if (cpu_affinity_set == NULL) {
1370                 perror("CPU_ALLOC");
1371                 exit(3);
1372         }
1373         cpu_affinity_setsize = CPU_ALLOC_SIZE((topo.max_cpu_num + 1));
1374         CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set);
1375
1376
1377         /*
1378          * For online cpus
1379          * find max_core_id, max_package_id
1380          */
1381         for (i = 0; i <= topo.max_cpu_num; ++i) {
1382                 int siblings;
1383
1384                 if (cpu_is_not_present(i)) {
1385                         if (verbose > 1)
1386                                 fprintf(stderr, "cpu%d NOT PRESENT\n", i);
1387                         continue;
1388                 }
1389                 cpus[i].core_id = get_core_id(i);
1390                 if (cpus[i].core_id > max_core_id)
1391                         max_core_id = cpus[i].core_id;
1392
1393                 cpus[i].physical_package_id = get_physical_package_id(i);
1394                 if (cpus[i].physical_package_id > max_package_id)
1395                         max_package_id = cpus[i].physical_package_id;
1396
1397                 siblings = get_num_ht_siblings(i);
1398                 if (siblings > max_siblings)
1399                         max_siblings = siblings;
1400                 if (verbose > 1)
1401                         fprintf(stderr, "cpu %d pkg %d core %d\n",
1402                                 i, cpus[i].physical_package_id, cpus[i].core_id);
1403         }
1404         topo.num_cores_per_pkg = max_core_id + 1;
1405         if (verbose > 1)
1406                 fprintf(stderr, "max_core_id %d, sizing for %d cores per package\n",
1407                         max_core_id, topo.num_cores_per_pkg);
1408         if (!summary_only && topo.num_cores_per_pkg > 1)
1409                 show_core = 1;
1410
1411         topo.num_packages = max_package_id + 1;
1412         if (verbose > 1)
1413                 fprintf(stderr, "max_package_id %d, sizing for %d packages\n",
1414                         max_package_id, topo.num_packages);
1415         if (!summary_only && topo.num_packages > 1)
1416                 show_pkg = 1;
1417
1418         topo.num_threads_per_core = max_siblings;
1419         if (verbose > 1)
1420                 fprintf(stderr, "max_siblings %d\n", max_siblings);
1421
1422         free(cpus);
1423 }
1424
1425 void
1426 allocate_counters(struct thread_data **t, struct core_data **c, struct pkg_data **p)
1427 {
1428         int i;
1429
1430         *t = calloc(topo.num_threads_per_core * topo.num_cores_per_pkg *
1431                 topo.num_packages, sizeof(struct thread_data));
1432         if (*t == NULL)
1433                 goto error;
1434
1435         for (i = 0; i < topo.num_threads_per_core *
1436                 topo.num_cores_per_pkg * topo.num_packages; i++)
1437                 (*t)[i].cpu_id = -1;
1438
1439         *c = calloc(topo.num_cores_per_pkg * topo.num_packages,
1440                 sizeof(struct core_data));
1441         if (*c == NULL)
1442                 goto error;
1443
1444         for (i = 0; i < topo.num_cores_per_pkg * topo.num_packages; i++)
1445                 (*c)[i].core_id = -1;
1446
1447         *p = calloc(topo.num_packages, sizeof(struct pkg_data));
1448         if (*p == NULL)
1449                 goto error;
1450
1451         for (i = 0; i < topo.num_packages; i++)
1452                 (*p)[i].package_id = i;
1453
1454         return;
1455 error:
1456         perror("calloc counters");
1457         exit(1);
1458 }
1459 /*
1460  * init_counter()
1461  *
1462  * set cpu_id, core_num, pkg_num
1463  * set FIRST_THREAD_IN_CORE and FIRST_CORE_IN_PACKAGE
1464  *
1465  * increment topo.num_cores when 1st core in pkg seen
1466  */
1467 void init_counter(struct thread_data *thread_base, struct core_data *core_base,
1468         struct pkg_data *pkg_base, int thread_num, int core_num,
1469         int pkg_num, int cpu_id)
1470 {
1471         struct thread_data *t;
1472         struct core_data *c;
1473         struct pkg_data *p;
1474
1475         t = GET_THREAD(thread_base, thread_num, core_num, pkg_num);
1476         c = GET_CORE(core_base, core_num, pkg_num);
1477         p = GET_PKG(pkg_base, pkg_num);
1478
1479         t->cpu_id = cpu_id;
1480         if (thread_num == 0) {
1481                 t->flags |= CPU_IS_FIRST_THREAD_IN_CORE;
1482                 if (cpu_is_first_core_in_package(cpu_id))
1483                         t->flags |= CPU_IS_FIRST_CORE_IN_PACKAGE;
1484         }
1485
1486         c->core_id = core_num;
1487         p->package_id = pkg_num;
1488 }
1489
1490
1491 int initialize_counters(int cpu_id)
1492 {
1493         int my_thread_id, my_core_id, my_package_id;
1494
1495         my_package_id = get_physical_package_id(cpu_id);
1496         my_core_id = get_core_id(cpu_id);
1497
1498         if (cpu_is_first_sibling_in_core(cpu_id)) {
1499                 my_thread_id = 0;
1500                 topo.num_cores++;
1501         } else {
1502                 my_thread_id = 1;
1503         }
1504
1505         init_counter(EVEN_COUNTERS, my_thread_id, my_core_id, my_package_id, cpu_id);
1506         init_counter(ODD_COUNTERS, my_thread_id, my_core_id, my_package_id, cpu_id);
1507         return 0;
1508 }
1509
1510 void allocate_output_buffer()
1511 {
1512         output_buffer = calloc(1, (1 + topo.num_cpus) * 128);
1513         outp = output_buffer;
1514         if (outp == NULL) {
1515                 perror("calloc");
1516                 exit(-1);
1517         }
1518 }
1519
1520 void setup_all_buffers(void)
1521 {
1522         topology_probe();
1523         allocate_counters(&thread_even, &core_even, &package_even);
1524         allocate_counters(&thread_odd, &core_odd, &package_odd);
1525         allocate_output_buffer();
1526         for_all_proc_cpus(initialize_counters);
1527 }
1528 void turbostat_init()
1529 {
1530         check_cpuid();
1531
1532         check_dev_msr();
1533         check_super_user();
1534
1535         setup_all_buffers();
1536
1537         if (verbose)
1538                 print_verbose_header();
1539 }
1540
1541 int fork_it(char **argv)
1542 {
1543         pid_t child_pid;
1544         int status;
1545
1546         status = for_all_cpus(get_counters, EVEN_COUNTERS);
1547         if (status)
1548                 exit(status);
1549         /* clear affinity side-effect of get_counters() */
1550         sched_setaffinity(0, cpu_present_setsize, cpu_present_set);
1551         gettimeofday(&tv_even, (struct timezone *)NULL);
1552
1553         child_pid = fork();
1554         if (!child_pid) {
1555                 /* child */
1556                 execvp(argv[0], argv);
1557         } else {
1558
1559                 /* parent */
1560                 if (child_pid == -1) {
1561                         perror("fork");
1562                         exit(1);
1563                 }
1564
1565                 signal(SIGINT, SIG_IGN);
1566                 signal(SIGQUIT, SIG_IGN);
1567                 if (waitpid(child_pid, &status, 0) == -1) {
1568                         perror("wait");
1569                         exit(status);
1570                 }
1571         }
1572         /*
1573          * n.b. fork_it() does not check for errors from for_all_cpus()
1574          * because re-starting is problematic when forking
1575          */
1576         for_all_cpus(get_counters, ODD_COUNTERS);
1577         gettimeofday(&tv_odd, (struct timezone *)NULL);
1578         timersub(&tv_odd, &tv_even, &tv_delta);
1579         for_all_cpus_2(delta_cpu, ODD_COUNTERS, EVEN_COUNTERS);
1580         compute_average(EVEN_COUNTERS);
1581         format_all_counters(EVEN_COUNTERS);
1582         flush_stderr();
1583
1584         fprintf(stderr, "%.6f sec\n", tv_delta.tv_sec + tv_delta.tv_usec/1000000.0);
1585
1586         return status;
1587 }
1588
1589 void cmdline(int argc, char **argv)
1590 {
1591         int opt;
1592
1593         progname = argv[0];
1594
1595         while ((opt = getopt(argc, argv, "+pPSvi:sc:sC:m:M:")) != -1) {
1596                 switch (opt) {
1597                 case 'p':
1598                         show_core_only++;
1599                         break;
1600                 case 'P':
1601                         show_pkg_only++;
1602                         break;
1603                 case 'S':
1604                         summary_only++;
1605                         break;
1606                 case 'v':
1607                         verbose++;
1608                         break;
1609                 case 'i':
1610                         interval_sec = atoi(optarg);
1611                         break;
1612                 case 'c':
1613                         sscanf(optarg, "%x", &extra_delta_offset32);
1614                         break;
1615                 case 's':
1616                         extra_delta_offset32 = 0x34;    /* SMI counter */
1617                         break;
1618                 case 'C':
1619                         sscanf(optarg, "%x", &extra_delta_offset64);
1620                         break;
1621                 case 'm':
1622                         sscanf(optarg, "%x", &extra_msr_offset32);
1623                         break;
1624                 case 'M':
1625                         sscanf(optarg, "%x", &extra_msr_offset64);
1626                         break;
1627                 default:
1628                         usage();
1629                 }
1630         }
1631 }
1632
1633 int main(int argc, char **argv)
1634 {
1635         cmdline(argc, argv);
1636
1637         if (verbose > 1)
1638                 fprintf(stderr, "turbostat v2.1 October 6, 2012"
1639                         " - Len Brown <lenb@kernel.org>\n");
1640
1641         turbostat_init();
1642
1643         /*
1644          * if any params left, it must be a command to fork
1645          */
1646         if (argc - optind)
1647                 return fork_it(argv + optind);
1648         else
1649                 turbostat_loop();
1650
1651         return 0;
1652 }