host_mem.rs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. use log::debug;
  2. use system_error::SystemError;
  3. use super::{vcpu::Vcpu, vm};
  4. use crate::mm::{kernel_mapper::KernelMapper, page::EntryFlags, VirtAddr};
  5. /*
  6. * Address types:
  7. *
  8. * gva - guest virtual address
  9. * gpa - guest physical address
  10. * gfn - guest frame number
  11. * hva - host virtual address
  12. * hpa - host physical address
  13. * hfn - host frame number
  14. */
  15. pub const KVM_USER_MEM_SLOTS: u32 = 16;
  16. pub const KVM_PRIVATE_MEM_SLOTS: u32 = 3;
  17. pub const KVM_MEM_SLOTS_NUM: u32 = KVM_USER_MEM_SLOTS + KVM_PRIVATE_MEM_SLOTS;
  18. pub const KVM_ADDRESS_SPACE_NUM: usize = 2;
  19. pub const KVM_MEM_LOG_DIRTY_PAGES: u32 = 1 << 0;
  20. pub const KVM_MEM_READONLY: u32 = 1 << 1;
  21. pub const KVM_MEM_MAX_NR_PAGES: u32 = (1 << 31) - 1;
  22. /*
  23. * The bit 16 ~ bit 31 of kvm_memory_region::flags are internally used
  24. * in kvm, other bits are visible for userspace which are defined in
  25. * include/linux/kvm_h.
  26. */
  27. pub const KVM_MEMSLOT_INVALID: u32 = 1 << 16;
  28. // pub const KVM_MEMSLOT_INCOHERENT:u32 = 1 << 17;
  29. // pub const KVM_PERMILLE_MMU_PAGES: u32 = 20; // the proportion of MMU pages required per thousand (out of 1000) memory pages.
  30. // pub const KVM_MIN_ALLOC_MMU_PAGES: u32 = 64;
  31. pub const PAGE_SHIFT: u32 = 12;
  32. pub const PAGE_SIZE: u32 = 1 << PAGE_SHIFT;
  33. pub const PAGE_MASK: u32 = !(PAGE_SIZE - 1);
  34. /// 通过这个结构可以将虚拟机的物理地址对应到用户进程的虚拟地址
  35. /// 用来表示虚拟机的一段物理内存
  36. #[repr(C)]
  37. #[derive(Default)]
  38. pub struct KvmUserspaceMemoryRegion {
  39. pub slot: u32, // 要在哪个slot上注册内存区间
  40. // flags有两个取值,KVM_MEM_LOG_DIRTY_PAGES和KVM_MEM_READONLY,用来指示kvm针对这段内存应该做的事情。
  41. // KVM_MEM_LOG_DIRTY_PAGES用来开启内存脏页,KVM_MEM_READONLY用来开启内存只读。
  42. pub flags: u32,
  43. pub guest_phys_addr: u64, // 虚机内存区间起始物理地址
  44. pub memory_size: u64, // 虚机内存区间大小
  45. pub userspace_addr: u64, // 虚机内存区间对应的主机虚拟地址
  46. }
  47. #[derive(Default, Clone, Copy, Debug)]
  48. pub struct KvmMemorySlot {
  49. pub base_gfn: u64, // 虚机内存区间起始物理页框号
  50. pub npages: u64, // 虚机内存区间页数,即内存区间的大小
  51. pub userspace_addr: u64, // 虚机内存区间对应的主机虚拟地址
  52. pub flags: u32, // 虚机内存区间属性
  53. pub id: u16, // 虚机内存区间id
  54. // 用来记录虚机内存区间的脏页信息,每个bit对应一个页,如果bit为1,表示对应的页是脏页,如果bit为0,表示对应的页是干净页。
  55. // pub dirty_bitmap: *mut u8,
  56. // unsigned long *rmap[KVM_NR_PAGE_SIZES]; 反向映射相关的结构, 创建EPT页表项时就记录GPA对应的页表项地址(GPA-->页表项地址),暂时不需要
  57. }
  58. #[derive(Default, Clone, Copy, Debug)]
  59. pub struct KvmMemorySlots {
  60. pub memslots: [KvmMemorySlot; KVM_MEM_SLOTS_NUM as usize], // 虚机内存区间数组
  61. pub used_slots: u32, // 已经使用的slot数量
  62. }
  63. #[derive(PartialEq, Eq, Debug)]
  64. pub enum KvmMemoryChange {
  65. Create,
  66. Delete,
  67. Move,
  68. FlagsOnly,
  69. }
  70. pub fn kvm_vcpu_memslots(_vcpu: &mut dyn Vcpu) -> KvmMemorySlots {
  71. let kvm = vm(0).unwrap();
  72. let as_id = 0;
  73. return kvm.memslots[as_id];
  74. }
  75. fn __gfn_to_memslot(slots: KvmMemorySlots, gfn: u64) -> Option<KvmMemorySlot> {
  76. debug!("__gfn_to_memslot");
  77. // TODO: 使用二分查找的方式优化
  78. for i in 0..slots.used_slots {
  79. let memslot = slots.memslots[i as usize];
  80. if gfn >= memslot.base_gfn && gfn < memslot.base_gfn + memslot.npages {
  81. return Some(memslot);
  82. }
  83. }
  84. return None;
  85. }
  86. fn __gfn_to_hva(slot: KvmMemorySlot, gfn: u64) -> u64 {
  87. return slot.userspace_addr + (gfn - slot.base_gfn) * (PAGE_SIZE as u64);
  88. }
  89. fn __gfn_to_hva_many(
  90. slot: Option<KvmMemorySlot>,
  91. gfn: u64,
  92. nr_pages: Option<&mut u64>,
  93. write: bool,
  94. ) -> Result<u64, SystemError> {
  95. debug!("__gfn_to_hva_many");
  96. if slot.is_none() {
  97. return Err(SystemError::KVM_HVA_ERR_BAD);
  98. }
  99. let slot = slot.unwrap();
  100. if slot.flags & KVM_MEMSLOT_INVALID != 0 || (slot.flags & KVM_MEM_READONLY != 0) && write {
  101. return Err(SystemError::KVM_HVA_ERR_BAD);
  102. }
  103. if let Some(nr_pages) = nr_pages {
  104. *nr_pages = slot.npages - (gfn - slot.base_gfn);
  105. }
  106. return Ok(__gfn_to_hva(slot, gfn));
  107. }
  108. /* From Linux kernel
  109. * Pin guest page in memory and return its pfn.
  110. * @addr: host virtual address which maps memory to the guest
  111. * @atomic: whether this function can sleep
  112. * @async: whether this function need to wait IO complete if the
  113. * host page is not in the memory
  114. * @write_fault: whether we should get a writable host page
  115. * @writable: whether it allows to map a writable host page for !@write_fault
  116. *
  117. * The function will map a writable host page for these two cases:
  118. * 1): @write_fault = true
  119. * 2): @write_fault = false && @writable, @writable will tell the caller
  120. * whether the mapping is writable.
  121. */
  122. // 计算 HVA 对应的 pfn,同时确保该物理页在内存中
  123. // host端虚拟地址到物理地址的转换,有两种方式,hva_to_pfn_fast、hva_to_pfn_slow
  124. // 正确性待验证
  125. fn hva_to_pfn(addr: u64, _atomic: bool, _writable: &mut bool) -> Result<u64, SystemError> {
  126. debug!("hva_to_pfn");
  127. unsafe {
  128. let raw = addr as *const i32;
  129. debug!("raw={:x}", *raw);
  130. }
  131. // let hpa = MMArch::virt_2_phys(VirtAddr::new(addr)).unwrap().data() as u64;
  132. let hva = VirtAddr::new(addr as usize);
  133. let mut mapper = KernelMapper::lock();
  134. let mapper = mapper.as_mut().unwrap();
  135. if let Some((hpa, _)) = mapper.translate(hva) {
  136. return Ok(hpa.data() as u64 >> PAGE_SHIFT);
  137. }
  138. unsafe {
  139. mapper.map(hva, EntryFlags::mmio_flags());
  140. }
  141. let (hpa, _) = mapper.translate(hva).unwrap();
  142. return Ok(hpa.data() as u64 >> PAGE_SHIFT);
  143. }
  144. pub fn __gfn_to_pfn(
  145. slot: Option<KvmMemorySlot>,
  146. gfn: u64,
  147. atomic: bool,
  148. write: bool,
  149. writable: &mut bool,
  150. ) -> Result<u64, SystemError> {
  151. debug!("__gfn_to_pfn");
  152. let mut nr_pages = 0;
  153. let addr = __gfn_to_hva_many(slot, gfn, Some(&mut nr_pages), write)?;
  154. let pfn = hva_to_pfn(addr, atomic, writable)?;
  155. debug!("hva={}, pfn={}", addr, pfn);
  156. return Ok(pfn);
  157. }
  158. pub fn kvm_vcpu_gfn_to_memslot(vcpu: &mut dyn Vcpu, gfn: u64) -> Option<KvmMemorySlot> {
  159. return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
  160. }