KVM max vcpu allocation

来源:互联网 发布:mac将图标放在桌面 编辑:程序博客网 时间:2024/05/16 07:20
From https://kernel.org/doc/Documentation/virtual/kvm/api.txt we can see, 


"The maximum possible value for max_vcpus can be retrieved using the 
KVM_CAP_MAX_VCPUS of the KVM_CHECK_EXTENSION ioctl() at run-time. 


If the KVM_CAP_NR_VCPUS does not exist, you should assume that max_vcpus is 4 
cpus max. 
If the KVM_CAP_MAX_VCPUS does not exist, you should assume that max_vcpus is 
same as the value returned from KVM_CAP_NR_VCPUS." 


The following c program is written according to the documentation above to retrieve KVM max vcpu directly from KVM and should give the same result as virsh maxvcpus kvm does. When given a arg "Recommended", it returns the recommended max vcpus. 


#include <stdio.h> 
#include <fcntl.h> 
#include <linux/kvm.h> 


static int kvmMaxVCPUs(int type) { 
int maxvcpus = -1; 


int r, fd; 


fd = open("/dev/kvm", O_RDONLY); 
if (fd < 0) { 
printf("Unable to open /dev/kvm, max vcpu default 4"); 
return 4; 



if(type) 
r = ioctl(fd, KVM_CHECK_EXTENSION, KVM_CAP_NR_VCPUS); 
else 
r = ioctl(fd, KVM_CHECK_EXTENSION, KVM_CAP_MAX_VCPUS); 
if (r > 0) 
maxvcpus = r; 


close(fd); 
return maxvcpus; 



int main ( int argc, char *argv[] ) 

if(argc > 1 && !strcmp(argv[1], "Recommended")) 
printf("recommended max vcpus: %d \n", kvmMaxVCPUs(1)); 
else 
printf("max vcpus: %d \n", kvmMaxVCPUs(0)); 

Below is some detail on how this value is returned from the kernel, which also explains the findings of your initial research. 


Call sequence in kernel space in response to the ioctl system call above, 
kvm_dev_ioctl -> kvm_dev_ioctl_check_extension_generic -> kvm_dev_ioctl_check_extension 

It eventually returns the macro you found, 
https://github.com/Canonical-kernel/Ubuntu-kernel/blob/v3.2.13/arch/x86/kvm/x86.c#L2113 

Registration of the char dev ops, 
static struct file_operations kvm_chardev_ops = { 
.unlocked_ioctl = kvm_dev_ioctl, 
.compat_ioctl = kvm_dev_ioctl, 
.llseek = noop_llseek, 
}; 

static struct miscdevice kvm_dev = { 
KVM_MINOR, 
"kvm", 
&kvm_chardev_ops, 
}; 


0 0
原创粉丝点击