1 /*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21 /*
22 * Copyright (c) 1992, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright 2021 Joyent, Inc.
24 * Copyright 2021 RackTop Systems, Inc.
25 * Copyright 2026 Oxide Computer Company
26 * Copyright 2025 Edgecast Cloud LLC.
27 */
28
29 /* Copyright (c) 1990, 1991 UNIX System Laboratories, Inc. */
30 /* Copyright (c) 1984, 1986, 1987, 1988, 1989, 1990 AT&T */
31 /* All Rights Reserved */
32
33 /* Copyright (c) 1987, 1988 Microsoft Corporation */
34 /* All Rights Reserved */
35
36 /*
37 * Copyright (c) 2009, Intel Corporation.
38 * All rights reserved.
39 */
40
41 #include <sys/types.h>
42 #include <sys/param.h>
43 #include <sys/signal.h>
44 #include <sys/regset.h>
45 #include <sys/privregs.h>
46 #include <sys/psw.h>
47 #include <sys/trap.h>
48 #include <sys/fault.h>
49 #include <sys/systm.h>
50 #include <sys/user.h>
51 #include <sys/file.h>
52 #include <sys/proc.h>
53 #include <sys/pcb.h>
54 #include <sys/lwp.h>
55 #include <sys/cpuvar.h>
56 #include <sys/thread.h>
57 #include <sys/disp.h>
58 #include <sys/fp.h>
59 #include <sys/siginfo.h>
60 #include <sys/archsystm.h>
61 #include <sys/kmem.h>
62 #include <sys/debug.h>
63 #include <sys/x86_archext.h>
64 #include <sys/sysmacros.h>
65 #include <sys/cmn_err.h>
66 #include <sys/kfpu.h>
67 #include <sys/stdbool.h>
68 #include <sys/stdalign.h>
69 #include <sys/procfs_isa.h>
70 #include <sys/sunddi.h>
71
72 /*
73 * FPU Management Overview
74 * -----------------------
75 *
76 * The x86 FPU has evolved substantially since its days as the x87 coprocessor;
77 * however, many aspects of its life as a coprocessor are still around in x86.
78 *
79 * Today, when we refer to the 'FPU', we don't just mean the original x87 FPU.
80 * While that state still exists, there is much more that is covered by the FPU.
81 * Today, this includes not just traditional FPU state, but also supervisor only
82 * state. The following state is currently managed and covered logically by the
83 * idea of the FPU registers and more generally is called the Extended Processor
84 * States:
85 *
86 * o Traditional x87 FPU
87 * o Vector Registers (%xmm, %ymm, %zmm)
88 * o Memory Protection Extensions (MPX) Bounds Registers
89 * o Protected Key Rights Registers (PKRU)
90 * o Processor Trace data
91 * o Control-Flow Enforcement state
92 * o Hardware Duty Cycle
93 * o Hardware P-states
94 *
95 * The rest of this covers how the FPU is managed and controlled, how state is
96 * saved and restored between threads, interactions with hypervisors, and other
97 * information exported to userland through aux vectors. A lot of background
98 * information is here to synthesize major parts of the Intel SDM, but
99 * unfortunately, it is not a replacement for reading it.
100 *
101 * FPU Control Registers
102 * ---------------------
103 *
104 * Because the x87 FPU began its life as a co-processor and the FPU was
105 * optional there are several bits that show up in %cr0 that we have to
106 * manipulate when dealing with the FPU. These are:
107 *
108 * o CR0.ET The 'extension type' bit. This was used originally to indicate
109 * that the FPU co-processor was present. Now it is forced on for
110 * compatibility. This is often used to verify whether or not the
111 * FPU is present.
112 *
113 * o CR0.NE The 'native error' bit. Used to indicate that native error
114 * mode should be enabled. This indicates that we should take traps
115 * on FPU errors. The OS enables this early in boot.
116 *
117 * o CR0.MP The 'Monitor Coprocessor' bit. Used to control whether or not
118 * wait/fwait instructions generate a #NM if CR0.TS is set.
119 *
120 * o CR0.EM The 'Emulation' bit. This is used to cause floating point
121 * operations (x87 through SSE4) to trap with a #UD so they can be
122 * emulated. The system never sets this bit, but makes sure it is
123 * clear on processor start up.
124 *
125 * o CR0.TS The 'Task Switched' bit. When this is turned on, a floating
126 * point operation will generate a #NM. An fwait will as well,
127 * depending on the value in CR0.MP.
128 *
129 * Our general policy is that CR0.ET, CR0.NE, and CR0.MP are always set by
130 * the system. Similarly CR0.EM is always unset by the system. CR0.TS has a more
131 * complicated role. Historically it has been used to allow running systems to
132 * restore the FPU registers lazily. This will be discussed in greater depth
133 * later on.
134 *
135 * %cr4 is also used as part of the FPU control. Specifically we need to worry
136 * about the following bits in the system:
137 *
138 * o CR4.OSFXSR This bit is used to indicate that the OS understands and
139 * supports the execution of the fxsave and fxrstor
140 * instructions. This bit is required to be set to enable
141 * the use of the SSE->SSE4 instructions.
142 *
143 * o CR4.OSXMMEXCPT This bit is used to indicate that the OS can understand
144 * and take a SIMD floating point exception (#XM). This bit
145 * is always enabled by the system.
146 *
147 * o CR4.OSXSAVE This bit is used to indicate that the OS understands and
148 * supports the execution of the xsave and xrstor family of
149 * instructions. This bit is required to use any of the AVX
150 * and newer feature sets.
151 *
152 * Because all supported processors are 64-bit, they'll always support the XMM
153 * extensions and we will enable both CR4.OXFXSR and CR4.OSXMMEXCPT in boot.
154 * CR4.OSXSAVE will be enabled and used whenever xsave is reported in cpuid.
155 *
156 * %xcr0 is used to manage the behavior of the xsave feature set and is only
157 * present on the system if xsave is supported. %xcr0 is read and written to
158 * through by the xgetbv and xsetbv instructions. This register is present
159 * whenever the xsave feature set is supported. Each bit in %xcr0 refers to a
160 * different component of the xsave state and controls whether or not that
161 * information is saved and restored. For newer feature sets like AVX and MPX,
162 * it also controls whether or not the corresponding instructions can be
163 * executed (much like CR0.OSFXSR does for the SSE feature sets).
164 *
165 * Everything in %xcr0 is around features available to users. There is also the
166 * IA32_XSS MSR which is used to control supervisor-only features that are still
167 * part of the xsave state. Bits that can be set in %xcr0 are reserved in
168 * IA32_XSS and vice versa. This is an important property that is particularly
169 * relevant to how the xsave instructions operate.
170 *
171 * Save Mechanisms
172 * ---------------
173 *
174 * When switching between running threads the FPU state needs to be saved and
175 * restored by the OS. If this state was not saved, users would rightfully
176 * complain about corrupt state. There are three mechanisms that exist on the
177 * processor for saving and restoring these state images:
178 *
179 * o fsave
180 * o fxsave
181 * o xsave
182 *
183 * fsave saves and restores only the x87 FPU and is the oldest of these
184 * mechanisms. This mechanism is never used in the kernel today because we are
185 * always running on systems that support fxsave.
186 *
187 * The fxsave and fxrstor mechanism allows the x87 FPU and the SSE register
188 * state to be saved and restored to and from a struct fxsave_state. This is the
189 * default mechanism that is used to save and restore the FPU on amd64. An
190 * important aspect of fxsave that was different from the original i386 fsave
191 * mechanism is that the restoring of FPU state with pending exceptions will not
192 * generate an exception, it will be deferred to the next use of the FPU.
193 *
194 * The final and by far the most complex mechanism is that of the xsave set.
195 * xsave allows for saving and restoring all of the traditional x86 pieces (x87
196 * and SSE), while allowing for extensions that will save the %ymm, %zmm, etc.
197 * registers.
198 *
199 * Data is saved and restored into and out of a struct xsave_state. The first
200 * part of the struct xsave_state is equivalent to the struct fxsave_state.
201 * After that, there is a header which is used to describe the remaining
202 * portions of the state. The header is a 64-byte value of which the first two
203 * uint64_t values are defined and the rest are reserved and must be zero. The
204 * first uint64_t is the xstate_bv member. This describes which values in the
205 * xsave_state are actually valid and present. This is updated on a save and
206 * used on restore. The second member is the xcomp_bv member. Its last bit
207 * determines whether or not a compressed version of the structure is used.
208 *
209 * When the uncompressed structure is used (currently the only format we
210 * support), then each state component is at a fixed offset in the structure,
211 * even if it is not being used. For example, if you only saved the AVX related
212 * state, but did not save the MPX related state, the offset would not change
213 * for any component. With the compressed format, components that aren't used
214 * are all elided (though the x87 and SSE state are always there).
215 *
216 * Unlike fxsave which saves all state, the xsave family does not always save
217 * and restore all the state that could be covered by the xsave_state. The
218 * instructions all take an argument which is a mask of what to consider. This
219 * is the same mask that will be used in the xstate_bv vector and it is also the
220 * same values that are present in %xcr0 and IA32_XSS. Though IA32_XSS is only
221 * considered with the xsaves and xrstors instructions.
222 *
223 * When a save or restore is requested, a bitwise and is performed between the
224 * requested bits and those that have been enabled in %xcr0. Only the bits that
225 * match that are then saved or restored. Others will be silently ignored by
226 * the processor. This idea is used often in the OS. We will always request that
227 * we save and restore all of the state, but only those portions that are
228 * actually enabled in %xcr0 will be touched.
229 *
230 * If a feature has been asked to be restored that is not set in the xstate_bv
231 * feature vector of the save state, then it will be set to its initial state by
232 * the processor (usually zeros). Also, when asked to save state, the processor
233 * may not write out data that is in its initial state as an optimization. This
234 * optimization only applies to saving data and not to restoring data.
235 *
236 * There are a few different variants of the xsave and xrstor instruction. They
237 * are:
238 *
239 * o xsave This is the original save instruction. It will save all of the
240 * requested data in the xsave state structure. It only saves data
241 * in the uncompressed (xcomp_bv[63] is zero) format. It may be
242 * executed at all privilege levels.
243 *
244 * o xrstor This is the original restore instruction. It will restore all of
245 * the requested data. The xrstor function can handle both the
246 * compressed and uncompressed formats. It may be executed at all
247 * privilege levels.
248 *
249 * o xsaveopt This is a variant of the xsave instruction that employs
250 * optimizations to try and only write out state that has been
251 * modified since the last time an xrstor instruction was called.
252 * The processor tracks a tuple of information about the last
253 * xrstor and tries to ensure that the same buffer is being used
254 * when this optimization is being used. However, because of the
255 * way that it tracks the xrstor buffer based on the address of it,
256 * it is not suitable for use if that buffer can be easily reused.
257 * The most common case is trying to save data to the stack in
258 * rtld. It may be executed at all privilege levels.
259 *
260 * o xsavec This is a variant of the xsave instruction that writes out the
261 * compressed form of the xsave_state. Otherwise it behaves as
262 * xsave. It may be executed at all privilege levels.
263 *
264 * o xsaves This is a variant of the xsave instruction. It is similar to
265 * xsavec in that it always writes the compressed form of the
266 * buffer. Unlike all the other forms, this instruction looks at
267 * both the user (%xcr0) and supervisor (IA32_XSS MSR) to determine
268 * what to save and restore. xsaves also implements the same
269 * optimization that xsaveopt does around modified pieces. User
270 * land may not execute the instruction.
271 *
272 * o xrstors This is a variant of the xrstor instruction. Similar to xsaves
273 * it can save and restore both the user and privileged states.
274 * Unlike xrstor it can only operate on the compressed form.
275 * User land may not execute the instruction.
276 *
277 * Based on all of these, the kernel has a precedence for what it will use.
278 * Basically, xsaves (not supported) is preferred to xsaveopt, which is
279 * preferred to xsave. A similar scheme is used when informing rtld (more later)
280 * about what it should use. xsavec is preferred to xsave. xsaveopt is not
281 * recommended due to the modified optimization not being appropriate for this
282 * use.
283 *
284 * Finally, there is one last gotcha with the xsave state. Importantly some AMD
285 * processors did not always save and restore some of the FPU exception state in
286 * some cases like Intel did. In those cases the OS will make up for this fact
287 * itself.
288 *
289 * FPU Initialization
290 * ------------------
291 *
292 * One difference with the FPU registers is that not all threads have FPU state,
293 * only those that have an lwp. Generally this means kernel threads, which all
294 * share p0 and its lwp, do not have FPU state. Though there are definitely
295 * exceptions such as kcfpoold. In the rest of this discussion we'll use thread
296 * and lwp interchangeably, just think of thread meaning a thread that has a
297 * lwp.
298 *
299 * Each lwp has its FPU state allocated in its pcb (process control block). The
300 * actual storage comes from the fpsave_cachep kmem cache. This cache is sized
301 * dynamically at start up based on the save mechanism that we're using and the
302 * amount of memory required for it. This is dynamic because the xsave_state
303 * size varies based on the supported feature set.
304 *
305 * The hardware side of the FPU is initialized early in boot before we mount the
306 * root file system. This is effectively done in fpu_probe(). This is where we
307 * make the final decision about what the save and restore mechanisms we should
308 * use are, create the fpsave_cachep kmem cache, and initialize a number of
309 * function pointers that use save and restoring logic.
310 *
311 * The thread/lwp side is a a little more involved. There are two different
312 * things that we need to concern ourselves with. The first is how the FPU
313 * resources are allocated and the second is how the FPU state is initialized
314 * for a given lwp.
315 *
316 * We allocate the FPU save state from our kmem cache as part of lwp_fp_init().
317 * This is always called unconditionally by the system as part of creating an
318 * LWP.
319 *
320 * There are three different initialization paths that we deal with. The first
321 * is when we are executing a new process. As part of exec all of the register
322 * state is reset. The exec case is particularly important because init is born
323 * like Athena, sprouting from the head of the kernel, without any true parent
324 * to fork from. The second is used whenever we fork or create a new lwp. The
325 * third is to deal with special lwps like the agent lwp.
326 *
327 * During exec, we will call fp_exec() which will initialize and set up the FPU
328 * state for the process. That will fill in the initial state for the FPU and
329 * also set that state in the FPU itself. As part of fp_exec() we also install a
330 * thread context operations vector that takes care of dealing with the saving
331 * and restoring of the FPU. These context handlers will also be called whenever
332 * an lwp is created or forked. In those cases, to initialize the FPU we will
333 * call fp_new_lwp(). Like fp_exec(), fp_new_lwp() will install a context
334 * operations vector for the new thread.
335 *
336 * Next we'll end up in the context operation fp_new_lwp(). This saves the
337 * current thread's state, initializes the new thread's state, and copies over
338 * the relevant parts of the originating thread's state. It's as this point that
339 * we also install the FPU context operations into the new thread, which ensures
340 * that all future threads that are descendants of the current one get the
341 * thread context operations (unless they call exec).
342 *
343 * The spawn(2) system call behind posix_spawn(3C) leans on this exec path too.
344 * A spawned child is created as a bare kernel thread that does not go through
345 * fork or fp_new_lwp(), so it inherits no FPU register state and no context
346 * operations from the spawning thread. Like init, it has no parent to fork from
347 * as far as the FPU is concerned. It runs in the kernel until it execs its
348 * target, at which point fp_exec() installs the context operations and the
349 * initial state. There is nothing to inherit; any state copied from the
350 * spawning thread would only be discarded by the exec that always follows.
351 *
352 * To deal with some things like the agent lwp, we double check the state of the
353 * FPU in sys_rtt_common() to make sure that it has been enabled before
354 * returning to userland. In general, this path should be rare, but it's useful
355 * for the odd lwp here and there.
356 *
357 * The FPU state will remain valid most of the time. There are times that
358 * the state will be rewritten. For example in restorecontext, due to /proc, or
359 * the lwp calls exec(). Whether the context is being freed or we are resetting
360 * the state, we will call fp_free() to disable the FPU and our context.
361 *
362 * Finally, when the lwp is destroyed, it will actually destroy and free the FPU
363 * state by calling fp_lwp_cleanup().
364 *
365 * Kernel FPU Multiplexing
366 * -----------------------
367 *
368 * Just as the kernel has to maintain all of the general purpose registers when
369 * switching between scheduled threads, the same is true of the FPU registers.
370 *
371 * When a thread has FPU state, it also has a set of context operations
372 * installed. These context operations take care of making sure that the FPU is
373 * properly saved and restored during a context switch (fpsave_ctxt and
374 * fprestore_ctxt respectively). This means that the current implementation of
375 * the FPU is 'eager', when a thread is running the CPU will have its FPU state
376 * loaded. While this is always true when executing in userland, there are a few
377 * cases where this is not true in the kernel.
378 *
379 * This was not always the case. Traditionally on x86 a 'lazy' FPU restore was
380 * employed. This meant that the FPU would be saved on a context switch and the
381 * CR0.TS bit would be set. When a thread next tried to use the FPU, it would
382 * then take a #NM trap, at which point we would restore the FPU from the save
383 * area and return to userland. Given the frequency of use of the FPU alone by
384 * libc, there's no point returning to userland just to trap again.
385 *
386 * There are a few cases though where the FPU state may need to be changed for a
387 * thread on its behalf. The most notable cases are in the case of processes
388 * using /proc, restorecontext, forking, etc. In all of these cases the kernel
389 * will force a threads FPU state to be saved into the PCB through the fp_save()
390 * function. Whenever the FPU is saved, then the FPU_VALID flag is set on the
391 * pcb. This indicates that the save state holds currently valid data. As a side
392 * effect of this, CR0.TS will be set. To make sure that all of the state is
393 * updated before returning to userland, in these cases, we set a flag on the
394 * PCB that says the FPU needs to be updated. This will make sure that we take
395 * the slow path out of a system call to fix things up for the thread. Due to
396 * the fact that this is a rather rare case, effectively setting the equivalent
397 * of t_postsys is acceptable.
398 *
399 * CR0.TS will be set after a save occurs and cleared when a restore occurs.
400 * Generally this means it will be cleared immediately by the new thread that is
401 * running in a context switch. However, this isn't the case for kernel threads.
402 * They currently operate with CR0.TS set as no kernel state is restored for
403 * them. This means that using the FPU will cause a #NM and panic.
404 *
405 * The FPU_VALID flag on the currently executing thread's pcb is meant to track
406 * what the value of CR0.TS should be. If it is set, then CR0.TS will be set.
407 * However, because we eagerly restore, the only time that CR0.TS should be set
408 * for a non-kernel thread is during operations where it will be cleared before
409 * returning to userland and importantly, the only data that is in it is its
410 * own.
411 *
412 * Kernel FPU Usage
413 * ----------------
414 *
415 * Traditionally the kernel never used the FPU since it had no need for
416 * floating point operations. However, modern FPU hardware supports a variety
417 * of SIMD extensions which can speed up code such as parity calculations or
418 * encryption.
419 *
420 * To allow the kernel to take advantage of these features, the
421 * kernel_fpu_begin() and kernel_fpu_end() functions should be wrapped
422 * around any usage of the FPU by the kernel to ensure that user-level context
423 * is properly saved/restored, as well as to properly setup the FPU for use by
424 * the kernel. There are a variety of ways this wrapping can be used, as
425 * discussed in this section below.
426 *
427 * When kernel_fpu_begin() and kernel_fpu_end() are used for extended
428 * operations, the kernel_fpu_alloc() function should be used to allocate a
429 * kfpu_state_t structure that is used to save/restore the thread's kernel FPU
430 * state. This structure is not tied to any thread. That is, different threads
431 * can reuse the same kfpu_state_t structure, although not concurrently. A
432 * kfpu_state_t structure is freed by the kernel_fpu_free() function.
433 *
434 * In some cases, the kernel may need to use the FPU for a short operation
435 * without the overhead to manage a kfpu_state_t structure and without
436 * allowing for a context switch off the FPU. In this case the KFPU_NO_STATE
437 * bit can be set in the kernel_fpu_begin() and kernel_fpu_end() flags
438 * parameter. This indicates that there is no kfpu_state_t. When used this way,
439 * kernel preemption should be disabled by the caller (kpreempt_disable) before
440 * calling kernel_fpu_begin(), and re-enabled after calling kernel_fpu_end().
441 * For this usage, it is important to limit the kernel's FPU use to short
442 * operations. The tradeoff between using the FPU without a kfpu_state_t
443 * structure vs. the overhead of allowing a context switch while using the FPU
444 * should be carefully considered on a case by case basis.
445 *
446 * In other cases, kernel threads have an LWP, but never execute in user space.
447 * In this situation, the LWP's pcb_fpu area can be used to save/restore the
448 * kernel's FPU state if the thread is context switched, instead of having to
449 * allocate and manage a kfpu_state_t structure. The KFPU_USE_LWP bit in the
450 * kernel_fpu_begin() and kernel_fpu_end() flags parameter is used to
451 * enable this behavior. It is the caller's responsibility to ensure that this
452 * is only used for a kernel thread which never executes in user space.
453 *
454 * FPU Exceptions
455 * --------------
456 *
457 * Certain operations can cause the kernel to take traps due to FPU activity.
458 * Generally these events will cause a user process to receive a SIGFPU and if
459 * the kernel receives it in kernel context, we will die. Traditionally the #NM
460 * (Device Not Available / No Math) exception generated by CR0.TS would have
461 * caused us to restore the FPU. Now it is a fatal event regardless of whether
462 * or not userland causes it.
463 *
464 * While there are some cases where the kernel uses the FPU, it is up to the
465 * kernel to use the FPU in a way such that it cannot receive a trap or to use
466 * the appropriate trap protection mechanisms.
467 *
468 * Hypervisors
469 * -----------
470 *
471 * When providing support for hypervisors things are a little bit more
472 * complicated because the FPU is not virtualized at all. This means that they
473 * need to save and restore the FPU and %xcr0 across entry and exit to the
474 * guest. To facilitate this, we provide a series of APIs in <sys/hma.h>. These
475 * allow us to use the full native state to make sure that we are always saving
476 * and restoring the full FPU that the host sees, even when the guest is using a
477 * subset.
478 *
479 * One tricky aspect of this is that the guest may be using a subset of %xcr0
480 * and therefore changing our %xcr0 on the fly. It is vital that when we're
481 * saving and restoring the FPU that we always use the largest %xcr0 contents
482 * otherwise we will end up leaving behind data in it.
483 *
484 * ELF PLT Support
485 * ---------------
486 *
487 * rtld has to preserve a subset of the FPU when it is saving and restoring
488 * registers due to the amd64 SYS V ABI. See cmd/sgs/rtld/amd64/boot_elf.s for
489 * more information. As a result, we set up an aux vector that contains
490 * information about what save and restore mechanisms it should be using and
491 * the sizing thereof based on what the kernel supports. This is passed down in
492 * a series of aux vectors SUN_AT_FPTYPE and SUN_AT_FPSIZE. This information is
493 * initialized in fpu_subr.c.
494 *
495 * Signal Handling and the ucontext_t
496 * ----------------------------------
497 *
498 * One of the many gifts that signals give us is the twofold fact that when a
499 * signal occurs, the signal handler is allowed to change the CPU's state
500 * arbitrarily and when the signal handler is done executing, we must restore it
501 * back to the original state. However, the second part of this is that the
502 * signal handler is actually allowed to modify the state that the thread will
503 * return to! To create this facade, the kernel will create a full ucontext_t
504 * state, effectively calling getcontext(2) on the thread's behalf, and a
505 * pointer to that is given to the signal handler (the void * argument for the
506 * sa_sigaction function pointer in sigaction(2)). When libc is done with a
507 * signal, it will call setcontext(2) with that same ucontext_t.
508 *
509 * Now, the ucontext_t has a fixed ABI for both ILP32 and LP64 environments and
510 * it's often declared on the stack itself, with the signal handler spilling all
511 * this state to the stack. The ucontext_t machine portion was broken into the
512 * general purpose and floating point registers. In 64-bit code, the floating
513 * point registers were mostly the same as the results of the fxsave instruction
514 * (i.e. struct fxsave_state). While the 64-bit kernel still uses the equivalent
515 * starting point for information, it is transformed into a different shape to
516 * deal with the history of the 32-bit SYS V ABI.
517 *
518 * While this worked, if you're reading this, you're aware that the x86 FPU and
519 * extended register states didn't stop at the initial 16 128-bit %xmm
520 * registers. Since then we have added 256-bit %ymm, 512-bit %zmm, and the %k
521 * opmask registers. None of these fit inside the standard ucontext_t; however,
522 * they must all be preserved and restored across a signal. While the various
523 * x86 platform-specific ABIs all suggest that these registers are not preserved
524 * across a function call, receiving a signal is not a function call and must be
525 * thought of like a process receiving an interrupt. In other words, this
526 * extended state must be preserved.
527 *
528 * To facilitate this, we have extended the ucontext_t structure with an
529 * additional flag, UC_XSAVE, which indicates that the traditional padding
530 * member, uc_xsave, actually is a pointer to the extended state. While this is
531 * accessible outside of a signal handling context through the combination of
532 * ucontext_alloc(3C) and getcontext_extd(2), our design around saving this
533 * state is focused on signal handling. Signal handling spills all this state to
534 * the stack and if we cannot spill the entire state to the stack then our
535 * inability to deliver the signal results in the process being killed! While
536 * there are separate efforts to ensure that the signal stack sizing that is
537 * used for the minimum and maximum signal sizes are sufficient, we still need
538 * to do our part to minimize the likelihood here.
539 *
540 * In designing this, we make the following observations which have helped us
541 * focus our design:
542 *
543 * o While the start of an xsave area is the traditional 512-byte fxsave XMM
544 * region, we already have that in the fpregs. Thus there is no reason to
545 * duplicate it. This not only saves 512 bytes of additional stack space,
546 * but it also means we don't have to ask which of the version of it to take
547 * if they were to differ.
548 *
549 * o Many applications out there aren't necessarily using the extended vectors
550 * and even when we do make libc and others take advantage of it, it will
551 * behoove us to ensure that they are put back into their initial state
552 * after use. This leads us to expect that in a number of cases, the actual
553 * extended register state will be in its initial state.
554 *
555 * o While the signal handler does allow contents to be modified, we are
556 * starting with making the interface private and thus allowing us to excise
557 * components that are in their initial state.
558 *
559 * o There are similarities to what we want to create with the compressed
560 * xsave format; however, because we don't always have support for the
561 * compressed format, we can't just arbitrarily say let's do a compressed
562 * save to the user stack.
563 *
564 * o Because we are not handing this state directly to and from hardware, we
565 * don't need to meet some of the constraints of the compressed xsave format
566 * around wanting alignment for the initial save or additional components.
567 *
568 * All of the above lead us to our own unique format for this data. When the
569 * UC_XSAVE flag is set in the ucontext_t, the uc_xsave member points to a
570 * uc_xsave_t structure which has a magic version number, a 32-bit length of the
571 * overall structure, and the 64-bit state bit-vector to represent which
572 * components are valid. Following this 8-byte header, each component that is
573 * present in the bit vector is immediately written out in roughly ascending bit
574 * order (the order is determined based on the order of the fpu_xsave_info
575 * array).
576 *
577 * This makes the rough logic that we have here when taking a signal and writing
578 * out this state as:
579 *
580 * 1. Ensure that the FPU is saved and that the contents of the pcb save area
581 * are valid. That is, call fp_save() if the state is not already flagged
582 * with FPU_VALID.
583 *
584 * 2. Copy the bit-vector from the save area and remove the XFEATURE_LEGACY_FP
585 * and XFEATURE_SSE bits as these will be placed in the xsave area.
586 *
587 * 3. Initialize the uc_xsave_t by setting our version field, initializing the
588 * length to the length of the current structure, and then setting the
589 * modified bit vector above.
590 *
591 * 4. Walk each remaining bit of the bit-vector. For each set bit, copy out
592 * its extended state starting at the current length in the header and then
593 * increase the header size by that length.
594 *
595 * 5. Finally write out the final uc_xsave_t structure.
596 *
597 * The above process is also used when someone manually calls getcontext_extd(2)
598 * to get this state. The main difference between the two is which copyout
599 * function we use. This deserves some explanation. Our main starting point for
600 * all the logic here is fpu_signal_copyout(). It takes a copyfunc that allows
601 * the signal handling context to operate with a different copyout than we
602 * normally use in say getcontext_extd(2).
603 *
604 * When we've received a signal, we're at the intersection of several different
605 * gotchas. Normal copyout (or ddi_copyout()) will trigger watchpoints. That is,
606 * the watchpoints effectively set a copyout override function (t_copyops) that
607 * we end up vectoring to rather than a normal copyout. This allows the data to
608 * be modified and for the watchpoint to fire. While this is all well and good
609 * normally, it is problematic if we are trying to handle a signal. The signal
610 * deliver logic, sendsig(), goes through and disables the watchpoint for the
611 * region of the stack that we are copying out to. However, disabling
612 * watchpoints is not sufficient, we also need to use the copyout_noerr
613 * variants.
614 *
615 * These variants also require the use of on_fault() and no_fault() for error
616 * handling. While it is tempting to try and on_fault() the entire
617 * fpu_signal_copyout() operation, that is actually fraught for a few reasons.
618 * The first is that we don't want to disable faults during the entire operation
619 * as if the kernel messes up we will treat that as a user error. That isn't
620 * theoretical and happened during development. The second and perhaps more
621 * important issue is that correctly bounding the on_fault() / no_fault() means
622 * being careful about state. For example, kernel pre-emption is often disabled
623 * during parts of these operations, but it needs to be re-enabled when we're
624 * done. This would require tracking in some volatile variable that this had
625 * been enabled and disabled and tracking that.
626 *
627 * Instead, this is why fpu_signal_copyout() takes a copy out function as an
628 * argument. When we're in signal handling context, the function will use
629 * coypout_noerr() and wrap it in the appropriate on_fault() mechanisms.
630 *
631 * RESTORING STATE
632 *
633 * Copying out our current state is the easier half of this problem. When the
634 * kernel is done with a signal it calls setcontext(2) with the ucontext_t we
635 * assembled for it as described above. setcontext(2) isn't just used for
636 * returning from signals.
637 *
638 * The process for this goes in two steps. The first step is to copy in,
639 * validate, and transform the ucontext_t UC_XSAVE that we created above into an
640 * equivalent xsave format that we can use the appropriate xrstor function on.
641 * This first phase is implemented in fpu_signal_copyin(). Once that is done, we
642 * come back through a second phase that is driven out of restorecontext() and
643 * is implemented in fpu_set_xsave().
644 *
645 * Let's start by discussing the second part of this, which is more
646 * straightforward. In particular, the second phase assumes that all of the
647 * validation and error handling has been done by the first phase. This means
648 * here, we have a buffer that is already the appropriate size
649 * (cpuid_get_xsave_size()) and all we need to do is make sure that we can
650 * replace the actual save state with the current one.
651 *
652 * The only piece of shenanigans we have to do is around the kernel provided
653 * notion of 'status' and 'xstatus', which are cached versions of the x87 and
654 * SSE exception vectors. These are part of the fpregset ABI and therefore we
655 * need to propagate them from the temporary storage that part 1 sets up in the
656 * ignored region of the fxsave data. We use that because it is not persisted by
657 * the CPU, so clobbering it is generally alright.
658 *
659 * Once that is done, we simply note that we need a PCB update to occur to
660 * refresh the FPU state before we return to userland. Given that someone has
661 * called setcontext(2), this was always going to happen because we have to
662 * update segment registers and related, so this isn't so bad. With that, let's
663 * move onto the more nuanced part (1).
664 *
665 * When we're handling a setcontext(2) we have, in userland, a data structure
666 * that should match one we serialized out, though we cannot assume that a user
667 * has not modified it either accidentally or maliciously. Our goal is to set up
668 * the appropriate xsave state that can be passed to the CPU's xrstor. The first
669 * problem we have to deal with is where do we actually put this state?
670 *
671 * While not many programs actually call setcontext(2) of their own volition,
672 * this is going to get hit every time we take a signal. The first thought was
673 * to re-use the existing thread's save area; however, that's a bit challenging
674 * for a few reasons. In particular, we would need to ensure that we don't go
675 * off-CPU for any reason, which we cannot assume with a copyin from a user
676 * address space. In particular, it is trivial for us to hit a case where the
677 * stack has been paged out for some reason, which eschews that path.
678 *
679 * Instead, whenever a thread first calls setcontext(2), generally from signal
680 * context, we will at that time allocate another entry from the 'fpsave_cachep'
681 * kmem cache, giving us a buffer of the appropriate space to handle this. Once
682 * this buffer has been allocated, we leave it assigned to the thread's pcb and
683 * only tear it down when the thread itself finally exits. We reason that a
684 * thread that takes a signal once is either going to have the process exit
685 * shortly thereafter or is much more likely to take a signal again in the
686 * future. Many daemons and other processes set things up so signals are
687 * dispatched via one location, masking signals in other thread, using
688 * sigsuspend(2), signalfd(3C), or something similar.
689 *
690 * With this buffer in hand, we begin our task of reassembling state. Note, all
691 * of this is conditional on UC_XSAVE being set in the uc_flags member of the
692 * ucontext_t. If it is not set, then we assume that there is no extended state
693 * and will use the traditional path of setting the fpregset_t into the system
694 * via setfpregs().
695 *
696 * We first will copyin and validate the uc_xsave_t. In particular, we need to
697 * make sure the version makes sense, that the xsave component bit-vector
698 * doesn't have anything unexpected and more importantly unsupported in it, and
699 * that the addresses we've been given are within the user address space. At
700 * this point we can walk through our table of implemented bits and process
701 * them.
702 *
703 * For most components in here, the processing is straightforward. We continue
704 * walking our cursor and copy data into the kernel and place it in the
705 * appropriate place in our xsave state. If a xsave state component bit-vector
706 * isn't set, then we must ensure that we have the item in the initial state,
707 * which for everything other than the x87/SSE state is the memory being zeroed.
708 *
709 * The most unique case in the copyin state is that of the x87/SSE state. You
710 * might recall that we didn't copy it out explicitly as part of the uc_xsave_t,
711 * but instead have opted to use the single definition in the fpregset_t. Thus
712 * here, we copy it out of the fpregset_t, which the kernel has helpfully
713 * already unified into the 64-bit fxsave version prior to calling us, and
714 * install that into the save area we're building up.
715 *
716 * As part of this, there are two important pieces to be aware of. The first is
717 * that because the fpregset_t has both the status and xstatus members
718 * mentioned earlier, we temporarily copy them to the software-usable ignored
719 * areas of the fxsave state so we can corral this extra state into part (2)
720 * without needing to allocate additional space. The second piece is that when
721 * we're done processing this we explicitly remove the UC_FPU flag that would
722 * tell the kernel to proceed with updating that region. The problem is that
723 * that goes directly into the pcb's save area and not to the intermediate
724 * buffer as it uses the same entry point as /proc, mainly setfpregs().
725 *
726 * We don't do much validation of the actual contents of the registers that are
727 * being set with the exception of ensuring that no reserved bits of the mxcsr
728 * are used. This is not as strict as /proc, but failure here means the process
729 * is likely going to die (returning from setcontext() in a signal handler is
730 * fatal).
731 *
732 * /proc xregs
733 * -----------
734 *
735 * Observability of the state of the extended registers is important for
736 * understanding the system. While on the surface this is similar to signal
737 * handling, it is crucially different in a number of ways:
738 *
739 * o In signal handling, we're trying to conserve every byte of stack that we
740 * can.
741 * o The /proc xregs file will end up in core files, which means that we need
742 * a way of knowing what components are present and not present in it,
743 * because this will vary from CPU to CPU due to the addition of
744 * architectural features. For example, some CPUs support AVX-512, but
745 * others do not.
746 *
747 * o The signal handling structure (uc_xsave_t) is private and we're not
748 * trying to have software modify it, on the other hand, the /proc
749 * interfaces that we support we do want software to be able to interrogate
750 * and manipulate. These need to be something that we can introduce
751 * additional components into and make other changes that still allow it to
752 * work.
753 *
754 * The x86 xregs format is documented in proc(5). The short form is that the
755 * prxregset_hdr_t has a number of information entries, which are of the type
756 * prxregset_info_t. Each of the information headers has a type, size, and
757 * offset which indicate where to find the additional data.
758 *
759 * Each entry is described as one of the entries in the fpu_xsave_info[]. These
760 * items either are a 1:1 correspondence with a xsave related feature (e.g.
761 * there is one entry for each of the three AVX-512 components) or it is
762 * something synthetic that we provide as additional information such as the
763 * PRX_INFO_XCR, which is a way of getting information about the system such as
764 * what is enabled in %xcr0 out there.
765 *
766 * Unlike signal handling, we are given the buffer to place everything that
767 * needs to be written out. This is partially the design of the /proc APIs. That
768 * is, we will always assemble everything into the entire buffer that /proc asks
769 * us to, and then it will use as much or as little of it as is required.
770 * Similarly, when setting things, we don't have to worry about copying in
771 * information in the same way as signal handling does, because /proc takes care
772 * of it and always hands us a full buffer. Sizing that is a little nuanced, but
773 * is all handled in prmachdep.c.
774 *
775 * When someone performs a read of the xregs and thus is asking us for the
776 * current state, there is a little bit of nuance that we need to deal with.
777 * The first, is whether or not the FPU is enabled and the second is if the FPU
778 * is enabled, whether a given component is noted as being in its initial state.
779 * This basically gives us three possible states for a given component:
780 *
781 * 1. FPU_EN is not set and FPU_VALID is not set. This means we need to take
782 * the illumos FPU default for an item. More on that in a moment.
783 * 2. The saved xsave state indicates that the bit for a given component is
784 * zero -- specifically the xsh_xstate_bv member of the struct xsave_state.
785 * In this case, we must take the CPU's default for an item. This is
786 * usually the same as illumos, but not always.
787 * 3. The saved xsave state indicates that a given component's state bit is
788 * valid. The simplest of our cases. We can just take what we have from the
789 * xsave state.
790 *
791 * The CPU's default state for most components other than the x87/SSE state is
792 * to have it be zeroed. This is what we treat as our default state as well. The
793 * primary difference is in the initialization of the x87/SSE state. The SYS V
794 * ABI requires that we enable a different floating point control word then the
795 * hardware default. This means that when we're dealing with case (1) for
796 * x87/SSE we have to be more careful than the other components. Thankfully for
797 * everything else this is just keeping it zeroed.
798 *
799 * A reasonable question would be why not just skip components that aren't
800 * marked as present. There are a few reasons we take a different approach and
801 * always include them. Both of these are to make lives simpler for consumers.
802 * In the first case, when someone is performing a read and wants to reassemble
803 * and answer the question of 'what is the value of %ymm0 or %zmm15', they have
804 * to combine multiple disparate parts. If one knows that the data we put into
805 * there is always valid and represents what is in hardware and doesn't have to
806 * keep track of what are the defaults in different circumstances, then that
807 * greatly simplifies consumers lives. It also helps us for core files and other
808 * observability cases because the answer to what is the operating system's
809 * default may change over time.
810 *
811 * Similarly, including all the possible structures means that we have
812 * simplified writes. Writes are always setting the full state of a thread,
813 * meaning that if someone wants to modify only a single register they must do a
814 * read, modify, and write. By including everything that they might need, it
815 * makes it easier for consumers to do this and not have to cons up the whole
816 * structure on their own.
817 *
818 * When we're setting state, things change around a little bit. We have a few
819 * constraints that are laid out in proc(5). In particular, we require that the
820 * PRX_INFO_XSAVE component always be present to tell us which other components
821 * we expect to be here and which ones we don't. We also are much stricter about
822 * writes in several ways. Of all the components, the PRX_INFO_XCR is read-only
823 * and may not be modified by a calling process. In addition, when we have
824 * 32-bit applications which have reserved registers in the %ymm, %zmm, etc.
825 * components, if they are being written to and have modifications, then we will
826 * indicate an error there.
827 *
828 * Because we are given the entire buffer from userland and don't need to have
829 * an intermediate place to copy it in, we will validate the entire thing in
830 * advance. Once it has been validated and we consider it legal, then we will
831 * translate each entry into its corresponding entry in pcb's normal floating
832 * point state. This is different from signal handling mostly because of the
833 * fact that we are not using copyin, and once we get to this point, there is
834 * no more validation, so we don't have the same concerns around blocking while
835 * pre-emption is disabled.
836 *
837 * The Wrinkle with fpregs
838 * -----------------------
839 *
840 * When we instead turn our attention to the fpregs, whether we're gathering
841 * them as part of the ucontext_t or as part of /proc, there are a few
842 * complications that we need to be aware of when we're operating on a kernel
843 * that is using xsave as the save mechanism. When we're using fxsave as the
844 * save mechanism, the CPU will always save the entire 512-byte fxsave region.
845 * The fpregs ABI that the kernel expects is basically this structure itself,
846 * which is transformed into a 32-bit compatible form in archdep.c.
847 *
848 * But xsave makes this much more complex and has historically been a source of
849 * bugs in the system. In particular, unlike fxsave, xsave has its component bit
850 * vector that is written out to indicate validity. This means that blindly
851 * copying the fxsave area without checking those bits will lead us to do the
852 * wrong thing. The XMM state flag mostly covers the 16 128-bit %xmm registers,
853 * while the x87 legacy fp flag covers the rest of the state. This is all good,
854 * aside from the MCXSR.
855 *
856 * One of the more complicated pieces of xsave state management is correctly
857 * answering the question of when the MXCSR is written out to xsave_state. In
858 * practice, this is rather convoluted and varies. If either the XMM or AVX
859 * feature bits are set then the CPU will write out the MXCSR and its mask
860 * register into the traditional fxsave state region. This behavior is dependent
861 * on the type of save function that we use. xsave and xsaveopt will look at the
862 * AVX feature bit; however, xsavec does not and only considers the SSE feature
863 * bit. This means that when we're retrieving things, we need to check both of
864 * those bits to determine if we should use the initial state or the value
865 * written out.
866 *
867 * When we come to someone trying to set the fpregs through /proc, the main
868 * question we have is what happens to the extended registers. We have opted to
869 * implement and document it such that a write to the fpregs only impacts the
870 * fpregs. Put differently, we will save the FPU state with fp_save() ahead of
871 * copying the data into the save area, set the state bits for x87 and XMM
872 * state, and then set the FPU to be restored. All in all, this basically means
873 * that writing to fpregs does not touch any of the %ymm, %zmm, or other state
874 * that we might have present.
875 *
876 * Forward Looking: Adding Intel AMX Support
877 * -----------------------------------------
878 *
879 * Nothing can stop the march of features being added into the FPU. One of the
880 * larger chunks that we will need to wrangle with is Intel's Advanced Matrix
881 * Extensions (AMX), which add a large chunk of xsave state to each process.
882 * While things like AVX and AVX-512 have been enabled by default, the broader
883 * OS community has not been wanting to do this for AMX ,because of the size of
884 * the state which exceeds 8 KiB. While the signal handling state went out of
885 * its way to minimize the size it wrote to the stack, if this is used, it would
886 * need to be preserved.
887 *
888 * To deal with this reality and the fact that folks don't really want to
889 * enable it by default for all purposes when its use will be quite special
890 * purpose, Intel has also added a MSR around extended feature disable or xfd.
891 * This is what we represent in the PRX_INFO_XCR prx_xfd member. Our starting
892 * assumption, and the reason that so much of the /proc and signal logic ensures
893 * that we have the thread and process around, taking as an example the unused
894 * process argument in fpu_proc_xregs_info(), is that we will follow suit and
895 * default to having support disabled, but that a process will be able to opt
896 * into it, which will result in several different assumptions around signal
897 * stack sizing and cause us to reallocate and extend the pcb's FPU save state.
898 *
899 * The following is a list of items to pay attention to for future folks who
900 * work on this:
901 *
902 * o We will want to confirm whether other systems have opted to make this
903 * process-wide or thread-wide. Assuming process-wide, we will need to do a
904 * hold of all lwps while making a change. The interface for that probably
905 * doesn't want to be /proc, as a process probably doesn't want to write to
906 * its own control file. Changing it for another process could be done
907 * through the agent-lwp.
908 * o Opting into this should probably be a one-way street.
909 * o Opting into this will need to evaluate all threads and in particular
910 * stack sizes to confirm they adhere to the new minimum.
911 * o We will need to make sure that setting and clearing the xfd MSR is part
912 * of the FPU context ops and something we set by default on every CPU.
913 * o We will need to add a new interface to allow opting into this feature.
914 * o We will need to ensure that all subsequently created signal stacks adhere
915 * to a required minimum size that we communicate through libc.
916 * o We will need to make sure that both rtld and libc no longer rely on a
917 * static value of the AT_SUN_FPSIZE, but rather realize that this can be
918 * dynamic. At that time, we should evaluate if we can get away with not
919 * needing to save this for rtld, even though signal handlers should assume
920 * they will.
921 * o The various components (because there is more than one) will want to be
922 * added to the fpu_xsave_info[]. Consulting the processes's xfd will be
923 * required and probably require logic changes.
924 *
925 * The above is not exhaustive. We'll probably have some other issues and fun
926 * while doing this.
927 */
928
929 /*
930 * The kind of FPU we advertise to rtld so it knows what to do when working
931 * through the PLT.
932 */
933 int fp_elf = AT_386_FPINFO_FXSAVE;
934
935 /*
936 * Mechanism to save FPU state.
937 */
938 int fp_save_mech = FP_FXSAVE;
939
940 /*
941 * See section 10.5.1 in the Intel 64 and IA-32 Architectures Software
942 * Developer's Manual, Volume 1.
943 */
944 #define FXSAVE_ALIGN 16
945
946 /*
947 * See section 13.4 in the Intel 64 and IA-32 Architectures Software
948 * Developer's Manual, Volume 1.
949 */
950 #define XSAVE_ALIGN 64
951
952 kmem_cache_t *fpsave_cachep;
953
954 /* Legacy fxsave layout + xsave header + ymm */
955 #define AVX_XSAVE_SIZE (512 + 64 + 256)
956
957 /*
958 * Various sanity checks.
959 */
960 CTASSERT(sizeof (struct fxsave_state) == 512);
961 CTASSERT(sizeof (struct fnsave_state) == 108);
962 CTASSERT((offsetof(struct fxsave_state, fx_xmm[0]) & 0xf) == 0);
963 CTASSERT(sizeof (struct xsave_state) >= AVX_XSAVE_SIZE);
964
965 /*
966 * Basic architectural alignment information.
967 */
968 #define FPU_ALIGN_XMM 16
969 #define FPU_ALIGN_YMM 32
970 #define FPU_ALIGN_ZMM 64
971
972 /*
973 * This structure is the x86 implementation of the kernel FPU that is defined in
974 * uts/common/sys/kfpu.h.
975 */
976
977 typedef enum kfpu_flags {
978 /*
979 * This indicates that the save state has initial FPU data.
980 */
981 KFPU_F_INITIALIZED = 0x01
982 } kfpu_flags_t;
983
984 struct kfpu_state {
985 fpu_ctx_t kfpu_ctx;
986 kfpu_flags_t kfpu_flags;
987 kthread_t *kfpu_curthread;
988 };
989
990 /*
991 * Initial kfpu state for SSE/SSE2 used by fpinit()
992 */
993 const struct fxsave_state sse_initial = {
994 FPU_CW_INIT, /* fx_fcw */
995 0, /* fx_fsw */
996 0, /* fx_fctw */
997 0, /* fx_fop */
998 0, /* fx_rip */
999 0, /* fx_rdp */
1000 SSE_MXCSR_INIT /* fx_mxcsr */
1001 /* rest of structure is zero */
1002 };
1003
1004 /*
1005 * Initial kfpu state for AVX used by fpinit()
1006 */
1007 const struct xsave_state avx_initial = {
1008 /*
1009 * The definition below needs to be identical with sse_initial
1010 * defined above.
1011 */
1012 .xs_fxsave = {
1013 .fx_fcw = FPU_CW_INIT,
1014 .fx_mxcsr = SSE_MXCSR_INIT,
1015 },
1016 .xs_header = {
1017 /*
1018 * bit0 = 1 for XSTATE_BV to indicate that legacy fields are
1019 * valid, and CPU should initialize XMM/YMM.
1020 */
1021 .xsh_xstate_bv = 1,
1022 .xsh_xcomp_bv = 0,
1023 },
1024 };
1025
1026 /*
1027 * mxcsr_mask value (possibly reset in fpu_probe); used to avoid
1028 * the #gp exception caused by setting unsupported bits in the
1029 * MXCSR register
1030 */
1031 uint32_t sse_mxcsr_mask = SSE_MXCSR_MASK_DEFAULT;
1032
1033 /*
1034 * This vector is patched to xsave_ctxt() or xsaveopt_ctxt() if we discover we
1035 * have an XSAVE-capable chip in fpu_probe.
1036 */
1037 void (*fpsave_ctxt)(void *) = fpxsave_ctxt;
1038 void (*fprestore_ctxt)(void *) = fpxrestore_ctxt;
1039
1040 /*
1041 * This function pointer is changed to xsaveopt if the CPU is xsaveopt capable.
1042 */
1043 void (*xsavep)(struct xsave_state *, uint64_t) = xsave;
1044
1045 static int fpe_sicode(uint_t);
1046 static int fpe_simd_sicode(uint_t);
1047 static void fp_new_lwp(void *, void *);
1048 static void fp_free_ctx(void *, int);
1049
1050 static struct ctxop *
fp_ctxop_allocate(struct fpu_ctx * fp)1051 fp_ctxop_allocate(struct fpu_ctx *fp)
1052 {
1053 const struct ctxop_template tpl = {
1054 .ct_rev = CTXOP_TPL_REV,
1055 .ct_save = fpsave_ctxt,
1056 .ct_restore = fprestore_ctxt,
1057 .ct_fork = fp_new_lwp,
1058 .ct_lwp_create = fp_new_lwp,
1059 .ct_free = fp_free_ctx,
1060 };
1061 return (ctxop_allocate(&tpl, fp));
1062 }
1063
1064 /*
1065 * Copy the state of parent lwp's floating point context into the new lwp.
1066 * Invoked for both fork() and lwp_create().
1067 *
1068 * Note that we inherit -only- the control state (e.g. exception masks,
1069 * rounding, precision control, etc.); the FPU registers are otherwise
1070 * reset to their initial state.
1071 */
1072 static void
fp_new_lwp(void * parent,void * child)1073 fp_new_lwp(void *parent, void *child)
1074 {
1075 kthread_id_t t = parent, ct = child;
1076 struct fpu_ctx *fp; /* parent fpu context */
1077 struct fpu_ctx *cfp; /* new fpu context */
1078 struct fxsave_state *fx, *cfx;
1079 struct xsave_state *cxs;
1080
1081 ASSERT(fp_kind != FP_NO);
1082
1083 fp = &t->t_lwp->lwp_pcb.pcb_fpu;
1084 cfp = &ct->t_lwp->lwp_pcb.pcb_fpu;
1085
1086 /*
1087 * If the parent FPU state is still in the FPU hw then save it;
1088 * conveniently, fp_save() already does this for us nicely.
1089 */
1090 fp_save(fp);
1091
1092 cfp->fpu_flags = FPU_EN | FPU_VALID;
1093 cfp->fpu_regs.kfpu_status = 0;
1094 cfp->fpu_regs.kfpu_xstatus = 0;
1095
1096 /*
1097 * Make sure that the child's FPU is cleaned up and made ready for user
1098 * land.
1099 */
1100 PCB_SET_UPDATE_FPU(&ct->t_lwp->lwp_pcb);
1101
1102 switch (fp_save_mech) {
1103 case FP_FXSAVE:
1104 fx = fp->fpu_regs.kfpu_u.kfpu_fx;
1105 cfx = cfp->fpu_regs.kfpu_u.kfpu_fx;
1106 bcopy(&sse_initial, cfx, sizeof (*cfx));
1107 cfx->fx_mxcsr = fx->fx_mxcsr & ~SSE_MXCSR_EFLAGS;
1108 cfx->fx_fcw = fx->fx_fcw;
1109 break;
1110
1111 case FP_XSAVE:
1112 cfp->fpu_xsave_mask = fp->fpu_xsave_mask;
1113
1114 VERIFY(fp->fpu_regs.kfpu_u.kfpu_xs != NULL);
1115
1116 fx = &fp->fpu_regs.kfpu_u.kfpu_xs->xs_fxsave;
1117 cxs = cfp->fpu_regs.kfpu_u.kfpu_xs;
1118 cfx = &cxs->xs_fxsave;
1119
1120 bcopy(&avx_initial, cxs, sizeof (*cxs));
1121 cfx->fx_mxcsr = fx->fx_mxcsr & ~SSE_MXCSR_EFLAGS;
1122 cfx->fx_fcw = fx->fx_fcw;
1123 cxs->xs_header.xsh_xstate_bv |=
1124 (get_xcr(XFEATURE_ENABLED_MASK) & XFEATURE_FP_INITIAL);
1125 break;
1126 default:
1127 panic("Invalid fp_save_mech");
1128 /*NOTREACHED*/
1129 }
1130
1131 /*
1132 * Mark that both the parent and child need to have the FPU cleaned up
1133 * before returning to userland.
1134 */
1135
1136 ctxop_attach(ct, fp_ctxop_allocate(cfp));
1137 }
1138
1139 /*
1140 * Free any state associated with floating point context.
1141 * Fp_free can be called in three cases:
1142 * 1) from reaper -> thread_free -> freectx-> fp_free
1143 * fp context belongs to a thread on deathrow
1144 * nothing to do, thread will never be resumed
1145 * thread calling ctxfree is reaper
1146 *
1147 * 2) from exec -> freectx -> fp_free
1148 * fp context belongs to the current thread
1149 * must disable fpu, thread calling ctxfree is curthread
1150 *
1151 * 3) from restorecontext -> setfpregs -> fp_free
1152 * we have a modified context in the memory (lwp->pcb_fpu)
1153 * disable fpu and release the fp context for the CPU
1154 *
1155 */
1156 void
fp_free(struct fpu_ctx * fp)1157 fp_free(struct fpu_ctx *fp)
1158 {
1159 ASSERT(fp_kind != FP_NO);
1160
1161 if (fp->fpu_flags & FPU_VALID)
1162 return;
1163
1164 kpreempt_disable();
1165 /*
1166 * We want to do fpsave rather than fpdisable so that we can
1167 * keep the fpu_flags as FPU_VALID tracking the CR0_TS bit
1168 */
1169 fp->fpu_flags |= FPU_VALID;
1170 /* If for current thread disable FP to track FPU_VALID */
1171 if (curthread->t_lwp && fp == &curthread->t_lwp->lwp_pcb.pcb_fpu) {
1172 /* Clear errors if any to prevent frstor from complaining */
1173 (void) fperr_reset();
1174 if (fp_kind & __FP_SSE)
1175 (void) fpxerr_reset();
1176 fpdisable();
1177 }
1178 kpreempt_enable();
1179 }
1180
1181 /*
1182 * Wrapper for freectx to make the types line up for fp_free()
1183 */
1184 static void
fp_free_ctx(void * arg,int isexec __unused)1185 fp_free_ctx(void *arg, int isexec __unused)
1186 {
1187 fp_free((struct fpu_ctx *)arg);
1188 }
1189
1190 /*
1191 * Store the floating point state and disable the floating point unit.
1192 */
1193 void
fp_save(struct fpu_ctx * fp)1194 fp_save(struct fpu_ctx *fp)
1195 {
1196 ASSERT(fp_kind != FP_NO);
1197
1198 kpreempt_disable();
1199 if (!fp || fp->fpu_flags & FPU_VALID ||
1200 (fp->fpu_flags & FPU_EN) == 0) {
1201 kpreempt_enable();
1202 return;
1203 }
1204 ASSERT(curthread->t_lwp && fp == &curthread->t_lwp->lwp_pcb.pcb_fpu);
1205
1206 switch (fp_save_mech) {
1207 case FP_FXSAVE:
1208 fpxsave(fp->fpu_regs.kfpu_u.kfpu_fx);
1209 break;
1210
1211 case FP_XSAVE:
1212 xsavep(fp->fpu_regs.kfpu_u.kfpu_xs, fp->fpu_xsave_mask);
1213 break;
1214 default:
1215 panic("Invalid fp_save_mech");
1216 /*NOTREACHED*/
1217 }
1218
1219 fp->fpu_flags |= FPU_VALID;
1220
1221 /*
1222 * We save the FPU as part of forking, execing, modifications via /proc,
1223 * restorecontext, etc. As such, we need to make sure that we return to
1224 * userland with valid state in the FPU. If we're context switched out
1225 * before we hit sys_rtt_common() we'll end up having restored the FPU
1226 * as part of the context ops operations. The restore logic always makes
1227 * sure that FPU_VALID is set before doing a restore so we don't restore
1228 * it a second time.
1229 */
1230 PCB_SET_UPDATE_FPU(&curthread->t_lwp->lwp_pcb);
1231
1232 kpreempt_enable();
1233 }
1234
1235 /*
1236 * Restore the FPU context for the thread:
1237 * The possibilities are:
1238 * 1. No active FPU context: Load the new context into the FPU hw
1239 * and enable the FPU.
1240 */
1241 void
fp_restore(struct fpu_ctx * fp)1242 fp_restore(struct fpu_ctx *fp)
1243 {
1244 switch (fp_save_mech) {
1245 case FP_FXSAVE:
1246 fpxrestore(fp->fpu_regs.kfpu_u.kfpu_fx);
1247 break;
1248
1249 case FP_XSAVE:
1250 xrestore(fp->fpu_regs.kfpu_u.kfpu_xs, fp->fpu_xsave_mask);
1251 break;
1252 default:
1253 panic("Invalid fp_save_mech");
1254 /*NOTREACHED*/
1255 }
1256
1257 fp->fpu_flags &= ~FPU_VALID;
1258 }
1259
1260 /*
1261 * Reset the FPU such that it is in a valid state for a new thread that is
1262 * coming out of exec. The FPU will be in a usable state at this point. At this
1263 * point we know that the FPU state has already been allocated and if this
1264 * wasn't an init process, then it will have had fp_free() previously called.
1265 */
1266 void
fp_exec(void)1267 fp_exec(void)
1268 {
1269 struct fpu_ctx *fp = &ttolwp(curthread)->lwp_pcb.pcb_fpu;
1270
1271 if (fp_save_mech == FP_XSAVE) {
1272 fp->fpu_xsave_mask = XFEATURE_FP_ALL;
1273 }
1274
1275 struct ctxop *ctx = fp_ctxop_allocate(fp);
1276 /*
1277 * Make sure that we're not preempted in the middle of initializing the
1278 * FPU on CPU.
1279 */
1280 kpreempt_disable();
1281 ctxop_attach(curthread, ctx);
1282 fpinit();
1283 fp->fpu_flags = FPU_EN;
1284 kpreempt_enable();
1285 }
1286
1287
1288 /*
1289 * Seeds the initial state for the current thread. The possibilities are:
1290 * 1. Another process has modified the FPU state before we have done any
1291 * initialization: Load the FPU state from the LWP state.
1292 * 2. The FPU state has not been externally modified: Load a clean state.
1293 */
1294 void
fp_seed(void)1295 fp_seed(void)
1296 {
1297 struct fpu_ctx *fp = &ttolwp(curthread)->lwp_pcb.pcb_fpu;
1298
1299 ASSERT(curthread->t_preempt >= 1);
1300 ASSERT((fp->fpu_flags & FPU_EN) == 0);
1301
1302 /*
1303 * Always initialize a new context and initialize the hardware.
1304 */
1305 if (fp_save_mech == FP_XSAVE) {
1306 fp->fpu_xsave_mask = XFEATURE_FP_ALL;
1307 }
1308
1309 ctxop_attach(curthread, fp_ctxop_allocate(fp));
1310 fpinit();
1311
1312 /*
1313 * If FPU_VALID is set, it means someone has modified registers via
1314 * /proc. In this case, restore the current lwp's state.
1315 */
1316 if (fp->fpu_flags & FPU_VALID)
1317 fp_restore(fp);
1318
1319 ASSERT((fp->fpu_flags & FPU_VALID) == 0);
1320 fp->fpu_flags = FPU_EN;
1321 }
1322
1323 /*
1324 * When using xsave/xrstor, these three functions are used by the lwp code to
1325 * manage the memory for the xsave area.
1326 */
1327 void
fp_lwp_init(klwp_t * lwp)1328 fp_lwp_init(klwp_t *lwp)
1329 {
1330 struct fpu_ctx *fp = &lwp->lwp_pcb.pcb_fpu;
1331
1332 /*
1333 * We keep a copy of the pointer in lwp_fpu so that we can restore the
1334 * value in forklwp() after we duplicate the parent's LWP state.
1335 */
1336 lwp->lwp_fpu = fp->fpu_regs.kfpu_u.kfpu_generic =
1337 kmem_cache_alloc(fpsave_cachep, KM_SLEEP);
1338 fp->fpu_signal = NULL;
1339
1340 if (fp_save_mech == FP_XSAVE) {
1341 /*
1342 *
1343 * We bzero since the fpinit() code path will only
1344 * partially initialize the xsave area using avx_inital.
1345 */
1346 ASSERT(cpuid_get_xsave_size() >= sizeof (struct xsave_state));
1347 bzero(fp->fpu_regs.kfpu_u.kfpu_xs, cpuid_get_xsave_size());
1348 }
1349 }
1350
1351 void
fp_lwp_cleanup(klwp_t * lwp)1352 fp_lwp_cleanup(klwp_t *lwp)
1353 {
1354 struct fpu_ctx *fp = &lwp->lwp_pcb.pcb_fpu;
1355
1356 if (fp->fpu_regs.kfpu_u.kfpu_generic != NULL) {
1357 kmem_cache_free(fpsave_cachep,
1358 fp->fpu_regs.kfpu_u.kfpu_generic);
1359 lwp->lwp_fpu = fp->fpu_regs.kfpu_u.kfpu_generic = NULL;
1360 }
1361
1362 if (fp->fpu_signal != NULL) {
1363 kmem_cache_free(fpsave_cachep, fp->fpu_signal);
1364 fp->fpu_signal = NULL;
1365 }
1366 }
1367
1368 /*
1369 * Called during the process of forklwp(). The kfpu_u pointer will have been
1370 * overwritten while copying the parent's LWP structure. We have a valid copy
1371 * stashed in the child's lwp_fpu which we use to restore the correct value.
1372 */
1373 void
fp_lwp_dup(klwp_t * lwp)1374 fp_lwp_dup(klwp_t *lwp)
1375 {
1376 void *xp = lwp->lwp_fpu;
1377 size_t sz;
1378
1379 switch (fp_save_mech) {
1380 case FP_FXSAVE:
1381 sz = sizeof (struct fxsave_state);
1382 break;
1383 case FP_XSAVE:
1384 sz = cpuid_get_xsave_size();
1385 break;
1386 default:
1387 panic("Invalid fp_save_mech");
1388 /*NOTREACHED*/
1389 }
1390
1391 /* copy the parent's values into the new lwp's struct */
1392 bcopy(lwp->lwp_pcb.pcb_fpu.fpu_regs.kfpu_u.kfpu_generic, xp, sz);
1393 /* now restore the pointer */
1394 lwp->lwp_pcb.pcb_fpu.fpu_regs.kfpu_u.kfpu_generic = xp;
1395 /* Ensure that we don't inherit our parent's signal state */
1396 lwp->lwp_pcb.pcb_fpu.fpu_signal = NULL;
1397 }
1398
1399 /*
1400 * Handle a processor extension error fault
1401 * Returns non zero for error.
1402 */
1403
1404 /*ARGSUSED*/
1405 int
fpexterrflt(struct regs * rp)1406 fpexterrflt(struct regs *rp)
1407 {
1408 uint32_t fpcw, fpsw;
1409 fpu_ctx_t *fp = &ttolwp(curthread)->lwp_pcb.pcb_fpu;
1410
1411 ASSERT(fp_kind != FP_NO);
1412
1413 /*
1414 * Now we can enable the interrupts.
1415 * (NOTE: x87 fp exceptions come thru interrupt gate)
1416 */
1417 sti();
1418
1419 if (!fpu_exists)
1420 return (FPE_FLTINV);
1421
1422 /*
1423 * Do an unconditional save of the FP state. If it's dirty (TS=0),
1424 * it'll be saved into the fpu context area passed in (that of the
1425 * current thread). If it's not dirty (it may not be, due to
1426 * an intervening save due to a context switch between the sti(),
1427 * above and here, then it's safe to just use the stored values in
1428 * the context save area to determine the cause of the fault.
1429 */
1430 fp_save(fp);
1431
1432 /* clear exception flags in saved state, as if by fnclex */
1433 switch (fp_save_mech) {
1434 case FP_FXSAVE:
1435 fpsw = fp->fpu_regs.kfpu_u.kfpu_fx->fx_fsw;
1436 fpcw = fp->fpu_regs.kfpu_u.kfpu_fx->fx_fcw;
1437 fp->fpu_regs.kfpu_u.kfpu_fx->fx_fsw &= ~FPS_SW_EFLAGS;
1438 break;
1439
1440 case FP_XSAVE:
1441 fpsw = fp->fpu_regs.kfpu_u.kfpu_xs->xs_fxsave.fx_fsw;
1442 fpcw = fp->fpu_regs.kfpu_u.kfpu_xs->xs_fxsave.fx_fcw;
1443 fp->fpu_regs.kfpu_u.kfpu_xs->xs_fxsave.fx_fsw &= ~FPS_SW_EFLAGS;
1444 /*
1445 * Always set LEGACY_FP as it may have been cleared by XSAVE
1446 * instruction
1447 */
1448 fp->fpu_regs.kfpu_u.kfpu_xs->xs_header.xsh_xstate_bv |=
1449 XFEATURE_LEGACY_FP;
1450 break;
1451 default:
1452 panic("Invalid fp_save_mech");
1453 /*NOTREACHED*/
1454 }
1455
1456 fp->fpu_regs.kfpu_status = fpsw;
1457
1458 if ((fpsw & FPS_ES) == 0)
1459 return (0); /* No exception */
1460
1461 /*
1462 * "and" the exception flags with the complement of the mask
1463 * bits to determine which exception occurred
1464 */
1465 return (fpe_sicode(fpsw & ~fpcw & 0x3f));
1466 }
1467
1468 /*
1469 * Handle an SSE/SSE2 precise exception.
1470 * Returns a non-zero sicode for error.
1471 */
1472 /*ARGSUSED*/
1473 int
fpsimderrflt(struct regs * rp)1474 fpsimderrflt(struct regs *rp)
1475 {
1476 uint32_t mxcsr, xmask;
1477 fpu_ctx_t *fp = &ttolwp(curthread)->lwp_pcb.pcb_fpu;
1478
1479 ASSERT(fp_kind & __FP_SSE);
1480
1481 /*
1482 * NOTE: Interrupts are disabled during execution of this
1483 * function. They are enabled by the caller in trap.c.
1484 */
1485
1486 /*
1487 * The only way we could have gotten here if there is no FP unit
1488 * is via a user executing an INT $19 instruction, so there is
1489 * no fault in that case.
1490 */
1491 if (!fpu_exists)
1492 return (0);
1493
1494 /*
1495 * Do an unconditional save of the FP state. If it's dirty (TS=0),
1496 * it'll be saved into the fpu context area passed in (that of the
1497 * current thread). If it's not dirty, then it's safe to just use
1498 * the stored values in the context save area to determine the
1499 * cause of the fault.
1500 */
1501 fp_save(fp); /* save the FPU state */
1502
1503 if (fp_save_mech == FP_XSAVE) {
1504 mxcsr = fp->fpu_regs.kfpu_u.kfpu_xs->xs_fxsave.fx_mxcsr;
1505 fp->fpu_regs.kfpu_status =
1506 fp->fpu_regs.kfpu_u.kfpu_xs->xs_fxsave.fx_fsw;
1507 } else {
1508 mxcsr = fp->fpu_regs.kfpu_u.kfpu_fx->fx_mxcsr;
1509 fp->fpu_regs.kfpu_status = fp->fpu_regs.kfpu_u.kfpu_fx->fx_fsw;
1510 }
1511 fp->fpu_regs.kfpu_xstatus = mxcsr;
1512
1513 /*
1514 * compute the mask that determines which conditions can cause
1515 * a #xm exception, and use this to clean the status bits so that
1516 * we can identify the true cause of this one.
1517 */
1518 xmask = (mxcsr >> 7) & SSE_MXCSR_EFLAGS;
1519 return (fpe_simd_sicode((mxcsr & SSE_MXCSR_EFLAGS) & ~xmask));
1520 }
1521
1522 /*
1523 * In the unlikely event that someone is relying on this subcode being
1524 * FPE_FLTILL for denormalize exceptions, it can always be patched back
1525 * again to restore old behaviour.
1526 */
1527 int fpe_fltden = FPE_FLTDEN;
1528
1529 /*
1530 * Map from the FPU status word to the FP exception si_code.
1531 */
1532 static int
fpe_sicode(uint_t sw)1533 fpe_sicode(uint_t sw)
1534 {
1535 if (sw & FPS_IE)
1536 return (FPE_FLTINV);
1537 if (sw & FPS_ZE)
1538 return (FPE_FLTDIV);
1539 if (sw & FPS_DE)
1540 return (fpe_fltden);
1541 if (sw & FPS_OE)
1542 return (FPE_FLTOVF);
1543 if (sw & FPS_UE)
1544 return (FPE_FLTUND);
1545 if (sw & FPS_PE)
1546 return (FPE_FLTRES);
1547 return (FPE_FLTINV); /* default si_code for other exceptions */
1548 }
1549
1550 /*
1551 * Map from the SSE status word to the FP exception si_code.
1552 */
1553 static int
fpe_simd_sicode(uint_t sw)1554 fpe_simd_sicode(uint_t sw)
1555 {
1556 if (sw & SSE_IE)
1557 return (FPE_FLTINV);
1558 if (sw & SSE_ZE)
1559 return (FPE_FLTDIV);
1560 if (sw & SSE_DE)
1561 return (FPE_FLTDEN);
1562 if (sw & SSE_OE)
1563 return (FPE_FLTOVF);
1564 if (sw & SSE_UE)
1565 return (FPE_FLTUND);
1566 if (sw & SSE_PE)
1567 return (FPE_FLTRES);
1568 return (FPE_FLTINV); /* default si_code for other exceptions */
1569 }
1570
1571 /*
1572 * This routine is invoked as part of libc's __fpstart implementation
1573 * via sysi86(2).
1574 *
1575 * It may be called -before- any context has been assigned in which case
1576 * we try and avoid touching the hardware. Or it may be invoked well
1577 * after the context has been assigned and fiddled with, in which case
1578 * just tweak it directly.
1579 */
1580 void
fpsetcw(uint16_t fcw,uint32_t mxcsr)1581 fpsetcw(uint16_t fcw, uint32_t mxcsr)
1582 {
1583 struct fpu_ctx *fp = &curthread->t_lwp->lwp_pcb.pcb_fpu;
1584 struct fxsave_state *fx;
1585
1586 if (!fpu_exists || fp_kind == FP_NO)
1587 return;
1588
1589 if ((fp->fpu_flags & FPU_EN) == 0) {
1590 if (fcw == FPU_CW_INIT && mxcsr == SSE_MXCSR_INIT) {
1591 /*
1592 * Common case. Floating point unit not yet
1593 * enabled, and kernel already intends to initialize
1594 * the hardware the way the caller wants.
1595 */
1596 return;
1597 }
1598 /*
1599 * Hmm. Userland wants a different default.
1600 * Do a fake "first trap" to establish the context, then
1601 * handle as if we already had a context before we came in.
1602 */
1603 kpreempt_disable();
1604 fp_seed();
1605 kpreempt_enable();
1606 }
1607
1608 /*
1609 * Ensure that the current hardware state is flushed back to the
1610 * pcb, then modify that copy. Next use of the fp will
1611 * restore the context.
1612 */
1613 fp_save(fp);
1614
1615 switch (fp_save_mech) {
1616 case FP_FXSAVE:
1617 fx = fp->fpu_regs.kfpu_u.kfpu_fx;
1618 fx->fx_fcw = fcw;
1619 fx->fx_mxcsr = sse_mxcsr_mask & mxcsr;
1620 break;
1621
1622 case FP_XSAVE:
1623 fx = &fp->fpu_regs.kfpu_u.kfpu_xs->xs_fxsave;
1624 fx->fx_fcw = fcw;
1625 fx->fx_mxcsr = sse_mxcsr_mask & mxcsr;
1626 /*
1627 * Always set LEGACY_FP as it may have been cleared by XSAVE
1628 * instruction
1629 */
1630 fp->fpu_regs.kfpu_u.kfpu_xs->xs_header.xsh_xstate_bv |=
1631 XFEATURE_LEGACY_FP;
1632 break;
1633 default:
1634 panic("Invalid fp_save_mech");
1635 /*NOTREACHED*/
1636 }
1637 }
1638
1639 static void
kernel_fpu_fpstate_init(kfpu_state_t * kfpu)1640 kernel_fpu_fpstate_init(kfpu_state_t *kfpu)
1641 {
1642 struct xsave_state *xs;
1643
1644 switch (fp_save_mech) {
1645 case FP_FXSAVE:
1646 bcopy(&sse_initial, kfpu->kfpu_ctx.fpu_regs.kfpu_u.kfpu_fx,
1647 sizeof (struct fxsave_state));
1648 kfpu->kfpu_ctx.fpu_xsave_mask = 0;
1649 break;
1650 case FP_XSAVE:
1651 xs = kfpu->kfpu_ctx.fpu_regs.kfpu_u.kfpu_xs;
1652 bzero(xs, cpuid_get_xsave_size());
1653 bcopy(&avx_initial, xs, sizeof (*xs));
1654 xs->xs_header.xsh_xstate_bv = XFEATURE_LEGACY_FP | XFEATURE_SSE;
1655 kfpu->kfpu_ctx.fpu_xsave_mask = XFEATURE_FP_ALL;
1656 break;
1657 default:
1658 panic("invalid fp_save_mech");
1659 }
1660
1661 /*
1662 * Set the corresponding flags that the system expects on the FPU state
1663 * to indicate that this is our state. The FPU_EN flag is required to
1664 * indicate that FPU usage is allowed. The FPU_KERN flag is explicitly
1665 * not set below as it represents that this state is being suppressed
1666 * by the kernel.
1667 */
1668 kfpu->kfpu_ctx.fpu_flags = FPU_EN | FPU_VALID;
1669 kfpu->kfpu_flags |= KFPU_F_INITIALIZED;
1670 }
1671
1672 kfpu_state_t *
kernel_fpu_alloc(int kmflags)1673 kernel_fpu_alloc(int kmflags)
1674 {
1675 kfpu_state_t *kfpu;
1676
1677 if ((kfpu = kmem_zalloc(sizeof (kfpu_state_t), kmflags)) == NULL) {
1678 return (NULL);
1679 }
1680
1681 kfpu->kfpu_ctx.fpu_regs.kfpu_u.kfpu_generic =
1682 kmem_cache_alloc(fpsave_cachep, kmflags);
1683 if (kfpu->kfpu_ctx.fpu_regs.kfpu_u.kfpu_generic == NULL) {
1684 kmem_free(kfpu, sizeof (kfpu_state_t));
1685 return (NULL);
1686 }
1687
1688 kernel_fpu_fpstate_init(kfpu);
1689
1690 return (kfpu);
1691 }
1692
1693 void
kernel_fpu_free(kfpu_state_t * kfpu)1694 kernel_fpu_free(kfpu_state_t *kfpu)
1695 {
1696 kmem_cache_free(fpsave_cachep,
1697 kfpu->kfpu_ctx.fpu_regs.kfpu_u.kfpu_generic);
1698 kmem_free(kfpu, sizeof (kfpu_state_t));
1699 }
1700
1701 static void
kernel_fpu_ctx_save(void * arg)1702 kernel_fpu_ctx_save(void *arg)
1703 {
1704 kfpu_state_t *kfpu = arg;
1705 fpu_ctx_t *pf;
1706
1707 if (kfpu == NULL) {
1708 /*
1709 * A NULL kfpu implies this is a kernel thread with an LWP and
1710 * no user-level FPU usage. Use the lwp fpu save area.
1711 */
1712 pf = &curthread->t_lwp->lwp_pcb.pcb_fpu;
1713
1714 ASSERT(curthread->t_procp->p_flag & SSYS);
1715 ASSERT3U(pf->fpu_flags & FPU_VALID, ==, 0);
1716
1717 fp_save(pf);
1718 } else {
1719 pf = &kfpu->kfpu_ctx;
1720
1721 ASSERT3P(kfpu->kfpu_curthread, ==, curthread);
1722 ASSERT3U(pf->fpu_flags & FPU_VALID, ==, 0);
1723
1724 /*
1725 * Note, we can't use fp_save because it assumes that we're
1726 * saving to the thread's PCB and not somewhere else. Because
1727 * this is a different FPU context, we instead have to do this
1728 * ourselves.
1729 */
1730 switch (fp_save_mech) {
1731 case FP_FXSAVE:
1732 fpxsave(pf->fpu_regs.kfpu_u.kfpu_fx);
1733 break;
1734 case FP_XSAVE:
1735 xsavep(pf->fpu_regs.kfpu_u.kfpu_xs, pf->fpu_xsave_mask);
1736 break;
1737 default:
1738 panic("Invalid fp_save_mech");
1739 }
1740
1741 /*
1742 * Because we have saved context here, our save state is no
1743 * longer valid and therefore needs to be reinitialized.
1744 */
1745 kfpu->kfpu_flags &= ~KFPU_F_INITIALIZED;
1746 }
1747
1748 pf->fpu_flags |= FPU_VALID;
1749
1750 /*
1751 * Clear KFPU flag. This allows swtch to check for improper kernel
1752 * usage of the FPU (i.e. switching to a new thread while the old
1753 * thread was in the kernel and using the FPU, but did not perform a
1754 * context save).
1755 */
1756 curthread->t_flag &= ~T_KFPU;
1757 }
1758
1759 static void
kernel_fpu_ctx_restore(void * arg)1760 kernel_fpu_ctx_restore(void *arg)
1761 {
1762 kfpu_state_t *kfpu = arg;
1763 fpu_ctx_t *pf;
1764
1765 if (kfpu == NULL) {
1766 /*
1767 * A NULL kfpu implies this is a kernel thread with an LWP and
1768 * no user-level FPU usage. Use the lwp fpu save area.
1769 */
1770 pf = &curthread->t_lwp->lwp_pcb.pcb_fpu;
1771
1772 ASSERT(curthread->t_procp->p_flag & SSYS);
1773 ASSERT3U(pf->fpu_flags & FPU_VALID, !=, 0);
1774 } else {
1775 pf = &kfpu->kfpu_ctx;
1776
1777 ASSERT3P(kfpu->kfpu_curthread, ==, curthread);
1778 ASSERT3U(pf->fpu_flags & FPU_VALID, !=, 0);
1779 }
1780
1781 fp_restore(pf);
1782 curthread->t_flag |= T_KFPU;
1783 }
1784
1785 /*
1786 * Validate that the thread is not switching off-cpu while actively using the
1787 * FPU within the kernel.
1788 */
1789 void
kernel_fpu_no_swtch(void)1790 kernel_fpu_no_swtch(void)
1791 {
1792 if ((curthread->t_flag & T_KFPU) != 0) {
1793 panic("curthread swtch-ing while the kernel is using the FPU");
1794 }
1795 }
1796
1797 static const struct ctxop_template kfpu_ctxop_tpl = {
1798 .ct_rev = CTXOP_TPL_REV,
1799 .ct_save = kernel_fpu_ctx_save,
1800 .ct_restore = kernel_fpu_ctx_restore,
1801 };
1802
1803 void
kernel_fpu_begin(kfpu_state_t * kfpu,uint_t flags)1804 kernel_fpu_begin(kfpu_state_t *kfpu, uint_t flags)
1805 {
1806 klwp_t *pl = curthread->t_lwp;
1807 struct ctxop *ctx;
1808
1809 if ((curthread->t_flag & T_KFPU) != 0) {
1810 panic("curthread attempting to nest kernel FPU states");
1811 }
1812
1813 /* KFPU_USE_LWP and KFPU_NO_STATE are mutually exclusive. */
1814 ASSERT((flags & (KFPU_USE_LWP | KFPU_NO_STATE)) !=
1815 (KFPU_USE_LWP | KFPU_NO_STATE));
1816
1817 if ((flags & KFPU_NO_STATE) == KFPU_NO_STATE) {
1818 /*
1819 * Since we don't have a kfpu_state or usable lwp pcb_fpu to
1820 * hold our kernel FPU context, we depend on the caller doing
1821 * kpreempt_disable for the duration of our FPU usage. This
1822 * should only be done for very short periods of time.
1823 */
1824 ASSERT(curthread->t_preempt > 0);
1825 ASSERT(kfpu == NULL);
1826
1827 if (pl != NULL) {
1828 /*
1829 * We might have already saved once so FPU_VALID could
1830 * be set. This is handled in fp_save.
1831 */
1832 fp_save(&pl->lwp_pcb.pcb_fpu);
1833 pl->lwp_pcb.pcb_fpu.fpu_flags |= FPU_KERNEL;
1834 }
1835
1836 curthread->t_flag |= T_KFPU;
1837
1838 /* Always restore the fpu to the initial state. */
1839 fpinit();
1840
1841 return;
1842 }
1843
1844 /*
1845 * We either have a kfpu, or are using the LWP pcb_fpu for context ops.
1846 */
1847
1848 if ((flags & KFPU_USE_LWP) == 0) {
1849 if (kfpu->kfpu_curthread != NULL)
1850 panic("attempting to reuse kernel FPU state at %p when "
1851 "another thread already is using", kfpu);
1852
1853 if ((kfpu->kfpu_flags & KFPU_F_INITIALIZED) == 0)
1854 kernel_fpu_fpstate_init(kfpu);
1855
1856 kfpu->kfpu_curthread = curthread;
1857 }
1858
1859 /*
1860 * Not all threads may have an active LWP. If they do and we're not
1861 * going to re-use the LWP, then we should go ahead and save the state.
1862 * We must also note that the fpu is now being used by the kernel and
1863 * therefore we do not want to manage the fpu state via the user-level
1864 * thread's context handlers.
1865 *
1866 * We might have already saved once (due to a prior use of the kernel
1867 * FPU or another code path) so FPU_VALID could be set. This is handled
1868 * by fp_save, as is the FPU_EN check.
1869 */
1870 ctx = ctxop_allocate(&kfpu_ctxop_tpl, kfpu);
1871 kpreempt_disable();
1872 if (pl != NULL) {
1873 if ((flags & KFPU_USE_LWP) == 0)
1874 fp_save(&pl->lwp_pcb.pcb_fpu);
1875 pl->lwp_pcb.pcb_fpu.fpu_flags |= FPU_KERNEL;
1876 }
1877
1878 /*
1879 * Set the context operations for kernel FPU usage. Because kernel FPU
1880 * setup and ctxop attachment needs to happen under the protection of
1881 * kpreempt_disable(), we allocate the ctxop outside the guard so its
1882 * sleeping allocation will not cause a voluntary swtch(). This allows
1883 * the rest of the initialization to proceed, ensuring valid state for
1884 * the ctxop handlers.
1885 */
1886 ctxop_attach(curthread, ctx);
1887 curthread->t_flag |= T_KFPU;
1888
1889 if ((flags & KFPU_USE_LWP) == KFPU_USE_LWP) {
1890 /*
1891 * For pure kernel threads with an LWP, we can use the LWP's
1892 * pcb_fpu to save/restore context.
1893 */
1894 fpu_ctx_t *pf = &pl->lwp_pcb.pcb_fpu;
1895
1896 VERIFY(curthread->t_procp->p_flag & SSYS);
1897 VERIFY(kfpu == NULL);
1898 ASSERT((pf->fpu_flags & FPU_EN) == 0);
1899
1900 /* Always restore the fpu to the initial state. */
1901 if (fp_save_mech == FP_XSAVE)
1902 pf->fpu_xsave_mask = XFEATURE_FP_ALL;
1903 fpinit();
1904 pf->fpu_flags = FPU_EN | FPU_KERNEL;
1905 } else {
1906 /* initialize the kfpu state */
1907 kernel_fpu_ctx_restore(kfpu);
1908 }
1909 kpreempt_enable();
1910 }
1911
1912 void
kernel_fpu_end(kfpu_state_t * kfpu,uint_t flags)1913 kernel_fpu_end(kfpu_state_t *kfpu, uint_t flags)
1914 {
1915 if ((curthread->t_flag & T_KFPU) == 0) {
1916 panic("curthread attempting to clear kernel FPU state "
1917 "without using it");
1918 }
1919
1920 /*
1921 * General comments on why the rest of this function is structured the
1922 * way it is. Be aware that there is a lot of subtlety here.
1923 *
1924 * If a user-level thread ever uses the fpu while in the kernel, then
1925 * we cannot call fpdisable since that does STTS. That will set the
1926 * ts bit in %cr0 which will cause an exception if anything touches the
1927 * fpu. However, the user-level context switch handler (fpsave_ctxt)
1928 * needs to access the fpu to save the registers into the pcb.
1929 * fpsave_ctxt relies on CLTS having been done to clear the ts bit in
1930 * fprestore_ctxt when the thread context switched onto the CPU.
1931 *
1932 * Calling fpdisable only effects the current CPU's %cr0 register.
1933 *
1934 * During ctxop_remove and kpreempt_enable, we can voluntarily context
1935 * switch, so the CPU we were on when we entered this function might
1936 * not be the same one we're on when we return from ctxop_remove or end
1937 * the function. Note there can be user-level context switch handlers
1938 * still installed if this is a user-level thread.
1939 *
1940 * We also must be careful in the unlikely chance we're running in an
1941 * interrupt thread, since we can't leave the CPU's %cr0 TS state set
1942 * incorrectly for the "real" thread to resume on this CPU.
1943 */
1944
1945 if ((flags & KFPU_NO_STATE) == 0) {
1946 kpreempt_disable();
1947 } else {
1948 ASSERT(curthread->t_preempt > 0);
1949 }
1950
1951 curthread->t_flag &= ~T_KFPU;
1952
1953 /*
1954 * When we are ending things, we explicitly don't save the current
1955 * kernel FPU state back to the temporary state. The kfpu API is not
1956 * intended to be a permanent save location.
1957 *
1958 * If this is a user-level thread and we were to context switch
1959 * before returning to user-land, fpsave_ctxt will be a no-op since we
1960 * already saved the user-level FPU state the first time we run
1961 * kernel_fpu_begin (i.e. we won't save the bad kernel fpu state over
1962 * the user-level fpu state). The fpsave_ctxt functions only save if
1963 * FPU_VALID is not already set. fp_save also set PCB_SET_UPDATE_FPU so
1964 * fprestore_ctxt will be done in sys_rtt_common when the thread
1965 * finally returns to user-land.
1966 */
1967
1968 if ((curthread->t_procp->p_flag & SSYS) != 0 &&
1969 curthread->t_intr == NULL) {
1970 /*
1971 * A kernel thread which is not an interrupt thread, so we
1972 * STTS now.
1973 */
1974 fpdisable();
1975 }
1976
1977 if ((flags & KFPU_NO_STATE) == 0) {
1978 ctxop_remove(curthread, &kfpu_ctxop_tpl, kfpu);
1979
1980 if (kfpu != NULL) {
1981 if (kfpu->kfpu_curthread != curthread) {
1982 panic("attempting to end kernel FPU state "
1983 "for %p, but active thread is not "
1984 "curthread", kfpu);
1985 } else {
1986 kfpu->kfpu_curthread = NULL;
1987 }
1988 }
1989
1990 kpreempt_enable();
1991 }
1992
1993 if (curthread->t_lwp != NULL) {
1994 uint_t f;
1995
1996 if (flags & KFPU_USE_LWP) {
1997 f = FPU_EN | FPU_KERNEL;
1998 } else {
1999 f = FPU_KERNEL;
2000 }
2001 curthread->t_lwp->lwp_pcb.pcb_fpu.fpu_flags &= ~f;
2002 }
2003 }
2004
2005 void
fpu_save_cache_init(void)2006 fpu_save_cache_init(void)
2007 {
2008 switch (fp_save_mech) {
2009 case FP_FXSAVE:
2010 fpsave_cachep = kmem_cache_create("fxsave_cache",
2011 sizeof (struct fxsave_state), FXSAVE_ALIGN,
2012 NULL, NULL, NULL, NULL, NULL, 0);
2013 break;
2014 case FP_XSAVE:
2015 fpsave_cachep = kmem_cache_create("xsave_cache",
2016 cpuid_get_xsave_size(), XSAVE_ALIGN,
2017 NULL, NULL, NULL, NULL, NULL, 0);
2018 break;
2019 default:
2020 panic("Invalid fp_save_mech");
2021 }
2022 }
2023
2024 /*
2025 * Fill in FPU information that is required by exec.
2026 */
2027 void
fpu_auxv_info(int * typep,size_t * lenp)2028 fpu_auxv_info(int *typep, size_t *lenp)
2029 {
2030 *typep = fp_elf;
2031 switch (fp_save_mech) {
2032 case FP_FXSAVE:
2033 *lenp = sizeof (struct fxsave_state);
2034 break;
2035 case FP_XSAVE:
2036 *lenp = cpuid_get_xsave_size();
2037 break;
2038 default:
2039 *lenp = 0;
2040 break;
2041 }
2042 }
2043
2044 /*
2045 * This function exists to transform an xsave_state into an fxsave_state. The
2046 * way that we have to do this is nuanced. We assume that callers have already
2047 * handled FPU_EN and thus we only need to consider the xsave_state and its
2048 * component vector itself. This results in the following cases that we need to
2049 * consider:
2050 *
2051 * o Neither the x87 / XMM state bits are set. We use the hardware default and
2052 * need to ensure to copy the xsave header.
2053 * o Both x87 / XMM state bits are set. We can copy everything.
2054 * o Only the x87 bit is set. We need to copy the x87 state but make the XMM
2055 * state be in the initial case.
2056 * o Only the XMM bit is set. The reverse of the above case.
2057 *
2058 * The illumos and hardware defaults in 'sse_initial' and 'avx_initial' are
2059 * generally the same; however, the default floating point control word is
2060 * different.
2061 *
2062 * Finally, we have the complication of the MXCSR and MCXSR_MASK registers.
2063 * Because we are using xsave and xsaveopt in the kernel right now and not
2064 * xsavec, the hardware may write out the MXCSR and MXCSR_MASK registers if the
2065 * XFEATURE_AVX bit is set. Therefore if we don't have the XMM bit set but AVX
2066 * is set, we must also come back and copy out the MXCSR register. Sorry, we
2067 * don't make the rules.
2068 */
2069 static void
fpu_xsave_to_fxsave(const struct xsave_state * xsave,struct fxsave_state * fx)2070 fpu_xsave_to_fxsave(const struct xsave_state *xsave, struct fxsave_state *fx)
2071 {
2072 const uint64_t comps = xsave->xs_header.xsh_xstate_bv;
2073
2074 switch (comps & (XFEATURE_LEGACY_FP | XFEATURE_SSE)) {
2075 case XFEATURE_LEGACY_FP | XFEATURE_SSE:
2076 bcopy(xsave, fx, sizeof (*fx));
2077 return;
2078 case XFEATURE_LEGACY_FP:
2079 bcopy(xsave, fx, offsetof(struct fxsave_state, fx_xmm));
2080 fx->fx_mxcsr = SSE_MXCSR_INIT;
2081 fx->fx_mxcsr_mask = 0;
2082 break;
2083 case XFEATURE_SSE:
2084 bcopy(&sse_initial, fx, offsetof(struct fxsave_state,
2085 fx_mxcsr));
2086
2087 fx->fx_fcw = FPU_CW_INIT_HW;
2088 fx->fx_mxcsr = xsave->xs_fxsave.fx_mxcsr;
2089 fx->fx_mxcsr_mask = xsave->xs_fxsave.fx_mxcsr_mask;
2090 bcopy(xsave->xs_fxsave.fx_xmm, fx->fx_xmm, sizeof (fx->fx_xmm));
2091 break;
2092 default:
2093 bcopy(&sse_initial, fx, sizeof (*fx));
2094 fx->fx_fcw = FPU_CW_INIT_HW;
2095 break;
2096 }
2097
2098 /*
2099 * Account for the AVX causing MXCSR to be valid.
2100 */
2101 if ((xsave->xs_header.xsh_xstate_bv & XFEATURE_AVX) != 0 &&
2102 (xsave->xs_header.xsh_xstate_bv & XFEATURE_SSE) == 0) {
2103 fx->fx_mxcsr = xsave->xs_fxsave.fx_mxcsr;
2104 fx->fx_mxcsr_mask = xsave->xs_fxsave.fx_mxcsr_mask;
2105 }
2106 }
2107
2108 /*
2109 * This function is designed to answer the question of are we using any xsave
2110 * family of instructions in context switch and therefore we have this state.
2111 * This should still remain true if we are using xsavec or xsaves in the kernel
2112 * in the future.
2113 */
2114 boolean_t
fpu_xsave_enabled(void)2115 fpu_xsave_enabled(void)
2116 {
2117 return (fp_save_mech == FP_XSAVE);
2118 }
2119
2120 /*
2121 * The following structure is used to track and manage the programmatic
2122 * construction of /proc and signal stack spilling of xsave information. All
2123 * known xsave types that the kernel supports must be included here.
2124 */
2125 typedef struct xsave_proc_info {
2126 /*
2127 * This matches the /proc xregs type that this data represents. This s
2128 * used for /proc only.
2129 */
2130 uint32_t xi_type;
2131 /*
2132 * This indicates the size of the /proc data that we're operating on.
2133 * This is only used for /proc.
2134 */
2135 size_t xi_size;
2136 /*
2137 * This indicates the alignment that we want to have for the member when
2138 * we're writing out. This is not used when setting data. This is only
2139 * used for /proc.
2140 */
2141 size_t xi_align;
2142 /*
2143 * This indicates whether this member must always be considered or not.
2144 * This is used in both /proc and context/signal handling.
2145 */
2146 bool xi_always;
2147 /*
2148 * This contains the corresponding bits in the xsave bit vector that
2149 * corresponds to this entry. This is used for both /proc and
2150 * context/signal handling.
2151 */
2152 uint64_t xi_bits;
2153 /*
2154 * The xi_fill function pointer is used to write out the /proc regset
2155 * data (e.g. when a user reads xregs). This is only used for the /proc
2156 * handling. The xi_valid function pointer is used instead to validate a
2157 * given set of data that we've read in, while the xi_set pointer is
2158 * used to actually transform the data in the underlying fpu save area.
2159 */
2160 void (*xi_fill)(const fpu_ctx_t *, const struct xsave_proc_info *,
2161 void *);
2162 bool (*xi_valid)(model_t, const void *);
2163 void (*xi_set)(fpu_ctx_t *, const struct xsave_proc_info *,
2164 uint64_t, const void *);
2165 /*
2166 * The xi_signal_in and xi_signal_out function pointers are used for
2167 * extended context and signal handling information. They are used when
2168 * reading in data from a ucontext_t and writing it out respectively.
2169 * These are only used for context/signal handling.
2170 */
2171 int (*xi_signal_in)(const struct xsave_proc_info *,
2172 const ucontext_t *, const uc_xsave_t *, void *, uintptr_t *,
2173 const uintptr_t);
2174 int (*xi_signal_out)(const struct xsave_proc_info *, fpu_copyout_f,
2175 uc_xsave_t *, const void *fpup, uintptr_t);
2176 } xsave_proc_info_t;
2177
2178 static bool
fpu_proc_xregs_initial_state(const fpu_ctx_t * fpu,uint64_t feats)2179 fpu_proc_xregs_initial_state(const fpu_ctx_t *fpu, uint64_t feats)
2180 {
2181 const struct xsave_state *xs = fpu->fpu_regs.kfpu_u.kfpu_xs;
2182
2183 if ((fpu->fpu_flags & (FPU_EN | FPU_VALID)) == 0) {
2184 return (true);
2185 }
2186
2187 return ((xs->xs_header.xsh_xstate_bv & feats) == 0);
2188 }
2189
2190 static void
fpu_proc_xregs_xcr_fill(const fpu_ctx_t * fpu,const xsave_proc_info_t * info,void * datap)2191 fpu_proc_xregs_xcr_fill(const fpu_ctx_t *fpu, const xsave_proc_info_t *info,
2192 void *datap)
2193 {
2194 prxregset_xcr_t *xcr = datap;
2195
2196 xcr->prx_xcr_xcr0 = xsave_bv_all;
2197 }
2198
2199 /*
2200 * Unlike other instruction portions, we treat the xsave header and the legacy
2201 * XMM section together as both are somewhat tied at the instruction hip. Unlike
2202 * the when dealing with other xsave regions like the ymm and zmm components,
2203 * the initial state here is much more nuanced as it has to match what we actual
2204 * do in the OS and depends on the components that are present.
2205 */
2206 static void
fpu_proc_xregs_xsave_fill(const fpu_ctx_t * fpu,const xsave_proc_info_t * info,void * datap)2207 fpu_proc_xregs_xsave_fill(const fpu_ctx_t *fpu, const xsave_proc_info_t *info,
2208 void *datap)
2209 {
2210 prxregset_xsave_t *prxsave = datap;
2211 const struct xsave_state *xsave = fpu->fpu_regs.kfpu_u.kfpu_xs;
2212 size_t hdr_off;
2213
2214 /*
2215 * In the x87/XMM case, the no device vs. initial state is different
2216 * because the initial state case still wants us to copy the real xsave
2217 * header. It's also worth calling out that the actual illumos default
2218 * fxsave state is not the same as what Intel documents. The main
2219 * difference is in what the x87 FPU control word is. This results in
2220 * the following different cases that we need to think about:
2221 *
2222 * o FPU_EN is not set. So we use the illumos default.
2223 */
2224 if ((fpu->fpu_flags & FPU_EN) == 0) {
2225 bcopy(&avx_initial, prxsave, sizeof (*prxsave));
2226 return;
2227 }
2228
2229 /*
2230 * Convert all the fxsave region while taking into account the validity
2231 * of the xsave bits. The prxregset_xsave_t structure is the same as the
2232 * xsave structure in our ABI and Intel designed the xsave header to
2233 * begin with the 512-bit fxsave structure.
2234 */
2235 fpu_xsave_to_fxsave(xsave, (struct fxsave_state *)prxsave);
2236
2237 /*
2238 * Now that we've dealt with the x87 and XMM state, take care of the
2239 * header.
2240 */
2241 hdr_off = offsetof(prxregset_xsave_t, prx_xsh_xstate_bv);
2242 bcopy((const void *)((uintptr_t)xsave + hdr_off),
2243 (void *)((uintptr_t)prxsave + hdr_off),
2244 sizeof (struct xsave_header));
2245 }
2246
2247 static void
fpu_proc_xregs_std_fill(const fpu_ctx_t * fpu,const xsave_proc_info_t * info,void * datap)2248 fpu_proc_xregs_std_fill(const fpu_ctx_t *fpu, const xsave_proc_info_t *info,
2249 void *datap)
2250 {
2251 if (!fpu_proc_xregs_initial_state(fpu, info->xi_bits)) {
2252 size_t size, off;
2253 const void *xsave_off;
2254
2255 cpuid_get_xsave_info(info->xi_bits, &size, &off);
2256 ASSERT3U(size, ==, info->xi_size);
2257 xsave_off = (void *)((uintptr_t)fpu->fpu_regs.kfpu_u.kfpu_xs +
2258 off);
2259 bcopy(xsave_off, datap, info->xi_size);
2260 }
2261 }
2262
2263 /*
2264 * Users are not allowed to actually set the xcr information this way. However,
2265 * to make it easier for someone to just do a read, modify, write, of the xregs
2266 * data, if it is identical, then we will accept it (and do nothing).
2267 */
2268 static bool
fpu_proc_xregs_xcr_valid(model_t model,const void * datap)2269 fpu_proc_xregs_xcr_valid(model_t model, const void *datap)
2270 {
2271 const prxregset_xcr_t *xcr = datap;
2272
2273 return (xcr->prx_xcr_xcr0 == xsave_bv_all && xcr->prx_xcr_xfd == 0 &&
2274 xcr->prx_xcr_pad[0] == 0 && xcr->prx_xcr_pad[1] == 0);
2275 }
2276
2277 /*
2278 * To match traditional /proc semantics, we do not error if reserved bits of
2279 * MXCSR are set, they will be masked off when writing data. We do not allow
2280 * someone to indicate that they are asking for compressed xsave data, hence the
2281 * check that prx_xsh_comp_bv is zero. Separately, in fpu_proc_xregs_set() we
2282 * check that each component that was indicated in the xstate_bv is actually
2283 * present.
2284 */
2285 static bool
fpu_proc_xregs_xsave_valid(model_t model,const void * datap)2286 fpu_proc_xregs_xsave_valid(model_t model, const void *datap)
2287 {
2288 const prxregset_xsave_t *xsave = datap;
2289 uint64_t rsvd[6] = { 0 };
2290
2291 if (bcmp(rsvd, xsave->prx_xsh_reserved, sizeof (rsvd)) != 0 ||
2292 xsave->prx_xsh_xcomp_bv != 0) {
2293 return (false);
2294 }
2295
2296 if ((xsave->prx_xsh_xstate_bv & ~xsave_bv_all) != 0) {
2297 return (false);
2298 }
2299
2300 return (true);
2301 }
2302
2303 /*
2304 * The YMM, ZMM, and Hi-ZMM registers are all valid when in an LP64 environment
2305 * on x86; however, when operating in ILP32, subsets are reserved. We require
2306 * that all reserved portions are set to zero.
2307 */
2308 static bool
fpu_proc_xregs_ymm_valid(model_t model,const void * datap)2309 fpu_proc_xregs_ymm_valid(model_t model, const void *datap)
2310 {
2311 upad128_t ymm_zero[8];
2312 const prxregset_ymm_t *ymm = datap;
2313
2314 if (model == DATAMODEL_LP64) {
2315 return (true);
2316 }
2317
2318 bzero(&ymm_zero, sizeof (ymm_zero));
2319 return (bcmp(&ymm->prx_ymm[8], &ymm_zero, sizeof (ymm_zero)) == 0);
2320 }
2321
2322 static bool
fpu_proc_xregs_zmm_valid(model_t model,const void * datap)2323 fpu_proc_xregs_zmm_valid(model_t model, const void *datap)
2324 {
2325 upad256_t zmm_zero[8];
2326 const prxregset_zmm_t *zmm = datap;
2327
2328 if (model == DATAMODEL_LP64) {
2329 return (true);
2330 }
2331
2332 bzero(&zmm_zero, sizeof (zmm_zero));
2333 return (bcmp(&zmm->prx_zmm[8], &zmm_zero, sizeof (zmm_zero)) == 0);
2334 }
2335
2336 static bool
fpu_proc_xregs_hi_zmm_valid(model_t model,const void * datap)2337 fpu_proc_xregs_hi_zmm_valid(model_t model, const void *datap)
2338 {
2339 prxregset_hi_zmm_t hi_zmm_zero;
2340 const prxregset_hi_zmm_t *hi_zmm = datap;
2341
2342 if (model == DATAMODEL_LP64) {
2343 return (true);
2344 }
2345
2346 bzero(&hi_zmm_zero, sizeof (hi_zmm_zero));
2347 return (bcmp(hi_zmm, &hi_zmm_zero, sizeof (hi_zmm_zero)) == 0);
2348 }
2349
2350 /*
2351 * The xsave state consists of the first 512 bytes of the XMM state and then the
2352 * xsave header itself. Because of the xsave header, this structure is marked
2353 * with xi_always, so we must always process and consider it.
2354 *
2355 * Semantically if either of the bits around SSE / x87 is set, then we will copy
2356 * the entire thing. This may mean that we end up copying a region that is not
2357 * valid into the save area; however, that should be OK as we still have the
2358 * specific bit flags that indicate what we should consider or not.
2359 *
2360 * There is one additional wrinkle we need to consider and honor here. The CPU
2361 * will load the MXCSR values if the AVX bit is set in an xrstor regardless of
2362 * anything else. So if this is set and we do not have a valid x87/XMM bits
2363 * set then we will set the MXCSR to its default state in case the processor
2364 * tries to load it. For reference see:
2365 *
2366 * o Intel SDM Volume 1: 13.8.1 Standard Form of XRSTOR
2367 * o AMD64 Volume 2: Section 11.5.9 MXCSR State Management
2368 *
2369 * Note, the behavior around this changes depending on whether using the
2370 * compressed xrstor or not. We are not, but it's worth being aware of. We do
2371 * not worry about MXCSR_MASK because the instructions ignore it.
2372 */
2373 static void
fpu_proc_xregs_xsave_set(fpu_ctx_t * fpu,const xsave_proc_info_t * info,uint64_t xsave_bv,const void * datap)2374 fpu_proc_xregs_xsave_set(fpu_ctx_t *fpu, const xsave_proc_info_t *info,
2375 uint64_t xsave_bv, const void *datap)
2376 {
2377 const struct xsave_state *src_xs = datap;
2378 struct xsave_state *targ_xs = fpu->fpu_regs.kfpu_u.kfpu_xs;
2379
2380 if ((xsave_bv & info->xi_bits) != 0) {
2381 bcopy(&src_xs->xs_fxsave, &targ_xs->xs_fxsave,
2382 sizeof (struct fxsave_state));
2383 } else if ((xsave_bv & XFEATURE_AVX) != 0) {
2384 targ_xs->xs_fxsave.fx_mxcsr = SSE_MXCSR_INIT;
2385 }
2386
2387 bcopy(&src_xs->xs_header, &targ_xs->xs_header,
2388 sizeof (struct xsave_header));
2389 targ_xs->xs_fxsave.fx_mxcsr &= sse_mxcsr_mask;
2390 }
2391
2392 static void
fpu_proc_xregs_std_set(fpu_ctx_t * fpu,const xsave_proc_info_t * info,uint64_t xsave_bv,const void * datap)2393 fpu_proc_xregs_std_set(fpu_ctx_t *fpu, const xsave_proc_info_t *info,
2394 uint64_t xsave_bv, const void *datap)
2395 {
2396 size_t size, off;
2397 void *xsave_off;
2398
2399 cpuid_get_xsave_info(info->xi_bits, &size, &off);
2400 xsave_off = (void *)((uintptr_t)fpu->fpu_regs.kfpu_u.kfpu_xs +
2401 off);
2402 bcopy(datap, xsave_off, size);
2403 }
2404
2405 /*
2406 * Dealing with XMM data is a little more annoying in signal context. If UC_FPU
2407 * is set, the ucontext_t's fpregset_t contains a copy of the XMM region. That
2408 * must take priority over an XMM region that showed up in the uc_xsave_t data.
2409 * In the signal copyout code we do not save XMM region in the uc_xsave_t or set
2410 * it as a present component because of it being kept in the fpregset_t. Because
2411 * of this behavior, if we find the XMM (or x87) state bits present, we treat
2412 * that as an error.
2413 *
2414 * The system has always gone through and cleaned up the reserved bits in the
2415 * fxsave state when someone calls setcontext(). Therefore we need to do the
2416 * same thing which is why you see the masking of the mxcsr below.
2417 *
2418 * Finally, there is one last wrinkle here that we need to consider. The
2419 * fpregset_t has two private words which cache the status/exception
2420 * information. Therefore, we well... cheat. Intel has left bytes 464 (0x1d0)
2421 * through 511 (0x1ff) available for us to do what we want. So we will pass this
2422 * through that for the moment to help us pass this state around without too
2423 * much extra allocation.
2424 */
2425 static int
fpu_signal_copyin_xmm(const xsave_proc_info_t * info,const ucontext_t * kuc,const uc_xsave_t * ucx,void * fpup,uintptr_t * udatap,const uintptr_t max_udata)2426 fpu_signal_copyin_xmm(const xsave_proc_info_t *info, const ucontext_t *kuc,
2427 const uc_xsave_t *ucx, void *fpup, uintptr_t *udatap,
2428 const uintptr_t max_udata)
2429 {
2430 struct xsave_state *xsave = fpup;
2431
2432 if ((ucx->ucx_bv & info->xi_bits) != 0) {
2433 return (EINVAL);
2434 }
2435
2436 if ((kuc->uc_flags & UC_FPU) != 0) {
2437 bcopy(&kuc->uc_mcontext.fpregs, &xsave->xs_fxsave,
2438 sizeof (struct fxsave_state));
2439 xsave->xs_fxsave.__fx_ign2[3]._l[0] =
2440 kuc->uc_mcontext.fpregs.fp_reg_set.fpchip_state.status;
2441 xsave->xs_fxsave.__fx_ign2[3]._l[1] =
2442 kuc->uc_mcontext.fpregs.fp_reg_set.fpchip_state.xstatus;
2443 xsave->xs_fxsave.fx_mxcsr &= sse_mxcsr_mask;
2444 xsave->xs_header.xsh_xstate_bv |= info->xi_bits;
2445 }
2446
2447 return (0);
2448 }
2449
2450 static int
fpu_signal_copyin_std(const xsave_proc_info_t * info,const ucontext_t * kuc,const uc_xsave_t * ucx,void * fpup,uintptr_t * udatap,const uintptr_t max_udata)2451 fpu_signal_copyin_std(const xsave_proc_info_t *info, const ucontext_t *kuc,
2452 const uc_xsave_t *ucx, void *fpup, uintptr_t *udatap,
2453 const uintptr_t max_udata)
2454 {
2455 size_t len, xsave_off;
2456 void *copy_to;
2457 struct xsave_state *xsave = fpup;
2458
2459 cpuid_get_xsave_info(info->xi_bits, &len, &xsave_off);
2460 if (*udatap + len > max_udata) {
2461 return (EOVERFLOW);
2462 }
2463
2464 copy_to = (void *)((uintptr_t)fpup + xsave_off);
2465 if (ddi_copyin((void *)*udatap, copy_to, len, 0) != 0) {
2466 return (EFAULT);
2467 }
2468
2469 xsave->xs_header.xsh_xstate_bv |= info->xi_bits;
2470 *udatap = *udatap + len;
2471
2472 return (0);
2473 }
2474
2475 static int
fpu_signal_copyout_std(const xsave_proc_info_t * info,fpu_copyout_f copyfunc,uc_xsave_t * ucx,const void * fpup,uintptr_t udatap)2476 fpu_signal_copyout_std(const xsave_proc_info_t *info, fpu_copyout_f copyfunc,
2477 uc_xsave_t *ucx, const void *fpup, uintptr_t udatap)
2478 {
2479 size_t len, xsave_off;
2480 const void *copy_from;
2481 void *copy_to;
2482 int ret;
2483
2484 cpuid_get_xsave_info(info->xi_bits, &len, &xsave_off);
2485 copy_from = (void *)(uintptr_t)fpup + xsave_off;
2486 copy_to = (void *)(udatap + ucx->ucx_len);
2487
2488 ret = copyfunc(copy_from, copy_to, len);
2489 if (ret != 0) {
2490 return (ret);
2491 }
2492
2493 ucx->ucx_len += len;
2494 ucx->ucx_bv |= info->xi_bits;
2495 return (0);
2496 }
2497
2498 /*
2499 * This table contains information about the extended FPU states and synthetic
2500 * information we create for /proc, the ucontext_t, and signal handling. The
2501 * definition of the xsave_proc_info_t describes how each member is used.
2502 *
2503 * In general, this table is expected to be in the order of the xsave data
2504 * structure itself. Synthetic elements that we create can go anywhere and new
2505 * ones should be inserted at the end. This structure is walked in order to
2506 * produce the /proc and signal handling logic, so changing the order is
2507 * meaningful for those and should not be done lightly.
2508 */
2509 static const xsave_proc_info_t fpu_xsave_info[] = { {
2510 .xi_type = PRX_INFO_XCR,
2511 .xi_size = sizeof (prxregset_xcr_t),
2512 .xi_align = alignof (prxregset_xcr_t),
2513 .xi_always = true,
2514 .xi_bits = 0,
2515 .xi_fill = fpu_proc_xregs_xcr_fill,
2516 .xi_valid = fpu_proc_xregs_xcr_valid
2517 }, {
2518 /*
2519 * The XSAVE entry covers both the xsave header and the %xmm registers.
2520 * Note, there is no signal copyout information for the %xmm registers
2521 * because it is expected that that data is already in the fpregset_t.
2522 */
2523 .xi_type = PRX_INFO_XSAVE,
2524 .xi_size = sizeof (prxregset_xsave_t),
2525 .xi_align = FPU_ALIGN_XMM,
2526 .xi_always = true,
2527 .xi_bits = XFEATURE_LEGACY_FP | XFEATURE_SSE,
2528 .xi_fill = fpu_proc_xregs_xsave_fill,
2529 .xi_set = fpu_proc_xregs_xsave_set,
2530 .xi_valid = fpu_proc_xregs_xsave_valid,
2531 .xi_signal_in = fpu_signal_copyin_xmm
2532 }, {
2533 .xi_type = PRX_INFO_YMM,
2534 .xi_size = sizeof (prxregset_ymm_t),
2535 .xi_align = FPU_ALIGN_YMM,
2536 .xi_always = false,
2537 .xi_bits = XFEATURE_AVX,
2538 .xi_fill = fpu_proc_xregs_std_fill,
2539 .xi_set = fpu_proc_xregs_std_set,
2540 .xi_signal_in = fpu_signal_copyin_std,
2541 .xi_valid = fpu_proc_xregs_ymm_valid,
2542 .xi_signal_out = fpu_signal_copyout_std
2543 }, {
2544 /*
2545 * There is no /proc validation function for the mask registers because
2546 * they are the same in ILP32 / LP64 and there is nothing for us to
2547 * actually validate.
2548 */
2549 .xi_type = PRX_INFO_OPMASK,
2550 .xi_size = sizeof (prxregset_opmask_t),
2551 .xi_align = alignof (prxregset_opmask_t),
2552 .xi_always = false,
2553 .xi_bits = XFEATURE_AVX512_OPMASK,
2554 .xi_fill = fpu_proc_xregs_std_fill,
2555 .xi_set = fpu_proc_xregs_std_set,
2556 .xi_signal_in = fpu_signal_copyin_std,
2557 .xi_signal_out = fpu_signal_copyout_std
2558 }, {
2559 .xi_type = PRX_INFO_ZMM,
2560 .xi_size = sizeof (prxregset_zmm_t),
2561 .xi_align = FPU_ALIGN_ZMM,
2562 .xi_always = false,
2563 .xi_bits = XFEATURE_AVX512_ZMM,
2564 .xi_fill = fpu_proc_xregs_std_fill,
2565 .xi_set = fpu_proc_xregs_std_set,
2566 .xi_valid = fpu_proc_xregs_zmm_valid,
2567 .xi_signal_in = fpu_signal_copyin_std,
2568 .xi_signal_out = fpu_signal_copyout_std
2569 }, {
2570 .xi_type = PRX_INFO_HI_ZMM,
2571 .xi_size = sizeof (prxregset_hi_zmm_t),
2572 .xi_align = FPU_ALIGN_ZMM,
2573 .xi_always = false,
2574 .xi_bits = XFEATURE_AVX512_HI_ZMM,
2575 .xi_fill = fpu_proc_xregs_std_fill,
2576 .xi_set = fpu_proc_xregs_std_set,
2577 .xi_valid = fpu_proc_xregs_hi_zmm_valid,
2578 .xi_signal_in = fpu_signal_copyin_std,
2579 .xi_signal_out = fpu_signal_copyout_std
2580 } };
2581
2582 static bool
fpu_proc_xregs_include(const xsave_proc_info_t * infop)2583 fpu_proc_xregs_include(const xsave_proc_info_t *infop)
2584 {
2585 return (infop->xi_always || (xsave_bv_all & infop->xi_bits) != 0);
2586 }
2587
2588 void
fpu_proc_xregs_info(struct proc * p __unused,uint32_t * ninfop,uint32_t * sizep,uint32_t * dstart)2589 fpu_proc_xregs_info(struct proc *p __unused, uint32_t *ninfop, uint32_t *sizep,
2590 uint32_t *dstart)
2591 {
2592 size_t ret = sizeof (prxregset_hdr_t);
2593 uint32_t ninfo = 0;
2594
2595 ASSERT(fpu_xsave_enabled());
2596
2597 /*
2598 * Right now the set of flags that are enabled in the FPU is global.
2599 * That is, while the pcb's fcpu_ctx_t has the fpu_xsave_mask, the
2600 * actual things that might show up and we care about are all about what
2601 * is set up in %xcr0 which is stored in the global xsave_bv_all. If we
2602 * move to per-process FPU enablement which is likely to come with AMX,
2603 * then this will need the proc_t to look at, hence why we've set things
2604 * up with the unused variable above.
2605 *
2606 * We take two passes through the array. The first is just to count up
2607 * how many informational entries we need.
2608 */
2609 for (size_t i = 0; i < ARRAY_SIZE(fpu_xsave_info); i++) {
2610 if (!fpu_proc_xregs_include(&fpu_xsave_info[i]))
2611 continue;
2612 ninfo++;
2613 }
2614
2615 ASSERT3U(ninfo, >, 0);
2616 ret += sizeof (prxregset_info_t) * ninfo;
2617
2618 for (size_t i = 0; i < ARRAY_SIZE(fpu_xsave_info); i++) {
2619 size_t curphase;
2620 if (!fpu_proc_xregs_include(&fpu_xsave_info[i]))
2621 continue;
2622
2623 curphase = ret % fpu_xsave_info[i].xi_align;
2624 if (ret < fpu_xsave_info[i].xi_align) {
2625 ret = fpu_xsave_info[i].xi_align;
2626 } else if (curphase != 0) {
2627 ret += curphase;
2628 }
2629
2630 if (i == 0 && dstart != NULL) {
2631 *dstart = ret;
2632 }
2633
2634 ret += fpu_xsave_info[i].xi_size;
2635 }
2636
2637 VERIFY3U(ret, <=, UINT32_MAX);
2638 if (sizep != NULL) {
2639 *sizep = ret;
2640 }
2641
2642 if (ninfop != NULL) {
2643 *ninfop = ninfo;
2644 }
2645 }
2646
2647 /*
2648 * This function supports /proc. Because /proc does not have a process locked
2649 * while processing a PCSXREG, this tries to establish an upper bound that we
2650 * will validate later in fpu_proc_xregs_set(). We basically say that if you
2651 * take the maximum xsave size and add 1 KiB that is a good enough approximation
2652 * for the maximum size. The 1 KiB is us basically trying to rationalize the
2653 * overhead of our structures that we're adding right, while being cognisant of
2654 * differing alignments and the fact that the full xsave size is in some cases
2655 * (when supervisor states or features we don't support are present) going to be
2656 * larger than we would need for this.
2657 */
2658 size_t
fpu_proc_xregs_max_size(void)2659 fpu_proc_xregs_max_size(void)
2660 {
2661 VERIFY(fpu_xsave_enabled());
2662 return (cpuid_get_xsave_size() + 0x1000);
2663 }
2664
2665 /*
2666 * This functions supports /proc. In particular, it's meant to perform the
2667 * following:
2668 *
2669 * o Potentially save the current thread's registers.
2670 * o Write out the x86 xsave /proc xregs format data from the xsave data we
2671 * actually have. Note, this can be a little weird for cases where the FPU is
2672 * not actually enabled, which happens for system processes.
2673 */
2674 void
fpu_proc_xregs_get(klwp_t * lwp,void * buf)2675 fpu_proc_xregs_get(klwp_t *lwp, void *buf)
2676 {
2677 uint32_t size, ninfo, curinfo, dstart;
2678 fpu_ctx_t *fpu = &lwp->lwp_pcb.pcb_fpu;
2679 prxregset_hdr_t *hdr = buf;
2680
2681 ASSERT(fpu_xsave_enabled());
2682 fpu_proc_xregs_info(lwp->lwp_procp, &ninfo, &size, &dstart);
2683
2684 /*
2685 * Before we get going, defensively zero out all the data buffer so that
2686 * the rest of the fill functions can assume a specific base.
2687 */
2688 bzero(buf, size);
2689
2690 kpreempt_disable();
2691 if ((fpu->fpu_flags & (FPU_EN | FPU_VALID)) == FPU_EN) {
2692 /*
2693 * This case suggests that thread in question doesn't have a
2694 * valid FPU save state which should only happen when it is on
2695 * CPU. If this is the case, we must ensure that we save the
2696 * current FPU state before proceeding. We also sanity check
2697 * several things here before doing this as using /proc on
2698 * yourself is always exciting. fp_save() will ensure that the
2699 * thread is flagged to go back to being an eager FPU before
2700 * returning back to userland.
2701 */
2702 VERIFY3P(curthread, ==, lwptot(lwp));
2703 VERIFY0(lwptot(lwp)->t_flag & T_KFPU);
2704 fp_save(fpu);
2705 }
2706 kpreempt_enable();
2707
2708 hdr->pr_type = PR_TYPE_XSAVE;
2709 hdr->pr_size = size;
2710 hdr->pr_flags = hdr->pr_pad[0] = hdr->pr_pad[1] = hdr->pr_pad[2] =
2711 hdr->pr_pad[3] = 0;
2712 hdr->pr_ninfo = ninfo;
2713
2714 curinfo = 0;
2715 for (size_t i = 0; i < ARRAY_SIZE(fpu_xsave_info); i++) {
2716 void *startp;
2717 uint32_t phase;
2718
2719 if (!fpu_proc_xregs_include(&fpu_xsave_info[i]))
2720 continue;
2721
2722 phase = dstart % fpu_xsave_info[i].xi_align;
2723 if (dstart < fpu_xsave_info[i].xi_align) {
2724 ASSERT3U(i, !=, 0);
2725 dstart = fpu_xsave_info[i].xi_align;
2726 } else if (phase != 0) {
2727 ASSERT3U(i, !=, 0);
2728 dstart += phase;
2729 }
2730
2731 hdr->pr_info[curinfo].pri_type = fpu_xsave_info[i].xi_type;
2732 hdr->pr_info[curinfo].pri_flags = 0;
2733 hdr->pr_info[curinfo].pri_size = fpu_xsave_info[i].xi_size;
2734 hdr->pr_info[curinfo].pri_offset = dstart;
2735
2736 startp = (void *)((uintptr_t)buf + dstart);
2737 fpu_xsave_info[i].xi_fill(fpu, &fpu_xsave_info[i], startp);
2738 dstart += fpu_xsave_info[i].xi_size;
2739 ASSERT3U(curinfo, <=, ninfo);
2740 curinfo++;
2741 }
2742 }
2743
2744 /*
2745 * We have been asked to set the data in the FPU for a given thread. Our
2746 * prmachdep code has already validated that the raw semantics of the data that
2747 * we have are valid (that is the appropriate sizes, offsets, and flags). We now
2748 * apply additional checking here:
2749 *
2750 * o The xsave structure is present and only valid bits are set.
2751 * o If the xsave component bit-vector is set, we have the corresponding proc
2752 * info item.
2753 * o Read-only items are ignored if and only if they actually match what we
2754 * gave the user mostly as a courtesy to simplify things here.
2755 * o ILP32 processes which can't support many of the regions are allowed to
2756 * have the items here (as we likely gave them to them), but they must be
2757 * zero if they are set.
2758 *
2759 * We take a first pass through all the data, validating it makes sense for the
2760 * FPU. Only after that point do we ensure that we have the FPU data in question
2761 * and then we clobber all the FPU data. Part of the semantics of setting this
2762 * is that we're setting the entire extended FPU.
2763 */
2764 int
fpu_proc_xregs_set(klwp_t * lwp,void * buf)2765 fpu_proc_xregs_set(klwp_t *lwp, void *buf)
2766 {
2767 prxregset_hdr_t *prx = buf;
2768 model_t model = lwp_getdatamodel(lwp);
2769 uint64_t bv_found = 0;
2770 const prxregset_xsave_t *xsave = NULL;
2771 fpu_ctx_t *fpu = &lwp->lwp_pcb.pcb_fpu;
2772
2773 VERIFY(fpu_xsave_enabled());
2774
2775 /*
2776 * First, walk each note info header that we have from the user and
2777 * proceed to validate it. The prmachdep code has already validated that
2778 * the size, type, and offset information is valid, but it has not
2779 * validated the semantic contents of this or if someone is trying to
2780 * write something they shouldn't.
2781 *
2782 * While we walk this, we keep track of where the xsave header is. We
2783 * also track all of the bits that we have found along the way so we can
2784 * match up and ensure that everything that was set has a corresponding
2785 * bit in the xsave bitmap. If we have something in the xsave bitmap,
2786 * but not its corresponding data, then that is an error. However, we
2787 * allow folks to write data regions without the bit set in the xsave
2788 * data to make the read, modify, write process simpler.
2789 */
2790 for (uint32_t i = 0; i < prx->pr_ninfo; i++) {
2791 const prxregset_info_t *info = &prx->pr_info[i];
2792 bool found = false;
2793
2794 for (size_t pt = 0; pt < ARRAY_SIZE(fpu_xsave_info); pt++) {
2795 void *data;
2796 if (info->pri_type != fpu_xsave_info[pt].xi_type)
2797 continue;
2798
2799 found = true;
2800 data = (void *)((uintptr_t)buf + info->pri_offset);
2801 if (fpu_xsave_info[pt].xi_valid != NULL &&
2802 !fpu_xsave_info[pt].xi_valid(model, data)) {
2803 return (EINVAL);
2804 }
2805
2806 if (info->pri_type == PRX_INFO_XSAVE) {
2807 xsave = data;
2808 }
2809 bv_found |= fpu_xsave_info[pt].xi_bits;
2810 break;
2811 }
2812
2813 if (!found) {
2814 return (EINVAL);
2815 }
2816 }
2817
2818 /*
2819 * No xsave data, no dice.
2820 */
2821 if (xsave == NULL) {
2822 return (EINVAL);
2823 }
2824
2825 /*
2826 * If anything is set in the xsave header that was not found as we
2827 * walked structures, then that is an error. The opposite is not true as
2828 * discussed above.
2829 */
2830 if ((xsave->prx_xsh_xstate_bv & ~bv_found) != 0) {
2831 return (EINVAL);
2832 }
2833
2834 /*
2835 * At this point, we consider all the data actually valid. Now we must
2836 * set up this information in the save area. If this is our own lwp, we
2837 * must disable it first. Otherwise, we expect that it is already valid.
2838 * To try to sanitize this, we will defensively zero the entire region
2839 * as we are setting everything that will result in here.
2840 */
2841 kpreempt_disable();
2842 if ((fpu->fpu_flags & (FPU_EN | FPU_VALID)) == FPU_EN) {
2843 /*
2844 * This case suggests that thread in question doesn't have a
2845 * valid FPU save state which should only happen when it is on
2846 * CPU. If this is the case, we explicitly disable the FPU, but
2847 * do not save it before proceeding. We also sanity check
2848 * several things here before doing this as using /proc on
2849 * yourself is always exciting. Unlike fp_save(), fp_free() does
2850 * not signal that an update is required, so we unconditionally
2851 * set that for all threads.
2852 */
2853 VERIFY3P(curthread, ==, lwptot(lwp));
2854 VERIFY0(lwptot(lwp)->t_flag & T_KFPU);
2855 fp_free(fpu);
2856 }
2857 PCB_SET_UPDATE_FPU(&lwp->lwp_pcb);
2858 bzero(lwp->lwp_pcb.pcb_fpu.fpu_regs.kfpu_u.kfpu_generic,
2859 cpuid_get_xsave_size());
2860
2861 for (uint32_t i = 0; i < prx->pr_ninfo; i++) {
2862 const prxregset_info_t *info = &prx->pr_info[i];
2863 bool found = false;
2864
2865 for (size_t pt = 0; pt < ARRAY_SIZE(fpu_xsave_info); pt++) {
2866 const void *data;
2867 if (info->pri_type != fpu_xsave_info[pt].xi_type)
2868 continue;
2869
2870 /*
2871 * Check if we have a set function and if we should
2872 * include this. We may not if this is something like
2873 * PRX_INFO_XCR which is read-only.
2874 *
2875 * We may not include a given entry as it may not have
2876 * been set in the actual xsave state that we have been
2877 * asked to restore, in which case to not break the
2878 * xsaveopt logic, we must leave it in its initial
2879 * state, e.g. zeroed (generally). XMM data initial
2880 * state is not zeroed, but is marked with xi_always to
2881 * help account for this.
2882 */
2883 found = true;
2884 if (fpu_xsave_info[pt].xi_set == NULL)
2885 break;
2886 if (!fpu_xsave_info[pt].xi_always &&
2887 (xsave->prx_xsh_xstate_bv &
2888 fpu_xsave_info[pt].xi_bits) !=
2889 fpu_xsave_info[pt].xi_bits) {
2890 break;
2891 }
2892
2893 data = (void *)((uintptr_t)buf + info->pri_offset);
2894 fpu_xsave_info[pt].xi_set(fpu, &fpu_xsave_info[pt],
2895 xsave->prx_xsh_xstate_bv, data);
2896 }
2897
2898 VERIFY(found);
2899 }
2900 kpreempt_enable();
2901
2902 return (0);
2903 }
2904
2905 /*
2906 * To be included in the signal copyout logic we must have a copy function and
2907 * the bit in question must be included. Note, we don't consult xi_always here
2908 * as that is really part of what is always present for xsave logic and
2909 * therefore isn't really pertinent here because of our custom format. See the
2910 * big theory statement for more info.
2911 */
2912 static bool
fpu_signal_include(const xsave_proc_info_t * infop,uint64_t xs_bv)2913 fpu_signal_include(const xsave_proc_info_t *infop, uint64_t xs_bv)
2914 {
2915 return ((infop->xi_bits & xs_bv) == infop->xi_bits &&
2916 infop->xi_signal_out != NULL);
2917 }
2918
2919 /*
2920 * We need to fill out the xsave related data into the ucontext_t that we've
2921 * been given. We should have a valid user pointer at this point in the uc_xsave
2922 * member. This is much simpler than the copyin that we have. Here are the
2923 * current assumptions:
2924 *
2925 * o This is being called for the current thread. This is not meant to operate
2926 * on an arbitrary thread's state.
2927 * o We cannot assume whether the FPU is valid in the pcb or not. While most
2928 * callers will have just called getfpregs() which saved the state, don't
2929 * assume that.
2930 * o We assume that the user address has the requisite required space for this
2931 * to be copied out.
2932 * o We assume that copyfunc() will ensure we are not copying into a kernel
2933 * address.
2934 *
2935 * For more information on the format of the data, see the 'Signal Handling and
2936 * the ucontext_t' portion of the big theory statement. We copy out all the
2937 * constituent parts and then come back and write out the actual final header
2938 * information.
2939 */
2940 int
fpu_signal_copyout(klwp_t * lwp,uintptr_t uaddr,fpu_copyout_f copyfunc)2941 fpu_signal_copyout(klwp_t *lwp, uintptr_t uaddr, fpu_copyout_f copyfunc)
2942 {
2943 struct fpu_ctx *fpu = &lwp->lwp_pcb.pcb_fpu;
2944 uint64_t xs_bv;
2945 uc_xsave_t ucx;
2946 int ret;
2947
2948 VERIFY3P(curthread, ==, lwptot(lwp));
2949 VERIFY0(lwptot(lwp)->t_flag & T_KFPU);
2950 VERIFY3U(fpu->fpu_flags & FPU_EN, ==, FPU_EN);
2951
2952 if (!fpu_xsave_enabled()) {
2953 return (ENOTSUP);
2954 }
2955
2956 /*
2957 * Unlike when we're dealing with /proc, we can unconditionally call
2958 * fp_save() because this is always called in the context where the lwp
2959 * we're operating on is always the one on CPU (which is what fp_save()
2960 * asserts).
2961 */
2962 fp_save(fpu);
2963
2964 bzero(&ucx, sizeof (ucx));
2965 ucx.ucx_vers = UC_XSAVE_VERS;
2966 ucx.ucx_len += sizeof (uc_xsave_t);
2967
2968 xs_bv = fpu->fpu_regs.kfpu_u.kfpu_xs->xs_header.xsh_xstate_bv;
2969 for (size_t i = 0; i < ARRAY_SIZE(fpu_xsave_info); i++) {
2970 const xsave_proc_info_t *info = &fpu_xsave_info[i];
2971
2972 if (!fpu_signal_include(&fpu_xsave_info[i], xs_bv))
2973 continue;
2974 ret = info->xi_signal_out(info, copyfunc, &ucx,
2975 lwp->lwp_pcb.pcb_fpu.fpu_regs.kfpu_u.kfpu_generic,
2976 uaddr);
2977 if (ret != 0) {
2978 kpreempt_enable();
2979 return (ret);
2980 }
2981 }
2982
2983 /*
2984 * Now that everything has been copied out, we should have an accurate
2985 * value in the uc_xsave_t header and we can copy that out at the start
2986 * of the user data.
2987 */
2988 ret = copyfunc(&ucx, (void *)uaddr, sizeof (ucx));
2989 return (ret);
2990 }
2991
2992 /*
2993 * Here we've been given a ucontext_t which potentially has a user pointer to
2994 * xsave state that we've copied out previously. In this case we need to do the
2995 * following, assuming UC_XSAVE is present:
2996 *
2997 * o Copy in our header and validate it.
2998 * o Allocate an fpu context to use as a holding ground for all this data.
2999 * o If UC_FPU is set, override the xsave structure with the saved XMM state,
3000 * clear UC_FPU, and make sure that the correct xsave_bv bits are set.
3001 *
3002 * Currently we always allocate the additional state as a holding ground for the
3003 * FPU. What we're copying in may not be valid and we don't want to clobber the
3004 * existing FPU state or deal with merging it until we believe it's reasonable
3005 * enough. The proc_t is here to set us up for when we have per-process settings
3006 * in the extended feature disable MSRs.
3007 */
3008 int
fpu_signal_copyin(klwp_t * lwp,ucontext_t * kuc)3009 fpu_signal_copyin(klwp_t *lwp, ucontext_t *kuc)
3010 {
3011 uc_xsave_t ucx;
3012 uint64_t bv;
3013 uintptr_t data, max_data;
3014 void *fpu;
3015 proc_t *p = lwp->lwp_procp;
3016 size_t ksize;
3017
3018 /*
3019 * Because this has been opaque filler and the kernel has never
3020 * historically looked at it, we don't really care about the uc_xsave
3021 * pointer being garbage in the case that the flag is not set. While
3022 * this isn't perhaps the most sporting choice in some cases, this is on
3023 * the other hand, pragmatic.
3024 */
3025 if ((kuc->uc_flags & UC_XSAVE) != 0) {
3026 if (kuc->uc_xsave == 0) {
3027 return (EINVAL);
3028 }
3029
3030 if (!fpu_xsave_enabled()) {
3031 return (ENOTSUP);
3032 }
3033 } else {
3034 return (0);
3035 }
3036
3037 if (ddi_copyin((const void *)kuc->uc_xsave, &ucx, sizeof (ucx), 0) !=
3038 0) {
3039 return (EFAULT);
3040 }
3041
3042 ksize = cpuid_get_xsave_size();
3043 if (ucx.ucx_vers != UC_XSAVE_VERS || ucx.ucx_len < sizeof (ucx) ||
3044 ucx.ucx_len > ksize ||
3045 (ucx.ucx_bv & ~xsave_bv_all) != 0 ||
3046 (uintptr_t)p->p_as->a_userlimit - ucx.ucx_len <
3047 (uintptr_t)kuc->uc_xsave) {
3048 return (EINVAL);
3049 }
3050
3051 /*
3052 * OK, our goal right now is to recreate a valid xsave_state structure
3053 * that we'll ultimately end up having to merge with our existing one in
3054 * the FPU save state. The reason we describe this as a merge is to help
3055 * future us when we want to retain supervisor state which will never be
3056 * part of userland signal state. The design of the userland signal
3057 * state is basically to compress it as much as we can. This is done for
3058 * two reasons:
3059 *
3060 * 1) We currently consider this a private interface.
3061 * 2) We really want to minimize the actual amount of stack space we
3062 * use as much as possible. Most applications aren't using AVX-512
3063 * right now, so doing our own compression style is worthwhile. If
3064 * libc adopts AVX-512 routines, we may want to change this.
3065 *
3066 * On the allocation below, our assumption is that if a thread has taken
3067 * a signal, then it is likely to take a signal again in the future (or
3068 * be shortly headed to its demise). As such, when that happens we will
3069 * leave the allocated signal stack around for the process. Most
3070 * applications don't allow all threads to take signals, so this should
3071 * hopefully help amortize the cost of the allocation.
3072 */
3073 max_data = (uintptr_t)kuc->uc_xsave + ucx.ucx_len;
3074 data = (uintptr_t)kuc->uc_xsave + sizeof (ucx);
3075 bv = ucx.ucx_bv;
3076 if (lwp->lwp_pcb.pcb_fpu.fpu_signal == NULL) {
3077 lwp->lwp_pcb.pcb_fpu.fpu_signal =
3078 kmem_cache_alloc(fpsave_cachep, KM_SLEEP);
3079 }
3080 fpu = lwp->lwp_pcb.pcb_fpu.fpu_signal;
3081
3082 /*
3083 * Unconditionally initialize the memory we get in here to ensure that
3084 * it is in a reasonable state for ourselves. This ensures that unused
3085 * regions are mostly left in their initial state (the main exception
3086 * here is the x87/XMM state, but that should be OK). We don't fill in
3087 * the initial xsave state as we expect that to happen as part of our
3088 * processing.
3089 */
3090 bzero(fpu, ksize);
3091
3092 for (size_t i = 0; i < ARRAY_SIZE(fpu_xsave_info); i++) {
3093 int ret;
3094 const xsave_proc_info_t *info = &fpu_xsave_info[i];
3095 if (!info->xi_always && (info->xi_bits & bv) == 0)
3096 continue;
3097 bv &= ~info->xi_bits;
3098
3099 if (info->xi_signal_in == NULL)
3100 continue;
3101 ret = info->xi_signal_in(info, kuc, &ucx, fpu, &data, max_data);
3102 if (ret != 0) {
3103 return (ret);
3104 }
3105 }
3106 ASSERT0(bv);
3107
3108 /*
3109 * As described in the big theory statement section 'Signal Handling and
3110 * the ucontext_t', we always remove UC_FPU from here as we've taken
3111 * care of reassembling it ourselves.
3112 */
3113 kuc->uc_flags &= ~UC_FPU;
3114 kuc->uc_xsave = (uintptr_t)fpu;
3115
3116 return (0);
3117 }
3118
3119 /*
3120 * This determines the size of the signal stack that we need for our custom form
3121 * of the xsave state.
3122 */
3123 size_t
fpu_signal_size(klwp_t * lwp)3124 fpu_signal_size(klwp_t *lwp)
3125 {
3126 struct fpu_ctx *fpu = &lwp->lwp_pcb.pcb_fpu;
3127 size_t len = sizeof (uc_xsave_t);
3128 uint64_t xs_bv;
3129
3130 VERIFY3P(curthread, ==, lwptot(lwp));
3131 VERIFY0(lwptot(lwp)->t_flag & T_KFPU);
3132 VERIFY3U(fpu->fpu_flags & FPU_EN, ==, FPU_EN);
3133
3134 if (!fpu_xsave_enabled()) {
3135 return (0);
3136 }
3137
3138 kpreempt_disable();
3139 if ((fpu->fpu_flags & (FPU_EN | FPU_VALID)) == FPU_EN) {
3140 fp_save(fpu);
3141 }
3142
3143 xs_bv = fpu->fpu_regs.kfpu_u.kfpu_xs->xs_header.xsh_xstate_bv;
3144 for (size_t i = 0; i < ARRAY_SIZE(fpu_xsave_info); i++) {
3145 size_t comp_size;
3146
3147 if (!fpu_signal_include(&fpu_xsave_info[i], xs_bv))
3148 continue;
3149
3150 cpuid_get_xsave_info(fpu_xsave_info[i].xi_bits, &comp_size,
3151 NULL);
3152 len += comp_size;
3153 }
3154
3155 kpreempt_enable();
3156 return (len);
3157 }
3158
3159 /*
3160 * This function is used in service of restorecontext() to set the specified
3161 * thread's extended FPU state to the passed in data. Our assumptions at this
3162 * point from the system are:
3163 *
3164 * o Someone has already verified that the actual xsave header is correct.
3165 * o Any traditional XMM state that causes a #gp has been clamped.
3166 * o That data is basically the correct sized xsave state structure. Right now
3167 * that means it is not compressed and follows the CPUID-based rules for
3168 * constructing and laying out data.
3169 * o That the lwp argument refers to the current thread.
3170 *
3171 * Our primary purpose here is to merge the current FPU state with what exists
3172 * here. Right now, "merge", strictly speaking is just "replace". We can get
3173 * away with just replacing everything because all we currently save are user
3174 * states. If we start saving kernel states in here, this will get more nuanced
3175 * and we will need to be more careful about how we store data here.
3176 */
3177 void
fpu_set_xsave(klwp_t * lwp,const void * data)3178 fpu_set_xsave(klwp_t *lwp, const void *data)
3179 {
3180 struct fpu_ctx *fpu = &lwp->lwp_pcb.pcb_fpu;
3181 uint32_t status, xstatus;
3182 struct xsave_state *dst_xsave;
3183
3184 VERIFY(fpu_xsave_enabled());
3185 VERIFY3P(curthread, ==, lwptot(lwp));
3186 VERIFY0(lwptot(lwp)->t_flag & T_KFPU);
3187 ASSERT3U(fpu->fpu_flags & FPU_EN, ==, FPU_EN);
3188
3189 /*
3190 * We use fp_save() here rather than a stock fpdisable() so we can
3191 * attempt to honor our invariants that when the thread state has been
3192 * saved, the valid flag is set, even though we're going to be
3193 * overwriting it shortly. If we just called fpdisable() then we would
3194 * basically be asking for trouble.
3195 *
3196 * Because we are modifying the state here and we don't want the system
3197 * to end up in an odd state, we are being a little paranoid and
3198 * disabling preemption across this operation. In particular, once the
3199 * state is properly tagged with FPU_VALID, there should be no other way
3200 * that this thread can return to userland and get cleared out because
3201 * we're resetting its context; however, we let paranoia win out.
3202 */
3203 kpreempt_disable();
3204 if ((fpu->fpu_flags & (FPU_EN | FPU_VALID)) == FPU_EN) {
3205 fp_save(fpu);
3206 }
3207
3208 bcopy(data, lwp->lwp_pcb.pcb_fpu.fpu_regs.kfpu_u.kfpu_generic,
3209 cpuid_get_xsave_size());
3210 dst_xsave = lwp->lwp_pcb.pcb_fpu.fpu_regs.kfpu_u.kfpu_generic;
3211 status = dst_xsave->xs_fxsave.__fx_ign2[3]._l[0];
3212 xstatus = dst_xsave->xs_fxsave.__fx_ign2[3]._l[1];
3213 dst_xsave->xs_fxsave.__fx_ign2[3]._l[0] = 0;
3214 dst_xsave->xs_fxsave.__fx_ign2[3]._l[1] = 0;
3215
3216 /*
3217 * These two status words are information that the kernel itself uses to
3218 * track additional information and is part of the traditional fpregset,
3219 * but is not part of our xregs information. Because we are setting this
3220 * state, we leave it up to the rest of the kernel to determine whether
3221 * this came from an fpregset_t or is being reset to the default of 0.
3222 */
3223 fpu->fpu_regs.kfpu_status = status;
3224 fpu->fpu_regs.kfpu_xstatus = xstatus;
3225
3226 fpu->fpu_flags |= FPU_VALID;
3227 PCB_SET_UPDATE_FPU(&lwp->lwp_pcb);
3228 kpreempt_enable();
3229 }
3230
3231 /*
3232 * Convert the current FPU state to the traditional fpregset_t. In the 64-bit
3233 * kernel, this is just an fxsave_state with additional values for the status
3234 * and xstatus members.
3235 *
3236 * This has the same nuance as the xregs cases discussed above, but is simpler
3237 * in that we only need to handle the fxsave state, but more complicated because
3238 * we need to check our save mechanism.
3239 */
3240 void
fpu_get_fpregset(klwp_t * lwp,fpregset_t * fp)3241 fpu_get_fpregset(klwp_t *lwp, fpregset_t *fp)
3242 {
3243 struct fpu_ctx *fpu = &lwp->lwp_pcb.pcb_fpu;
3244
3245 kpreempt_disable();
3246 fp->fp_reg_set.fpchip_state.status = fpu->fpu_regs.kfpu_status;
3247 fp->fp_reg_set.fpchip_state.xstatus = fpu->fpu_regs.kfpu_xstatus;
3248
3249 if ((fpu->fpu_flags & (FPU_EN | FPU_VALID)) == FPU_EN) {
3250 /*
3251 * If we're requesting the fpregs of a thread that isn't
3252 * currently valid and isn't the one that we're executing, then
3253 * we consider getting this information to be a best-effort and
3254 * we will not stop the thread in question to serialize it,
3255 * which means possibly getting stale data. This is the
3256 * traditional semantics that the system has used to service
3257 * this for /proc.
3258 */
3259 if (curthread == lwptot(lwp)) {
3260 VERIFY0(lwptot(lwp)->t_flag & T_KFPU);
3261 fp_save(fpu);
3262 }
3263 }
3264
3265 /*
3266 * If the FPU is not enabled and the state isn't valid (due to someone
3267 * else setting it), just copy the initial state.
3268 */
3269 if ((fpu->fpu_flags & (FPU_EN | FPU_VALID)) == 0) {
3270 bcopy(&sse_initial, fp, sizeof (sse_initial));
3271 kpreempt_enable();
3272 return;
3273 }
3274
3275 /*
3276 * Given that we have an enabled FPU, we must look at the type of FPU
3277 * save mechanism to clean this up. In particular, while we can just
3278 * copy the save area with FXSAVE, with XSAVE we must carefully copy
3279 * only the bits that are valid and reset the rest to their default
3280 * state.
3281 */
3282 switch (fp_save_mech) {
3283 case FP_FXSAVE:
3284 bcopy(fpu->fpu_regs.kfpu_u.kfpu_fx, fp,
3285 sizeof (struct fxsave_state));
3286 break;
3287 case FP_XSAVE:
3288 fpu_xsave_to_fxsave(fpu->fpu_regs.kfpu_u.kfpu_xs,
3289 (struct fxsave_state *)fp);
3290 break;
3291 default:
3292 panic("Invalid fp_save_mech");
3293 }
3294
3295 kpreempt_enable();
3296 }
3297
3298 /*
3299 * This is a request to set the ABI fpregset_t into our actual hardware state.
3300 * In the 64-bit kernel the first 512 bytes of the fpregset_t is the same as the
3301 * 512-byte fxsave area.
3302 */
3303 void
fpu_set_fpregset(klwp_t * lwp,const fpregset_t * fp)3304 fpu_set_fpregset(klwp_t *lwp, const fpregset_t *fp)
3305 {
3306 struct fpu_ctx *fpu = &lwp->lwp_pcb.pcb_fpu;
3307
3308 kpreempt_disable();
3309 if ((fpu->fpu_flags & (FPU_EN | FPU_VALID)) == FPU_EN) {
3310 /*
3311 * We always save the entire FPU. This is required if we're
3312 * using xsave. If we're using fxsave, we could skip the
3313 * 512-byte write and instead just disable the FPU since we'd be
3314 * replacing it all. For now we don't bother with more
3315 * conditional logic.
3316 */
3317 VERIFY3P(curthread, ==, lwptot(lwp));
3318 VERIFY0(lwptot(lwp)->t_flag & T_KFPU);
3319 fp_save(fpu);
3320 }
3321
3322 fpu->fpu_regs.kfpu_xstatus = fp->fp_reg_set.fpchip_state.xstatus;
3323 fpu->fpu_regs.kfpu_status = fp->fp_reg_set.fpchip_state.status;
3324 switch (fp_save_mech) {
3325 case FP_FXSAVE:
3326 bcopy(fp, fpu->fpu_regs.kfpu_u.kfpu_fx,
3327 sizeof (struct fxsave_state));
3328 break;
3329 case FP_XSAVE:
3330 bcopy(fp, fpu->fpu_regs.kfpu_u.kfpu_xs,
3331 sizeof (struct fxsave_state));
3332 fpu->fpu_regs.kfpu_u.kfpu_xs->xs_header.xsh_xstate_bv |=
3333 XFEATURE_LEGACY_FP | XFEATURE_SSE;
3334 break;
3335 default:
3336 panic("Invalid fp_save_mech");
3337 }
3338
3339 fpu->fpu_flags |= FPU_VALID;
3340 PCB_SET_UPDATE_FPU(&lwp->lwp_pcb);
3341 kpreempt_enable();
3342 }
3343