-
Notifications
You must be signed in to change notification settings - Fork 15
/
powerstat.c
3230 lines (2833 loc) · 77.8 KB
/
powerstat.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2011-2021 Canonical
* Copyright (C) 2021-2024 Colin Ian King
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Author: Colin Ian King <colin.i.king@gmail.com>
*/
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdint.h>
#include <inttypes.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <limits.h>
#include <dirent.h>
#include <ctype.h>
#include <math.h>
#include <float.h>
#include <time.h>
#include <getopt.h>
#include <sched.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <fcntl.h>
#include <linux/connector.h>
#include <linux/netlink.h>
#include <linux/cn_proc.h>
#define MIN_RUN_DURATION (5*60) /* We recommend a run of 5 minutes */
#define MIN_RUN_DURATION_RAPL (60) /* RAPL, 60 seconds is enough */
#define SAMPLE_DELAY (10.0) /* Delay between samples in seconds */
#define SAMPLE_DELAY_RAPL (1.0) /* Delay between samples for RAPL mode */
#define START_DELAY (3*60) /* Delay to wait before sampling */
#define START_DELAY_RAPL (0.0) /* Delay to wait before sampling, RAPL */
#define MIN_SAMPLE_DELAY (0.5) /* Minimum sample delay */
#define ROLLING_AVERAGE_SECS (120) /* 2 minute rolling average for power calculation */
#define STANDARD_AVERAGE_SECS (120)
#define MAX_MEASUREMENTS (ROLLING_AVERAGE_SECS + 10)
#define MAX_PIDS (32769) /* Hash Max PIDs */
#define RATE_ZERO_LIMIT (0.001) /* Less than this we call the power rate zero */
#define IDLE_THRESHOLD (98) /* Less than this and we assume the device is not idle */
#define MAX_POWER_DOMAINS (16) /* Maximum number of power domains allowed */
#define MAX_THERMAL_ZONES (16) /* Maximum number of thermal zones allowed */
/* Histogram specific constants */
#define MAX_DIVISIONS (10)
#define HISTOGRAM_WIDTH (40)
#define GOT_TGID (0x01)
#define GOT_PPID (0x02)
#define GOT_ALL (GOT_TGID | GOT_PPID)
#define I915_ENERGY_UJ "/sys/kernel/debug/dri/0/i915_energy_uJ"
#define SIZEOF_ARRAY(a) (sizeof(a) / sizeof(a[0]))
#define MAX(x, y) (x) > (y) ? (x) : (y)
#define MIN(x, y) (x) > (y) ? (y) : (x)
#define FLOAT_TINY (0.0000001)
#define FLOAT_CMP(a, b) (fabs((a) - (b)) < FLOAT_TINY)
/* Statistics gathered from /proc/stat and process activity */
typedef enum {
CPU_USER = 0,
CPU_NICE,
CPU_SYS,
CPU_IDLE,
CPU_IOWAIT,
CPU_TOTAL,
CPU_IRQ ,
CPU_SOFTIRQ,
CPU_INTR,
CPU_CTXT,
CPU_PROCS_RUN,
CPU_PROCS_BLK,
CPU_FREQ,
CPU_FREQ_MIN,
CPU_FREQ_MAX,
GPU_FREQ,
PROC_FORK,
PROC_EXEC,
PROC_EXIT,
POWER_TOTAL,
POWER_DOMAIN_0,
THERMAL_ZONE_0 = POWER_DOMAIN_0 + MAX_POWER_DOMAINS,
MAX_VALUES = THERMAL_ZONE_0 + MAX_THERMAL_ZONES,
} stat_type;
/*
* C-State information, 1 for each unique C-state
*/
typedef struct cpu_state {
struct cpu_state *hash_next; /* next in hash table */
struct cpu_state *list_next; /* linked list of C-states */
struct cpu_info *cpu_info_list; /* linked list of CPUs that have this state */
char *name; /* C-State name, e.g. C1E-IVB */
char *name_short; /* short name, e.g. C1E */
uint64_t latency; /* latency */
uint64_t usage_total; /* total usage count */
double resident; /* percentage time resident in this state */
} cpu_state_t;
/*
* Per CPU C-State info, total of these are
* N-CPUs x N-CPU states
*/
typedef struct cpu_info {
struct cpu_info *hash_next; /* Next in hash table */
struct cpu_info *list_next; /* Next in list of cpu_infos list */
char *state; /* C-State sysfs name, e.g 'state2' */
cpu_state_t *cpu_state; /* C-State info */
double prev_tod; /* Previous Time-of-Day */
double tod; /* Time of Day */
double tod_diff; /* Difference between current and previous tod */
uint64_t prev_time; /* Previous #microseconds in this C-state */
uint64_t time; /* Current #microseconds in this C-state */
uint64_t time_diff; /* Difference in microseconds in this C-state */
uint64_t prev_usage; /* Previous usage count */
uint64_t usage; /* Current usage count */
uint64_t usage_diff; /* Difference in usage count */
uint32_t cpu_id; /* CPU ID */
} cpu_info_t;
typedef struct {
double threshold;
double scale;
char *suffix;
} cpu_freq_scale_t;
/* Different freq scaling rates */
static const cpu_freq_scale_t cpu_freq_scale[] = {
{ 1e1, 1e0, "Hz" },
{ 1e4, 1e3, "KHz" },
{ 1e7, 1e6, "MHz" },
{ 1e10, 1e9, "GHz" },
{ 1e13, 1e12, "THz" },
{ 1e16, 1e15, "PHz" },
{ -1.0, -1.0, NULL }
};
#define MAX_STATES (67)
#define MAX_CPUS (1031)
static cpu_state_t *cpu_states_list; /* List of all CPU-states */
static cpu_state_t *cpu_states[MAX_STATES];/* Hash of all CPU-states */
static cpu_info_t *cpu_info[MAX_CPUS]; /* Hash of all CPU infos */
static const char *cpu_path = "/sys/devices/system/cpu";
/* Arg opt flags */
#define OPTS_SHOW_PROC_ACTIVITY (0x0001) /* dump out process activity */
#define OPTS_REDO_NETLINK_BUSY (0x0002) /* tasks fork/exec/exit */
#define OPTS_REDO_WHEN_NOT_IDLE (0x0004) /* when idle below idle_threshold */
#define OPTS_ZERO_RATE_ALLOW (0x0008) /* force allow zero rates */
#define OPTS_ROOT_PRIV (0x0010) /* has root privilege */
#define OPTS_STANDARD_AVERAGE (0x0020) /* calc standard average */
#define OPTS_RAPL (0x0040) /* use Intel RAPL */
#define OPTS_START_DELAY (0x0080) /* -d option used */
#define OPTS_SAMPLE_DELAY (0x0100) /* sample delay has been specified */
#define OPTS_DOMAIN_STATS (0x0200) /* Extra wide power domain stats */
#define OPTS_HISTOGRAM (0x0400) /* Histogram */
#define OPTS_CSTATES (0x0800) /* C-STATES dump */
#define OPTS_CPU_FREQ (0x1000) /* Average CPU frequency */
#define OPTS_NO_STATS_HEADINGS (0x2000) /* No stats headings */
#define OPTS_THERMAL_ZONE (0x4000) /* Thermal zones */
#define OPTS_GPU_FREQ (0x8000) /* GPU frequency */
#define OPTS_USE_NETLINK (OPTS_SHOW_PROC_ACTIVITY | \
OPTS_REDO_NETLINK_BUSY | \
OPTS_ROOT_PRIV)
#define SYS_CLASS_POWER_SUPPLY "/sys/class/power_supply"
#define PROC_ACPI_BATTERY "/proc/acpi/battery"
#define SYS_FIELD_VOLTAGE "POWER_SUPPLY_VOLTAGE_NOW="
#define SYS_FIELD_WATTS_RATE "POWER_SUPPLY_POWER_NOW="
#define SYS_FIELD_WATTS_LEFT "POWER_SUPPLY_ENERGY_NOW="
#define SYS_FIELD_AMPS_RATE "POWER_SUPPLY_CURRENT_NOW="
#define SYS_FIELD_AMPS_LEFT "POWER_SUPPLY_CHARGE_NOW="
#define SYS_FIELD_STATUS_DISCHARGING "POWER_SUPPLY_STATUS=Discharging"
#if defined(__x86_64__) || defined(__x86_64) || \
defined(__i386__) || defined(__i386)
#define POWERSTAT_X86
#endif
/* Measurement entry */
typedef struct {
double value; /* Measurement value */
time_t when; /* When it was measured */
} measurement_t;
/* Statistics entry */
typedef struct {
double value[MAX_VALUES]; /* /proc/stats values */
bool inaccurate[MAX_VALUES]; /* True if not accurate reading */
} stats_t;
/* /proc info cache */
typedef struct {
pid_t pid; /* Process ID */
char *cmdline; /* /proc/pid/cmdline text */
} proc_info_t;
/* Log item link list */
typedef struct log_item_t {
struct log_item_t *next; /* Next log item */
char *text; /* Log text */
} log_item_t;
/* Log list header */
typedef struct {
log_item_t *head; /* List head */
log_item_t *tail; /* List tail */
} log_t;
/* RAPL domain info */
typedef struct rapl_info {
struct rapl_info *next; /* Next RAPL domain */
char *name; /* RAPL name */
char *domain_name; /* RAPL domain name */
double max_energy_uj; /* Energy in micro Joules */
double last_energy_uj; /* Last energy reading in micro Joules */
double t_last; /* Time of last reading */
} rapl_info_t;
/* Thermal zone info */
typedef struct tz_info {
struct tz_info *next; /* Next TZ */
char *name; /* Thermal Zone pathname */
char *type; /* Thermal Zone type */
} tz_info_t;
#if defined(POWERSTAT_X86)
static rapl_info_t *rapl_list = NULL; /* List of RAPL domains */
#endif
static tz_info_t *tz_list = NULL; /* List of thermal zones */
static proc_info_t *proc_info[MAX_PIDS]; /* Proc hash table */
static uint32_t max_readings; /* number of samples to gather */
static double sample_delay = SAMPLE_DELAY; /* time between each sample in secs */
static int32_t start_delay = START_DELAY; /* seconds before we start displaying stats */
static double idle_threshold = IDLE_THRESHOLD; /* lower than this and the CPU is busy */
static log_t infolog; /* log */
static uint32_t opts; /* opt arg opt flags */
static volatile bool stop_recv; /* sighandler stop flag */
static bool power_calc_from_capacity = false; /* true of power is calculated via capacity change */
static const char *app_name = "powerstat"; /* name of application */
static const char *(*get_domain)(const int i) = NULL;
static int power_domains = 0; /* Number of RAPL domains */
static int thermal_zones = 0; /* Number of thermal zones */
static const char *tz_get_type(const int n);
static int tz_get_temperature(stats_t *stats);
/*
* Attempt to catch a range of signals so
* we can clean
*/
static const int signals[] = {
/* POSIX.1-1990 */
#ifdef SIGHUP
SIGHUP,
#endif
#ifdef SIGINT
SIGINT,
#endif
#ifdef SIGQUIT
SIGQUIT,
#endif
#ifdef SIGFPE
SIGFPE,
#endif
#ifdef SIGTERM
SIGTERM,
#endif
#ifdef SIGUSR1
SIGUSR1,
#endif
#ifdef SIGUSR2
SIGUSR2,
/* POSIX.1-2001 */
#endif
#ifdef SIGXCPU
SIGXCPU,
#endif
#ifdef SIGXFSZ
SIGXFSZ,
#endif
/* Linux various */
#ifdef SIGIOT
SIGIOT,
#endif
#ifdef SIGSTKFLT
SIGSTKFLT,
#endif
#ifdef SIGPWR
SIGPWR,
#endif
#ifdef SIGINFO
SIGINFO,
#endif
#ifdef SIGVTALRM
SIGVTALRM,
#endif
};
/*
* bsd_strlcpy()
* BSD strlcpy
*/
static size_t bsd_strlcpy(char *dst, const char *src, size_t len)
{
char *d = dst;
const char *s = src;
size_t n = len;
if (n) {
while (--n) {
char c = *s++;
*d++ = c;
if (c == '\0')
break;
}
}
if (!n) {
if (len)
*d = '\0';
while (*s)
s++;
}
return (s - src - 1);
}
/*
* set_prioity
* set high priority to try and get netlink activity
* before short lived processes die
*/
static void set_priority(void)
{
int max;
struct sched_param param;
int sched;
#if defined(SCHED_DEADLINE)
sched = SCHED_DEADLINE;
#elif defined(SCHED_SCHED_FIFO)
sched = SCHED_FIFO;
#elif defined(SCHED_RR)
sched = SCHED_FIFO;
#else
sched = SCHED_OTHER; /* Oh well */
#endif
if ((max = sched_get_priority_max(sched)) < 0)
return;
(void)memset(¶m, 0, sizeof(param));
param.sched_priority = max;
(void)sched_setscheduler(getpid(), sched, ¶m);
}
/*
* file_get()
* read a line from a /sys file
*/
static char *file_get(const char *const file)
{
FILE *fp;
char buffer[4096];
if ((fp = fopen(file, "r")) == NULL)
return NULL;
if (fgets(buffer, sizeof(buffer), fp) == NULL) {
(void)fclose(fp);
return NULL;
}
(void)fclose(fp);
return strdup(buffer);
}
/*
* file_get_uint64()
* read a line from a /sys file
*/
static int file_get_uint64(const char *const file, uint64_t *val)
{
FILE *fp;
*val = 0;
if ((fp = fopen(file, "r")) == NULL)
return -1;
if (fscanf(fp, "%" SCNu64, val) != 1) {
*val = 0;
(void)fclose(fp);
return -1;
}
(void)fclose(fp);
return 0;
}
/*
* cpu_freq_format()
* scale cpu freq into a human readable form
*/
static const char *cpu_freq_format(const double freq)
{
static char buffer[40];
char *suffix = "EHz";
const double f = freq * 1000000.0; /* MHz to Hz */
double scale = 1e18;
size_t i;
if (freq > 0) {
for (i = 0; cpu_freq_scale[i].suffix; i++) {
if (f < cpu_freq_scale[i].threshold) {
suffix = cpu_freq_scale[i].suffix;
scale = cpu_freq_scale[i].scale;
break;
}
}
(void)snprintf(buffer, sizeof(buffer), "%5.2f %-3s",
f / scale, suffix);
} else {
(void)snprintf(buffer, sizeof(buffer), " N/A ");
}
return buffer;
}
/*
* get_parent_pid()
* get parent pid and set is_thread to true if process
* not forked but a newly created thread
*/
static pid_t get_parent_pid(const pid_t pid, bool *is_thread)
{
FILE *fp;
char path[PATH_MAX];
char buffer[4096];
pid_t tgid = 0, ppid = 0;
unsigned int got = 0;
*is_thread = false;
(void)snprintf(path, sizeof(path), "/proc/%u/status", pid);
if ((fp = fopen(path, "r")) == NULL)
return 0;
while (((got & GOT_ALL) != GOT_ALL) &&
(fgets(buffer, sizeof(buffer), fp) != NULL)) {
if (!strncmp(buffer, "Tgid:", 5)) {
if (sscanf(buffer + 5, "%10u", &tgid) == 1) {
got |= GOT_TGID;
} else {
tgid = 0;
}
}
if (!strncmp(buffer, "PPid:", 5)) {
if (sscanf(buffer + 5, "%10u", &ppid) == 1) {
got |= GOT_PPID;
} else {
ppid = 0;
}
}
}
(void)fclose(fp);
if ((got & GOT_ALL) == GOT_ALL) {
/* TGID and PID are not the same if it is a thread */
if (tgid != pid) {
/* In this case, the parent is the TGID */
ppid = tgid;
*is_thread = true;
}
} else {
ppid = 0;
}
return ppid;
}
/*
* tty_height()
* try and find height of tty
*/
static int tty_height(void)
{
#ifdef TIOCGWINSZ
int fd = 0;
struct winsize ws;
(void)memset(&ws, 0, sizeof(ws));
/* if tty and we can get a sane width, return it */
if (isatty(fd) &&
(ioctl(fd, TIOCGWINSZ, &ws) != -1) &&
(0 < ws.ws_row) &&
(ws.ws_row == (size_t)ws.ws_row))
return ws.ws_row;
#endif
return 25; /* else standard tty 80x25 */
}
/*
* timeval_to_double
* timeval to a double (in seconds)
*/
static inline double timeval_to_double(const struct timeval *const tv)
{
return (double)tv->tv_sec + ((double)tv->tv_usec / 1000000.0);
}
/*
* double_to_timeval
* seconds in double to timeval
*/
static inline void double_to_timeval(const double val, struct timeval *tv)
{
tv->tv_sec = val;
tv->tv_usec = (val - (time_t)val) * 1000000.0;
}
/*
* gettime_to_double()
* get time as a double
*/
static double gettime_to_double(void)
{
struct timeval tv;
if (gettimeofday(&tv, NULL) < 0) {
(void)fprintf(stderr, "gettimeofday failed: errno=%d (%s).\n",
errno, strerror(errno));
return -1.0;
}
return timeval_to_double(&tv);
}
/*
* get_time()
* Gather current time in buffer
*/
static void get_time(char *const buffer, const size_t buflen)
{
struct tm tm;
time_t now;
now = time(NULL);
if (now == ((time_t) -1)) {
/* Unknown time! */
(void)snprintf(buffer, buflen, "--:--:-- ");
return;
}
(void)localtime_r(&now, &tm);
(void)snprintf(buffer, buflen, "%2.2d:%2.2d:%2.2d ",
tm.tm_hour, tm.tm_min, tm.tm_sec);
}
/*
* log_init()
* Initialise log head
*/
static inline void log_init(void)
{
infolog.head = NULL;
infolog.tail = NULL;
}
static int log_printf(const char *const fmt, ...) __attribute__((format(printf, 1, 2)));
/*
* log_printf()
* append log messages in log list
*/
static int log_printf(const char *const fmt, ...)
{
char buffer[4096];
char tmbuffer[10];
va_list ap;
log_item_t *log_item;
size_t len;
va_start(ap, fmt);
get_time(tmbuffer, sizeof(tmbuffer));
(void)vsnprintf(buffer, sizeof(buffer), fmt, ap);
va_end(ap);
if ((log_item = calloc(1, sizeof(*log_item))) == NULL) {
(void)fprintf(stderr, "Out of memory allocating log item.\n");
return -1;
}
len = strlen(buffer) + strlen(tmbuffer) + 1;
if ((log_item->text = calloc(1, len)) == NULL) {
free(log_item);
(void)fprintf(stderr, "Out of memory allocating log item text.\n");
return -1;
}
(void)snprintf(log_item->text, len, "%s%s", tmbuffer, buffer);
if (infolog.head == NULL)
infolog.head = log_item;
else
infolog.tail->next = log_item;
infolog.tail = log_item;
return 0;
}
/*
* log_dump()
* dump out any saved log messages
*/
static void log_dump(void)
{
log_item_t *log_item;
if (infolog.head != NULL)
(void)printf("\nLog of fork()/exec()/exit() calls:\n");
for (log_item = infolog.head; log_item; log_item = log_item->next)
(void)printf("%s", log_item->text);
}
/*
* log_free()
* free log messages
*/
static void log_free(void)
{
log_item_t *log_item = infolog.head;
while (log_item) {
log_item_t *log_next = log_item->next;
free(log_item->text);
free(log_item);
log_item = log_next;
}
infolog.head = NULL;
infolog.tail = NULL;
}
/*
* handle_sig()
* catch signals and flag a stop
*/
static void handle_sig(int dummy)
{
(void)dummy;
stop_recv = true;
}
/*
* netlink_connect()
* connect to netlink socket
*/
static int netlink_connect(void)
{
int sock;
struct sockaddr_nl addr;
if ((sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR)) < 0) {
if (errno == EPROTONOSUPPORT)
return -EPROTONOSUPPORT;
(void)fprintf(stderr, "socket failed: errno=%d (%s).\n",
errno, strerror(errno));
return -1;
}
(void)memset(&addr, 0, sizeof(addr));
addr.nl_pid = getpid();
addr.nl_family = AF_NETLINK;
addr.nl_groups = CN_IDX_PROC;
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
(void)fprintf(stderr, "Bind failed: errno=%d (%s).\n",
errno, strerror(errno));
(void)close(sock);
return -1;
}
return sock;
}
/*
* netlink_listen()
* proc connector listen
*/
static int netlink_listen(const int sock)
{
struct iovec iov[3];
struct nlmsghdr nlmsghdr;
struct cn_msg cn_msg;
enum proc_cn_mcast_op op;
(void)memset(&nlmsghdr, 0, sizeof(nlmsghdr));
nlmsghdr.nlmsg_len = NLMSG_LENGTH(sizeof(cn_msg) + sizeof(op));
nlmsghdr.nlmsg_pid = getpid();
nlmsghdr.nlmsg_type = NLMSG_DONE;
iov[0].iov_base = &nlmsghdr;
iov[0].iov_len = sizeof(nlmsghdr);
(void)memset(&cn_msg, 0, sizeof(cn_msg));
cn_msg.id.idx = CN_IDX_PROC;
cn_msg.id.val = CN_VAL_PROC;
cn_msg.len = sizeof(enum proc_cn_mcast_op);
iov[1].iov_base = &cn_msg;
iov[1].iov_len = sizeof(cn_msg);
op = PROC_CN_MCAST_LISTEN;
iov[2].iov_base = &op;
iov[2].iov_len = sizeof(op);
return writev(sock, iov, 3);
}
/*
* stats_set()
* set stats
*/
static void stats_set(
stats_t *const stats,
const double value,
const bool inaccurate)
{
int i;
for (i = 0; i < MAX_VALUES; i++) {
stats->value[i] = value;
stats->inaccurate[i] = inaccurate;
}
}
/*
* stats_set()
* clear stats
*/
static inline void stats_clear(stats_t *const stats)
{
stats_set(stats, 0.0, false);
}
/*
* stats_clear_all()
* zero stats data
*/
static void stats_clear_all(stats_t *const stats, const long int n)
{
int i;
for (i = 0; i < n; i++)
stats_clear(&stats[i]);
}
static void stats_gpu_freq_read(stats_t *const stats)
{
uint64_t freq = 0;
if (file_get_uint64("/sys/class/drm/card0/gt_cur_freq_mhz", &freq) == 0) {
stats->value[GPU_FREQ] = (double)freq;
} else if (file_get_uint64("/sys/class/graphics/fb0/device/drm/card0/gt_cur_freq_mhz", &freq) == 0) {
stats->value[GPU_FREQ] = (double)freq;
} else {
stats->value[GPU_FREQ] = 0.0;
}
}
static void stats_cpu_freq_read(stats_t *const stats)
{
struct dirent **cpu_list = NULL;
int i, n_cpus, n = 0;
double freq_min = 1E12, freq_max = 0.0;
double mant = 1.0; /* geometric mean mantissa */
long int expon = 0; /* goemetric mean exponent */
n_cpus = scandir("/sys/devices/system/cpu", &cpu_list, NULL, alphasort);
for (i = 0; i < n_cpus; i++) {
char *name = cpu_list[i]->d_name;
if (!strncmp(name, "cpu", 3) && isdigit(name[3])) {
char path[PATH_MAX];
uint64_t freq;
(void)snprintf(path, sizeof(path),
"/sys/devices/system/cpu/%s/cpufreq/scaling_cur_freq",
name);
if (file_get_uint64(path, &freq) == 0) {
int e;
const double freq_mhz = (double)freq / 1000.0;
const double f = frexp(freq_mhz, &e);
mant *= f;
expon += e;
if (freq_mhz > freq_max)
freq_max = freq_mhz;
if (freq_mhz < freq_min)
freq_min = freq_mhz;
n++;
}
}
free(cpu_list[i]);
}
if (n_cpus > -1)
free(cpu_list);
if (n) {
const double inverse_n = 1.0 / (double)n;
const double geomean = pow(mant, inverse_n) * pow(2.0, (double)expon * inverse_n);
stats->value[CPU_FREQ] = geomean;
stats->value[CPU_FREQ_MIN] = freq_min;
stats->value[CPU_FREQ_MAX] = freq_max;
} else {
stats->value[CPU_FREQ] = 0.0;
stats->value[CPU_FREQ_MIN] = 0.0;
stats->value[CPU_FREQ_MAX] = 0.0;
}
}
/*
* stats_read()
* gather pertinent /proc/stat data
*/
static int stats_read(stats_t *const stats)
{
FILE *fp;
char buf[4096];
int i, j;
static const stat_type indices[] = {
CPU_USER, CPU_NICE, CPU_SYS, CPU_IDLE,
CPU_IOWAIT, CPU_IRQ, CPU_SOFTIRQ, CPU_CTXT,
CPU_INTR, CPU_PROCS_RUN, CPU_PROCS_BLK, -1
};
for (i = 0; (j = indices[i]) != -1; i++) {
stats->value[j] = 0.0;
stats->inaccurate[j] = true;
}
if ((fp = fopen("/proc/stat", "r")) == NULL) {
(void)fprintf(stderr, "Cannot read /proc/stat, errno=%d (%s).\n",
errno, strerror(errno));
return -1;
}
while (fgets(buf, sizeof(buf), fp) != NULL) {
if (strncmp(buf, "cpu ", 4) == 0)
if (sscanf(buf, "%*s %15lf %15lf %15lf %15lf %15lf %15lf %15lf",
&(stats->value[CPU_USER]),
&(stats->value[CPU_NICE]),
&(stats->value[CPU_SYS]),
&(stats->value[CPU_IDLE]),
&(stats->value[CPU_IOWAIT]),
&(stats->value[CPU_IRQ]),
&(stats->value[CPU_SOFTIRQ])) == 7) {
stats->inaccurate[CPU_USER] = false;
stats->inaccurate[CPU_NICE] = false;
stats->inaccurate[CPU_SYS] = false;
stats->inaccurate[CPU_IDLE] = false;
stats->inaccurate[CPU_IOWAIT] = false;
stats->inaccurate[CPU_IRQ] = false;
stats->inaccurate[CPU_SOFTIRQ] = false;
}
if (strncmp(buf, "ctxt ", 5) == 0)
if (sscanf(buf, "%*s %15lf", &(stats->value[CPU_CTXT])) == 1)
stats->inaccurate[CPU_CTXT] = false;
if (strncmp(buf, "intr ", 5) == 0)
if (sscanf(buf, "%*s %15lf", &(stats->value[CPU_INTR])) == 1)
stats->inaccurate[CPU_INTR] = false;
if (strncmp(buf, "procs_running ", 14) == 0)
if (sscanf(buf, "%*s %15lf", &(stats->value[CPU_PROCS_RUN])) == 1)
stats->inaccurate[CPU_PROCS_RUN] = false;
if (strncmp(buf, "procs_blocked ", 14) == 0)
if (sscanf(buf, "%*s %15lf", &(stats->value[CPU_PROCS_BLK])) == 1)
stats->inaccurate[CPU_PROCS_BLK] = false;
}
(void)fclose(fp);
if (opts & OPTS_CPU_FREQ)
stats_cpu_freq_read(stats);
if (opts & OPTS_GPU_FREQ)
stats_gpu_freq_read(stats);
return 0;
}
/*
* stats_sane()
* check if stats are accurate and calculate a
* sane -ve delta
*/
static double stats_sane(
const stats_t *const s1,
const stats_t *const s2,
const int index)
{
double ret;
/* Discard inaccurate or empty stats */
if (s1->inaccurate[index] || s2->inaccurate[index])
return 0.0;
/*
* On Nexus 4 we occasionally get idle time going backwards so
* work around this by ensuring we don't get -ve deltas.
*/
ret = s2->value[index] - s1->value[index];
return ret < 0.0 ? 0.0 : ret;
}
#define INACCURATE(s1, s2, index) \
(s1->inaccurate[index] | s2->inaccurate[index])
/*
* stats_gather()
* gather up delta between last stats and current to get
* some form of per sample accounting calculated.
*/
static bool stats_gather(
const stats_t *const s1,
const stats_t *const s2,
stats_t *const res)
{
double total;
int i, j;
bool inaccurate = false;
static const int indices[] = {
CPU_USER, CPU_NICE, CPU_SYS, CPU_IDLE,
CPU_IOWAIT, -1
};
res->value[CPU_USER] = stats_sane(s1, s2, CPU_USER);
res->value[CPU_NICE] = stats_sane(s1, s2, CPU_NICE);
res->value[CPU_SYS] = stats_sane(s1, s2, CPU_SYS);
res->value[CPU_IDLE] = stats_sane(s1, s2, CPU_IDLE);
res->value[CPU_IOWAIT] = stats_sane(s1, s2, CPU_IOWAIT);
res->value[CPU_IRQ] = stats_sane(s1, s2, CPU_IRQ);
res->value[CPU_SOFTIRQ] = stats_sane(s1, s2, CPU_SOFTIRQ);
res->value[CPU_CTXT] = stats_sane(s1, s2, CPU_CTXT);
res->value[CPU_INTR] = stats_sane(s1, s2, CPU_INTR);
for (i = 0; (j = indices[i]) != -1; i++)
inaccurate |= (s1->inaccurate[j] | s2->inaccurate[j]);
total = res->value[CPU_USER] + res->value[CPU_NICE] +
res->value[CPU_SYS] + res->value[CPU_IDLE] +
res->value[CPU_IOWAIT];
/*
* This should not happen, but we need to avoid division
* by zero or weird results if the data is deemed valid
*/
if (!inaccurate && total <= 0.0)
return false;
res->value[CPU_TOTAL] = 100.0 * (total - res->value[CPU_IDLE]) / total;