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