Re: include/asm-generic/unaligned.h:119:16: sparse: sparse: cast truncates bits from constant value (aa01a0 becomes a0)

From: Luc Van Oostenryck
Date: Sun Jan 07 2024 - 08:03:48 EST


On Sat, Jan 06, 2024 at 09:54:05PM -0800, Linus Torvalds wrote:
> On Sat, 6 Jan 2024 at 16:42, Dmitry Torokhov <dmitry.torokhov@xxxxxxxxx> wrote:
> >
> > This is not really a kernel/driver bug, just sparse being over-eager
> > with truncation detection. I wonder if we could make sparse skip this
> > check on forced casts like this:
>
> No, please don't.
>
> Just face the fact that using integer casts to mask bits off is a bad idea.
>
> ...
>
> The *natural* thing to do is to simply make the masking itself be
> explicit - not the cast. IOW, just write it as
>
> *p++ = (val >> 16) & 0xff;
> *p++ = (val >> 8) & 0xff;
> *p++ = val & 0xff;
>
> ...
>
> And while the code is a bit more to read, I think it is actually to
> some degree more obvious to a human too what is going on.


I fully agree.

It's kinda sad is that there is more than 800 occurrences of this
"cast truncates bits from constant value" warning and almost all of
them are of the kind:
"a 32bit constant must be written in 2 steps via 16bit IO registers"

In these cases, no bits are lost, they're just written in the other write,
and real problems, when present, are drown/lost into these 800 harmless ones.
It's in fact the 4th most common warning in the kernel, the top 10 being:
2858 incorrect type in assignment (different base types)
2715 cast to restricted type
923 incorrect type in argument (different address spaces)
818 cast truncates bits from constant value
739 restricted type degrades to integer
549 context imbalance - unexpected unlock
500 symbol was not declared. Should it be static?
407 cast removes address space '__iomem' of expression
344 incompatible types in comparison expression (different address spaces)
323 context imbalance - different lock contexts for basic block

-- Luc