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