Re: Issues with capability bits and meta-data in kdbus

Linus Torvalds
2015-04-24T18:00:53Z

On Fri, Apr 24, 2015 at 10:52 AM, Linus Torvalds
<torvalds@linux-foundation.org> wrote:
>
> So even today, by all means make your protocols or disk images use
> big-endian byte formats. But do it unconditionally. Don't make the
> mistake of encoding the byte order as part of the data, and then
> dynamically switching things (or not) around.

Side note: even if you pick the "wrong" byte order, an unconditional
byte ordering choice can often avoid the bswap, just because many
operations are byte order independent.

For example, you can still test specific bits in bitfields etc. If you
have a constant mask you want to check, instead of converting the
field to the CPU byte order at runtime, convert that constant _mask_
to the data byte order at compile-time, and use it without any dynamic
byte swapping of the data.

And generally, avoid byte swapping until you really need it. Some
people seem to think that if the data is in one particular byte order
on disk, you should byteswap as you read it in, and as you write it
out. No, it's often best to actually keep it in the original format,
and only byte swap when actually using the value. Then you can mmap
files and not generate extra copies, or - as per above - you may be
able to structure your code to never need the byte swap at all.

So this is why (for example) the kernel byte swapping helper functions
do odd things like this:

#define __swab32(x) \
(__builtin_constant_p((__u32)(x)) ? \
___constant_swab32(x) : \
__fswab32(x))

just because the "___constant_swab32()" is designed to do everything
at compile-time.

Linus