views:

257

answers:

5

The following line printed output as 4 whereas I was expecting 0.

 printk(KERN_INFO "size of spinlock_t  %d\n", sizeof(spinlock_t));

I tried this on a system with single cpu. No debugging flags are enabled while building kernel like CONFIG_DEBUG_SPINLOCK or CONFIG_DEBUG_LOCK_ALLOC. According to kernel header files, it should be zero but output is not consistent with it, any guesses ?

+2  A: 

The sizeof a type can never be zero.

Baffe Boyois
Yes it can be, take a structure with no members, it will print zero.
vinit dhatrak
The article he just pointed to gives you chapter and verse in the C++ Standard, saying this is not the case. If you have a compiler that gives you 0 for an empty structure, it's violating the Standard. +1, Baffe.
Warren Young
ah ok ... this is C++ standard and I am using C as this is linux kernel code. In C, size of empty struct is zero.
vinit dhatrak
A test confirms a result of 1 for C++ and 0 for C using GCC 4.2.4
Duck
+1 Duck, I got same result.
vinit dhatrak
The claim in the answer is generally correct, but is irrelevant here. ISO C prohibits structs with no members, so we're in language extension territory (in this case gcc) anyway. And obviously if gcc permits empty structs in C, it doesn't have to follow the C++ rules for them.
Pavel Minaev
+4  A: 

The best guess I have is that although you have a single CPU, the kernel is still compiled with CONFIG_SMP set.

caf
you are correct, kernel is compiled with CONFIG_SMP.
vinit dhatrak
+1  A: 

From what I remember, spinlock_t is enabled only in CONFIG_SMP is set i.e it is disabled on uniprocessor machines. Therefore, you might be getting some garbage.

Algorist
+1  A: 

The spinlock_t is always a structure and it contains a rawlock_t irrespective of kernel build options. SMP and kernel preemption can add extra fields to the spinlock_t, but spinlock_t is always a concrete type with a none zero size. The compiler needs the spinlock_t to resolve to a real valid C type otherwise it wouldn't compile any structure that incorporated a spinlock. If there is no preemption or SMP then its the spinlock operations that are NULL not the structure. To support a zero sized structure would be very messy, every reference would need to be via pre-processors macros so spinlock_t ends up being an int (on x86 at least), there isn't any point going for an variable whose size is less than 4 bytes because the compiler is likely to pad any variable to maintain alignment.

Andrew Roca
A: 

This depends on your architecture. If you look at include/linux/spinlock_types_up.h, you can see that there are indeed times where it will come out to 0 size.

Jeff