On Mon, Mar 23, 2026 at 04:39:58PM +0000, Andrew Cooper wrote:
> On 23/03/2026 5:55 am, Lai, Yi wrote:
> > On Fri, Mar 20, 2026 at 08:50:54AM -0700, Dave Hansen wrote:
> >> On 3/20/26 08:47, Andrew Cooper wrote:
> >>>> First, CPUID doesn't tell you if FRED is in use. Is it even on by
> >>>> default yet? There might not be a better way to do this than checking
> >>>> CPUID, but checking CPUID is imprecise at best.
> >>> A reliable way to distinguish IDT and FRED mode is to:
> >>>
> >>> 1) Load $3 into %fs (x86_64) or %gs (i386) (i.e. whichever isn't thread
> >>> local stoage)
> >>> 2) execute a breakpoint, ignore the signal
> >>> 3) Look to see whether %fs/%gs holds 3 or 0
> >>>
> >>> IRET has a fun behaviour where it zeroes NULL selectors even if they had
> >>> a non-zero RPL.
> >>>
> >>> ERETU doesn't do this; Andy Luto and I asked for this minor information
> >>> leak to be removed, and Intel agreed as it served no purpose anyone
> >>> could identify.
> >>>
> >>> As a consequence, you can use it to determine whether the kernel used
> >>> IRET or ERET to return back to userspace.
> >> I was thinking of just grepping /proc/cpuinfo for "fred", but that
> >> sounds much more fun! :)
> > Thank you both for the review and suggestions. The behavioral difference
> > between IRET and ERETU is a more robust way to detect FRED activation
> > than checking CPUID.
> >
> > How about the following implementation to add a helper function to
> > determine if FRED is enabled at runtime:
> >
> > static void empty_handler(int sig, siginfo_t *info, void *ctx_void)
> > {
> > }
> >
> > static bool is_fred_enabled(void)
> > {
> > unsigned short gs_val;
> >
> > sethandler(SIGTRAP, empty_handler, 0);
>
> What about setting SIG_IGN instead?
>
I tested setting signal(SIGTRAP, SIG_IGN), but it causes the test to
terminate with a trace/breakpoint trap (core dump) when the 'int3'
instruction initiates the hardware exception. Therefore, I will keep the
empty_handler() implementation to ensure it can safely resume execution.
> >
> > /*
> > * Distinguish IDT and FRED mode by loading GS with a non-zero RPL and
> > * triggering an exception:
> > * IDT (IRET) clears RPL bits of NULL selectors.
> > * FRED (ERETU) preserves them.
> > *
> > * If GS is loaded with 3 (Index=0, RPL=3), and we trigger an exception:
> > * Legacy should restore GS as 0.
> > * FRED should preserve GS as 3.
> > */
> > asm volatile(
> > "mov $3, %%ax\n\t"
> > "mov %%ax, %%gs\n\t"
> > "int3\n\t"
> > "mov %%gs, %%ax\n\t"
> > "mov %%ax, %0\n\t"
> > : "=r" (gs_val)
> > :
> > : "ax", "memory"
> > );
>
> asm volatile (
> "mov %[rpl3], %%gs\n\t"
> "int3\n\t"
> "mov %%gs, %[res]"
> : [res] "=r" (gs_val)
> : [rpl3] "r" (3));
>
> No need for any clobbers. Let the compiler do the hard work for you.
>
Thank you for the improved assembly block and it's indeed cleaner. I
will adopt your suggestion and send out v2.
Regards,
Yi Lai
> ~Andrew