Linux 5.7.6
[linux/fpc-iii.git] / arch / x86 / lib / msr.c
blob3bd905e10ee21bd532338740c5294ea75a8284ba
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/export.h>
3 #include <linux/percpu.h>
4 #include <linux/preempt.h>
5 #include <asm/msr.h>
6 #define CREATE_TRACE_POINTS
7 #include <asm/msr-trace.h>
9 struct msr *msrs_alloc(void)
11 struct msr *msrs = NULL;
13 msrs = alloc_percpu(struct msr);
14 if (!msrs) {
15 pr_warn("%s: error allocating msrs\n", __func__);
16 return NULL;
19 return msrs;
21 EXPORT_SYMBOL(msrs_alloc);
23 void msrs_free(struct msr *msrs)
25 free_percpu(msrs);
27 EXPORT_SYMBOL(msrs_free);
29 /**
30 * Read an MSR with error handling
32 * @msr: MSR to read
33 * @m: value to read into
35 * It returns read data only on success, otherwise it doesn't change the output
36 * argument @m.
39 int msr_read(u32 msr, struct msr *m)
41 int err;
42 u64 val;
44 err = rdmsrl_safe(msr, &val);
45 if (!err)
46 m->q = val;
48 return err;
51 /**
52 * Write an MSR with error handling
54 * @msr: MSR to write
55 * @m: value to write
57 int msr_write(u32 msr, struct msr *m)
59 return wrmsrl_safe(msr, m->q);
62 static inline int __flip_bit(u32 msr, u8 bit, bool set)
64 struct msr m, m1;
65 int err = -EINVAL;
67 if (bit > 63)
68 return err;
70 err = msr_read(msr, &m);
71 if (err)
72 return err;
74 m1 = m;
75 if (set)
76 m1.q |= BIT_64(bit);
77 else
78 m1.q &= ~BIT_64(bit);
80 if (m1.q == m.q)
81 return 0;
83 err = msr_write(msr, &m1);
84 if (err)
85 return err;
87 return 1;
90 /**
91 * Set @bit in a MSR @msr.
93 * Retval:
94 * < 0: An error was encountered.
95 * = 0: Bit was already set.
96 * > 0: Hardware accepted the MSR write.
98 int msr_set_bit(u32 msr, u8 bit)
100 return __flip_bit(msr, bit, true);
104 * Clear @bit in a MSR @msr.
106 * Retval:
107 * < 0: An error was encountered.
108 * = 0: Bit was already cleared.
109 * > 0: Hardware accepted the MSR write.
111 int msr_clear_bit(u32 msr, u8 bit)
113 return __flip_bit(msr, bit, false);
116 #ifdef CONFIG_TRACEPOINTS
117 void do_trace_write_msr(unsigned int msr, u64 val, int failed)
119 trace_write_msr(msr, val, failed);
121 EXPORT_SYMBOL(do_trace_write_msr);
122 EXPORT_TRACEPOINT_SYMBOL(write_msr);
124 void do_trace_read_msr(unsigned int msr, u64 val, int failed)
126 trace_read_msr(msr, val, failed);
128 EXPORT_SYMBOL(do_trace_read_msr);
129 EXPORT_TRACEPOINT_SYMBOL(read_msr);
131 void do_trace_rdpmc(unsigned counter, u64 val, int failed)
133 trace_rdpmc(counter, val, failed);
135 EXPORT_SYMBOL(do_trace_rdpmc);
136 EXPORT_TRACEPOINT_SYMBOL(rdpmc);
138 #endif