-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmced.c
1394 lines (1257 loc) · 31.3 KB
/
mced.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
/*
* mced.c - MCE daemon.
*
* Based on code from acpid.
* Copyright (c) 2007 Tim Hockin ([email protected])
* Copyright (c) 2007 Google, Inc. ([email protected])
* Portions Copyright (c) 2004 Tim Hockin ([email protected])
* Portions Copyright (c) 2001 Sun Microsystems
* Portions Copyright (c) 2000 Andrew Henroid
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <sys/poll.h>
#include <grp.h>
#include <syslog.h>
#include <stdarg.h>
#include <sys/ioctl.h>
#include <sys/utsname.h>
#include "mced.h"
#include "cmdline.h"
#if ENABLE_MCEDB
#include "mcedb.h"
#endif
#if ENABLE_DBUS
#include "dbus.h"
#endif
#include "ud_socket.h"
/* global debug level */
int mced_debug_level;
/* do we log event info? */
int mced_log_events;
/* the number of non-root clients that are connected */
int mced_non_root_clients;
/* the size of a kernel MCE record in bytes */
size_t mced_kernel_record_len;
/* how many bytes of kernel record to copy */
size_t mced_copy_len;
/* how many bytes of mce structure to zero, if kernel record is smaller */
size_t mced_zero_len;
#if ENABLE_MCEDB
/* global database handle */
struct mce_database *mced_db;
#endif
/* statics */
static const char *progname;
static cmdline_int bootnum = -1;
static cmdline_int debug_level = 0;
static cmdline_bool log_events = 0;
static cmdline_string confdir = MCED_CONFDIR;
static cmdline_string device = MCED_EVENTFILE;
static cmdline_int max_interval_ms = MCED_MAX_INTERVAL;
static cmdline_int min_interval_ms = MCED_MIN_INTERVAL;
static cmdline_int mce_rate_limit = -1;
static cmdline_string socketfile = MCED_SOCKETFILE_V2;
static cmdline_string socketfile_compat = NULL;
static cmdline_bool nosocket = 0;
static cmdline_string socketgroup = NULL;
static cmdline_mode_t socketmode = MCED_SOCKETMODE;
static cmdline_bool foreground = 0;
static cmdline_string pidfile = MCED_PIDFILE;
static cmdline_int clientmax = MCED_CLIENTMAX;
static cmdline_int overflow_suppress_time = MCED_OVERFLOW_SUPPRESS_TIME;
static cmdline_bool retry_mcelog = 0;
#if ENABLE_MCEDB
static cmdline_string dbdir = MCED_DBDIR;
#endif
#if ENABLE_DBUS
static cmdline_bool no_dbus = 0;
static cmdline_bool use_session_dbus = 0;
#endif
static int mcelog_poll_works = 0;
static int log_is_open = 0;
static int fake_dev_mcelog = 0;
static enum {
KERNEL_MCE_UNKNOWN = 0,
KERNEL_MCE_V1, /* the historical 'struct mce' layout */
KERNEL_MCE_V2, /* 2.6.31 made 'struct mce' changes */
} kernel_mce_version;
/*
* Helpers
*/
static void do_help(const struct cmdline_opt *, ...);
static void do_version(const struct cmdline_opt *, ...);
static struct cmdline_opt mced_opts[] = {
#if ENABLE_MCEDB
{
"B", "dbdir",
CMDLINE_OPT_STRING, &dbdir,
"<dir>", "Set the database directory"
},
#endif /* ENABLE_MCEDB */
{
"d", "debug",
CMDLINE_OPT_COUNTER, &debug_level,
"", "Increase the debugging level (implies -f)"
},
{
"f", "foreground",
CMDLINE_OPT_BOOL, &foreground,
"", "Run in the foreground"
},
{
"b", "bootnum",
CMDLINE_OPT_INT, &bootnum,
"<num>", "Set the current boot number"
},
{
"c", "confdir",
CMDLINE_OPT_STRING, &confdir,
"<dir>", "Set the configuration directory"
},
{
"D", "device",
CMDLINE_OPT_STRING, &device,
"<file>", "Use the specified mcelog device"
},
{
"R", "retrydev",
CMDLINE_OPT_BOOL, &retry_mcelog,
"", "Retry the mcelog device if it fails to open"
},
{
"p", "pidfile",
CMDLINE_OPT_STRING, &pidfile,
"<file>", "Use the specified PID file"
},
{
"l", "logevents",
CMDLINE_OPT_BOOL, &log_events,
"", "Log each MCE and handlers"
},
{
"n", "mininterval",
CMDLINE_OPT_INT, &min_interval_ms,
"<num>", "Set the MCE polling min interval (in msecs)"
},
{
"x", "maxinterval",
CMDLINE_OPT_INT, &max_interval_ms,
"<num>", "Set the MCE polling max interval (in msecs)"
},
{
"r", "ratelimit",
CMDLINE_OPT_INT, &mce_rate_limit,
"<num>", "Limit the number of MCEs handled per second"
},
{
"o", "oflowsuppress",
CMDLINE_OPT_INT, &overflow_suppress_time,
"<num>", "Set the log period for overflows (in secs)"
},
{
"s", "socketfile",
CMDLINE_OPT_STRING, &socketfile,
"<file>", "Use the specified socket file"
},
{
"S", "nosocket",
CMDLINE_OPT_BOOL, &nosocket,
"", "Don't listen on a UNIX socket (overrides -s)"
},
{
"g", "socketgroup",
CMDLINE_OPT_STRING, &socketgroup,
"<group>", "Set the group on the socket file"
},
{
"m", "socketmode",
CMDLINE_OPT_MODE_T, &socketmode,
"<mode>", "Set the permissions on the socket file"
},
{
"C", "clientmax",
CMDLINE_OPT_INT, &clientmax,
"<num>", "Limit the number of non-root socket clients"
},
{
"O", "oldsocket",
CMDLINE_OPT_STRING, &socketfile_compat,
"", "Use the specified v1-compatible socket file"
},
#if ENABLE_DBUS
{
NULL, "no-dbus",
CMDLINE_OPT_BOOL, &no_dbus,
"", "Don't send MCEs over D-Bus"
},
{
NULL, "dbus-session-bus",
CMDLINE_OPT_BOOL, &use_session_dbus,
"", "Use D-Bus session bus, instead of system bus"
},
#endif
{
"v", "version",
CMDLINE_OPT_CALLBACK, do_version,
"", "Print version information and exit"
},
{
"h", "help",
CMDLINE_OPT_CALLBACK, do_help,
"", "Print this help message and exit"
},
CMDLINE_OPT_END_OF_LIST
};
/*
* Print usage info.
*/
static void
usage(FILE *out)
{
const char *help_str;
fprintf(out, "Usage: %s [OPTIONS]\n", cmdline_progname);
fprintf(out, "\n");
while ((help_str = cmdline_help(mced_opts))) {
fprintf(out, " %s\n", help_str);
}
fprintf(out, "\n");
}
/*
* Parse command line arguments.
*/
static int
handle_cmdline(int *argc, const char ***argv)
{
/* Parse the command line. */
if (cmdline_parse(argc, argv, mced_opts) != 0) {
usage(stderr);
exit(EXIT_FAILURE);
}
if (*argc != 1) {
fprintf(stderr,
"Unknown command line argument: '%s'\n\n", (*argv)[1]);
usage(stderr);
exit(EXIT_FAILURE);
}
/*
* Post-process command line flags.
*/
mced_debug_level = debug_level;
mced_log_events = log_events;
if (mced_debug_level > 0) {
foreground = 1;
}
if (max_interval_ms <= 0) {
max_interval_ms = -1;
}
if (min_interval_ms < 0) {
min_interval_ms = 0;
}
if (clientmax < 0) {
clientmax = 0;
}
if (overflow_suppress_time < 0) {
overflow_suppress_time = 0;
}
if (mce_rate_limit <= 0) {
mce_rate_limit = -1;
}
if (socketfile_compat && socketfile_compat[0] == '\0') {
socketfile_compat = MCED_SOCKETFILE_V1;
}
return 0;
}
/*
* Helper function for handling '-h' cmdlines.
*/
static void
do_help(const struct cmdline_opt *opt __attribute__((unused)), ...)
{
usage(stdout);
exit(EXIT_SUCCESS);
}
/*
* Helper function for handling '-v' cmdlines.
*/
static void
do_version(const struct cmdline_opt *opt __attribute__((unused)), ...)
{
printf(PACKAGE "-" PRJ_VERSION "\n");
exit(EXIT_SUCCESS);
}
static void
close_fds(void)
{
int fd, max;
max = sysconf(_SC_OPEN_MAX);
for (fd = 3; fd < max; fd++)
close(fd);
}
static int
daemonize(void)
{
switch(fork()) {
case -1:
mced_log(LOG_ERR, "ERR: fork: %s\n", strerror(errno));
return -1;
case 0:
/* child */
break;
default:
/* parent */
exit(EXIT_SUCCESS);
}
/* disconnect */
setsid();
umask(0);
/* get out of the way */
if (chdir("/") < 0) {
mced_log(LOG_ERR, "ERR: chdir(\"/\"): %s\n", strerror(errno));
return -1;
}
return 0;
}
static int
open_log(void)
{
int nullfd;
int log_opts;
int ret;
/* open /dev/null */
nullfd = open("/dev/null", O_RDWR);
if (nullfd < 0) {
mced_log(LOG_ERR, "ERR: can't open /dev/null: %s\n",
strerror(errno));
return -1;
}
log_opts = LOG_CONS|LOG_NDELAY;
if (mced_debug_level > 0) {
log_opts |= LOG_PERROR;
}
openlog(PACKAGE, log_opts, LOG_DAEMON);
/* set up stdin, stdout, stderr to /dev/null */
ret = 0;
if (dup2(nullfd, STDIN_FILENO) != STDIN_FILENO) {
mced_log(LOG_ERR, "LOG_ERR: dup2: %s\n", strerror(errno));
ret = -1;
}
if (!mced_debug_level && dup2(nullfd, STDOUT_FILENO) != STDOUT_FILENO) {
mced_log(LOG_ERR, "ERR: dup2: %s\n", strerror(errno));
ret = -1;
}
if (!mced_debug_level && dup2(nullfd, STDERR_FILENO) != STDERR_FILENO) {
mced_log(LOG_ERR, "ERR: dup2: %s\n", strerror(errno));
ret = -1;
}
close(nullfd);
log_is_open = 1;
return ret;
}
static int
create_pidfile(void)
{
int fd;
/* JIC */
unlink(pidfile);
/* open the pidfile */
fd = open(pidfile, O_WRONLY|O_CREAT|O_EXCL, 0644);
if (fd >= 0) {
FILE *f;
/* write our pid to it */
f = fdopen(fd, "w");
if (f != NULL) {
fprintf(f, "%d\n", getpid());
fclose(f);
/* leave the fd open */
return 0;
}
close(fd);
}
/* something went wrong */
mced_log(LOG_ERR, "ERR: can't create pidfile %s: %s\n",
pidfile, strerror(errno));
return -1;
}
static void
clean_exit_with_status(int status)
{
mced_cleanup_rules(1);
#if ENABLE_MCEDB
mcedb_close(mced_db);
#endif
unlink(pidfile);
mced_log(LOG_NOTICE, "exiting\n");
exit(status);
}
static void
clean_exit(int sig)
{
mced_log(LOG_NOTICE, "caught signal %d\n", sig);
clean_exit_with_status(EXIT_SUCCESS);
}
static void
clean_exit_with_killer(int signum, siginfo_t *siginfo,
void __attribute__((unused)) *context) {
char fname[255];
char cmdline[1023];
int cmdline_success = 0;
mced_log(LOG_NOTICE, "caught signal %d\n", signum);
snprintf(fname, sizeof(fname)-1, "/proc/%u/cmdline", siginfo->si_pid);
FILE *cmdline_file = fopen(fname, "r");
if (cmdline_file) {
if (fgets(cmdline, 1023, cmdline_file)) {
cmdline_success = 1;
}
fclose(cmdline_file);
}
if (cmdline_success) { // file successfully read
mced_log(
LOG_NOTICE,
"killed by process with pid %u and command line %.1022s\n",
siginfo->si_pid,
cmdline);
} else {
mced_log(
LOG_NOTICE,
"killed by process with pid %u and unknown command line\n",
siginfo->si_pid);
}
clean_exit_with_status(EXIT_SUCCESS);
}
static void
reload_conf(int sig __attribute__((unused)))
{
mced_log(LOG_NOTICE, "reloading configuration\n");
mced_cleanup_rules(0);
mced_read_conf(confdir);
}
static int
mced_vlog(int level, const char *fmt, va_list args)
{
if (log_is_open) {
vsyslog(level, fmt, args);
} else {
vfprintf(stderr, fmt, args);
}
return 0;
}
int
mced_log(int level, const char *fmt, ...)
{
va_list args;
int r;
va_start(args, fmt);
r = mced_vlog(level, fmt, args);
va_end(args);
return r;
}
int
mced_debug(int min_dbg_lvl, const char *fmt, ...)
{
va_list args;
int r;
if (mced_debug_level < min_dbg_lvl) {
return 0;
}
va_start(args, fmt);
r = mced_vlog(LOG_DEBUG, fmt, args);
va_end(args);
return r;
}
int
mced_perror(int level, const char *str)
{
return mced_log(level, "%s: %s\n", str, strerror(errno));
}
static int
open_socket(const char *path, mode_t mode, const char *group)
{
int sock_fd;
sock_fd = ud_create_socket(path);
if (sock_fd < 0) {
mced_log(LOG_ERR, "ERR: can't open socket %s: %s\n",
path, strerror(errno));
return -1;
}
fcntl(sock_fd, F_SETFD, FD_CLOEXEC);
chmod(path, mode);
if (group) {
struct group *gr;
struct stat buf;
gr = getgrnam(group);
if (!gr) {
mced_log(LOG_ERR, "ERR: group %s does not exist\n",
group);
close(sock_fd);
return -1;
}
if (stat(path, &buf) < 0) {
mced_log(LOG_ERR, "ERR: can't stat %s\n", path);
close(sock_fd);
return -1;
}
if (chown(path, buf.st_uid, gr->gr_gid) < 0) {
mced_log(LOG_ERR, "ERR: chown(): %s\n",
strerror(errno));
close(sock_fd);
return -1;
}
}
return sock_fd;
}
/* convert a kernel MCE struct to our MCE struct */
static void
kmce_to_mce(struct kernel_mce *kmce, struct mce *mce)
{
struct timeval tv;
gettimeofday(&tv, NULL);
/* common fields for all versions of 'struct kernel_mce' */
mce->boot = bootnum;
mce->bank = kmce->bank;
mce->mci_status = kmce->status;
mce->mci_address = kmce->addr;
mce->mci_misc = kmce->misc;
mce->mci_synd = kmce->synd;
mce->mci_ipid = kmce->ipid;
mce->mcg_status = kmce->mcgstatus;
mce->tsc = kmce->tsc;
mce->cs = kmce->cs;
mce->ip = kmce->rip;
if (kernel_mce_version == KERNEL_MCE_V1) {
mce->time = (tv.tv_sec * 1000000ULL) + tv.tv_usec;
mce->cpu = kmce->cpu;
mce->socket = -1;
mce->vendor = VENDOR_UNKNOWN;
mce->cpuid_eax = 0;
mce->init_apic_id = (uint32_t)-1U;
mce->mcg_status = 0;
} else if (kernel_mce_version == KERNEL_MCE_V2) {
if (kmce->time != 0) {
mce->time = kmce->time * 1000000ULL;
} else {
mce->time = (tv.tv_sec * 1000000ULL) + tv.tv_usec;
}
mce->cpu = kmce->extcpu;
mce->socket = kmce->socketid;
mce->vendor = kmce->cpuvendor;
mce->cpuid_eax = kmce->cpuid;
mce->init_apic_id = kmce->apicid;
mce->mcg_status = kmce->mcgcap;
} else {
/* this should never happen */
mced_log(LOG_EMERG,
"FATAL: kernel_mce_version (%d) is unknown\n",
kernel_mce_version);
clean_exit_with_status(EXIT_FAILURE);
}
}
/* this is used in a few places to throttle messages */
struct rate_limit {
int initialized; /* first one been done? */
struct timeval period;
struct timeval last_time; /* last time we hit this */
};
/* do we need to apply rate limiting? */
static int
apply_rate_limit(struct rate_limit *limit)
{
struct timeval now;
struct timeval since_last;
if (!limit->initialized) {
/* first time through here, just remember it */
limit->initialized = 1;
gettimeofday(&limit->last_time, NULL);
return 0;
}
/* find how long it has been since the last event */
gettimeofday(&now, NULL);
timersub(&now, &limit->last_time, &since_last);
/* has enough time elapsed? */
if (timercmp(&since_last, &limit->period, <)) {
/* rate limit */
return 1;
}
/* do not rate limit */
limit->last_time = now;
return 0;
}
/* process a single MCE */
static int
do_one_mce(struct kernel_mce *kmce)
{
struct mce mce;
static struct rate_limit hw_overflow_limit;
static int rate_limit_initialized = 0;
/* initialize the rate limits based on a commandline flag */
if (!rate_limit_initialized) {
rate_limit_initialized = 1;
hw_overflow_limit.period.tv_sec = overflow_suppress_time;
}
/* convert the kernel's MCE struct to our own */
kmce_to_mce(kmce, &mce);
/* check for overflow */
if ((mce.mci_status & MCI_STATUS_OVER)
&& (mced_log_events || !apply_rate_limit(&hw_overflow_limit))) {
mced_log(LOG_WARNING, "MCE overflow detected by hardware\n");
if (!mced_log_events && overflow_suppress_time) {
mced_log(LOG_WARNING,
"(previous message suppressed for %lld seconds)",
overflow_suppress_time);
}
}
#if ENABLE_MCEDB
if (mcedb_append(mced_db, &mce) < 0) {
mced_log(LOG_ERR,
"ERR: failed to append MCE to database - not good!!\n");
} else {
mced_debug(1, "DBG: logged MCE #%d\n", mcedb_end(mced_db)-1);
}
#endif
if (mced_log_events) {
mced_log(LOG_INFO, "starting MCE handlers\n");
}
mced_handle_mce(&mce);
if (mced_log_events) {
mced_log(LOG_INFO, "completed MCE handlers\n");
}
#if ENABLE_DBUS
if (!no_dbus) {
dbus_send_mce(&mce);
}
#endif
return 0;
}
/* get the MCE log length from the kernel */
static int
get_loglen(int mce_fd)
{
if (!fake_dev_mcelog) {
int loglen;
int r = ioctl(mce_fd, MCE_GET_LOG_LEN, &loglen);
if (r < 0) {
mced_perror(LOG_ERR, "ERR: ioctl(MCE_GET_LOG_LEN)");
return -1;
}
return loglen;
} else {
return 1;
}
}
/* Convert seconds to microseconds. */
static long int
SEC_TO_USEC(long int sec)
{
return sec * 1000000;
}
/* Convert timeval to microseconds. */
static long int
TIMEVAL_TO_USEC(struct timeval *tv)
{
return SEC_TO_USEC(tv->tv_sec) + tv->tv_usec;
}
/* Divide a timeval by an integer. The quotient is normalized. */
static void
timerdiv(const struct timeval *tv, int divisor, struct timeval *quotient) {
/* Avoid relying on tv->tv_sec after setting quotient->tv_sec in cases they alias. */
long int remainder_sec = tv->tv_sec % divisor;
quotient->tv_sec = tv->tv_sec / divisor;
quotient->tv_usec = (SEC_TO_USEC(remainder_sec) + tv->tv_usec) / divisor;
}
/* enforce MCE rate limiting */
static void
rate_limit_mces(void)
{
static int first_event = 1;
static struct timeval last_timestamp;
static struct timeval bias;
if (mce_rate_limit <= 0) {
/* no rate limiting */
return;
} else if (first_event) {
/* first time through here, just remember it */
first_event = 0;
gettimeofday(&last_timestamp, NULL);
} else {
/* we might have to rate limit */
struct timeval now;
struct timeval since_last;
static const struct timeval one_second = {1, 0};
struct timeval time_per_event;
timerdiv(&one_second, mce_rate_limit, &time_per_event);
/* find how long it has been since the last event */
gettimeofday(&now, NULL);
timersub(&now, &last_timestamp, &since_last);
/* set the last_timestamp to now, we might change it later */
last_timestamp = now;
/* are we under the minimum time between events? */
if (timercmp(&time_per_event, &since_last, >)) {
struct timeval time_to_kill;
struct timeval missed_by;
struct timeval time_to_sleep;
/*
* We set the last_timestamp to the *ideal* time
* (now + usecs_to_kill), rather than the real
* time after the usleep(). This is because
* usleep() (and all other sleeps, really) is
* inaccurate with very small values. This gets
* us closer to the actual requested rate
* limiting.
*
* We also try to bias the sleep time based on
* past inaccuracy. We integrate the over/under
* deltas somewhat slowly, so large transients
* should not distort the bias too quickly.
*/
timersub(&time_per_event, &since_last, &time_to_kill);
timeradd(&last_timestamp, &time_to_kill, &last_timestamp);
timeradd(&time_to_kill, &bias, &time_to_sleep);
if (TIMEVAL_TO_USEC(&time_to_sleep) > 0) {
/* do the actual sleep */
usleep(TIMEVAL_TO_USEC(&time_to_sleep));
}
/* adjust the bias */
gettimeofday(&now, NULL);
timersub(&now, &last_timestamp, &missed_by);
timerdiv(&missed_by, 8, &missed_by);
timersub(&bias, &missed_by, &bias);
}
}
}
/* read and handle and MCEs that are pending in the kernel */
static int
do_pending_mces(int mce_fd)
{
int loglen;
int nmces = 0;
int flags = 0;
static struct rate_limit sw_overflow_limit;
static int rate_limit_initialized = 0;
/* initialize the rate limits based on a commandline flag */
if (!rate_limit_initialized) {
rate_limit_initialized = 1;
sw_overflow_limit.period.tv_sec = overflow_suppress_time;
}
/* check for MCEs */
loglen = get_loglen(mce_fd);
if (loglen > 0) {
uint8_t buf[mced_kernel_record_len*loglen];
int n;
/* read all of the MCE data */
n = read(mce_fd, buf, mced_kernel_record_len*loglen);
if (n < 0) {
if (fake_dev_mcelog && errno == EAGAIN) {
return 0;
}
mced_perror(LOG_ERR, "ERR: read()");
return -1;
}
/* did we get any MCES? */
nmces = n/mced_kernel_record_len;
if (nmces > 0) {
int i;
/* read the flags */
if (!fake_dev_mcelog
&& ioctl(mce_fd, MCE_GETCLEAR_FLAGS, &flags) < 0) {
mced_log(LOG_ERR, "ERR: can't get flags: %s\n",
strerror(errno));
return -1;
}
/* check for overflow */
if ((flags & MCE_FLAG_OVERFLOW)
&& (mced_log_events
|| !apply_rate_limit(&sw_overflow_limit))){
mced_log(LOG_WARNING,
"MCE overflow detected by software\n");
if (!mced_log_events
&& overflow_suppress_time) {
mced_log(LOG_WARNING,
"(previous message suppressed "
"for %lld seconds)",
overflow_suppress_time);
}
}
if (mced_log_events) {
mced_debug(1, "DBG: got %d MCE%s\n",
nmces, (nmces==1)?"":"s");
}
/* handle all the new MCEs */
for (i = 0; i < nmces; i++) {
struct kernel_mce kmce;
void *src, *dst;
rate_limit_mces();
/* The assumption is that newer versions of
* 'struct kernel_mce' are guaranteed to be
* supersets of older versions. Only copy
* the portion of the structure that we
* currently know about, and zero the rest. */
src = &buf[i*mced_kernel_record_len];
dst = &kmce;
memcpy(dst, src, mced_copy_len);
memset(dst + mced_copy_len, 0, mced_zero_len);
do_one_mce(&kmce);
}
}
}
return nmces;
}
/* see if poll() works on /dev/mcelog */
static int
check_mcelog_poll(int mce_fd)
{
if (!CHECK_FOR_NON_POLL_KERNELS) {
return 1;
}
// On a machine with a lot of errors, this loops forever!
while (1) {
int r;
struct pollfd ar[1];
/* try poll() on mcelog and see what happens */
ar[0].fd = mce_fd;
ar[0].events = POLLIN;
r = poll(ar, 1, 0);
if (r < 0) {
if (errno == EINTR) {
continue;
}
mced_perror(LOG_ERR, "ERR: poll()");
return 0;
}
/* if poll() reports a timeout, we assume it works */
if (r == 0) {
return 1;
}
/*
* If poll() reports data, we have to read it to find out
* if there is actually data, or if it is a bogus return.
* If we find data, we need to retry. We can't be sure
* poll() works unless we can trigger some behavior that
* is not present in non-poll() kernels. That's a
* timeout. If poll() reports data, but read() finds
* none, we can assume poll() does not work.
*/
if (ar[0].revents) {
if (ar[0].revents & POLLIN) {
if (do_pending_mces(mce_fd) > 0) {
continue;
}
} else {
mced_log(LOG_WARNING,
"odd, poll set flags 0x%x\n",
ar[0].revents);
}
}
break;
}
return 0;
}
static int
get_kernel_version(unsigned *vmajor, unsigned *vminor, unsigned *vmicro)
{
struct utsname u;
int r = uname(&u);
if (r < 0) {
return r;
}
r = sscanf(u.release, "%u.%u.%u", vmajor, vminor, vmicro);
if (r != 3) {
errno = EBADMSG;
return -1;
}
mced_debug(1, "DBG: found kernel %u.%u.%u\n",
*vmajor, *vminor, *vmicro);
return 0;
}
static int
init_kernel_mce_interface(int mce_fd)
{
if (fake_dev_mcelog) {
mced_kernel_record_len = sizeof(struct kernel_mce);
kernel_mce_version = KERNEL_MCE_V1;
} else {
int r;
/* Adjust for kernel versions. */
unsigned vmajor, vminor, vmicro;
r = get_kernel_version(&vmajor, &vminor, &vmicro);
if (r < 0) {
static int printed_msg;
if (!printed_msg) {