KVM: SVM: Trap access to the cr8 register
[safe/jmp/linux-2.6] / drivers / kvm / lapic.c
1
2 /*
3  * Local APIC virtualization
4  *
5  * Copyright (C) 2006 Qumranet, Inc.
6  * Copyright (C) 2007 Novell
7  * Copyright (C) 2007 Intel
8  *
9  * Authors:
10  *   Dor Laor <dor.laor@qumranet.com>
11  *   Gregory Haskins <ghaskins@novell.com>
12  *   Yaozu (Eddie) Dong <eddie.dong@intel.com>
13  *
14  * Based on Xen 3.1 code, Copyright (c) 2004, Intel Corporation.
15  *
16  * This work is licensed under the terms of the GNU GPL, version 2.  See
17  * the COPYING file in the top-level directory.
18  */
19
20 #include "kvm.h"
21 #include "x86.h"
22
23 #include <linux/kvm.h>
24 #include <linux/mm.h>
25 #include <linux/highmem.h>
26 #include <linux/smp.h>
27 #include <linux/hrtimer.h>
28 #include <linux/io.h>
29 #include <linux/module.h>
30 #include <asm/processor.h>
31 #include <asm/msr.h>
32 #include <asm/page.h>
33 #include <asm/current.h>
34 #include <asm/apicdef.h>
35 #include <asm/atomic.h>
36 #include <asm/div64.h>
37 #include "irq.h"
38
39 #define PRId64 "d"
40 #define PRIx64 "llx"
41 #define PRIu64 "u"
42 #define PRIo64 "o"
43
44 #define APIC_BUS_CYCLE_NS 1
45
46 /* #define apic_debug(fmt,arg...) printk(KERN_WARNING fmt,##arg) */
47 #define apic_debug(fmt, arg...)
48
49 #define APIC_LVT_NUM                    6
50 /* 14 is the version for Xeon and Pentium 8.4.8*/
51 #define APIC_VERSION                    (0x14UL | ((APIC_LVT_NUM - 1) << 16))
52 #define LAPIC_MMIO_LENGTH               (1 << 12)
53 /* followed define is not in apicdef.h */
54 #define APIC_SHORT_MASK                 0xc0000
55 #define APIC_DEST_NOSHORT               0x0
56 #define APIC_DEST_MASK                  0x800
57 #define MAX_APIC_VECTOR                 256
58
59 #define VEC_POS(v) ((v) & (32 - 1))
60 #define REG_POS(v) (((v) >> 5) << 4)
61 static inline u32 apic_get_reg(struct kvm_lapic *apic, int reg_off)
62 {
63         return *((u32 *) (apic->regs + reg_off));
64 }
65
66 static inline void apic_set_reg(struct kvm_lapic *apic, int reg_off, u32 val)
67 {
68         *((u32 *) (apic->regs + reg_off)) = val;
69 }
70
71 static inline int apic_test_and_set_vector(int vec, void *bitmap)
72 {
73         return test_and_set_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
74 }
75
76 static inline int apic_test_and_clear_vector(int vec, void *bitmap)
77 {
78         return test_and_clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
79 }
80
81 static inline void apic_set_vector(int vec, void *bitmap)
82 {
83         set_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
84 }
85
86 static inline void apic_clear_vector(int vec, void *bitmap)
87 {
88         clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
89 }
90
91 static inline int apic_hw_enabled(struct kvm_lapic *apic)
92 {
93         return (apic)->vcpu->apic_base & MSR_IA32_APICBASE_ENABLE;
94 }
95
96 static inline int  apic_sw_enabled(struct kvm_lapic *apic)
97 {
98         return apic_get_reg(apic, APIC_SPIV) & APIC_SPIV_APIC_ENABLED;
99 }
100
101 static inline int apic_enabled(struct kvm_lapic *apic)
102 {
103         return apic_sw_enabled(apic) && apic_hw_enabled(apic);
104 }
105
106 #define LVT_MASK        \
107         (APIC_LVT_MASKED | APIC_SEND_PENDING | APIC_VECTOR_MASK)
108
109 #define LINT_MASK       \
110         (LVT_MASK | APIC_MODE_MASK | APIC_INPUT_POLARITY | \
111          APIC_LVT_REMOTE_IRR | APIC_LVT_LEVEL_TRIGGER)
112
113 static inline int kvm_apic_id(struct kvm_lapic *apic)
114 {
115         return (apic_get_reg(apic, APIC_ID) >> 24) & 0xff;
116 }
117
118 static inline int apic_lvt_enabled(struct kvm_lapic *apic, int lvt_type)
119 {
120         return !(apic_get_reg(apic, lvt_type) & APIC_LVT_MASKED);
121 }
122
123 static inline int apic_lvt_vector(struct kvm_lapic *apic, int lvt_type)
124 {
125         return apic_get_reg(apic, lvt_type) & APIC_VECTOR_MASK;
126 }
127
128 static inline int apic_lvtt_period(struct kvm_lapic *apic)
129 {
130         return apic_get_reg(apic, APIC_LVTT) & APIC_LVT_TIMER_PERIODIC;
131 }
132
133 static unsigned int apic_lvt_mask[APIC_LVT_NUM] = {
134         LVT_MASK | APIC_LVT_TIMER_PERIODIC,     /* LVTT */
135         LVT_MASK | APIC_MODE_MASK,      /* LVTTHMR */
136         LVT_MASK | APIC_MODE_MASK,      /* LVTPC */
137         LINT_MASK, LINT_MASK,   /* LVT0-1 */
138         LVT_MASK                /* LVTERR */
139 };
140
141 static int find_highest_vector(void *bitmap)
142 {
143         u32 *word = bitmap;
144         int word_offset = MAX_APIC_VECTOR >> 5;
145
146         while ((word_offset != 0) && (word[(--word_offset) << 2] == 0))
147                 continue;
148
149         if (likely(!word_offset && !word[0]))
150                 return -1;
151         else
152                 return fls(word[word_offset << 2]) - 1 + (word_offset << 5);
153 }
154
155 static inline int apic_test_and_set_irr(int vec, struct kvm_lapic *apic)
156 {
157         return apic_test_and_set_vector(vec, apic->regs + APIC_IRR);
158 }
159
160 static inline void apic_clear_irr(int vec, struct kvm_lapic *apic)
161 {
162         apic_clear_vector(vec, apic->regs + APIC_IRR);
163 }
164
165 static inline int apic_find_highest_irr(struct kvm_lapic *apic)
166 {
167         int result;
168
169         result = find_highest_vector(apic->regs + APIC_IRR);
170         ASSERT(result == -1 || result >= 16);
171
172         return result;
173 }
174
175 int kvm_lapic_find_highest_irr(struct kvm_vcpu *vcpu)
176 {
177         struct kvm_lapic *apic = vcpu->apic;
178         int highest_irr;
179
180         if (!apic)
181                 return 0;
182         highest_irr = apic_find_highest_irr(apic);
183
184         return highest_irr;
185 }
186 EXPORT_SYMBOL_GPL(kvm_lapic_find_highest_irr);
187
188 int kvm_apic_set_irq(struct kvm_vcpu *vcpu, u8 vec, u8 trig)
189 {
190         struct kvm_lapic *apic = vcpu->apic;
191
192         if (!apic_test_and_set_irr(vec, apic)) {
193                 /* a new pending irq is set in IRR */
194                 if (trig)
195                         apic_set_vector(vec, apic->regs + APIC_TMR);
196                 else
197                         apic_clear_vector(vec, apic->regs + APIC_TMR);
198                 kvm_vcpu_kick(apic->vcpu);
199                 return 1;
200         }
201         return 0;
202 }
203
204 static inline int apic_find_highest_isr(struct kvm_lapic *apic)
205 {
206         int result;
207
208         result = find_highest_vector(apic->regs + APIC_ISR);
209         ASSERT(result == -1 || result >= 16);
210
211         return result;
212 }
213
214 static void apic_update_ppr(struct kvm_lapic *apic)
215 {
216         u32 tpr, isrv, ppr;
217         int isr;
218
219         tpr = apic_get_reg(apic, APIC_TASKPRI);
220         isr = apic_find_highest_isr(apic);
221         isrv = (isr != -1) ? isr : 0;
222
223         if ((tpr & 0xf0) >= (isrv & 0xf0))
224                 ppr = tpr & 0xff;
225         else
226                 ppr = isrv & 0xf0;
227
228         apic_debug("vlapic %p, ppr 0x%x, isr 0x%x, isrv 0x%x",
229                    apic, ppr, isr, isrv);
230
231         apic_set_reg(apic, APIC_PROCPRI, ppr);
232 }
233
234 static void apic_set_tpr(struct kvm_lapic *apic, u32 tpr)
235 {
236         apic_set_reg(apic, APIC_TASKPRI, tpr);
237         apic_update_ppr(apic);
238 }
239
240 int kvm_apic_match_physical_addr(struct kvm_lapic *apic, u16 dest)
241 {
242         return kvm_apic_id(apic) == dest;
243 }
244
245 int kvm_apic_match_logical_addr(struct kvm_lapic *apic, u8 mda)
246 {
247         int result = 0;
248         u8 logical_id;
249
250         logical_id = GET_APIC_LOGICAL_ID(apic_get_reg(apic, APIC_LDR));
251
252         switch (apic_get_reg(apic, APIC_DFR)) {
253         case APIC_DFR_FLAT:
254                 if (logical_id & mda)
255                         result = 1;
256                 break;
257         case APIC_DFR_CLUSTER:
258                 if (((logical_id >> 4) == (mda >> 0x4))
259                     && (logical_id & mda & 0xf))
260                         result = 1;
261                 break;
262         default:
263                 printk(KERN_WARNING "Bad DFR vcpu %d: %08x\n",
264                        apic->vcpu->vcpu_id, apic_get_reg(apic, APIC_DFR));
265                 break;
266         }
267
268         return result;
269 }
270
271 static int apic_match_dest(struct kvm_vcpu *vcpu, struct kvm_lapic *source,
272                            int short_hand, int dest, int dest_mode)
273 {
274         int result = 0;
275         struct kvm_lapic *target = vcpu->apic;
276
277         apic_debug("target %p, source %p, dest 0x%x, "
278                    "dest_mode 0x%x, short_hand 0x%x",
279                    target, source, dest, dest_mode, short_hand);
280
281         ASSERT(!target);
282         switch (short_hand) {
283         case APIC_DEST_NOSHORT:
284                 if (dest_mode == 0) {
285                         /* Physical mode. */
286                         if ((dest == 0xFF) || (dest == kvm_apic_id(target)))
287                                 result = 1;
288                 } else
289                         /* Logical mode. */
290                         result = kvm_apic_match_logical_addr(target, dest);
291                 break;
292         case APIC_DEST_SELF:
293                 if (target == source)
294                         result = 1;
295                 break;
296         case APIC_DEST_ALLINC:
297                 result = 1;
298                 break;
299         case APIC_DEST_ALLBUT:
300                 if (target != source)
301                         result = 1;
302                 break;
303         default:
304                 printk(KERN_WARNING "Bad dest shorthand value %x\n",
305                        short_hand);
306                 break;
307         }
308
309         return result;
310 }
311
312 /*
313  * Add a pending IRQ into lapic.
314  * Return 1 if successfully added and 0 if discarded.
315  */
316 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
317                              int vector, int level, int trig_mode)
318 {
319         int orig_irr, result = 0;
320         struct kvm_vcpu *vcpu = apic->vcpu;
321
322         switch (delivery_mode) {
323         case APIC_DM_FIXED:
324         case APIC_DM_LOWEST:
325                 /* FIXME add logic for vcpu on reset */
326                 if (unlikely(!apic_enabled(apic)))
327                         break;
328
329                 orig_irr = apic_test_and_set_irr(vector, apic);
330                 if (orig_irr && trig_mode) {
331                         apic_debug("level trig mode repeatedly for vector %d",
332                                    vector);
333                         break;
334                 }
335
336                 if (trig_mode) {
337                         apic_debug("level trig mode for vector %d", vector);
338                         apic_set_vector(vector, apic->regs + APIC_TMR);
339                 } else
340                         apic_clear_vector(vector, apic->regs + APIC_TMR);
341
342                 if (vcpu->mp_state == VCPU_MP_STATE_RUNNABLE)
343                         kvm_vcpu_kick(vcpu);
344                 else if (vcpu->mp_state == VCPU_MP_STATE_HALTED) {
345                         vcpu->mp_state = VCPU_MP_STATE_RUNNABLE;
346                         if (waitqueue_active(&vcpu->wq))
347                                 wake_up_interruptible(&vcpu->wq);
348                 }
349
350                 result = (orig_irr == 0);
351                 break;
352
353         case APIC_DM_REMRD:
354                 printk(KERN_DEBUG "Ignoring delivery mode 3\n");
355                 break;
356
357         case APIC_DM_SMI:
358                 printk(KERN_DEBUG "Ignoring guest SMI\n");
359                 break;
360         case APIC_DM_NMI:
361                 printk(KERN_DEBUG "Ignoring guest NMI\n");
362                 break;
363
364         case APIC_DM_INIT:
365                 if (level) {
366                         if (vcpu->mp_state == VCPU_MP_STATE_RUNNABLE)
367                                 printk(KERN_DEBUG
368                                        "INIT on a runnable vcpu %d\n",
369                                        vcpu->vcpu_id);
370                         vcpu->mp_state = VCPU_MP_STATE_INIT_RECEIVED;
371                         kvm_vcpu_kick(vcpu);
372                 } else {
373                         printk(KERN_DEBUG
374                                "Ignoring de-assert INIT to vcpu %d\n",
375                                vcpu->vcpu_id);
376                 }
377
378                 break;
379
380         case APIC_DM_STARTUP:
381                 printk(KERN_DEBUG "SIPI to vcpu %d vector 0x%02x\n",
382                        vcpu->vcpu_id, vector);
383                 if (vcpu->mp_state == VCPU_MP_STATE_INIT_RECEIVED) {
384                         vcpu->sipi_vector = vector;
385                         vcpu->mp_state = VCPU_MP_STATE_SIPI_RECEIVED;
386                         if (waitqueue_active(&vcpu->wq))
387                                 wake_up_interruptible(&vcpu->wq);
388                 }
389                 break;
390
391         default:
392                 printk(KERN_ERR "TODO: unsupported delivery mode %x\n",
393                        delivery_mode);
394                 break;
395         }
396         return result;
397 }
398
399 static struct kvm_lapic *kvm_apic_round_robin(struct kvm *kvm, u8 vector,
400                                        unsigned long bitmap)
401 {
402         int last;
403         int next;
404         struct kvm_lapic *apic = NULL;
405
406         last = kvm->round_robin_prev_vcpu;
407         next = last;
408
409         do {
410                 if (++next == KVM_MAX_VCPUS)
411                         next = 0;
412                 if (kvm->vcpus[next] == NULL || !test_bit(next, &bitmap))
413                         continue;
414                 apic = kvm->vcpus[next]->apic;
415                 if (apic && apic_enabled(apic))
416                         break;
417                 apic = NULL;
418         } while (next != last);
419         kvm->round_robin_prev_vcpu = next;
420
421         if (!apic)
422                 printk(KERN_DEBUG "vcpu not ready for apic_round_robin\n");
423
424         return apic;
425 }
426
427 struct kvm_vcpu *kvm_get_lowest_prio_vcpu(struct kvm *kvm, u8 vector,
428                 unsigned long bitmap)
429 {
430         struct kvm_lapic *apic;
431
432         apic = kvm_apic_round_robin(kvm, vector, bitmap);
433         if (apic)
434                 return apic->vcpu;
435         return NULL;
436 }
437
438 static void apic_set_eoi(struct kvm_lapic *apic)
439 {
440         int vector = apic_find_highest_isr(apic);
441
442         /*
443          * Not every write EOI will has corresponding ISR,
444          * one example is when Kernel check timer on setup_IO_APIC
445          */
446         if (vector == -1)
447                 return;
448
449         apic_clear_vector(vector, apic->regs + APIC_ISR);
450         apic_update_ppr(apic);
451
452         if (apic_test_and_clear_vector(vector, apic->regs + APIC_TMR))
453                 kvm_ioapic_update_eoi(apic->vcpu->kvm, vector);
454 }
455
456 static void apic_send_ipi(struct kvm_lapic *apic)
457 {
458         u32 icr_low = apic_get_reg(apic, APIC_ICR);
459         u32 icr_high = apic_get_reg(apic, APIC_ICR2);
460
461         unsigned int dest = GET_APIC_DEST_FIELD(icr_high);
462         unsigned int short_hand = icr_low & APIC_SHORT_MASK;
463         unsigned int trig_mode = icr_low & APIC_INT_LEVELTRIG;
464         unsigned int level = icr_low & APIC_INT_ASSERT;
465         unsigned int dest_mode = icr_low & APIC_DEST_MASK;
466         unsigned int delivery_mode = icr_low & APIC_MODE_MASK;
467         unsigned int vector = icr_low & APIC_VECTOR_MASK;
468
469         struct kvm_vcpu *target;
470         struct kvm_vcpu *vcpu;
471         unsigned long lpr_map = 0;
472         int i;
473
474         apic_debug("icr_high 0x%x, icr_low 0x%x, "
475                    "short_hand 0x%x, dest 0x%x, trig_mode 0x%x, level 0x%x, "
476                    "dest_mode 0x%x, delivery_mode 0x%x, vector 0x%x\n",
477                    icr_high, icr_low, short_hand, dest,
478                    trig_mode, level, dest_mode, delivery_mode, vector);
479
480         for (i = 0; i < KVM_MAX_VCPUS; i++) {
481                 vcpu = apic->vcpu->kvm->vcpus[i];
482                 if (!vcpu)
483                         continue;
484
485                 if (vcpu->apic &&
486                     apic_match_dest(vcpu, apic, short_hand, dest, dest_mode)) {
487                         if (delivery_mode == APIC_DM_LOWEST)
488                                 set_bit(vcpu->vcpu_id, &lpr_map);
489                         else
490                                 __apic_accept_irq(vcpu->apic, delivery_mode,
491                                                   vector, level, trig_mode);
492                 }
493         }
494
495         if (delivery_mode == APIC_DM_LOWEST) {
496                 target = kvm_get_lowest_prio_vcpu(vcpu->kvm, vector, lpr_map);
497                 if (target != NULL)
498                         __apic_accept_irq(target->apic, delivery_mode,
499                                           vector, level, trig_mode);
500         }
501 }
502
503 static u32 apic_get_tmcct(struct kvm_lapic *apic)
504 {
505         u64 counter_passed;
506         ktime_t passed, now;
507         u32 tmcct;
508
509         ASSERT(apic != NULL);
510
511         now = apic->timer.dev.base->get_time();
512         tmcct = apic_get_reg(apic, APIC_TMICT);
513
514         /* if initial count is 0, current count should also be 0 */
515         if (tmcct == 0)
516                 return 0;
517
518         if (unlikely(ktime_to_ns(now) <=
519                 ktime_to_ns(apic->timer.last_update))) {
520                 /* Wrap around */
521                 passed = ktime_add(( {
522                                     (ktime_t) {
523                                     .tv64 = KTIME_MAX -
524                                     (apic->timer.last_update).tv64}; }
525                                    ), now);
526                 apic_debug("time elapsed\n");
527         } else
528                 passed = ktime_sub(now, apic->timer.last_update);
529
530         counter_passed = div64_64(ktime_to_ns(passed),
531                                   (APIC_BUS_CYCLE_NS * apic->timer.divide_count));
532
533         if (counter_passed > tmcct) {
534                 if (unlikely(!apic_lvtt_period(apic))) {
535                         /* one-shot timers stick at 0 until reset */
536                         tmcct = 0;
537                 } else {
538                         /*
539                          * periodic timers reset to APIC_TMICT when they
540                          * hit 0. The while loop simulates this happening N
541                          * times. (counter_passed %= tmcct) would also work,
542                          * but might be slower or not work on 32-bit??
543                          */
544                         while (counter_passed > tmcct)
545                                 counter_passed -= tmcct;
546                         tmcct -= counter_passed;
547                 }
548         } else {
549                 tmcct -= counter_passed;
550         }
551
552         return tmcct;
553 }
554
555 static u32 __apic_read(struct kvm_lapic *apic, unsigned int offset)
556 {
557         u32 val = 0;
558
559         if (offset >= LAPIC_MMIO_LENGTH)
560                 return 0;
561
562         switch (offset) {
563         case APIC_ARBPRI:
564                 printk(KERN_WARNING "Access APIC ARBPRI register "
565                        "which is for P6\n");
566                 break;
567
568         case APIC_TMCCT:        /* Timer CCR */
569                 val = apic_get_tmcct(apic);
570                 break;
571
572         default:
573                 apic_update_ppr(apic);
574                 val = apic_get_reg(apic, offset);
575                 break;
576         }
577
578         return val;
579 }
580
581 static void apic_mmio_read(struct kvm_io_device *this,
582                            gpa_t address, int len, void *data)
583 {
584         struct kvm_lapic *apic = (struct kvm_lapic *)this->private;
585         unsigned int offset = address - apic->base_address;
586         unsigned char alignment = offset & 0xf;
587         u32 result;
588
589         if ((alignment + len) > 4) {
590                 printk(KERN_ERR "KVM_APIC_READ: alignment error %lx %d",
591                        (unsigned long)address, len);
592                 return;
593         }
594         result = __apic_read(apic, offset & ~0xf);
595
596         switch (len) {
597         case 1:
598         case 2:
599         case 4:
600                 memcpy(data, (char *)&result + alignment, len);
601                 break;
602         default:
603                 printk(KERN_ERR "Local APIC read with len = %x, "
604                        "should be 1,2, or 4 instead\n", len);
605                 break;
606         }
607 }
608
609 static void update_divide_count(struct kvm_lapic *apic)
610 {
611         u32 tmp1, tmp2, tdcr;
612
613         tdcr = apic_get_reg(apic, APIC_TDCR);
614         tmp1 = tdcr & 0xf;
615         tmp2 = ((tmp1 & 0x3) | ((tmp1 & 0x8) >> 1)) + 1;
616         apic->timer.divide_count = 0x1 << (tmp2 & 0x7);
617
618         apic_debug("timer divide count is 0x%x\n",
619                                    apic->timer.divide_count);
620 }
621
622 static void start_apic_timer(struct kvm_lapic *apic)
623 {
624         ktime_t now = apic->timer.dev.base->get_time();
625
626         apic->timer.last_update = now;
627
628         apic->timer.period = apic_get_reg(apic, APIC_TMICT) *
629                     APIC_BUS_CYCLE_NS * apic->timer.divide_count;
630         atomic_set(&apic->timer.pending, 0);
631         hrtimer_start(&apic->timer.dev,
632                       ktime_add_ns(now, apic->timer.period),
633                       HRTIMER_MODE_ABS);
634
635         apic_debug("%s: bus cycle is %" PRId64 "ns, now 0x%016"
636                            PRIx64 ", "
637                            "timer initial count 0x%x, period %lldns, "
638                            "expire @ 0x%016" PRIx64 ".\n", __FUNCTION__,
639                            APIC_BUS_CYCLE_NS, ktime_to_ns(now),
640                            apic_get_reg(apic, APIC_TMICT),
641                            apic->timer.period,
642                            ktime_to_ns(ktime_add_ns(now,
643                                         apic->timer.period)));
644 }
645
646 static void apic_mmio_write(struct kvm_io_device *this,
647                             gpa_t address, int len, const void *data)
648 {
649         struct kvm_lapic *apic = (struct kvm_lapic *)this->private;
650         unsigned int offset = address - apic->base_address;
651         unsigned char alignment = offset & 0xf;
652         u32 val;
653
654         /*
655          * APIC register must be aligned on 128-bits boundary.
656          * 32/64/128 bits registers must be accessed thru 32 bits.
657          * Refer SDM 8.4.1
658          */
659         if (len != 4 || alignment) {
660                 if (printk_ratelimit())
661                         printk(KERN_ERR "apic write: bad size=%d %lx\n",
662                                len, (long)address);
663                 return;
664         }
665
666         val = *(u32 *) data;
667
668         /* too common printing */
669         if (offset != APIC_EOI)
670                 apic_debug("%s: offset 0x%x with length 0x%x, and value is "
671                            "0x%x\n", __FUNCTION__, offset, len, val);
672
673         offset &= 0xff0;
674
675         switch (offset) {
676         case APIC_ID:           /* Local APIC ID */
677                 apic_set_reg(apic, APIC_ID, val);
678                 break;
679
680         case APIC_TASKPRI:
681                 apic_set_tpr(apic, val & 0xff);
682                 break;
683
684         case APIC_EOI:
685                 apic_set_eoi(apic);
686                 break;
687
688         case APIC_LDR:
689                 apic_set_reg(apic, APIC_LDR, val & APIC_LDR_MASK);
690                 break;
691
692         case APIC_DFR:
693                 apic_set_reg(apic, APIC_DFR, val | 0x0FFFFFFF);
694                 break;
695
696         case APIC_SPIV:
697                 apic_set_reg(apic, APIC_SPIV, val & 0x3ff);
698                 if (!(val & APIC_SPIV_APIC_ENABLED)) {
699                         int i;
700                         u32 lvt_val;
701
702                         for (i = 0; i < APIC_LVT_NUM; i++) {
703                                 lvt_val = apic_get_reg(apic,
704                                                        APIC_LVTT + 0x10 * i);
705                                 apic_set_reg(apic, APIC_LVTT + 0x10 * i,
706                                              lvt_val | APIC_LVT_MASKED);
707                         }
708                         atomic_set(&apic->timer.pending, 0);
709
710                 }
711                 break;
712
713         case APIC_ICR:
714                 /* No delay here, so we always clear the pending bit */
715                 apic_set_reg(apic, APIC_ICR, val & ~(1 << 12));
716                 apic_send_ipi(apic);
717                 break;
718
719         case APIC_ICR2:
720                 apic_set_reg(apic, APIC_ICR2, val & 0xff000000);
721                 break;
722
723         case APIC_LVTT:
724         case APIC_LVTTHMR:
725         case APIC_LVTPC:
726         case APIC_LVT0:
727         case APIC_LVT1:
728         case APIC_LVTERR:
729                 /* TODO: Check vector */
730                 if (!apic_sw_enabled(apic))
731                         val |= APIC_LVT_MASKED;
732
733                 val &= apic_lvt_mask[(offset - APIC_LVTT) >> 4];
734                 apic_set_reg(apic, offset, val);
735
736                 break;
737
738         case APIC_TMICT:
739                 hrtimer_cancel(&apic->timer.dev);
740                 apic_set_reg(apic, APIC_TMICT, val);
741                 start_apic_timer(apic);
742                 return;
743
744         case APIC_TDCR:
745                 if (val & 4)
746                         printk(KERN_ERR "KVM_WRITE:TDCR %x\n", val);
747                 apic_set_reg(apic, APIC_TDCR, val);
748                 update_divide_count(apic);
749                 break;
750
751         default:
752                 apic_debug("Local APIC Write to read-only register %x\n",
753                            offset);
754                 break;
755         }
756
757 }
758
759 static int apic_mmio_range(struct kvm_io_device *this, gpa_t addr)
760 {
761         struct kvm_lapic *apic = (struct kvm_lapic *)this->private;
762         int ret = 0;
763
764
765         if (apic_hw_enabled(apic) &&
766             (addr >= apic->base_address) &&
767             (addr < (apic->base_address + LAPIC_MMIO_LENGTH)))
768                 ret = 1;
769
770         return ret;
771 }
772
773 void kvm_free_lapic(struct kvm_vcpu *vcpu)
774 {
775         if (!vcpu->apic)
776                 return;
777
778         hrtimer_cancel(&vcpu->apic->timer.dev);
779
780         if (vcpu->apic->regs_page)
781                 __free_page(vcpu->apic->regs_page);
782
783         kfree(vcpu->apic);
784 }
785
786 /*
787  *----------------------------------------------------------------------
788  * LAPIC interface
789  *----------------------------------------------------------------------
790  */
791
792 void kvm_lapic_set_tpr(struct kvm_vcpu *vcpu, unsigned long cr8)
793 {
794         struct kvm_lapic *apic = vcpu->apic;
795
796         if (!apic)
797                 return;
798         apic_set_tpr(apic, ((cr8 & 0x0f) << 4));
799 }
800
801 u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu)
802 {
803         struct kvm_lapic *apic = vcpu->apic;
804         u64 tpr;
805
806         if (!apic)
807                 return 0;
808         tpr = (u64) apic_get_reg(apic, APIC_TASKPRI);
809
810         return (tpr & 0xf0) >> 4;
811 }
812 EXPORT_SYMBOL_GPL(kvm_lapic_get_cr8);
813
814 void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
815 {
816         struct kvm_lapic *apic = vcpu->apic;
817
818         if (!apic) {
819                 value |= MSR_IA32_APICBASE_BSP;
820                 vcpu->apic_base = value;
821                 return;
822         }
823         if (apic->vcpu->vcpu_id)
824                 value &= ~MSR_IA32_APICBASE_BSP;
825
826         vcpu->apic_base = value;
827         apic->base_address = apic->vcpu->apic_base &
828                              MSR_IA32_APICBASE_BASE;
829
830         /* with FSB delivery interrupt, we can restart APIC functionality */
831         apic_debug("apic base msr is 0x%016" PRIx64 ", and base address is "
832                    "0x%lx.\n", apic->apic_base, apic->base_address);
833
834 }
835
836 u64 kvm_lapic_get_base(struct kvm_vcpu *vcpu)
837 {
838         return vcpu->apic_base;
839 }
840 EXPORT_SYMBOL_GPL(kvm_lapic_get_base);
841
842 void kvm_lapic_reset(struct kvm_vcpu *vcpu)
843 {
844         struct kvm_lapic *apic;
845         int i;
846
847         apic_debug("%s\n", __FUNCTION__);
848
849         ASSERT(vcpu);
850         apic = vcpu->apic;
851         ASSERT(apic != NULL);
852
853         /* Stop the timer in case it's a reset to an active apic */
854         hrtimer_cancel(&apic->timer.dev);
855
856         apic_set_reg(apic, APIC_ID, vcpu->vcpu_id << 24);
857         apic_set_reg(apic, APIC_LVR, APIC_VERSION);
858
859         for (i = 0; i < APIC_LVT_NUM; i++)
860                 apic_set_reg(apic, APIC_LVTT + 0x10 * i, APIC_LVT_MASKED);
861         apic_set_reg(apic, APIC_LVT0,
862                      SET_APIC_DELIVERY_MODE(0, APIC_MODE_EXTINT));
863
864         apic_set_reg(apic, APIC_DFR, 0xffffffffU);
865         apic_set_reg(apic, APIC_SPIV, 0xff);
866         apic_set_reg(apic, APIC_TASKPRI, 0);
867         apic_set_reg(apic, APIC_LDR, 0);
868         apic_set_reg(apic, APIC_ESR, 0);
869         apic_set_reg(apic, APIC_ICR, 0);
870         apic_set_reg(apic, APIC_ICR2, 0);
871         apic_set_reg(apic, APIC_TDCR, 0);
872         apic_set_reg(apic, APIC_TMICT, 0);
873         for (i = 0; i < 8; i++) {
874                 apic_set_reg(apic, APIC_IRR + 0x10 * i, 0);
875                 apic_set_reg(apic, APIC_ISR + 0x10 * i, 0);
876                 apic_set_reg(apic, APIC_TMR + 0x10 * i, 0);
877         }
878         update_divide_count(apic);
879         atomic_set(&apic->timer.pending, 0);
880         if (vcpu->vcpu_id == 0)
881                 vcpu->apic_base |= MSR_IA32_APICBASE_BSP;
882         apic_update_ppr(apic);
883
884         apic_debug(KERN_INFO "%s: vcpu=%p, id=%d, base_msr="
885                    "0x%016" PRIx64 ", base_address=0x%0lx.\n", __FUNCTION__,
886                    vcpu, kvm_apic_id(apic),
887                    vcpu->apic_base, apic->base_address);
888 }
889 EXPORT_SYMBOL_GPL(kvm_lapic_reset);
890
891 int kvm_lapic_enabled(struct kvm_vcpu *vcpu)
892 {
893         struct kvm_lapic *apic = vcpu->apic;
894         int ret = 0;
895
896         if (!apic)
897                 return 0;
898         ret = apic_enabled(apic);
899
900         return ret;
901 }
902 EXPORT_SYMBOL_GPL(kvm_lapic_enabled);
903
904 /*
905  *----------------------------------------------------------------------
906  * timer interface
907  *----------------------------------------------------------------------
908  */
909
910 /* TODO: make sure __apic_timer_fn runs in current pCPU */
911 static int __apic_timer_fn(struct kvm_lapic *apic)
912 {
913         int result = 0;
914         wait_queue_head_t *q = &apic->vcpu->wq;
915
916         atomic_inc(&apic->timer.pending);
917         if (waitqueue_active(q)) {
918                 apic->vcpu->mp_state = VCPU_MP_STATE_RUNNABLE;
919                 wake_up_interruptible(q);
920         }
921         if (apic_lvtt_period(apic)) {
922                 result = 1;
923                 apic->timer.dev.expires = ktime_add_ns(
924                                         apic->timer.dev.expires,
925                                         apic->timer.period);
926         }
927         return result;
928 }
929
930 static int __inject_apic_timer_irq(struct kvm_lapic *apic)
931 {
932         int vector;
933
934         vector = apic_lvt_vector(apic, APIC_LVTT);
935         return __apic_accept_irq(apic, APIC_DM_FIXED, vector, 1, 0);
936 }
937
938 static enum hrtimer_restart apic_timer_fn(struct hrtimer *data)
939 {
940         struct kvm_lapic *apic;
941         int restart_timer = 0;
942
943         apic = container_of(data, struct kvm_lapic, timer.dev);
944
945         restart_timer = __apic_timer_fn(apic);
946
947         if (restart_timer)
948                 return HRTIMER_RESTART;
949         else
950                 return HRTIMER_NORESTART;
951 }
952
953 int kvm_create_lapic(struct kvm_vcpu *vcpu)
954 {
955         struct kvm_lapic *apic;
956
957         ASSERT(vcpu != NULL);
958         apic_debug("apic_init %d\n", vcpu->vcpu_id);
959
960         apic = kzalloc(sizeof(*apic), GFP_KERNEL);
961         if (!apic)
962                 goto nomem;
963
964         vcpu->apic = apic;
965
966         apic->regs_page = alloc_page(GFP_KERNEL);
967         if (apic->regs_page == NULL) {
968                 printk(KERN_ERR "malloc apic regs error for vcpu %x\n",
969                        vcpu->vcpu_id);
970                 goto nomem_free_apic;
971         }
972         apic->regs = page_address(apic->regs_page);
973         memset(apic->regs, 0, PAGE_SIZE);
974         apic->vcpu = vcpu;
975
976         hrtimer_init(&apic->timer.dev, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
977         apic->timer.dev.function = apic_timer_fn;
978         apic->base_address = APIC_DEFAULT_PHYS_BASE;
979         vcpu->apic_base = APIC_DEFAULT_PHYS_BASE;
980
981         kvm_lapic_reset(vcpu);
982         apic->dev.read = apic_mmio_read;
983         apic->dev.write = apic_mmio_write;
984         apic->dev.in_range = apic_mmio_range;
985         apic->dev.private = apic;
986
987         return 0;
988 nomem_free_apic:
989         kfree(apic);
990 nomem:
991         return -ENOMEM;
992 }
993 EXPORT_SYMBOL_GPL(kvm_create_lapic);
994
995 int kvm_apic_has_interrupt(struct kvm_vcpu *vcpu)
996 {
997         struct kvm_lapic *apic = vcpu->apic;
998         int highest_irr;
999
1000         if (!apic || !apic_enabled(apic))
1001                 return -1;
1002
1003         apic_update_ppr(apic);
1004         highest_irr = apic_find_highest_irr(apic);
1005         if ((highest_irr == -1) ||
1006             ((highest_irr & 0xF0) <= apic_get_reg(apic, APIC_PROCPRI)))
1007                 return -1;
1008         return highest_irr;
1009 }
1010
1011 int kvm_apic_accept_pic_intr(struct kvm_vcpu *vcpu)
1012 {
1013         u32 lvt0 = apic_get_reg(vcpu->apic, APIC_LVT0);
1014         int r = 0;
1015
1016         if (vcpu->vcpu_id == 0) {
1017                 if (!apic_hw_enabled(vcpu->apic))
1018                         r = 1;
1019                 if ((lvt0 & APIC_LVT_MASKED) == 0 &&
1020                     GET_APIC_DELIVERY_MODE(lvt0) == APIC_MODE_EXTINT)
1021                         r = 1;
1022         }
1023         return r;
1024 }
1025
1026 void kvm_inject_apic_timer_irqs(struct kvm_vcpu *vcpu)
1027 {
1028         struct kvm_lapic *apic = vcpu->apic;
1029
1030         if (apic && apic_lvt_enabled(apic, APIC_LVTT) &&
1031                 atomic_read(&apic->timer.pending) > 0) {
1032                 if (__inject_apic_timer_irq(apic))
1033                         atomic_dec(&apic->timer.pending);
1034         }
1035 }
1036
1037 void kvm_apic_timer_intr_post(struct kvm_vcpu *vcpu, int vec)
1038 {
1039         struct kvm_lapic *apic = vcpu->apic;
1040
1041         if (apic && apic_lvt_vector(apic, APIC_LVTT) == vec)
1042                 apic->timer.last_update = ktime_add_ns(
1043                                 apic->timer.last_update,
1044                                 apic->timer.period);
1045 }
1046
1047 int kvm_get_apic_interrupt(struct kvm_vcpu *vcpu)
1048 {
1049         int vector = kvm_apic_has_interrupt(vcpu);
1050         struct kvm_lapic *apic = vcpu->apic;
1051
1052         if (vector == -1)
1053                 return -1;
1054
1055         apic_set_vector(vector, apic->regs + APIC_ISR);
1056         apic_update_ppr(apic);
1057         apic_clear_irr(vector, apic);
1058         return vector;
1059 }
1060
1061 void kvm_apic_post_state_restore(struct kvm_vcpu *vcpu)
1062 {
1063         struct kvm_lapic *apic = vcpu->apic;
1064
1065         apic->base_address = vcpu->apic_base &
1066                              MSR_IA32_APICBASE_BASE;
1067         apic_set_reg(apic, APIC_LVR, APIC_VERSION);
1068         apic_update_ppr(apic);
1069         hrtimer_cancel(&apic->timer.dev);
1070         update_divide_count(apic);
1071         start_apic_timer(apic);
1072 }
1073
1074 void kvm_migrate_apic_timer(struct kvm_vcpu *vcpu)
1075 {
1076         struct kvm_lapic *apic = vcpu->apic;
1077         struct hrtimer *timer;
1078
1079         if (!apic)
1080                 return;
1081
1082         timer = &apic->timer.dev;
1083         if (hrtimer_cancel(timer))
1084                 hrtimer_start(timer, timer->expires, HRTIMER_MODE_ABS);
1085 }
1086 EXPORT_SYMBOL_GPL(kvm_migrate_apic_timer);