Linux Kernel Architecture

(Jacob Rumans) #1
Mauerer app03.tex V1 - 09/04/2008 6:11pm Page 1203

Appendix C: Notes on C


be specified in the structure definition to prevent the compiler from introducing pad bytes. Naturally,
the possibly unaligned components of this structure must then be accessed using the aforementioned
functions.

Bytes are always aligned by definition — their width is 1 byte, and every address is divisible by one.

Generic Alignment


Sometimes, it is necessary to fulfill additional alignment criteria besides natural alignment — such as
when a data structure must be aligned along cache lines, but there are numerous other applications in
the memory management implementation. The kernel provides the macroALIGN(x,y)for this purpose:
It returns the minimum alignment required to align the datumxonybyte boundaries. Some examples of
how to use this macro were previously presented in Table 3-9.

C.2.4 Bit Arithmetic


Bit operations are part of the standard kernel repertoire and are frequently used in all subsystems. In
the past, operations of this kind were often employedin userspace programs because some things could
be done faster than with standard C resources. Now that the optimization mechanisms of compilers
have become more sophisticated, bit operations are hardly ever needed. However, as an extremely
performance-critical program, the kernel is an exception. Similarly, bit operations are able to achieve
certain effects that are not possible using other statements.

intnumbers can be held in memory as a bit string with 32 entries. Similarly,unsigned longvalues can
be regarded as bit strings with 32 or 64 positions — depending on the word length of the processor.
However, by default, C provides no facilities for accessing the individual bits of a variable. This is why
the kernel has to resort to a number of tricks.

Two basic operations with integers are left and right shift, represented by the<<and>>operators. The
argument specifies how many positions all bits in the string are to be moved left or right. For example,a
=a>>3moves all bits ofathree positions to the right.

Because then-th bit in a bit string has the value 2nand a shift operation moves all bit positions one
to the left or one to the right, the value of a bit changes to 2n±^1. This is the equivalent of dividing or
multiplying the expression by 2. Likewise, ann-fold shift is the same as a division or multiplication by 2n
because this equates tonconsecutive shift operations. Multiplication and division by the power of two
can therefore be replaced with bit shifts for integer numbers as the following example demonstrates (like
all other arithmetic operators, shift operators can also be used in the form<<=or>>=to link the shift with
assignment of a new value to the old variable):

int main() {
unsigned int val = 1;
unsigned int count;

for (count = 0; count <= 10; count++) {
printf("count, val: %u, %u\n", count, val);
val <<= 1;
}
}
Free download pdf