github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/sentry/platform/kvm/kvm_amd64_unsafe.go (about) 1 // Copyright 2018 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // +build amd64 16 17 package kvm 18 19 import ( 20 "fmt" 21 "unsafe" 22 23 "golang.org/x/sys/unix" 24 ) 25 26 var ( 27 runDataSize int 28 hasGuestPCID bool 29 cpuidSupported = cpuidEntries{nr: _KVM_NR_CPUID_ENTRIES} 30 ) 31 32 func updateSystemValues(fd int) error { 33 // Extract the mmap size. 34 sz, _, errno := unix.RawSyscall(unix.SYS_IOCTL, uintptr(fd), _KVM_GET_VCPU_MMAP_SIZE, 0) 35 if errno != 0 { 36 return fmt.Errorf("getting VCPU mmap size: %v", errno) 37 } 38 39 // Save the data. 40 runDataSize = int(sz) 41 42 // Must do the dance to figure out the number of entries. 43 _, _, errno = unix.RawSyscall( 44 unix.SYS_IOCTL, 45 uintptr(fd), 46 _KVM_GET_SUPPORTED_CPUID, 47 uintptr(unsafe.Pointer(&cpuidSupported))) 48 if errno != 0 && errno != unix.ENOMEM { 49 // Some other error occurred. 50 return fmt.Errorf("getting supported CPUID: %v", errno) 51 } 52 53 // The number should now be correct. 54 _, _, errno = unix.RawSyscall( 55 unix.SYS_IOCTL, 56 uintptr(fd), 57 _KVM_GET_SUPPORTED_CPUID, 58 uintptr(unsafe.Pointer(&cpuidSupported))) 59 if errno != 0 { 60 // Didn't work with the right number. 61 return fmt.Errorf("getting supported CPUID (2nd attempt): %v", errno) 62 } 63 64 // Calculate whether guestPCID is supported. 65 // 66 // FIXME(ascannell): These should go through the much more pleasant 67 // cpuid package interfaces, once a way to accept raw kvm CPUID entries 68 // is plumbed (or some rough equivalent). 69 for i := 0; i < int(cpuidSupported.nr); i++ { 70 entry := cpuidSupported.entries[i] 71 if entry.function == 1 && entry.index == 0 && entry.ecx&(1<<17) != 0 { 72 hasGuestPCID = true // Found matching PCID in guest feature set. 73 } 74 } 75 76 // Success. 77 return nil 78 }