요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
.. SPDX-License-Identifier: GPL-2.0
=================
KVM Lock Overview
=================
1. Acquisition Orders
---------------------
The acquisition orders for mutexes are as follows:
- cpus_read_lock() is taken outside kvm_lock
- kvm_usage_lock is taken outside cpus_read_lock()
- kvm->lock is taken outside vcpu->mutex
- kvm->lock is taken outside kvm->slots_lock and kvm->irq_lock
- kvm->slots_lock is taken outside kvm->irq_lock, though acquiring
them together is quite rare.
- kvm->mn_active_invalidate_count ensures that pairs of
invalidate_range_start() and invalidate_range_end() callbacks
use the same memslots array. kvm->slots_lock and kvm->slots_arch_lock
are taken on the waiting side when modifying memslots, so MMU notifiers
must not take either kvm->slots_lock or kvm->slots_arch_lock.
cpus_read_lock() vs kvm_lock:
- Taking cpus_read_lock() outside of kvm_lock is problematic, despite that
being the official ordering, as it is quite easy to unknowingly trigger
cpus_read_lock() while holding kvm_lock. Use caution when walking vm_list,
e.g. avoid complex operations when possible.
For SRCU:
- ``synchronize_srcu(&kvm->srcu)`` is called inside critical sections
for kvm->lock, vcpu->mutex and kvm->slots_lock. These locks _cannot_
be taken inside a kvm->srcu read-side critical section; that is, the
following is broken::
srcu_read_lock(&kvm->srcu);
mutex_lock(&kvm->slots_lock);
- kvm->slots_arch_lock instead is released before the call to
``synchronize_srcu()``. It _can_ therefore be taken inside a
kvm->srcu read-side critical section, for example while processing
a vmexit.
On x86:
- vcpu->mutex is taken outside kvm->arch.hyperv.hv_lock and kvm->arch.xen.xen_lock
- kvm->arch.mmu_lock is an rwlock; critical sections for
kvm->arch.tdp_mmu_pages_lock and kvm->arch.mmu_unsync_pages_lock must
also take kvm->arch.mmu_lock
Everything else is a leaf: no other lock is taken inside the critical
sections.
2. Exception
------------
Fast page fault:
Fast page fault is the fast path which fixes the guest page fault out of
the mmu-lock on x86. Currently, the page fault can be fast in one of the
following two cases:
1. Access Tracking: The SPTE is not present, but it is marked for access
tracking. That means we need to restore the saved R/X bits. This is
described in more detail later below.
2. Write-Protection: The SPTE is present and the fault is caused by
write-protect. That means we just need to change the W bit of the spte.
What we use to avoid all the races is the Host-writable bit and MMU-writable bit
on the spte:
- Host-writable means the gfn is writable in the host kernel page tables and in
its KVM memslot.
- MMU-writable means the gfn is writable in the guest's mmu and it is not
write-protected by shadow page write-protection.
On fast page fault path, we will use cmpxchg to atomically set the spte W
bit if spte.HOST_WRITEABLE = 1 and spte.WRITE_PROTECT = 1, to restore the saved
R/X bits if for an access-traced spte, or both. This is safe because whenever
changing these bits can be detected by cmpxchg.
But we need carefully check these cases:
1) The mapping from gfn to pfn
The mapping from gfn to pfn may be changed since we can only ensure the pfn
is not changed during cmpxchg. This is a ABA problem, for example, below case
will happen:
+------------------------------------------------------------------------+
| At the beginning:: |
| |
| gpte = gfn1 |
| gfn1 is mapped to pfn1 on host |
| spte is the shadow page table entry corresponding with gpte and |
| spte = pfn1 |
+------------------------------------------------------------------------+
| On fast page fault path: |
+------------------------------------+-----------------------------------+
| CPU 0: | CPU 1: |
+------------------------------------+-----------------------------------+
| :: | |
| | |
| old_spte = *spte; | |
+------------------------------------+-----------------------------------+
| | pfn1 is swapped out:: |
| | |
| | spte = 0; |
| | |
| | pfn1 is re-alloced for gfn2. |
| | |
| | gpte is changed to point to |
| | gfn2 by the guest:: |
| | |
| | spte = pfn1; |
+------------------------------------+-----------------------------------+
| :: |
| |
| if (cmpxchg(spte, old_spte, old_spte+W) |
| mark_page_dirty(vcpu->kvm, gfn1) |
| OOPS!!! |
+------------------------------------------------------------------------+
We dirty-log for gfn1, that means gfn2 is lost in dirty-bitmap.
For direct sp, we can easily avoid it since the spte of direct sp is fixed
to gfn. For indirect sp, we disabled fast page fault for simplicity.
A solution for indirect sp could be to pin the gfn before the cmpxchg. After
the pinning:
- We have held the refcount of pfn; that means the pfn can not be freed and
be reused for another gfn.
- The pfn is writable and therefore it cannot be shared between different gfns
by KSM.
Then, we can ensure the dirty bitmaps is correctly set for a gfn.
2) Dirty bit tracking
In the original code, the spte can be fast updated (non-atomically) if the
spte is read-only and the Accessed bit has already been set since the
Accessed bit and Dirty bit can not be lost.
But it is not true after fast page fault since the spte can be marked
writable between reading spte and updating spte. Like below case:
+-------------------------------------------------------------------------+
| At the beginning:: |
| |
| spte.W = 0 |
| spte.Accessed = 1 |
+-------------------------------------+-----------------------------------+
| CPU 0: | CPU 1: |
+-------------------------------------+-----------------------------------+
| In mmu_spte_update():: | |
| | |
| old_spte = *spte; | |
| | |
| | |
| /* 'if' condition is satisfied. */ | |
| if (old_spte.Accessed == 1 && | |
| old_spte.W == 0) | |
| spte = new_spte; | |
+-------------------------------------+-----------------------------------+
| | on fast page fault path:: |
| | |
| | spte.W = 1 |
| | |
| | memory write on the spte:: |
| | |
| | spte.Dirty = 1 |
+-------------------------------------+-----------------------------------+
| :: | |
| | |
| else | |
| old_spte = xchg(spte, new_spte);| |
| if (old_spte.Accessed && | |
| !new_spte.Accessed) | |
| flush = true; | |
| if (old_spte.Dirty && | |
| !new_spte.Dirty) | |
| flush = true; | |
| OOPS!!! | |
+-------------------------------------+-----------------------------------+
The Dirty bit is lost in this case.
In order to avoid this kind of issue, we always treat the spte as "volatile"
if it can be updated out of mmu-lock [see spte_needs_atomic_update()]; it means
the spte is always atomically updated in this case.
3) flush tlbs due to spte updated
If the spte is updated from writable to read-only, we should flush all TLBs,
otherwise rmap_write_protect will find a read-only spte, even though the
writable spte might be cached on a CPU's TLB.
As mentioned before, the spte can be updated to writable out of mmu-lock on
fast page fault path. In order to easily audit the path, we see if TLBs needing
to be flushed caused this reason in mmu_spte_update() since this is a common
function to update spte (present -> present).
Since the spte is "volatile" if it can be updated out of mmu-lock, we always
atomically update the spte and the race caused by fast page fault can be avoided.
See the comments in spte_needs_atomic_update() and mmu_spte_update().
Lockless Access Tracking:
This is used for Intel CPUs that are using EPT but do not support the EPT A/D
bits. In this case, PTEs are tagged as A/D disabled (using ignored bits), and
when the KVM MMU notifier is called to track accesses to a page (via
kvm_mmu_notifier_clear_flush_young), it marks the PTE not-present in hardware
by clearing the RWX bits in the PTE and storing the original R & X bits in more
unused/ignored bits. When the VM tries to access the page later on, a fault is
generated and the fast page fault mechanism described above is used to
atomically restore the PTE to a Present state. The W bit is not saved when the
PTE is marked for access tracking and during restoration to the Present state,
the W bit is set depending on whether or not it was a write access. If it
wasn't, then the W bit will remain clear until a write access happens, at which
time it will be set using the Dirty tracking mechanism described above.
3. Reference
------------
``kvm_lock``
^^^^^^^^^^^^
:Type: mutex
:Arch: any
:Protects: - vm_list
``kvm_usage_lock``
^^^^^^^^^^^^^^^^^^
:Type: mutex
:Arch: any
:Protects: - kvm_usage_count
- hardware virtualization enable/disable
:Comment: Exists to allow taking cpus_read_lock() while kvm_usage_count is
protected, which simplifies the virtualization enabling logic.
``kvm->mn_invalidate_lock``
^^^^^^^^^^^^^^^^^^^^^^^^^^^
:Type: spinlock_t
:Arch: any
:Protects: mn_active_invalidate_count, mn_memslots_update_rcuwait
``kvm_arch::tsc_write_lock``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:Type: raw_spinlock_t
:Arch: x86
:Protects: - kvm_arch::{last_tsc_write,last_tsc_nsec,last_tsc_offset}
- tsc offset in vmcb
:Comment: 'raw' because updating the tsc offsets must not be preempted.
``kvm->mmu_lock``
^^^^^^^^^^^^^^^^^
:Type: spinlock_t or rwlock_t
:Arch: any
:Protects: -shadow page/shadow tlb entry
:Comment: it is a spinlock since it is used in mmu notifier.
``kvm->srcu``
^^^^^^^^^^^^^
:Type: srcu lock
:Arch: any
:Protects: - kvm->memslots
- kvm->buses
:Comment: The srcu read lock must be held while accessing memslots (e.g.
when using gfn_to_* functions) and while accessing in-kernel
MMIO/PIO address->device structure mapping (kvm->buses).
The srcu index can be stored in kvm_vcpu->srcu_idx per vcpu
if it is needed by multiple functions.
``kvm->slots_arch_lock``
^^^^^^^^^^^^^^^^^^^^^^^^
:Type: mutex
:Arch: any (only needed on x86 though)
:Protects: any arch-specific fields of memslots that have to be modified
in a ``kvm->srcu`` read-side critical section.
:Comment: must be held before reading the pointer to the current memslots,
until after all changes to the memslots are complete
``wakeup_vcpus_on_cpu_lock``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:Type: spinlock_t
:Arch: x86
:Protects: wakeup_vcpus_on_cpu
:Comment: This is a per-CPU lock and it is used for VT-d posted-interrupts.
When VT-d posted-interrupts are supported and the VM has assigned
devices, we put the blocked vCPU on the list blocked_vcpu_on_cpu
protected by blocked_vcpu_on_cpu_lock. When VT-d hardware issues
wakeup notification event since external interrupts from the
assigned devices happens, we will find the vCPU on the list to
wakeup.
``vendor_module_lock``
^^^^^^^^^^^^^^^^^^^^^^
:Type: mutex
:Arch: x86
:Protects: loading a vendor module (kvm_amd or kvm_intel)
:Comment: Exists because using kvm_lock leads to deadlock. kvm_lock is taken
in notifiers, e.g. __kvmclock_cpufreq_notifier(), that may be invoked while
cpu_hotplug_lock is held, e.g. from cpufreq_boost_trigger_state(), and many
operations need to take cpu_hotplug_lock when loading a vendor module, e.g.
updating static calls.
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
잠금 획득 순서
1-61KVM의 상위 잠금 순서는 `kvm_usage_lock` 바깥에서 `cpus_read_lock()`을, `cpus_read_lock()` 바깥에서 `kvm_lock`을 잡는 구조입니다. VM 내부에서는 `kvm->lock`을 `vcpu->mutex`, `kvm->slots_lock`, `kvm->irq_lock`보다 먼저 잡고 `kvm->slots_lock`을 `kvm->irq_lock`보다 먼저 잡습니다.
왼쪽 잠금이 오른쪽 잠금보다 바깥에서 획득됩니다.
`kvm->mn_active_invalidate_count`는 `invalidate_range_start()`와 `invalidate_range_end()`가 같은 memslots 배열을 쓰게 합니다. memslot 변경을 기다리는 쪽이 `kvm->slots_lock`과 `kvm->slots_arch_lock`을 잡으므로 MMU notifier는 이 두 잠금을 잡아서는 안 됩니다.
공식 순서가 `cpus_read_lock()` 다음 `kvm_lock`이지만 `kvm_lock`을 가진 채 간접적으로 `cpus_read_lock()`을 호출하기 쉽습니다. 따라서 `vm_list`를 순회할 때 복잡한 동작을 피해야 합니다.
`synchronize_srcu(&kvm->srcu)`는 `kvm->lock`, `vcpu->mutex`, `kvm->slots_lock` 임계 구역 안에서 호출되므로 이 잠금들은 SRCU 읽기 임계 구역 안에서 잡을 수 없습니다. 반면 `kvm->slots_arch_lock`은 `synchronize_srcu()` 전에 해제되므로 VM exit 처리 같은 SRCU 읽기 구간에서 잡을 수 있습니다.
x86의 `kvm->arch.mmu_lock`은 rwlock입니다. `kvm->arch.tdp_mmu_pages_lock`과 `kvm->arch.mmu_unsync_pages_lock`의 임계 구역은 반드시 `kvm->arch.mmu_lock`도 함께 잡아야 합니다. 그 밖의 잠금은 내부에서 다른 잠금을 잡지 않는 leaf입니다.
.. SPDX-License-Identifier: GPL-2.0
=================
KVM Lock Overview
=================
1. Acquisition Orders
---------------------
The acquisition orders for mutexes are as follows:
- cpus_read_lock() is taken outside kvm_lock
- kvm_usage_lock is taken outside cpus_read_lock()
- kvm->lock is taken outside vcpu->mutex
- kvm->lock is taken outside kvm->slots_lock and kvm->irq_lock
- kvm->slots_lock is taken outside kvm->irq_lock, though acquiring
them together is quite rare.
- kvm->mn_active_invalidate_count ensures that pairs of
invalidate_range_start() and invalidate_range_end() callbacks
use the same memslots array. kvm->slots_lock and kvm->slots_arch_lock
are taken on the waiting side when modifying memslots, so MMU notifiers
must not take either kvm->slots_lock or kvm->slots_arch_lock.
cpus_read_lock() vs kvm_lock:
- Taking cpus_read_lock() outside of kvm_lock is problematic, despite that
being the official ordering, as it is quite easy to unknowingly trigger
cpus_read_lock() while holding kvm_lock. Use caution when walking vm_list,
e.g. avoid complex operations when possible.
For SRCU:
- ``synchronize_srcu(&kvm->srcu)`` is called inside critical sections
for kvm->lock, vcpu->mutex and kvm->slots_lock. These locks _cannot_
be taken inside a kvm->srcu read-side critical section; that is, the
following is broken::
srcu_read_lock(&kvm->srcu);
mutex_lock(&kvm->slots_lock);
- kvm->slots_arch_lock instead is released before the call to
``synchronize_srcu()``. It _can_ therefore be taken inside a
kvm->srcu read-side critical section, for example while processing
a vmexit.
On x86:
- vcpu->mutex is taken outside kvm->arch.hyperv.hv_lock and kvm->arch.xen.xen_lock
- kvm->arch.mmu_lock is an rwlock; critical sections for
kvm->arch.tdp_mmu_pages_lock and kvm->arch.mmu_unsync_pages_lock must
also take kvm->arch.mmu_lock
Everything else is a leaf: no other lock is taken inside the critical
sections.
빠른 페이지 폴트와 GFN-PFN 경쟁
62-146x86의 fast page fault는 `mmu_lock` 밖에서 게스트 페이지 폴트를 처리하는 빠른 경로입니다. access tracking으로 non-present 표시된 SPTE의 저장된 R/X 비트를 복원하거나, write-protect로 발생한 폴트에서 SPTE의 W 비트를 켜는 두 경우를 다룹니다.
빠른 경로는 두 쓰기 가능 비트와 원자적 비교 교환을 사용합니다.
빠른 경로는 `cmpxchg`로 SPTE W 비트를 켜거나 access-traced SPTE의 R/X 비트를 복원합니다. 비교 교환이 읽은 값과 현재 값을 함께 검증하므로 해당 비트 변경 경쟁을 탐지할 수 있습니다.
하지만 GFN에서 PFN으로의 매핑은 `cmpxchg` 전후에 ABA 형태로 바뀔 수 있습니다. 예시에서는 `gfn1`의 `pfn1`이 swap out된 뒤 `gfn2`에 재할당되고 게스트 PTE도 `gfn2`를 가리킵니다. SPTE 값은 다시 `pfn1`이어서 비교 교환이 성공하지만 `mark_page_dirty()`는 잘못된 `gfn1`을 기록해 `gfn2`가 dirty bitmap에서 누락됩니다.
direct shadow page는 SPTE가 GFN에 고정되어 이 문제를 피할 수 있습니다. 간접 shadow page에서는 단순성을 위해 fast page fault를 끕니다. 대안은 비교 교환 전에 GFN을 pin해 PFN 참조 횟수를 유지하고 재사용을 막는 것입니다. 쓰기 가능한 PFN은 KSM으로 다른 GFN과 공유할 수 없으므로 dirty bitmap을 올바르게 갱신할 수 있습니다.
2. Exception
------------
Fast page fault:
Fast page fault is the fast path which fixes the guest page fault out of
the mmu-lock on x86. Currently, the page fault can be fast in one of the
following two cases:
1. Access Tracking: The SPTE is not present, but it is marked for access
tracking. That means we need to restore the saved R/X bits. This is
described in more detail later below.
2. Write-Protection: The SPTE is present and the fault is caused by
write-protect. That means we just need to change the W bit of the spte.
What we use to avoid all the races is the Host-writable bit and MMU-writable bit
on the spte:
- Host-writable means the gfn is writable in the host kernel page tables and in
its KVM memslot.
- MMU-writable means the gfn is writable in the guest's mmu and it is not
write-protected by shadow page write-protection.
On fast page fault path, we will use cmpxchg to atomically set the spte W
bit if spte.HOST_WRITEABLE = 1 and spte.WRITE_PROTECT = 1, to restore the saved
R/X bits if for an access-traced spte, or both. This is safe because whenever
changing these bits can be detected by cmpxchg.
But we need carefully check these cases:
1) The mapping from gfn to pfn
The mapping from gfn to pfn may be changed since we can only ensure the pfn
is not changed during cmpxchg. This is a ABA problem, for example, below case
will happen:
+------------------------------------------------------------------------+
| At the beginning:: |
| |
| gpte = gfn1 |
| gfn1 is mapped to pfn1 on host |
| spte is the shadow page table entry corresponding with gpte and |
| spte = pfn1 |
+------------------------------------------------------------------------+
| On fast page fault path: |
+------------------------------------+-----------------------------------+
| CPU 0: | CPU 1: |
+------------------------------------+-----------------------------------+
| :: | |
| | |
| old_spte = *spte; | |
+------------------------------------+-----------------------------------+
| | pfn1 is swapped out:: |
| | |
| | spte = 0; |
| | |
| | pfn1 is re-alloced for gfn2. |
| | |
| | gpte is changed to point to |
| | gfn2 by the guest:: |
| | |
| | spte = pfn1; |
+------------------------------------+-----------------------------------+
| :: |
| |
| if (cmpxchg(spte, old_spte, old_spte+W) |
| mark_page_dirty(vcpu->kvm, gfn1) |
| OOPS!!! |
+------------------------------------------------------------------------+
We dirty-log for gfn1, that means gfn2 is lost in dirty-bitmap.
For direct sp, we can easily avoid it since the spte of direct sp is fixed
to gfn. For indirect sp, we disabled fast page fault for simplicity.
A solution for indirect sp could be to pin the gfn before the cmpxchg. After
the pinning:
- We have held the refcount of pfn; that means the pfn can not be freed and
be reused for another gfn.
- The pfn is writable and therefore it cannot be shared between different gfns
by KSM.
Then, we can ensure the dirty bitmaps is correctly set for a gfn.
Dirty 비트와 TLB 경쟁
147-216기존 코드는 읽기 전용 SPTE에 Accessed 비트가 이미 있으면 Accessed와 Dirty 비트를 잃지 않는다고 보고 비원자적으로 빠르게 갱신할 수 있었습니다. fast page fault가 `mmu_lock` 밖에서 SPTE를 쓰기 가능하게 만들 수 있게 되면서 이 가정은 더 이상 안전하지 않습니다.
예시에서 CPU 0은 `old_spte.W == 0`을 보고 비원자 갱신 경로를 선택합니다. 그 사이 CPU 1이 빠른 페이지 폴트로 W를 켜고 메모리 쓰기로 Dirty를 세웁니다. CPU 0이 새 SPTE를 대입하면 CPU 1이 만든 Dirty 비트가 사라집니다.
이를 막기 위해 `spte_needs_atomic_update()`는 `mmu_lock` 밖에서 바뀔 수 있는 SPTE를 volatile로 취급하고 항상 원자적으로 갱신합니다.
SPTE를 쓰기 가능에서 읽기 전용으로 바꾸면 모든 TLB를 flush해야 합니다. 그렇지 않으면 `rmap_write_protect`가 읽기 전용 SPTE를 보더라도 어떤 CPU TLB에는 쓰기 가능한 항목이 남을 수 있습니다. `mmu_spte_update()`는 present-to-present 갱신의 공통 지점에서 이 flush 필요성을 판정하며, volatile SPTE의 원자 갱신이 fast page fault와의 경쟁도 차단합니다.
fast page fault가 만든 잠금 없는 변경을 보존하는 순서입니다.
2) Dirty bit tracking
In the original code, the spte can be fast updated (non-atomically) if the
spte is read-only and the Accessed bit has already been set since the
Accessed bit and Dirty bit can not be lost.
But it is not true after fast page fault since the spte can be marked
writable between reading spte and updating spte. Like below case:
+-------------------------------------------------------------------------+
| At the beginning:: |
| |
| spte.W = 0 |
| spte.Accessed = 1 |
+-------------------------------------+-----------------------------------+
| CPU 0: | CPU 1: |
+-------------------------------------+-----------------------------------+
| In mmu_spte_update():: | |
| | |
| old_spte = *spte; | |
| | |
| | |
| /* 'if' condition is satisfied. */ | |
| if (old_spte.Accessed == 1 && | |
| old_spte.W == 0) | |
| spte = new_spte; | |
+-------------------------------------+-----------------------------------+
| | on fast page fault path:: |
| | |
| | spte.W = 1 |
| | |
| | memory write on the spte:: |
| | |
| | spte.Dirty = 1 |
+-------------------------------------+-----------------------------------+
| :: | |
| | |
| else | |
| old_spte = xchg(spte, new_spte);| |
| if (old_spte.Accessed && | |
| !new_spte.Accessed) | |
| flush = true; | |
| if (old_spte.Dirty && | |
| !new_spte.Dirty) | |
| flush = true; | |
| OOPS!!! | |
+-------------------------------------+-----------------------------------+
The Dirty bit is lost in this case.
In order to avoid this kind of issue, we always treat the spte as "volatile"
if it can be updated out of mmu-lock [see spte_needs_atomic_update()]; it means
the spte is always atomically updated in this case.
3) flush tlbs due to spte updated
If the spte is updated from writable to read-only, we should flush all TLBs,
otherwise rmap_write_protect will find a read-only spte, even though the
writable spte might be cached on a CPU's TLB.
As mentioned before, the spte can be updated to writable out of mmu-lock on
fast page fault path. In order to easily audit the path, we see if TLBs needing
to be flushed caused this reason in mmu_spte_update() since this is a common
function to update spte (present -> present).
Since the spte is "volatile" if it can be updated out of mmu-lock, we always
atomically update the spte and the race caused by fast page fault can be avoided.
See the comments in spte_needs_atomic_update() and mmu_spte_update().
잠금 없는 접근 추적
217-231이 방식은 EPT를 쓰지만 EPT A/D 비트를 지원하지 않는 Intel CPU에 사용됩니다. PTE의 무시되는 비트로 A/D 비활성 상태를 표시하고, `kvm_mmu_notifier_clear_flush_young`이 접근 추적을 요청하면 RWX 비트를 지워 하드웨어 관점에서 non-present로 만듭니다. 원래 R/X 비트는 다른 미사용 비트에 저장합니다.
VM이 페이지에 다시 접근하면 폴트가 발생하고 fast page fault가 PTE를 원자적으로 Present 상태로 복원합니다. W 비트는 추적 표시 시 저장하지 않습니다. 복원 접근이 쓰기이면 W를 세우고, 읽기이면 W를 비운 채 두었다가 이후 쓰기 폴트에서 앞의 dirty tracking 방식으로 세웁니다.
Lockless Access Tracking:
This is used for Intel CPUs that are using EPT but do not support the EPT A/D
bits. In this case, PTEs are tagged as A/D disabled (using ignored bits), and
when the KVM MMU notifier is called to track accesses to a page (via
kvm_mmu_notifier_clear_flush_young), it marks the PTE not-present in hardware
by clearing the RWX bits in the PTE and storing the original R & X bits in more
unused/ignored bits. When the VM tries to access the page later on, a fault is
generated and the fast page fault mechanism described above is used to
atomically restore the PTE to a Present state. The W bit is not saved when the
PTE is marked for access tracking and during restoration to the Present state,
the W bit is set depending on whether or not it was a write access. If it
wasn't, then the W bit will remain clear until a write access happens, at which
time it will be set using the Dirty tracking mechanism described above.
잠금 참조표
232-318각 잠금이 보호하는 공통 상태입니다.
`kvm_usage_lock`은 `kvm_usage_count`를 보호하면서 `cpus_read_lock()`을 잡을 수 있게 해 가상화 활성화 로직을 단순화합니다. `kvm->mmu_lock`은 MMU notifier에서도 쓰이므로 스핀 잠금이며, x86에서는 rwlock일 수 있습니다.
`kvm->srcu` 읽기 잠금은 memslot과 `gfn_to_*` 함수, 그리고 `kvm->buses`의 커널 내부 MMIO/PIO 주소-장치 매핑을 접근하는 동안 유지해야 합니다. 여러 함수가 필요로 하면 SRCU 인덱스를 vCPU별 `kvm_vcpu->srcu_idx`에 저장할 수 있습니다.
`kvm->slots_arch_lock`은 현재 memslots 포인터를 읽기 전에 잡아 모든 변경이 끝날 때까지 유지합니다. 이 잠금은 모든 아키텍처에 정의되지만 실질적으로 x86에만 필요합니다.
시간, posted interrupt, 벤더 모듈 상태를 보호합니다.
`vendor_module_lock`은 `kvm_lock`을 쓰면 교착될 수 있어 별도로 존재합니다. `kvm_lock`은 CPU hotplug 잠금 아래에서 호출될 수 있는 notifier가 잡고, 벤더 모듈 로딩의 여러 작업도 `cpu_hotplug_lock`을 필요로 하기 때문입니다.
3. Reference
------------
``kvm_lock``
^^^^^^^^^^^^
:Type: mutex
:Arch: any
:Protects: - vm_list
``kvm_usage_lock``
^^^^^^^^^^^^^^^^^^
:Type: mutex
:Arch: any
:Protects: - kvm_usage_count
- hardware virtualization enable/disable
:Comment: Exists to allow taking cpus_read_lock() while kvm_usage_count is
protected, which simplifies the virtualization enabling logic.
``kvm->mn_invalidate_lock``
^^^^^^^^^^^^^^^^^^^^^^^^^^^
:Type: spinlock_t
:Arch: any
:Protects: mn_active_invalidate_count, mn_memslots_update_rcuwait
``kvm_arch::tsc_write_lock``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:Type: raw_spinlock_t
:Arch: x86
:Protects: - kvm_arch::{last_tsc_write,last_tsc_nsec,last_tsc_offset}
- tsc offset in vmcb
:Comment: 'raw' because updating the tsc offsets must not be preempted.
``kvm->mmu_lock``
^^^^^^^^^^^^^^^^^
:Type: spinlock_t or rwlock_t
:Arch: any
:Protects: -shadow page/shadow tlb entry
:Comment: it is a spinlock since it is used in mmu notifier.
``kvm->srcu``
^^^^^^^^^^^^^
:Type: srcu lock
:Arch: any
:Protects: - kvm->memslots
- kvm->buses
:Comment: The srcu read lock must be held while accessing memslots (e.g.
when using gfn_to_* functions) and while accessing in-kernel
MMIO/PIO address->device structure mapping (kvm->buses).
The srcu index can be stored in kvm_vcpu->srcu_idx per vcpu
if it is needed by multiple functions.
``kvm->slots_arch_lock``
^^^^^^^^^^^^^^^^^^^^^^^^
:Type: mutex
:Arch: any (only needed on x86 though)
:Protects: any arch-specific fields of memslots that have to be modified
in a ``kvm->srcu`` read-side critical section.
:Comment: must be held before reading the pointer to the current memslots,
until after all changes to the memslots are complete
``wakeup_vcpus_on_cpu_lock``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:Type: spinlock_t
:Arch: x86
:Protects: wakeup_vcpus_on_cpu
:Comment: This is a per-CPU lock and it is used for VT-d posted-interrupts.
When VT-d posted-interrupts are supported and the VM has assigned
devices, we put the blocked vCPU on the list blocked_vcpu_on_cpu
protected by blocked_vcpu_on_cpu_lock. When VT-d hardware issues
wakeup notification event since external interrupts from the
assigned devices happens, we will find the vCPU on the list to
wakeup.
``vendor_module_lock``
^^^^^^^^^^^^^^^^^^^^^^
:Type: mutex
:Arch: x86
:Protects: loading a vendor module (kvm_amd or kvm_intel)
:Comment: Exists because using kvm_lock leads to deadlock. kvm_lock is taken
in notifiers, e.g. __kvmclock_cpufreq_notifier(), that may be invoked while
cpu_hotplug_lock is held, e.g. from cpufreq_boost_trigger_state(), and many
operations need to take cpu_hotplug_lock when loading a vendor module, e.g.
updating static calls.
요약·해설
locking.rst:1-318KVM 잠금 획득 순서와 x86 fast page fault의 SPTE·dirty bit·TLB 경쟁 방지 규칙을 정리합니다.
원문 기호, 함수명, 경로, 레지스터와 줄 좌표를 유지하면서 동작 순서와 경쟁 조건을 한국어로 풀어 설명합니다.