1 /* SPDX-License-Identifier: GPL-2.0-only */
2 /*
3  * POWER Data Stream Control Register (DSCR)
4  *
5  * This header file contains helper functions and macros
6  * required for all the DSCR related test cases.
7  *
8  * Copyright 2012, Anton Blanchard, IBM Corporation.
9  * Copyright 2015, Anshuman Khandual, IBM Corporation.
10  */
11 #ifndef _SELFTESTS_POWERPC_DSCR_DSCR_H
12 #define _SELFTESTS_POWERPC_DSCR_DSCR_H
13 
14 #include <unistd.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <fcntl.h>
19 #include <dirent.h>
20 #include <pthread.h>
21 #include <sched.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <sys/wait.h>
25 
26 #include "utils.h"
27 
28 #define THREADS		100	/* Max threads */
29 #define COUNT		100	/* Max iterations */
30 #define DSCR_MAX	16	/* Max DSCR value */
31 #define LEN_MAX		100	/* Max name length */
32 
33 #define DSCR_DEFAULT	"/sys/devices/system/cpu/dscr_default"
34 #define CPU_PATH	"/sys/devices/system/cpu/"
35 
36 #define rmb()  asm volatile("lwsync":::"memory")
37 #define wmb()  asm volatile("lwsync":::"memory")
38 
39 #define READ_ONCE(x) (*(volatile typeof(x) *)&(x))
40 
41 /* Prilvilege state DSCR access */
42 inline unsigned long get_dscr(void)
43 {
44 	unsigned long ret;
45 
46 	asm volatile("mfspr %0,%1" : "=r" (ret) : "i" (SPRN_DSCR_PRIV));
47 
48 	return ret;
49 }
50 
51 inline void set_dscr(unsigned long val)
52 {
53 	asm volatile("mtspr %1,%0" : : "r" (val), "i" (SPRN_DSCR_PRIV));
54 }
55 
56 /* Problem state DSCR access */
57 inline unsigned long get_dscr_usr(void)
58 {
59 	unsigned long ret;
60 
61 	asm volatile("mfspr %0,%1" : "=r" (ret) : "i" (SPRN_DSCR));
62 
63 	return ret;
64 }
65 
66 inline void set_dscr_usr(unsigned long val)
67 {
68 	asm volatile("mtspr %1,%0" : : "r" (val), "i" (SPRN_DSCR));
69 }
70 
71 /* Default DSCR access */
72 unsigned long get_default_dscr(void)
73 {
74 	int fd = -1, ret;
75 	char buf[16];
76 	unsigned long val;
77 
78 	if (fd == -1) {
79 		fd = open(DSCR_DEFAULT, O_RDONLY);
80 		if (fd == -1) {
81 			perror("open() failed");
82 			exit(1);
83 		}
84 	}
85 	memset(buf, 0, sizeof(buf));
86 	lseek(fd, 0, SEEK_SET);
87 	ret = read(fd, buf, sizeof(buf));
88 	if (ret == -1) {
89 		perror("read() failed");
90 		exit(1);
91 	}
92 	sscanf(buf, "%lx", &val);
93 	close(fd);
94 	return val;
95 }
96 
97 void set_default_dscr(unsigned long val)
98 {
99 	int fd = -1, ret;
100 	char buf[16];
101 
102 	if (fd == -1) {
103 		fd = open(DSCR_DEFAULT, O_RDWR);
104 		if (fd == -1) {
105 			perror("open() failed");
106 			exit(1);
107 		}
108 	}
109 	sprintf(buf, "%lx\n", val);
110 	ret = write(fd, buf, strlen(buf));
111 	if (ret == -1) {
112 		perror("write() failed");
113 		exit(1);
114 	}
115 	close(fd);
116 }
117 
118 double uniform_deviate(int seed)
119 {
120 	return seed * (1.0 / (RAND_MAX + 1.0));
121 }
122 #endif	/* _SELFTESTS_POWERPC_DSCR_DSCR_H */
123