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