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