Re: [RFC 6/8] x86_64/bug: Implement __WARN_printf()

David Laight
2025-06-03T22:23:15Z

On Tue, 3 Jun 2025 15:04:55 +0200
Peter Zijlstra <peterz@infradead.org> wrote:

> On Mon, Jun 02, 2025 at 04:10:16PM -0700, Linus Torvalds wrote:
> > On Mon, 2 Jun 2025 at 14:57, Peter Zijlstra <peterz@infradead.org> wrote:
> > >
> > > So if I stuff the asm macro in a global asm() block then GCC ends up
> > > looking like so:
> >
> > Better, but as then the clang thing looks like a horrendous disaster.
> >
> > How about we simply make this all *code* instead of playing games with
> > register numbers?
> >
> > Why not just push the arguments by hand on the stack, and make that be
> > the interface? A 'push %reg' is like a byte or two. And you'd do it in
> > the cold section, so nobody cares.
> >
> > And the asm would look somewhat sane, instead of being crazy noise due
> > to crazy macros.
> >
> > Or so I imagine, because I didn't actually try it.
>
> Yeah, I can make that work.
>
> I've been trying to make __WARN_printk() (or similar) do a tail-call to
> a "UD2; RET;" stub. But doing printk() in a function makes GCC generate
> wild code that refuses to actually tail-call :/
>
> The next crazy idea was to make a variant of __WARN_printk() that takes
> a struct bug_entry * as first argument such that it has access to the
> bug entry and then take the trap on the way out (while keeping the
> pointer in the first argument) and then have the trap handler complete
> things.
>
> That way it would all 'just work'. Except I can't seem to force GCC to
> emit that tail-call :-(
>
> I'll prod at it some more.

How about a slightly less generic macro, something that could be:
#define WARN_IF(a, op, b, msg) \
if (unlikely((a) op (b)) { \
printf("WARN: %s (%x " #op " %x)\n", \
msg ? msg : "(" #a ") " #op " (" #b ")", (a), (b)); \
}
but could just be:
if (unlikely((a) op (b)) {
asm( " ud2; cmp %0, %1"
" .asciz msg; .asciz #op"
:: "r" (a), "r" (b));
}
So a ud2 followed by a reg-reg compare (should be REX/D16 prefix followed
by '3[89ab] /r') and two strings (literals or addresses).
With a suitable exception table entry.

That saves the problem of a generic printf format while still giving the
values of the variables associated with the failing test (for simple tests).
It should also avoid destroying register assignment for the rest of the
function.

If gcc refuses to do a jump for the 'if (unlikely...))' try adding an 'else'
clause containing an asm comment.
I've done that in the past to convert a backwards conditional jump (predicted taken)
into a forwards jump (predicted not taken) to an unconditional jump to the
actual target.
(I had a very tight clock limit for the 'worst case' path.)

David