KVM: arm-vgic: Add vgic reg access from dev attr
[firefly-linux-kernel-4.4.55.git] / virt / kvm / arm / vgic.c
1 /*
2  * Copyright (C) 2012 ARM Ltd.
3  * Author: Marc Zyngier <marc.zyngier@arm.com>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  */
18
19 #include <linux/cpu.h>
20 #include <linux/kvm.h>
21 #include <linux/kvm_host.h>
22 #include <linux/interrupt.h>
23 #include <linux/io.h>
24 #include <linux/of.h>
25 #include <linux/of_address.h>
26 #include <linux/of_irq.h>
27
28 #include <linux/irqchip/arm-gic.h>
29
30 #include <asm/kvm_emulate.h>
31 #include <asm/kvm_arm.h>
32 #include <asm/kvm_mmu.h>
33
34 /*
35  * How the whole thing works (courtesy of Christoffer Dall):
36  *
37  * - At any time, the dist->irq_pending_on_cpu is the oracle that knows if
38  *   something is pending
39  * - VGIC pending interrupts are stored on the vgic.irq_state vgic
40  *   bitmap (this bitmap is updated by both user land ioctls and guest
41  *   mmio ops, and other in-kernel peripherals such as the
42  *   arch. timers) and indicate the 'wire' state.
43  * - Every time the bitmap changes, the irq_pending_on_cpu oracle is
44  *   recalculated
45  * - To calculate the oracle, we need info for each cpu from
46  *   compute_pending_for_cpu, which considers:
47  *   - PPI: dist->irq_state & dist->irq_enable
48  *   - SPI: dist->irq_state & dist->irq_enable & dist->irq_spi_target
49  *   - irq_spi_target is a 'formatted' version of the GICD_ICFGR
50  *     registers, stored on each vcpu. We only keep one bit of
51  *     information per interrupt, making sure that only one vcpu can
52  *     accept the interrupt.
53  * - The same is true when injecting an interrupt, except that we only
54  *   consider a single interrupt at a time. The irq_spi_cpu array
55  *   contains the target CPU for each SPI.
56  *
57  * The handling of level interrupts adds some extra complexity. We
58  * need to track when the interrupt has been EOIed, so we can sample
59  * the 'line' again. This is achieved as such:
60  *
61  * - When a level interrupt is moved onto a vcpu, the corresponding
62  *   bit in irq_active is set. As long as this bit is set, the line
63  *   will be ignored for further interrupts. The interrupt is injected
64  *   into the vcpu with the GICH_LR_EOI bit set (generate a
65  *   maintenance interrupt on EOI).
66  * - When the interrupt is EOIed, the maintenance interrupt fires,
67  *   and clears the corresponding bit in irq_active. This allow the
68  *   interrupt line to be sampled again.
69  */
70
71 #define VGIC_ADDR_UNDEF         (-1)
72 #define IS_VGIC_ADDR_UNDEF(_x)  ((_x) == VGIC_ADDR_UNDEF)
73
74 /* Physical address of vgic virtual cpu interface */
75 static phys_addr_t vgic_vcpu_base;
76
77 /* Virtual control interface base address */
78 static void __iomem *vgic_vctrl_base;
79
80 static struct device_node *vgic_node;
81
82 #define ACCESS_READ_VALUE       (1 << 0)
83 #define ACCESS_READ_RAZ         (0 << 0)
84 #define ACCESS_READ_MASK(x)     ((x) & (1 << 0))
85 #define ACCESS_WRITE_IGNORED    (0 << 1)
86 #define ACCESS_WRITE_SETBIT     (1 << 1)
87 #define ACCESS_WRITE_CLEARBIT   (2 << 1)
88 #define ACCESS_WRITE_VALUE      (3 << 1)
89 #define ACCESS_WRITE_MASK(x)    ((x) & (3 << 1))
90
91 static void vgic_retire_disabled_irqs(struct kvm_vcpu *vcpu);
92 static void vgic_update_state(struct kvm *kvm);
93 static void vgic_kick_vcpus(struct kvm *kvm);
94 static void vgic_dispatch_sgi(struct kvm_vcpu *vcpu, u32 reg);
95 static u32 vgic_nr_lr;
96
97 static unsigned int vgic_maint_irq;
98
99 static u32 *vgic_bitmap_get_reg(struct vgic_bitmap *x,
100                                 int cpuid, u32 offset)
101 {
102         offset >>= 2;
103         if (!offset)
104                 return x->percpu[cpuid].reg;
105         else
106                 return x->shared.reg + offset - 1;
107 }
108
109 static int vgic_bitmap_get_irq_val(struct vgic_bitmap *x,
110                                    int cpuid, int irq)
111 {
112         if (irq < VGIC_NR_PRIVATE_IRQS)
113                 return test_bit(irq, x->percpu[cpuid].reg_ul);
114
115         return test_bit(irq - VGIC_NR_PRIVATE_IRQS, x->shared.reg_ul);
116 }
117
118 static void vgic_bitmap_set_irq_val(struct vgic_bitmap *x, int cpuid,
119                                     int irq, int val)
120 {
121         unsigned long *reg;
122
123         if (irq < VGIC_NR_PRIVATE_IRQS) {
124                 reg = x->percpu[cpuid].reg_ul;
125         } else {
126                 reg =  x->shared.reg_ul;
127                 irq -= VGIC_NR_PRIVATE_IRQS;
128         }
129
130         if (val)
131                 set_bit(irq, reg);
132         else
133                 clear_bit(irq, reg);
134 }
135
136 static unsigned long *vgic_bitmap_get_cpu_map(struct vgic_bitmap *x, int cpuid)
137 {
138         if (unlikely(cpuid >= VGIC_MAX_CPUS))
139                 return NULL;
140         return x->percpu[cpuid].reg_ul;
141 }
142
143 static unsigned long *vgic_bitmap_get_shared_map(struct vgic_bitmap *x)
144 {
145         return x->shared.reg_ul;
146 }
147
148 static u32 *vgic_bytemap_get_reg(struct vgic_bytemap *x, int cpuid, u32 offset)
149 {
150         offset >>= 2;
151         BUG_ON(offset > (VGIC_NR_IRQS / 4));
152         if (offset < 8)
153                 return x->percpu[cpuid] + offset;
154         else
155                 return x->shared + offset - 8;
156 }
157
158 #define VGIC_CFG_LEVEL  0
159 #define VGIC_CFG_EDGE   1
160
161 static bool vgic_irq_is_edge(struct kvm_vcpu *vcpu, int irq)
162 {
163         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
164         int irq_val;
165
166         irq_val = vgic_bitmap_get_irq_val(&dist->irq_cfg, vcpu->vcpu_id, irq);
167         return irq_val == VGIC_CFG_EDGE;
168 }
169
170 static int vgic_irq_is_enabled(struct kvm_vcpu *vcpu, int irq)
171 {
172         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
173
174         return vgic_bitmap_get_irq_val(&dist->irq_enabled, vcpu->vcpu_id, irq);
175 }
176
177 static int vgic_irq_is_active(struct kvm_vcpu *vcpu, int irq)
178 {
179         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
180
181         return vgic_bitmap_get_irq_val(&dist->irq_active, vcpu->vcpu_id, irq);
182 }
183
184 static void vgic_irq_set_active(struct kvm_vcpu *vcpu, int irq)
185 {
186         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
187
188         vgic_bitmap_set_irq_val(&dist->irq_active, vcpu->vcpu_id, irq, 1);
189 }
190
191 static void vgic_irq_clear_active(struct kvm_vcpu *vcpu, int irq)
192 {
193         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
194
195         vgic_bitmap_set_irq_val(&dist->irq_active, vcpu->vcpu_id, irq, 0);
196 }
197
198 static int vgic_dist_irq_is_pending(struct kvm_vcpu *vcpu, int irq)
199 {
200         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
201
202         return vgic_bitmap_get_irq_val(&dist->irq_state, vcpu->vcpu_id, irq);
203 }
204
205 static void vgic_dist_irq_set(struct kvm_vcpu *vcpu, int irq)
206 {
207         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
208
209         vgic_bitmap_set_irq_val(&dist->irq_state, vcpu->vcpu_id, irq, 1);
210 }
211
212 static void vgic_dist_irq_clear(struct kvm_vcpu *vcpu, int irq)
213 {
214         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
215
216         vgic_bitmap_set_irq_val(&dist->irq_state, vcpu->vcpu_id, irq, 0);
217 }
218
219 static void vgic_cpu_irq_set(struct kvm_vcpu *vcpu, int irq)
220 {
221         if (irq < VGIC_NR_PRIVATE_IRQS)
222                 set_bit(irq, vcpu->arch.vgic_cpu.pending_percpu);
223         else
224                 set_bit(irq - VGIC_NR_PRIVATE_IRQS,
225                         vcpu->arch.vgic_cpu.pending_shared);
226 }
227
228 static void vgic_cpu_irq_clear(struct kvm_vcpu *vcpu, int irq)
229 {
230         if (irq < VGIC_NR_PRIVATE_IRQS)
231                 clear_bit(irq, vcpu->arch.vgic_cpu.pending_percpu);
232         else
233                 clear_bit(irq - VGIC_NR_PRIVATE_IRQS,
234                           vcpu->arch.vgic_cpu.pending_shared);
235 }
236
237 static u32 mmio_data_read(struct kvm_exit_mmio *mmio, u32 mask)
238 {
239         return *((u32 *)mmio->data) & mask;
240 }
241
242 static void mmio_data_write(struct kvm_exit_mmio *mmio, u32 mask, u32 value)
243 {
244         *((u32 *)mmio->data) = value & mask;
245 }
246
247 /**
248  * vgic_reg_access - access vgic register
249  * @mmio:   pointer to the data describing the mmio access
250  * @reg:    pointer to the virtual backing of vgic distributor data
251  * @offset: least significant 2 bits used for word offset
252  * @mode:   ACCESS_ mode (see defines above)
253  *
254  * Helper to make vgic register access easier using one of the access
255  * modes defined for vgic register access
256  * (read,raz,write-ignored,setbit,clearbit,write)
257  */
258 static void vgic_reg_access(struct kvm_exit_mmio *mmio, u32 *reg,
259                             phys_addr_t offset, int mode)
260 {
261         int word_offset = (offset & 3) * 8;
262         u32 mask = (1UL << (mmio->len * 8)) - 1;
263         u32 regval;
264
265         /*
266          * Any alignment fault should have been delivered to the guest
267          * directly (ARM ARM B3.12.7 "Prioritization of aborts").
268          */
269
270         if (reg) {
271                 regval = *reg;
272         } else {
273                 BUG_ON(mode != (ACCESS_READ_RAZ | ACCESS_WRITE_IGNORED));
274                 regval = 0;
275         }
276
277         if (mmio->is_write) {
278                 u32 data = mmio_data_read(mmio, mask) << word_offset;
279                 switch (ACCESS_WRITE_MASK(mode)) {
280                 case ACCESS_WRITE_IGNORED:
281                         return;
282
283                 case ACCESS_WRITE_SETBIT:
284                         regval |= data;
285                         break;
286
287                 case ACCESS_WRITE_CLEARBIT:
288                         regval &= ~data;
289                         break;
290
291                 case ACCESS_WRITE_VALUE:
292                         regval = (regval & ~(mask << word_offset)) | data;
293                         break;
294                 }
295                 *reg = regval;
296         } else {
297                 switch (ACCESS_READ_MASK(mode)) {
298                 case ACCESS_READ_RAZ:
299                         regval = 0;
300                         /* fall through */
301
302                 case ACCESS_READ_VALUE:
303                         mmio_data_write(mmio, mask, regval >> word_offset);
304                 }
305         }
306 }
307
308 static bool handle_mmio_misc(struct kvm_vcpu *vcpu,
309                              struct kvm_exit_mmio *mmio, phys_addr_t offset)
310 {
311         u32 reg;
312         u32 word_offset = offset & 3;
313
314         switch (offset & ~3) {
315         case 0:                 /* CTLR */
316                 reg = vcpu->kvm->arch.vgic.enabled;
317                 vgic_reg_access(mmio, &reg, word_offset,
318                                 ACCESS_READ_VALUE | ACCESS_WRITE_VALUE);
319                 if (mmio->is_write) {
320                         vcpu->kvm->arch.vgic.enabled = reg & 1;
321                         vgic_update_state(vcpu->kvm);
322                         return true;
323                 }
324                 break;
325
326         case 4:                 /* TYPER */
327                 reg  = (atomic_read(&vcpu->kvm->online_vcpus) - 1) << 5;
328                 reg |= (VGIC_NR_IRQS >> 5) - 1;
329                 vgic_reg_access(mmio, &reg, word_offset,
330                                 ACCESS_READ_VALUE | ACCESS_WRITE_IGNORED);
331                 break;
332
333         case 8:                 /* IIDR */
334                 reg = 0x4B00043B;
335                 vgic_reg_access(mmio, &reg, word_offset,
336                                 ACCESS_READ_VALUE | ACCESS_WRITE_IGNORED);
337                 break;
338         }
339
340         return false;
341 }
342
343 static bool handle_mmio_raz_wi(struct kvm_vcpu *vcpu,
344                                struct kvm_exit_mmio *mmio, phys_addr_t offset)
345 {
346         vgic_reg_access(mmio, NULL, offset,
347                         ACCESS_READ_RAZ | ACCESS_WRITE_IGNORED);
348         return false;
349 }
350
351 static bool handle_mmio_set_enable_reg(struct kvm_vcpu *vcpu,
352                                        struct kvm_exit_mmio *mmio,
353                                        phys_addr_t offset)
354 {
355         u32 *reg = vgic_bitmap_get_reg(&vcpu->kvm->arch.vgic.irq_enabled,
356                                        vcpu->vcpu_id, offset);
357         vgic_reg_access(mmio, reg, offset,
358                         ACCESS_READ_VALUE | ACCESS_WRITE_SETBIT);
359         if (mmio->is_write) {
360                 vgic_update_state(vcpu->kvm);
361                 return true;
362         }
363
364         return false;
365 }
366
367 static bool handle_mmio_clear_enable_reg(struct kvm_vcpu *vcpu,
368                                          struct kvm_exit_mmio *mmio,
369                                          phys_addr_t offset)
370 {
371         u32 *reg = vgic_bitmap_get_reg(&vcpu->kvm->arch.vgic.irq_enabled,
372                                        vcpu->vcpu_id, offset);
373         vgic_reg_access(mmio, reg, offset,
374                         ACCESS_READ_VALUE | ACCESS_WRITE_CLEARBIT);
375         if (mmio->is_write) {
376                 if (offset < 4) /* Force SGI enabled */
377                         *reg |= 0xffff;
378                 vgic_retire_disabled_irqs(vcpu);
379                 vgic_update_state(vcpu->kvm);
380                 return true;
381         }
382
383         return false;
384 }
385
386 static bool handle_mmio_set_pending_reg(struct kvm_vcpu *vcpu,
387                                         struct kvm_exit_mmio *mmio,
388                                         phys_addr_t offset)
389 {
390         u32 *reg = vgic_bitmap_get_reg(&vcpu->kvm->arch.vgic.irq_state,
391                                        vcpu->vcpu_id, offset);
392         vgic_reg_access(mmio, reg, offset,
393                         ACCESS_READ_VALUE | ACCESS_WRITE_SETBIT);
394         if (mmio->is_write) {
395                 vgic_update_state(vcpu->kvm);
396                 return true;
397         }
398
399         return false;
400 }
401
402 static bool handle_mmio_clear_pending_reg(struct kvm_vcpu *vcpu,
403                                           struct kvm_exit_mmio *mmio,
404                                           phys_addr_t offset)
405 {
406         u32 *reg = vgic_bitmap_get_reg(&vcpu->kvm->arch.vgic.irq_state,
407                                        vcpu->vcpu_id, offset);
408         vgic_reg_access(mmio, reg, offset,
409                         ACCESS_READ_VALUE | ACCESS_WRITE_CLEARBIT);
410         if (mmio->is_write) {
411                 vgic_update_state(vcpu->kvm);
412                 return true;
413         }
414
415         return false;
416 }
417
418 static bool handle_mmio_priority_reg(struct kvm_vcpu *vcpu,
419                                      struct kvm_exit_mmio *mmio,
420                                      phys_addr_t offset)
421 {
422         u32 *reg = vgic_bytemap_get_reg(&vcpu->kvm->arch.vgic.irq_priority,
423                                         vcpu->vcpu_id, offset);
424         vgic_reg_access(mmio, reg, offset,
425                         ACCESS_READ_VALUE | ACCESS_WRITE_VALUE);
426         return false;
427 }
428
429 #define GICD_ITARGETSR_SIZE     32
430 #define GICD_CPUTARGETS_BITS    8
431 #define GICD_IRQS_PER_ITARGETSR (GICD_ITARGETSR_SIZE / GICD_CPUTARGETS_BITS)
432 static u32 vgic_get_target_reg(struct kvm *kvm, int irq)
433 {
434         struct vgic_dist *dist = &kvm->arch.vgic;
435         int i;
436         u32 val = 0;
437
438         irq -= VGIC_NR_PRIVATE_IRQS;
439
440         for (i = 0; i < GICD_IRQS_PER_ITARGETSR; i++)
441                 val |= 1 << (dist->irq_spi_cpu[irq + i] + i * 8);
442
443         return val;
444 }
445
446 static void vgic_set_target_reg(struct kvm *kvm, u32 val, int irq)
447 {
448         struct vgic_dist *dist = &kvm->arch.vgic;
449         struct kvm_vcpu *vcpu;
450         int i, c;
451         unsigned long *bmap;
452         u32 target;
453
454         irq -= VGIC_NR_PRIVATE_IRQS;
455
456         /*
457          * Pick the LSB in each byte. This ensures we target exactly
458          * one vcpu per IRQ. If the byte is null, assume we target
459          * CPU0.
460          */
461         for (i = 0; i < GICD_IRQS_PER_ITARGETSR; i++) {
462                 int shift = i * GICD_CPUTARGETS_BITS;
463                 target = ffs((val >> shift) & 0xffU);
464                 target = target ? (target - 1) : 0;
465                 dist->irq_spi_cpu[irq + i] = target;
466                 kvm_for_each_vcpu(c, vcpu, kvm) {
467                         bmap = vgic_bitmap_get_shared_map(&dist->irq_spi_target[c]);
468                         if (c == target)
469                                 set_bit(irq + i, bmap);
470                         else
471                                 clear_bit(irq + i, bmap);
472                 }
473         }
474 }
475
476 static bool handle_mmio_target_reg(struct kvm_vcpu *vcpu,
477                                    struct kvm_exit_mmio *mmio,
478                                    phys_addr_t offset)
479 {
480         u32 reg;
481
482         /* We treat the banked interrupts targets as read-only */
483         if (offset < 32) {
484                 u32 roreg = 1 << vcpu->vcpu_id;
485                 roreg |= roreg << 8;
486                 roreg |= roreg << 16;
487
488                 vgic_reg_access(mmio, &roreg, offset,
489                                 ACCESS_READ_VALUE | ACCESS_WRITE_IGNORED);
490                 return false;
491         }
492
493         reg = vgic_get_target_reg(vcpu->kvm, offset & ~3U);
494         vgic_reg_access(mmio, &reg, offset,
495                         ACCESS_READ_VALUE | ACCESS_WRITE_VALUE);
496         if (mmio->is_write) {
497                 vgic_set_target_reg(vcpu->kvm, reg, offset & ~3U);
498                 vgic_update_state(vcpu->kvm);
499                 return true;
500         }
501
502         return false;
503 }
504
505 static u32 vgic_cfg_expand(u16 val)
506 {
507         u32 res = 0;
508         int i;
509
510         /*
511          * Turn a 16bit value like abcd...mnop into a 32bit word
512          * a0b0c0d0...m0n0o0p0, which is what the HW cfg register is.
513          */
514         for (i = 0; i < 16; i++)
515                 res |= ((val >> i) & VGIC_CFG_EDGE) << (2 * i + 1);
516
517         return res;
518 }
519
520 static u16 vgic_cfg_compress(u32 val)
521 {
522         u16 res = 0;
523         int i;
524
525         /*
526          * Turn a 32bit word a0b0c0d0...m0n0o0p0 into 16bit value like
527          * abcd...mnop which is what we really care about.
528          */
529         for (i = 0; i < 16; i++)
530                 res |= ((val >> (i * 2 + 1)) & VGIC_CFG_EDGE) << i;
531
532         return res;
533 }
534
535 /*
536  * The distributor uses 2 bits per IRQ for the CFG register, but the
537  * LSB is always 0. As such, we only keep the upper bit, and use the
538  * two above functions to compress/expand the bits
539  */
540 static bool handle_mmio_cfg_reg(struct kvm_vcpu *vcpu,
541                                 struct kvm_exit_mmio *mmio, phys_addr_t offset)
542 {
543         u32 val;
544         u32 *reg;
545
546         offset >>= 1;
547         reg = vgic_bitmap_get_reg(&vcpu->kvm->arch.vgic.irq_cfg,
548                                   vcpu->vcpu_id, offset);
549
550         if (offset & 2)
551                 val = *reg >> 16;
552         else
553                 val = *reg & 0xffff;
554
555         val = vgic_cfg_expand(val);
556         vgic_reg_access(mmio, &val, offset,
557                         ACCESS_READ_VALUE | ACCESS_WRITE_VALUE);
558         if (mmio->is_write) {
559                 if (offset < 4) {
560                         *reg = ~0U; /* Force PPIs/SGIs to 1 */
561                         return false;
562                 }
563
564                 val = vgic_cfg_compress(val);
565                 if (offset & 2) {
566                         *reg &= 0xffff;
567                         *reg |= val << 16;
568                 } else {
569                         *reg &= 0xffff << 16;
570                         *reg |= val;
571                 }
572         }
573
574         return false;
575 }
576
577 static bool handle_mmio_sgi_reg(struct kvm_vcpu *vcpu,
578                                 struct kvm_exit_mmio *mmio, phys_addr_t offset)
579 {
580         u32 reg;
581         vgic_reg_access(mmio, &reg, offset,
582                         ACCESS_READ_RAZ | ACCESS_WRITE_VALUE);
583         if (mmio->is_write) {
584                 vgic_dispatch_sgi(vcpu, reg);
585                 vgic_update_state(vcpu->kvm);
586                 return true;
587         }
588
589         return false;
590 }
591
592 static bool handle_mmio_sgi_clear(struct kvm_vcpu *vcpu,
593                                   struct kvm_exit_mmio *mmio,
594                                   phys_addr_t offset)
595 {
596         return false;
597 }
598
599 static bool handle_mmio_sgi_set(struct kvm_vcpu *vcpu,
600                                 struct kvm_exit_mmio *mmio,
601                                 phys_addr_t offset)
602 {
603         return false;
604 }
605
606 /*
607  * I would have liked to use the kvm_bus_io_*() API instead, but it
608  * cannot cope with banked registers (only the VM pointer is passed
609  * around, and we need the vcpu). One of these days, someone please
610  * fix it!
611  */
612 struct mmio_range {
613         phys_addr_t base;
614         unsigned long len;
615         bool (*handle_mmio)(struct kvm_vcpu *vcpu, struct kvm_exit_mmio *mmio,
616                             phys_addr_t offset);
617 };
618
619 static const struct mmio_range vgic_dist_ranges[] = {
620         {
621                 .base           = GIC_DIST_CTRL,
622                 .len            = 12,
623                 .handle_mmio    = handle_mmio_misc,
624         },
625         {
626                 .base           = GIC_DIST_IGROUP,
627                 .len            = VGIC_NR_IRQS / 8,
628                 .handle_mmio    = handle_mmio_raz_wi,
629         },
630         {
631                 .base           = GIC_DIST_ENABLE_SET,
632                 .len            = VGIC_NR_IRQS / 8,
633                 .handle_mmio    = handle_mmio_set_enable_reg,
634         },
635         {
636                 .base           = GIC_DIST_ENABLE_CLEAR,
637                 .len            = VGIC_NR_IRQS / 8,
638                 .handle_mmio    = handle_mmio_clear_enable_reg,
639         },
640         {
641                 .base           = GIC_DIST_PENDING_SET,
642                 .len            = VGIC_NR_IRQS / 8,
643                 .handle_mmio    = handle_mmio_set_pending_reg,
644         },
645         {
646                 .base           = GIC_DIST_PENDING_CLEAR,
647                 .len            = VGIC_NR_IRQS / 8,
648                 .handle_mmio    = handle_mmio_clear_pending_reg,
649         },
650         {
651                 .base           = GIC_DIST_ACTIVE_SET,
652                 .len            = VGIC_NR_IRQS / 8,
653                 .handle_mmio    = handle_mmio_raz_wi,
654         },
655         {
656                 .base           = GIC_DIST_ACTIVE_CLEAR,
657                 .len            = VGIC_NR_IRQS / 8,
658                 .handle_mmio    = handle_mmio_raz_wi,
659         },
660         {
661                 .base           = GIC_DIST_PRI,
662                 .len            = VGIC_NR_IRQS,
663                 .handle_mmio    = handle_mmio_priority_reg,
664         },
665         {
666                 .base           = GIC_DIST_TARGET,
667                 .len            = VGIC_NR_IRQS,
668                 .handle_mmio    = handle_mmio_target_reg,
669         },
670         {
671                 .base           = GIC_DIST_CONFIG,
672                 .len            = VGIC_NR_IRQS / 4,
673                 .handle_mmio    = handle_mmio_cfg_reg,
674         },
675         {
676                 .base           = GIC_DIST_SOFTINT,
677                 .len            = 4,
678                 .handle_mmio    = handle_mmio_sgi_reg,
679         },
680         {
681                 .base           = GIC_DIST_SGI_PENDING_CLEAR,
682                 .len            = VGIC_NR_SGIS,
683                 .handle_mmio    = handle_mmio_sgi_clear,
684         },
685         {
686                 .base           = GIC_DIST_SGI_PENDING_SET,
687                 .len            = VGIC_NR_SGIS,
688                 .handle_mmio    = handle_mmio_sgi_set,
689         },
690         {}
691 };
692
693 static const
694 struct mmio_range *find_matching_range(const struct mmio_range *ranges,
695                                        struct kvm_exit_mmio *mmio,
696                                        phys_addr_t offset)
697 {
698         const struct mmio_range *r = ranges;
699
700         while (r->len) {
701                 if (offset >= r->base &&
702                     (offset + mmio->len) <= (r->base + r->len))
703                         return r;
704                 r++;
705         }
706
707         return NULL;
708 }
709
710 /**
711  * vgic_handle_mmio - handle an in-kernel MMIO access
712  * @vcpu:       pointer to the vcpu performing the access
713  * @run:        pointer to the kvm_run structure
714  * @mmio:       pointer to the data describing the access
715  *
716  * returns true if the MMIO access has been performed in kernel space,
717  * and false if it needs to be emulated in user space.
718  */
719 bool vgic_handle_mmio(struct kvm_vcpu *vcpu, struct kvm_run *run,
720                       struct kvm_exit_mmio *mmio)
721 {
722         const struct mmio_range *range;
723         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
724         unsigned long base = dist->vgic_dist_base;
725         bool updated_state;
726         unsigned long offset;
727
728         if (!irqchip_in_kernel(vcpu->kvm) ||
729             mmio->phys_addr < base ||
730             (mmio->phys_addr + mmio->len) > (base + KVM_VGIC_V2_DIST_SIZE))
731                 return false;
732
733         /* We don't support ldrd / strd or ldm / stm to the emulated vgic */
734         if (mmio->len > 4) {
735                 kvm_inject_dabt(vcpu, mmio->phys_addr);
736                 return true;
737         }
738
739         offset = mmio->phys_addr - base;
740         range = find_matching_range(vgic_dist_ranges, mmio, offset);
741         if (unlikely(!range || !range->handle_mmio)) {
742                 pr_warn("Unhandled access %d %08llx %d\n",
743                         mmio->is_write, mmio->phys_addr, mmio->len);
744                 return false;
745         }
746
747         spin_lock(&vcpu->kvm->arch.vgic.lock);
748         offset = mmio->phys_addr - range->base - base;
749         updated_state = range->handle_mmio(vcpu, mmio, offset);
750         spin_unlock(&vcpu->kvm->arch.vgic.lock);
751         kvm_prepare_mmio(run, mmio);
752         kvm_handle_mmio_return(vcpu, run);
753
754         if (updated_state)
755                 vgic_kick_vcpus(vcpu->kvm);
756
757         return true;
758 }
759
760 static void vgic_dispatch_sgi(struct kvm_vcpu *vcpu, u32 reg)
761 {
762         struct kvm *kvm = vcpu->kvm;
763         struct vgic_dist *dist = &kvm->arch.vgic;
764         int nrcpus = atomic_read(&kvm->online_vcpus);
765         u8 target_cpus;
766         int sgi, mode, c, vcpu_id;
767
768         vcpu_id = vcpu->vcpu_id;
769
770         sgi = reg & 0xf;
771         target_cpus = (reg >> 16) & 0xff;
772         mode = (reg >> 24) & 3;
773
774         switch (mode) {
775         case 0:
776                 if (!target_cpus)
777                         return;
778
779         case 1:
780                 target_cpus = ((1 << nrcpus) - 1) & ~(1 << vcpu_id) & 0xff;
781                 break;
782
783         case 2:
784                 target_cpus = 1 << vcpu_id;
785                 break;
786         }
787
788         kvm_for_each_vcpu(c, vcpu, kvm) {
789                 if (target_cpus & 1) {
790                         /* Flag the SGI as pending */
791                         vgic_dist_irq_set(vcpu, sgi);
792                         dist->irq_sgi_sources[c][sgi] |= 1 << vcpu_id;
793                         kvm_debug("SGI%d from CPU%d to CPU%d\n", sgi, vcpu_id, c);
794                 }
795
796                 target_cpus >>= 1;
797         }
798 }
799
800 static int compute_pending_for_cpu(struct kvm_vcpu *vcpu)
801 {
802         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
803         unsigned long *pending, *enabled, *pend_percpu, *pend_shared;
804         unsigned long pending_private, pending_shared;
805         int vcpu_id;
806
807         vcpu_id = vcpu->vcpu_id;
808         pend_percpu = vcpu->arch.vgic_cpu.pending_percpu;
809         pend_shared = vcpu->arch.vgic_cpu.pending_shared;
810
811         pending = vgic_bitmap_get_cpu_map(&dist->irq_state, vcpu_id);
812         enabled = vgic_bitmap_get_cpu_map(&dist->irq_enabled, vcpu_id);
813         bitmap_and(pend_percpu, pending, enabled, VGIC_NR_PRIVATE_IRQS);
814
815         pending = vgic_bitmap_get_shared_map(&dist->irq_state);
816         enabled = vgic_bitmap_get_shared_map(&dist->irq_enabled);
817         bitmap_and(pend_shared, pending, enabled, VGIC_NR_SHARED_IRQS);
818         bitmap_and(pend_shared, pend_shared,
819                    vgic_bitmap_get_shared_map(&dist->irq_spi_target[vcpu_id]),
820                    VGIC_NR_SHARED_IRQS);
821
822         pending_private = find_first_bit(pend_percpu, VGIC_NR_PRIVATE_IRQS);
823         pending_shared = find_first_bit(pend_shared, VGIC_NR_SHARED_IRQS);
824         return (pending_private < VGIC_NR_PRIVATE_IRQS ||
825                 pending_shared < VGIC_NR_SHARED_IRQS);
826 }
827
828 /*
829  * Update the interrupt state and determine which CPUs have pending
830  * interrupts. Must be called with distributor lock held.
831  */
832 static void vgic_update_state(struct kvm *kvm)
833 {
834         struct vgic_dist *dist = &kvm->arch.vgic;
835         struct kvm_vcpu *vcpu;
836         int c;
837
838         if (!dist->enabled) {
839                 set_bit(0, &dist->irq_pending_on_cpu);
840                 return;
841         }
842
843         kvm_for_each_vcpu(c, vcpu, kvm) {
844                 if (compute_pending_for_cpu(vcpu)) {
845                         pr_debug("CPU%d has pending interrupts\n", c);
846                         set_bit(c, &dist->irq_pending_on_cpu);
847                 }
848         }
849 }
850
851 #define LR_CPUID(lr)    \
852         (((lr) & GICH_LR_PHYSID_CPUID) >> GICH_LR_PHYSID_CPUID_SHIFT)
853 #define MK_LR_PEND(src, irq)    \
854         (GICH_LR_PENDING_BIT | ((src) << GICH_LR_PHYSID_CPUID_SHIFT) | (irq))
855
856 /*
857  * An interrupt may have been disabled after being made pending on the
858  * CPU interface (the classic case is a timer running while we're
859  * rebooting the guest - the interrupt would kick as soon as the CPU
860  * interface gets enabled, with deadly consequences).
861  *
862  * The solution is to examine already active LRs, and check the
863  * interrupt is still enabled. If not, just retire it.
864  */
865 static void vgic_retire_disabled_irqs(struct kvm_vcpu *vcpu)
866 {
867         struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
868         int lr;
869
870         for_each_set_bit(lr, vgic_cpu->lr_used, vgic_cpu->nr_lr) {
871                 int irq = vgic_cpu->vgic_lr[lr] & GICH_LR_VIRTUALID;
872
873                 if (!vgic_irq_is_enabled(vcpu, irq)) {
874                         vgic_cpu->vgic_irq_lr_map[irq] = LR_EMPTY;
875                         clear_bit(lr, vgic_cpu->lr_used);
876                         vgic_cpu->vgic_lr[lr] &= ~GICH_LR_STATE;
877                         if (vgic_irq_is_active(vcpu, irq))
878                                 vgic_irq_clear_active(vcpu, irq);
879                 }
880         }
881 }
882
883 /*
884  * Queue an interrupt to a CPU virtual interface. Return true on success,
885  * or false if it wasn't possible to queue it.
886  */
887 static bool vgic_queue_irq(struct kvm_vcpu *vcpu, u8 sgi_source_id, int irq)
888 {
889         struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
890         int lr;
891
892         /* Sanitize the input... */
893         BUG_ON(sgi_source_id & ~7);
894         BUG_ON(sgi_source_id && irq >= VGIC_NR_SGIS);
895         BUG_ON(irq >= VGIC_NR_IRQS);
896
897         kvm_debug("Queue IRQ%d\n", irq);
898
899         lr = vgic_cpu->vgic_irq_lr_map[irq];
900
901         /* Do we have an active interrupt for the same CPUID? */
902         if (lr != LR_EMPTY &&
903             (LR_CPUID(vgic_cpu->vgic_lr[lr]) == sgi_source_id)) {
904                 kvm_debug("LR%d piggyback for IRQ%d %x\n",
905                           lr, irq, vgic_cpu->vgic_lr[lr]);
906                 BUG_ON(!test_bit(lr, vgic_cpu->lr_used));
907                 vgic_cpu->vgic_lr[lr] |= GICH_LR_PENDING_BIT;
908                 return true;
909         }
910
911         /* Try to use another LR for this interrupt */
912         lr = find_first_zero_bit((unsigned long *)vgic_cpu->lr_used,
913                                vgic_cpu->nr_lr);
914         if (lr >= vgic_cpu->nr_lr)
915                 return false;
916
917         kvm_debug("LR%d allocated for IRQ%d %x\n", lr, irq, sgi_source_id);
918         vgic_cpu->vgic_lr[lr] = MK_LR_PEND(sgi_source_id, irq);
919         vgic_cpu->vgic_irq_lr_map[irq] = lr;
920         set_bit(lr, vgic_cpu->lr_used);
921
922         if (!vgic_irq_is_edge(vcpu, irq))
923                 vgic_cpu->vgic_lr[lr] |= GICH_LR_EOI;
924
925         return true;
926 }
927
928 static bool vgic_queue_sgi(struct kvm_vcpu *vcpu, int irq)
929 {
930         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
931         unsigned long sources;
932         int vcpu_id = vcpu->vcpu_id;
933         int c;
934
935         sources = dist->irq_sgi_sources[vcpu_id][irq];
936
937         for_each_set_bit(c, &sources, VGIC_MAX_CPUS) {
938                 if (vgic_queue_irq(vcpu, c, irq))
939                         clear_bit(c, &sources);
940         }
941
942         dist->irq_sgi_sources[vcpu_id][irq] = sources;
943
944         /*
945          * If the sources bitmap has been cleared it means that we
946          * could queue all the SGIs onto link registers (see the
947          * clear_bit above), and therefore we are done with them in
948          * our emulated gic and can get rid of them.
949          */
950         if (!sources) {
951                 vgic_dist_irq_clear(vcpu, irq);
952                 vgic_cpu_irq_clear(vcpu, irq);
953                 return true;
954         }
955
956         return false;
957 }
958
959 static bool vgic_queue_hwirq(struct kvm_vcpu *vcpu, int irq)
960 {
961         if (vgic_irq_is_active(vcpu, irq))
962                 return true; /* level interrupt, already queued */
963
964         if (vgic_queue_irq(vcpu, 0, irq)) {
965                 if (vgic_irq_is_edge(vcpu, irq)) {
966                         vgic_dist_irq_clear(vcpu, irq);
967                         vgic_cpu_irq_clear(vcpu, irq);
968                 } else {
969                         vgic_irq_set_active(vcpu, irq);
970                 }
971
972                 return true;
973         }
974
975         return false;
976 }
977
978 /*
979  * Fill the list registers with pending interrupts before running the
980  * guest.
981  */
982 static void __kvm_vgic_flush_hwstate(struct kvm_vcpu *vcpu)
983 {
984         struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
985         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
986         int i, vcpu_id;
987         int overflow = 0;
988
989         vcpu_id = vcpu->vcpu_id;
990
991         /*
992          * We may not have any pending interrupt, or the interrupts
993          * may have been serviced from another vcpu. In all cases,
994          * move along.
995          */
996         if (!kvm_vgic_vcpu_pending_irq(vcpu)) {
997                 pr_debug("CPU%d has no pending interrupt\n", vcpu_id);
998                 goto epilog;
999         }
1000
1001         /* SGIs */
1002         for_each_set_bit(i, vgic_cpu->pending_percpu, VGIC_NR_SGIS) {
1003                 if (!vgic_queue_sgi(vcpu, i))
1004                         overflow = 1;
1005         }
1006
1007         /* PPIs */
1008         for_each_set_bit_from(i, vgic_cpu->pending_percpu, VGIC_NR_PRIVATE_IRQS) {
1009                 if (!vgic_queue_hwirq(vcpu, i))
1010                         overflow = 1;
1011         }
1012
1013         /* SPIs */
1014         for_each_set_bit(i, vgic_cpu->pending_shared, VGIC_NR_SHARED_IRQS) {
1015                 if (!vgic_queue_hwirq(vcpu, i + VGIC_NR_PRIVATE_IRQS))
1016                         overflow = 1;
1017         }
1018
1019 epilog:
1020         if (overflow) {
1021                 vgic_cpu->vgic_hcr |= GICH_HCR_UIE;
1022         } else {
1023                 vgic_cpu->vgic_hcr &= ~GICH_HCR_UIE;
1024                 /*
1025                  * We're about to run this VCPU, and we've consumed
1026                  * everything the distributor had in store for
1027                  * us. Claim we don't have anything pending. We'll
1028                  * adjust that if needed while exiting.
1029                  */
1030                 clear_bit(vcpu_id, &dist->irq_pending_on_cpu);
1031         }
1032 }
1033
1034 static bool vgic_process_maintenance(struct kvm_vcpu *vcpu)
1035 {
1036         struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
1037         bool level_pending = false;
1038
1039         kvm_debug("MISR = %08x\n", vgic_cpu->vgic_misr);
1040
1041         if (vgic_cpu->vgic_misr & GICH_MISR_EOI) {
1042                 /*
1043                  * Some level interrupts have been EOIed. Clear their
1044                  * active bit.
1045                  */
1046                 int lr, irq;
1047
1048                 for_each_set_bit(lr, (unsigned long *)vgic_cpu->vgic_eisr,
1049                                  vgic_cpu->nr_lr) {
1050                         irq = vgic_cpu->vgic_lr[lr] & GICH_LR_VIRTUALID;
1051
1052                         vgic_irq_clear_active(vcpu, irq);
1053                         vgic_cpu->vgic_lr[lr] &= ~GICH_LR_EOI;
1054
1055                         /* Any additional pending interrupt? */
1056                         if (vgic_dist_irq_is_pending(vcpu, irq)) {
1057                                 vgic_cpu_irq_set(vcpu, irq);
1058                                 level_pending = true;
1059                         } else {
1060                                 vgic_cpu_irq_clear(vcpu, irq);
1061                         }
1062
1063                         /*
1064                          * Despite being EOIed, the LR may not have
1065                          * been marked as empty.
1066                          */
1067                         set_bit(lr, (unsigned long *)vgic_cpu->vgic_elrsr);
1068                         vgic_cpu->vgic_lr[lr] &= ~GICH_LR_ACTIVE_BIT;
1069                 }
1070         }
1071
1072         if (vgic_cpu->vgic_misr & GICH_MISR_U)
1073                 vgic_cpu->vgic_hcr &= ~GICH_HCR_UIE;
1074
1075         return level_pending;
1076 }
1077
1078 /*
1079  * Sync back the VGIC state after a guest run. The distributor lock is
1080  * needed so we don't get preempted in the middle of the state processing.
1081  */
1082 static void __kvm_vgic_sync_hwstate(struct kvm_vcpu *vcpu)
1083 {
1084         struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
1085         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
1086         int lr, pending;
1087         bool level_pending;
1088
1089         level_pending = vgic_process_maintenance(vcpu);
1090
1091         /* Clear mappings for empty LRs */
1092         for_each_set_bit(lr, (unsigned long *)vgic_cpu->vgic_elrsr,
1093                          vgic_cpu->nr_lr) {
1094                 int irq;
1095
1096                 if (!test_and_clear_bit(lr, vgic_cpu->lr_used))
1097                         continue;
1098
1099                 irq = vgic_cpu->vgic_lr[lr] & GICH_LR_VIRTUALID;
1100
1101                 BUG_ON(irq >= VGIC_NR_IRQS);
1102                 vgic_cpu->vgic_irq_lr_map[irq] = LR_EMPTY;
1103         }
1104
1105         /* Check if we still have something up our sleeve... */
1106         pending = find_first_zero_bit((unsigned long *)vgic_cpu->vgic_elrsr,
1107                                       vgic_cpu->nr_lr);
1108         if (level_pending || pending < vgic_cpu->nr_lr)
1109                 set_bit(vcpu->vcpu_id, &dist->irq_pending_on_cpu);
1110 }
1111
1112 void kvm_vgic_flush_hwstate(struct kvm_vcpu *vcpu)
1113 {
1114         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
1115
1116         if (!irqchip_in_kernel(vcpu->kvm))
1117                 return;
1118
1119         spin_lock(&dist->lock);
1120         __kvm_vgic_flush_hwstate(vcpu);
1121         spin_unlock(&dist->lock);
1122 }
1123
1124 void kvm_vgic_sync_hwstate(struct kvm_vcpu *vcpu)
1125 {
1126         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
1127
1128         if (!irqchip_in_kernel(vcpu->kvm))
1129                 return;
1130
1131         spin_lock(&dist->lock);
1132         __kvm_vgic_sync_hwstate(vcpu);
1133         spin_unlock(&dist->lock);
1134 }
1135
1136 int kvm_vgic_vcpu_pending_irq(struct kvm_vcpu *vcpu)
1137 {
1138         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
1139
1140         if (!irqchip_in_kernel(vcpu->kvm))
1141                 return 0;
1142
1143         return test_bit(vcpu->vcpu_id, &dist->irq_pending_on_cpu);
1144 }
1145
1146 static void vgic_kick_vcpus(struct kvm *kvm)
1147 {
1148         struct kvm_vcpu *vcpu;
1149         int c;
1150
1151         /*
1152          * We've injected an interrupt, time to find out who deserves
1153          * a good kick...
1154          */
1155         kvm_for_each_vcpu(c, vcpu, kvm) {
1156                 if (kvm_vgic_vcpu_pending_irq(vcpu))
1157                         kvm_vcpu_kick(vcpu);
1158         }
1159 }
1160
1161 static int vgic_validate_injection(struct kvm_vcpu *vcpu, int irq, int level)
1162 {
1163         int is_edge = vgic_irq_is_edge(vcpu, irq);
1164         int state = vgic_dist_irq_is_pending(vcpu, irq);
1165
1166         /*
1167          * Only inject an interrupt if:
1168          * - edge triggered and we have a rising edge
1169          * - level triggered and we change level
1170          */
1171         if (is_edge)
1172                 return level > state;
1173         else
1174                 return level != state;
1175 }
1176
1177 static bool vgic_update_irq_state(struct kvm *kvm, int cpuid,
1178                                   unsigned int irq_num, bool level)
1179 {
1180         struct vgic_dist *dist = &kvm->arch.vgic;
1181         struct kvm_vcpu *vcpu;
1182         int is_edge, is_level;
1183         int enabled;
1184         bool ret = true;
1185
1186         spin_lock(&dist->lock);
1187
1188         vcpu = kvm_get_vcpu(kvm, cpuid);
1189         is_edge = vgic_irq_is_edge(vcpu, irq_num);
1190         is_level = !is_edge;
1191
1192         if (!vgic_validate_injection(vcpu, irq_num, level)) {
1193                 ret = false;
1194                 goto out;
1195         }
1196
1197         if (irq_num >= VGIC_NR_PRIVATE_IRQS) {
1198                 cpuid = dist->irq_spi_cpu[irq_num - VGIC_NR_PRIVATE_IRQS];
1199                 vcpu = kvm_get_vcpu(kvm, cpuid);
1200         }
1201
1202         kvm_debug("Inject IRQ%d level %d CPU%d\n", irq_num, level, cpuid);
1203
1204         if (level)
1205                 vgic_dist_irq_set(vcpu, irq_num);
1206         else
1207                 vgic_dist_irq_clear(vcpu, irq_num);
1208
1209         enabled = vgic_irq_is_enabled(vcpu, irq_num);
1210
1211         if (!enabled) {
1212                 ret = false;
1213                 goto out;
1214         }
1215
1216         if (is_level && vgic_irq_is_active(vcpu, irq_num)) {
1217                 /*
1218                  * Level interrupt in progress, will be picked up
1219                  * when EOId.
1220                  */
1221                 ret = false;
1222                 goto out;
1223         }
1224
1225         if (level) {
1226                 vgic_cpu_irq_set(vcpu, irq_num);
1227                 set_bit(cpuid, &dist->irq_pending_on_cpu);
1228         }
1229
1230 out:
1231         spin_unlock(&dist->lock);
1232
1233         return ret;
1234 }
1235
1236 /**
1237  * kvm_vgic_inject_irq - Inject an IRQ from a device to the vgic
1238  * @kvm:     The VM structure pointer
1239  * @cpuid:   The CPU for PPIs
1240  * @irq_num: The IRQ number that is assigned to the device
1241  * @level:   Edge-triggered:  true:  to trigger the interrupt
1242  *                            false: to ignore the call
1243  *           Level-sensitive  true:  activates an interrupt
1244  *                            false: deactivates an interrupt
1245  *
1246  * The GIC is not concerned with devices being active-LOW or active-HIGH for
1247  * level-sensitive interrupts.  You can think of the level parameter as 1
1248  * being HIGH and 0 being LOW and all devices being active-HIGH.
1249  */
1250 int kvm_vgic_inject_irq(struct kvm *kvm, int cpuid, unsigned int irq_num,
1251                         bool level)
1252 {
1253         if (vgic_update_irq_state(kvm, cpuid, irq_num, level))
1254                 vgic_kick_vcpus(kvm);
1255
1256         return 0;
1257 }
1258
1259 static irqreturn_t vgic_maintenance_handler(int irq, void *data)
1260 {
1261         /*
1262          * We cannot rely on the vgic maintenance interrupt to be
1263          * delivered synchronously. This means we can only use it to
1264          * exit the VM, and we perform the handling of EOIed
1265          * interrupts on the exit path (see vgic_process_maintenance).
1266          */
1267         return IRQ_HANDLED;
1268 }
1269
1270 /**
1271  * kvm_vgic_vcpu_init - Initialize per-vcpu VGIC state
1272  * @vcpu: pointer to the vcpu struct
1273  *
1274  * Initialize the vgic_cpu struct and vgic_dist struct fields pertaining to
1275  * this vcpu and enable the VGIC for this VCPU
1276  */
1277 int kvm_vgic_vcpu_init(struct kvm_vcpu *vcpu)
1278 {
1279         struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
1280         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
1281         int i;
1282
1283         if (vcpu->vcpu_id >= VGIC_MAX_CPUS)
1284                 return -EBUSY;
1285
1286         for (i = 0; i < VGIC_NR_IRQS; i++) {
1287                 if (i < VGIC_NR_PPIS)
1288                         vgic_bitmap_set_irq_val(&dist->irq_enabled,
1289                                                 vcpu->vcpu_id, i, 1);
1290                 if (i < VGIC_NR_PRIVATE_IRQS)
1291                         vgic_bitmap_set_irq_val(&dist->irq_cfg,
1292                                                 vcpu->vcpu_id, i, VGIC_CFG_EDGE);
1293
1294                 vgic_cpu->vgic_irq_lr_map[i] = LR_EMPTY;
1295         }
1296
1297         /*
1298          * By forcing VMCR to zero, the GIC will restore the binary
1299          * points to their reset values. Anything else resets to zero
1300          * anyway.
1301          */
1302         vgic_cpu->vgic_vmcr = 0;
1303
1304         vgic_cpu->nr_lr = vgic_nr_lr;
1305         vgic_cpu->vgic_hcr = GICH_HCR_EN; /* Get the show on the road... */
1306
1307         return 0;
1308 }
1309
1310 static void vgic_init_maintenance_interrupt(void *info)
1311 {
1312         enable_percpu_irq(vgic_maint_irq, 0);
1313 }
1314
1315 static int vgic_cpu_notify(struct notifier_block *self,
1316                            unsigned long action, void *cpu)
1317 {
1318         switch (action) {
1319         case CPU_STARTING:
1320         case CPU_STARTING_FROZEN:
1321                 vgic_init_maintenance_interrupt(NULL);
1322                 break;
1323         case CPU_DYING:
1324         case CPU_DYING_FROZEN:
1325                 disable_percpu_irq(vgic_maint_irq);
1326                 break;
1327         }
1328
1329         return NOTIFY_OK;
1330 }
1331
1332 static struct notifier_block vgic_cpu_nb = {
1333         .notifier_call = vgic_cpu_notify,
1334 };
1335
1336 int kvm_vgic_hyp_init(void)
1337 {
1338         int ret;
1339         struct resource vctrl_res;
1340         struct resource vcpu_res;
1341
1342         vgic_node = of_find_compatible_node(NULL, NULL, "arm,cortex-a15-gic");
1343         if (!vgic_node) {
1344                 kvm_err("error: no compatible vgic node in DT\n");
1345                 return -ENODEV;
1346         }
1347
1348         vgic_maint_irq = irq_of_parse_and_map(vgic_node, 0);
1349         if (!vgic_maint_irq) {
1350                 kvm_err("error getting vgic maintenance irq from DT\n");
1351                 ret = -ENXIO;
1352                 goto out;
1353         }
1354
1355         ret = request_percpu_irq(vgic_maint_irq, vgic_maintenance_handler,
1356                                  "vgic", kvm_get_running_vcpus());
1357         if (ret) {
1358                 kvm_err("Cannot register interrupt %d\n", vgic_maint_irq);
1359                 goto out;
1360         }
1361
1362         ret = register_cpu_notifier(&vgic_cpu_nb);
1363         if (ret) {
1364                 kvm_err("Cannot register vgic CPU notifier\n");
1365                 goto out_free_irq;
1366         }
1367
1368         ret = of_address_to_resource(vgic_node, 2, &vctrl_res);
1369         if (ret) {
1370                 kvm_err("Cannot obtain VCTRL resource\n");
1371                 goto out_free_irq;
1372         }
1373
1374         vgic_vctrl_base = of_iomap(vgic_node, 2);
1375         if (!vgic_vctrl_base) {
1376                 kvm_err("Cannot ioremap VCTRL\n");
1377                 ret = -ENOMEM;
1378                 goto out_free_irq;
1379         }
1380
1381         vgic_nr_lr = readl_relaxed(vgic_vctrl_base + GICH_VTR);
1382         vgic_nr_lr = (vgic_nr_lr & 0x3f) + 1;
1383
1384         ret = create_hyp_io_mappings(vgic_vctrl_base,
1385                                      vgic_vctrl_base + resource_size(&vctrl_res),
1386                                      vctrl_res.start);
1387         if (ret) {
1388                 kvm_err("Cannot map VCTRL into hyp\n");
1389                 goto out_unmap;
1390         }
1391
1392         kvm_info("%s@%llx IRQ%d\n", vgic_node->name,
1393                  vctrl_res.start, vgic_maint_irq);
1394         on_each_cpu(vgic_init_maintenance_interrupt, NULL, 1);
1395
1396         if (of_address_to_resource(vgic_node, 3, &vcpu_res)) {
1397                 kvm_err("Cannot obtain VCPU resource\n");
1398                 ret = -ENXIO;
1399                 goto out_unmap;
1400         }
1401         vgic_vcpu_base = vcpu_res.start;
1402
1403         goto out;
1404
1405 out_unmap:
1406         iounmap(vgic_vctrl_base);
1407 out_free_irq:
1408         free_percpu_irq(vgic_maint_irq, kvm_get_running_vcpus());
1409 out:
1410         of_node_put(vgic_node);
1411         return ret;
1412 }
1413
1414 /**
1415  * kvm_vgic_init - Initialize global VGIC state before running any VCPUs
1416  * @kvm: pointer to the kvm struct
1417  *
1418  * Map the virtual CPU interface into the VM before running any VCPUs.  We
1419  * can't do this at creation time, because user space must first set the
1420  * virtual CPU interface address in the guest physical address space.  Also
1421  * initialize the ITARGETSRn regs to 0 on the emulated distributor.
1422  */
1423 int kvm_vgic_init(struct kvm *kvm)
1424 {
1425         int ret = 0, i;
1426
1427         if (!irqchip_in_kernel(kvm))
1428                 return 0;
1429
1430         mutex_lock(&kvm->lock);
1431
1432         if (vgic_initialized(kvm))
1433                 goto out;
1434
1435         if (IS_VGIC_ADDR_UNDEF(kvm->arch.vgic.vgic_dist_base) ||
1436             IS_VGIC_ADDR_UNDEF(kvm->arch.vgic.vgic_cpu_base)) {
1437                 kvm_err("Need to set vgic cpu and dist addresses first\n");
1438                 ret = -ENXIO;
1439                 goto out;
1440         }
1441
1442         ret = kvm_phys_addr_ioremap(kvm, kvm->arch.vgic.vgic_cpu_base,
1443                                     vgic_vcpu_base, KVM_VGIC_V2_CPU_SIZE);
1444         if (ret) {
1445                 kvm_err("Unable to remap VGIC CPU to VCPU\n");
1446                 goto out;
1447         }
1448
1449         for (i = VGIC_NR_PRIVATE_IRQS; i < VGIC_NR_IRQS; i += 4)
1450                 vgic_set_target_reg(kvm, 0, i);
1451
1452         kvm->arch.vgic.ready = true;
1453 out:
1454         mutex_unlock(&kvm->lock);
1455         return ret;
1456 }
1457
1458 int kvm_vgic_create(struct kvm *kvm)
1459 {
1460         int i, vcpu_lock_idx = -1, ret = 0;
1461         struct kvm_vcpu *vcpu;
1462
1463         mutex_lock(&kvm->lock);
1464
1465         if (kvm->arch.vgic.vctrl_base) {
1466                 ret = -EEXIST;
1467                 goto out;
1468         }
1469
1470         /*
1471          * Any time a vcpu is run, vcpu_load is called which tries to grab the
1472          * vcpu->mutex.  By grabbing the vcpu->mutex of all VCPUs we ensure
1473          * that no other VCPUs are run while we create the vgic.
1474          */
1475         kvm_for_each_vcpu(i, vcpu, kvm) {
1476                 if (!mutex_trylock(&vcpu->mutex))
1477                         goto out_unlock;
1478                 vcpu_lock_idx = i;
1479         }
1480
1481         kvm_for_each_vcpu(i, vcpu, kvm) {
1482                 if (vcpu->arch.has_run_once) {
1483                         ret = -EBUSY;
1484                         goto out_unlock;
1485                 }
1486         }
1487
1488         spin_lock_init(&kvm->arch.vgic.lock);
1489         kvm->arch.vgic.vctrl_base = vgic_vctrl_base;
1490         kvm->arch.vgic.vgic_dist_base = VGIC_ADDR_UNDEF;
1491         kvm->arch.vgic.vgic_cpu_base = VGIC_ADDR_UNDEF;
1492
1493 out_unlock:
1494         for (; vcpu_lock_idx >= 0; vcpu_lock_idx--) {
1495                 vcpu = kvm_get_vcpu(kvm, vcpu_lock_idx);
1496                 mutex_unlock(&vcpu->mutex);
1497         }
1498
1499 out:
1500         mutex_unlock(&kvm->lock);
1501         return ret;
1502 }
1503
1504 static bool vgic_ioaddr_overlap(struct kvm *kvm)
1505 {
1506         phys_addr_t dist = kvm->arch.vgic.vgic_dist_base;
1507         phys_addr_t cpu = kvm->arch.vgic.vgic_cpu_base;
1508
1509         if (IS_VGIC_ADDR_UNDEF(dist) || IS_VGIC_ADDR_UNDEF(cpu))
1510                 return 0;
1511         if ((dist <= cpu && dist + KVM_VGIC_V2_DIST_SIZE > cpu) ||
1512             (cpu <= dist && cpu + KVM_VGIC_V2_CPU_SIZE > dist))
1513                 return -EBUSY;
1514         return 0;
1515 }
1516
1517 static int vgic_ioaddr_assign(struct kvm *kvm, phys_addr_t *ioaddr,
1518                               phys_addr_t addr, phys_addr_t size)
1519 {
1520         int ret;
1521
1522         if (addr & ~KVM_PHYS_MASK)
1523                 return -E2BIG;
1524
1525         if (addr & (SZ_4K - 1))
1526                 return -EINVAL;
1527
1528         if (!IS_VGIC_ADDR_UNDEF(*ioaddr))
1529                 return -EEXIST;
1530         if (addr + size < addr)
1531                 return -EINVAL;
1532
1533         ret = vgic_ioaddr_overlap(kvm);
1534         if (ret)
1535                 return ret;
1536         *ioaddr = addr;
1537         return ret;
1538 }
1539
1540 /**
1541  * kvm_vgic_addr - set or get vgic VM base addresses
1542  * @kvm:   pointer to the vm struct
1543  * @type:  the VGIC addr type, one of KVM_VGIC_V2_ADDR_TYPE_XXX
1544  * @addr:  pointer to address value
1545  * @write: if true set the address in the VM address space, if false read the
1546  *          address
1547  *
1548  * Set or get the vgic base addresses for the distributor and the virtual CPU
1549  * interface in the VM physical address space.  These addresses are properties
1550  * of the emulated core/SoC and therefore user space initially knows this
1551  * information.
1552  */
1553 int kvm_vgic_addr(struct kvm *kvm, unsigned long type, u64 *addr, bool write)
1554 {
1555         int r = 0;
1556         struct vgic_dist *vgic = &kvm->arch.vgic;
1557
1558         mutex_lock(&kvm->lock);
1559         switch (type) {
1560         case KVM_VGIC_V2_ADDR_TYPE_DIST:
1561                 if (write) {
1562                         r = vgic_ioaddr_assign(kvm, &vgic->vgic_dist_base,
1563                                                *addr, KVM_VGIC_V2_DIST_SIZE);
1564                 } else {
1565                         *addr = vgic->vgic_dist_base;
1566                 }
1567                 break;
1568         case KVM_VGIC_V2_ADDR_TYPE_CPU:
1569                 if (write) {
1570                         r = vgic_ioaddr_assign(kvm, &vgic->vgic_cpu_base,
1571                                                *addr, KVM_VGIC_V2_CPU_SIZE);
1572                 } else {
1573                         *addr = vgic->vgic_cpu_base;
1574                 }
1575                 break;
1576         default:
1577                 r = -ENODEV;
1578         }
1579
1580         mutex_unlock(&kvm->lock);
1581         return r;
1582 }
1583
1584 static bool handle_cpu_mmio_misc(struct kvm_vcpu *vcpu,
1585                                  struct kvm_exit_mmio *mmio, phys_addr_t offset)
1586 {
1587         return true;
1588 }
1589
1590 static const struct mmio_range vgic_cpu_ranges[] = {
1591         {
1592                 .base           = GIC_CPU_CTRL,
1593                 .len            = 12,
1594                 .handle_mmio    = handle_cpu_mmio_misc,
1595         },
1596         {
1597                 .base           = GIC_CPU_ALIAS_BINPOINT,
1598                 .len            = 4,
1599                 .handle_mmio    = handle_cpu_mmio_misc,
1600         },
1601         {
1602                 .base           = GIC_CPU_ACTIVEPRIO,
1603                 .len            = 16,
1604                 .handle_mmio    = handle_cpu_mmio_misc,
1605         },
1606         {
1607                 .base           = GIC_CPU_IDENT,
1608                 .len            = 4,
1609                 .handle_mmio    = handle_cpu_mmio_misc,
1610         },
1611 };
1612
1613 static int vgic_attr_regs_access(struct kvm_device *dev,
1614                                  struct kvm_device_attr *attr,
1615                                  u32 *reg, bool is_write)
1616 {
1617         const struct mmio_range *r = NULL, *ranges;
1618         phys_addr_t offset;
1619         int ret, cpuid, c;
1620         struct kvm_vcpu *vcpu, *tmp_vcpu;
1621         struct vgic_dist *vgic;
1622         struct kvm_exit_mmio mmio;
1623
1624         offset = attr->attr & KVM_DEV_ARM_VGIC_OFFSET_MASK;
1625         cpuid = (attr->attr & KVM_DEV_ARM_VGIC_CPUID_MASK) >>
1626                 KVM_DEV_ARM_VGIC_CPUID_SHIFT;
1627
1628         mutex_lock(&dev->kvm->lock);
1629
1630         if (cpuid >= atomic_read(&dev->kvm->online_vcpus)) {
1631                 ret = -EINVAL;
1632                 goto out;
1633         }
1634
1635         vcpu = kvm_get_vcpu(dev->kvm, cpuid);
1636         vgic = &dev->kvm->arch.vgic;
1637
1638         mmio.len = 4;
1639         mmio.is_write = is_write;
1640         if (is_write)
1641                 mmio_data_write(&mmio, ~0, *reg);
1642         switch (attr->group) {
1643         case KVM_DEV_ARM_VGIC_GRP_DIST_REGS:
1644                 mmio.phys_addr = vgic->vgic_dist_base + offset;
1645                 ranges = vgic_dist_ranges;
1646                 break;
1647         case KVM_DEV_ARM_VGIC_GRP_CPU_REGS:
1648                 mmio.phys_addr = vgic->vgic_cpu_base + offset;
1649                 ranges = vgic_cpu_ranges;
1650                 break;
1651         default:
1652                 BUG();
1653         }
1654         r = find_matching_range(ranges, &mmio, offset);
1655
1656         if (unlikely(!r || !r->handle_mmio)) {
1657                 ret = -ENXIO;
1658                 goto out;
1659         }
1660
1661
1662         spin_lock(&vgic->lock);
1663
1664         /*
1665          * Ensure that no other VCPU is running by checking the vcpu->cpu
1666          * field.  If no other VPCUs are running we can safely access the VGIC
1667          * state, because even if another VPU is run after this point, that
1668          * VCPU will not touch the vgic state, because it will block on
1669          * getting the vgic->lock in kvm_vgic_sync_hwstate().
1670          */
1671         kvm_for_each_vcpu(c, tmp_vcpu, dev->kvm) {
1672                 if (unlikely(tmp_vcpu->cpu != -1)) {
1673                         ret = -EBUSY;
1674                         goto out_vgic_unlock;
1675                 }
1676         }
1677
1678         offset -= r->base;
1679         r->handle_mmio(vcpu, &mmio, offset);
1680
1681         if (!is_write)
1682                 *reg = mmio_data_read(&mmio, ~0);
1683
1684         ret = 0;
1685 out_vgic_unlock:
1686         spin_unlock(&vgic->lock);
1687 out:
1688         mutex_unlock(&dev->kvm->lock);
1689         return ret;
1690 }
1691
1692 static int vgic_set_attr(struct kvm_device *dev, struct kvm_device_attr *attr)
1693 {
1694         int r;
1695
1696         switch (attr->group) {
1697         case KVM_DEV_ARM_VGIC_GRP_ADDR: {
1698                 u64 __user *uaddr = (u64 __user *)(long)attr->addr;
1699                 u64 addr;
1700                 unsigned long type = (unsigned long)attr->attr;
1701
1702                 if (copy_from_user(&addr, uaddr, sizeof(addr)))
1703                         return -EFAULT;
1704
1705                 r = kvm_vgic_addr(dev->kvm, type, &addr, true);
1706                 return (r == -ENODEV) ? -ENXIO : r;
1707         }
1708
1709         case KVM_DEV_ARM_VGIC_GRP_DIST_REGS:
1710         case KVM_DEV_ARM_VGIC_GRP_CPU_REGS: {
1711                 u32 __user *uaddr = (u32 __user *)(long)attr->addr;
1712                 u32 reg;
1713
1714                 if (get_user(reg, uaddr))
1715                         return -EFAULT;
1716
1717                 return vgic_attr_regs_access(dev, attr, &reg, true);
1718         }
1719
1720         }
1721
1722         return -ENXIO;
1723 }
1724
1725 static int vgic_get_attr(struct kvm_device *dev, struct kvm_device_attr *attr)
1726 {
1727         int r = -ENXIO;
1728
1729         switch (attr->group) {
1730         case KVM_DEV_ARM_VGIC_GRP_ADDR: {
1731                 u64 __user *uaddr = (u64 __user *)(long)attr->addr;
1732                 u64 addr;
1733                 unsigned long type = (unsigned long)attr->attr;
1734
1735                 r = kvm_vgic_addr(dev->kvm, type, &addr, false);
1736                 if (r)
1737                         return (r == -ENODEV) ? -ENXIO : r;
1738
1739                 if (copy_to_user(uaddr, &addr, sizeof(addr)))
1740                         return -EFAULT;
1741                 break;
1742         }
1743
1744         case KVM_DEV_ARM_VGIC_GRP_DIST_REGS:
1745         case KVM_DEV_ARM_VGIC_GRP_CPU_REGS: {
1746                 u32 __user *uaddr = (u32 __user *)(long)attr->addr;
1747                 u32 reg = 0;
1748
1749                 r = vgic_attr_regs_access(dev, attr, &reg, false);
1750                 if (r)
1751                         return r;
1752                 r = put_user(reg, uaddr);
1753                 break;
1754         }
1755
1756         }
1757
1758         return r;
1759 }
1760
1761 static int vgic_has_attr_regs(const struct mmio_range *ranges,
1762                               phys_addr_t offset)
1763 {
1764         struct kvm_exit_mmio dev_attr_mmio;
1765
1766         dev_attr_mmio.len = 4;
1767         if (find_matching_range(ranges, &dev_attr_mmio, offset))
1768                 return 0;
1769         else
1770                 return -ENXIO;
1771 }
1772
1773 static int vgic_has_attr(struct kvm_device *dev, struct kvm_device_attr *attr)
1774 {
1775         phys_addr_t offset;
1776
1777         switch (attr->group) {
1778         case KVM_DEV_ARM_VGIC_GRP_ADDR:
1779                 switch (attr->attr) {
1780                 case KVM_VGIC_V2_ADDR_TYPE_DIST:
1781                 case KVM_VGIC_V2_ADDR_TYPE_CPU:
1782                         return 0;
1783                 }
1784                 break;
1785         case KVM_DEV_ARM_VGIC_GRP_DIST_REGS:
1786                 offset = attr->attr & KVM_DEV_ARM_VGIC_OFFSET_MASK;
1787                 return vgic_has_attr_regs(vgic_dist_ranges, offset);
1788         case KVM_DEV_ARM_VGIC_GRP_CPU_REGS:
1789                 offset = attr->attr & KVM_DEV_ARM_VGIC_OFFSET_MASK;
1790                 return vgic_has_attr_regs(vgic_cpu_ranges, offset);
1791         }
1792         return -ENXIO;
1793 }
1794
1795 static void vgic_destroy(struct kvm_device *dev)
1796 {
1797         kfree(dev);
1798 }
1799
1800 static int vgic_create(struct kvm_device *dev, u32 type)
1801 {
1802         return kvm_vgic_create(dev->kvm);
1803 }
1804
1805 struct kvm_device_ops kvm_arm_vgic_v2_ops = {
1806         .name = "kvm-arm-vgic",
1807         .create = vgic_create,
1808         .destroy = vgic_destroy,
1809         .set_attr = vgic_set_attr,
1810         .get_attr = vgic_get_attr,
1811         .has_attr = vgic_has_attr,
1812 };