/ util / msrtool / linux.c
linux.c
 1  /* SPDX-License-Identifier: GPL-2.0-only */
 2  
 3  #include <sys/types.h>
 4  #include <sys/stat.h>
 5  #include <fcntl.h>
 6  #include <unistd.h>
 7  #include <string.h>
 8  #include <errno.h>
 9  
10  #include "msrtool.h"
11  
12  static int msr_fd[MAX_CORES] = {-1, -1, -1, -1, -1, -1, -1, -1};
13  
14  int linux_probe(const struct sysdef *system) {
15  	struct stat st;
16  	return 0 == stat("/dev/cpu/0/msr", &st);
17  }
18  
19  int linux_open(uint8_t cpu, enum SysModes mode) {
20  	int fmode;
21  	char fn[32];
22  	switch (mode) {
23  	case SYS_RDWR:
24  		fmode = O_RDWR;
25  		break;
26  	case SYS_WRONLY:
27  		fmode = O_WRONLY;
28  		break;
29  	case SYS_RDONLY:
30  	default:
31  		fmode = O_RDONLY;
32  		break;
33  	}
34  	if (cpu >= MAX_CORES) {
35  		fprintf(stderr, "%s: only cores 0-%d are supported. requested=%d\n", __func__, MAX_CORES, cpu);
36  		return 0;
37  	}
38  	if (snprintf(fn, sizeof(fn), "/dev/cpu/%d/msr", cpu) == -1) {
39  		fprintf(stderr, "%s: snprintf: %s\n", __func__, strerror(errno));
40  		return 0;
41  	}
42  	msr_fd[cpu] = open(fn, fmode);
43  	if (-1 == msr_fd[cpu]) {
44  		fprintf(stderr, "open(%s): %s\n", fn, strerror(errno));
45  		return 0;
46  	}
47  	return 1;
48  }
49  
50  int linux_close(uint8_t cpu) {
51  	int ret;
52  	if (cpu >= MAX_CORES) {
53  		fprintf(stderr, "%s: only cores 0-%d are supported. requested=%d\n", __func__, MAX_CORES, cpu);
54  		return 0;
55  	}
56  	ret = close(msr_fd[cpu]);
57  	msr_fd[cpu] = 0;
58  	return 0 == ret;
59  }
60  
61  int linux_rdmsr(uint8_t cpu, uint32_t addr, struct msr *val) {
62  	struct msr tmp;
63  	if (lseek(msr_fd[cpu], addr, SEEK_SET) == -1) {
64  		SYSERROR(lseek, addr);
65  		return 0;
66  	}
67  	if (read(msr_fd[cpu], &tmp, 8) != 8) {
68  		SYSERROR(read, addr);
69  		return 0;
70  	}
71  	val->hi = tmp.lo;
72  	val->lo = tmp.hi;
73  	return 1;
74  }