1.. SPDX-License-Identifier: GPL-2.0
2
3=================
4KVM Lock Overview
5=================
6
71. Acquisition Orders
8---------------------
9
10The acquisition orders for mutexes are as follows:
11
12- kvm->lock is taken outside vcpu->mutex
13
14- kvm->lock is taken outside kvm->slots_lock and kvm->irq_lock
15
16- kvm->slots_lock is taken outside kvm->irq_lock, though acquiring
17  them together is quite rare.
18
19- Unlike kvm->slots_lock, kvm->slots_arch_lock is released before
20  synchronize_srcu(&kvm->srcu).  Therefore kvm->slots_arch_lock
21  can be taken inside a kvm->srcu read-side critical section,
22  while kvm->slots_lock cannot.
23
24- kvm->mn_active_invalidate_count ensures that pairs of
25  invalidate_range_start() and invalidate_range_end() callbacks
26  use the same memslots array.  kvm->slots_lock and kvm->slots_arch_lock
27  are taken on the waiting side in install_new_memslots, so MMU notifiers
28  must not take either kvm->slots_lock or kvm->slots_arch_lock.
29
30On x86:
31
32- vcpu->mutex is taken outside kvm->arch.hyperv.hv_lock
33
34- kvm->arch.mmu_lock is an rwlock.  kvm->arch.tdp_mmu_pages_lock and
35  kvm->arch.mmu_unsync_pages_lock are taken inside kvm->arch.mmu_lock, and
36  cannot be taken without already holding kvm->arch.mmu_lock (typically with
37  ``read_lock`` for the TDP MMU, thus the need for additional spinlocks).
38
39Everything else is a leaf: no other lock is taken inside the critical
40sections.
41
422. Exception
43------------
44
45Fast page fault:
46
47Fast page fault is the fast path which fixes the guest page fault out of
48the mmu-lock on x86. Currently, the page fault can be fast in one of the
49following two cases:
50
511. Access Tracking: The SPTE is not present, but it is marked for access
52   tracking. That means we need to restore the saved R/X bits. This is
53   described in more detail later below.
54
552. Write-Protection: The SPTE is present and the fault is caused by
56   write-protect. That means we just need to change the W bit of the spte.
57
58What we use to avoid all the race is the Host-writable bit and MMU-writable bit
59on the spte:
60
61- Host-writable means the gfn is writable in the host kernel page tables and in
62  its KVM memslot.
63- MMU-writable means the gfn is writable in the guest's mmu and it is not
64  write-protected by shadow page write-protection.
65
66On fast page fault path, we will use cmpxchg to atomically set the spte W
67bit if spte.HOST_WRITEABLE = 1 and spte.WRITE_PROTECT = 1, to restore the saved
68R/X bits if for an access-traced spte, or both. This is safe because whenever
69changing these bits can be detected by cmpxchg.
70
71But we need carefully check these cases:
72
731) The mapping from gfn to pfn
74
75The mapping from gfn to pfn may be changed since we can only ensure the pfn
76is not changed during cmpxchg. This is a ABA problem, for example, below case
77will happen:
78
79+------------------------------------------------------------------------+
80| At the beginning::                                                     |
81|                                                                        |
82|	gpte = gfn1                                                      |
83|	gfn1 is mapped to pfn1 on host                                   |
84|	spte is the shadow page table entry corresponding with gpte and  |
85|	spte = pfn1                                                      |
86+------------------------------------------------------------------------+
87| On fast page fault path:                                               |
88+------------------------------------+-----------------------------------+
89| CPU 0:                             | CPU 1:                            |
90+------------------------------------+-----------------------------------+
91| ::                                 |                                   |
92|                                    |                                   |
93|   old_spte = *spte;                |                                   |
94+------------------------------------+-----------------------------------+
95|                                    | pfn1 is swapped out::             |
96|                                    |                                   |
97|                                    |    spte = 0;                      |
98|                                    |                                   |
99|                                    | pfn1 is re-alloced for gfn2.      |
100|                                    |                                   |
101|                                    | gpte is changed to point to       |
102|                                    | gfn2 by the guest::               |
103|                                    |                                   |
104|                                    |    spte = pfn1;                   |
105+------------------------------------+-----------------------------------+
106| ::                                                                     |
107|                                                                        |
108|   if (cmpxchg(spte, old_spte, old_spte+W)                              |
109|	mark_page_dirty(vcpu->kvm, gfn1)                                 |
110|            OOPS!!!                                                     |
111+------------------------------------------------------------------------+
112
113We dirty-log for gfn1, that means gfn2 is lost in dirty-bitmap.
114
115For direct sp, we can easily avoid it since the spte of direct sp is fixed
116to gfn.  For indirect sp, we disabled fast page fault for simplicity.
117
118A solution for indirect sp could be to pin the gfn, for example via
119kvm_vcpu_gfn_to_pfn_atomic, before the cmpxchg.  After the pinning:
120
121- We have held the refcount of pfn that means the pfn can not be freed and
122  be reused for another gfn.
123- The pfn is writable and therefore it cannot be shared between different gfns
124  by KSM.
125
126Then, we can ensure the dirty bitmaps is correctly set for a gfn.
127
1282) Dirty bit tracking
129
130In the origin code, the spte can be fast updated (non-atomically) if the
131spte is read-only and the Accessed bit has already been set since the
132Accessed bit and Dirty bit can not be lost.
133
134But it is not true after fast page fault since the spte can be marked
135writable between reading spte and updating spte. Like below case:
136
137+------------------------------------------------------------------------+
138| At the beginning::                                                     |
139|                                                                        |
140|	spte.W = 0                                                       |
141|	spte.Accessed = 1                                                |
142+------------------------------------+-----------------------------------+
143| CPU 0:                             | CPU 1:                            |
144+------------------------------------+-----------------------------------+
145| In mmu_spte_clear_track_bits()::   |                                   |
146|                                    |                                   |
147|  old_spte = *spte;                 |                                   |
148|                                    |                                   |
149|                                    |                                   |
150|  /* 'if' condition is satisfied. */|                                   |
151|  if (old_spte.Accessed == 1 &&     |                                   |
152|       old_spte.W == 0)             |                                   |
153|     spte = 0ull;                   |                                   |
154+------------------------------------+-----------------------------------+
155|                                    | on fast page fault path::         |
156|                                    |                                   |
157|                                    |    spte.W = 1                     |
158|                                    |                                   |
159|                                    | memory write on the spte::        |
160|                                    |                                   |
161|                                    |    spte.Dirty = 1                 |
162+------------------------------------+-----------------------------------+
163|  ::                                |                                   |
164|                                    |                                   |
165|   else                             |                                   |
166|     old_spte = xchg(spte, 0ull)    |                                   |
167|   if (old_spte.Accessed == 1)      |                                   |
168|     kvm_set_pfn_accessed(spte.pfn);|                                   |
169|   if (old_spte.Dirty == 1)         |                                   |
170|     kvm_set_pfn_dirty(spte.pfn);   |                                   |
171|     OOPS!!!                        |                                   |
172+------------------------------------+-----------------------------------+
173
174The Dirty bit is lost in this case.
175
176In order to avoid this kind of issue, we always treat the spte as "volatile"
177if it can be updated out of mmu-lock, see spte_has_volatile_bits(), it means,
178the spte is always atomically updated in this case.
179
1803) flush tlbs due to spte updated
181
182If the spte is updated from writable to readonly, we should flush all TLBs,
183otherwise rmap_write_protect will find a read-only spte, even though the
184writable spte might be cached on a CPU's TLB.
185
186As mentioned before, the spte can be updated to writable out of mmu-lock on
187fast page fault path, in order to easily audit the path, we see if TLBs need
188be flushed caused by this reason in mmu_spte_update() since this is a common
189function to update spte (present -> present).
190
191Since the spte is "volatile" if it can be updated out of mmu-lock, we always
192atomically update the spte, the race caused by fast page fault can be avoided,
193See the comments in spte_has_volatile_bits() and mmu_spte_update().
194
195Lockless Access Tracking:
196
197This is used for Intel CPUs that are using EPT but do not support the EPT A/D
198bits. In this case, PTEs are tagged as A/D disabled (using ignored bits), and
199when the KVM MMU notifier is called to track accesses to a page (via
200kvm_mmu_notifier_clear_flush_young), it marks the PTE not-present in hardware
201by clearing the RWX bits in the PTE and storing the original R & X bits in more
202unused/ignored bits. When the VM tries to access the page later on, a fault is
203generated and the fast page fault mechanism described above is used to
204atomically restore the PTE to a Present state. The W bit is not saved when the
205PTE is marked for access tracking and during restoration to the Present state,
206the W bit is set depending on whether or not it was a write access. If it
207wasn't, then the W bit will remain clear until a write access happens, at which
208time it will be set using the Dirty tracking mechanism described above.
209
2103. Reference
211------------
212
213:Name:		kvm_lock
214:Type:		mutex
215:Arch:		any
216:Protects:	- vm_list
217
218:Name:		kvm_count_lock
219:Type:		raw_spinlock_t
220:Arch:		any
221:Protects:	- hardware virtualization enable/disable
222:Comment:	'raw' because hardware enabling/disabling must be atomic /wrt
223		migration.
224
225:Name:		kvm_arch::tsc_write_lock
226:Type:		raw_spinlock
227:Arch:		x86
228:Protects:	- kvm_arch::{last_tsc_write,last_tsc_nsec,last_tsc_offset}
229		- tsc offset in vmcb
230:Comment:	'raw' because updating the tsc offsets must not be preempted.
231
232:Name:		kvm->mmu_lock
233:Type:		spinlock_t
234:Arch:		any
235:Protects:	-shadow page/shadow tlb entry
236:Comment:	it is a spinlock since it is used in mmu notifier.
237
238:Name:		kvm->srcu
239:Type:		srcu lock
240:Arch:		any
241:Protects:	- kvm->memslots
242		- kvm->buses
243:Comment:	The srcu read lock must be held while accessing memslots (e.g.
244		when using gfn_to_* functions) and while accessing in-kernel
245		MMIO/PIO address->device structure mapping (kvm->buses).
246		The srcu index can be stored in kvm_vcpu->srcu_idx per vcpu
247		if it is needed by multiple functions.
248
249:Name:		blocked_vcpu_on_cpu_lock
250:Type:		spinlock_t
251:Arch:		x86
252:Protects:	blocked_vcpu_on_cpu
253:Comment:	This is a per-CPU lock and it is used for VT-d posted-interrupts.
254		When VT-d posted-interrupts is supported and the VM has assigned
255		devices, we put the blocked vCPU on the list blocked_vcpu_on_cpu
256		protected by blocked_vcpu_on_cpu_lock, when VT-d hardware issues
257		wakeup notification event since external interrupts from the
258		assigned devices happens, we will find the vCPU on the list to
259		wakeup.
260