xref: /aosp_15_r20/external/coreboot/util/post/post.c (revision b9411a12aaaa7e1e6a6fb7c5e057f44ee179a49c)
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 
3 #include <errno.h>
4 #include <limits.h>
5 #include <stdarg.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <sys/io.h>
9 
10 #define POST_DEFAULT_IO_PORT 0x80
11 
usage(char * progname,const char * error,...)12 void usage(char *progname, const char *error, ...)
13 {
14 	printf("Usage: %s <VALUE> [PORT]\n", progname);
15 	printf("The VALUE argument is an integer between 0x00 and 0xff\n");
16 	printf("The PORT argument is an integer between 0x00 and 0xffff\n");
17 
18 	if (error) {
19 		va_list args;
20 
21 		va_start(args, error);
22 		vprintf(error, args);
23 		va_end(args);
24 	};
25 }
26 
check_int(long val,int min,int max,int err,char * string,char * endptr,char * progname)27 void check_int(long val, int min, int max, int err, char *string, char *endptr,
28 	       char *progname)
29 {
30 	if (val < min || val > max) {
31 		usage(progname,
32 		      "\nError: The value has to be between 0x%x and 0x%x\n",
33 		      min, max);
34 		exit(EXIT_FAILURE);
35 	}
36 
37 	if (endptr == string || *endptr != '\0') {
38 		usage(progname, "\nError: An integer is required\n");
39 		exit(EXIT_FAILURE);
40 	}
41 
42 	if ((err) && (!val)) {
43 		perror("strtol");
44 		exit(EXIT_FAILURE);
45 	}
46 }
47 
main(int argc,char * argv[])48 int main(int argc, char *argv[])
49 {
50 	unsigned long val;
51 	unsigned long port = POST_DEFAULT_IO_PORT;
52 	char *endptr;
53 	int err;
54 
55 	if (argc != 2 && argc != 3) {
56 		usage(argv[0], NULL);
57 		exit(EXIT_FAILURE);
58 	}
59 
60 	val = strtol(argv[1], &endptr, 0);
61 	err = errno;
62 	check_int(val, 0x00, 0xff, err, argv[1], endptr, argv[0]);
63 
64 	if (argc > 2) {
65 		port = strtol(argv[2], &endptr, 0);
66 		err = errno;
67 		check_int(port, 0x0000, 0xffff, err, argv[2], endptr, argv[0]);
68 	}
69 
70 	err = iopl(3);
71 	if (err == -1) {
72 		perror("Not root");
73 		exit(EXIT_FAILURE);
74 	}
75 
76 	outb(val, port);
77 
78 	return 0;
79 }
80