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