xref: /freebsd/sys/dev/cpuctl/cpuctl.c (revision 52c2bb75163559a6e2866ad374a7de67a4ea1273)
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 #include <x86/ucode.h>
57 
58 static d_open_t cpuctl_open;
59 static d_ioctl_t cpuctl_ioctl;
60 
61 #define	CPUCTL_VERSION 1
62 
63 #ifdef CPUCTL_DEBUG
64 # define	DPRINTF(format,...) printf(format, __VA_ARGS__);
65 #else
66 # define	DPRINTF(...)
67 #endif
68 
69 #define	UCODE_SIZE_MAX	(4 * 1024 * 1024)
70 
71 static int cpuctl_do_msr(int cpu, cpuctl_msr_args_t *data, u_long cmd,
72     struct thread *td);
73 static int cpuctl_do_cpuid(int cpu, cpuctl_cpuid_args_t *data,
74     struct thread *td);
75 static int cpuctl_do_cpuid_count(int cpu, cpuctl_cpuid_count_args_t *data,
76     struct thread *td);
77 static int cpuctl_do_eval_cpu_features(int cpu, struct thread *td);
78 static int cpuctl_do_update(int cpu, cpuctl_update_args_t *data,
79     struct thread *td);
80 static int update_intel(int cpu, cpuctl_update_args_t *args,
81     struct thread *td);
82 static int update_amd(int cpu, cpuctl_update_args_t *args, struct thread *td);
83 static int update_via(int cpu, cpuctl_update_args_t *args,
84     struct thread *td);
85 
86 static struct cdev **cpuctl_devs;
87 static MALLOC_DEFINE(M_CPUCTL, "cpuctl", "CPUCTL buffer");
88 
89 static struct cdevsw cpuctl_cdevsw = {
90         .d_version =    D_VERSION,
91         .d_open =       cpuctl_open,
92         .d_ioctl =      cpuctl_ioctl,
93         .d_name =       "cpuctl",
94 };
95 
96 /*
97  * This function checks if specified cpu enabled or not.
98  */
99 static int
100 cpu_enabled(int cpu)
101 {
102 
103 	return (pmc_cpu_is_disabled(cpu) == 0);
104 }
105 
106 /*
107  * Check if the current thread is bound to a specific cpu.
108  */
109 static int
110 cpu_sched_is_bound(struct thread *td)
111 {
112 	int ret;
113 
114 	thread_lock(td);
115 	ret = sched_is_bound(td);
116 	thread_unlock(td);
117 	return (ret);
118 }
119 
120 /*
121  * Switch to target cpu to run.
122  */
123 static void
124 set_cpu(int cpu, struct thread *td)
125 {
126 
127 	KASSERT(cpu >= 0 && cpu <= mp_maxid && cpu_enabled(cpu),
128 	    ("[cpuctl,%d]: bad cpu number %d", __LINE__, cpu));
129 	thread_lock(td);
130 	sched_bind(td, cpu);
131 	thread_unlock(td);
132 	KASSERT(td->td_oncpu == cpu,
133 	    ("[cpuctl,%d]: cannot bind to target cpu %d on cpu %d", __LINE__,
134 	    cpu, td->td_oncpu));
135 }
136 
137 static void
138 restore_cpu(int oldcpu, int is_bound, struct thread *td)
139 {
140 
141 	KASSERT(oldcpu >= 0 && oldcpu <= mp_maxid && cpu_enabled(oldcpu),
142 	    ("[cpuctl,%d]: bad cpu number %d", __LINE__, oldcpu));
143 	thread_lock(td);
144 	if (is_bound == 0)
145 		sched_unbind(td);
146 	else
147 		sched_bind(td, oldcpu);
148 	thread_unlock(td);
149 }
150 
151 int
152 cpuctl_ioctl(struct cdev *dev, u_long cmd, caddr_t data,
153     int flags, struct thread *td)
154 {
155 	int cpu, ret;
156 
157 	cpu = dev2unit(dev);
158 	if (cpu > mp_maxid || !cpu_enabled(cpu)) {
159 		DPRINTF("[cpuctl,%d]: bad cpu number %d\n", __LINE__, cpu);
160 		return (ENXIO);
161 	}
162 	/* Require write flag for "write" requests. */
163 	if ((cmd == CPUCTL_MSRCBIT || cmd == CPUCTL_MSRSBIT ||
164 	    cmd == CPUCTL_UPDATE || cmd == CPUCTL_WRMSR ||
165 	    cmd == CPUCTL_EVAL_CPU_FEATURES) &&
166 	    (flags & FWRITE) == 0)
167 		return (EPERM);
168 	switch (cmd) {
169 	case CPUCTL_RDMSR:
170 		ret = cpuctl_do_msr(cpu, (cpuctl_msr_args_t *)data, cmd, td);
171 		break;
172 	case CPUCTL_MSRSBIT:
173 	case CPUCTL_MSRCBIT:
174 	case CPUCTL_WRMSR:
175 		ret = priv_check(td, PRIV_CPUCTL_WRMSR);
176 		if (ret != 0)
177 			goto fail;
178 		ret = cpuctl_do_msr(cpu, (cpuctl_msr_args_t *)data, cmd, td);
179 		break;
180 	case CPUCTL_CPUID:
181 		ret = cpuctl_do_cpuid(cpu, (cpuctl_cpuid_args_t *)data, td);
182 		break;
183 	case CPUCTL_UPDATE:
184 		ret = priv_check(td, PRIV_CPUCTL_UPDATE);
185 		if (ret != 0)
186 			goto fail;
187 		ret = cpuctl_do_update(cpu, (cpuctl_update_args_t *)data, td);
188 		break;
189 	case CPUCTL_CPUID_COUNT:
190 		ret = cpuctl_do_cpuid_count(cpu,
191 		    (cpuctl_cpuid_count_args_t *)data, td);
192 		break;
193 	case CPUCTL_EVAL_CPU_FEATURES:
194 		ret = cpuctl_do_eval_cpu_features(cpu, td);
195 		break;
196 	default:
197 		ret = EINVAL;
198 		break;
199 	}
200 fail:
201 	return (ret);
202 }
203 
204 /*
205  * Actually perform cpuid operation.
206  */
207 static int
208 cpuctl_do_cpuid_count(int cpu, cpuctl_cpuid_count_args_t *data,
209     struct thread *td)
210 {
211 	int is_bound = 0;
212 	int oldcpu;
213 
214 	KASSERT(cpu >= 0 && cpu <= mp_maxid,
215 	    ("[cpuctl,%d]: bad cpu number %d", __LINE__, cpu));
216 
217 	/* Explicitly clear cpuid data to avoid returning stale info. */
218 	bzero(data->data, sizeof(data->data));
219 	DPRINTF("[cpuctl,%d]: retrieving cpuid lev %#0x type %#0x for %d cpu\n",
220 	    __LINE__, data->level, data->level_type, cpu);
221 #ifdef __i386__
222 	if (cpu_id == 0)
223 		return (ENODEV);
224 #endif
225 	oldcpu = td->td_oncpu;
226 	is_bound = cpu_sched_is_bound(td);
227 	set_cpu(cpu, td);
228 	cpuid_count(data->level, data->level_type, data->data);
229 	restore_cpu(oldcpu, is_bound, td);
230 	return (0);
231 }
232 
233 static int
234 cpuctl_do_cpuid(int cpu, cpuctl_cpuid_args_t *data, struct thread *td)
235 {
236 	cpuctl_cpuid_count_args_t cdata;
237 	int error;
238 
239 	cdata.level = data->level;
240 	/* Override the level type. */
241 	cdata.level_type = 0;
242 	error = cpuctl_do_cpuid_count(cpu, &cdata, td);
243 	bcopy(cdata.data, data->data, sizeof(data->data)); /* Ignore error */
244 	return (error);
245 }
246 
247 /*
248  * Actually perform MSR operations.
249  */
250 static int
251 cpuctl_do_msr(int cpu, cpuctl_msr_args_t *data, u_long cmd, struct thread *td)
252 {
253 	uint64_t reg;
254 	int is_bound = 0;
255 	int oldcpu;
256 	int ret;
257 
258 	KASSERT(cpu >= 0 && cpu <= mp_maxid,
259 	    ("[cpuctl,%d]: bad cpu number %d", __LINE__, cpu));
260 
261 	/*
262 	 * Explicitly clear cpuid data to avoid returning stale
263 	 * info
264 	 */
265 	DPRINTF("[cpuctl,%d]: operating on MSR %#0x for %d cpu\n", __LINE__,
266 	    data->msr, cpu);
267 #ifdef __i386__
268 	if ((cpu_feature & CPUID_MSR) == 0)
269 		return (ENODEV);
270 #endif
271 	oldcpu = td->td_oncpu;
272 	is_bound = cpu_sched_is_bound(td);
273 	set_cpu(cpu, td);
274 	if (cmd == CPUCTL_RDMSR) {
275 		data->data = 0;
276 		ret = rdmsr_safe(data->msr, &data->data);
277 	} else if (cmd == CPUCTL_WRMSR) {
278 		ret = wrmsr_safe(data->msr, data->data);
279 	} else if (cmd == CPUCTL_MSRSBIT) {
280 		critical_enter();
281 		ret = rdmsr_safe(data->msr, &reg);
282 		if (ret == 0)
283 			ret = wrmsr_safe(data->msr, reg | data->data);
284 		critical_exit();
285 	} else if (cmd == CPUCTL_MSRCBIT) {
286 		critical_enter();
287 		ret = rdmsr_safe(data->msr, &reg);
288 		if (ret == 0)
289 			ret = wrmsr_safe(data->msr, reg & ~data->data);
290 		critical_exit();
291 	} else
292 		panic("[cpuctl,%d]: unknown operation requested: %lu",
293 		    __LINE__, cmd);
294 	restore_cpu(oldcpu, is_bound, td);
295 	return (ret);
296 }
297 
298 /*
299  * Actually perform microcode update.
300  */
301 static int
302 cpuctl_do_update(int cpu, cpuctl_update_args_t *data, struct thread *td)
303 {
304 	cpuctl_cpuid_args_t args = {
305 		.level = 0,
306 	};
307 	char vendor[13];
308 	int ret;
309 
310 	KASSERT(cpu >= 0 && cpu <= mp_maxid,
311 	    ("[cpuctl,%d]: bad cpu number %d", __LINE__, cpu));
312 	DPRINTF("[cpuctl,%d]: XXX %d", __LINE__, cpu);
313 
314 	ret = cpuctl_do_cpuid(cpu, &args, td);
315 	if (ret != 0)
316 		return (ret);
317 	((uint32_t *)vendor)[0] = args.data[1];
318 	((uint32_t *)vendor)[1] = args.data[3];
319 	((uint32_t *)vendor)[2] = args.data[2];
320 	vendor[12] = '\0';
321 	if (strncmp(vendor, INTEL_VENDOR_ID, sizeof(INTEL_VENDOR_ID)) == 0)
322 		ret = update_intel(cpu, data, td);
323 	else if(strncmp(vendor, AMD_VENDOR_ID, sizeof(AMD_VENDOR_ID)) == 0)
324 		ret = update_amd(cpu, data, td);
325 	else if(strncmp(vendor, CENTAUR_VENDOR_ID, sizeof(CENTAUR_VENDOR_ID))
326 	    == 0)
327 		ret = update_via(cpu, data, td);
328 	else
329 		ret = ENXIO;
330 	return (ret);
331 }
332 
333 struct ucode_update_data {
334 	void *ptr;
335 	int cpu;
336 	int ret;
337 };
338 
339 static void
340 ucode_intel_load_rv(void *arg)
341 {
342 	struct ucode_update_data *d;
343 
344 	d = arg;
345 	if (PCPU_GET(cpuid) == d->cpu)
346 		d->ret = ucode_intel_load(d->ptr, true, NULL, NULL);
347 }
348 
349 static int
350 update_intel(int cpu, cpuctl_update_args_t *args, struct thread *td)
351 {
352 	struct ucode_update_data d;
353 	void *ptr;
354 	int is_bound, oldcpu, ret;
355 
356 	if (args->size == 0 || args->data == NULL) {
357 		DPRINTF("[cpuctl,%d]: zero-sized firmware image", __LINE__);
358 		return (EINVAL);
359 	}
360 	if (args->size > UCODE_SIZE_MAX) {
361 		DPRINTF("[cpuctl,%d]: firmware image too large", __LINE__);
362 		return (EINVAL);
363 	}
364 
365 	/*
366 	 * 16 byte alignment required.  Rely on the fact that
367 	 * malloc(9) always returns the pointer aligned at least on
368 	 * the size of the allocation.
369 	 */
370 	ptr = malloc(args->size + 16, M_CPUCTL, M_WAITOK);
371 	if (copyin(args->data, ptr, args->size) != 0) {
372 		DPRINTF("[cpuctl,%d]: copyin %p->%p of %zd bytes failed",
373 		    __LINE__, args->data, ptr, args->size);
374 		ret = EFAULT;
375 		goto out;
376 	}
377 	oldcpu = td->td_oncpu;
378 	is_bound = cpu_sched_is_bound(td);
379 	set_cpu(cpu, td);
380 	d.ptr = ptr;
381 	d.cpu = cpu;
382 	smp_rendezvous(NULL, ucode_intel_load_rv, NULL, &d);
383 	restore_cpu(oldcpu, is_bound, td);
384 	ret = d.ret;
385 
386 	/*
387 	 * Replace any existing update.  This ensures that the new update
388 	 * will be reloaded automatically during ACPI resume.
389 	 */
390 	if (ret == 0)
391 		ptr = ucode_update(ptr);
392 
393 out:
394 	free(ptr, M_CPUCTL);
395 	return (ret);
396 }
397 
398 /*
399  * NB: MSR 0xc0010020, MSR_K8_UCODE_UPDATE, is not documented by AMD.
400  * Coreboot, illumos and Linux source code was used to understand
401  * its workings.
402  */
403 static void
404 amd_ucode_wrmsr(void *ucode_ptr)
405 {
406 	uint32_t tmp[4];
407 
408 	wrmsr_safe(MSR_K8_UCODE_UPDATE, (uintptr_t)ucode_ptr);
409 	do_cpuid(0, tmp);
410 }
411 
412 static int
413 update_amd(int cpu, cpuctl_update_args_t *args, struct thread *td)
414 {
415 	void *ptr;
416 	int ret;
417 
418 	if (args->size == 0 || args->data == NULL) {
419 		DPRINTF("[cpuctl,%d]: zero-sized firmware image", __LINE__);
420 		return (EINVAL);
421 	}
422 	if (args->size > UCODE_SIZE_MAX) {
423 		DPRINTF("[cpuctl,%d]: firmware image too large", __LINE__);
424 		return (EINVAL);
425 	}
426 
427 	/*
428 	 * 16 byte alignment required.  Rely on the fact that
429 	 * malloc(9) always returns the pointer aligned at least on
430 	 * the size of the allocation.
431 	 */
432 	ptr = malloc(args->size + 16, M_CPUCTL, M_ZERO | M_WAITOK);
433 	if (copyin(args->data, ptr, args->size) != 0) {
434 		DPRINTF("[cpuctl,%d]: copyin %p->%p of %zd bytes failed",
435 		    __LINE__, args->data, ptr, args->size);
436 		ret = EFAULT;
437 		goto fail;
438 	}
439 	smp_rendezvous(NULL, amd_ucode_wrmsr, NULL, ptr);
440 	ret = 0;
441 fail:
442 	free(ptr, M_CPUCTL);
443 	return (ret);
444 }
445 
446 static int
447 update_via(int cpu, cpuctl_update_args_t *args, struct thread *td)
448 {
449 	void *ptr;
450 	uint64_t rev0, rev1, res;
451 	uint32_t tmp[4];
452 	int is_bound;
453 	int oldcpu;
454 	int ret;
455 
456 	if (args->size == 0 || args->data == NULL) {
457 		DPRINTF("[cpuctl,%d]: zero-sized firmware image", __LINE__);
458 		return (EINVAL);
459 	}
460 	if (args->size > UCODE_SIZE_MAX) {
461 		DPRINTF("[cpuctl,%d]: firmware image too large", __LINE__);
462 		return (EINVAL);
463 	}
464 
465 	/*
466 	 * 4 byte alignment required.
467 	 */
468 	ptr = malloc(args->size, M_CPUCTL, M_WAITOK);
469 	if (copyin(args->data, ptr, args->size) != 0) {
470 		DPRINTF("[cpuctl,%d]: copyin %p->%p of %zd bytes failed",
471 		    __LINE__, args->data, ptr, args->size);
472 		ret = EFAULT;
473 		goto fail;
474 	}
475 	oldcpu = td->td_oncpu;
476 	is_bound = cpu_sched_is_bound(td);
477 	set_cpu(cpu, td);
478 	critical_enter();
479 	rdmsr_safe(MSR_BIOS_SIGN, &rev0); /* Get current microcode revision. */
480 
481 	/*
482 	 * Perform update.
483 	 */
484 	wrmsr_safe(MSR_BIOS_UPDT_TRIG, (uintptr_t)(ptr));
485 	do_cpuid(1, tmp);
486 
487 	/*
488 	 * Result are in low byte of MSR FCR5:
489 	 * 0x00: No update has been attempted since RESET.
490 	 * 0x01: The last attempted update was successful.
491 	 * 0x02: The last attempted update was unsuccessful due to a bad
492 	 *       environment. No update was loaded and any preexisting
493 	 *       patches are still active.
494 	 * 0x03: The last attempted update was not applicable to this processor.
495 	 *       No update was loaded and any preexisting patches are still
496 	 *       active.
497 	 * 0x04: The last attempted update was not successful due to an invalid
498 	 *       update data block. No update was loaded and any preexisting
499 	 *       patches are still active
500 	 */
501 	rdmsr_safe(0x1205, &res);
502 	res &= 0xff;
503 	critical_exit();
504 	rdmsr_safe(MSR_BIOS_SIGN, &rev1); /* Get new microcode revision. */
505 	restore_cpu(oldcpu, is_bound, td);
506 
507 	DPRINTF("[cpu,%d]: rev0=%x rev1=%x res=%x\n", __LINE__,
508 	    (unsigned)(rev0 >> 32), (unsigned)(rev1 >> 32), (unsigned)res);
509 
510 	if (res != 0x01)
511 		ret = EINVAL;
512 	else
513 		ret = 0;
514 fail:
515 	free(ptr, M_CPUCTL);
516 	return (ret);
517 }
518 
519 static int
520 cpuctl_do_eval_cpu_features(int cpu, struct thread *td)
521 {
522 	int is_bound = 0;
523 	int oldcpu;
524 
525 	KASSERT(cpu >= 0 && cpu <= mp_maxid,
526 	    ("[cpuctl,%d]: bad cpu number %d", __LINE__, cpu));
527 
528 #ifdef __i386__
529 	if (cpu_id == 0)
530 		return (ENODEV);
531 #endif
532 	oldcpu = td->td_oncpu;
533 	is_bound = cpu_sched_is_bound(td);
534 	set_cpu(cpu, td);
535 	identify_cpu1();
536 	identify_cpu2();
537 	hw_ibrs_recalculate();
538 	restore_cpu(oldcpu, is_bound, td);
539 	hw_ssb_recalculate(true);
540 #ifdef __amd64__
541 	amd64_syscall_ret_flush_l1d_recalc();
542 #endif
543 	hw_mds_recalculate();
544 	printcpuinfo();
545 	return (0);
546 }
547 
548 
549 int
550 cpuctl_open(struct cdev *dev, int flags, int fmt __unused, struct thread *td)
551 {
552 	int ret = 0;
553 	int cpu;
554 
555 	cpu = dev2unit(dev);
556 	if (cpu > mp_maxid || !cpu_enabled(cpu)) {
557 		DPRINTF("[cpuctl,%d]: incorrect cpu number %d\n", __LINE__,
558 		    cpu);
559 		return (ENXIO);
560 	}
561 	if (flags & FWRITE)
562 		ret = securelevel_gt(td->td_ucred, 0);
563 	return (ret);
564 }
565 
566 static int
567 cpuctl_modevent(module_t mod __unused, int type, void *data __unused)
568 {
569 	int cpu;
570 
571 	switch(type) {
572 	case MOD_LOAD:
573 		if (bootverbose)
574 			printf("cpuctl: access to MSR registers/cpuid info.\n");
575 		cpuctl_devs = malloc(sizeof(*cpuctl_devs) * (mp_maxid + 1), M_CPUCTL,
576 		    M_WAITOK | M_ZERO);
577 		CPU_FOREACH(cpu)
578 			if (cpu_enabled(cpu))
579 				cpuctl_devs[cpu] = make_dev(&cpuctl_cdevsw, cpu,
580 				    UID_ROOT, GID_KMEM, 0640, "cpuctl%d", cpu);
581 		break;
582 	case MOD_UNLOAD:
583 		CPU_FOREACH(cpu) {
584 			if (cpuctl_devs[cpu] != NULL)
585 				destroy_dev(cpuctl_devs[cpu]);
586 		}
587 		free(cpuctl_devs, M_CPUCTL);
588 		break;
589 	case MOD_SHUTDOWN:
590 		break;
591 	default:
592 		return (EOPNOTSUPP);
593         }
594 	return (0);
595 }
596 
597 DEV_MODULE(cpuctl, cpuctl_modevent, NULL);
598 MODULE_VERSION(cpuctl, CPUCTL_VERSION);
599