xref: /freebsd/sys/dev/cpuctl/cpuctl.c (revision 964219664dcec4198441910904fb9064569d174d)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2006-2008 Stanislav Sedov <stas@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/conf.h>
36 #include <sys/fcntl.h>
37 #include <sys/ioccom.h>
38 #include <sys/malloc.h>
39 #include <sys/module.h>
40 #include <sys/mutex.h>
41 #include <sys/priv.h>
42 #include <sys/proc.h>
43 #include <sys/queue.h>
44 #include <sys/sched.h>
45 #include <sys/kernel.h>
46 #include <sys/sysctl.h>
47 #include <sys/uio.h>
48 #include <sys/pcpu.h>
49 #include <sys/smp.h>
50 #include <sys/pmckern.h>
51 #include <sys/cpuctl.h>
52 
53 #include <machine/cpufunc.h>
54 #include <machine/md_var.h>
55 #include <machine/specialreg.h>
56 
57 static d_open_t cpuctl_open;
58 static d_ioctl_t cpuctl_ioctl;
59 
60 #define	CPUCTL_VERSION 1
61 
62 #ifdef CPUCTL_DEBUG
63 # define	DPRINTF(format,...) printf(format, __VA_ARGS__);
64 #else
65 # define	DPRINTF(...)
66 #endif
67 
68 #define	UCODE_SIZE_MAX	(4 * 1024 * 1024)
69 
70 static int cpuctl_do_msr(int cpu, cpuctl_msr_args_t *data, u_long cmd,
71     struct thread *td);
72 static int cpuctl_do_cpuid(int cpu, cpuctl_cpuid_args_t *data,
73     struct thread *td);
74 static int cpuctl_do_cpuid_count(int cpu, cpuctl_cpuid_count_args_t *data,
75     struct thread *td);
76 static int cpuctl_do_eval_cpu_features(int cpu, struct thread *td);
77 static int cpuctl_do_update(int cpu, cpuctl_update_args_t *data,
78     struct thread *td);
79 static int update_intel(int cpu, cpuctl_update_args_t *args,
80     struct thread *td);
81 static int update_amd(int cpu, cpuctl_update_args_t *args, struct thread *td);
82 static int update_via(int cpu, cpuctl_update_args_t *args,
83     struct thread *td);
84 
85 static struct cdev **cpuctl_devs;
86 static MALLOC_DEFINE(M_CPUCTL, "cpuctl", "CPUCTL buffer");
87 
88 static struct cdevsw cpuctl_cdevsw = {
89         .d_version =    D_VERSION,
90         .d_open =       cpuctl_open,
91         .d_ioctl =      cpuctl_ioctl,
92         .d_name =       "cpuctl",
93 };
94 
95 /*
96  * This function checks if specified cpu enabled or not.
97  */
98 static int
99 cpu_enabled(int cpu)
100 {
101 
102 	return (pmc_cpu_is_disabled(cpu) == 0);
103 }
104 
105 /*
106  * Check if the current thread is bound to a specific cpu.
107  */
108 static int
109 cpu_sched_is_bound(struct thread *td)
110 {
111 	int ret;
112 
113 	thread_lock(td);
114 	ret = sched_is_bound(td);
115 	thread_unlock(td);
116 	return (ret);
117 }
118 
119 /*
120  * Switch to target cpu to run.
121  */
122 static void
123 set_cpu(int cpu, struct thread *td)
124 {
125 
126 	KASSERT(cpu >= 0 && cpu <= mp_maxid && cpu_enabled(cpu),
127 	    ("[cpuctl,%d]: bad cpu number %d", __LINE__, cpu));
128 	thread_lock(td);
129 	sched_bind(td, cpu);
130 	thread_unlock(td);
131 	KASSERT(td->td_oncpu == cpu,
132 	    ("[cpuctl,%d]: cannot bind to target cpu %d on cpu %d", __LINE__,
133 	    cpu, td->td_oncpu));
134 }
135 
136 static void
137 restore_cpu(int oldcpu, int is_bound, struct thread *td)
138 {
139 
140 	KASSERT(oldcpu >= 0 && oldcpu <= mp_maxid && cpu_enabled(oldcpu),
141 	    ("[cpuctl,%d]: bad cpu number %d", __LINE__, oldcpu));
142 	thread_lock(td);
143 	if (is_bound == 0)
144 		sched_unbind(td);
145 	else
146 		sched_bind(td, oldcpu);
147 	thread_unlock(td);
148 }
149 
150 int
151 cpuctl_ioctl(struct cdev *dev, u_long cmd, caddr_t data,
152     int flags, struct thread *td)
153 {
154 	int cpu, ret;
155 
156 	cpu = dev2unit(dev);
157 	if (cpu > mp_maxid || !cpu_enabled(cpu)) {
158 		DPRINTF("[cpuctl,%d]: bad cpu number %d\n", __LINE__, cpu);
159 		return (ENXIO);
160 	}
161 	/* Require write flag for "write" requests. */
162 	if ((cmd == CPUCTL_MSRCBIT || cmd == CPUCTL_MSRSBIT ||
163 	    cmd == CPUCTL_UPDATE || cmd == CPUCTL_WRMSR ||
164 	    cmd == CPUCTL_EVAL_CPU_FEATURES) &&
165 	    (flags & FWRITE) == 0)
166 		return (EPERM);
167 	switch (cmd) {
168 	case CPUCTL_RDMSR:
169 		ret = cpuctl_do_msr(cpu, (cpuctl_msr_args_t *)data, cmd, td);
170 		break;
171 	case CPUCTL_MSRSBIT:
172 	case CPUCTL_MSRCBIT:
173 	case CPUCTL_WRMSR:
174 		ret = priv_check(td, PRIV_CPUCTL_WRMSR);
175 		if (ret != 0)
176 			goto fail;
177 		ret = cpuctl_do_msr(cpu, (cpuctl_msr_args_t *)data, cmd, td);
178 		break;
179 	case CPUCTL_CPUID:
180 		ret = cpuctl_do_cpuid(cpu, (cpuctl_cpuid_args_t *)data, td);
181 		break;
182 	case CPUCTL_UPDATE:
183 		ret = priv_check(td, PRIV_CPUCTL_UPDATE);
184 		if (ret != 0)
185 			goto fail;
186 		ret = cpuctl_do_update(cpu, (cpuctl_update_args_t *)data, td);
187 		break;
188 	case CPUCTL_CPUID_COUNT:
189 		ret = cpuctl_do_cpuid_count(cpu,
190 		    (cpuctl_cpuid_count_args_t *)data, td);
191 		break;
192 	case CPUCTL_EVAL_CPU_FEATURES:
193 		ret = cpuctl_do_eval_cpu_features(cpu, td);
194 		break;
195 	default:
196 		ret = EINVAL;
197 		break;
198 	}
199 fail:
200 	return (ret);
201 }
202 
203 /*
204  * Actually perform cpuid operation.
205  */
206 static int
207 cpuctl_do_cpuid_count(int cpu, cpuctl_cpuid_count_args_t *data,
208     struct thread *td)
209 {
210 	int is_bound = 0;
211 	int oldcpu;
212 
213 	KASSERT(cpu >= 0 && cpu <= mp_maxid,
214 	    ("[cpuctl,%d]: bad cpu number %d", __LINE__, cpu));
215 
216 	/* Explicitly clear cpuid data to avoid returning stale info. */
217 	bzero(data->data, sizeof(data->data));
218 	DPRINTF("[cpuctl,%d]: retrieving cpuid lev %#0x type %#0x for %d cpu\n",
219 	    __LINE__, data->level, data->level_type, cpu);
220 #ifdef __i386__
221 	if (cpu_id == 0)
222 		return (ENODEV);
223 #endif
224 	oldcpu = td->td_oncpu;
225 	is_bound = cpu_sched_is_bound(td);
226 	set_cpu(cpu, td);
227 	cpuid_count(data->level, data->level_type, data->data);
228 	restore_cpu(oldcpu, is_bound, td);
229 	return (0);
230 }
231 
232 static int
233 cpuctl_do_cpuid(int cpu, cpuctl_cpuid_args_t *data, struct thread *td)
234 {
235 	cpuctl_cpuid_count_args_t cdata;
236 	int error;
237 
238 	cdata.level = data->level;
239 	/* Override the level type. */
240 	cdata.level_type = 0;
241 	error = cpuctl_do_cpuid_count(cpu, &cdata, td);
242 	bcopy(cdata.data, data->data, sizeof(data->data)); /* Ignore error */
243 	return (error);
244 }
245 
246 /*
247  * Actually perform MSR operations.
248  */
249 static int
250 cpuctl_do_msr(int cpu, cpuctl_msr_args_t *data, u_long cmd, struct thread *td)
251 {
252 	uint64_t reg;
253 	int is_bound = 0;
254 	int oldcpu;
255 	int ret;
256 
257 	KASSERT(cpu >= 0 && cpu <= mp_maxid,
258 	    ("[cpuctl,%d]: bad cpu number %d", __LINE__, cpu));
259 
260 	/*
261 	 * Explicitly clear cpuid data to avoid returning stale
262 	 * info
263 	 */
264 	DPRINTF("[cpuctl,%d]: operating on MSR %#0x for %d cpu\n", __LINE__,
265 	    data->msr, cpu);
266 #ifdef __i386__
267 	if ((cpu_feature & CPUID_MSR) == 0)
268 		return (ENODEV);
269 #endif
270 	oldcpu = td->td_oncpu;
271 	is_bound = cpu_sched_is_bound(td);
272 	set_cpu(cpu, td);
273 	if (cmd == CPUCTL_RDMSR) {
274 		data->data = 0;
275 		ret = rdmsr_safe(data->msr, &data->data);
276 	} else if (cmd == CPUCTL_WRMSR) {
277 		ret = wrmsr_safe(data->msr, data->data);
278 	} else if (cmd == CPUCTL_MSRSBIT) {
279 		critical_enter();
280 		ret = rdmsr_safe(data->msr, &reg);
281 		if (ret == 0)
282 			ret = wrmsr_safe(data->msr, reg | data->data);
283 		critical_exit();
284 	} else if (cmd == CPUCTL_MSRCBIT) {
285 		critical_enter();
286 		ret = rdmsr_safe(data->msr, &reg);
287 		if (ret == 0)
288 			ret = wrmsr_safe(data->msr, reg & ~data->data);
289 		critical_exit();
290 	} else
291 		panic("[cpuctl,%d]: unknown operation requested: %lu",
292 		    __LINE__, cmd);
293 	restore_cpu(oldcpu, is_bound, td);
294 	return (ret);
295 }
296 
297 /*
298  * Actually perform microcode update.
299  */
300 static int
301 cpuctl_do_update(int cpu, cpuctl_update_args_t *data, struct thread *td)
302 {
303 	cpuctl_cpuid_args_t args = {
304 		.level = 0,
305 	};
306 	char vendor[13];
307 	int ret;
308 
309 	KASSERT(cpu >= 0 && cpu <= mp_maxid,
310 	    ("[cpuctl,%d]: bad cpu number %d", __LINE__, cpu));
311 	DPRINTF("[cpuctl,%d]: XXX %d", __LINE__, cpu);
312 
313 	ret = cpuctl_do_cpuid(cpu, &args, td);
314 	if (ret != 0)
315 		return (ret);
316 	((uint32_t *)vendor)[0] = args.data[1];
317 	((uint32_t *)vendor)[1] = args.data[3];
318 	((uint32_t *)vendor)[2] = args.data[2];
319 	vendor[12] = '\0';
320 	if (strncmp(vendor, INTEL_VENDOR_ID, sizeof(INTEL_VENDOR_ID)) == 0)
321 		ret = update_intel(cpu, data, td);
322 	else if(strncmp(vendor, AMD_VENDOR_ID, sizeof(AMD_VENDOR_ID)) == 0)
323 		ret = update_amd(cpu, data, td);
324 	else if(strncmp(vendor, CENTAUR_VENDOR_ID, sizeof(CENTAUR_VENDOR_ID))
325 	    == 0)
326 		ret = update_via(cpu, data, td);
327 	else
328 		ret = ENXIO;
329 	return (ret);
330 }
331 
332 static int
333 update_intel(int cpu, cpuctl_update_args_t *args, struct thread *td)
334 {
335 	void *ptr;
336 	uint64_t rev0, rev1;
337 	uint32_t tmp[4];
338 	int is_bound;
339 	int oldcpu;
340 	int ret;
341 
342 	if (args->size == 0 || args->data == NULL) {
343 		DPRINTF("[cpuctl,%d]: zero-sized firmware image", __LINE__);
344 		return (EINVAL);
345 	}
346 	if (args->size > UCODE_SIZE_MAX) {
347 		DPRINTF("[cpuctl,%d]: firmware image too large", __LINE__);
348 		return (EINVAL);
349 	}
350 
351 	/*
352 	 * 16 byte alignment required.  Rely on the fact that
353 	 * malloc(9) always returns the pointer aligned at least on
354 	 * the size of the allocation.
355 	 */
356 	ptr = malloc(args->size + 16, M_CPUCTL, M_WAITOK);
357 	if (copyin(args->data, ptr, args->size) != 0) {
358 		DPRINTF("[cpuctl,%d]: copyin %p->%p of %zd bytes failed",
359 		    __LINE__, args->data, ptr, args->size);
360 		ret = EFAULT;
361 		goto fail;
362 	}
363 	oldcpu = td->td_oncpu;
364 	is_bound = cpu_sched_is_bound(td);
365 	set_cpu(cpu, td);
366 	critical_enter();
367 	rdmsr_safe(MSR_BIOS_SIGN, &rev0); /* Get current microcode revision. */
368 
369 	/*
370 	 * Perform update.  Flush caches first to work around seemingly
371 	 * undocumented errata applying to some Broadwell CPUs.
372 	 */
373 	wbinvd();
374 	wrmsr_safe(MSR_BIOS_UPDT_TRIG, (uintptr_t)(ptr));
375 	wrmsr_safe(MSR_BIOS_SIGN, 0);
376 
377 	/*
378 	 * Serialize instruction flow.
379 	 */
380 	do_cpuid(0, tmp);
381 	critical_exit();
382 	rdmsr_safe(MSR_BIOS_SIGN, &rev1); /* Get new microcode revision. */
383 	restore_cpu(oldcpu, is_bound, td);
384 	if (rev1 > rev0)
385 		ret = 0;
386 	else
387 		ret = EEXIST;
388 fail:
389 	free(ptr, M_CPUCTL);
390 	return (ret);
391 }
392 
393 /*
394  * NB: MSR 0xc0010020, MSR_K8_UCODE_UPDATE, is not documented by AMD.
395  * Coreboot, illumos and Linux source code was used to understand
396  * its workings.
397  */
398 static void
399 amd_ucode_wrmsr(void *ucode_ptr)
400 {
401 	uint32_t tmp[4];
402 
403 	wrmsr_safe(MSR_K8_UCODE_UPDATE, (uintptr_t)ucode_ptr);
404 	do_cpuid(0, tmp);
405 }
406 
407 static int
408 update_amd(int cpu, cpuctl_update_args_t *args, struct thread *td)
409 {
410 	void *ptr;
411 	int ret;
412 
413 	if (args->size == 0 || args->data == NULL) {
414 		DPRINTF("[cpuctl,%d]: zero-sized firmware image", __LINE__);
415 		return (EINVAL);
416 	}
417 	if (args->size > UCODE_SIZE_MAX) {
418 		DPRINTF("[cpuctl,%d]: firmware image too large", __LINE__);
419 		return (EINVAL);
420 	}
421 
422 	/*
423 	 * 16 byte alignment required.  Rely on the fact that
424 	 * malloc(9) always returns the pointer aligned at least on
425 	 * the size of the allocation.
426 	 */
427 	ptr = malloc(args->size + 16, M_CPUCTL, M_ZERO | M_WAITOK);
428 	if (copyin(args->data, ptr, args->size) != 0) {
429 		DPRINTF("[cpuctl,%d]: copyin %p->%p of %zd bytes failed",
430 		    __LINE__, args->data, ptr, args->size);
431 		ret = EFAULT;
432 		goto fail;
433 	}
434 	smp_rendezvous(NULL, amd_ucode_wrmsr, NULL, ptr);
435 	ret = 0;
436 fail:
437 	free(ptr, M_CPUCTL);
438 	return (ret);
439 }
440 
441 static int
442 update_via(int cpu, cpuctl_update_args_t *args, struct thread *td)
443 {
444 	void *ptr;
445 	uint64_t rev0, rev1, res;
446 	uint32_t tmp[4];
447 	int is_bound;
448 	int oldcpu;
449 	int ret;
450 
451 	if (args->size == 0 || args->data == NULL) {
452 		DPRINTF("[cpuctl,%d]: zero-sized firmware image", __LINE__);
453 		return (EINVAL);
454 	}
455 	if (args->size > UCODE_SIZE_MAX) {
456 		DPRINTF("[cpuctl,%d]: firmware image too large", __LINE__);
457 		return (EINVAL);
458 	}
459 
460 	/*
461 	 * 4 byte alignment required.
462 	 */
463 	ptr = malloc(args->size, M_CPUCTL, M_WAITOK);
464 	if (copyin(args->data, ptr, args->size) != 0) {
465 		DPRINTF("[cpuctl,%d]: copyin %p->%p of %zd bytes failed",
466 		    __LINE__, args->data, ptr, args->size);
467 		ret = EFAULT;
468 		goto fail;
469 	}
470 	oldcpu = td->td_oncpu;
471 	is_bound = cpu_sched_is_bound(td);
472 	set_cpu(cpu, td);
473 	critical_enter();
474 	rdmsr_safe(MSR_BIOS_SIGN, &rev0); /* Get current microcode revision. */
475 
476 	/*
477 	 * Perform update.
478 	 */
479 	wrmsr_safe(MSR_BIOS_UPDT_TRIG, (uintptr_t)(ptr));
480 	do_cpuid(1, tmp);
481 
482 	/*
483 	 * Result are in low byte of MSR FCR5:
484 	 * 0x00: No update has been attempted since RESET.
485 	 * 0x01: The last attempted update was successful.
486 	 * 0x02: The last attempted update was unsuccessful due to a bad
487 	 *       environment. No update was loaded and any preexisting
488 	 *       patches are still active.
489 	 * 0x03: The last attempted update was not applicable to this processor.
490 	 *       No update was loaded and any preexisting patches are still
491 	 *       active.
492 	 * 0x04: The last attempted update was not successful due to an invalid
493 	 *       update data block. No update was loaded and any preexisting
494 	 *       patches are still active
495 	 */
496 	rdmsr_safe(0x1205, &res);
497 	res &= 0xff;
498 	critical_exit();
499 	rdmsr_safe(MSR_BIOS_SIGN, &rev1); /* Get new microcode revision. */
500 	restore_cpu(oldcpu, is_bound, td);
501 
502 	DPRINTF("[cpu,%d]: rev0=%x rev1=%x res=%x\n", __LINE__,
503 	    (unsigned)(rev0 >> 32), (unsigned)(rev1 >> 32), (unsigned)res);
504 
505 	if (res != 0x01)
506 		ret = EINVAL;
507 	else
508 		ret = 0;
509 fail:
510 	free(ptr, M_CPUCTL);
511 	return (ret);
512 }
513 
514 static int
515 cpuctl_do_eval_cpu_features(int cpu, struct thread *td)
516 {
517 	int is_bound = 0;
518 	int oldcpu;
519 
520 	KASSERT(cpu >= 0 && cpu <= mp_maxid,
521 	    ("[cpuctl,%d]: bad cpu number %d", __LINE__, cpu));
522 
523 #ifdef __i386__
524 	if (cpu_id == 0)
525 		return (ENODEV);
526 #endif
527 	oldcpu = td->td_oncpu;
528 	is_bound = cpu_sched_is_bound(td);
529 	set_cpu(cpu, td);
530 	identify_cpu1();
531 	identify_cpu2();
532 	hw_ibrs_recalculate();
533 	restore_cpu(oldcpu, is_bound, td);
534 	hw_ssb_recalculate(true);
535 	printcpuinfo();
536 	return (0);
537 }
538 
539 
540 int
541 cpuctl_open(struct cdev *dev, int flags, int fmt __unused, struct thread *td)
542 {
543 	int ret = 0;
544 	int cpu;
545 
546 	cpu = dev2unit(dev);
547 	if (cpu > mp_maxid || !cpu_enabled(cpu)) {
548 		DPRINTF("[cpuctl,%d]: incorrect cpu number %d\n", __LINE__,
549 		    cpu);
550 		return (ENXIO);
551 	}
552 	if (flags & FWRITE)
553 		ret = securelevel_gt(td->td_ucred, 0);
554 	return (ret);
555 }
556 
557 static int
558 cpuctl_modevent(module_t mod __unused, int type, void *data __unused)
559 {
560 	int cpu;
561 
562 	switch(type) {
563 	case MOD_LOAD:
564 		if (bootverbose)
565 			printf("cpuctl: access to MSR registers/cpuid info.\n");
566 		cpuctl_devs = malloc(sizeof(*cpuctl_devs) * (mp_maxid + 1), M_CPUCTL,
567 		    M_WAITOK | M_ZERO);
568 		CPU_FOREACH(cpu)
569 			if (cpu_enabled(cpu))
570 				cpuctl_devs[cpu] = make_dev(&cpuctl_cdevsw, cpu,
571 				    UID_ROOT, GID_KMEM, 0640, "cpuctl%d", cpu);
572 		break;
573 	case MOD_UNLOAD:
574 		CPU_FOREACH(cpu) {
575 			if (cpuctl_devs[cpu] != NULL)
576 				destroy_dev(cpuctl_devs[cpu]);
577 		}
578 		free(cpuctl_devs, M_CPUCTL);
579 		break;
580 	case MOD_SHUTDOWN:
581 		break;
582 	default:
583 		return (EOPNOTSUPP);
584         }
585 	return (0);
586 }
587 
588 DEV_MODULE(cpuctl, cpuctl_modevent, NULL);
589 MODULE_VERSION(cpuctl, CPUCTL_VERSION);
590