blob: 1a5ead9737dcf7d39a4b17de855badb67945e951 [file] [log] [blame]
Patrick Georgiafd4c872020-05-05 23:43:18 +02001/* intelmetool */
Patrick Georgiac959032020-05-05 22:49:26 +02002/* SPDX-License-Identifier: GPL-2.0-or-later */
Philipp Deppenwiese73add172016-08-26 02:10:51 +02003
4#include <fcntl.h>
5#include <unistd.h>
6#include <stdio.h>
7#include <stdlib.h>
8#include <string.h>
9#include <errno.h>
10
11#include "msr.h"
12
13#ifndef __DARWIN__
14static int fd_msr = 0;
15
Patrick Rudolph3df9dbe2017-11-25 14:43:06 +010016static int rdmsr(int addr, uint64_t *msr)
Philipp Deppenwiese73add172016-08-26 02:10:51 +020017{
Philipp Deppenwiese73add172016-08-26 02:10:51 +020018 if (lseek(fd_msr, (off_t) addr, SEEK_SET) == -1) {
19 perror("Could not lseek() to MSR");
20 close(fd_msr);
21 return -1;
22 }
23
Patrick Rudolph3df9dbe2017-11-25 14:43:06 +010024 if (read(fd_msr, msr, 8) == 8) {
Philipp Deppenwiese73add172016-08-26 02:10:51 +020025 close(fd_msr);
Patrick Rudolph3df9dbe2017-11-25 14:43:06 +010026 return 0;
Philipp Deppenwiese73add172016-08-26 02:10:51 +020027 }
28
29 if (errno == EIO) {
30 perror("IO error couldn't read MSR.");
31 close(fd_msr);
Patrick Rudolph3df9dbe2017-11-25 14:43:06 +010032 /* On older platforms the MSR might not exists */
Philipp Deppenwiese73add172016-08-26 02:10:51 +020033 return -2;
34 }
35
36 perror("Couldn't read() MSR");
37 close(fd_msr);
38 return -1;
39}
40#endif
41
Pablo Stebler9ac91d22020-09-18 10:32:22 +020042int msr_bootguard(uint64_t *msr)
Philipp Deppenwiese73add172016-08-26 02:10:51 +020043{
44
45#ifndef __DARWIN__
46 fd_msr = open("/dev/cpu/0/msr", O_RDONLY);
47 if (fd_msr < 0) {
48 perror("Error while opening /dev/cpu/0/msr");
49 printf("Did you run 'modprobe msr'?\n");
50 return -1;
51 }
52
Patrick Rudolph3df9dbe2017-11-25 14:43:06 +010053 if (rdmsr(MSR_BOOTGUARD, msr) < 0)
54 return -1;
Philipp Deppenwiese73add172016-08-26 02:10:51 +020055#endif
56
Philipp Deppenwiese73add172016-08-26 02:10:51 +020057 return 0;
58}