]> git.saurik.com Git - apple/xnu.git/blob - osfmk/i386/fpu.c
xnu-6153.101.6.tar.gz
[apple/xnu.git] / osfmk / i386 / fpu.c
1 /*
2 * Copyright (c) 2000-2019 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /*
29 * @OSF_COPYRIGHT@
30 */
31 /*
32 * Mach Operating System
33 * Copyright (c) 1992-1990 Carnegie Mellon University
34 * All Rights Reserved.
35 *
36 * Permission to use, copy, modify and distribute this software and its
37 * documentation is hereby granted, provided that both the copyright
38 * notice and this permission notice appear in all copies of the
39 * software, derivative works or modified versions, and any portions
40 * thereof, and that both notices appear in supporting documentation.
41 *
42 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
43 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
44 * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
45 *
46 * Carnegie Mellon requests users of this software to return to
47 *
48 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
49 * School of Computer Science
50 * Carnegie Mellon University
51 * Pittsburgh PA 15213-3890
52 *
53 * any improvements or extensions that they make and grant Carnegie Mellon
54 * the rights to redistribute these changes.
55 */
56
57 #include <mach/exception_types.h>
58 #include <mach/i386/thread_status.h>
59 #include <mach/i386/fp_reg.h>
60
61 #include <kern/mach_param.h>
62 #include <kern/processor.h>
63 #include <kern/thread.h>
64 #include <kern/zalloc.h>
65 #include <kern/misc_protos.h>
66 #include <kern/spl.h>
67 #include <kern/assert.h>
68
69 #include <libkern/OSAtomic.h>
70
71 #include <architecture/i386/pio.h>
72 #include <i386/cpuid.h>
73 #include <i386/fpu.h>
74 #include <i386/proc_reg.h>
75 #include <i386/misc_protos.h>
76 #include <i386/thread.h>
77 #include <i386/trap.h>
78
79 xstate_t fpu_capability = UNDEFINED; /* extended state capability */
80 xstate_t fpu_default = UNDEFINED; /* default extended state */
81
82 #define ALIGNED(addr, size) (((uintptr_t)(addr)&((size)-1))==0)
83
84 /* Forward */
85
86 extern void fpinit(void);
87 extern void fp_save(
88 thread_t thr_act);
89 extern void fp_load(
90 thread_t thr_act);
91
92 static void configure_mxcsr_capability_mask(x86_ext_thread_state_t *fps);
93 static xstate_t thread_xstate(thread_t);
94
95 x86_ext_thread_state_t initial_fp_state __attribute((aligned(64)));
96 x86_ext_thread_state_t default_avx512_state __attribute((aligned(64)));
97 x86_ext_thread_state_t default_avx_state __attribute((aligned(64)));
98 x86_ext_thread_state_t default_fx_state __attribute((aligned(64)));
99
100 /* Global MXCSR capability bitmask */
101 static unsigned int mxcsr_capability_mask;
102
103 #define fninit() \
104 __asm__ volatile("fninit")
105
106 #define fnstcw(control) \
107 __asm__("fnstcw %0" : "=m" (*(unsigned short *)(control)))
108
109 #define fldcw(control) \
110 __asm__ volatile("fldcw %0" : : "m" (*(unsigned short *) &(control)) )
111
112 #define fnclex() \
113 __asm__ volatile("fnclex")
114
115 #define fnsave(state) \
116 __asm__ volatile("fnsave %0" : "=m" (*state))
117
118 #define frstor(state) \
119 __asm__ volatile("frstor %0" : : "m" (state))
120
121 #define fwait() \
122 __asm__("fwait");
123
124 static inline void
125 fxrstor(struct x86_fx_thread_state *a)
126 {
127 __asm__ __volatile__ ("fxrstor %0" :: "m" (*a));
128 }
129
130 static inline void
131 fxsave(struct x86_fx_thread_state *a)
132 {
133 __asm__ __volatile__ ("fxsave %0" : "=m" (*a));
134 }
135
136 static inline void
137 fxrstor64(struct x86_fx_thread_state *a)
138 {
139 __asm__ __volatile__ ("fxrstor64 %0" :: "m" (*a));
140 }
141
142 static inline void
143 fxsave64(struct x86_fx_thread_state *a)
144 {
145 __asm__ __volatile__ ("fxsave64 %0" : "=m" (*a));
146 }
147
148 #define IS_VALID_XSTATE(x) ((x) == FP || (x) == AVX || (x) == AVX512)
149
150 zone_t ifps_zone[] = {
151 [FP] = NULL,
152 [AVX] = NULL,
153 [AVX512] = NULL
154 };
155 static uint32_t fp_state_size[] = {
156 [FP] = sizeof(struct x86_fx_thread_state),
157 [AVX] = sizeof(struct x86_avx_thread_state),
158 [AVX512] = sizeof(struct x86_avx512_thread_state)
159 };
160
161 static const char *xstate_name[] = {
162 [UNDEFINED] = "UNDEFINED",
163 [FP] = "FP",
164 [AVX] = "AVX",
165 [AVX512] = "AVX512"
166 };
167
168 #define fpu_ZMM_capable (fpu_capability == AVX512)
169 #define fpu_YMM_capable (fpu_capability == AVX || fpu_capability == AVX512)
170 /*
171 * On-demand AVX512 support
172 * ------------------------
173 * On machines with AVX512 support, by default, threads are created with
174 * AVX512 masked off in XCR0 and an AVX-sized savearea is used. However, AVX512
175 * capabilities are advertised in the commpage and via sysctl. If a thread
176 * opts to use AVX512 instructions, the first will result in a #UD exception.
177 * Faulting AVX512 intructions are recognizable by their unique prefix.
178 * This exception results in the thread being promoted to use an AVX512-sized
179 * savearea and for the AVX512 bit masks being set in its XCR0. The faulting
180 * instruction is re-driven and the thread can proceed to perform AVX512
181 * operations.
182 *
183 * In addition to AVX512 instructions causing promotion, the thread_set_state()
184 * primitive with an AVX512 state flavor result in promotion.
185 *
186 * AVX512 promotion of the first thread in a task causes the default xstate
187 * of the task to be promoted so that any subsequently created or subsequently
188 * DNA-faulted thread will have AVX512 xstate and it will not need to fault-in
189 * a promoted xstate.
190 *
191 * Two savearea zones are used: the default pool of AVX-sized (832 byte) areas
192 * and a second pool of larger AVX512-sized (2688 byte) areas.
193 *
194 * Note the initial state value is an AVX512 object but that the AVX initial
195 * value is a subset of it.
196 */
197 static uint32_t cpuid_reevaluated = 0;
198
199 static void fpu_store_registers(void *, boolean_t);
200 static void fpu_load_registers(void *);
201
202 static const uint32_t xstate_xmask[] = {
203 [FP] = FP_XMASK,
204 [AVX] = AVX_XMASK,
205 [AVX512] = AVX512_XMASK
206 };
207
208 static inline void
209 xsave(struct x86_fx_thread_state *a, uint32_t rfbm)
210 {
211 __asm__ __volatile__ ("xsave %0" :"=m" (*a) : "a"(rfbm), "d"(0));
212 }
213
214 static inline void
215 xsave64(struct x86_fx_thread_state *a, uint32_t rfbm)
216 {
217 __asm__ __volatile__ ("xsave64 %0" :"=m" (*a) : "a"(rfbm), "d"(0));
218 }
219
220 static inline void
221 xrstor(struct x86_fx_thread_state *a, uint32_t rfbm)
222 {
223 __asm__ __volatile__ ("xrstor %0" :: "m" (*a), "a"(rfbm), "d"(0));
224 }
225
226 static inline void
227 xrstor64(struct x86_fx_thread_state *a, uint32_t rfbm)
228 {
229 __asm__ __volatile__ ("xrstor64 %0" :: "m" (*a), "a"(rfbm), "d"(0));
230 }
231
232 __unused static inline void
233 vzeroupper(void)
234 {
235 __asm__ __volatile__ ("vzeroupper" ::);
236 }
237
238 static boolean_t fpu_thread_promote_avx512(thread_t); /* Forward */
239
240
241 /*
242 * Furthermore, make compile-time asserts that no padding creeps into structures
243 * for which we're doing this.
244 */
245 #define ASSERT_PACKED(t, m1, m2, n, mt) \
246 extern char assert_packed_ ## t ## _ ## m1 ## _ ## m2 \
247 [(offsetof(t,m2) - offsetof(t,m1) == (n - 1)*sizeof(mt)) ? 1 : -1]
248
249 ASSERT_PACKED(x86_avx_state32_t, fpu_ymmh0, fpu_ymmh7, 8, _STRUCT_XMM_REG);
250
251 ASSERT_PACKED(x86_avx_state64_t, fpu_ymmh0, fpu_ymmh15, 16, _STRUCT_XMM_REG);
252
253 ASSERT_PACKED(x86_avx512_state32_t, fpu_k0, fpu_k7, 8, _STRUCT_OPMASK_REG);
254 ASSERT_PACKED(x86_avx512_state32_t, fpu_ymmh0, fpu_ymmh7, 8, _STRUCT_XMM_REG);
255 ASSERT_PACKED(x86_avx512_state32_t, fpu_zmmh0, fpu_zmmh7, 8, _STRUCT_YMM_REG);
256
257 ASSERT_PACKED(x86_avx512_state64_t, fpu_k0, fpu_k7, 8, _STRUCT_OPMASK_REG);
258 ASSERT_PACKED(x86_avx512_state64_t, fpu_ymmh0, fpu_ymmh15, 16, _STRUCT_XMM_REG);
259 ASSERT_PACKED(x86_avx512_state64_t, fpu_zmmh0, fpu_zmmh15, 16, _STRUCT_YMM_REG);
260 ASSERT_PACKED(x86_avx512_state64_t, fpu_zmm16, fpu_zmm31, 16, _STRUCT_ZMM_REG);
261
262 #if defined(DEBUG_AVX512)
263
264 #define DBG(x...) kprintf("DBG: " x)
265
266 typedef struct { uint8_t byte[8]; } opmask_t;
267 typedef struct { uint8_t byte[16]; } xmm_t;
268 typedef struct { uint8_t byte[32]; } ymm_t;
269 typedef struct { uint8_t byte[64]; } zmm_t;
270
271 static void
272 DBG_AVX512_STATE(struct x86_avx512_thread_state *sp)
273 {
274 int i, j;
275 xmm_t *xmm = (xmm_t *) &sp->fp.fx_XMM_reg;
276 xmm_t *ymmh = (xmm_t *) &sp->x_YMM_Hi128;
277 ymm_t *zmmh = (ymm_t *) &sp->x_ZMM_Hi256;
278 zmm_t *zmm = (zmm_t *) &sp->x_Hi16_ZMM;
279 opmask_t *k = (opmask_t *) &sp->x_Opmask;
280
281 kprintf("x_YMM_Hi128: %lu\n", offsetof(struct x86_avx512_thread_state, x_YMM_Hi128));
282 kprintf("x_Opmask: %lu\n", offsetof(struct x86_avx512_thread_state, x_Opmask));
283 kprintf("x_ZMM_Hi256: %lu\n", offsetof(struct x86_avx512_thread_state, x_ZMM_Hi256));
284 kprintf("x_Hi16_ZMM: %lu\n", offsetof(struct x86_avx512_thread_state, x_Hi16_ZMM));
285
286 kprintf("XCR0: 0x%016llx\n", xgetbv(XCR0));
287 kprintf("XINUSE: 0x%016llx\n", xgetbv(1));
288
289 /* Print all ZMM registers */
290 for (i = 0; i < 16; i++) {
291 kprintf("zmm%d:\t0x", i);
292 for (j = 0; j < 16; j++) {
293 kprintf("%02x", xmm[i].byte[j]);
294 }
295 for (j = 0; j < 16; j++) {
296 kprintf("%02x", ymmh[i].byte[j]);
297 }
298 for (j = 0; j < 32; j++) {
299 kprintf("%02x", zmmh[i].byte[j]);
300 }
301 kprintf("\n");
302 }
303 for (i = 0; i < 16; i++) {
304 kprintf("zmm%d:\t0x", 16 + i);
305 for (j = 0; j < 64; j++) {
306 kprintf("%02x", zmm[i].byte[j]);
307 }
308 kprintf("\n");
309 }
310 for (i = 0; i < 8; i++) {
311 kprintf("k%d:\t0x", i);
312 for (j = 0; j < 8; j++) {
313 kprintf("%02x", k[i].byte[j]);
314 }
315 kprintf("\n");
316 }
317
318 kprintf("xstate_bv: 0x%016llx\n", sp->_xh.xstate_bv);
319 kprintf("xcomp_bv: 0x%016llx\n", sp->_xh.xcomp_bv);
320 }
321 #else
322 #define DBG(x...)
323 static void
324 DBG_AVX512_STATE(__unused struct x86_avx512_thread_state *sp)
325 {
326 return;
327 }
328 #endif /* DEBUG_AVX512 */
329
330 #if DEBUG
331 static inline unsigned short
332 fnstsw(void)
333 {
334 unsigned short status;
335 __asm__ volatile ("fnstsw %0" : "=ma" (status));
336 return status;
337 }
338 #endif
339
340 /*
341 * Configure the initial FPU state presented to new threads.
342 * Determine the MXCSR capability mask, which allows us to mask off any
343 * potentially unsafe "reserved" bits before restoring the FPU context.
344 * *Not* per-cpu, assumes symmetry.
345 */
346
347 static void
348 configure_mxcsr_capability_mask(x86_ext_thread_state_t *fps)
349 {
350 /* XSAVE requires a 64 byte aligned store */
351 assert(ALIGNED(fps, 64));
352 /* Clear, to prepare for the diagnostic FXSAVE */
353 bzero(fps, sizeof(*fps));
354
355 fpinit();
356 fpu_store_registers(fps, FALSE);
357
358 mxcsr_capability_mask = fps->fx.fx_MXCSR_MASK;
359
360 /* Set default mask value if necessary */
361 if (mxcsr_capability_mask == 0) {
362 mxcsr_capability_mask = 0xffbf;
363 }
364
365 /* Clear vector register store */
366 bzero(&fps->fx.fx_XMM_reg[0][0], sizeof(fps->fx.fx_XMM_reg));
367 bzero(fps->avx.x_YMM_Hi128, sizeof(fps->avx.x_YMM_Hi128));
368 if (fpu_ZMM_capable) {
369 bzero(fps->avx512.x_ZMM_Hi256, sizeof(fps->avx512.x_ZMM_Hi256));
370 bzero(fps->avx512.x_Hi16_ZMM, sizeof(fps->avx512.x_Hi16_ZMM));
371 bzero(fps->avx512.x_Opmask, sizeof(fps->avx512.x_Opmask));
372 }
373
374 fps->fx.fp_valid = TRUE;
375 fps->fx.fp_save_layout = fpu_YMM_capable ? XSAVE32: FXSAVE32;
376 fpu_load_registers(fps);
377
378 if (fpu_ZMM_capable) {
379 xsave64((struct x86_fx_thread_state *)&default_avx512_state, xstate_xmask[AVX512]);
380 }
381 if (fpu_YMM_capable) {
382 xsave64((struct x86_fx_thread_state *)&default_avx_state, xstate_xmask[AVX]);
383 } else {
384 fxsave64((struct x86_fx_thread_state *)&default_fx_state);
385 }
386
387 /* Poison values to trap unsafe usage */
388 fps->fx.fp_valid = 0xFFFFFFFF;
389 fps->fx.fp_save_layout = FP_UNUSED;
390
391 /* Re-enable FPU/SSE DNA exceptions */
392 set_ts();
393 }
394
395 int fpsimd_fault_popc = 0;
396 /*
397 * Look for FPU and initialize it.
398 * Called on each CPU.
399 */
400 void
401 init_fpu(void)
402 {
403 #if DEBUG
404 unsigned short status;
405 unsigned short control;
406 #endif
407 /*
408 * Check for FPU by initializing it,
409 * then trying to read the correct bit patterns from
410 * the control and status registers.
411 */
412 set_cr0((get_cr0() & ~(CR0_EM | CR0_TS)) | CR0_NE); /* allow use of FPU */
413 fninit();
414 #if DEBUG
415 status = fnstsw();
416 fnstcw(&control);
417
418 assert(((status & 0xff) == 0) && ((control & 0x103f) == 0x3f));
419 #endif
420 /* Advertise SSE support */
421 if (cpuid_features() & CPUID_FEATURE_FXSR) {
422 set_cr4(get_cr4() | CR4_OSFXS);
423 /* And allow SIMD exceptions if present */
424 if (cpuid_features() & CPUID_FEATURE_SSE) {
425 set_cr4(get_cr4() | CR4_OSXMM);
426 }
427 } else {
428 panic("fpu is not FP_FXSR");
429 }
430
431 fpu_capability = fpu_default = FP;
432
433 PE_parse_boot_argn("fpsimd_fault_popc", &fpsimd_fault_popc, sizeof(fpsimd_fault_popc));
434
435 static boolean_t is_avx512_enabled = TRUE;
436 if (cpu_number() == master_cpu) {
437 if (cpuid_leaf7_features() & CPUID_LEAF7_FEATURE_AVX512F) {
438 PE_parse_boot_argn("avx512", &is_avx512_enabled, sizeof(boolean_t));
439 kprintf("AVX512 supported %s\n",
440 is_avx512_enabled ? "and enabled" : "but disabled");
441 }
442 }
443
444 /* Configure the XSAVE context mechanism if the processor supports
445 * AVX/YMM registers
446 */
447 if (cpuid_features() & CPUID_FEATURE_XSAVE) {
448 cpuid_xsave_leaf_t *xs0p = &cpuid_info()->cpuid_xsave_leaf[0];
449 if (is_avx512_enabled &&
450 (xs0p->extended_state[eax] & XFEM_ZMM) == XFEM_ZMM) {
451 assert(xs0p->extended_state[eax] & XFEM_SSE);
452 assert(xs0p->extended_state[eax] & XFEM_YMM);
453 fpu_capability = AVX512;
454 /* XSAVE container size for all features */
455 set_cr4(get_cr4() | CR4_OSXSAVE);
456 xsetbv(0, AVX512_XMASK);
457 /* Re-evaluate CPUID, once, to reflect OSXSAVE */
458 if (OSCompareAndSwap(0, 1, &cpuid_reevaluated)) {
459 cpuid_set_info();
460 }
461 /* Verify that now selected state can be accommodated */
462 assert(xs0p->extended_state[ebx] == fp_state_size[AVX512]);
463 /*
464 * AVX set until AVX512 is used.
465 * See comment above about on-demand AVX512 support.
466 */
467 xsetbv(0, AVX_XMASK);
468 fpu_default = AVX;
469 } else if (xs0p->extended_state[eax] & XFEM_YMM) {
470 assert(xs0p->extended_state[eax] & XFEM_SSE);
471 fpu_capability = AVX;
472 fpu_default = AVX;
473 /* XSAVE container size for all features */
474 set_cr4(get_cr4() | CR4_OSXSAVE);
475 xsetbv(0, AVX_XMASK);
476 /* Re-evaluate CPUID, once, to reflect OSXSAVE */
477 if (OSCompareAndSwap(0, 1, &cpuid_reevaluated)) {
478 cpuid_set_info();
479 }
480 /* Verify that now selected state can be accommodated */
481 assert(xs0p->extended_state[ebx] == fp_state_size[AVX]);
482 }
483 }
484
485 if (cpu_number() == master_cpu) {
486 kprintf("fpu_state: %s, state_size: %d\n",
487 xstate_name[fpu_capability],
488 fp_state_size[fpu_capability]);
489 }
490
491 fpinit();
492 current_cpu_datap()->cpu_xstate = fpu_default;
493
494 /*
495 * Trap wait instructions. Turn off FPU for now.
496 */
497 set_cr0(get_cr0() | CR0_TS | CR0_MP);
498 }
499
500 /*
501 * Allocate and initialize FP state for specified xstate.
502 * Don't load state.
503 */
504 static void *
505 fp_state_alloc(xstate_t xs)
506 {
507 struct x86_fx_thread_state *ifps;
508
509 assert(ifps_zone[xs] != NULL);
510 ifps = zalloc(ifps_zone[xs]);
511
512 #if DEBUG
513 if (!(ALIGNED(ifps, 64))) {
514 panic("fp_state_alloc: %p, %u, %p, %u",
515 ifps, (unsigned) ifps_zone[xs]->elem_size,
516 (void *) ifps_zone[xs]->free_elements,
517 (unsigned) ifps_zone[xs]->alloc_size);
518 }
519 #endif
520 bzero(ifps, fp_state_size[xs]);
521
522 return ifps;
523 }
524
525 static inline void
526 fp_state_free(void *ifps, xstate_t xs)
527 {
528 assert(ifps_zone[xs] != NULL);
529 zfree(ifps_zone[xs], ifps);
530 }
531
532 void
533 clear_fpu(void)
534 {
535 set_ts();
536 }
537
538
539 static void
540 fpu_load_registers(void *fstate)
541 {
542 struct x86_fx_thread_state *ifps = fstate;
543 fp_save_layout_t layout = ifps->fp_save_layout;
544
545 assert(current_task() == NULL || \
546 (thread_is_64bit_addr(current_thread()) ? \
547 (layout == FXSAVE64 || layout == XSAVE64) : \
548 (layout == FXSAVE32 || layout == XSAVE32)));
549 assert(ALIGNED(ifps, 64));
550 assert(ml_get_interrupts_enabled() == FALSE);
551
552 #if DEBUG
553 if (layout == XSAVE32 || layout == XSAVE64) {
554 struct x86_avx_thread_state *iavx = fstate;
555 unsigned i;
556 /* Verify reserved bits in the XSAVE header*/
557 if (iavx->_xh.xstate_bv & ~xstate_xmask[current_xstate()]) {
558 panic("iavx->_xh.xstate_bv: 0x%llx", iavx->_xh.xstate_bv);
559 }
560 for (i = 0; i < sizeof(iavx->_xh.xhrsvd); i++) {
561 if (iavx->_xh.xhrsvd[i]) {
562 panic("Reserved bit set");
563 }
564 }
565 }
566 if (fpu_YMM_capable) {
567 if (layout != XSAVE32 && layout != XSAVE64) {
568 panic("Inappropriate layout: %u\n", layout);
569 }
570 }
571 #endif /* DEBUG */
572
573 switch (layout) {
574 case FXSAVE64:
575 fxrstor64(ifps);
576 break;
577 case FXSAVE32:
578 fxrstor(ifps);
579 break;
580 case XSAVE64:
581 xrstor64(ifps, xstate_xmask[current_xstate()]);
582 break;
583 case XSAVE32:
584 xrstor(ifps, xstate_xmask[current_xstate()]);
585 break;
586 default:
587 panic("fpu_load_registers() bad layout: %d\n", layout);
588 }
589 }
590
591 static void
592 fpu_store_registers(void *fstate, boolean_t is64)
593 {
594 struct x86_fx_thread_state *ifps = fstate;
595 assert(ALIGNED(ifps, 64));
596 xstate_t xs = current_xstate();
597 switch (xs) {
598 case FP:
599 if (is64) {
600 fxsave64(fstate);
601 ifps->fp_save_layout = FXSAVE64;
602 } else {
603 fxsave(fstate);
604 ifps->fp_save_layout = FXSAVE32;
605 }
606 break;
607 case AVX:
608 case AVX512:
609 if (is64) {
610 xsave64(ifps, xstate_xmask[xs]);
611 ifps->fp_save_layout = XSAVE64;
612 } else {
613 xsave(ifps, xstate_xmask[xs]);
614 ifps->fp_save_layout = XSAVE32;
615 }
616 break;
617 default:
618 panic("fpu_store_registers() bad xstate: %d\n", xs);
619 }
620 }
621
622 /*
623 * Initialize FP handling.
624 */
625
626 void
627 fpu_module_init(void)
628 {
629 if (!IS_VALID_XSTATE(fpu_default)) {
630 panic("fpu_module_init: invalid extended state %u\n",
631 fpu_default);
632 }
633
634 /* We explicitly choose an allocation size of 13 pages = 64 * 832
635 * to eliminate waste for the 832 byte sized
636 * AVX XSAVE register save area.
637 */
638 ifps_zone[fpu_default] = zinit(fp_state_size[fpu_default],
639 thread_max * fp_state_size[fpu_default],
640 64 * fp_state_size[fpu_default],
641 "x86 fpsave state");
642
643 /* To maintain the required alignment, disable
644 * zone debugging for this zone as that appends
645 * 16 bytes to each element.
646 */
647 zone_change(ifps_zone[fpu_default], Z_ALIGNMENT_REQUIRED, TRUE);
648
649 /*
650 * If AVX512 is supported, create a separate savearea zone.
651 * with allocation size: 19 pages = 32 * 2668
652 */
653 if (fpu_capability == AVX512) {
654 ifps_zone[AVX512] = zinit(fp_state_size[AVX512],
655 thread_max * fp_state_size[AVX512],
656 32 * fp_state_size[AVX512],
657 "x86 avx512 save state");
658 zone_change(ifps_zone[AVX512], Z_ALIGNMENT_REQUIRED, TRUE);
659 }
660
661 /* Determine MXCSR reserved bits and configure initial FPU state*/
662 configure_mxcsr_capability_mask(&initial_fp_state);
663 }
664
665 /*
666 * Context switch fpu state.
667 * Always save old thread`s FPU context but don't load new .. allow that to fault-in.
668 * Switch to the new task's xstate.
669 */
670
671 void
672 fpu_switch_context(thread_t old, thread_t new)
673 {
674 struct x86_fx_thread_state *ifps;
675 cpu_data_t *cdp = current_cpu_datap();
676 xstate_t new_xstate = new ? thread_xstate(new) : fpu_default;
677
678 assert(ml_get_interrupts_enabled() == FALSE);
679 ifps = (old)->machine.ifps;
680 #if DEBUG
681 if (ifps && ((ifps->fp_valid != FALSE) && (ifps->fp_valid != TRUE))) {
682 panic("ifps->fp_valid: %u\n", ifps->fp_valid);
683 }
684 #endif
685 if (ifps != 0 && (ifps->fp_valid == FALSE)) {
686 /* Clear CR0.TS in preparation for the FP context save. In
687 * theory, this shouldn't be necessary since a live FPU should
688 * indicate that TS is clear. However, various routines
689 * (such as sendsig & sigreturn) manipulate TS directly.
690 */
691 clear_ts();
692 /* registers are in FPU - save to memory */
693 boolean_t is64 = (thread_is_64bit_addr(old) &&
694 is_saved_state64(old->machine.iss));
695
696 fpu_store_registers(ifps, is64);
697 ifps->fp_valid = TRUE;
698
699 if (fpu_ZMM_capable && (cdp->cpu_xstate == AVX512)) {
700 xrstor64((struct x86_fx_thread_state *)&default_avx512_state, xstate_xmask[AVX512]);
701 } else if (fpu_YMM_capable) {
702 xrstor64((struct x86_fx_thread_state *) &default_avx_state, xstate_xmask[AVX]);
703 } else {
704 fxrstor64((struct x86_fx_thread_state *)&default_fx_state);
705 }
706 }
707
708 assertf(fpu_YMM_capable ? (xgetbv(XCR0) == xstate_xmask[cdp->cpu_xstate]) : TRUE, "XCR0 mismatch: 0x%llx 0x%x 0x%x", xgetbv(XCR0), cdp->cpu_xstate, xstate_xmask[cdp->cpu_xstate]);
709 if (new_xstate != (xstate_t) cdp->cpu_xstate) {
710 DBG("fpu_switch_context(%p,%p) new xstate: %s\n",
711 old, new, xstate_name[new_xstate]);
712 xsetbv(0, xstate_xmask[new_xstate]);
713 cdp->cpu_xstate = new_xstate;
714 }
715 set_ts();
716 }
717
718
719 /*
720 * Free a FPU save area.
721 * Called only when thread terminating - no locking necessary.
722 */
723 void
724 fpu_free(thread_t thread, void *fps)
725 {
726 pcb_t pcb = THREAD_TO_PCB(thread);
727
728 fp_state_free(fps, pcb->xstate);
729 pcb->xstate = UNDEFINED;
730 }
731
732 /*
733 * Set the floating-point state for a thread based
734 * on the FXSave formatted data. This is basically
735 * the same as fpu_set_state except it uses the
736 * expanded data structure.
737 * If the thread is not the current thread, it is
738 * not running (held). Locking needed against
739 * concurrent fpu_set_state or fpu_get_state.
740 */
741 kern_return_t
742 fpu_set_fxstate(
743 thread_t thr_act,
744 thread_state_t tstate,
745 thread_flavor_t f)
746 {
747 struct x86_fx_thread_state *ifps;
748 struct x86_fx_thread_state *new_ifps;
749 x86_float_state64_t *state;
750 pcb_t pcb;
751 boolean_t old_valid, fresh_state = FALSE;
752 xstate_t thr_xstate;
753
754 if (fpu_capability == UNDEFINED) {
755 return KERN_FAILURE;
756 }
757
758 if ((f == x86_AVX_STATE32 || f == x86_AVX_STATE64) &&
759 fpu_capability < AVX) {
760 return KERN_FAILURE;
761 }
762
763 assert(thr_act != THREAD_NULL);
764
765 thr_xstate = thread_xstate(thr_act);
766
767 if ((f == x86_AVX512_STATE32 || f == x86_AVX512_STATE64) &&
768 thr_xstate == AVX) {
769 if (!fpu_thread_promote_avx512(thr_act)) {
770 return KERN_FAILURE;
771 } else {
772 /* Reload thr_xstate after successful promotion */
773 thr_xstate = thread_xstate(thr_act);
774 }
775 }
776
777 state = (x86_float_state64_t *)tstate;
778
779 pcb = THREAD_TO_PCB(thr_act);
780
781 if (state == NULL) {
782 /*
783 * new FPU state is 'invalid'.
784 * Deallocate the fp state if it exists.
785 */
786 simple_lock(&pcb->lock, LCK_GRP_NULL);
787
788 ifps = pcb->ifps;
789 pcb->ifps = 0;
790
791 simple_unlock(&pcb->lock);
792
793 if (ifps != 0) {
794 fp_state_free(ifps, thr_xstate);
795 }
796 } else {
797 /*
798 * Valid incoming state. Allocate the fp state if there is none.
799 */
800 new_ifps = 0;
801 Retry:
802 simple_lock(&pcb->lock, LCK_GRP_NULL);
803
804 ifps = pcb->ifps;
805 if (ifps == 0) {
806 if (new_ifps == 0) {
807 simple_unlock(&pcb->lock);
808 new_ifps = fp_state_alloc(thr_xstate);
809 goto Retry;
810 }
811 ifps = new_ifps;
812 new_ifps = 0;
813 pcb->ifps = ifps;
814 pcb->xstate = thr_xstate;
815 fresh_state = TRUE;
816 }
817
818 /*
819 * now copy over the new data.
820 */
821
822 old_valid = ifps->fp_valid;
823
824 #if DEBUG || DEVELOPMENT
825 if ((fresh_state == FALSE) && (old_valid == FALSE) && (thr_act != current_thread())) {
826 panic("fpu_set_fxstate inconsistency, thread: %p not stopped", thr_act);
827 }
828 #endif
829 /*
830 * Clear any reserved bits in the MXCSR to prevent a GPF
831 * when issuing an FXRSTOR.
832 */
833
834 state->fpu_mxcsr &= mxcsr_capability_mask;
835
836 __nochk_bcopy((char *)&state->fpu_fcw, (char *)ifps, fp_state_size[FP]);
837
838 switch (thr_xstate) {
839 case UNDEFINED_FULL:
840 case FP_FULL:
841 case AVX_FULL:
842 case AVX512_FULL:
843 panic("fpu_set_fxstate() INVALID xstate: 0x%x", thr_xstate);
844 break;
845
846 case UNDEFINED:
847 panic("fpu_set_fxstate() UNDEFINED xstate");
848 break;
849 case FP:
850 ifps->fp_save_layout = thread_is_64bit_addr(thr_act) ? FXSAVE64 : FXSAVE32;
851 break;
852 case AVX: {
853 struct x86_avx_thread_state *iavx = (void *) ifps;
854 x86_avx_state64_t *xs = (x86_avx_state64_t *) state;
855
856 iavx->fp.fp_save_layout = thread_is_64bit_addr(thr_act) ? XSAVE64 : XSAVE32;
857
858 /* Sanitize XSAVE header */
859 bzero(&iavx->_xh.xhrsvd[0], sizeof(iavx->_xh.xhrsvd));
860 iavx->_xh.xstate_bv = AVX_XMASK;
861 iavx->_xh.xcomp_bv = 0;
862
863 if (f == x86_AVX_STATE32) {
864 __nochk_bcopy(&xs->fpu_ymmh0, iavx->x_YMM_Hi128, 8 * sizeof(_STRUCT_XMM_REG));
865 } else if (f == x86_AVX_STATE64) {
866 __nochk_bcopy(&xs->fpu_ymmh0, iavx->x_YMM_Hi128, 16 * sizeof(_STRUCT_XMM_REG));
867 } else {
868 iavx->_xh.xstate_bv = (XFEM_SSE | XFEM_X87);
869 }
870 break;
871 }
872 case AVX512: {
873 struct x86_avx512_thread_state *iavx = (void *) ifps;
874 union {
875 thread_state_t ts;
876 x86_avx512_state32_t *s32;
877 x86_avx512_state64_t *s64;
878 } xs = { .ts = tstate };
879
880 iavx->fp.fp_save_layout = thread_is_64bit_addr(thr_act) ? XSAVE64 : XSAVE32;
881
882 /* Sanitize XSAVE header */
883 bzero(&iavx->_xh.xhrsvd[0], sizeof(iavx->_xh.xhrsvd));
884 iavx->_xh.xstate_bv = AVX512_XMASK;
885 iavx->_xh.xcomp_bv = 0;
886
887 switch (f) {
888 case x86_AVX512_STATE32:
889 __nochk_bcopy(&xs.s32->fpu_k0, iavx->x_Opmask, 8 * sizeof(_STRUCT_OPMASK_REG));
890 __nochk_bcopy(&xs.s32->fpu_zmmh0, iavx->x_ZMM_Hi256, 8 * sizeof(_STRUCT_YMM_REG));
891 __nochk_bcopy(&xs.s32->fpu_ymmh0, iavx->x_YMM_Hi128, 8 * sizeof(_STRUCT_XMM_REG));
892 DBG_AVX512_STATE(iavx);
893 break;
894 case x86_AVX_STATE32:
895 __nochk_bcopy(&xs.s32->fpu_ymmh0, iavx->x_YMM_Hi128, 8 * sizeof(_STRUCT_XMM_REG));
896 break;
897 case x86_AVX512_STATE64:
898 __nochk_bcopy(&xs.s64->fpu_k0, iavx->x_Opmask, 8 * sizeof(_STRUCT_OPMASK_REG));
899 __nochk_bcopy(&xs.s64->fpu_zmm16, iavx->x_Hi16_ZMM, 16 * sizeof(_STRUCT_ZMM_REG));
900 __nochk_bcopy(&xs.s64->fpu_zmmh0, iavx->x_ZMM_Hi256, 16 * sizeof(_STRUCT_YMM_REG));
901 __nochk_bcopy(&xs.s64->fpu_ymmh0, iavx->x_YMM_Hi128, 16 * sizeof(_STRUCT_XMM_REG));
902 DBG_AVX512_STATE(iavx);
903 break;
904 case x86_AVX_STATE64:
905 __nochk_bcopy(&xs.s64->fpu_ymmh0, iavx->x_YMM_Hi128, 16 * sizeof(_STRUCT_XMM_REG));
906 break;
907 }
908 break;
909 }
910 }
911
912 ifps->fp_valid = old_valid;
913
914 if (old_valid == FALSE) {
915 boolean_t istate = ml_set_interrupts_enabled(FALSE);
916 ifps->fp_valid = TRUE;
917 /* If altering the current thread's state, disable FPU */
918 if (thr_act == current_thread()) {
919 set_ts();
920 }
921
922 ml_set_interrupts_enabled(istate);
923 }
924
925 simple_unlock(&pcb->lock);
926
927 if (new_ifps != 0) {
928 fp_state_free(new_ifps, thr_xstate);
929 }
930 }
931 return KERN_SUCCESS;
932 }
933
934 /*
935 * Get the floating-point state for a thread.
936 * If the thread is not the current thread, it is
937 * not running (held). Locking needed against
938 * concurrent fpu_set_state or fpu_get_state.
939 */
940 kern_return_t
941 fpu_get_fxstate(
942 thread_t thr_act,
943 thread_state_t tstate,
944 thread_flavor_t f)
945 {
946 struct x86_fx_thread_state *ifps;
947 x86_float_state64_t *state;
948 kern_return_t ret = KERN_FAILURE;
949 pcb_t pcb;
950 xstate_t thr_xstate = thread_xstate(thr_act);
951
952 if (fpu_capability == UNDEFINED) {
953 return KERN_FAILURE;
954 }
955
956 if ((f == x86_AVX_STATE32 || f == x86_AVX_STATE64) &&
957 fpu_capability < AVX) {
958 return KERN_FAILURE;
959 }
960
961 if ((f == x86_AVX512_STATE32 || f == x86_AVX512_STATE64) &&
962 thr_xstate != AVX512) {
963 return KERN_FAILURE;
964 }
965
966 state = (x86_float_state64_t *)tstate;
967
968 assert(thr_act != THREAD_NULL);
969 pcb = THREAD_TO_PCB(thr_act);
970
971 simple_lock(&pcb->lock, LCK_GRP_NULL);
972
973 ifps = pcb->ifps;
974 if (ifps == 0) {
975 /*
976 * No valid floating-point state.
977 */
978
979 __nochk_bcopy((char *)&initial_fp_state, (char *)&state->fpu_fcw,
980 fp_state_size[FP]);
981
982 simple_unlock(&pcb->lock);
983
984 return KERN_SUCCESS;
985 }
986 /*
987 * Make sure we`ve got the latest fp state info
988 * If the live fpu state belongs to our target
989 */
990 if (thr_act == current_thread()) {
991 boolean_t intr;
992
993 intr = ml_set_interrupts_enabled(FALSE);
994
995 clear_ts();
996 fp_save(thr_act);
997 clear_fpu();
998
999 (void)ml_set_interrupts_enabled(intr);
1000 }
1001 if (ifps->fp_valid) {
1002 __nochk_bcopy((char *)ifps, (char *)&state->fpu_fcw, fp_state_size[FP]);
1003 switch (thr_xstate) {
1004 case UNDEFINED_FULL:
1005 case FP_FULL:
1006 case AVX_FULL:
1007 case AVX512_FULL:
1008 panic("fpu_get_fxstate() INVALID xstate: 0x%x", thr_xstate);
1009 break;
1010
1011 case UNDEFINED:
1012 panic("fpu_get_fxstate() UNDEFINED xstate");
1013 break;
1014 case FP:
1015 break; /* already done */
1016 case AVX: {
1017 struct x86_avx_thread_state *iavx = (void *) ifps;
1018 x86_avx_state64_t *xs = (x86_avx_state64_t *) state;
1019 if (f == x86_AVX_STATE32) {
1020 __nochk_bcopy(iavx->x_YMM_Hi128, &xs->fpu_ymmh0, 8 * sizeof(_STRUCT_XMM_REG));
1021 } else if (f == x86_AVX_STATE64) {
1022 __nochk_bcopy(iavx->x_YMM_Hi128, &xs->fpu_ymmh0, 16 * sizeof(_STRUCT_XMM_REG));
1023 }
1024 break;
1025 }
1026 case AVX512: {
1027 struct x86_avx512_thread_state *iavx = (void *) ifps;
1028 union {
1029 thread_state_t ts;
1030 x86_avx512_state32_t *s32;
1031 x86_avx512_state64_t *s64;
1032 } xs = { .ts = tstate };
1033 switch (f) {
1034 case x86_AVX512_STATE32:
1035 __nochk_bcopy(iavx->x_Opmask, &xs.s32->fpu_k0, 8 * sizeof(_STRUCT_OPMASK_REG));
1036 __nochk_bcopy(iavx->x_ZMM_Hi256, &xs.s32->fpu_zmmh0, 8 * sizeof(_STRUCT_YMM_REG));
1037 __nochk_bcopy(iavx->x_YMM_Hi128, &xs.s32->fpu_ymmh0, 8 * sizeof(_STRUCT_XMM_REG));
1038 DBG_AVX512_STATE(iavx);
1039 break;
1040 case x86_AVX_STATE32:
1041 __nochk_bcopy(iavx->x_YMM_Hi128, &xs.s32->fpu_ymmh0, 8 * sizeof(_STRUCT_XMM_REG));
1042 break;
1043 case x86_AVX512_STATE64:
1044 __nochk_bcopy(iavx->x_Opmask, &xs.s64->fpu_k0, 8 * sizeof(_STRUCT_OPMASK_REG));
1045 __nochk_bcopy(iavx->x_Hi16_ZMM, &xs.s64->fpu_zmm16, 16 * sizeof(_STRUCT_ZMM_REG));
1046 __nochk_bcopy(iavx->x_ZMM_Hi256, &xs.s64->fpu_zmmh0, 16 * sizeof(_STRUCT_YMM_REG));
1047 __nochk_bcopy(iavx->x_YMM_Hi128, &xs.s64->fpu_ymmh0, 16 * sizeof(_STRUCT_XMM_REG));
1048 DBG_AVX512_STATE(iavx);
1049 break;
1050 case x86_AVX_STATE64:
1051 __nochk_bcopy(iavx->x_YMM_Hi128, &xs.s64->fpu_ymmh0, 16 * sizeof(_STRUCT_XMM_REG));
1052 break;
1053 }
1054 break;
1055 }
1056 }
1057
1058 ret = KERN_SUCCESS;
1059 }
1060 simple_unlock(&pcb->lock);
1061
1062 return ret;
1063 }
1064
1065
1066
1067 /*
1068 * the child thread is 'stopped' with the thread
1069 * mutex held and is currently not known by anyone
1070 * so no way for fpu state to get manipulated by an
1071 * outside agency -> no need for pcb lock
1072 */
1073
1074 void
1075 fpu_dup_fxstate(
1076 thread_t parent,
1077 thread_t child)
1078 {
1079 struct x86_fx_thread_state *new_ifps = NULL;
1080 boolean_t intr;
1081 pcb_t ppcb;
1082 xstate_t xstate = thread_xstate(parent);
1083
1084 ppcb = THREAD_TO_PCB(parent);
1085
1086 if (ppcb->ifps == NULL) {
1087 return;
1088 }
1089
1090 if (child->machine.ifps) {
1091 panic("fpu_dup_fxstate: child's ifps non-null");
1092 }
1093
1094 new_ifps = fp_state_alloc(xstate);
1095
1096 simple_lock(&ppcb->lock, LCK_GRP_NULL);
1097
1098 if (ppcb->ifps != NULL) {
1099 struct x86_fx_thread_state *ifps = ppcb->ifps;
1100 /*
1101 * Make sure we`ve got the latest fp state info
1102 */
1103 if (current_thread() == parent) {
1104 intr = ml_set_interrupts_enabled(FALSE);
1105 assert(current_thread() == parent);
1106 clear_ts();
1107 fp_save(parent);
1108 clear_fpu();
1109
1110 (void)ml_set_interrupts_enabled(intr);
1111 }
1112
1113 if (ifps->fp_valid) {
1114 child->machine.ifps = new_ifps;
1115 child->machine.xstate = xstate;
1116 __nochk_bcopy((char *)(ppcb->ifps),
1117 (char *)(child->machine.ifps),
1118 fp_state_size[xstate]);
1119
1120 /* Mark the new fp saved state as non-live. */
1121 /* Temporarily disabled: radar 4647827
1122 * new_ifps->fp_valid = TRUE;
1123 */
1124
1125 /*
1126 * Clear any reserved bits in the MXCSR to prevent a GPF
1127 * when issuing an FXRSTOR.
1128 */
1129 new_ifps->fx_MXCSR &= mxcsr_capability_mask;
1130 new_ifps = NULL;
1131 }
1132 }
1133 simple_unlock(&ppcb->lock);
1134
1135 if (new_ifps != NULL) {
1136 fp_state_free(new_ifps, xstate);
1137 }
1138 }
1139
1140 /*
1141 * Initialize FPU.
1142 * FNINIT programs the x87 control word to 0x37f, which matches
1143 * the desired default for macOS.
1144 */
1145
1146 void
1147 fpinit(void)
1148 {
1149 boolean_t istate = ml_set_interrupts_enabled(FALSE);
1150 clear_ts();
1151 fninit();
1152 #if DEBUG
1153 /* We skip this power-on-default verification sequence on
1154 * non-DEBUG, as dirtying the x87 control word may slow down
1155 * xsave/xrstor and affect energy use.
1156 */
1157 unsigned short control, control2;
1158 fnstcw(&control);
1159 control2 = control;
1160 control &= ~(FPC_PC | FPC_RC); /* Clear precision & rounding control */
1161 control |= (FPC_PC_64 | /* Set precision */
1162 FPC_RC_RN | /* round-to-nearest */
1163 FPC_ZE | /* Suppress zero-divide */
1164 FPC_OE | /* and overflow */
1165 FPC_UE | /* underflow */
1166 FPC_IE | /* Allow NaNQs and +-INF */
1167 FPC_DE | /* Allow denorms as operands */
1168 FPC_PE); /* No trap for precision loss */
1169 assert(control == control2);
1170 fldcw(control);
1171 #endif
1172 /* Initialize SSE/SSE2 */
1173 __builtin_ia32_ldmxcsr(0x1f80);
1174 if (fpu_YMM_capable) {
1175 vzeroall();
1176 } else {
1177 xmmzeroall();
1178 }
1179 ml_set_interrupts_enabled(istate);
1180 }
1181
1182 /*
1183 * Coprocessor not present.
1184 */
1185
1186 uint64_t x86_isr_fp_simd_use;
1187
1188 void
1189 fpnoextflt(void)
1190 {
1191 boolean_t intr;
1192 thread_t thr_act;
1193 pcb_t pcb;
1194 struct x86_fx_thread_state *ifps = 0;
1195 xstate_t xstate = current_xstate();
1196
1197 thr_act = current_thread();
1198 pcb = THREAD_TO_PCB(thr_act);
1199
1200 if (pcb->ifps == 0 && !get_interrupt_level()) {
1201 ifps = fp_state_alloc(xstate);
1202 __nochk_bcopy((char *)&initial_fp_state, (char *)ifps,
1203 fp_state_size[xstate]);
1204 if (!thread_is_64bit_addr(thr_act)) {
1205 ifps->fp_save_layout = fpu_YMM_capable ? XSAVE32 : FXSAVE32;
1206 } else {
1207 ifps->fp_save_layout = fpu_YMM_capable ? XSAVE64 : FXSAVE64;
1208 }
1209 ifps->fp_valid = TRUE;
1210 }
1211 intr = ml_set_interrupts_enabled(FALSE);
1212
1213 clear_ts(); /* Enable FPU use */
1214
1215 if (__improbable(get_interrupt_level())) {
1216 /* Track number of #DNA traps at interrupt context,
1217 * which is likely suboptimal. Racy, but good enough.
1218 */
1219 x86_isr_fp_simd_use++;
1220 /*
1221 * Save current FP/SIMD context if valid
1222 * Initialize live FP/SIMD registers
1223 */
1224 if (pcb->ifps) {
1225 fp_save(thr_act);
1226 }
1227 fpinit();
1228 } else {
1229 if (pcb->ifps == 0) {
1230 pcb->ifps = ifps;
1231 pcb->xstate = xstate;
1232 ifps = 0;
1233 }
1234 /*
1235 * Load this thread`s state into coprocessor live context.
1236 */
1237 fp_load(thr_act);
1238 }
1239 (void)ml_set_interrupts_enabled(intr);
1240
1241 if (ifps) {
1242 fp_state_free(ifps, xstate);
1243 }
1244 }
1245
1246 /*
1247 * FPU overran end of segment.
1248 * Re-initialize FPU. Floating point state is not valid.
1249 */
1250
1251 void
1252 fpextovrflt(void)
1253 {
1254 thread_t thr_act = current_thread();
1255 pcb_t pcb;
1256 struct x86_fx_thread_state *ifps;
1257 boolean_t intr;
1258 xstate_t xstate = current_xstate();
1259
1260 intr = ml_set_interrupts_enabled(FALSE);
1261
1262 if (get_interrupt_level()) {
1263 panic("FPU segment overrun exception at interrupt context\n");
1264 }
1265 if (current_task() == kernel_task) {
1266 panic("FPU segment overrun exception in kernel thread context\n");
1267 }
1268
1269 /*
1270 * This is a non-recoverable error.
1271 * Invalidate the thread`s FPU state.
1272 */
1273 pcb = THREAD_TO_PCB(thr_act);
1274 simple_lock(&pcb->lock, LCK_GRP_NULL);
1275 ifps = pcb->ifps;
1276 pcb->ifps = 0;
1277 simple_unlock(&pcb->lock);
1278
1279 /*
1280 * Re-initialize the FPU.
1281 */
1282 clear_ts();
1283 fninit();
1284
1285 /*
1286 * And disable access.
1287 */
1288 clear_fpu();
1289
1290 (void)ml_set_interrupts_enabled(intr);
1291
1292 if (ifps) {
1293 fp_state_free(ifps, xstate);
1294 }
1295 }
1296
1297 extern void fpxlog(int, uint32_t, uint32_t, uint32_t);
1298
1299 /*
1300 * FPU error. Called by AST.
1301 */
1302
1303 void
1304 fpexterrflt(void)
1305 {
1306 thread_t thr_act = current_thread();
1307 struct x86_fx_thread_state *ifps = thr_act->machine.ifps;
1308 boolean_t intr;
1309
1310 intr = ml_set_interrupts_enabled(FALSE);
1311
1312 if (get_interrupt_level()) {
1313 panic("FPU error exception at interrupt context\n");
1314 }
1315 if (current_task() == kernel_task) {
1316 panic("FPU error exception in kernel thread context\n");
1317 }
1318
1319 /*
1320 * Save the FPU state and turn off the FPU.
1321 */
1322 fp_save(thr_act);
1323
1324 (void)ml_set_interrupts_enabled(intr);
1325
1326 const uint32_t mask = ifps->fx_control &
1327 (FPC_IM | FPC_DM | FPC_ZM | FPC_OM | FPC_UE | FPC_PE);
1328 const uint32_t xcpt = ~mask & (ifps->fx_status &
1329 (FPS_IE | FPS_DE | FPS_ZE | FPS_OE | FPS_UE | FPS_PE));
1330 fpxlog(EXC_I386_EXTERR, ifps->fx_status, ifps->fx_control, xcpt);
1331 }
1332
1333 /*
1334 * Save FPU state.
1335 *
1336 * Locking not needed:
1337 * . if called from fpu_get_state, pcb already locked.
1338 * . if called from fpnoextflt or fp_intr, we are single-cpu
1339 * . otherwise, thread is running.
1340 * N.B.: Must be called with interrupts disabled
1341 */
1342
1343 void
1344 fp_save(
1345 thread_t thr_act)
1346 {
1347 pcb_t pcb = THREAD_TO_PCB(thr_act);
1348 struct x86_fx_thread_state *ifps = pcb->ifps;
1349
1350 assert(ifps != 0);
1351 if (ifps != 0 && !ifps->fp_valid) {
1352 assert((get_cr0() & CR0_TS) == 0);
1353 /* registers are in FPU */
1354 ifps->fp_valid = TRUE;
1355 fpu_store_registers(ifps, thread_is_64bit_addr(thr_act));
1356 }
1357 }
1358
1359 /*
1360 * Restore FPU state from PCB.
1361 *
1362 * Locking not needed; always called on the current thread.
1363 */
1364
1365 void
1366 fp_load(
1367 thread_t thr_act)
1368 {
1369 pcb_t pcb = THREAD_TO_PCB(thr_act);
1370 struct x86_fx_thread_state *ifps = pcb->ifps;
1371
1372 assert(ifps);
1373 #if DEBUG
1374 if (ifps->fp_valid != FALSE && ifps->fp_valid != TRUE) {
1375 panic("fp_load() invalid fp_valid: %u, fp_save_layout: %u\n",
1376 ifps->fp_valid, ifps->fp_save_layout);
1377 }
1378 #endif
1379
1380 if (ifps->fp_valid == FALSE) {
1381 fpinit();
1382 } else {
1383 fpu_load_registers(ifps);
1384 }
1385 ifps->fp_valid = FALSE; /* in FPU */
1386 }
1387
1388 /*
1389 * SSE arithmetic exception handling code.
1390 * Basically the same as the x87 exception handler with a different subtype
1391 */
1392
1393 void
1394 fpSSEexterrflt(void)
1395 {
1396 thread_t thr_act = current_thread();
1397 struct x86_fx_thread_state *ifps = thr_act->machine.ifps;
1398 boolean_t intr;
1399
1400 intr = ml_set_interrupts_enabled(FALSE);
1401
1402 if (get_interrupt_level()) {
1403 panic("SSE exception at interrupt context\n");
1404 }
1405 if (current_task() == kernel_task) {
1406 panic("SSE exception in kernel thread context\n");
1407 }
1408
1409 /*
1410 * Save the FPU state and turn off the FPU.
1411 */
1412 fp_save(thr_act);
1413
1414 (void)ml_set_interrupts_enabled(intr);
1415 /*
1416 * Raise FPU exception.
1417 * Locking not needed on pcb->ifps,
1418 * since thread is running.
1419 */
1420 const uint32_t mask = (ifps->fx_MXCSR >> 7) &
1421 (FPC_IM | FPC_DM | FPC_ZM | FPC_OM | FPC_UE | FPC_PE);
1422 const uint32_t xcpt = ~mask & (ifps->fx_MXCSR &
1423 (FPS_IE | FPS_DE | FPS_ZE | FPS_OE | FPS_UE | FPS_PE));
1424 fpxlog(EXC_I386_SSEEXTERR, ifps->fx_MXCSR, ifps->fx_MXCSR, xcpt);
1425 }
1426
1427
1428 /*
1429 * If a thread is using an AVX-sized savearea:
1430 * - allocate a new AVX512-sized area,
1431 * - copy the 256-bit state into the 512-bit area,
1432 * - deallocate the smaller area
1433 * ASSUMES: thread is the current thread.
1434 */
1435 static void
1436 fpu_savearea_promote_avx512(thread_t thread)
1437 {
1438 struct x86_avx_thread_state *ifps = NULL;
1439 struct x86_avx512_thread_state *ifps512 = NULL;
1440 pcb_t pcb = THREAD_TO_PCB(thread);
1441 boolean_t do_avx512_alloc = FALSE;
1442 boolean_t intr;
1443
1444 assert(thread == current_thread());
1445
1446 DBG("fpu_savearea_promote_avx512(%p)\n", thread);
1447
1448 simple_lock(&pcb->lock, LCK_GRP_NULL);
1449
1450 ifps = pcb->ifps;
1451 if (ifps == NULL) {
1452 pcb->xstate = AVX512;
1453 simple_unlock(&pcb->lock);
1454 /*
1455 * Now that the PCB xstate has been promoted, set XCR0 so
1456 * that we don't re-trip #UD on the next AVX-512 instruction.
1457 *
1458 * Since this branch is taken when the first FP instruction
1459 * attempted by this thread is an AVX-512 instruction, we
1460 * call fpnoextflt() to allocate an appropriately-sized
1461 * AVX-512 save-area, thereby avoiding the overhead of another
1462 * fault that would be triggered immediately on return.
1463 */
1464 intr = ml_set_interrupts_enabled(FALSE);
1465 xsetbv(0, AVX512_XMASK);
1466 current_cpu_datap()->cpu_xstate = AVX512;
1467 (void)ml_set_interrupts_enabled(intr);
1468
1469 fpnoextflt();
1470 return;
1471 }
1472
1473 if (pcb->xstate != AVX512) {
1474 do_avx512_alloc = TRUE;
1475 }
1476
1477 simple_unlock(&pcb->lock);
1478
1479 if (do_avx512_alloc == TRUE) {
1480 ifps512 = fp_state_alloc(AVX512);
1481 }
1482
1483 simple_lock(&pcb->lock, LCK_GRP_NULL);
1484
1485 intr = ml_set_interrupts_enabled(FALSE);
1486
1487 clear_ts();
1488 fp_save(thread);
1489 clear_fpu();
1490
1491 xsetbv(0, AVX512_XMASK);
1492 current_cpu_datap()->cpu_xstate = AVX512;
1493 (void)ml_set_interrupts_enabled(intr);
1494
1495 assert(ifps->fp.fp_valid);
1496
1497 /* Allocate an AVX512 savearea and copy AVX state into it */
1498 if (pcb->xstate != AVX512) {
1499 __nochk_bcopy(ifps, ifps512, fp_state_size[AVX]);
1500 pcb->ifps = ifps512;
1501 pcb->xstate = AVX512;
1502 ifps512 = NULL;
1503 } else {
1504 ifps = NULL;
1505 }
1506 /* The PCB lock is redundant in some scenarios given the higher level
1507 * thread mutex, but its pre-emption disablement is relied upon here
1508 */
1509 simple_unlock(&pcb->lock);
1510
1511 if (ifps) {
1512 fp_state_free(ifps, AVX);
1513 }
1514 if (ifps512) {
1515 fp_state_free(ifps, AVX512);
1516 }
1517 }
1518
1519 /*
1520 * Upgrade the calling thread to AVX512.
1521 */
1522 boolean_t
1523 fpu_thread_promote_avx512(thread_t thread)
1524 {
1525 task_t task = current_task();
1526
1527 if (thread != current_thread()) {
1528 return FALSE;
1529 }
1530 if (!ml_fpu_avx512_enabled()) {
1531 return FALSE;
1532 }
1533
1534 fpu_savearea_promote_avx512(thread);
1535
1536 /* Racy but the task's xstate is only a hint */
1537 task->xstate = AVX512;
1538
1539 return TRUE;
1540 }
1541
1542
1543 /*
1544 * Called from user_trap() when an invalid opcode fault is taken.
1545 * If the user is attempting an AVX512 instruction on a machine
1546 * that supports this, we switch the calling thread to use
1547 * a larger savearea, set its XCR0 bit mask to enable AVX512 and
1548 * return to user_trap() with a 0 return value.
1549 * Otherwise, simply return a nonzero value.
1550 */
1551
1552 #define MAX_X86_INSN_LENGTH (15)
1553 int
1554 fpUDflt(user_addr_t rip)
1555 {
1556 uint8_t instruction_prefix;
1557 boolean_t is_AVX512_instruction = FALSE;
1558 user_addr_t original_rip = rip;
1559 do {
1560 /* TODO: as an optimisation, copy up to the lesser of the
1561 * next page boundary or maximal prefix length in one pass
1562 * rather than issue multiple copyins
1563 */
1564 if (copyin(rip, (char *) &instruction_prefix, 1)) {
1565 return 1;
1566 }
1567 DBG("fpUDflt(0x%016llx) prefix: 0x%x\n",
1568 rip, instruction_prefix);
1569 /* TODO: determine more specifically which prefixes
1570 * are sane possibilities for AVX512 insns
1571 */
1572 switch (instruction_prefix) {
1573 case 0x2E: /* CS segment override */
1574 case 0x36: /* SS segment override */
1575 case 0x3E: /* DS segment override */
1576 case 0x26: /* ES segment override */
1577 case 0x64: /* FS segment override */
1578 case 0x65: /* GS segment override */
1579 case 0x66: /* Operand-size override */
1580 case 0x67: /* address-size override */
1581 /* Skip optional prefixes */
1582 rip++;
1583 if ((rip - original_rip) > MAX_X86_INSN_LENGTH) {
1584 return 1;
1585 }
1586 break;
1587 case 0x62: /* EVEX */
1588 case 0xC5: /* VEX 2-byte */
1589 case 0xC4: /* VEX 3-byte */
1590 is_AVX512_instruction = TRUE;
1591 break;
1592 default:
1593 return 1;
1594 }
1595 } while (!is_AVX512_instruction);
1596
1597 /* Here if we detect attempted execution of an AVX512 instruction */
1598
1599 /*
1600 * Fail if this machine doesn't support AVX512
1601 */
1602 if (fpu_capability != AVX512) {
1603 return 1;
1604 }
1605
1606 assert(xgetbv(XCR0) == AVX_XMASK);
1607
1608 DBG("fpUDflt() switching xstate to AVX512\n");
1609 (void) fpu_thread_promote_avx512(current_thread());
1610
1611 return 0;
1612 }
1613
1614 void
1615 fp_setvalid(boolean_t value)
1616 {
1617 thread_t thr_act = current_thread();
1618 struct x86_fx_thread_state *ifps = thr_act->machine.ifps;
1619
1620 if (ifps) {
1621 ifps->fp_valid = value;
1622
1623 if (value == TRUE) {
1624 boolean_t istate = ml_set_interrupts_enabled(FALSE);
1625 clear_fpu();
1626 ml_set_interrupts_enabled(istate);
1627 }
1628 }
1629 }
1630
1631 boolean_t
1632 ml_fpu_avx_enabled(void)
1633 {
1634 return fpu_capability >= AVX;
1635 }
1636
1637 boolean_t
1638 ml_fpu_avx512_enabled(void)
1639 {
1640 return fpu_capability == AVX512;
1641 }
1642
1643 static xstate_t
1644 task_xstate(task_t task)
1645 {
1646 if (task == TASK_NULL) {
1647 return fpu_default;
1648 } else {
1649 return task->xstate;
1650 }
1651 }
1652
1653 static xstate_t
1654 thread_xstate(thread_t thread)
1655 {
1656 xstate_t xs = THREAD_TO_PCB(thread)->xstate;
1657 if (xs == UNDEFINED) {
1658 return task_xstate(thread->task);
1659 } else {
1660 return xs;
1661 }
1662 }
1663
1664 xstate_t
1665 current_xstate(void)
1666 {
1667 return thread_xstate(current_thread());
1668 }
1669
1670 /*
1671 * Called when exec'ing between bitnesses.
1672 * If valid FPU state exists, adjust the layout.
1673 */
1674 void
1675 fpu_switch_addrmode(thread_t thread, boolean_t is_64bit)
1676 {
1677 struct x86_fx_thread_state *ifps = thread->machine.ifps;
1678 mp_disable_preemption();
1679
1680 if (ifps && ifps->fp_valid) {
1681 if (thread_xstate(thread) == FP) {
1682 ifps->fp_save_layout = is_64bit ? FXSAVE64 : FXSAVE32;
1683 } else {
1684 ifps->fp_save_layout = is_64bit ? XSAVE64 : XSAVE32;
1685 }
1686 }
1687 mp_enable_preemption();
1688 }
1689
1690 static inline uint32_t
1691 fpsimd_pop(uintptr_t ins, int sz)
1692 {
1693 uint32_t rv = 0;
1694
1695
1696 while (sz >= 16) {
1697 uint32_t rv1, rv2;
1698 uint64_t *ins64 = (uint64_t *) ins;
1699 uint64_t *ins642 = (uint64_t *) (ins + 8);
1700 rv1 = __builtin_popcountll(*ins64);
1701 rv2 = __builtin_popcountll(*ins642);
1702 rv += rv1 + rv2;
1703 sz -= 16;
1704 ins += 16;
1705 }
1706
1707 while (sz >= 4) {
1708 uint32_t *ins32 = (uint32_t *) ins;
1709 rv += __builtin_popcount(*ins32);
1710 sz -= 4;
1711 ins += 4;
1712 }
1713
1714 while (sz > 0) {
1715 char *ins8 = (char *)ins;
1716 rv += __builtin_popcount(*ins8);
1717 sz--;
1718 ins++;
1719 }
1720 return rv;
1721 }
1722
1723 uint32_t
1724 thread_fpsimd_hash(thread_t ft)
1725 {
1726 if (fpsimd_fault_popc == 0) {
1727 return 0;
1728 }
1729
1730 uint32_t prv = 0;
1731 boolean_t istate = ml_set_interrupts_enabled(FALSE);
1732 struct x86_fx_thread_state *pifps = THREAD_TO_PCB(ft)->ifps;
1733
1734 if (pifps) {
1735 if (pifps->fp_valid) {
1736 prv = fpsimd_pop((uintptr_t) &pifps->fx_XMM_reg[0][0],
1737 sizeof(pifps->fx_XMM_reg));
1738 } else {
1739 uintptr_t cr0 = get_cr0();
1740 clear_ts();
1741 fp_save(ft);
1742 prv = fpsimd_pop((uintptr_t) &pifps->fx_XMM_reg[0][0],
1743 sizeof(pifps->fx_XMM_reg));
1744 pifps->fp_valid = FALSE;
1745 if (cr0 & CR0_TS) {
1746 set_cr0(cr0);
1747 }
1748 }
1749 }
1750 ml_set_interrupts_enabled(istate);
1751 return prv;
1752 }