Subject: Re: Bitfields and kernel
To: der Mouse <mouse@Rodents.Montreal.QC.CA>
From: Brian C. Grayson <>
List: tech-kern
Date: 09/30/1999 15:03:55
On Wed, Sep 29, 1999 at 12:47:15PM -0400, der Mouse wrote:
> > typedef struct {
> >   unsigned int reserved0_12:13;
> >   unsigned int pow:1;
> >   unsigned int reserved14:1;
> >   unsigned int ile:1;
> >   ...
> > } reg_msr_t;
> > reg_msr_t msr;
> > msr.pow = 1;
> > msr.ile = 0;
> The biggest problem with this, aside from the nonportability various
> people have commented on, is that it becomes impossible to manipulate
> multiple bits at the same time.  This can be important for setting and
> clearing bits and can be useful when testing bits.

  For setting multiple bits, using bitfields will work, and gcc optimizes
it as tight as any hand-coded or (1<<30)|(1<<25) code -- into a
single ori, in PowerPC-speak.  I see no inherent reason why gcc
can't do as good of a job optimizing bitfield manipulations as
it can #define'd bitmask ops.

  For testing multiple bits, to me it is more clear to say
if ((msr.pow == 1) && (msr.ile == 0))
if ((msr&POW_BIT) && !(msr&ILE_BIT))
if ((msr&POW_BIT == POW_BIT) && (msr&ILE_BIT == 0))

  And it's definitely handy when you have 3-bit fields that are
treated like a 3-bit number, as someone else mentioned.

  It looks like there's no clear consensus :), so I'll just do
what I like for private userland code, and I'll try to match
the current style whenever doing any NetBSD devel.