]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/vmm/io/vlapic.c
cpuset(9): Add CPU_FOREACH_IS(SET|CLR) and modify consumers to use it
[FreeBSD/FreeBSD.git] / sys / amd64 / vmm / io / vlapic.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2011 NetApp, Inc.
5  * All rights reserved.
6  * Copyright (c) 2019 Joyent, Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $FreeBSD$
30  */
31
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34
35 #include "opt_bhyve_snapshot.h"
36
37 #include <sys/param.h>
38 #include <sys/lock.h>
39 #include <sys/kernel.h>
40 #include <sys/malloc.h>
41 #include <sys/mutex.h>
42 #include <sys/systm.h>
43 #include <sys/smp.h>
44
45 #include <x86/specialreg.h>
46 #include <x86/apicreg.h>
47
48 #include <machine/clock.h>
49 #include <machine/smp.h>
50
51 #include <machine/vmm.h>
52 #include <machine/vmm_snapshot.h>
53
54 #include "vmm_lapic.h"
55 #include "vmm_ktr.h"
56 #include "vmm_stat.h"
57
58 #include "vlapic.h"
59 #include "vlapic_priv.h"
60 #include "vioapic.h"
61
62 #define PRIO(x)                 ((x) >> 4)
63
64 #define VLAPIC_VERSION          (16)
65
66 #define x2apic(vlapic)  (((vlapic)->msr_apicbase & APICBASE_X2APIC) ? 1 : 0)
67
68 /*
69  * The 'vlapic->timer_mtx' is used to provide mutual exclusion between the
70  * vlapic_callout_handler() and vcpu accesses to:
71  * - timer_freq_bt, timer_period_bt, timer_fire_bt
72  * - timer LVT register
73  */
74 #define VLAPIC_TIMER_LOCK(vlapic)       mtx_lock_spin(&((vlapic)->timer_mtx))
75 #define VLAPIC_TIMER_UNLOCK(vlapic)     mtx_unlock_spin(&((vlapic)->timer_mtx))
76 #define VLAPIC_TIMER_LOCKED(vlapic)     mtx_owned(&((vlapic)->timer_mtx))
77
78 /*
79  * APIC timer frequency:
80  * - arbitrary but chosen to be in the ballpark of contemporary hardware.
81  * - power-of-two to avoid loss of precision when converted to a bintime.
82  */
83 #define VLAPIC_BUS_FREQ         (128 * 1024 * 1024)
84
85 static void vlapic_set_error(struct vlapic *, uint32_t, bool);
86
87 static __inline uint32_t
88 vlapic_get_id(struct vlapic *vlapic)
89 {
90
91         if (x2apic(vlapic))
92                 return (vlapic->vcpuid);
93         else
94                 return (vlapic->vcpuid << 24);
95 }
96
97 static uint32_t
98 x2apic_ldr(struct vlapic *vlapic)
99 {
100         int apicid;
101         uint32_t ldr;
102
103         apicid = vlapic_get_id(vlapic);
104         ldr = 1 << (apicid & 0xf);
105         ldr |= (apicid & 0xffff0) << 12;
106         return (ldr);
107 }
108
109 void
110 vlapic_dfr_write_handler(struct vlapic *vlapic)
111 {
112         struct LAPIC *lapic;
113
114         lapic = vlapic->apic_page;
115         if (x2apic(vlapic)) {
116                 VM_CTR1(vlapic->vm, "ignoring write to DFR in x2apic mode: %#x",
117                     lapic->dfr);
118                 lapic->dfr = 0;
119                 return;
120         }
121
122         lapic->dfr &= APIC_DFR_MODEL_MASK;
123         lapic->dfr |= APIC_DFR_RESERVED;
124
125         if ((lapic->dfr & APIC_DFR_MODEL_MASK) == APIC_DFR_MODEL_FLAT)
126                 VLAPIC_CTR0(vlapic, "vlapic DFR in Flat Model");
127         else if ((lapic->dfr & APIC_DFR_MODEL_MASK) == APIC_DFR_MODEL_CLUSTER)
128                 VLAPIC_CTR0(vlapic, "vlapic DFR in Cluster Model");
129         else
130                 VLAPIC_CTR1(vlapic, "DFR in Unknown Model %#x", lapic->dfr);
131 }
132
133 void
134 vlapic_ldr_write_handler(struct vlapic *vlapic)
135 {
136         struct LAPIC *lapic;
137
138         lapic = vlapic->apic_page;
139
140         /* LDR is read-only in x2apic mode */
141         if (x2apic(vlapic)) {
142                 VLAPIC_CTR1(vlapic, "ignoring write to LDR in x2apic mode: %#x",
143                     lapic->ldr);
144                 lapic->ldr = x2apic_ldr(vlapic);
145         } else {
146                 lapic->ldr &= ~APIC_LDR_RESERVED;
147                 VLAPIC_CTR1(vlapic, "vlapic LDR set to %#x", lapic->ldr);
148         }
149 }
150
151 void
152 vlapic_id_write_handler(struct vlapic *vlapic)
153 {
154         struct LAPIC *lapic;
155
156         /*
157          * We don't allow the ID register to be modified so reset it back to
158          * its default value.
159          */
160         lapic = vlapic->apic_page;
161         lapic->id = vlapic_get_id(vlapic);
162 }
163
164 static int
165 vlapic_timer_divisor(uint32_t dcr)
166 {
167         switch (dcr & 0xB) {
168         case APIC_TDCR_1:
169                 return (1);
170         case APIC_TDCR_2:
171                 return (2);
172         case APIC_TDCR_4:
173                 return (4);
174         case APIC_TDCR_8:
175                 return (8);
176         case APIC_TDCR_16:
177                 return (16);
178         case APIC_TDCR_32:
179                 return (32);
180         case APIC_TDCR_64:
181                 return (64);
182         case APIC_TDCR_128:
183                 return (128);
184         default:
185                 panic("vlapic_timer_divisor: invalid dcr 0x%08x", dcr);
186         }
187 }
188
189 #if 0
190 static inline void
191 vlapic_dump_lvt(uint32_t offset, uint32_t *lvt)
192 {
193         printf("Offset %x: lvt %08x (V:%02x DS:%x M:%x)\n", offset,
194             *lvt, *lvt & APIC_LVTT_VECTOR, *lvt & APIC_LVTT_DS,
195             *lvt & APIC_LVTT_M);
196 }
197 #endif
198
199 static uint32_t
200 vlapic_get_ccr(struct vlapic *vlapic)
201 {
202         struct bintime bt_now, bt_rem;
203         struct LAPIC *lapic;
204         uint32_t ccr;
205
206         ccr = 0;
207         lapic = vlapic->apic_page;
208
209         VLAPIC_TIMER_LOCK(vlapic);
210         if (callout_active(&vlapic->callout)) {
211                 /*
212                  * If the timer is scheduled to expire in the future then
213                  * compute the value of 'ccr' based on the remaining time.
214                  */
215                 binuptime(&bt_now);
216                 if (bintime_cmp(&vlapic->timer_fire_bt, &bt_now, >)) {
217                         bt_rem = vlapic->timer_fire_bt;
218                         bintime_sub(&bt_rem, &bt_now);
219                         ccr += bt_rem.sec * BT2FREQ(&vlapic->timer_freq_bt);
220                         ccr += bt_rem.frac / vlapic->timer_freq_bt.frac;
221                 }
222         }
223         KASSERT(ccr <= lapic->icr_timer, ("vlapic_get_ccr: invalid ccr %#x, "
224             "icr_timer is %#x", ccr, lapic->icr_timer));
225         VLAPIC_CTR2(vlapic, "vlapic ccr_timer = %#x, icr_timer = %#x",
226             ccr, lapic->icr_timer);
227         VLAPIC_TIMER_UNLOCK(vlapic);
228         return (ccr);
229 }
230
231 void
232 vlapic_dcr_write_handler(struct vlapic *vlapic)
233 {
234         struct LAPIC *lapic;
235         int divisor;
236
237         lapic = vlapic->apic_page;
238         VLAPIC_TIMER_LOCK(vlapic);
239
240         divisor = vlapic_timer_divisor(lapic->dcr_timer);
241         VLAPIC_CTR2(vlapic, "vlapic dcr_timer=%#x, divisor=%d",
242             lapic->dcr_timer, divisor);
243
244         /*
245          * Update the timer frequency and the timer period.
246          *
247          * XXX changes to the frequency divider will not take effect until
248          * the timer is reloaded.
249          */
250         FREQ2BT(VLAPIC_BUS_FREQ / divisor, &vlapic->timer_freq_bt);
251         vlapic->timer_period_bt = vlapic->timer_freq_bt;
252         bintime_mul(&vlapic->timer_period_bt, lapic->icr_timer);
253
254         VLAPIC_TIMER_UNLOCK(vlapic);
255 }
256
257 void
258 vlapic_esr_write_handler(struct vlapic *vlapic)
259 {
260         struct LAPIC *lapic;
261
262         lapic = vlapic->apic_page;
263         lapic->esr = vlapic->esr_pending;
264         vlapic->esr_pending = 0;
265 }
266
267 int
268 vlapic_set_intr_ready(struct vlapic *vlapic, int vector, bool level)
269 {
270         struct LAPIC *lapic;
271         uint32_t *irrptr, *tmrptr, mask;
272         int idx;
273
274         KASSERT(vector >= 0 && vector < 256, ("invalid vector %d", vector));
275
276         lapic = vlapic->apic_page;
277         if (!(lapic->svr & APIC_SVR_ENABLE)) {
278                 VLAPIC_CTR1(vlapic, "vlapic is software disabled, ignoring "
279                     "interrupt %d", vector);
280                 return (0);
281         }
282
283         if (vector < 16) {
284                 vlapic_set_error(vlapic, APIC_ESR_RECEIVE_ILLEGAL_VECTOR,
285                     false);
286                 VLAPIC_CTR1(vlapic, "vlapic ignoring interrupt to vector %d",
287                     vector);
288                 return (1);
289         }
290
291         if (vlapic->ops.set_intr_ready)
292                 return ((*vlapic->ops.set_intr_ready)(vlapic, vector, level));
293
294         idx = (vector / 32) * 4;
295         mask = 1 << (vector % 32);
296
297         irrptr = &lapic->irr0;
298         atomic_set_int(&irrptr[idx], mask);
299
300         /*
301          * Verify that the trigger-mode of the interrupt matches with
302          * the vlapic TMR registers.
303          */
304         tmrptr = &lapic->tmr0;
305         if ((tmrptr[idx] & mask) != (level ? mask : 0)) {
306                 VLAPIC_CTR3(vlapic, "vlapic TMR[%d] is 0x%08x but "
307                     "interrupt is %s-triggered", idx / 4, tmrptr[idx],
308                     level ? "level" : "edge");
309         }
310
311         VLAPIC_CTR_IRR(vlapic, "vlapic_set_intr_ready");
312         return (1);
313 }
314
315 static __inline uint32_t *
316 vlapic_get_lvtptr(struct vlapic *vlapic, uint32_t offset)
317 {
318         struct LAPIC    *lapic = vlapic->apic_page;
319         int              i;
320
321         switch (offset) {
322         case APIC_OFFSET_CMCI_LVT:
323                 return (&lapic->lvt_cmci);
324         case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
325                 i = (offset - APIC_OFFSET_TIMER_LVT) >> 2;
326                 return ((&lapic->lvt_timer) + i);
327         default:
328                 panic("vlapic_get_lvt: invalid LVT\n");
329         }
330 }
331
332 static __inline int
333 lvt_off_to_idx(uint32_t offset)
334 {
335         int index;
336
337         switch (offset) {
338         case APIC_OFFSET_CMCI_LVT:
339                 index = APIC_LVT_CMCI;
340                 break;
341         case APIC_OFFSET_TIMER_LVT:
342                 index = APIC_LVT_TIMER;
343                 break;
344         case APIC_OFFSET_THERM_LVT:
345                 index = APIC_LVT_THERMAL;
346                 break;
347         case APIC_OFFSET_PERF_LVT:
348                 index = APIC_LVT_PMC;
349                 break;
350         case APIC_OFFSET_LINT0_LVT:
351                 index = APIC_LVT_LINT0;
352                 break;
353         case APIC_OFFSET_LINT1_LVT:
354                 index = APIC_LVT_LINT1;
355                 break;
356         case APIC_OFFSET_ERROR_LVT:
357                 index = APIC_LVT_ERROR;
358                 break;
359         default:
360                 index = -1;
361                 break;
362         }
363         KASSERT(index >= 0 && index <= VLAPIC_MAXLVT_INDEX, ("lvt_off_to_idx: "
364             "invalid lvt index %d for offset %#x", index, offset));
365
366         return (index);
367 }
368
369 static __inline uint32_t
370 vlapic_get_lvt(struct vlapic *vlapic, uint32_t offset)
371 {
372         int idx;
373         uint32_t val;
374
375         idx = lvt_off_to_idx(offset);
376         val = atomic_load_acq_32(&vlapic->lvt_last[idx]);
377         return (val);
378 }
379
380 void
381 vlapic_lvt_write_handler(struct vlapic *vlapic, uint32_t offset)
382 {
383         uint32_t *lvtptr, mask, val;
384         struct LAPIC *lapic;
385         int idx;
386
387         lapic = vlapic->apic_page;
388         lvtptr = vlapic_get_lvtptr(vlapic, offset);     
389         val = *lvtptr;
390         idx = lvt_off_to_idx(offset);
391
392         if (!(lapic->svr & APIC_SVR_ENABLE))
393                 val |= APIC_LVT_M;
394         mask = APIC_LVT_M | APIC_LVT_DS | APIC_LVT_VECTOR;
395         switch (offset) {
396         case APIC_OFFSET_TIMER_LVT:
397                 mask |= APIC_LVTT_TM;
398                 break;
399         case APIC_OFFSET_ERROR_LVT:
400                 break;
401         case APIC_OFFSET_LINT0_LVT:
402         case APIC_OFFSET_LINT1_LVT:
403                 mask |= APIC_LVT_TM | APIC_LVT_RIRR | APIC_LVT_IIPP;
404                 /* FALLTHROUGH */
405         default:
406                 mask |= APIC_LVT_DM;
407                 break;
408         }
409         val &= mask;
410         *lvtptr = val;
411         atomic_store_rel_32(&vlapic->lvt_last[idx], val);
412 }
413
414 static void
415 vlapic_mask_lvts(struct vlapic *vlapic)
416 {
417         struct LAPIC *lapic = vlapic->apic_page;
418
419         lapic->lvt_cmci |= APIC_LVT_M;
420         vlapic_lvt_write_handler(vlapic, APIC_OFFSET_CMCI_LVT);
421
422         lapic->lvt_timer |= APIC_LVT_M;
423         vlapic_lvt_write_handler(vlapic, APIC_OFFSET_TIMER_LVT);
424
425         lapic->lvt_thermal |= APIC_LVT_M;
426         vlapic_lvt_write_handler(vlapic, APIC_OFFSET_THERM_LVT);
427
428         lapic->lvt_pcint |= APIC_LVT_M;
429         vlapic_lvt_write_handler(vlapic, APIC_OFFSET_PERF_LVT);
430
431         lapic->lvt_lint0 |= APIC_LVT_M;
432         vlapic_lvt_write_handler(vlapic, APIC_OFFSET_LINT0_LVT);
433
434         lapic->lvt_lint1 |= APIC_LVT_M;
435         vlapic_lvt_write_handler(vlapic, APIC_OFFSET_LINT1_LVT);
436
437         lapic->lvt_error |= APIC_LVT_M;
438         vlapic_lvt_write_handler(vlapic, APIC_OFFSET_ERROR_LVT);
439 }
440
441 static int
442 vlapic_fire_lvt(struct vlapic *vlapic, u_int lvt)
443 {
444         uint32_t mode, reg, vec;
445
446         reg = atomic_load_acq_32(&vlapic->lvt_last[lvt]);
447
448         if (reg & APIC_LVT_M)
449                 return (0);
450         vec = reg & APIC_LVT_VECTOR;
451         mode = reg & APIC_LVT_DM;
452
453         switch (mode) {
454         case APIC_LVT_DM_FIXED:
455                 if (vec < 16) {
456                         vlapic_set_error(vlapic, APIC_ESR_SEND_ILLEGAL_VECTOR,
457                             lvt == APIC_LVT_ERROR);
458                         return (0);
459                 }
460                 if (vlapic_set_intr_ready(vlapic, vec, false))
461                         vcpu_notify_event(vlapic->vm, vlapic->vcpuid, true);
462                 break;
463         case APIC_LVT_DM_NMI:
464                 vm_inject_nmi(vlapic->vm, vlapic->vcpuid);
465                 break;
466         case APIC_LVT_DM_EXTINT:
467                 vm_inject_extint(vlapic->vm, vlapic->vcpuid);
468                 break;
469         default:
470                 // Other modes ignored
471                 return (0);
472         }
473         return (1);
474 }
475
476 #if 1
477 static void
478 dump_isrvec_stk(struct vlapic *vlapic)
479 {
480         int i;
481         uint32_t *isrptr;
482
483         isrptr = &vlapic->apic_page->isr0;
484         for (i = 0; i < 8; i++)
485                 printf("ISR%d 0x%08x\n", i, isrptr[i * 4]);
486
487         for (i = 0; i <= vlapic->isrvec_stk_top; i++)
488                 printf("isrvec_stk[%d] = %d\n", i, vlapic->isrvec_stk[i]);
489 }
490 #endif
491
492 /*
493  * Algorithm adopted from section "Interrupt, Task and Processor Priority"
494  * in Intel Architecture Manual Vol 3a.
495  */
496 static void
497 vlapic_update_ppr(struct vlapic *vlapic)
498 {
499         int isrvec, tpr, ppr;
500
501         /*
502          * Note that the value on the stack at index 0 is always 0.
503          *
504          * This is a placeholder for the value of ISRV when none of the
505          * bits is set in the ISRx registers.
506          */
507         isrvec = vlapic->isrvec_stk[vlapic->isrvec_stk_top];
508         tpr = vlapic->apic_page->tpr;
509
510 #if 1
511         {
512                 int i, lastprio, curprio, vector, idx;
513                 uint32_t *isrptr;
514
515                 if (vlapic->isrvec_stk_top == 0 && isrvec != 0)
516                         panic("isrvec_stk is corrupted: %d", isrvec);
517
518                 /*
519                  * Make sure that the priority of the nested interrupts is
520                  * always increasing.
521                  */
522                 lastprio = -1;
523                 for (i = 1; i <= vlapic->isrvec_stk_top; i++) {
524                         curprio = PRIO(vlapic->isrvec_stk[i]);
525                         if (curprio <= lastprio) {
526                                 dump_isrvec_stk(vlapic);
527                                 panic("isrvec_stk does not satisfy invariant");
528                         }
529                         lastprio = curprio;
530                 }
531
532                 /*
533                  * Make sure that each bit set in the ISRx registers has a
534                  * corresponding entry on the isrvec stack.
535                  */
536                 i = 1;
537                 isrptr = &vlapic->apic_page->isr0;
538                 for (vector = 0; vector < 256; vector++) {
539                         idx = (vector / 32) * 4;
540                         if (isrptr[idx] & (1 << (vector % 32))) {
541                                 if (i > vlapic->isrvec_stk_top ||
542                                     vlapic->isrvec_stk[i] != vector) {
543                                         dump_isrvec_stk(vlapic);
544                                         panic("ISR and isrvec_stk out of sync");
545                                 }
546                                 i++;
547                         }
548                 }
549         }
550 #endif
551
552         if (PRIO(tpr) >= PRIO(isrvec))
553                 ppr = tpr;
554         else
555                 ppr = isrvec & 0xf0;
556
557         vlapic->apic_page->ppr = ppr;
558         VLAPIC_CTR1(vlapic, "vlapic_update_ppr 0x%02x", ppr);
559 }
560
561 void
562 vlapic_sync_tpr(struct vlapic *vlapic)
563 {
564         vlapic_update_ppr(vlapic);
565 }
566
567 static VMM_STAT(VLAPIC_GRATUITOUS_EOI, "EOI without any in-service interrupt");
568
569 static void
570 vlapic_process_eoi(struct vlapic *vlapic)
571 {
572         struct LAPIC    *lapic = vlapic->apic_page;
573         uint32_t        *isrptr, *tmrptr;
574         int             i, idx, bitpos, vector;
575
576         isrptr = &lapic->isr0;
577         tmrptr = &lapic->tmr0;
578
579         for (i = 7; i >= 0; i--) {
580                 idx = i * 4;
581                 bitpos = fls(isrptr[idx]);
582                 if (bitpos-- != 0) {
583                         if (vlapic->isrvec_stk_top <= 0) {
584                                 panic("invalid vlapic isrvec_stk_top %d",
585                                       vlapic->isrvec_stk_top);
586                         }
587                         isrptr[idx] &= ~(1 << bitpos);
588                         vector = i * 32 + bitpos;
589                         VCPU_CTR1(vlapic->vm, vlapic->vcpuid, "EOI vector %d",
590                             vector);
591                         VLAPIC_CTR_ISR(vlapic, "vlapic_process_eoi");
592                         vlapic->isrvec_stk_top--;
593                         vlapic_update_ppr(vlapic);
594                         if ((tmrptr[idx] & (1 << bitpos)) != 0) {
595                                 vioapic_process_eoi(vlapic->vm, vlapic->vcpuid,
596                                     vector);
597                         }
598                         return;
599                 }
600         }
601         VCPU_CTR0(vlapic->vm, vlapic->vcpuid, "Gratuitous EOI");
602         vmm_stat_incr(vlapic->vm, vlapic->vcpuid, VLAPIC_GRATUITOUS_EOI, 1);
603 }
604
605 static __inline int
606 vlapic_get_lvt_field(uint32_t lvt, uint32_t mask)
607 {
608
609         return (lvt & mask);
610 }
611
612 static __inline int
613 vlapic_periodic_timer(struct vlapic *vlapic)
614 {
615         uint32_t lvt;
616
617         lvt = vlapic_get_lvt(vlapic, APIC_OFFSET_TIMER_LVT);
618
619         return (vlapic_get_lvt_field(lvt, APIC_LVTT_TM_PERIODIC));
620 }
621
622 static VMM_STAT(VLAPIC_INTR_ERROR, "error interrupts generated by vlapic");
623
624 static void
625 vlapic_set_error(struct vlapic *vlapic, uint32_t mask, bool lvt_error)
626 {
627
628         vlapic->esr_pending |= mask;
629
630         /*
631          * Avoid infinite recursion if the error LVT itself is configured with
632          * an illegal vector.
633          */
634         if (lvt_error)
635                 return;
636
637         if (vlapic_fire_lvt(vlapic, APIC_LVT_ERROR)) {
638                 vmm_stat_incr(vlapic->vm, vlapic->vcpuid, VLAPIC_INTR_ERROR, 1);
639         }
640 }
641
642 static VMM_STAT(VLAPIC_INTR_TIMER, "timer interrupts generated by vlapic");
643
644 static void
645 vlapic_fire_timer(struct vlapic *vlapic)
646 {
647
648         KASSERT(VLAPIC_TIMER_LOCKED(vlapic), ("vlapic_fire_timer not locked"));
649
650         if (vlapic_fire_lvt(vlapic, APIC_LVT_TIMER)) {
651                 VLAPIC_CTR0(vlapic, "vlapic timer fired");
652                 vmm_stat_incr(vlapic->vm, vlapic->vcpuid, VLAPIC_INTR_TIMER, 1);
653         }
654 }
655
656 static VMM_STAT(VLAPIC_INTR_CMC,
657     "corrected machine check interrupts generated by vlapic");
658
659 void
660 vlapic_fire_cmci(struct vlapic *vlapic)
661 {
662
663         if (vlapic_fire_lvt(vlapic, APIC_LVT_CMCI)) {
664                 vmm_stat_incr(vlapic->vm, vlapic->vcpuid, VLAPIC_INTR_CMC, 1);
665         }
666 }
667
668 static VMM_STAT_ARRAY(LVTS_TRIGGERRED, VLAPIC_MAXLVT_INDEX + 1,
669     "lvts triggered");
670
671 int
672 vlapic_trigger_lvt(struct vlapic *vlapic, int vector)
673 {
674
675         if (vlapic_enabled(vlapic) == false) {
676                 /*
677                  * When the local APIC is global/hardware disabled,
678                  * LINT[1:0] pins are configured as INTR and NMI pins,
679                  * respectively.
680                 */
681                 switch (vector) {
682                         case APIC_LVT_LINT0:
683                                 vm_inject_extint(vlapic->vm, vlapic->vcpuid);
684                                 break;
685                         case APIC_LVT_LINT1:
686                                 vm_inject_nmi(vlapic->vm, vlapic->vcpuid);
687                                 break;
688                         default:
689                                 break;
690                 }
691                 return (0);
692         }
693
694         switch (vector) {
695         case APIC_LVT_LINT0:
696         case APIC_LVT_LINT1:
697         case APIC_LVT_TIMER:
698         case APIC_LVT_ERROR:
699         case APIC_LVT_PMC:
700         case APIC_LVT_THERMAL:
701         case APIC_LVT_CMCI:
702                 if (vlapic_fire_lvt(vlapic, vector)) {
703                         vmm_stat_array_incr(vlapic->vm, vlapic->vcpuid,
704                             LVTS_TRIGGERRED, vector, 1);
705                 }
706                 break;
707         default:
708                 return (EINVAL);
709         }
710         return (0);
711 }
712
713 static void
714 vlapic_callout_handler(void *arg)
715 {
716         struct vlapic *vlapic;
717         struct bintime bt, btnow;
718         sbintime_t rem_sbt;
719
720         vlapic = arg;
721
722         VLAPIC_TIMER_LOCK(vlapic);
723         if (callout_pending(&vlapic->callout))  /* callout was reset */
724                 goto done;
725
726         if (!callout_active(&vlapic->callout))  /* callout was stopped */
727                 goto done;
728
729         callout_deactivate(&vlapic->callout);
730
731         vlapic_fire_timer(vlapic);
732
733         if (vlapic_periodic_timer(vlapic)) {
734                 binuptime(&btnow);
735                 KASSERT(bintime_cmp(&btnow, &vlapic->timer_fire_bt, >=),
736                     ("vlapic callout at %#lx.%#lx, expected at %#lx.#%lx",
737                     btnow.sec, btnow.frac, vlapic->timer_fire_bt.sec,
738                     vlapic->timer_fire_bt.frac));
739
740                 /*
741                  * Compute the delta between when the timer was supposed to
742                  * fire and the present time.
743                  */
744                 bt = btnow;
745                 bintime_sub(&bt, &vlapic->timer_fire_bt);
746
747                 rem_sbt = bttosbt(vlapic->timer_period_bt);
748                 if (bintime_cmp(&bt, &vlapic->timer_period_bt, <)) {
749                         /*
750                          * Adjust the time until the next countdown downward
751                          * to account for the lost time.
752                          */
753                         rem_sbt -= bttosbt(bt);
754                 } else {
755                         /*
756                          * If the delta is greater than the timer period then
757                          * just reset our time base instead of trying to catch
758                          * up.
759                          */
760                         vlapic->timer_fire_bt = btnow;
761                         VLAPIC_CTR2(vlapic, "vlapic timer lagging by %lu "
762                             "usecs, period is %lu usecs - resetting time base",
763                             bttosbt(bt) / SBT_1US,
764                             bttosbt(vlapic->timer_period_bt) / SBT_1US);
765                 }
766
767                 bintime_add(&vlapic->timer_fire_bt, &vlapic->timer_period_bt);
768                 callout_reset_sbt(&vlapic->callout, rem_sbt, 0,
769                     vlapic_callout_handler, vlapic, 0);
770         }
771 done:
772         VLAPIC_TIMER_UNLOCK(vlapic);
773 }
774
775 void
776 vlapic_icrtmr_write_handler(struct vlapic *vlapic)
777 {
778         struct LAPIC *lapic;
779         sbintime_t sbt;
780         uint32_t icr_timer;
781
782         VLAPIC_TIMER_LOCK(vlapic);
783
784         lapic = vlapic->apic_page;
785         icr_timer = lapic->icr_timer;
786
787         vlapic->timer_period_bt = vlapic->timer_freq_bt;
788         bintime_mul(&vlapic->timer_period_bt, icr_timer);
789
790         if (icr_timer != 0) {
791                 binuptime(&vlapic->timer_fire_bt);
792                 bintime_add(&vlapic->timer_fire_bt, &vlapic->timer_period_bt);
793
794                 sbt = bttosbt(vlapic->timer_period_bt);
795                 callout_reset_sbt(&vlapic->callout, sbt, 0,
796                     vlapic_callout_handler, vlapic, 0);
797         } else
798                 callout_stop(&vlapic->callout);
799
800         VLAPIC_TIMER_UNLOCK(vlapic);
801 }
802
803 /*
804  * This function populates 'dmask' with the set of vcpus that match the
805  * addressing specified by the (dest, phys, lowprio) tuple.
806  * 
807  * 'x2apic_dest' specifies whether 'dest' is interpreted as x2APIC (32-bit)
808  * or xAPIC (8-bit) destination field.
809  */
810 static void
811 vlapic_calcdest(struct vm *vm, cpuset_t *dmask, uint32_t dest, bool phys,
812     bool lowprio, bool x2apic_dest)
813 {
814         struct vlapic *vlapic;
815         uint32_t dfr, ldr, ldest, cluster;
816         uint32_t mda_flat_ldest, mda_cluster_ldest, mda_ldest, mda_cluster_id;
817         cpuset_t amask;
818         int vcpuid;
819
820         if ((x2apic_dest && dest == 0xffffffff) ||
821             (!x2apic_dest && dest == 0xff)) {
822                 /*
823                  * Broadcast in both logical and physical modes.
824                  */
825                 *dmask = vm_active_cpus(vm);
826                 return;
827         }
828
829         if (phys) {
830                 /*
831                  * Physical mode: destination is APIC ID.
832                  */
833                 CPU_ZERO(dmask);
834                 vcpuid = vm_apicid2vcpuid(vm, dest);
835                 amask = vm_active_cpus(vm);
836                 if (vcpuid < vm_get_maxcpus(vm) && CPU_ISSET(vcpuid, &amask))
837                         CPU_SET(vcpuid, dmask);
838         } else {
839                 /*
840                  * In the "Flat Model" the MDA is interpreted as an 8-bit wide
841                  * bitmask. This model is only available in the xAPIC mode.
842                  */
843                 mda_flat_ldest = dest & 0xff;
844
845                 /*
846                  * In the "Cluster Model" the MDA is used to identify a
847                  * specific cluster and a set of APICs in that cluster.
848                  */
849                 if (x2apic_dest) {
850                         mda_cluster_id = dest >> 16;
851                         mda_cluster_ldest = dest & 0xffff;
852                 } else {
853                         mda_cluster_id = (dest >> 4) & 0xf;
854                         mda_cluster_ldest = dest & 0xf;
855                 }
856
857                 /*
858                  * Logical mode: match each APIC that has a bit set
859                  * in its LDR that matches a bit in the ldest.
860                  */
861                 CPU_ZERO(dmask);
862                 amask = vm_active_cpus(vm);
863                 CPU_FOREACH_ISSET(vcpuid, &amask) {
864                         vlapic = vm_lapic(vm, vcpuid);
865                         dfr = vlapic->apic_page->dfr;
866                         ldr = vlapic->apic_page->ldr;
867
868                         if ((dfr & APIC_DFR_MODEL_MASK) ==
869                             APIC_DFR_MODEL_FLAT) {
870                                 ldest = ldr >> 24;
871                                 mda_ldest = mda_flat_ldest;
872                         } else if ((dfr & APIC_DFR_MODEL_MASK) ==
873                             APIC_DFR_MODEL_CLUSTER) {
874                                 if (x2apic(vlapic)) {
875                                         cluster = ldr >> 16;
876                                         ldest = ldr & 0xffff;
877                                 } else {
878                                         cluster = ldr >> 28;
879                                         ldest = (ldr >> 24) & 0xf;
880                                 }
881                                 if (cluster != mda_cluster_id)
882                                         continue;
883                                 mda_ldest = mda_cluster_ldest;
884                         } else {
885                                 /*
886                                  * Guest has configured a bad logical
887                                  * model for this vcpu - skip it.
888                                  */
889                                 VLAPIC_CTR1(vlapic, "vlapic has bad logical "
890                                     "model %x - cannot deliver interrupt", dfr);
891                                 continue;
892                         }
893
894                         if ((mda_ldest & ldest) != 0) {
895                                 CPU_SET(vcpuid, dmask);
896                                 if (lowprio)
897                                         break;
898                         }
899                 }
900         }
901 }
902
903 static VMM_STAT_ARRAY(IPIS_SENT, VM_MAXCPU, "ipis sent to vcpu");
904
905 static void
906 vlapic_set_tpr(struct vlapic *vlapic, uint8_t val)
907 {
908         struct LAPIC *lapic = vlapic->apic_page;
909
910         if (lapic->tpr != val) {
911                 VCPU_CTR2(vlapic->vm, vlapic->vcpuid, "vlapic TPR changed "
912                     "from %#x to %#x", lapic->tpr, val);
913                 lapic->tpr = val;
914                 vlapic_update_ppr(vlapic);
915         }
916 }
917
918 static uint8_t
919 vlapic_get_tpr(struct vlapic *vlapic)
920 {
921         struct LAPIC *lapic = vlapic->apic_page;
922
923         return (lapic->tpr);
924 }
925
926 void
927 vlapic_set_cr8(struct vlapic *vlapic, uint64_t val)
928 {
929         uint8_t tpr;
930
931         if (val & ~0xf) {
932                 vm_inject_gp(vlapic->vm, vlapic->vcpuid);
933                 return;
934         }
935
936         tpr = val << 4;
937         vlapic_set_tpr(vlapic, tpr);
938 }
939
940 uint64_t
941 vlapic_get_cr8(struct vlapic *vlapic)
942 {
943         uint8_t tpr;
944
945         tpr = vlapic_get_tpr(vlapic);
946         return (tpr >> 4);
947 }
948
949 int
950 vlapic_icrlo_write_handler(struct vlapic *vlapic, bool *retu)
951 {
952         int i;
953         bool phys;
954         cpuset_t dmask;
955         uint64_t icrval;
956         uint32_t dest, vec, mode;
957         struct vlapic *vlapic2;
958         struct vm_exit *vmexit;
959         struct LAPIC *lapic;
960         uint16_t maxcpus;
961
962         lapic = vlapic->apic_page;
963         lapic->icr_lo &= ~APIC_DELSTAT_PEND;
964         icrval = ((uint64_t)lapic->icr_hi << 32) | lapic->icr_lo;
965
966         if (x2apic(vlapic))
967                 dest = icrval >> 32;
968         else
969                 dest = icrval >> (32 + 24);
970         vec = icrval & APIC_VECTOR_MASK;
971         mode = icrval & APIC_DELMODE_MASK;
972
973         if (mode == APIC_DELMODE_FIXED && vec < 16) {
974                 vlapic_set_error(vlapic, APIC_ESR_SEND_ILLEGAL_VECTOR, false);
975                 VLAPIC_CTR1(vlapic, "Ignoring invalid IPI %d", vec);
976                 return (0);
977         }
978
979         VLAPIC_CTR2(vlapic, "icrlo 0x%016lx triggered ipi %d", icrval, vec);
980
981         if (mode == APIC_DELMODE_FIXED || mode == APIC_DELMODE_NMI) {
982                 switch (icrval & APIC_DEST_MASK) {
983                 case APIC_DEST_DESTFLD:
984                         phys = ((icrval & APIC_DESTMODE_LOG) == 0);
985                         vlapic_calcdest(vlapic->vm, &dmask, dest, phys, false,
986                             x2apic(vlapic));
987                         break;
988                 case APIC_DEST_SELF:
989                         CPU_SETOF(vlapic->vcpuid, &dmask);
990                         break;
991                 case APIC_DEST_ALLISELF:
992                         dmask = vm_active_cpus(vlapic->vm);
993                         break;
994                 case APIC_DEST_ALLESELF:
995                         dmask = vm_active_cpus(vlapic->vm);
996                         CPU_CLR(vlapic->vcpuid, &dmask);
997                         break;
998                 default:
999                         CPU_ZERO(&dmask);       /* satisfy gcc */
1000                         break;
1001                 }
1002
1003                 CPU_FOREACH_ISSET(i, &dmask) {
1004                         if (mode == APIC_DELMODE_FIXED) {
1005                                 lapic_intr_edge(vlapic->vm, i, vec);
1006                                 vmm_stat_array_incr(vlapic->vm, vlapic->vcpuid,
1007                                                     IPIS_SENT, i, 1);
1008                                 VLAPIC_CTR2(vlapic, "vlapic sending ipi %d "
1009                                     "to vcpuid %d", vec, i);
1010                         } else {
1011                                 vm_inject_nmi(vlapic->vm, i);
1012                                 VLAPIC_CTR1(vlapic, "vlapic sending ipi nmi "
1013                                     "to vcpuid %d", i);
1014                         }
1015                 }
1016
1017                 return (0);     /* handled completely in the kernel */
1018         }
1019
1020         maxcpus = vm_get_maxcpus(vlapic->vm);
1021         if (mode == APIC_DELMODE_INIT) {
1022                 if ((icrval & APIC_LEVEL_MASK) == APIC_LEVEL_DEASSERT)
1023                         return (0);
1024
1025                 if (vlapic->vcpuid == 0 && dest != 0 && dest < maxcpus) {
1026                         vlapic2 = vm_lapic(vlapic->vm, dest);
1027
1028                         /* move from INIT to waiting-for-SIPI state */
1029                         if (vlapic2->boot_state == BS_INIT) {
1030                                 vlapic2->boot_state = BS_SIPI;
1031                         }
1032
1033                         return (0);
1034                 }
1035         }
1036
1037         if (mode == APIC_DELMODE_STARTUP) {
1038                 if (vlapic->vcpuid == 0 && dest != 0 && dest < maxcpus) {
1039                         vlapic2 = vm_lapic(vlapic->vm, dest);
1040
1041                         /*
1042                          * Ignore SIPIs in any state other than wait-for-SIPI
1043                          */
1044                         if (vlapic2->boot_state != BS_SIPI)
1045                                 return (0);
1046
1047                         vlapic2->boot_state = BS_RUNNING;
1048
1049                         *retu = true;
1050                         vmexit = vm_exitinfo(vlapic->vm, vlapic->vcpuid);
1051                         vmexit->exitcode = VM_EXITCODE_SPINUP_AP;
1052                         vmexit->u.spinup_ap.vcpu = dest;
1053                         vmexit->u.spinup_ap.rip = vec << PAGE_SHIFT;
1054
1055                         return (0);
1056                 }
1057         }
1058
1059         /*
1060          * This will cause a return to userland.
1061          */
1062         return (1);
1063 }
1064
1065 void
1066 vlapic_self_ipi_handler(struct vlapic *vlapic, uint64_t val)
1067 {
1068         int vec;
1069
1070         KASSERT(x2apic(vlapic), ("SELF_IPI does not exist in xAPIC mode"));
1071
1072         vec = val & 0xff;
1073         lapic_intr_edge(vlapic->vm, vlapic->vcpuid, vec);
1074         vmm_stat_array_incr(vlapic->vm, vlapic->vcpuid, IPIS_SENT,
1075             vlapic->vcpuid, 1);
1076         VLAPIC_CTR1(vlapic, "vlapic self-ipi %d", vec);
1077 }
1078
1079 int
1080 vlapic_pending_intr(struct vlapic *vlapic, int *vecptr)
1081 {
1082         struct LAPIC    *lapic = vlapic->apic_page;
1083         int              idx, i, bitpos, vector;
1084         uint32_t        *irrptr, val;
1085
1086         vlapic_update_ppr(vlapic);
1087
1088         if (vlapic->ops.pending_intr)
1089                 return ((*vlapic->ops.pending_intr)(vlapic, vecptr));
1090
1091         irrptr = &lapic->irr0;
1092
1093         for (i = 7; i >= 0; i--) {
1094                 idx = i * 4;
1095                 val = atomic_load_acq_int(&irrptr[idx]);
1096                 bitpos = fls(val);
1097                 if (bitpos != 0) {
1098                         vector = i * 32 + (bitpos - 1);
1099                         if (PRIO(vector) > PRIO(lapic->ppr)) {
1100                                 VLAPIC_CTR1(vlapic, "pending intr %d", vector);
1101                                 if (vecptr != NULL)
1102                                         *vecptr = vector;
1103                                 return (1);
1104                         } else 
1105                                 break;
1106                 }
1107         }
1108         return (0);
1109 }
1110
1111 void
1112 vlapic_intr_accepted(struct vlapic *vlapic, int vector)
1113 {
1114         struct LAPIC    *lapic = vlapic->apic_page;
1115         uint32_t        *irrptr, *isrptr;
1116         int             idx, stk_top;
1117
1118         if (vlapic->ops.intr_accepted)
1119                 return ((*vlapic->ops.intr_accepted)(vlapic, vector));
1120
1121         /*
1122          * clear the ready bit for vector being accepted in irr 
1123          * and set the vector as in service in isr.
1124          */
1125         idx = (vector / 32) * 4;
1126
1127         irrptr = &lapic->irr0;
1128         atomic_clear_int(&irrptr[idx], 1 << (vector % 32));
1129         VLAPIC_CTR_IRR(vlapic, "vlapic_intr_accepted");
1130
1131         isrptr = &lapic->isr0;
1132         isrptr[idx] |= 1 << (vector % 32);
1133         VLAPIC_CTR_ISR(vlapic, "vlapic_intr_accepted");
1134
1135         /*
1136          * Update the PPR
1137          */
1138         vlapic->isrvec_stk_top++;
1139
1140         stk_top = vlapic->isrvec_stk_top;
1141         if (stk_top >= ISRVEC_STK_SIZE)
1142                 panic("isrvec_stk_top overflow %d", stk_top);
1143
1144         vlapic->isrvec_stk[stk_top] = vector;
1145 }
1146
1147 void
1148 vlapic_svr_write_handler(struct vlapic *vlapic)
1149 {
1150         struct LAPIC *lapic;
1151         uint32_t old, new, changed;
1152
1153         lapic = vlapic->apic_page;
1154
1155         new = lapic->svr;
1156         old = vlapic->svr_last;
1157         vlapic->svr_last = new;
1158
1159         changed = old ^ new;
1160         if ((changed & APIC_SVR_ENABLE) != 0) {
1161                 if ((new & APIC_SVR_ENABLE) == 0) {
1162                         /*
1163                          * The apic is now disabled so stop the apic timer
1164                          * and mask all the LVT entries.
1165                          */
1166                         VLAPIC_CTR0(vlapic, "vlapic is software-disabled");
1167                         VLAPIC_TIMER_LOCK(vlapic);
1168                         callout_stop(&vlapic->callout);
1169                         VLAPIC_TIMER_UNLOCK(vlapic);
1170                         vlapic_mask_lvts(vlapic);
1171                 } else {
1172                         /*
1173                          * The apic is now enabled so restart the apic timer
1174                          * if it is configured in periodic mode.
1175                          */
1176                         VLAPIC_CTR0(vlapic, "vlapic is software-enabled");
1177                         if (vlapic_periodic_timer(vlapic))
1178                                 vlapic_icrtmr_write_handler(vlapic);
1179                 }
1180         }
1181 }
1182
1183 int
1184 vlapic_read(struct vlapic *vlapic, int mmio_access, uint64_t offset,
1185     uint64_t *data, bool *retu)
1186 {
1187         struct LAPIC    *lapic = vlapic->apic_page;
1188         uint32_t        *reg;
1189         int              i;
1190
1191         /* Ignore MMIO accesses in x2APIC mode */
1192         if (x2apic(vlapic) && mmio_access) {
1193                 VLAPIC_CTR1(vlapic, "MMIO read from offset %#lx in x2APIC mode",
1194                     offset);
1195                 *data = 0;
1196                 goto done;
1197         }
1198
1199         if (!x2apic(vlapic) && !mmio_access) {
1200                 /*
1201                  * XXX Generate GP fault for MSR accesses in xAPIC mode
1202                  */
1203                 VLAPIC_CTR1(vlapic, "x2APIC MSR read from offset %#lx in "
1204                     "xAPIC mode", offset);
1205                 *data = 0;
1206                 goto done;
1207         }
1208
1209         if (offset > sizeof(*lapic)) {
1210                 *data = 0;
1211                 goto done;
1212         }
1213
1214         offset &= ~3;
1215         switch(offset)
1216         {
1217                 case APIC_OFFSET_ID:
1218                         *data = lapic->id;
1219                         break;
1220                 case APIC_OFFSET_VER:
1221                         *data = lapic->version;
1222                         break;
1223                 case APIC_OFFSET_TPR:
1224                         *data = vlapic_get_tpr(vlapic);
1225                         break;
1226                 case APIC_OFFSET_APR:
1227                         *data = lapic->apr;
1228                         break;
1229                 case APIC_OFFSET_PPR:
1230                         *data = lapic->ppr;
1231                         break;
1232                 case APIC_OFFSET_EOI:
1233                         *data = lapic->eoi;
1234                         break;
1235                 case APIC_OFFSET_LDR:
1236                         *data = lapic->ldr;
1237                         break;
1238                 case APIC_OFFSET_DFR:
1239                         *data = lapic->dfr;
1240                         break;
1241                 case APIC_OFFSET_SVR:
1242                         *data = lapic->svr;
1243                         break;
1244                 case APIC_OFFSET_ISR0 ... APIC_OFFSET_ISR7:
1245                         i = (offset - APIC_OFFSET_ISR0) >> 2;
1246                         reg = &lapic->isr0;
1247                         *data = *(reg + i);
1248                         break;
1249                 case APIC_OFFSET_TMR0 ... APIC_OFFSET_TMR7:
1250                         i = (offset - APIC_OFFSET_TMR0) >> 2;
1251                         reg = &lapic->tmr0;
1252                         *data = *(reg + i);
1253                         break;
1254                 case APIC_OFFSET_IRR0 ... APIC_OFFSET_IRR7:
1255                         i = (offset - APIC_OFFSET_IRR0) >> 2;
1256                         reg = &lapic->irr0;
1257                         *data = atomic_load_acq_int(reg + i);
1258                         break;
1259                 case APIC_OFFSET_ESR:
1260                         *data = lapic->esr;
1261                         break;
1262                 case APIC_OFFSET_ICR_LOW: 
1263                         *data = lapic->icr_lo;
1264                         if (x2apic(vlapic))
1265                                 *data |= (uint64_t)lapic->icr_hi << 32;
1266                         break;
1267                 case APIC_OFFSET_ICR_HI: 
1268                         *data = lapic->icr_hi;
1269                         break;
1270                 case APIC_OFFSET_CMCI_LVT:
1271                 case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
1272                         *data = vlapic_get_lvt(vlapic, offset); 
1273 #ifdef INVARIANTS
1274                         reg = vlapic_get_lvtptr(vlapic, offset);
1275                         KASSERT(*data == *reg, ("inconsistent lvt value at "
1276                             "offset %#lx: %#lx/%#x", offset, *data, *reg));
1277 #endif
1278                         break;
1279                 case APIC_OFFSET_TIMER_ICR:
1280                         *data = lapic->icr_timer;
1281                         break;
1282                 case APIC_OFFSET_TIMER_CCR:
1283                         *data = vlapic_get_ccr(vlapic);
1284                         break;
1285                 case APIC_OFFSET_TIMER_DCR:
1286                         *data = lapic->dcr_timer;
1287                         break;
1288                 case APIC_OFFSET_SELF_IPI:
1289                         /*
1290                          * XXX generate a GP fault if vlapic is in x2apic mode
1291                          */
1292                         *data = 0;
1293                         break;
1294                 case APIC_OFFSET_RRR:
1295                 default:
1296                         *data = 0;
1297                         break;
1298         }
1299 done:
1300         VLAPIC_CTR2(vlapic, "vlapic read offset %#x, data %#lx", offset, *data);
1301         return 0;
1302 }
1303
1304 int
1305 vlapic_write(struct vlapic *vlapic, int mmio_access, uint64_t offset,
1306     uint64_t data, bool *retu)
1307 {
1308         struct LAPIC    *lapic = vlapic->apic_page;
1309         uint32_t        *regptr;
1310         int             retval;
1311
1312         KASSERT((offset & 0xf) == 0 && offset < PAGE_SIZE,
1313             ("vlapic_write: invalid offset %#lx", offset));
1314
1315         VLAPIC_CTR2(vlapic, "vlapic write offset %#lx, data %#lx",
1316             offset, data);
1317
1318         if (offset > sizeof(*lapic))
1319                 return (0);
1320
1321         /* Ignore MMIO accesses in x2APIC mode */
1322         if (x2apic(vlapic) && mmio_access) {
1323                 VLAPIC_CTR2(vlapic, "MMIO write of %#lx to offset %#lx "
1324                     "in x2APIC mode", data, offset);
1325                 return (0);
1326         }
1327
1328         /*
1329          * XXX Generate GP fault for MSR accesses in xAPIC mode
1330          */
1331         if (!x2apic(vlapic) && !mmio_access) {
1332                 VLAPIC_CTR2(vlapic, "x2APIC MSR write of %#lx to offset %#lx "
1333                     "in xAPIC mode", data, offset);
1334                 return (0);
1335         }
1336
1337         retval = 0;
1338         switch(offset)
1339         {
1340                 case APIC_OFFSET_ID:
1341                         lapic->id = data;
1342                         vlapic_id_write_handler(vlapic);
1343                         break;
1344                 case APIC_OFFSET_TPR:
1345                         vlapic_set_tpr(vlapic, data & 0xff);
1346                         break;
1347                 case APIC_OFFSET_EOI:
1348                         vlapic_process_eoi(vlapic);
1349                         break;
1350                 case APIC_OFFSET_LDR:
1351                         lapic->ldr = data;
1352                         vlapic_ldr_write_handler(vlapic);
1353                         break;
1354                 case APIC_OFFSET_DFR:
1355                         lapic->dfr = data;
1356                         vlapic_dfr_write_handler(vlapic);
1357                         break;
1358                 case APIC_OFFSET_SVR:
1359                         lapic->svr = data;
1360                         vlapic_svr_write_handler(vlapic);
1361                         break;
1362                 case APIC_OFFSET_ICR_LOW: 
1363                         lapic->icr_lo = data;
1364                         if (x2apic(vlapic))
1365                                 lapic->icr_hi = data >> 32;
1366                         retval = vlapic_icrlo_write_handler(vlapic, retu);
1367                         break;
1368                 case APIC_OFFSET_ICR_HI:
1369                         lapic->icr_hi = data;
1370                         break;
1371                 case APIC_OFFSET_CMCI_LVT:
1372                 case APIC_OFFSET_TIMER_LVT ... APIC_OFFSET_ERROR_LVT:
1373                         regptr = vlapic_get_lvtptr(vlapic, offset);
1374                         *regptr = data;
1375                         vlapic_lvt_write_handler(vlapic, offset);
1376                         break;
1377                 case APIC_OFFSET_TIMER_ICR:
1378                         lapic->icr_timer = data;
1379                         vlapic_icrtmr_write_handler(vlapic);
1380                         break;
1381
1382                 case APIC_OFFSET_TIMER_DCR:
1383                         lapic->dcr_timer = data;
1384                         vlapic_dcr_write_handler(vlapic);
1385                         break;
1386
1387                 case APIC_OFFSET_ESR:
1388                         vlapic_esr_write_handler(vlapic);
1389                         break;
1390
1391                 case APIC_OFFSET_SELF_IPI:
1392                         if (x2apic(vlapic))
1393                                 vlapic_self_ipi_handler(vlapic, data);
1394                         break;
1395
1396                 case APIC_OFFSET_VER:
1397                 case APIC_OFFSET_APR:
1398                 case APIC_OFFSET_PPR:
1399                 case APIC_OFFSET_RRR:
1400                 case APIC_OFFSET_ISR0 ... APIC_OFFSET_ISR7:
1401                 case APIC_OFFSET_TMR0 ... APIC_OFFSET_TMR7:
1402                 case APIC_OFFSET_IRR0 ... APIC_OFFSET_IRR7:
1403                 case APIC_OFFSET_TIMER_CCR:
1404                 default:
1405                         // Read only.
1406                         break;
1407         }
1408
1409         return (retval);
1410 }
1411
1412 static void
1413 vlapic_reset(struct vlapic *vlapic)
1414 {
1415         struct LAPIC *lapic;
1416
1417         lapic = vlapic->apic_page;
1418         bzero(lapic, sizeof(struct LAPIC));
1419
1420         lapic->id = vlapic_get_id(vlapic);
1421         lapic->version = VLAPIC_VERSION;
1422         lapic->version |= (VLAPIC_MAXLVT_INDEX << MAXLVTSHIFT);
1423         lapic->dfr = 0xffffffff;
1424         lapic->svr = APIC_SVR_VECTOR;
1425         vlapic_mask_lvts(vlapic);
1426         vlapic_reset_tmr(vlapic);
1427
1428         lapic->dcr_timer = 0;
1429         vlapic_dcr_write_handler(vlapic);
1430
1431         if (vlapic->vcpuid == 0)
1432                 vlapic->boot_state = BS_RUNNING;        /* BSP */
1433         else
1434                 vlapic->boot_state = BS_INIT;           /* AP */
1435
1436         vlapic->svr_last = lapic->svr;
1437 }
1438
1439 void
1440 vlapic_init(struct vlapic *vlapic)
1441 {
1442         KASSERT(vlapic->vm != NULL, ("vlapic_init: vm is not initialized"));
1443         KASSERT(vlapic->vcpuid >= 0 &&
1444             vlapic->vcpuid < vm_get_maxcpus(vlapic->vm),
1445             ("vlapic_init: vcpuid is not initialized"));
1446         KASSERT(vlapic->apic_page != NULL, ("vlapic_init: apic_page is not "
1447             "initialized"));
1448
1449         /*
1450          * If the vlapic is configured in x2apic mode then it will be
1451          * accessed in the critical section via the MSR emulation code.
1452          *
1453          * Therefore the timer mutex must be a spinlock because blockable
1454          * mutexes cannot be acquired in a critical section.
1455          */
1456         mtx_init(&vlapic->timer_mtx, "vlapic timer mtx", NULL, MTX_SPIN);
1457         callout_init(&vlapic->callout, 1);
1458
1459         vlapic->msr_apicbase = DEFAULT_APIC_BASE | APICBASE_ENABLED;
1460
1461         if (vlapic->vcpuid == 0)
1462                 vlapic->msr_apicbase |= APICBASE_BSP;
1463
1464         vlapic_reset(vlapic);
1465 }
1466
1467 void
1468 vlapic_cleanup(struct vlapic *vlapic)
1469 {
1470
1471         callout_drain(&vlapic->callout);
1472 }
1473
1474 uint64_t
1475 vlapic_get_apicbase(struct vlapic *vlapic)
1476 {
1477
1478         return (vlapic->msr_apicbase);
1479 }
1480
1481 int
1482 vlapic_set_apicbase(struct vlapic *vlapic, uint64_t new)
1483 {
1484
1485         if (vlapic->msr_apicbase != new) {
1486                 VLAPIC_CTR2(vlapic, "Changing APIC_BASE MSR from %#lx to %#lx "
1487                     "not supported", vlapic->msr_apicbase, new);
1488                 return (-1);
1489         }
1490
1491         return (0);
1492 }
1493
1494 void
1495 vlapic_set_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state state)
1496 {
1497         struct vlapic *vlapic;
1498         struct LAPIC *lapic;
1499
1500         vlapic = vm_lapic(vm, vcpuid);
1501
1502         if (state == X2APIC_DISABLED)
1503                 vlapic->msr_apicbase &= ~APICBASE_X2APIC;
1504         else
1505                 vlapic->msr_apicbase |= APICBASE_X2APIC;
1506
1507         /*
1508          * Reset the local APIC registers whose values are mode-dependent.
1509          *
1510          * XXX this works because the APIC mode can be changed only at vcpu
1511          * initialization time.
1512          */
1513         lapic = vlapic->apic_page;
1514         lapic->id = vlapic_get_id(vlapic);
1515         if (x2apic(vlapic)) {
1516                 lapic->ldr = x2apic_ldr(vlapic);
1517                 lapic->dfr = 0;
1518         } else {
1519                 lapic->ldr = 0;
1520                 lapic->dfr = 0xffffffff;
1521         }
1522
1523         if (state == X2APIC_ENABLED) {
1524                 if (vlapic->ops.enable_x2apic_mode)
1525                         (*vlapic->ops.enable_x2apic_mode)(vlapic);
1526         }
1527 }
1528
1529 void
1530 vlapic_deliver_intr(struct vm *vm, bool level, uint32_t dest, bool phys,
1531     int delmode, int vec)
1532 {
1533         bool lowprio;
1534         int vcpuid;
1535         cpuset_t dmask;
1536
1537         if (delmode != IOART_DELFIXED &&
1538             delmode != IOART_DELLOPRI &&
1539             delmode != IOART_DELEXINT) {
1540                 VM_CTR1(vm, "vlapic intr invalid delmode %#x", delmode);
1541                 return;
1542         }
1543         lowprio = (delmode == IOART_DELLOPRI);
1544
1545         /*
1546          * We don't provide any virtual interrupt redirection hardware so
1547          * all interrupts originating from the ioapic or MSI specify the
1548          * 'dest' in the legacy xAPIC format.
1549          */
1550         vlapic_calcdest(vm, &dmask, dest, phys, lowprio, false);
1551
1552         CPU_FOREACH_ISSET(vcpuid, &dmask) {
1553                 if (delmode == IOART_DELEXINT) {
1554                         vm_inject_extint(vm, vcpuid);
1555                 } else {
1556                         lapic_set_intr(vm, vcpuid, vec, level);
1557                 }
1558         }
1559 }
1560
1561 void
1562 vlapic_post_intr(struct vlapic *vlapic, int hostcpu, int ipinum)
1563 {
1564         /*
1565          * Post an interrupt to the vcpu currently running on 'hostcpu'.
1566          *
1567          * This is done by leveraging features like Posted Interrupts (Intel)
1568          * Doorbell MSR (AMD AVIC) that avoid a VM exit.
1569          *
1570          * If neither of these features are available then fallback to
1571          * sending an IPI to 'hostcpu'.
1572          */
1573         if (vlapic->ops.post_intr)
1574                 (*vlapic->ops.post_intr)(vlapic, hostcpu);
1575         else
1576                 ipi_cpu(hostcpu, ipinum);
1577 }
1578
1579 bool
1580 vlapic_enabled(struct vlapic *vlapic)
1581 {
1582         struct LAPIC *lapic = vlapic->apic_page;
1583
1584         if ((vlapic->msr_apicbase & APICBASE_ENABLED) != 0 &&
1585             (lapic->svr & APIC_SVR_ENABLE) != 0)
1586                 return (true);
1587         else
1588                 return (false);
1589 }
1590
1591 static void
1592 vlapic_set_tmr(struct vlapic *vlapic, int vector, bool level)
1593 {
1594         struct LAPIC *lapic;
1595         uint32_t *tmrptr, mask;
1596         int idx;
1597
1598         lapic = vlapic->apic_page;
1599         tmrptr = &lapic->tmr0;
1600         idx = (vector / 32) * 4;
1601         mask = 1 << (vector % 32);
1602         if (level)
1603                 tmrptr[idx] |= mask;
1604         else
1605                 tmrptr[idx] &= ~mask;
1606
1607         if (vlapic->ops.set_tmr != NULL)
1608                 (*vlapic->ops.set_tmr)(vlapic, vector, level);
1609 }
1610
1611 void
1612 vlapic_reset_tmr(struct vlapic *vlapic)
1613 {
1614         int vector;
1615
1616         VLAPIC_CTR0(vlapic, "vlapic resetting all vectors to edge-triggered");
1617
1618         for (vector = 0; vector <= 255; vector++)
1619                 vlapic_set_tmr(vlapic, vector, false);
1620 }
1621
1622 void
1623 vlapic_set_tmr_level(struct vlapic *vlapic, uint32_t dest, bool phys,
1624     int delmode, int vector)
1625 {
1626         cpuset_t dmask;
1627         bool lowprio;
1628
1629         KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d", vector));
1630
1631         /*
1632          * A level trigger is valid only for fixed and lowprio delivery modes.
1633          */
1634         if (delmode != APIC_DELMODE_FIXED && delmode != APIC_DELMODE_LOWPRIO) {
1635                 VLAPIC_CTR1(vlapic, "Ignoring level trigger-mode for "
1636                     "delivery-mode %d", delmode);
1637                 return;
1638         }
1639
1640         lowprio = (delmode == APIC_DELMODE_LOWPRIO);
1641         vlapic_calcdest(vlapic->vm, &dmask, dest, phys, lowprio, false);
1642
1643         if (!CPU_ISSET(vlapic->vcpuid, &dmask))
1644                 return;
1645
1646         VLAPIC_CTR1(vlapic, "vector %d set to level-triggered", vector);
1647         vlapic_set_tmr(vlapic, vector, true);
1648 }
1649
1650 #ifdef BHYVE_SNAPSHOT
1651 static void
1652 vlapic_reset_callout(struct vlapic *vlapic, uint32_t ccr)
1653 {
1654         /* The implementation is similar to the one in the
1655          * `vlapic_icrtmr_write_handler` function
1656          */
1657         sbintime_t sbt;
1658         struct bintime bt;
1659
1660         VLAPIC_TIMER_LOCK(vlapic);
1661
1662         bt = vlapic->timer_freq_bt;
1663         bintime_mul(&bt, ccr);
1664
1665         if (ccr != 0) {
1666                 binuptime(&vlapic->timer_fire_bt);
1667                 bintime_add(&vlapic->timer_fire_bt, &bt);
1668
1669                 sbt = bttosbt(bt);
1670                 callout_reset_sbt(&vlapic->callout, sbt, 0,
1671                     vlapic_callout_handler, vlapic, 0);
1672         } else {
1673                 /* even if the CCR was 0, periodic timers should be reset */
1674                 if (vlapic_periodic_timer(vlapic)) {
1675                         binuptime(&vlapic->timer_fire_bt);
1676                         bintime_add(&vlapic->timer_fire_bt,
1677                                     &vlapic->timer_period_bt);
1678                         sbt = bttosbt(vlapic->timer_period_bt);
1679
1680                         callout_stop(&vlapic->callout);
1681                         callout_reset_sbt(&vlapic->callout, sbt, 0,
1682                                           vlapic_callout_handler, vlapic, 0);
1683                 }
1684         }
1685
1686         VLAPIC_TIMER_UNLOCK(vlapic);
1687 }
1688
1689 int
1690 vlapic_snapshot(struct vm *vm, struct vm_snapshot_meta *meta)
1691 {
1692         int i, ret;
1693         struct vlapic *vlapic;
1694         struct LAPIC *lapic;
1695         uint32_t ccr;
1696
1697         KASSERT(vm != NULL, ("%s: arg was NULL", __func__));
1698
1699         ret = 0;
1700
1701         for (i = 0; i < VM_MAXCPU; i++) {
1702                 vlapic = vm_lapic(vm, i);
1703
1704                 /* snapshot the page first; timer period depends on icr_timer */
1705                 lapic = vlapic->apic_page;
1706                 SNAPSHOT_BUF_OR_LEAVE(lapic, PAGE_SIZE, meta, ret, done);
1707
1708                 SNAPSHOT_VAR_OR_LEAVE(vlapic->esr_pending, meta, ret, done);
1709
1710                 SNAPSHOT_VAR_OR_LEAVE(vlapic->timer_freq_bt.sec,
1711                                       meta, ret, done);
1712                 SNAPSHOT_VAR_OR_LEAVE(vlapic->timer_freq_bt.frac,
1713                                       meta, ret, done);
1714
1715                 /*
1716                  * Timer period is equal to 'icr_timer' ticks at a frequency of
1717                  * 'timer_freq_bt'.
1718                  */
1719                 if (meta->op == VM_SNAPSHOT_RESTORE) {
1720                         vlapic->timer_period_bt = vlapic->timer_freq_bt;
1721                         bintime_mul(&vlapic->timer_period_bt, lapic->icr_timer);
1722                 }
1723
1724                 SNAPSHOT_BUF_OR_LEAVE(vlapic->isrvec_stk,
1725                                       sizeof(vlapic->isrvec_stk),
1726                                       meta, ret, done);
1727                 SNAPSHOT_VAR_OR_LEAVE(vlapic->isrvec_stk_top, meta, ret, done);
1728                 SNAPSHOT_VAR_OR_LEAVE(vlapic->boot_state, meta, ret, done);
1729
1730                 SNAPSHOT_BUF_OR_LEAVE(vlapic->lvt_last,
1731                                       sizeof(vlapic->lvt_last),
1732                                       meta, ret, done);
1733
1734                 if (meta->op == VM_SNAPSHOT_SAVE)
1735                         ccr = vlapic_get_ccr(vlapic);
1736
1737                 SNAPSHOT_VAR_OR_LEAVE(ccr, meta, ret, done);
1738
1739                 if (meta->op == VM_SNAPSHOT_RESTORE) {
1740                         /* Reset the value of the 'timer_fire_bt' and the vlapic
1741                          * callout based on the value of the current count
1742                          * register saved when the VM snapshot was created
1743                          */
1744                         vlapic_reset_callout(vlapic, ccr);
1745                 }
1746         }
1747
1748 done:
1749         return (ret);
1750 }
1751 #endif