首先我们来分析一下定义在cpumask.h中 结构体cpumask_t
typedef struct cpumask { DECLARE_BITMAP(bits, NR_CPUS); } cpumask_t;
#define DECLARE_BITMAP(name,bits) \
unsigned long name[BITS_TO_LONGS(bits)]
#define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, BITS_PER_BYTE * sizeof(long))
#define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d))
假设我们当前使用的cpu核数为24,即NR_CPUS=24,sizeof(long)=8,BITS_PER_BYTE=8,则在DIV_ROUND_UP(n,d)中, n = 24,d=64,宏的展开结果为(24+64-1)/64 = 1,DECLARE_BITMAP(name,bits) 展开后即为 unsigned long name[1],最后cpumask即为:
struct cpumask{
unsigned long bits[1];
};
绕了好大一个圈,就定义了一个unsigned long bits[1],想想就明白了,64位机器上,一个long有64个bit,而只有24个核,所以一个long足够表示了。在linux内核中,cpu_possible_mask 位图,用来表示系统中的CPU,每颗处理器对应其中一位,
cpu_online_mask 位图,用来当前处于工作状态的CPU,每颗处理器对应其中一位
接下来,分析cpu_bit_map
/*
* cpu_bit_bitmap[] is a special, "compressed" data structure that
* represents all NR_CPUS bits binary values of 1<<nr.
*
* It is used by cpumask_of() to get a constant address to a CPU
* mask value that has a single bit set only.
*/
/* cpu_bit_bitmap[0] is empty - so we can back into it */
#define MASK_DECLARE_1(x) [x+1][0] = (1UL << (x))
#define MASK_DECLARE_2(x) MASK_DECLARE_1(x), MASK_DECLARE_1(x+1)
#define MASK_DECLARE_4(x) MASK_DECLARE_2(x), MASK_DECLARE_2(x+2)
#define MASK_DECLARE_8(x) MASK_DECLARE_4(x), MASK_DECLARE_4(x+4)
const unsigned long cpu_bit_bitmap[BITS_PER_LONG+1][BITS_TO_LONGS(NR_CPUS)] = {
MASK_DECLARE_8(0), MASK_DECLARE_8(8),
MASK_DECLARE_8(16), MASK_DECLARE_8(24),
#if BITS_PER_LONG > 32
MASK_DECLARE_8(32), MASK_DECLARE_8(40),
MASK_DECLARE_8(48), MASK_DECLARE_8(56),
#endif
};
EXPORT_SYMBOL_GPL(cpu_bit_bitmap);