| |
| |
| |
|
|
| |
|
|
| package cpu |
|
|
| |
| |
| |
| |
| |
| |
| func DataCacheSizes() []uintptr { |
| maxFunctionInformation, ebx0, ecx0, edx0 := cpuid(0, 0) |
| if maxFunctionInformation < 1 { |
| return nil |
| } |
|
|
| switch { |
| |
| case ebx0 == 0x756E6547 && ecx0 == 0x6C65746E && edx0 == 0x49656E69: |
| return getDataCacheSizesIntel(maxFunctionInformation) |
| |
| case ebx0 == 0x68747541 && ecx0 == 0x444D4163 && edx0 == 0x69746E65: |
| return getDataCacheSizesAMD() |
| } |
| return nil |
| } |
|
|
| func extractBits(arg uint32, l int, r int) uint32 { |
| if l > r { |
| panic("bad bit range") |
| } |
| return (arg >> l) & ((1 << (r - l + 1)) - 1) |
| } |
|
|
| func getDataCacheSizesIntel(maxID uint32) []uintptr { |
| |
| const ( |
| noCache = 0 |
| dataCache = 1 |
| instructionCache = 2 |
| unifiedCache = 3 |
| ) |
| if maxID < 4 { |
| return nil |
| } |
|
|
| |
| var caches []uintptr |
| for i := uint32(0); i < 0xFFFF; i++ { |
| eax, ebx, ecx, _ := cpuid(4, i) |
|
|
| cacheType := eax & 0xF |
| if cacheType == 0 { |
| break |
| } |
|
|
| |
| if !(cacheType == dataCache || cacheType == unifiedCache) { |
| continue |
| } |
|
|
| |
| level := (eax >> 5) & 0x7 |
|
|
| lineSize := extractBits(ebx, 0, 11) + 1 |
| partitions := extractBits(ebx, 12, 21) + 1 |
| ways := extractBits(ebx, 22, 31) + 1 |
| sets := uint64(ecx) + 1 |
| size := uint64(ways*partitions*lineSize) * sets |
|
|
| caches = append(caches, uintptr(size)) |
|
|
| |
| |
| |
| |
| |
| if level != uint32(len(caches)) { |
| panic("expected levels to be in order and for there to be one data/unified cache per level") |
| } |
| } |
| return caches |
| } |
|
|
| func getDataCacheSizesAMD() []uintptr { |
| maxExtendedFunctionInformation, _, _, _ := cpuid(0x80000000, 0) |
| if maxExtendedFunctionInformation < 0x80000006 { |
| return nil |
| } |
|
|
| var caches []uintptr |
|
|
| _, _, ecx5, _ := cpuid(0x80000005, 0) |
| _, _, ecx6, edx6 := cpuid(0x80000006, 0) |
|
|
| |
| l1dSize := uintptr(extractBits(ecx5, 24, 31) << 10) |
| caches = append(caches, l1dSize) |
|
|
| |
| if l2Assoc := extractBits(ecx6, 12, 15); l2Assoc == 0 { |
| return caches |
| } |
| l2Size := uintptr(extractBits(ecx6, 16, 31) << 10) |
| caches = append(caches, l2Size) |
|
|
| |
| if l3Assoc := extractBits(edx6, 12, 15); l3Assoc == 0 { |
| return caches |
| } |
| |
| |
| l3Size := uintptr(extractBits(edx6, 18, 31) * (512 << 10)) |
| caches = append(caches, l3Size) |
|
|
| return caches |
| } |
|
|