lscpu 中读取cache 信息的源码如下:
https://github.com/karelzak/util-linux/blob/master/sys-utils/lscpu.c
下面这段code 中主要从/sys/devices/system/cpu/cpu0/cache/index0 这个文件系统中查找cache信息,包含cache的type.level,size
read_cache(struct lscpu_desc *desc, int idx)
{
char buf[256];
int i;
int num = real_cpu_num(desc, idx);
if (!desc->ncaches) {
while (ul_path_accessf(desc->syscpu, F_OK,
"cpu%d/cache/index%d",
num, desc->ncaches) == 0)
desc->ncaches++;
if (!desc->ncaches)
return;
desc->caches = xcalloc(desc->ncaches, sizeof(*desc->caches));
}
for (i = 0; i < desc->ncaches; i++) {
struct cpu_cache *ca = &desc->caches[i];
cpu_set_t *map;
if (ul_path_accessf(desc->syscpu, F_OK,
"cpu%d/cache/index%d", num, i) != 0)
continue;
if (!ca->name) {
int type = 0, level;
/* cache type */
if (ul_path_readf_buffer(desc->syscpu, buf, sizeof(buf),
"cpu%d/cache/index%d/type", num, i) > 0) {
if (!strcmp(buf, "Data"))
type = 'd';
else if (!strcmp(buf, "Instruction"))
type = 'i';
}
/* cache level */
ul_path_readf_s32(desc->syscpu, &level,
"cpu%d/cache/index%d/level", num, i);
if (type)
snprintf(buf, sizeof(buf), "L%d%c", level, type);
else
snprintf(buf, sizeof(buf), "L%d", level);
ca->name = xstrdup(buf);
/* cache size */
if (ul_path_readf_string(desc->syscpu, &ca->size,
"cpu%d/cache/index%d/size", num, i) < 0)
ca->size = xstrdup("unknown size");
}
/* information about how CPUs share different caches */
ul_path_readf_cpuset(desc->syscpu, &map, maxcpus,
"cpu%d/cache/index%d/shared_cpu_map", num, i);
if (!ca->sharedmaps)
ca->sharedmaps = xcalloc(desc->ncpuspos, sizeof(cpu_set_t *));
add_cpuset_to_array(ca->sharedmaps, &ca->nsharedmaps, map);
}
}
与之对应的os中实现/sys/devices/system/cpu/cpu0/cache/index0/ 这个sysfs文件系统对应的源码在driver/base/cacheinfo.c
show_one(id, id);
show_one(level, level);
show_one(coherency_line_size, coherency_line_size);
可以看到这里实现了读取cache的id/level/size.与之对应的文件系统得到的结果如下:
tiantao@BoardServer2:/sys/devices/system/cpu/cpu0/cache/index0$ ls
coherency_line_size level number_of_sets physical_line_partition power shared_cpu_list shared_cpu_map size type uevent ways_of_associativity
tiantao@BoardServer2:/sys/devices/system/cpu/cpu0/cache/index0$ cat type
Data
tiantao@BoardServer2:/sys/devices/system/cpu/cpu0/cache/index0$ cat level
1
tiantao@BoardServer2:/sys/devices/system/cpu/cpu0/cache/index0$ cat coherency_line_size
64
tiantao@BoardServer2:/sys/devices/system/cpu/cpu0/cache/index0$
从这里可以知道L1的data cache size是64