tools turbostat: reduce measurement overhead due to IPIs
[firefly-linux-kernel-4.4.55.git] / tools / power / x86 / turbostat / turbostat.c
1 /*
2  * turbostat -- show CPU frequency and C-state residency
3  * on modern Intel turbo-capable processors.
4  *
5  * Copyright (c) 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 <stdio.h>
24 #include <unistd.h>
25 #include <sys/types.h>
26 #include <sys/wait.h>
27 #include <sys/stat.h>
28 #include <sys/resource.h>
29 #include <fcntl.h>
30 #include <signal.h>
31 #include <sys/time.h>
32 #include <stdlib.h>
33 #include <dirent.h>
34 #include <string.h>
35 #include <ctype.h>
36 #include <sched.h>
37
38 #define MSR_TSC 0x10
39 #define MSR_NEHALEM_PLATFORM_INFO       0xCE
40 #define MSR_NEHALEM_TURBO_RATIO_LIMIT   0x1AD
41 #define MSR_APERF       0xE8
42 #define MSR_MPERF       0xE7
43 #define MSR_PKG_C2_RESIDENCY    0x60D   /* SNB only */
44 #define MSR_PKG_C3_RESIDENCY    0x3F8
45 #define MSR_PKG_C6_RESIDENCY    0x3F9
46 #define MSR_PKG_C7_RESIDENCY    0x3FA   /* SNB only */
47 #define MSR_CORE_C3_RESIDENCY   0x3FC
48 #define MSR_CORE_C6_RESIDENCY   0x3FD
49 #define MSR_CORE_C7_RESIDENCY   0x3FE   /* SNB only */
50
51 char *proc_stat = "/proc/stat";
52 unsigned int interval_sec = 5;  /* set with -i interval_sec */
53 unsigned int verbose;           /* set with -v */
54 unsigned int summary_only;      /* set with -s */
55 unsigned int skip_c0;
56 unsigned int skip_c1;
57 unsigned int do_nhm_cstates;
58 unsigned int do_snb_cstates;
59 unsigned int has_aperf;
60 unsigned int units = 1000000000;        /* Ghz etc */
61 unsigned int genuine_intel;
62 unsigned int has_invariant_tsc;
63 unsigned int do_nehalem_platform_info;
64 unsigned int do_nehalem_turbo_ratio_limit;
65 unsigned int extra_msr_offset;
66 double bclk;
67 unsigned int show_pkg;
68 unsigned int show_core;
69 unsigned int show_cpu;
70
71 int aperf_mperf_unstable;
72 int backwards_count;
73 char *progname;
74 int need_reinitialize;
75
76 int num_cpus;
77 cpu_set_t *cpu_mask;
78 size_t cpu_mask_size;
79
80 struct counters {
81         unsigned long long tsc;         /* per thread */
82         unsigned long long aperf;       /* per thread */
83         unsigned long long mperf;       /* per thread */
84         unsigned long long c1;  /* per thread (calculated) */
85         unsigned long long c3;  /* per core */
86         unsigned long long c6;  /* per core */
87         unsigned long long c7;  /* per core */
88         unsigned long long pc2; /* per package */
89         unsigned long long pc3; /* per package */
90         unsigned long long pc6; /* per package */
91         unsigned long long pc7; /* per package */
92         unsigned long long extra_msr;   /* per thread */
93         int pkg;
94         int core;
95         int cpu;
96         struct counters *next;
97 };
98
99 struct counters *cnt_even;
100 struct counters *cnt_odd;
101 struct counters *cnt_delta;
102 struct counters *cnt_average;
103 struct timeval tv_even;
104 struct timeval tv_odd;
105 struct timeval tv_delta;
106
107 /*
108  * cpu_mask_init(ncpus)
109  *
110  * allocate and clear cpu_mask
111  * set cpu_mask_size
112  */
113 void cpu_mask_init(int ncpus)
114 {
115         cpu_mask = CPU_ALLOC(ncpus);
116         if (cpu_mask == NULL) {
117                 perror("CPU_ALLOC");
118                 exit(3);
119         }
120         cpu_mask_size = CPU_ALLOC_SIZE(ncpus);
121         CPU_ZERO_S(cpu_mask_size, cpu_mask);
122 }
123
124 void cpu_mask_uninit()
125 {
126         CPU_FREE(cpu_mask);
127         cpu_mask = NULL;
128         cpu_mask_size = 0;
129 }
130
131 int cpu_migrate(int cpu)
132 {
133         CPU_ZERO_S(cpu_mask_size, cpu_mask);
134         CPU_SET_S(cpu, cpu_mask_size, cpu_mask);
135         if (sched_setaffinity(0, cpu_mask_size, cpu_mask) == -1)
136                 return -1;
137         else
138                 return 0;
139 }
140
141 unsigned long long get_msr(int cpu, off_t offset)
142 {
143         ssize_t retval;
144         unsigned long long msr;
145         char pathname[32];
146         int fd;
147
148         sprintf(pathname, "/dev/cpu/%d/msr", cpu);
149         fd = open(pathname, O_RDONLY);
150         if (fd < 0) {
151                 perror(pathname);
152                 need_reinitialize = 1;
153                 return 0;
154         }
155
156         retval = pread(fd, &msr, sizeof msr, offset);
157         if (retval != sizeof msr) {
158                 fprintf(stderr, "cpu%d pread(..., 0x%zx) = %jd\n",
159                         cpu, offset, retval);
160                 exit(-2);
161         }
162
163         close(fd);
164         return msr;
165 }
166
167 void print_header(void)
168 {
169         if (show_pkg)
170                 fprintf(stderr, "pk");
171         if (show_pkg)
172                 fprintf(stderr, " ");
173         if (show_core)
174                 fprintf(stderr, "cor");
175         if (show_cpu)
176                 fprintf(stderr, " CPU");
177         if (show_pkg || show_core || show_cpu)
178                 fprintf(stderr, " ");
179         if (do_nhm_cstates)
180                 fprintf(stderr, "   %%c0");
181         if (has_aperf)
182                 fprintf(stderr, "  GHz");
183         fprintf(stderr, "  TSC");
184         if (do_nhm_cstates)
185                 fprintf(stderr, "    %%c1");
186         if (do_nhm_cstates)
187                 fprintf(stderr, "    %%c3");
188         if (do_nhm_cstates)
189                 fprintf(stderr, "    %%c6");
190         if (do_snb_cstates)
191                 fprintf(stderr, "    %%c7");
192         if (do_snb_cstates)
193                 fprintf(stderr, "   %%pc2");
194         if (do_nhm_cstates)
195                 fprintf(stderr, "   %%pc3");
196         if (do_nhm_cstates)
197                 fprintf(stderr, "   %%pc6");
198         if (do_snb_cstates)
199                 fprintf(stderr, "   %%pc7");
200         if (extra_msr_offset)
201                 fprintf(stderr, "        MSR 0x%x ", extra_msr_offset);
202
203         putc('\n', stderr);
204 }
205
206 void dump_cnt(struct counters *cnt)
207 {
208         if (!cnt)
209                 return;
210         if (cnt->pkg) fprintf(stderr, "package: %d ", cnt->pkg);
211         if (cnt->core) fprintf(stderr, "core:: %d ", cnt->core);
212         if (cnt->cpu) fprintf(stderr, "CPU: %d ", cnt->cpu);
213         if (cnt->tsc) fprintf(stderr, "TSC: %016llX\n", cnt->tsc);
214         if (cnt->c3) fprintf(stderr, "c3: %016llX\n", cnt->c3);
215         if (cnt->c6) fprintf(stderr, "c6: %016llX\n", cnt->c6);
216         if (cnt->c7) fprintf(stderr, "c7: %016llX\n", cnt->c7);
217         if (cnt->aperf) fprintf(stderr, "aperf: %016llX\n", cnt->aperf);
218         if (cnt->pc2) fprintf(stderr, "pc2: %016llX\n", cnt->pc2);
219         if (cnt->pc3) fprintf(stderr, "pc3: %016llX\n", cnt->pc3);
220         if (cnt->pc6) fprintf(stderr, "pc6: %016llX\n", cnt->pc6);
221         if (cnt->pc7) fprintf(stderr, "pc7: %016llX\n", cnt->pc7);
222         if (cnt->extra_msr) fprintf(stderr, "msr0x%x: %016llX\n", extra_msr_offset, cnt->extra_msr);
223 }
224
225 void dump_list(struct counters *cnt)
226 {
227         printf("dump_list 0x%p\n", cnt);
228
229         for (; cnt; cnt = cnt->next)
230                 dump_cnt(cnt);
231 }
232
233 /*
234  * column formatting convention & formats
235  * package: "pk" 2 columns %2d
236  * core: "cor" 3 columns %3d
237  * CPU: "CPU" 3 columns %3d
238  * GHz: "GHz" 3 columns %3.2
239  * TSC: "TSC" 3 columns %3.2
240  * percentage " %pc3" %6.2
241  */
242 void print_cnt(struct counters *p)
243 {
244         double interval_float;
245
246         interval_float = tv_delta.tv_sec + tv_delta.tv_usec/1000000.0;
247
248         /* topology columns, print blanks on 1st (average) line */
249         if (p == cnt_average) {
250                 if (show_pkg)
251                         fprintf(stderr, "  ");
252                 if (show_pkg && show_core)
253                         fprintf(stderr, " ");
254                 if (show_core)
255                         fprintf(stderr, "   ");
256                 if (show_cpu)
257                         fprintf(stderr, " " "   ");
258         } else {
259                 if (show_pkg)
260                         fprintf(stderr, "%2d", p->pkg);
261                 if (show_pkg && show_core)
262                         fprintf(stderr, " ");
263                 if (show_core)
264                         fprintf(stderr, "%3d", p->core);
265                 if (show_cpu)
266                         fprintf(stderr, " %3d", p->cpu);
267         }
268
269         /* %c0 */
270         if (do_nhm_cstates) {
271                 if (show_pkg || show_core || show_cpu)
272                         fprintf(stderr, " ");
273                 if (!skip_c0)
274                         fprintf(stderr, "%6.2f", 100.0 * p->mperf/p->tsc);
275                 else
276                         fprintf(stderr, "  ****");
277         }
278
279         /* GHz */
280         if (has_aperf) {
281                 if (!aperf_mperf_unstable) {
282                         fprintf(stderr, " %3.2f",
283                                 1.0 * p->tsc / units * p->aperf /
284                                 p->mperf / interval_float);
285                 } else {
286                         if (p->aperf > p->tsc || p->mperf > p->tsc) {
287                                 fprintf(stderr, " ***");
288                         } else {
289                                 fprintf(stderr, "%3.1f*",
290                                         1.0 * p->tsc /
291                                         units * p->aperf /
292                                         p->mperf / interval_float);
293                         }
294                 }
295         }
296
297         /* TSC */
298         fprintf(stderr, "%5.2f", 1.0 * p->tsc/units/interval_float);
299
300         if (do_nhm_cstates) {
301                 if (!skip_c1)
302                         fprintf(stderr, " %6.2f", 100.0 * p->c1/p->tsc);
303                 else
304                         fprintf(stderr, "  ****");
305         }
306         if (do_nhm_cstates)
307                 fprintf(stderr, " %6.2f", 100.0 * p->c3/p->tsc);
308         if (do_nhm_cstates)
309                 fprintf(stderr, " %6.2f", 100.0 * p->c6/p->tsc);
310         if (do_snb_cstates)
311                 fprintf(stderr, " %6.2f", 100.0 * p->c7/p->tsc);
312         if (do_snb_cstates)
313                 fprintf(stderr, " %6.2f", 100.0 * p->pc2/p->tsc);
314         if (do_nhm_cstates)
315                 fprintf(stderr, " %6.2f", 100.0 * p->pc3/p->tsc);
316         if (do_nhm_cstates)
317                 fprintf(stderr, " %6.2f", 100.0 * p->pc6/p->tsc);
318         if (do_snb_cstates)
319                 fprintf(stderr, " %6.2f", 100.0 * p->pc7/p->tsc);
320         if (extra_msr_offset)
321                 fprintf(stderr, "  0x%016llx", p->extra_msr);
322         putc('\n', stderr);
323 }
324
325 void print_counters(struct counters *counters)
326 {
327         struct counters *cnt;
328         static int printed;
329
330
331         if (!printed || !summary_only)
332                 print_header();
333
334         if (num_cpus > 1)
335                 print_cnt(cnt_average);
336
337         printed = 1;
338
339         if (summary_only)
340                 return;
341
342         for (cnt = counters; cnt != NULL; cnt = cnt->next)
343                 print_cnt(cnt);
344
345 }
346
347 #define SUBTRACT_COUNTER(after, before, delta) (delta = (after - before), (before > after))
348
349 int compute_delta(struct counters *after,
350         struct counters *before, struct counters *delta)
351 {
352         int errors = 0;
353         int perf_err = 0;
354
355         skip_c0 = skip_c1 = 0;
356
357         for ( ; after && before && delta;
358                 after = after->next, before = before->next, delta = delta->next) {
359                 if (before->cpu != after->cpu) {
360                         printf("cpu configuration changed: %d != %d\n",
361                                 before->cpu, after->cpu);
362                         return -1;
363                 }
364
365                 if (SUBTRACT_COUNTER(after->tsc, before->tsc, delta->tsc)) {
366                         fprintf(stderr, "cpu%d TSC went backwards %llX to %llX\n",
367                                 before->cpu, before->tsc, after->tsc);
368                         errors++;
369                 }
370                 /* check for TSC < 1 Mcycles over interval */
371                 if (delta->tsc < (1000 * 1000)) {
372                         fprintf(stderr, "Insanely slow TSC rate,"
373                                 " TSC stops in idle?\n");
374                         fprintf(stderr, "You can disable all c-states"
375                                 " by booting with \"idle=poll\"\n");
376                         fprintf(stderr, "or just the deep ones with"
377                                 " \"processor.max_cstate=1\"\n");
378                         exit(-3);
379                 }
380                 if (SUBTRACT_COUNTER(after->c3, before->c3, delta->c3)) {
381                         fprintf(stderr, "cpu%d c3 counter went backwards %llX to %llX\n",
382                                 before->cpu, before->c3, after->c3);
383                         errors++;
384                 }
385                 if (SUBTRACT_COUNTER(after->c6, before->c6, delta->c6)) {
386                         fprintf(stderr, "cpu%d c6 counter went backwards %llX to %llX\n",
387                                 before->cpu, before->c6, after->c6);
388                         errors++;
389                 }
390                 if (SUBTRACT_COUNTER(after->c7, before->c7, delta->c7)) {
391                         fprintf(stderr, "cpu%d c7 counter went backwards %llX to %llX\n",
392                                 before->cpu, before->c7, after->c7);
393                         errors++;
394                 }
395                 if (SUBTRACT_COUNTER(after->pc2, before->pc2, delta->pc2)) {
396                         fprintf(stderr, "cpu%d pc2 counter went backwards %llX to %llX\n",
397                                 before->cpu, before->pc2, after->pc2);
398                         errors++;
399                 }
400                 if (SUBTRACT_COUNTER(after->pc3, before->pc3, delta->pc3)) {
401                         fprintf(stderr, "cpu%d pc3 counter went backwards %llX to %llX\n",
402                                 before->cpu, before->pc3, after->pc3);
403                         errors++;
404                 }
405                 if (SUBTRACT_COUNTER(after->pc6, before->pc6, delta->pc6)) {
406                         fprintf(stderr, "cpu%d pc6 counter went backwards %llX to %llX\n",
407                                 before->cpu, before->pc6, after->pc6);
408                         errors++;
409                 }
410                 if (SUBTRACT_COUNTER(after->pc7, before->pc7, delta->pc7)) {
411                         fprintf(stderr, "cpu%d pc7 counter went backwards %llX to %llX\n",
412                                 before->cpu, before->pc7, after->pc7);
413                         errors++;
414                 }
415
416                 perf_err = SUBTRACT_COUNTER(after->aperf, before->aperf, delta->aperf);
417                 if (perf_err) {
418                         fprintf(stderr, "cpu%d aperf counter went backwards %llX to %llX\n",
419                                 before->cpu, before->aperf, after->aperf);
420                 }
421                 perf_err |= SUBTRACT_COUNTER(after->mperf, before->mperf, delta->mperf);
422                 if (perf_err) {
423                         fprintf(stderr, "cpu%d mperf counter went backwards %llX to %llX\n",
424                                 before->cpu, before->mperf, after->mperf);
425                 }
426                 if (perf_err) {
427                         if (!aperf_mperf_unstable) {
428                                 fprintf(stderr, "%s: APERF or MPERF went backwards *\n", progname);
429                                 fprintf(stderr, "* Frequency results do not cover entire interval *\n");
430                                 fprintf(stderr, "* fix this by running Linux-2.6.30 or later *\n");
431
432                                 aperf_mperf_unstable = 1;
433                         }
434                         /*
435                          * mperf delta is likely a huge "positive" number
436                          * can not use it for calculating c0 time
437                          */
438                         skip_c0 = 1;
439                         skip_c1 = 1;
440                 }
441
442                 /*
443                  * As mperf and tsc collection are not atomic,
444                  * it is possible for mperf's non-halted cycles
445                  * to exceed TSC's all cycles: show c1 = 0% in that case.
446                  */
447                 if (delta->mperf > delta->tsc)
448                         delta->c1 = 0;
449                 else /* normal case, derive c1 */
450                         delta->c1 = delta->tsc - delta->mperf
451                                 - delta->c3 - delta->c6 - delta->c7;
452
453                 if (delta->mperf == 0)
454                         delta->mperf = 1;       /* divide by 0 protection */
455
456                 /*
457                  * for "extra msr", just copy the latest w/o subtracting
458                  */
459                 delta->extra_msr = after->extra_msr;
460                 if (errors) {
461                         fprintf(stderr, "ERROR cpu%d before:\n", before->cpu);
462                         dump_cnt(before);
463                         fprintf(stderr, "ERROR cpu%d after:\n", before->cpu);
464                         dump_cnt(after);
465                         errors = 0;
466                 }
467         }
468         return 0;
469 }
470
471 void compute_average(struct counters *delta, struct counters *avg)
472 {
473         struct counters *sum;
474
475         sum = calloc(1, sizeof(struct counters));
476         if (sum == NULL) {
477                 perror("calloc sum");
478                 exit(1);
479         }
480
481         for (; delta; delta = delta->next) {
482                 sum->tsc += delta->tsc;
483                 sum->c1 += delta->c1;
484                 sum->c3 += delta->c3;
485                 sum->c6 += delta->c6;
486                 sum->c7 += delta->c7;
487                 sum->aperf += delta->aperf;
488                 sum->mperf += delta->mperf;
489                 sum->pc2 += delta->pc2;
490                 sum->pc3 += delta->pc3;
491                 sum->pc6 += delta->pc6;
492                 sum->pc7 += delta->pc7;
493         }
494         avg->tsc = sum->tsc/num_cpus;
495         avg->c1 = sum->c1/num_cpus;
496         avg->c3 = sum->c3/num_cpus;
497         avg->c6 = sum->c6/num_cpus;
498         avg->c7 = sum->c7/num_cpus;
499         avg->aperf = sum->aperf/num_cpus;
500         avg->mperf = sum->mperf/num_cpus;
501         avg->pc2 = sum->pc2/num_cpus;
502         avg->pc3 = sum->pc3/num_cpus;
503         avg->pc6 = sum->pc6/num_cpus;
504         avg->pc7 = sum->pc7/num_cpus;
505
506         free(sum);
507 }
508
509 void get_counters(struct counters *cnt)
510 {
511         for ( ; cnt; cnt = cnt->next) {
512                 if (cpu_migrate(cnt->cpu)) {
513                         need_reinitialize = 1;
514                         return;
515                 }
516
517                 cnt->tsc = get_msr(cnt->cpu, MSR_TSC);
518                 if (do_nhm_cstates)
519                         cnt->c3 = get_msr(cnt->cpu, MSR_CORE_C3_RESIDENCY);
520                 if (do_nhm_cstates)
521                         cnt->c6 = get_msr(cnt->cpu, MSR_CORE_C6_RESIDENCY);
522                 if (do_snb_cstates)
523                         cnt->c7 = get_msr(cnt->cpu, MSR_CORE_C7_RESIDENCY);
524                 if (has_aperf)
525                         cnt->aperf = get_msr(cnt->cpu, MSR_APERF);
526                 if (has_aperf)
527                         cnt->mperf = get_msr(cnt->cpu, MSR_MPERF);
528                 if (do_snb_cstates)
529                         cnt->pc2 = get_msr(cnt->cpu, MSR_PKG_C2_RESIDENCY);
530                 if (do_nhm_cstates)
531                         cnt->pc3 = get_msr(cnt->cpu, MSR_PKG_C3_RESIDENCY);
532                 if (do_nhm_cstates)
533                         cnt->pc6 = get_msr(cnt->cpu, MSR_PKG_C6_RESIDENCY);
534                 if (do_snb_cstates)
535                         cnt->pc7 = get_msr(cnt->cpu, MSR_PKG_C7_RESIDENCY);
536                 if (extra_msr_offset)
537                         cnt->extra_msr = get_msr(cnt->cpu, extra_msr_offset);
538         }
539 }
540
541 void print_nehalem_info(void)
542 {
543         unsigned long long msr;
544         unsigned int ratio;
545
546         if (!do_nehalem_platform_info)
547                 return;
548
549         msr = get_msr(0, MSR_NEHALEM_PLATFORM_INFO);
550
551         ratio = (msr >> 40) & 0xFF;
552         fprintf(stderr, "%d * %.0f = %.0f MHz max efficiency\n",
553                 ratio, bclk, ratio * bclk);
554
555         ratio = (msr >> 8) & 0xFF;
556         fprintf(stderr, "%d * %.0f = %.0f MHz TSC frequency\n",
557                 ratio, bclk, ratio * bclk);
558
559         if (verbose > 1)
560                 fprintf(stderr, "MSR_NEHALEM_PLATFORM_INFO: 0x%llx\n", msr);
561
562         if (!do_nehalem_turbo_ratio_limit)
563                 return;
564
565         msr = get_msr(0, MSR_NEHALEM_TURBO_RATIO_LIMIT);
566
567         ratio = (msr >> 24) & 0xFF;
568         if (ratio)
569                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 4 active cores\n",
570                         ratio, bclk, ratio * bclk);
571
572         ratio = (msr >> 16) & 0xFF;
573         if (ratio)
574                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 3 active cores\n",
575                         ratio, bclk, ratio * bclk);
576
577         ratio = (msr >> 8) & 0xFF;
578         if (ratio)
579                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 2 active cores\n",
580                         ratio, bclk, ratio * bclk);
581
582         ratio = (msr >> 0) & 0xFF;
583         if (ratio)
584                 fprintf(stderr, "%d * %.0f = %.0f MHz max turbo 1 active cores\n",
585                         ratio, bclk, ratio * bclk);
586
587 }
588
589 void free_counter_list(struct counters *list)
590 {
591         struct counters *p;
592
593         for (p = list; p; ) {
594                 struct counters *free_me;
595
596                 free_me = p;
597                 p = p->next;
598                 free(free_me);
599         }
600 }
601
602 void free_all_counters(void)
603 {
604         free_counter_list(cnt_even);
605         cnt_even = NULL;
606
607         free_counter_list(cnt_odd);
608         cnt_odd = NULL;
609
610         free_counter_list(cnt_delta);
611         cnt_delta = NULL;
612
613         free_counter_list(cnt_average);
614         cnt_average = NULL;
615 }
616
617 void insert_counters(struct counters **list,
618         struct counters *new)
619 {
620         struct counters *prev;
621
622         /*
623          * list was empty
624          */
625         if (*list == NULL) {
626                 new->next = *list;
627                 *list = new;
628                 return;
629         }
630
631         if (!summary_only)
632                 show_cpu = 1;   /* there is more than one CPU */
633
634         /*
635          * insert on front of list.
636          * It is sorted by ascending package#, core#, cpu#
637          */
638         if (((*list)->pkg > new->pkg) ||
639             (((*list)->pkg == new->pkg) && ((*list)->core > new->core)) ||
640             (((*list)->pkg == new->pkg) && ((*list)->core == new->core) && ((*list)->cpu > new->cpu))) {
641                 new->next = *list;
642                 *list = new;
643                 return;
644         }
645
646         prev = *list;
647
648         while (prev->next && (prev->next->pkg < new->pkg)) {
649                 prev = prev->next;
650                 if (!summary_only)
651                         show_pkg = 1;   /* there is more than 1 package */
652         }
653
654         while (prev->next && (prev->next->pkg == new->pkg)
655                 && (prev->next->core < new->core)) {
656                 prev = prev->next;
657                 if (!summary_only)
658                         show_core = 1;  /* there is more than 1 core */
659         }
660
661         while (prev->next && (prev->next->pkg == new->pkg)
662                 && (prev->next->core == new->core)
663                 && (prev->next->cpu < new->cpu)) {
664                 prev = prev->next;
665         }
666
667         /*
668          * insert after "prev"
669          */
670         new->next = prev->next;
671         prev->next = new;
672 }
673
674 void alloc_new_counters(int pkg, int core, int cpu)
675 {
676         struct counters *new;
677
678         if (verbose > 1)
679                 printf("pkg%d core%d, cpu%d\n", pkg, core, cpu);
680
681         new = (struct counters *)calloc(1, sizeof(struct counters));
682         if (new == NULL) {
683                 perror("calloc");
684                 exit(1);
685         }
686         new->pkg = pkg;
687         new->core = core;
688         new->cpu = cpu;
689         insert_counters(&cnt_odd, new);
690
691         new = (struct counters *)calloc(1,
692                 sizeof(struct counters));
693         if (new == NULL) {
694                 perror("calloc");
695                 exit(1);
696         }
697         new->pkg = pkg;
698         new->core = core;
699         new->cpu = cpu;
700         insert_counters(&cnt_even, new);
701
702         new = (struct counters *)calloc(1, sizeof(struct counters));
703         if (new == NULL) {
704                 perror("calloc");
705                 exit(1);
706         }
707         new->pkg = pkg;
708         new->core = core;
709         new->cpu = cpu;
710         insert_counters(&cnt_delta, new);
711
712         new = (struct counters *)calloc(1, sizeof(struct counters));
713         if (new == NULL) {
714                 perror("calloc");
715                 exit(1);
716         }
717         new->pkg = pkg;
718         new->core = core;
719         new->cpu = cpu;
720         cnt_average = new;
721 }
722
723 int get_physical_package_id(int cpu)
724 {
725         char path[64];
726         FILE *filep;
727         int pkg;
728
729         sprintf(path, "/sys/devices/system/cpu/cpu%d/topology/physical_package_id", cpu);
730         filep = fopen(path, "r");
731         if (filep == NULL) {
732                 perror(path);
733                 exit(1);
734         }
735         fscanf(filep, "%d", &pkg);
736         fclose(filep);
737         return pkg;
738 }
739
740 int get_core_id(int cpu)
741 {
742         char path[64];
743         FILE *filep;
744         int core;
745
746         sprintf(path, "/sys/devices/system/cpu/cpu%d/topology/core_id", cpu);
747         filep = fopen(path, "r");
748         if (filep == NULL) {
749                 perror(path);
750                 exit(1);
751         }
752         fscanf(filep, "%d", &core);
753         fclose(filep);
754         return core;
755 }
756
757 /*
758  * run func(index, cpu) on every cpu in /proc/stat
759  */
760
761 int for_all_cpus(void (func)(int, int, int))
762 {
763         FILE *fp;
764         int cpu_count;
765         int retval;
766
767         fp = fopen(proc_stat, "r");
768         if (fp == NULL) {
769                 perror(proc_stat);
770                 exit(1);
771         }
772
773         retval = fscanf(fp, "cpu %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n");
774         if (retval != 0) {
775                 perror("/proc/stat format");
776                 exit(1);
777         }
778
779         for (cpu_count = 0; ; cpu_count++) {
780                 int cpu;
781
782                 retval = fscanf(fp, "cpu%u %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n", &cpu);
783                 if (retval != 1)
784                         break;
785
786                 func(get_physical_package_id(cpu), get_core_id(cpu), cpu);
787         }
788         fclose(fp);
789         return cpu_count;
790 }
791
792 void re_initialize(void)
793 {
794         printf("turbostat: topology changed, re-initializing.\n");
795         free_all_counters();
796         num_cpus = for_all_cpus(alloc_new_counters);
797         need_reinitialize = 0;
798         cpu_mask_uninit();
799         cpu_mask_init(num_cpus);
800         printf("num_cpus is now %d\n", num_cpus);
801 }
802
803 void dummy(int pkg, int core, int cpu) { return; }
804 /*
805  * check to see if a cpu came on-line
806  */
807 void verify_num_cpus(void)
808 {
809         int new_num_cpus;
810
811         new_num_cpus = for_all_cpus(dummy);
812
813         if (new_num_cpus != num_cpus) {
814                 if (verbose)
815                         printf("num_cpus was %d, is now  %d\n",
816                                 num_cpus, new_num_cpus);
817                 need_reinitialize = 1;
818         }
819 }
820
821 void turbostat_loop()
822 {
823 restart:
824         get_counters(cnt_even);
825         gettimeofday(&tv_even, (struct timezone *)NULL);
826
827         while (1) {
828                 verify_num_cpus();
829                 if (need_reinitialize) {
830                         re_initialize();
831                         goto restart;
832                 }
833                 sleep(interval_sec);
834                 get_counters(cnt_odd);
835                 gettimeofday(&tv_odd, (struct timezone *)NULL);
836
837                 compute_delta(cnt_odd, cnt_even, cnt_delta);
838                 timersub(&tv_odd, &tv_even, &tv_delta);
839                 compute_average(cnt_delta, cnt_average);
840                 print_counters(cnt_delta);
841                 if (need_reinitialize) {
842                         re_initialize();
843                         goto restart;
844                 }
845                 sleep(interval_sec);
846                 get_counters(cnt_even);
847                 gettimeofday(&tv_even, (struct timezone *)NULL);
848                 compute_delta(cnt_even, cnt_odd, cnt_delta);
849                 timersub(&tv_even, &tv_odd, &tv_delta);
850                 compute_average(cnt_delta, cnt_average);
851                 print_counters(cnt_delta);
852         }
853 }
854
855 void check_dev_msr()
856 {
857         struct stat sb;
858
859         if (stat("/dev/cpu/0/msr", &sb)) {
860                 fprintf(stderr, "no /dev/cpu/0/msr\n");
861                 fprintf(stderr, "Try \"# modprobe msr\"\n");
862                 exit(-5);
863         }
864 }
865
866 void check_super_user()
867 {
868         if (getuid() != 0) {
869                 fprintf(stderr, "must be root\n");
870                 exit(-6);
871         }
872 }
873
874 int has_nehalem_turbo_ratio_limit(unsigned int family, unsigned int model)
875 {
876         if (!genuine_intel)
877                 return 0;
878
879         if (family != 6)
880                 return 0;
881
882         switch (model) {
883         case 0x1A:      /* Core i7, Xeon 5500 series - Bloomfield, Gainstown NHM-EP */
884         case 0x1E:      /* Core i7 and i5 Processor - Clarksfield, Lynnfield, Jasper Forest */
885         case 0x1F:      /* Core i7 and i5 Processor - Nehalem */
886         case 0x25:      /* Westmere Client - Clarkdale, Arrandale */
887         case 0x2C:      /* Westmere EP - Gulftown */
888         case 0x2A:      /* SNB */
889         case 0x2D:      /* SNB Xeon */
890         case 0x3A:      /* IVB */
891         case 0x3D:      /* IVB Xeon */
892                 return 1;
893         case 0x2E:      /* Nehalem-EX Xeon - Beckton */
894         case 0x2F:      /* Westmere-EX Xeon - Eagleton */
895         default:
896                 return 0;
897         }
898 }
899
900 int is_snb(unsigned int family, unsigned int model)
901 {
902         if (!genuine_intel)
903                 return 0;
904
905         switch (model) {
906         case 0x2A:
907         case 0x2D:
908                 return 1;
909         }
910         return 0;
911 }
912
913 double discover_bclk(unsigned int family, unsigned int model)
914 {
915         if (is_snb(family, model))
916                 return 100.00;
917         else
918                 return 133.33;
919 }
920
921 void check_cpuid()
922 {
923         unsigned int eax, ebx, ecx, edx, max_level;
924         unsigned int fms, family, model, stepping;
925
926         eax = ebx = ecx = edx = 0;
927
928         asm("cpuid" : "=a" (max_level), "=b" (ebx), "=c" (ecx), "=d" (edx) : "a" (0));
929
930         if (ebx == 0x756e6547 && edx == 0x49656e69 && ecx == 0x6c65746e)
931                 genuine_intel = 1;
932
933         if (verbose)
934                 fprintf(stderr, "%.4s%.4s%.4s ",
935                         (char *)&ebx, (char *)&edx, (char *)&ecx);
936
937         asm("cpuid" : "=a" (fms), "=c" (ecx), "=d" (edx) : "a" (1) : "ebx");
938         family = (fms >> 8) & 0xf;
939         model = (fms >> 4) & 0xf;
940         stepping = fms & 0xf;
941         if (family == 6 || family == 0xf)
942                 model += ((fms >> 16) & 0xf) << 4;
943
944         if (verbose)
945                 fprintf(stderr, "%d CPUID levels; family:model:stepping 0x%x:%x:%x (%d:%d:%d)\n",
946                         max_level, family, model, stepping, family, model, stepping);
947
948         if (!(edx & (1 << 5))) {
949                 fprintf(stderr, "CPUID: no MSR\n");
950                 exit(1);
951         }
952
953         /*
954          * check max extended function levels of CPUID.
955          * This is needed to check for invariant TSC.
956          * This check is valid for both Intel and AMD.
957          */
958         ebx = ecx = edx = 0;
959         asm("cpuid" : "=a" (max_level), "=b" (ebx), "=c" (ecx), "=d" (edx) : "a" (0x80000000));
960
961         if (max_level < 0x80000007) {
962                 fprintf(stderr, "CPUID: no invariant TSC (max_level 0x%x)\n", max_level);
963                 exit(1);
964         }
965
966         /*
967          * Non-Stop TSC is advertised by CPUID.EAX=0x80000007: EDX.bit8
968          * this check is valid for both Intel and AMD
969          */
970         asm("cpuid" : "=a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx) : "a" (0x80000007));
971         has_invariant_tsc = edx & (1 << 8);
972
973         if (!has_invariant_tsc) {
974                 fprintf(stderr, "No invariant TSC\n");
975                 exit(1);
976         }
977
978         /*
979          * APERF/MPERF is advertised by CPUID.EAX=0x6: ECX.bit0
980          * this check is valid for both Intel and AMD
981          */
982
983         asm("cpuid" : "=a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx) : "a" (0x6));
984         has_aperf = ecx & (1 << 0);
985         if (!has_aperf) {
986                 fprintf(stderr, "No APERF MSR\n");
987                 exit(1);
988         }
989
990         do_nehalem_platform_info = genuine_intel && has_invariant_tsc;
991         do_nhm_cstates = genuine_intel; /* all Intel w/ non-stop TSC have NHM counters */
992         do_snb_cstates = is_snb(family, model);
993         bclk = discover_bclk(family, model);
994
995         do_nehalem_turbo_ratio_limit = has_nehalem_turbo_ratio_limit(family, model);
996 }
997
998
999 void usage()
1000 {
1001         fprintf(stderr, "%s: [-v] [-M MSR#] [-i interval_sec | command ...]\n",
1002                 progname);
1003         exit(1);
1004 }
1005
1006
1007 /*
1008  * in /dev/cpu/ return success for names that are numbers
1009  * ie. filter out ".", "..", "microcode".
1010  */
1011 int dir_filter(const struct dirent *dirp)
1012 {
1013         if (isdigit(dirp->d_name[0]))
1014                 return 1;
1015         else
1016                 return 0;
1017 }
1018
1019 int open_dev_cpu_msr(int dummy1)
1020 {
1021         return 0;
1022 }
1023
1024 void turbostat_init()
1025 {
1026         check_cpuid();
1027
1028         check_dev_msr();
1029         check_super_user();
1030
1031         num_cpus = for_all_cpus(alloc_new_counters);
1032         cpu_mask_init(num_cpus);
1033
1034         if (verbose)
1035                 print_nehalem_info();
1036 }
1037
1038 int fork_it(char **argv)
1039 {
1040         int retval;
1041         pid_t child_pid;
1042         get_counters(cnt_even);
1043         gettimeofday(&tv_even, (struct timezone *)NULL);
1044
1045         child_pid = fork();
1046         if (!child_pid) {
1047                 /* child */
1048                 execvp(argv[0], argv);
1049         } else {
1050                 int status;
1051
1052                 /* parent */
1053                 if (child_pid == -1) {
1054                         perror("fork");
1055                         exit(1);
1056                 }
1057
1058                 signal(SIGINT, SIG_IGN);
1059                 signal(SIGQUIT, SIG_IGN);
1060                 if (waitpid(child_pid, &status, 0) == -1) {
1061                         perror("wait");
1062                         exit(1);
1063                 }
1064         }
1065         get_counters(cnt_odd);
1066         gettimeofday(&tv_odd, (struct timezone *)NULL);
1067         retval = compute_delta(cnt_odd, cnt_even, cnt_delta);
1068
1069         timersub(&tv_odd, &tv_even, &tv_delta);
1070         compute_average(cnt_delta, cnt_average);
1071         if (!retval)
1072                 print_counters(cnt_delta);
1073
1074         fprintf(stderr, "%.6f sec\n", tv_delta.tv_sec + tv_delta.tv_usec/1000000.0);
1075
1076         return 0;
1077 }
1078
1079 void cmdline(int argc, char **argv)
1080 {
1081         int opt;
1082
1083         progname = argv[0];
1084
1085         while ((opt = getopt(argc, argv, "+svi:M:")) != -1) {
1086                 switch (opt) {
1087                 case 's':
1088                         summary_only++;
1089                         break;
1090                 case 'v':
1091                         verbose++;
1092                         break;
1093                 case 'i':
1094                         interval_sec = atoi(optarg);
1095                         break;
1096                 case 'M':
1097                         sscanf(optarg, "%x", &extra_msr_offset);
1098                         if (verbose > 1)
1099                                 fprintf(stderr, "MSR 0x%X\n", extra_msr_offset);
1100                         break;
1101                 default:
1102                         usage();
1103                 }
1104         }
1105 }
1106
1107 int main(int argc, char **argv)
1108 {
1109         cmdline(argc, argv);
1110
1111         if (verbose > 1)
1112                 fprintf(stderr, "turbostat Dec 6, 2010"
1113                         " - Len Brown <lenb@kernel.org>\n");
1114         if (verbose > 1)
1115                 fprintf(stderr, "http://userweb.kernel.org/~lenb/acpi/utils/pmtools/turbostat/\n");
1116
1117         turbostat_init();
1118
1119         /*
1120          * if any params left, it must be a command to fork
1121          */
1122         if (argc - optind)
1123                 return fork_it(argv + optind);
1124         else
1125                 turbostat_loop();
1126
1127         return 0;
1128 }