On i386 linux. Preferably in c/(c/posix std libs)/proc if possible. If not is there any piece of assembly or third party library that can do this?
Edit: I’m trying to develop test whether a kernel module clear a cache line or the whole proccesor(with wbinvd()). Program runs as root but I’d prefer to stay in user space if possible.
Cache coherent systems do their utmost to hide such things from you. I think you will have to observe it indirectly, either by using performance counting registers to detect cache misses or by carefully measuring the time to read a memory location with a high resolution timer.
This program works on my x86_64 box to demonstrate the effects of
clflush. It times how long it takes to read a global variable usingrdtsc. Being a single instruction tied directly to the CPU clock makes direct use ofrdtscideal for this.Here is the output:
You see 3 trials: The first ensures
iis in the cache (which it is, because it was just zeroed as part of BSS), the second is a read ofithat should be in the cache. Thenclflushkicksiout of the cache (along with its neighbors) and shows that re-reading it takes significantly longer. A final read verifies it is back in the cache. The results are very reproducible and the difference is substantial enough to easily see the cache misses. If you cared to calibrate the overhead ofrdtsc()you could make the difference even more pronounced.If you can’t read the memory address you want to test (although even
mmapof/dev/memshould work for these purposes) you may be able to infer what you want if you know the cacheline size and associativity of the cache. Then you can use accessible memory locations to probe the activity in the set you’re interested in.Source code:
(1. Use
static inlineor other methods referenced here if using newer gcc2. Inspired by the comment, better use
asm volatile ("lfence;rdtsc;lfence" : "=a" (a), "=d" (d)::"memory");if your CPU may reorder the instruction at runtime. Herevolatileimplies no need ofmfencearoundcflushto ensure thatinstructions after
cflushcan observe its effect)