60668a7f319a8adbeaff9f3ea1518ec9847fa6c1
[cascardo/linux.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/irq.h>
25 #include <linux/rculist.h>
26 #include <linux/uaccess.h>
27
28 #include <asm/kvm_emulate.h>
29 #include <asm/kvm_arm.h>
30 #include <asm/kvm_mmu.h>
31 #include <trace/events/kvm.h>
32 #include <asm/kvm.h>
33 #include <kvm/iodev.h>
34 #include <linux/irqchip/arm-gic-common.h>
35
36 #define CREATE_TRACE_POINTS
37 #include "trace.h"
38
39 /*
40  * How the whole thing works (courtesy of Christoffer Dall):
41  *
42  * - At any time, the dist->irq_pending_on_cpu is the oracle that knows if
43  *   something is pending on the CPU interface.
44  * - Interrupts that are pending on the distributor are stored on the
45  *   vgic.irq_pending vgic bitmap (this bitmap is updated by both user land
46  *   ioctls and guest mmio ops, and other in-kernel peripherals such as the
47  *   arch. timers).
48  * - Every time the bitmap changes, the irq_pending_on_cpu oracle is
49  *   recalculated
50  * - To calculate the oracle, we need info for each cpu from
51  *   compute_pending_for_cpu, which considers:
52  *   - PPI: dist->irq_pending & dist->irq_enable
53  *   - SPI: dist->irq_pending & dist->irq_enable & dist->irq_spi_target
54  *   - irq_spi_target is a 'formatted' version of the GICD_ITARGETSRn
55  *     registers, stored on each vcpu. We only keep one bit of
56  *     information per interrupt, making sure that only one vcpu can
57  *     accept the interrupt.
58  * - If any of the above state changes, we must recalculate the oracle.
59  * - The same is true when injecting an interrupt, except that we only
60  *   consider a single interrupt at a time. The irq_spi_cpu array
61  *   contains the target CPU for each SPI.
62  *
63  * The handling of level interrupts adds some extra complexity. We
64  * need to track when the interrupt has been EOIed, so we can sample
65  * the 'line' again. This is achieved as such:
66  *
67  * - When a level interrupt is moved onto a vcpu, the corresponding
68  *   bit in irq_queued is set. As long as this bit is set, the line
69  *   will be ignored for further interrupts. The interrupt is injected
70  *   into the vcpu with the GICH_LR_EOI bit set (generate a
71  *   maintenance interrupt on EOI).
72  * - When the interrupt is EOIed, the maintenance interrupt fires,
73  *   and clears the corresponding bit in irq_queued. This allows the
74  *   interrupt line to be sampled again.
75  * - Note that level-triggered interrupts can also be set to pending from
76  *   writes to GICD_ISPENDRn and lowering the external input line does not
77  *   cause the interrupt to become inactive in such a situation.
78  *   Conversely, writes to GICD_ICPENDRn do not cause the interrupt to become
79  *   inactive as long as the external input line is held high.
80  *
81  *
82  * Initialization rules: there are multiple stages to the vgic
83  * initialization, both for the distributor and the CPU interfaces.
84  *
85  * Distributor:
86  *
87  * - kvm_vgic_early_init(): initialization of static data that doesn't
88  *   depend on any sizing information or emulation type. No allocation
89  *   is allowed there.
90  *
91  * - vgic_init(): allocation and initialization of the generic data
92  *   structures that depend on sizing information (number of CPUs,
93  *   number of interrupts). Also initializes the vcpu specific data
94  *   structures. Can be executed lazily for GICv2.
95  *   [to be renamed to kvm_vgic_init??]
96  *
97  * CPU Interface:
98  *
99  * - kvm_vgic_cpu_early_init(): initialization of static data that
100  *   doesn't depend on any sizing information or emulation type. No
101  *   allocation is allowed there.
102  */
103
104 #include "vgic.h"
105
106 static void vgic_retire_disabled_irqs(struct kvm_vcpu *vcpu);
107 static void vgic_retire_lr(int lr_nr, struct kvm_vcpu *vcpu);
108 static struct vgic_lr vgic_get_lr(const struct kvm_vcpu *vcpu, int lr);
109 static void vgic_set_lr(struct kvm_vcpu *vcpu, int lr, struct vgic_lr lr_desc);
110 static u64 vgic_get_elrsr(struct kvm_vcpu *vcpu);
111 static struct irq_phys_map *vgic_irq_map_search(struct kvm_vcpu *vcpu,
112                                                 int virt_irq);
113 static int compute_pending_for_cpu(struct kvm_vcpu *vcpu);
114
115 static const struct vgic_ops *vgic_ops;
116 static const struct vgic_params *vgic;
117
118 static void add_sgi_source(struct kvm_vcpu *vcpu, int irq, int source)
119 {
120         vcpu->kvm->arch.vgic.vm_ops.add_sgi_source(vcpu, irq, source);
121 }
122
123 static bool queue_sgi(struct kvm_vcpu *vcpu, int irq)
124 {
125         return vcpu->kvm->arch.vgic.vm_ops.queue_sgi(vcpu, irq);
126 }
127
128 int kvm_vgic_map_resources(struct kvm *kvm)
129 {
130         return kvm->arch.vgic.vm_ops.map_resources(kvm, vgic);
131 }
132
133 /*
134  * struct vgic_bitmap contains a bitmap made of unsigned longs, but
135  * extracts u32s out of them.
136  *
137  * This does not work on 64-bit BE systems, because the bitmap access
138  * will store two consecutive 32-bit words with the higher-addressed
139  * register's bits at the lower index and the lower-addressed register's
140  * bits at the higher index.
141  *
142  * Therefore, swizzle the register index when accessing the 32-bit word
143  * registers to access the right register's value.
144  */
145 #if defined(CONFIG_CPU_BIG_ENDIAN) && BITS_PER_LONG == 64
146 #define REG_OFFSET_SWIZZLE      1
147 #else
148 #define REG_OFFSET_SWIZZLE      0
149 #endif
150
151 static int vgic_init_bitmap(struct vgic_bitmap *b, int nr_cpus, int nr_irqs)
152 {
153         int nr_longs;
154
155         nr_longs = nr_cpus + BITS_TO_LONGS(nr_irqs - VGIC_NR_PRIVATE_IRQS);
156
157         b->private = kzalloc(sizeof(unsigned long) * nr_longs, GFP_KERNEL);
158         if (!b->private)
159                 return -ENOMEM;
160
161         b->shared = b->private + nr_cpus;
162
163         return 0;
164 }
165
166 static void vgic_free_bitmap(struct vgic_bitmap *b)
167 {
168         kfree(b->private);
169         b->private = NULL;
170         b->shared = NULL;
171 }
172
173 /*
174  * Call this function to convert a u64 value to an unsigned long * bitmask
175  * in a way that works on both 32-bit and 64-bit LE and BE platforms.
176  *
177  * Warning: Calling this function may modify *val.
178  */
179 static unsigned long *u64_to_bitmask(u64 *val)
180 {
181 #if defined(CONFIG_CPU_BIG_ENDIAN) && BITS_PER_LONG == 32
182         *val = (*val >> 32) | (*val << 32);
183 #endif
184         return (unsigned long *)val;
185 }
186
187 u32 *vgic_bitmap_get_reg(struct vgic_bitmap *x, int cpuid, u32 offset)
188 {
189         offset >>= 2;
190         if (!offset)
191                 return (u32 *)(x->private + cpuid) + REG_OFFSET_SWIZZLE;
192         else
193                 return (u32 *)(x->shared) + ((offset - 1) ^ REG_OFFSET_SWIZZLE);
194 }
195
196 static int vgic_bitmap_get_irq_val(struct vgic_bitmap *x,
197                                    int cpuid, int irq)
198 {
199         if (irq < VGIC_NR_PRIVATE_IRQS)
200                 return test_bit(irq, x->private + cpuid);
201
202         return test_bit(irq - VGIC_NR_PRIVATE_IRQS, x->shared);
203 }
204
205 void vgic_bitmap_set_irq_val(struct vgic_bitmap *x, int cpuid,
206                              int irq, int val)
207 {
208         unsigned long *reg;
209
210         if (irq < VGIC_NR_PRIVATE_IRQS) {
211                 reg = x->private + cpuid;
212         } else {
213                 reg = x->shared;
214                 irq -= VGIC_NR_PRIVATE_IRQS;
215         }
216
217         if (val)
218                 set_bit(irq, reg);
219         else
220                 clear_bit(irq, reg);
221 }
222
223 static unsigned long *vgic_bitmap_get_cpu_map(struct vgic_bitmap *x, int cpuid)
224 {
225         return x->private + cpuid;
226 }
227
228 unsigned long *vgic_bitmap_get_shared_map(struct vgic_bitmap *x)
229 {
230         return x->shared;
231 }
232
233 static int vgic_init_bytemap(struct vgic_bytemap *x, int nr_cpus, int nr_irqs)
234 {
235         int size;
236
237         size  = nr_cpus * VGIC_NR_PRIVATE_IRQS;
238         size += nr_irqs - VGIC_NR_PRIVATE_IRQS;
239
240         x->private = kzalloc(size, GFP_KERNEL);
241         if (!x->private)
242                 return -ENOMEM;
243
244         x->shared = x->private + nr_cpus * VGIC_NR_PRIVATE_IRQS / sizeof(u32);
245         return 0;
246 }
247
248 static void vgic_free_bytemap(struct vgic_bytemap *b)
249 {
250         kfree(b->private);
251         b->private = NULL;
252         b->shared = NULL;
253 }
254
255 u32 *vgic_bytemap_get_reg(struct vgic_bytemap *x, int cpuid, u32 offset)
256 {
257         u32 *reg;
258
259         if (offset < VGIC_NR_PRIVATE_IRQS) {
260                 reg = x->private;
261                 offset += cpuid * VGIC_NR_PRIVATE_IRQS;
262         } else {
263                 reg = x->shared;
264                 offset -= VGIC_NR_PRIVATE_IRQS;
265         }
266
267         return reg + (offset / sizeof(u32));
268 }
269
270 #define VGIC_CFG_LEVEL  0
271 #define VGIC_CFG_EDGE   1
272
273 static bool vgic_irq_is_edge(struct kvm_vcpu *vcpu, int irq)
274 {
275         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
276         int irq_val;
277
278         irq_val = vgic_bitmap_get_irq_val(&dist->irq_cfg, vcpu->vcpu_id, irq);
279         return irq_val == VGIC_CFG_EDGE;
280 }
281
282 static int vgic_irq_is_enabled(struct kvm_vcpu *vcpu, int irq)
283 {
284         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
285
286         return vgic_bitmap_get_irq_val(&dist->irq_enabled, vcpu->vcpu_id, irq);
287 }
288
289 static int vgic_irq_is_queued(struct kvm_vcpu *vcpu, int irq)
290 {
291         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
292
293         return vgic_bitmap_get_irq_val(&dist->irq_queued, vcpu->vcpu_id, irq);
294 }
295
296 static int vgic_irq_is_active(struct kvm_vcpu *vcpu, int irq)
297 {
298         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
299
300         return vgic_bitmap_get_irq_val(&dist->irq_active, vcpu->vcpu_id, irq);
301 }
302
303 static void vgic_irq_set_queued(struct kvm_vcpu *vcpu, int irq)
304 {
305         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
306
307         vgic_bitmap_set_irq_val(&dist->irq_queued, vcpu->vcpu_id, irq, 1);
308 }
309
310 static void vgic_irq_clear_queued(struct kvm_vcpu *vcpu, int irq)
311 {
312         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
313
314         vgic_bitmap_set_irq_val(&dist->irq_queued, vcpu->vcpu_id, irq, 0);
315 }
316
317 static void vgic_irq_set_active(struct kvm_vcpu *vcpu, int irq)
318 {
319         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
320
321         vgic_bitmap_set_irq_val(&dist->irq_active, vcpu->vcpu_id, irq, 1);
322 }
323
324 static void vgic_irq_clear_active(struct kvm_vcpu *vcpu, int irq)
325 {
326         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
327
328         vgic_bitmap_set_irq_val(&dist->irq_active, vcpu->vcpu_id, irq, 0);
329 }
330
331 static int vgic_dist_irq_get_level(struct kvm_vcpu *vcpu, int irq)
332 {
333         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
334
335         return vgic_bitmap_get_irq_val(&dist->irq_level, vcpu->vcpu_id, irq);
336 }
337
338 static void vgic_dist_irq_set_level(struct kvm_vcpu *vcpu, int irq)
339 {
340         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
341
342         vgic_bitmap_set_irq_val(&dist->irq_level, vcpu->vcpu_id, irq, 1);
343 }
344
345 static void vgic_dist_irq_clear_level(struct kvm_vcpu *vcpu, int irq)
346 {
347         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
348
349         vgic_bitmap_set_irq_val(&dist->irq_level, vcpu->vcpu_id, irq, 0);
350 }
351
352 static int vgic_dist_irq_soft_pend(struct kvm_vcpu *vcpu, int irq)
353 {
354         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
355
356         return vgic_bitmap_get_irq_val(&dist->irq_soft_pend, vcpu->vcpu_id, irq);
357 }
358
359 static void vgic_dist_irq_clear_soft_pend(struct kvm_vcpu *vcpu, int irq)
360 {
361         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
362
363         vgic_bitmap_set_irq_val(&dist->irq_soft_pend, vcpu->vcpu_id, irq, 0);
364         if (!vgic_dist_irq_get_level(vcpu, irq)) {
365                 vgic_dist_irq_clear_pending(vcpu, irq);
366                 if (!compute_pending_for_cpu(vcpu))
367                         clear_bit(vcpu->vcpu_id, dist->irq_pending_on_cpu);
368         }
369 }
370
371 static int vgic_dist_irq_is_pending(struct kvm_vcpu *vcpu, int irq)
372 {
373         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
374
375         return vgic_bitmap_get_irq_val(&dist->irq_pending, vcpu->vcpu_id, irq);
376 }
377
378 void vgic_dist_irq_set_pending(struct kvm_vcpu *vcpu, int irq)
379 {
380         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
381
382         vgic_bitmap_set_irq_val(&dist->irq_pending, vcpu->vcpu_id, irq, 1);
383 }
384
385 void vgic_dist_irq_clear_pending(struct kvm_vcpu *vcpu, int irq)
386 {
387         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
388
389         vgic_bitmap_set_irq_val(&dist->irq_pending, vcpu->vcpu_id, irq, 0);
390 }
391
392 static void vgic_cpu_irq_set(struct kvm_vcpu *vcpu, int irq)
393 {
394         if (irq < VGIC_NR_PRIVATE_IRQS)
395                 set_bit(irq, vcpu->arch.vgic_cpu.pending_percpu);
396         else
397                 set_bit(irq - VGIC_NR_PRIVATE_IRQS,
398                         vcpu->arch.vgic_cpu.pending_shared);
399 }
400
401 void vgic_cpu_irq_clear(struct kvm_vcpu *vcpu, int irq)
402 {
403         if (irq < VGIC_NR_PRIVATE_IRQS)
404                 clear_bit(irq, vcpu->arch.vgic_cpu.pending_percpu);
405         else
406                 clear_bit(irq - VGIC_NR_PRIVATE_IRQS,
407                           vcpu->arch.vgic_cpu.pending_shared);
408 }
409
410 static bool vgic_can_sample_irq(struct kvm_vcpu *vcpu, int irq)
411 {
412         return !vgic_irq_is_queued(vcpu, irq);
413 }
414
415 /**
416  * vgic_reg_access - access vgic register
417  * @mmio:   pointer to the data describing the mmio access
418  * @reg:    pointer to the virtual backing of vgic distributor data
419  * @offset: least significant 2 bits used for word offset
420  * @mode:   ACCESS_ mode (see defines above)
421  *
422  * Helper to make vgic register access easier using one of the access
423  * modes defined for vgic register access
424  * (read,raz,write-ignored,setbit,clearbit,write)
425  */
426 void vgic_reg_access(struct kvm_exit_mmio *mmio, u32 *reg,
427                      phys_addr_t offset, int mode)
428 {
429         int word_offset = (offset & 3) * 8;
430         u32 mask = (1UL << (mmio->len * 8)) - 1;
431         u32 regval;
432
433         /*
434          * Any alignment fault should have been delivered to the guest
435          * directly (ARM ARM B3.12.7 "Prioritization of aborts").
436          */
437
438         if (reg) {
439                 regval = *reg;
440         } else {
441                 BUG_ON(mode != (ACCESS_READ_RAZ | ACCESS_WRITE_IGNORED));
442                 regval = 0;
443         }
444
445         if (mmio->is_write) {
446                 u32 data = mmio_data_read(mmio, mask) << word_offset;
447                 switch (ACCESS_WRITE_MASK(mode)) {
448                 case ACCESS_WRITE_IGNORED:
449                         return;
450
451                 case ACCESS_WRITE_SETBIT:
452                         regval |= data;
453                         break;
454
455                 case ACCESS_WRITE_CLEARBIT:
456                         regval &= ~data;
457                         break;
458
459                 case ACCESS_WRITE_VALUE:
460                         regval = (regval & ~(mask << word_offset)) | data;
461                         break;
462                 }
463                 *reg = regval;
464         } else {
465                 switch (ACCESS_READ_MASK(mode)) {
466                 case ACCESS_READ_RAZ:
467                         regval = 0;
468                         /* fall through */
469
470                 case ACCESS_READ_VALUE:
471                         mmio_data_write(mmio, mask, regval >> word_offset);
472                 }
473         }
474 }
475
476 bool handle_mmio_raz_wi(struct kvm_vcpu *vcpu, struct kvm_exit_mmio *mmio,
477                         phys_addr_t offset)
478 {
479         vgic_reg_access(mmio, NULL, offset,
480                         ACCESS_READ_RAZ | ACCESS_WRITE_IGNORED);
481         return false;
482 }
483
484 bool vgic_handle_enable_reg(struct kvm *kvm, struct kvm_exit_mmio *mmio,
485                             phys_addr_t offset, int vcpu_id, int access)
486 {
487         u32 *reg;
488         int mode = ACCESS_READ_VALUE | access;
489         struct kvm_vcpu *target_vcpu = kvm_get_vcpu(kvm, vcpu_id);
490
491         reg = vgic_bitmap_get_reg(&kvm->arch.vgic.irq_enabled, vcpu_id, offset);
492         vgic_reg_access(mmio, reg, offset, mode);
493         if (mmio->is_write) {
494                 if (access & ACCESS_WRITE_CLEARBIT) {
495                         if (offset < 4) /* Force SGI enabled */
496                                 *reg |= 0xffff;
497                         vgic_retire_disabled_irqs(target_vcpu);
498                 }
499                 vgic_update_state(kvm);
500                 return true;
501         }
502
503         return false;
504 }
505
506 bool vgic_handle_set_pending_reg(struct kvm *kvm,
507                                  struct kvm_exit_mmio *mmio,
508                                  phys_addr_t offset, int vcpu_id)
509 {
510         u32 *reg, orig;
511         u32 level_mask;
512         int mode = ACCESS_READ_VALUE | ACCESS_WRITE_SETBIT;
513         struct vgic_dist *dist = &kvm->arch.vgic;
514
515         reg = vgic_bitmap_get_reg(&dist->irq_cfg, vcpu_id, offset);
516         level_mask = (~(*reg));
517
518         /* Mark both level and edge triggered irqs as pending */
519         reg = vgic_bitmap_get_reg(&dist->irq_pending, vcpu_id, offset);
520         orig = *reg;
521         vgic_reg_access(mmio, reg, offset, mode);
522
523         if (mmio->is_write) {
524                 /* Set the soft-pending flag only for level-triggered irqs */
525                 reg = vgic_bitmap_get_reg(&dist->irq_soft_pend,
526                                           vcpu_id, offset);
527                 vgic_reg_access(mmio, reg, offset, mode);
528                 *reg &= level_mask;
529
530                 /* Ignore writes to SGIs */
531                 if (offset < 2) {
532                         *reg &= ~0xffff;
533                         *reg |= orig & 0xffff;
534                 }
535
536                 vgic_update_state(kvm);
537                 return true;
538         }
539
540         return false;
541 }
542
543 bool vgic_handle_clear_pending_reg(struct kvm *kvm,
544                                    struct kvm_exit_mmio *mmio,
545                                    phys_addr_t offset, int vcpu_id)
546 {
547         u32 *level_active;
548         u32 *reg, orig;
549         int mode = ACCESS_READ_VALUE | ACCESS_WRITE_CLEARBIT;
550         struct vgic_dist *dist = &kvm->arch.vgic;
551
552         reg = vgic_bitmap_get_reg(&dist->irq_pending, vcpu_id, offset);
553         orig = *reg;
554         vgic_reg_access(mmio, reg, offset, mode);
555         if (mmio->is_write) {
556                 /* Re-set level triggered level-active interrupts */
557                 level_active = vgic_bitmap_get_reg(&dist->irq_level,
558                                           vcpu_id, offset);
559                 reg = vgic_bitmap_get_reg(&dist->irq_pending, vcpu_id, offset);
560                 *reg |= *level_active;
561
562                 /* Ignore writes to SGIs */
563                 if (offset < 2) {
564                         *reg &= ~0xffff;
565                         *reg |= orig & 0xffff;
566                 }
567
568                 /* Clear soft-pending flags */
569                 reg = vgic_bitmap_get_reg(&dist->irq_soft_pend,
570                                           vcpu_id, offset);
571                 vgic_reg_access(mmio, reg, offset, mode);
572
573                 vgic_update_state(kvm);
574                 return true;
575         }
576         return false;
577 }
578
579 bool vgic_handle_set_active_reg(struct kvm *kvm,
580                                 struct kvm_exit_mmio *mmio,
581                                 phys_addr_t offset, int vcpu_id)
582 {
583         u32 *reg;
584         struct vgic_dist *dist = &kvm->arch.vgic;
585
586         reg = vgic_bitmap_get_reg(&dist->irq_active, vcpu_id, offset);
587         vgic_reg_access(mmio, reg, offset,
588                         ACCESS_READ_VALUE | ACCESS_WRITE_SETBIT);
589
590         if (mmio->is_write) {
591                 vgic_update_state(kvm);
592                 return true;
593         }
594
595         return false;
596 }
597
598 bool vgic_handle_clear_active_reg(struct kvm *kvm,
599                                   struct kvm_exit_mmio *mmio,
600                                   phys_addr_t offset, int vcpu_id)
601 {
602         u32 *reg;
603         struct vgic_dist *dist = &kvm->arch.vgic;
604
605         reg = vgic_bitmap_get_reg(&dist->irq_active, vcpu_id, offset);
606         vgic_reg_access(mmio, reg, offset,
607                         ACCESS_READ_VALUE | ACCESS_WRITE_CLEARBIT);
608
609         if (mmio->is_write) {
610                 vgic_update_state(kvm);
611                 return true;
612         }
613
614         return false;
615 }
616
617 static u32 vgic_cfg_expand(u16 val)
618 {
619         u32 res = 0;
620         int i;
621
622         /*
623          * Turn a 16bit value like abcd...mnop into a 32bit word
624          * a0b0c0d0...m0n0o0p0, which is what the HW cfg register is.
625          */
626         for (i = 0; i < 16; i++)
627                 res |= ((val >> i) & VGIC_CFG_EDGE) << (2 * i + 1);
628
629         return res;
630 }
631
632 static u16 vgic_cfg_compress(u32 val)
633 {
634         u16 res = 0;
635         int i;
636
637         /*
638          * Turn a 32bit word a0b0c0d0...m0n0o0p0 into 16bit value like
639          * abcd...mnop which is what we really care about.
640          */
641         for (i = 0; i < 16; i++)
642                 res |= ((val >> (i * 2 + 1)) & VGIC_CFG_EDGE) << i;
643
644         return res;
645 }
646
647 /*
648  * The distributor uses 2 bits per IRQ for the CFG register, but the
649  * LSB is always 0. As such, we only keep the upper bit, and use the
650  * two above functions to compress/expand the bits
651  */
652 bool vgic_handle_cfg_reg(u32 *reg, struct kvm_exit_mmio *mmio,
653                          phys_addr_t offset)
654 {
655         u32 val;
656
657         if (offset & 4)
658                 val = *reg >> 16;
659         else
660                 val = *reg & 0xffff;
661
662         val = vgic_cfg_expand(val);
663         vgic_reg_access(mmio, &val, offset,
664                         ACCESS_READ_VALUE | ACCESS_WRITE_VALUE);
665         if (mmio->is_write) {
666                 /* Ignore writes to read-only SGI and PPI bits */
667                 if (offset < 8)
668                         return false;
669
670                 val = vgic_cfg_compress(val);
671                 if (offset & 4) {
672                         *reg &= 0xffff;
673                         *reg |= val << 16;
674                 } else {
675                         *reg &= 0xffff << 16;
676                         *reg |= val;
677                 }
678         }
679
680         return false;
681 }
682
683 /**
684  * vgic_unqueue_irqs - move pending/active IRQs from LRs to the distributor
685  * @vgic_cpu: Pointer to the vgic_cpu struct holding the LRs
686  *
687  * Move any IRQs that have already been assigned to LRs back to the
688  * emulated distributor state so that the complete emulated state can be read
689  * from the main emulation structures without investigating the LRs.
690  */
691 void vgic_unqueue_irqs(struct kvm_vcpu *vcpu)
692 {
693         struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
694         u64 elrsr = vgic_get_elrsr(vcpu);
695         unsigned long *elrsr_ptr = u64_to_bitmask(&elrsr);
696         int i;
697
698         for_each_clear_bit(i, elrsr_ptr, vgic_cpu->nr_lr) {
699                 struct vgic_lr lr = vgic_get_lr(vcpu, i);
700
701                 /*
702                  * There are three options for the state bits:
703                  *
704                  * 01: pending
705                  * 10: active
706                  * 11: pending and active
707                  */
708                 BUG_ON(!(lr.state & LR_STATE_MASK));
709
710                 /* Reestablish SGI source for pending and active IRQs */
711                 if (lr.irq < VGIC_NR_SGIS)
712                         add_sgi_source(vcpu, lr.irq, lr.source);
713
714                 /*
715                  * If the LR holds an active (10) or a pending and active (11)
716                  * interrupt then move the active state to the
717                  * distributor tracking bit.
718                  */
719                 if (lr.state & LR_STATE_ACTIVE)
720                         vgic_irq_set_active(vcpu, lr.irq);
721
722                 /*
723                  * Reestablish the pending state on the distributor and the
724                  * CPU interface and mark the LR as free for other use.
725                  */
726                 vgic_retire_lr(i, vcpu);
727
728                 /* Finally update the VGIC state. */
729                 vgic_update_state(vcpu->kvm);
730         }
731 }
732
733 const
734 struct vgic_io_range *vgic_find_range(const struct vgic_io_range *ranges,
735                                       int len, gpa_t offset)
736 {
737         while (ranges->len) {
738                 if (offset >= ranges->base &&
739                     (offset + len) <= (ranges->base + ranges->len))
740                         return ranges;
741                 ranges++;
742         }
743
744         return NULL;
745 }
746
747 static bool vgic_validate_access(const struct vgic_dist *dist,
748                                  const struct vgic_io_range *range,
749                                  unsigned long offset)
750 {
751         int irq;
752
753         if (!range->bits_per_irq)
754                 return true;    /* Not an irq-based access */
755
756         irq = offset * 8 / range->bits_per_irq;
757         if (irq >= dist->nr_irqs)
758                 return false;
759
760         return true;
761 }
762
763 /*
764  * Call the respective handler function for the given range.
765  * We split up any 64 bit accesses into two consecutive 32 bit
766  * handler calls and merge the result afterwards.
767  * We do this in a little endian fashion regardless of the host's
768  * or guest's endianness, because the GIC is always LE and the rest of
769  * the code (vgic_reg_access) also puts it in a LE fashion already.
770  * At this point we have already identified the handle function, so
771  * range points to that one entry and offset is relative to this.
772  */
773 static bool call_range_handler(struct kvm_vcpu *vcpu,
774                                struct kvm_exit_mmio *mmio,
775                                unsigned long offset,
776                                const struct vgic_io_range *range)
777 {
778         struct kvm_exit_mmio mmio32;
779         bool ret;
780
781         if (likely(mmio->len <= 4))
782                 return range->handle_mmio(vcpu, mmio, offset);
783
784         /*
785          * Any access bigger than 4 bytes (that we currently handle in KVM)
786          * is actually 8 bytes long, caused by a 64-bit access
787          */
788
789         mmio32.len = 4;
790         mmio32.is_write = mmio->is_write;
791         mmio32.private = mmio->private;
792
793         mmio32.phys_addr = mmio->phys_addr + 4;
794         mmio32.data = &((u32 *)mmio->data)[1];
795         ret = range->handle_mmio(vcpu, &mmio32, offset + 4);
796
797         mmio32.phys_addr = mmio->phys_addr;
798         mmio32.data = &((u32 *)mmio->data)[0];
799         ret |= range->handle_mmio(vcpu, &mmio32, offset);
800
801         return ret;
802 }
803
804 /**
805  * vgic_handle_mmio_access - handle an in-kernel MMIO access
806  * This is called by the read/write KVM IO device wrappers below.
807  * @vcpu:       pointer to the vcpu performing the access
808  * @this:       pointer to the KVM IO device in charge
809  * @addr:       guest physical address of the access
810  * @len:        size of the access
811  * @val:        pointer to the data region
812  * @is_write:   read or write access
813  *
814  * returns true if the MMIO access could be performed
815  */
816 static int vgic_handle_mmio_access(struct kvm_vcpu *vcpu,
817                                    struct kvm_io_device *this, gpa_t addr,
818                                    int len, void *val, bool is_write)
819 {
820         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
821         struct vgic_io_device *iodev = container_of(this,
822                                                     struct vgic_io_device, dev);
823         struct kvm_run *run = vcpu->run;
824         const struct vgic_io_range *range;
825         struct kvm_exit_mmio mmio;
826         bool updated_state;
827         gpa_t offset;
828
829         offset = addr - iodev->addr;
830         range = vgic_find_range(iodev->reg_ranges, len, offset);
831         if (unlikely(!range || !range->handle_mmio)) {
832                 pr_warn("Unhandled access %d %08llx %d\n", is_write, addr, len);
833                 return -ENXIO;
834         }
835
836         mmio.phys_addr = addr;
837         mmio.len = len;
838         mmio.is_write = is_write;
839         mmio.data = val;
840         mmio.private = iodev->redist_vcpu;
841
842         spin_lock(&dist->lock);
843         offset -= range->base;
844         if (vgic_validate_access(dist, range, offset)) {
845                 updated_state = call_range_handler(vcpu, &mmio, offset, range);
846         } else {
847                 if (!is_write)
848                         memset(val, 0, len);
849                 updated_state = false;
850         }
851         spin_unlock(&dist->lock);
852         run->mmio.is_write      = is_write;
853         run->mmio.len           = len;
854         run->mmio.phys_addr     = addr;
855         memcpy(run->mmio.data, val, len);
856
857         kvm_handle_mmio_return(vcpu, run);
858
859         if (updated_state)
860                 vgic_kick_vcpus(vcpu->kvm);
861
862         return 0;
863 }
864
865 static int vgic_handle_mmio_read(struct kvm_vcpu *vcpu,
866                                  struct kvm_io_device *this,
867                                  gpa_t addr, int len, void *val)
868 {
869         return vgic_handle_mmio_access(vcpu, this, addr, len, val, false);
870 }
871
872 static int vgic_handle_mmio_write(struct kvm_vcpu *vcpu,
873                                   struct kvm_io_device *this,
874                                   gpa_t addr, int len, const void *val)
875 {
876         return vgic_handle_mmio_access(vcpu, this, addr, len, (void *)val,
877                                        true);
878 }
879
880 static struct kvm_io_device_ops vgic_io_ops = {
881         .read   = vgic_handle_mmio_read,
882         .write  = vgic_handle_mmio_write,
883 };
884
885 /**
886  * vgic_register_kvm_io_dev - register VGIC register frame on the KVM I/O bus
887  * @kvm:            The VM structure pointer
888  * @base:           The (guest) base address for the register frame
889  * @len:            Length of the register frame window
890  * @ranges:         Describing the handler functions for each register
891  * @redist_vcpu_id: The VCPU ID to pass on to the handlers on call
892  * @iodev:          Points to memory to be passed on to the handler
893  *
894  * @iodev stores the parameters of this function to be usable by the handler
895  * respectively the dispatcher function (since the KVM I/O bus framework lacks
896  * an opaque parameter). Initialization is done in this function, but the
897  * reference should be valid and unique for the whole VGIC lifetime.
898  * If the register frame is not mapped for a specific VCPU, pass -1 to
899  * @redist_vcpu_id.
900  */
901 int vgic_register_kvm_io_dev(struct kvm *kvm, gpa_t base, int len,
902                              const struct vgic_io_range *ranges,
903                              int redist_vcpu_id,
904                              struct vgic_io_device *iodev)
905 {
906         struct kvm_vcpu *vcpu = NULL;
907         int ret;
908
909         if (redist_vcpu_id >= 0)
910                 vcpu = kvm_get_vcpu(kvm, redist_vcpu_id);
911
912         iodev->addr             = base;
913         iodev->len              = len;
914         iodev->reg_ranges       = ranges;
915         iodev->redist_vcpu      = vcpu;
916
917         kvm_iodevice_init(&iodev->dev, &vgic_io_ops);
918
919         mutex_lock(&kvm->slots_lock);
920
921         ret = kvm_io_bus_register_dev(kvm, KVM_MMIO_BUS, base, len,
922                                       &iodev->dev);
923         mutex_unlock(&kvm->slots_lock);
924
925         /* Mark the iodev as invalid if registration fails. */
926         if (ret)
927                 iodev->dev.ops = NULL;
928
929         return ret;
930 }
931
932 static int vgic_nr_shared_irqs(struct vgic_dist *dist)
933 {
934         return dist->nr_irqs - VGIC_NR_PRIVATE_IRQS;
935 }
936
937 static int compute_active_for_cpu(struct kvm_vcpu *vcpu)
938 {
939         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
940         unsigned long *active, *enabled, *act_percpu, *act_shared;
941         unsigned long active_private, active_shared;
942         int nr_shared = vgic_nr_shared_irqs(dist);
943         int vcpu_id;
944
945         vcpu_id = vcpu->vcpu_id;
946         act_percpu = vcpu->arch.vgic_cpu.active_percpu;
947         act_shared = vcpu->arch.vgic_cpu.active_shared;
948
949         active = vgic_bitmap_get_cpu_map(&dist->irq_active, vcpu_id);
950         enabled = vgic_bitmap_get_cpu_map(&dist->irq_enabled, vcpu_id);
951         bitmap_and(act_percpu, active, enabled, VGIC_NR_PRIVATE_IRQS);
952
953         active = vgic_bitmap_get_shared_map(&dist->irq_active);
954         enabled = vgic_bitmap_get_shared_map(&dist->irq_enabled);
955         bitmap_and(act_shared, active, enabled, nr_shared);
956         bitmap_and(act_shared, act_shared,
957                    vgic_bitmap_get_shared_map(&dist->irq_spi_target[vcpu_id]),
958                    nr_shared);
959
960         active_private = find_first_bit(act_percpu, VGIC_NR_PRIVATE_IRQS);
961         active_shared = find_first_bit(act_shared, nr_shared);
962
963         return (active_private < VGIC_NR_PRIVATE_IRQS ||
964                 active_shared < nr_shared);
965 }
966
967 static int compute_pending_for_cpu(struct kvm_vcpu *vcpu)
968 {
969         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
970         unsigned long *pending, *enabled, *pend_percpu, *pend_shared;
971         unsigned long pending_private, pending_shared;
972         int nr_shared = vgic_nr_shared_irqs(dist);
973         int vcpu_id;
974
975         vcpu_id = vcpu->vcpu_id;
976         pend_percpu = vcpu->arch.vgic_cpu.pending_percpu;
977         pend_shared = vcpu->arch.vgic_cpu.pending_shared;
978
979         if (!dist->enabled) {
980                 bitmap_zero(pend_percpu, VGIC_NR_PRIVATE_IRQS);
981                 bitmap_zero(pend_shared, nr_shared);
982                 return 0;
983         }
984
985         pending = vgic_bitmap_get_cpu_map(&dist->irq_pending, vcpu_id);
986         enabled = vgic_bitmap_get_cpu_map(&dist->irq_enabled, vcpu_id);
987         bitmap_and(pend_percpu, pending, enabled, VGIC_NR_PRIVATE_IRQS);
988
989         pending = vgic_bitmap_get_shared_map(&dist->irq_pending);
990         enabled = vgic_bitmap_get_shared_map(&dist->irq_enabled);
991         bitmap_and(pend_shared, pending, enabled, nr_shared);
992         bitmap_and(pend_shared, pend_shared,
993                    vgic_bitmap_get_shared_map(&dist->irq_spi_target[vcpu_id]),
994                    nr_shared);
995
996         pending_private = find_first_bit(pend_percpu, VGIC_NR_PRIVATE_IRQS);
997         pending_shared = find_first_bit(pend_shared, nr_shared);
998         return (pending_private < VGIC_NR_PRIVATE_IRQS ||
999                 pending_shared < vgic_nr_shared_irqs(dist));
1000 }
1001
1002 /*
1003  * Update the interrupt state and determine which CPUs have pending
1004  * or active interrupts. Must be called with distributor lock held.
1005  */
1006 void vgic_update_state(struct kvm *kvm)
1007 {
1008         struct vgic_dist *dist = &kvm->arch.vgic;
1009         struct kvm_vcpu *vcpu;
1010         int c;
1011
1012         kvm_for_each_vcpu(c, vcpu, kvm) {
1013                 if (compute_pending_for_cpu(vcpu))
1014                         set_bit(c, dist->irq_pending_on_cpu);
1015
1016                 if (compute_active_for_cpu(vcpu))
1017                         set_bit(c, dist->irq_active_on_cpu);
1018                 else
1019                         clear_bit(c, dist->irq_active_on_cpu);
1020         }
1021 }
1022
1023 static struct vgic_lr vgic_get_lr(const struct kvm_vcpu *vcpu, int lr)
1024 {
1025         return vgic_ops->get_lr(vcpu, lr);
1026 }
1027
1028 static void vgic_set_lr(struct kvm_vcpu *vcpu, int lr,
1029                                struct vgic_lr vlr)
1030 {
1031         vgic_ops->set_lr(vcpu, lr, vlr);
1032 }
1033
1034 static inline u64 vgic_get_elrsr(struct kvm_vcpu *vcpu)
1035 {
1036         return vgic_ops->get_elrsr(vcpu);
1037 }
1038
1039 static inline u64 vgic_get_eisr(struct kvm_vcpu *vcpu)
1040 {
1041         return vgic_ops->get_eisr(vcpu);
1042 }
1043
1044 static inline void vgic_clear_eisr(struct kvm_vcpu *vcpu)
1045 {
1046         vgic_ops->clear_eisr(vcpu);
1047 }
1048
1049 static inline u32 vgic_get_interrupt_status(struct kvm_vcpu *vcpu)
1050 {
1051         return vgic_ops->get_interrupt_status(vcpu);
1052 }
1053
1054 static inline void vgic_enable_underflow(struct kvm_vcpu *vcpu)
1055 {
1056         vgic_ops->enable_underflow(vcpu);
1057 }
1058
1059 static inline void vgic_disable_underflow(struct kvm_vcpu *vcpu)
1060 {
1061         vgic_ops->disable_underflow(vcpu);
1062 }
1063
1064 void vgic_get_vmcr(struct kvm_vcpu *vcpu, struct vgic_vmcr *vmcr)
1065 {
1066         vgic_ops->get_vmcr(vcpu, vmcr);
1067 }
1068
1069 void vgic_set_vmcr(struct kvm_vcpu *vcpu, struct vgic_vmcr *vmcr)
1070 {
1071         vgic_ops->set_vmcr(vcpu, vmcr);
1072 }
1073
1074 static inline void vgic_enable(struct kvm_vcpu *vcpu)
1075 {
1076         vgic_ops->enable(vcpu);
1077 }
1078
1079 static void vgic_retire_lr(int lr_nr, struct kvm_vcpu *vcpu)
1080 {
1081         struct vgic_lr vlr = vgic_get_lr(vcpu, lr_nr);
1082
1083         vgic_irq_clear_queued(vcpu, vlr.irq);
1084
1085         /*
1086          * We must transfer the pending state back to the distributor before
1087          * retiring the LR, otherwise we may loose edge-triggered interrupts.
1088          */
1089         if (vlr.state & LR_STATE_PENDING) {
1090                 vgic_dist_irq_set_pending(vcpu, vlr.irq);
1091                 vlr.hwirq = 0;
1092         }
1093
1094         vlr.state = 0;
1095         vgic_set_lr(vcpu, lr_nr, vlr);
1096 }
1097
1098 static bool dist_active_irq(struct kvm_vcpu *vcpu)
1099 {
1100         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
1101
1102         return test_bit(vcpu->vcpu_id, dist->irq_active_on_cpu);
1103 }
1104
1105 bool kvm_vgic_map_is_active(struct kvm_vcpu *vcpu, struct irq_phys_map *map)
1106 {
1107         int i;
1108
1109         for (i = 0; i < vcpu->arch.vgic_cpu.nr_lr; i++) {
1110                 struct vgic_lr vlr = vgic_get_lr(vcpu, i);
1111
1112                 if (vlr.irq == map->virt_irq && vlr.state & LR_STATE_ACTIVE)
1113                         return true;
1114         }
1115
1116         return vgic_irq_is_active(vcpu, map->virt_irq);
1117 }
1118
1119 /*
1120  * An interrupt may have been disabled after being made pending on the
1121  * CPU interface (the classic case is a timer running while we're
1122  * rebooting the guest - the interrupt would kick as soon as the CPU
1123  * interface gets enabled, with deadly consequences).
1124  *
1125  * The solution is to examine already active LRs, and check the
1126  * interrupt is still enabled. If not, just retire it.
1127  */
1128 static void vgic_retire_disabled_irqs(struct kvm_vcpu *vcpu)
1129 {
1130         u64 elrsr = vgic_get_elrsr(vcpu);
1131         unsigned long *elrsr_ptr = u64_to_bitmask(&elrsr);
1132         int lr;
1133
1134         for_each_clear_bit(lr, elrsr_ptr, vgic->nr_lr) {
1135                 struct vgic_lr vlr = vgic_get_lr(vcpu, lr);
1136
1137                 if (!vgic_irq_is_enabled(vcpu, vlr.irq))
1138                         vgic_retire_lr(lr, vcpu);
1139         }
1140 }
1141
1142 static void vgic_queue_irq_to_lr(struct kvm_vcpu *vcpu, int irq,
1143                                  int lr_nr, struct vgic_lr vlr)
1144 {
1145         if (vgic_irq_is_active(vcpu, irq)) {
1146                 vlr.state |= LR_STATE_ACTIVE;
1147                 kvm_debug("Set active, clear distributor: 0x%x\n", vlr.state);
1148                 vgic_irq_clear_active(vcpu, irq);
1149                 vgic_update_state(vcpu->kvm);
1150         } else {
1151                 WARN_ON(!vgic_dist_irq_is_pending(vcpu, irq));
1152                 vlr.state |= LR_STATE_PENDING;
1153                 kvm_debug("Set pending: 0x%x\n", vlr.state);
1154         }
1155
1156         if (!vgic_irq_is_edge(vcpu, irq))
1157                 vlr.state |= LR_EOI_INT;
1158
1159         if (vlr.irq >= VGIC_NR_SGIS) {
1160                 struct irq_phys_map *map;
1161                 map = vgic_irq_map_search(vcpu, irq);
1162
1163                 if (map) {
1164                         vlr.hwirq = map->phys_irq;
1165                         vlr.state |= LR_HW;
1166                         vlr.state &= ~LR_EOI_INT;
1167
1168                         /*
1169                          * Make sure we're not going to sample this
1170                          * again, as a HW-backed interrupt cannot be
1171                          * in the PENDING_ACTIVE stage.
1172                          */
1173                         vgic_irq_set_queued(vcpu, irq);
1174                 }
1175         }
1176
1177         vgic_set_lr(vcpu, lr_nr, vlr);
1178 }
1179
1180 /*
1181  * Queue an interrupt to a CPU virtual interface. Return true on success,
1182  * or false if it wasn't possible to queue it.
1183  * sgi_source must be zero for any non-SGI interrupts.
1184  */
1185 bool vgic_queue_irq(struct kvm_vcpu *vcpu, u8 sgi_source_id, int irq)
1186 {
1187         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
1188         u64 elrsr = vgic_get_elrsr(vcpu);
1189         unsigned long *elrsr_ptr = u64_to_bitmask(&elrsr);
1190         struct vgic_lr vlr;
1191         int lr;
1192
1193         /* Sanitize the input... */
1194         BUG_ON(sgi_source_id & ~7);
1195         BUG_ON(sgi_source_id && irq >= VGIC_NR_SGIS);
1196         BUG_ON(irq >= dist->nr_irqs);
1197
1198         kvm_debug("Queue IRQ%d\n", irq);
1199
1200         /* Do we have an active interrupt for the same CPUID? */
1201         for_each_clear_bit(lr, elrsr_ptr, vgic->nr_lr) {
1202                 vlr = vgic_get_lr(vcpu, lr);
1203                 if (vlr.irq == irq && vlr.source == sgi_source_id) {
1204                         kvm_debug("LR%d piggyback for IRQ%d\n", lr, vlr.irq);
1205                         vgic_queue_irq_to_lr(vcpu, irq, lr, vlr);
1206                         return true;
1207                 }
1208         }
1209
1210         /* Try to use another LR for this interrupt */
1211         lr = find_first_bit(elrsr_ptr, vgic->nr_lr);
1212         if (lr >= vgic->nr_lr)
1213                 return false;
1214
1215         kvm_debug("LR%d allocated for IRQ%d %x\n", lr, irq, sgi_source_id);
1216
1217         vlr.irq = irq;
1218         vlr.source = sgi_source_id;
1219         vlr.state = 0;
1220         vgic_queue_irq_to_lr(vcpu, irq, lr, vlr);
1221
1222         return true;
1223 }
1224
1225 static bool vgic_queue_hwirq(struct kvm_vcpu *vcpu, int irq)
1226 {
1227         if (!vgic_can_sample_irq(vcpu, irq))
1228                 return true; /* level interrupt, already queued */
1229
1230         if (vgic_queue_irq(vcpu, 0, irq)) {
1231                 if (vgic_irq_is_edge(vcpu, irq)) {
1232                         vgic_dist_irq_clear_pending(vcpu, irq);
1233                         vgic_cpu_irq_clear(vcpu, irq);
1234                 } else {
1235                         vgic_irq_set_queued(vcpu, irq);
1236                 }
1237
1238                 return true;
1239         }
1240
1241         return false;
1242 }
1243
1244 /*
1245  * Fill the list registers with pending interrupts before running the
1246  * guest.
1247  */
1248 static void __kvm_vgic_flush_hwstate(struct kvm_vcpu *vcpu)
1249 {
1250         struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
1251         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
1252         unsigned long *pa_percpu, *pa_shared;
1253         int i, vcpu_id;
1254         int overflow = 0;
1255         int nr_shared = vgic_nr_shared_irqs(dist);
1256
1257         vcpu_id = vcpu->vcpu_id;
1258
1259         pa_percpu = vcpu->arch.vgic_cpu.pend_act_percpu;
1260         pa_shared = vcpu->arch.vgic_cpu.pend_act_shared;
1261
1262         bitmap_or(pa_percpu, vgic_cpu->pending_percpu, vgic_cpu->active_percpu,
1263                   VGIC_NR_PRIVATE_IRQS);
1264         bitmap_or(pa_shared, vgic_cpu->pending_shared, vgic_cpu->active_shared,
1265                   nr_shared);
1266         /*
1267          * We may not have any pending interrupt, or the interrupts
1268          * may have been serviced from another vcpu. In all cases,
1269          * move along.
1270          */
1271         if (!kvm_vgic_vcpu_pending_irq(vcpu) && !dist_active_irq(vcpu))
1272                 goto epilog;
1273
1274         /* SGIs */
1275         for_each_set_bit(i, pa_percpu, VGIC_NR_SGIS) {
1276                 if (!queue_sgi(vcpu, i))
1277                         overflow = 1;
1278         }
1279
1280         /* PPIs */
1281         for_each_set_bit_from(i, pa_percpu, VGIC_NR_PRIVATE_IRQS) {
1282                 if (!vgic_queue_hwirq(vcpu, i))
1283                         overflow = 1;
1284         }
1285
1286         /* SPIs */
1287         for_each_set_bit(i, pa_shared, nr_shared) {
1288                 if (!vgic_queue_hwirq(vcpu, i + VGIC_NR_PRIVATE_IRQS))
1289                         overflow = 1;
1290         }
1291
1292
1293
1294
1295 epilog:
1296         if (overflow) {
1297                 vgic_enable_underflow(vcpu);
1298         } else {
1299                 vgic_disable_underflow(vcpu);
1300                 /*
1301                  * We're about to run this VCPU, and we've consumed
1302                  * everything the distributor had in store for
1303                  * us. Claim we don't have anything pending. We'll
1304                  * adjust that if needed while exiting.
1305                  */
1306                 clear_bit(vcpu_id, dist->irq_pending_on_cpu);
1307         }
1308 }
1309
1310 static int process_queued_irq(struct kvm_vcpu *vcpu,
1311                                    int lr, struct vgic_lr vlr)
1312 {
1313         int pending = 0;
1314
1315         /*
1316          * If the IRQ was EOIed (called from vgic_process_maintenance) or it
1317          * went from active to non-active (called from vgic_sync_hwirq) it was
1318          * also ACKed and we we therefore assume we can clear the soft pending
1319          * state (should it had been set) for this interrupt.
1320          *
1321          * Note: if the IRQ soft pending state was set after the IRQ was
1322          * acked, it actually shouldn't be cleared, but we have no way of
1323          * knowing that unless we start trapping ACKs when the soft-pending
1324          * state is set.
1325          */
1326         vgic_dist_irq_clear_soft_pend(vcpu, vlr.irq);
1327
1328         /*
1329          * Tell the gic to start sampling this interrupt again.
1330          */
1331         vgic_irq_clear_queued(vcpu, vlr.irq);
1332
1333         /* Any additional pending interrupt? */
1334         if (vgic_irq_is_edge(vcpu, vlr.irq)) {
1335                 BUG_ON(!(vlr.state & LR_HW));
1336                 pending = vgic_dist_irq_is_pending(vcpu, vlr.irq);
1337         } else {
1338                 if (vgic_dist_irq_get_level(vcpu, vlr.irq)) {
1339                         vgic_cpu_irq_set(vcpu, vlr.irq);
1340                         pending = 1;
1341                 } else {
1342                         vgic_dist_irq_clear_pending(vcpu, vlr.irq);
1343                         vgic_cpu_irq_clear(vcpu, vlr.irq);
1344                 }
1345         }
1346
1347         /*
1348          * Despite being EOIed, the LR may not have
1349          * been marked as empty.
1350          */
1351         vlr.state = 0;
1352         vlr.hwirq = 0;
1353         vgic_set_lr(vcpu, lr, vlr);
1354
1355         return pending;
1356 }
1357
1358 static bool vgic_process_maintenance(struct kvm_vcpu *vcpu)
1359 {
1360         u32 status = vgic_get_interrupt_status(vcpu);
1361         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
1362         struct kvm *kvm = vcpu->kvm;
1363         int level_pending = 0;
1364
1365         kvm_debug("STATUS = %08x\n", status);
1366
1367         if (status & INT_STATUS_EOI) {
1368                 /*
1369                  * Some level interrupts have been EOIed. Clear their
1370                  * active bit.
1371                  */
1372                 u64 eisr = vgic_get_eisr(vcpu);
1373                 unsigned long *eisr_ptr = u64_to_bitmask(&eisr);
1374                 int lr;
1375
1376                 for_each_set_bit(lr, eisr_ptr, vgic->nr_lr) {
1377                         struct vgic_lr vlr = vgic_get_lr(vcpu, lr);
1378
1379                         WARN_ON(vgic_irq_is_edge(vcpu, vlr.irq));
1380                         WARN_ON(vlr.state & LR_STATE_MASK);
1381
1382
1383                         /*
1384                          * kvm_notify_acked_irq calls kvm_set_irq()
1385                          * to reset the IRQ level, which grabs the dist->lock
1386                          * so we call this before taking the dist->lock.
1387                          */
1388                         kvm_notify_acked_irq(kvm, 0,
1389                                              vlr.irq - VGIC_NR_PRIVATE_IRQS);
1390
1391                         spin_lock(&dist->lock);
1392                         level_pending |= process_queued_irq(vcpu, lr, vlr);
1393                         spin_unlock(&dist->lock);
1394                 }
1395         }
1396
1397         if (status & INT_STATUS_UNDERFLOW)
1398                 vgic_disable_underflow(vcpu);
1399
1400         /*
1401          * In the next iterations of the vcpu loop, if we sync the vgic state
1402          * after flushing it, but before entering the guest (this happens for
1403          * pending signals and vmid rollovers), then make sure we don't pick
1404          * up any old maintenance interrupts here.
1405          */
1406         vgic_clear_eisr(vcpu);
1407
1408         return level_pending;
1409 }
1410
1411 /*
1412  * Save the physical active state, and reset it to inactive.
1413  *
1414  * Return true if there's a pending forwarded interrupt to queue.
1415  */
1416 static bool vgic_sync_hwirq(struct kvm_vcpu *vcpu, int lr, struct vgic_lr vlr)
1417 {
1418         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
1419         bool level_pending;
1420
1421         if (!(vlr.state & LR_HW))
1422                 return false;
1423
1424         if (vlr.state & LR_STATE_ACTIVE)
1425                 return false;
1426
1427         spin_lock(&dist->lock);
1428         level_pending = process_queued_irq(vcpu, lr, vlr);
1429         spin_unlock(&dist->lock);
1430         return level_pending;
1431 }
1432
1433 /* Sync back the VGIC state after a guest run */
1434 static void __kvm_vgic_sync_hwstate(struct kvm_vcpu *vcpu)
1435 {
1436         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
1437         u64 elrsr;
1438         unsigned long *elrsr_ptr;
1439         int lr, pending;
1440         bool level_pending;
1441
1442         level_pending = vgic_process_maintenance(vcpu);
1443
1444         /* Deal with HW interrupts, and clear mappings for empty LRs */
1445         for (lr = 0; lr < vgic->nr_lr; lr++) {
1446                 struct vgic_lr vlr = vgic_get_lr(vcpu, lr);
1447
1448                 level_pending |= vgic_sync_hwirq(vcpu, lr, vlr);
1449                 BUG_ON(vlr.irq >= dist->nr_irqs);
1450         }
1451
1452         /* Check if we still have something up our sleeve... */
1453         elrsr = vgic_get_elrsr(vcpu);
1454         elrsr_ptr = u64_to_bitmask(&elrsr);
1455         pending = find_first_zero_bit(elrsr_ptr, vgic->nr_lr);
1456         if (level_pending || pending < vgic->nr_lr)
1457                 set_bit(vcpu->vcpu_id, dist->irq_pending_on_cpu);
1458 }
1459
1460 void kvm_vgic_flush_hwstate(struct kvm_vcpu *vcpu)
1461 {
1462         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
1463
1464         if (!irqchip_in_kernel(vcpu->kvm))
1465                 return;
1466
1467         spin_lock(&dist->lock);
1468         __kvm_vgic_flush_hwstate(vcpu);
1469         spin_unlock(&dist->lock);
1470 }
1471
1472 void kvm_vgic_sync_hwstate(struct kvm_vcpu *vcpu)
1473 {
1474         if (!irqchip_in_kernel(vcpu->kvm))
1475                 return;
1476
1477         __kvm_vgic_sync_hwstate(vcpu);
1478 }
1479
1480 int kvm_vgic_vcpu_pending_irq(struct kvm_vcpu *vcpu)
1481 {
1482         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
1483
1484         if (!irqchip_in_kernel(vcpu->kvm))
1485                 return 0;
1486
1487         return test_bit(vcpu->vcpu_id, dist->irq_pending_on_cpu);
1488 }
1489
1490 void vgic_kick_vcpus(struct kvm *kvm)
1491 {
1492         struct kvm_vcpu *vcpu;
1493         int c;
1494
1495         /*
1496          * We've injected an interrupt, time to find out who deserves
1497          * a good kick...
1498          */
1499         kvm_for_each_vcpu(c, vcpu, kvm) {
1500                 if (kvm_vgic_vcpu_pending_irq(vcpu))
1501                         kvm_vcpu_kick(vcpu);
1502         }
1503 }
1504
1505 static int vgic_validate_injection(struct kvm_vcpu *vcpu, int irq, int level)
1506 {
1507         int edge_triggered = vgic_irq_is_edge(vcpu, irq);
1508
1509         /*
1510          * Only inject an interrupt if:
1511          * - edge triggered and we have a rising edge
1512          * - level triggered and we change level
1513          */
1514         if (edge_triggered) {
1515                 int state = vgic_dist_irq_is_pending(vcpu, irq);
1516                 return level > state;
1517         } else {
1518                 int state = vgic_dist_irq_get_level(vcpu, irq);
1519                 return level != state;
1520         }
1521 }
1522
1523 static int vgic_update_irq_pending(struct kvm *kvm, int cpuid,
1524                                    struct irq_phys_map *map,
1525                                    unsigned int irq_num, bool level)
1526 {
1527         struct vgic_dist *dist = &kvm->arch.vgic;
1528         struct kvm_vcpu *vcpu;
1529         int edge_triggered, level_triggered;
1530         int enabled;
1531         bool ret = true, can_inject = true;
1532
1533         trace_vgic_update_irq_pending(cpuid, irq_num, level);
1534
1535         if (irq_num >= min(kvm->arch.vgic.nr_irqs, 1020))
1536                 return -EINVAL;
1537
1538         spin_lock(&dist->lock);
1539
1540         vcpu = kvm_get_vcpu(kvm, cpuid);
1541         edge_triggered = vgic_irq_is_edge(vcpu, irq_num);
1542         level_triggered = !edge_triggered;
1543
1544         if (!vgic_validate_injection(vcpu, irq_num, level)) {
1545                 ret = false;
1546                 goto out;
1547         }
1548
1549         if (irq_num >= VGIC_NR_PRIVATE_IRQS) {
1550                 cpuid = dist->irq_spi_cpu[irq_num - VGIC_NR_PRIVATE_IRQS];
1551                 if (cpuid == VCPU_NOT_ALLOCATED) {
1552                         /* Pretend we use CPU0, and prevent injection */
1553                         cpuid = 0;
1554                         can_inject = false;
1555                 }
1556                 vcpu = kvm_get_vcpu(kvm, cpuid);
1557         }
1558
1559         kvm_debug("Inject IRQ%d level %d CPU%d\n", irq_num, level, cpuid);
1560
1561         if (level) {
1562                 if (level_triggered)
1563                         vgic_dist_irq_set_level(vcpu, irq_num);
1564                 vgic_dist_irq_set_pending(vcpu, irq_num);
1565         } else {
1566                 if (level_triggered) {
1567                         vgic_dist_irq_clear_level(vcpu, irq_num);
1568                         if (!vgic_dist_irq_soft_pend(vcpu, irq_num)) {
1569                                 vgic_dist_irq_clear_pending(vcpu, irq_num);
1570                                 vgic_cpu_irq_clear(vcpu, irq_num);
1571                                 if (!compute_pending_for_cpu(vcpu))
1572                                         clear_bit(cpuid, dist->irq_pending_on_cpu);
1573                         }
1574                 }
1575
1576                 ret = false;
1577                 goto out;
1578         }
1579
1580         enabled = vgic_irq_is_enabled(vcpu, irq_num);
1581
1582         if (!enabled || !can_inject) {
1583                 ret = false;
1584                 goto out;
1585         }
1586
1587         if (!vgic_can_sample_irq(vcpu, irq_num)) {
1588                 /*
1589                  * Level interrupt in progress, will be picked up
1590                  * when EOId.
1591                  */
1592                 ret = false;
1593                 goto out;
1594         }
1595
1596         if (level) {
1597                 vgic_cpu_irq_set(vcpu, irq_num);
1598                 set_bit(cpuid, dist->irq_pending_on_cpu);
1599         }
1600
1601 out:
1602         spin_unlock(&dist->lock);
1603
1604         if (ret) {
1605                 /* kick the specified vcpu */
1606                 kvm_vcpu_kick(kvm_get_vcpu(kvm, cpuid));
1607         }
1608
1609         return 0;
1610 }
1611
1612 static int vgic_lazy_init(struct kvm *kvm)
1613 {
1614         int ret = 0;
1615
1616         if (unlikely(!vgic_initialized(kvm))) {
1617                 /*
1618                  * We only provide the automatic initialization of the VGIC
1619                  * for the legacy case of a GICv2. Any other type must
1620                  * be explicitly initialized once setup with the respective
1621                  * KVM device call.
1622                  */
1623                 if (kvm->arch.vgic.vgic_model != KVM_DEV_TYPE_ARM_VGIC_V2)
1624                         return -EBUSY;
1625
1626                 mutex_lock(&kvm->lock);
1627                 ret = vgic_init(kvm);
1628                 mutex_unlock(&kvm->lock);
1629         }
1630
1631         return ret;
1632 }
1633
1634 /**
1635  * kvm_vgic_inject_irq - Inject an IRQ from a device to the vgic
1636  * @kvm:     The VM structure pointer
1637  * @cpuid:   The CPU for PPIs
1638  * @irq_num: The IRQ number that is assigned to the device. This IRQ
1639  *           must not be mapped to a HW interrupt.
1640  * @level:   Edge-triggered:  true:  to trigger the interrupt
1641  *                            false: to ignore the call
1642  *           Level-sensitive  true:  raise the input signal
1643  *                            false: lower the input signal
1644  *
1645  * The GIC is not concerned with devices being active-LOW or active-HIGH for
1646  * level-sensitive interrupts.  You can think of the level parameter as 1
1647  * being HIGH and 0 being LOW and all devices being active-HIGH.
1648  */
1649 int kvm_vgic_inject_irq(struct kvm *kvm, int cpuid, unsigned int irq_num,
1650                         bool level)
1651 {
1652         struct irq_phys_map *map;
1653         int ret;
1654
1655         ret = vgic_lazy_init(kvm);
1656         if (ret)
1657                 return ret;
1658
1659         map = vgic_irq_map_search(kvm_get_vcpu(kvm, cpuid), irq_num);
1660         if (map)
1661                 return -EINVAL;
1662
1663         return vgic_update_irq_pending(kvm, cpuid, NULL, irq_num, level);
1664 }
1665
1666 /**
1667  * kvm_vgic_inject_mapped_irq - Inject a physically mapped IRQ to the vgic
1668  * @kvm:     The VM structure pointer
1669  * @cpuid:   The CPU for PPIs
1670  * @map:     Pointer to a irq_phys_map structure describing the mapping
1671  * @level:   Edge-triggered:  true:  to trigger the interrupt
1672  *                            false: to ignore the call
1673  *           Level-sensitive  true:  raise the input signal
1674  *                            false: lower the input signal
1675  *
1676  * The GIC is not concerned with devices being active-LOW or active-HIGH for
1677  * level-sensitive interrupts.  You can think of the level parameter as 1
1678  * being HIGH and 0 being LOW and all devices being active-HIGH.
1679  */
1680 int kvm_vgic_inject_mapped_irq(struct kvm *kvm, int cpuid,
1681                                struct irq_phys_map *map, bool level)
1682 {
1683         int ret;
1684
1685         ret = vgic_lazy_init(kvm);
1686         if (ret)
1687                 return ret;
1688
1689         return vgic_update_irq_pending(kvm, cpuid, map, map->virt_irq, level);
1690 }
1691
1692 static irqreturn_t vgic_maintenance_handler(int irq, void *data)
1693 {
1694         /*
1695          * We cannot rely on the vgic maintenance interrupt to be
1696          * delivered synchronously. This means we can only use it to
1697          * exit the VM, and we perform the handling of EOIed
1698          * interrupts on the exit path (see vgic_process_maintenance).
1699          */
1700         return IRQ_HANDLED;
1701 }
1702
1703 static struct list_head *vgic_get_irq_phys_map_list(struct kvm_vcpu *vcpu,
1704                                                     int virt_irq)
1705 {
1706         if (virt_irq < VGIC_NR_PRIVATE_IRQS)
1707                 return &vcpu->arch.vgic_cpu.irq_phys_map_list;
1708         else
1709                 return &vcpu->kvm->arch.vgic.irq_phys_map_list;
1710 }
1711
1712 /**
1713  * kvm_vgic_map_phys_irq - map a virtual IRQ to a physical IRQ
1714  * @vcpu: The VCPU pointer
1715  * @virt_irq: The virtual irq number
1716  * @irq: The Linux IRQ number
1717  *
1718  * Establish a mapping between a guest visible irq (@virt_irq) and a
1719  * Linux irq (@irq). On injection, @virt_irq will be associated with
1720  * the physical interrupt represented by @irq. This mapping can be
1721  * established multiple times as long as the parameters are the same.
1722  *
1723  * Returns a valid pointer on success, and an error pointer otherwise
1724  */
1725 struct irq_phys_map *kvm_vgic_map_phys_irq(struct kvm_vcpu *vcpu,
1726                                            int virt_irq, int irq)
1727 {
1728         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
1729         struct list_head *root = vgic_get_irq_phys_map_list(vcpu, virt_irq);
1730         struct irq_phys_map *map;
1731         struct irq_phys_map_entry *entry;
1732         struct irq_desc *desc;
1733         struct irq_data *data;
1734         int phys_irq;
1735
1736         desc = irq_to_desc(irq);
1737         if (!desc) {
1738                 kvm_err("%s: no interrupt descriptor\n", __func__);
1739                 return ERR_PTR(-EINVAL);
1740         }
1741
1742         data = irq_desc_get_irq_data(desc);
1743         while (data->parent_data)
1744                 data = data->parent_data;
1745
1746         phys_irq = data->hwirq;
1747
1748         /* Create a new mapping */
1749         entry = kzalloc(sizeof(*entry), GFP_KERNEL);
1750         if (!entry)
1751                 return ERR_PTR(-ENOMEM);
1752
1753         spin_lock(&dist->irq_phys_map_lock);
1754
1755         /* Try to match an existing mapping */
1756         map = vgic_irq_map_search(vcpu, virt_irq);
1757         if (map) {
1758                 /* Make sure this mapping matches */
1759                 if (map->phys_irq != phys_irq   ||
1760                     map->irq      != irq)
1761                         map = ERR_PTR(-EINVAL);
1762
1763                 /* Found an existing, valid mapping */
1764                 goto out;
1765         }
1766
1767         map           = &entry->map;
1768         map->virt_irq = virt_irq;
1769         map->phys_irq = phys_irq;
1770         map->irq      = irq;
1771
1772         list_add_tail_rcu(&entry->entry, root);
1773
1774 out:
1775         spin_unlock(&dist->irq_phys_map_lock);
1776         /* If we've found a hit in the existing list, free the useless
1777          * entry */
1778         if (IS_ERR(map) || map != &entry->map)
1779                 kfree(entry);
1780         return map;
1781 }
1782
1783 static struct irq_phys_map *vgic_irq_map_search(struct kvm_vcpu *vcpu,
1784                                                 int virt_irq)
1785 {
1786         struct list_head *root = vgic_get_irq_phys_map_list(vcpu, virt_irq);
1787         struct irq_phys_map_entry *entry;
1788         struct irq_phys_map *map;
1789
1790         rcu_read_lock();
1791
1792         list_for_each_entry_rcu(entry, root, entry) {
1793                 map = &entry->map;
1794                 if (map->virt_irq == virt_irq) {
1795                         rcu_read_unlock();
1796                         return map;
1797                 }
1798         }
1799
1800         rcu_read_unlock();
1801
1802         return NULL;
1803 }
1804
1805 static void vgic_free_phys_irq_map_rcu(struct rcu_head *rcu)
1806 {
1807         struct irq_phys_map_entry *entry;
1808
1809         entry = container_of(rcu, struct irq_phys_map_entry, rcu);
1810         kfree(entry);
1811 }
1812
1813 /**
1814  * kvm_vgic_unmap_phys_irq - Remove a virtual to physical IRQ mapping
1815  * @vcpu: The VCPU pointer
1816  * @map: The pointer to a mapping obtained through kvm_vgic_map_phys_irq
1817  *
1818  * Remove an existing mapping between virtual and physical interrupts.
1819  */
1820 int kvm_vgic_unmap_phys_irq(struct kvm_vcpu *vcpu, struct irq_phys_map *map)
1821 {
1822         struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
1823         struct irq_phys_map_entry *entry;
1824         struct list_head *root;
1825
1826         if (!map)
1827                 return -EINVAL;
1828
1829         root = vgic_get_irq_phys_map_list(vcpu, map->virt_irq);
1830
1831         spin_lock(&dist->irq_phys_map_lock);
1832
1833         list_for_each_entry(entry, root, entry) {
1834                 if (&entry->map == map) {
1835                         list_del_rcu(&entry->entry);
1836                         call_rcu(&entry->rcu, vgic_free_phys_irq_map_rcu);
1837                         break;
1838                 }
1839         }
1840
1841         spin_unlock(&dist->irq_phys_map_lock);
1842
1843         return 0;
1844 }
1845
1846 static void vgic_destroy_irq_phys_map(struct kvm *kvm, struct list_head *root)
1847 {
1848         struct vgic_dist *dist = &kvm->arch.vgic;
1849         struct irq_phys_map_entry *entry;
1850
1851         spin_lock(&dist->irq_phys_map_lock);
1852
1853         list_for_each_entry(entry, root, entry) {
1854                 list_del_rcu(&entry->entry);
1855                 call_rcu(&entry->rcu, vgic_free_phys_irq_map_rcu);
1856         }
1857
1858         spin_unlock(&dist->irq_phys_map_lock);
1859 }
1860
1861 void kvm_vgic_vcpu_destroy(struct kvm_vcpu *vcpu)
1862 {
1863         struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
1864
1865         kfree(vgic_cpu->pending_shared);
1866         kfree(vgic_cpu->active_shared);
1867         kfree(vgic_cpu->pend_act_shared);
1868         vgic_destroy_irq_phys_map(vcpu->kvm, &vgic_cpu->irq_phys_map_list);
1869         vgic_cpu->pending_shared = NULL;
1870         vgic_cpu->active_shared = NULL;
1871         vgic_cpu->pend_act_shared = NULL;
1872 }
1873
1874 static int vgic_vcpu_init_maps(struct kvm_vcpu *vcpu, int nr_irqs)
1875 {
1876         struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
1877         int nr_longs = BITS_TO_LONGS(nr_irqs - VGIC_NR_PRIVATE_IRQS);
1878         int sz = nr_longs * sizeof(unsigned long);
1879         vgic_cpu->pending_shared = kzalloc(sz, GFP_KERNEL);
1880         vgic_cpu->active_shared = kzalloc(sz, GFP_KERNEL);
1881         vgic_cpu->pend_act_shared = kzalloc(sz, GFP_KERNEL);
1882
1883         if (!vgic_cpu->pending_shared
1884                 || !vgic_cpu->active_shared
1885                 || !vgic_cpu->pend_act_shared) {
1886                 kvm_vgic_vcpu_destroy(vcpu);
1887                 return -ENOMEM;
1888         }
1889
1890         /*
1891          * Store the number of LRs per vcpu, so we don't have to go
1892          * all the way to the distributor structure to find out. Only
1893          * assembly code should use this one.
1894          */
1895         vgic_cpu->nr_lr = vgic->nr_lr;
1896
1897         return 0;
1898 }
1899
1900 /**
1901  * kvm_vgic_vcpu_early_init - Earliest possible per-vcpu vgic init stage
1902  *
1903  * No memory allocation should be performed here, only static init.
1904  */
1905 void kvm_vgic_vcpu_early_init(struct kvm_vcpu *vcpu)
1906 {
1907         struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
1908         INIT_LIST_HEAD(&vgic_cpu->irq_phys_map_list);
1909 }
1910
1911 /**
1912  * kvm_vgic_get_max_vcpus - Get the maximum number of VCPUs allowed by HW
1913  *
1914  * The host's GIC naturally limits the maximum amount of VCPUs a guest
1915  * can use.
1916  */
1917 int kvm_vgic_get_max_vcpus(void)
1918 {
1919         return vgic->max_gic_vcpus;
1920 }
1921
1922 void kvm_vgic_destroy(struct kvm *kvm)
1923 {
1924         struct vgic_dist *dist = &kvm->arch.vgic;
1925         struct kvm_vcpu *vcpu;
1926         int i;
1927
1928         kvm_for_each_vcpu(i, vcpu, kvm)
1929                 kvm_vgic_vcpu_destroy(vcpu);
1930
1931         vgic_free_bitmap(&dist->irq_enabled);
1932         vgic_free_bitmap(&dist->irq_level);
1933         vgic_free_bitmap(&dist->irq_pending);
1934         vgic_free_bitmap(&dist->irq_soft_pend);
1935         vgic_free_bitmap(&dist->irq_queued);
1936         vgic_free_bitmap(&dist->irq_cfg);
1937         vgic_free_bytemap(&dist->irq_priority);
1938         if (dist->irq_spi_target) {
1939                 for (i = 0; i < dist->nr_cpus; i++)
1940                         vgic_free_bitmap(&dist->irq_spi_target[i]);
1941         }
1942         kfree(dist->irq_sgi_sources);
1943         kfree(dist->irq_spi_cpu);
1944         kfree(dist->irq_spi_mpidr);
1945         kfree(dist->irq_spi_target);
1946         kfree(dist->irq_pending_on_cpu);
1947         kfree(dist->irq_active_on_cpu);
1948         vgic_destroy_irq_phys_map(kvm, &dist->irq_phys_map_list);
1949         dist->irq_sgi_sources = NULL;
1950         dist->irq_spi_cpu = NULL;
1951         dist->irq_spi_target = NULL;
1952         dist->irq_pending_on_cpu = NULL;
1953         dist->irq_active_on_cpu = NULL;
1954         dist->nr_cpus = 0;
1955 }
1956
1957 /*
1958  * Allocate and initialize the various data structures. Must be called
1959  * with kvm->lock held!
1960  */
1961 int vgic_init(struct kvm *kvm)
1962 {
1963         struct vgic_dist *dist = &kvm->arch.vgic;
1964         struct kvm_vcpu *vcpu;
1965         int nr_cpus, nr_irqs;
1966         int ret, i, vcpu_id;
1967
1968         if (vgic_initialized(kvm))
1969                 return 0;
1970
1971         nr_cpus = dist->nr_cpus = atomic_read(&kvm->online_vcpus);
1972         if (!nr_cpus)           /* No vcpus? Can't be good... */
1973                 return -ENODEV;
1974
1975         /*
1976          * If nobody configured the number of interrupts, use the
1977          * legacy one.
1978          */
1979         if (!dist->nr_irqs)
1980                 dist->nr_irqs = VGIC_NR_IRQS_LEGACY;
1981
1982         nr_irqs = dist->nr_irqs;
1983
1984         ret  = vgic_init_bitmap(&dist->irq_enabled, nr_cpus, nr_irqs);
1985         ret |= vgic_init_bitmap(&dist->irq_level, nr_cpus, nr_irqs);
1986         ret |= vgic_init_bitmap(&dist->irq_pending, nr_cpus, nr_irqs);
1987         ret |= vgic_init_bitmap(&dist->irq_soft_pend, nr_cpus, nr_irqs);
1988         ret |= vgic_init_bitmap(&dist->irq_queued, nr_cpus, nr_irqs);
1989         ret |= vgic_init_bitmap(&dist->irq_active, nr_cpus, nr_irqs);
1990         ret |= vgic_init_bitmap(&dist->irq_cfg, nr_cpus, nr_irqs);
1991         ret |= vgic_init_bytemap(&dist->irq_priority, nr_cpus, nr_irqs);
1992
1993         if (ret)
1994                 goto out;
1995
1996         dist->irq_sgi_sources = kzalloc(nr_cpus * VGIC_NR_SGIS, GFP_KERNEL);
1997         dist->irq_spi_cpu = kzalloc(nr_irqs - VGIC_NR_PRIVATE_IRQS, GFP_KERNEL);
1998         dist->irq_spi_target = kzalloc(sizeof(*dist->irq_spi_target) * nr_cpus,
1999                                        GFP_KERNEL);
2000         dist->irq_pending_on_cpu = kzalloc(BITS_TO_LONGS(nr_cpus) * sizeof(long),
2001                                            GFP_KERNEL);
2002         dist->irq_active_on_cpu = kzalloc(BITS_TO_LONGS(nr_cpus) * sizeof(long),
2003                                            GFP_KERNEL);
2004         if (!dist->irq_sgi_sources ||
2005             !dist->irq_spi_cpu ||
2006             !dist->irq_spi_target ||
2007             !dist->irq_pending_on_cpu ||
2008             !dist->irq_active_on_cpu) {
2009                 ret = -ENOMEM;
2010                 goto out;
2011         }
2012
2013         for (i = 0; i < nr_cpus; i++)
2014                 ret |= vgic_init_bitmap(&dist->irq_spi_target[i],
2015                                         nr_cpus, nr_irqs);
2016
2017         if (ret)
2018                 goto out;
2019
2020         ret = kvm->arch.vgic.vm_ops.init_model(kvm);
2021         if (ret)
2022                 goto out;
2023
2024         kvm_for_each_vcpu(vcpu_id, vcpu, kvm) {
2025                 ret = vgic_vcpu_init_maps(vcpu, nr_irqs);
2026                 if (ret) {
2027                         kvm_err("VGIC: Failed to allocate vcpu memory\n");
2028                         break;
2029                 }
2030
2031                 /*
2032                  * Enable and configure all SGIs to be edge-triggere and
2033                  * configure all PPIs as level-triggered.
2034                  */
2035                 for (i = 0; i < VGIC_NR_PRIVATE_IRQS; i++) {
2036                         if (i < VGIC_NR_SGIS) {
2037                                 /* SGIs */
2038                                 vgic_bitmap_set_irq_val(&dist->irq_enabled,
2039                                                         vcpu->vcpu_id, i, 1);
2040                                 vgic_bitmap_set_irq_val(&dist->irq_cfg,
2041                                                         vcpu->vcpu_id, i,
2042                                                         VGIC_CFG_EDGE);
2043                         } else if (i < VGIC_NR_PRIVATE_IRQS) {
2044                                 /* PPIs */
2045                                 vgic_bitmap_set_irq_val(&dist->irq_cfg,
2046                                                         vcpu->vcpu_id, i,
2047                                                         VGIC_CFG_LEVEL);
2048                         }
2049                 }
2050
2051                 vgic_enable(vcpu);
2052         }
2053
2054 out:
2055         if (ret)
2056                 kvm_vgic_destroy(kvm);
2057
2058         return ret;
2059 }
2060
2061 static int init_vgic_model(struct kvm *kvm, int type)
2062 {
2063         switch (type) {
2064         case KVM_DEV_TYPE_ARM_VGIC_V2:
2065                 vgic_v2_init_emulation(kvm);
2066                 break;
2067 #ifdef CONFIG_KVM_ARM_VGIC_V3
2068         case KVM_DEV_TYPE_ARM_VGIC_V3:
2069                 vgic_v3_init_emulation(kvm);
2070                 break;
2071 #endif
2072         default:
2073                 return -ENODEV;
2074         }
2075
2076         if (atomic_read(&kvm->online_vcpus) > kvm->arch.max_vcpus)
2077                 return -E2BIG;
2078
2079         return 0;
2080 }
2081
2082 /**
2083  * kvm_vgic_early_init - Earliest possible vgic initialization stage
2084  *
2085  * No memory allocation should be performed here, only static init.
2086  */
2087 void kvm_vgic_early_init(struct kvm *kvm)
2088 {
2089         spin_lock_init(&kvm->arch.vgic.lock);
2090         spin_lock_init(&kvm->arch.vgic.irq_phys_map_lock);
2091         INIT_LIST_HEAD(&kvm->arch.vgic.irq_phys_map_list);
2092 }
2093
2094 int kvm_vgic_create(struct kvm *kvm, u32 type)
2095 {
2096         int i, vcpu_lock_idx = -1, ret;
2097         struct kvm_vcpu *vcpu;
2098
2099         mutex_lock(&kvm->lock);
2100
2101         if (irqchip_in_kernel(kvm)) {
2102                 ret = -EEXIST;
2103                 goto out;
2104         }
2105
2106         /*
2107          * This function is also called by the KVM_CREATE_IRQCHIP handler,
2108          * which had no chance yet to check the availability of the GICv2
2109          * emulation. So check this here again. KVM_CREATE_DEVICE does
2110          * the proper checks already.
2111          */
2112         if (type == KVM_DEV_TYPE_ARM_VGIC_V2 && !vgic->can_emulate_gicv2) {
2113                 ret = -ENODEV;
2114                 goto out;
2115         }
2116
2117         /*
2118          * Any time a vcpu is run, vcpu_load is called which tries to grab the
2119          * vcpu->mutex.  By grabbing the vcpu->mutex of all VCPUs we ensure
2120          * that no other VCPUs are run while we create the vgic.
2121          */
2122         ret = -EBUSY;
2123         kvm_for_each_vcpu(i, vcpu, kvm) {
2124                 if (!mutex_trylock(&vcpu->mutex))
2125                         goto out_unlock;
2126                 vcpu_lock_idx = i;
2127         }
2128
2129         kvm_for_each_vcpu(i, vcpu, kvm) {
2130                 if (vcpu->arch.has_run_once)
2131                         goto out_unlock;
2132         }
2133         ret = 0;
2134
2135         ret = init_vgic_model(kvm, type);
2136         if (ret)
2137                 goto out_unlock;
2138
2139         kvm->arch.vgic.in_kernel = true;
2140         kvm->arch.vgic.vgic_model = type;
2141         kvm->arch.vgic.vctrl_base = vgic->vctrl_base;
2142         kvm->arch.vgic.vgic_dist_base = VGIC_ADDR_UNDEF;
2143         kvm->arch.vgic.vgic_cpu_base = VGIC_ADDR_UNDEF;
2144         kvm->arch.vgic.vgic_redist_base = VGIC_ADDR_UNDEF;
2145
2146 out_unlock:
2147         for (; vcpu_lock_idx >= 0; vcpu_lock_idx--) {
2148                 vcpu = kvm_get_vcpu(kvm, vcpu_lock_idx);
2149                 mutex_unlock(&vcpu->mutex);
2150         }
2151
2152 out:
2153         mutex_unlock(&kvm->lock);
2154         return ret;
2155 }
2156
2157 static int vgic_ioaddr_overlap(struct kvm *kvm)
2158 {
2159         phys_addr_t dist = kvm->arch.vgic.vgic_dist_base;
2160         phys_addr_t cpu = kvm->arch.vgic.vgic_cpu_base;
2161
2162         if (IS_VGIC_ADDR_UNDEF(dist) || IS_VGIC_ADDR_UNDEF(cpu))
2163                 return 0;
2164         if ((dist <= cpu && dist + KVM_VGIC_V2_DIST_SIZE > cpu) ||
2165             (cpu <= dist && cpu + KVM_VGIC_V2_CPU_SIZE > dist))
2166                 return -EBUSY;
2167         return 0;
2168 }
2169
2170 static int vgic_ioaddr_assign(struct kvm *kvm, phys_addr_t *ioaddr,
2171                               phys_addr_t addr, phys_addr_t size)
2172 {
2173         int ret;
2174
2175         if (addr & ~KVM_PHYS_MASK)
2176                 return -E2BIG;
2177
2178         if (addr & (SZ_4K - 1))
2179                 return -EINVAL;
2180
2181         if (!IS_VGIC_ADDR_UNDEF(*ioaddr))
2182                 return -EEXIST;
2183         if (addr + size < addr)
2184                 return -EINVAL;
2185
2186         *ioaddr = addr;
2187         ret = vgic_ioaddr_overlap(kvm);
2188         if (ret)
2189                 *ioaddr = VGIC_ADDR_UNDEF;
2190
2191         return ret;
2192 }
2193
2194 /**
2195  * kvm_vgic_addr - set or get vgic VM base addresses
2196  * @kvm:   pointer to the vm struct
2197  * @type:  the VGIC addr type, one of KVM_VGIC_V[23]_ADDR_TYPE_XXX
2198  * @addr:  pointer to address value
2199  * @write: if true set the address in the VM address space, if false read the
2200  *          address
2201  *
2202  * Set or get the vgic base addresses for the distributor and the virtual CPU
2203  * interface in the VM physical address space.  These addresses are properties
2204  * of the emulated core/SoC and therefore user space initially knows this
2205  * information.
2206  */
2207 int kvm_vgic_addr(struct kvm *kvm, unsigned long type, u64 *addr, bool write)
2208 {
2209         int r = 0;
2210         struct vgic_dist *vgic = &kvm->arch.vgic;
2211         int type_needed;
2212         phys_addr_t *addr_ptr, block_size;
2213         phys_addr_t alignment;
2214
2215         mutex_lock(&kvm->lock);
2216         switch (type) {
2217         case KVM_VGIC_V2_ADDR_TYPE_DIST:
2218                 type_needed = KVM_DEV_TYPE_ARM_VGIC_V2;
2219                 addr_ptr = &vgic->vgic_dist_base;
2220                 block_size = KVM_VGIC_V2_DIST_SIZE;
2221                 alignment = SZ_4K;
2222                 break;
2223         case KVM_VGIC_V2_ADDR_TYPE_CPU:
2224                 type_needed = KVM_DEV_TYPE_ARM_VGIC_V2;
2225                 addr_ptr = &vgic->vgic_cpu_base;
2226                 block_size = KVM_VGIC_V2_CPU_SIZE;
2227                 alignment = SZ_4K;
2228                 break;
2229 #ifdef CONFIG_KVM_ARM_VGIC_V3
2230         case KVM_VGIC_V3_ADDR_TYPE_DIST:
2231                 type_needed = KVM_DEV_TYPE_ARM_VGIC_V3;
2232                 addr_ptr = &vgic->vgic_dist_base;
2233                 block_size = KVM_VGIC_V3_DIST_SIZE;
2234                 alignment = SZ_64K;
2235                 break;
2236         case KVM_VGIC_V3_ADDR_TYPE_REDIST:
2237                 type_needed = KVM_DEV_TYPE_ARM_VGIC_V3;
2238                 addr_ptr = &vgic->vgic_redist_base;
2239                 block_size = KVM_VGIC_V3_REDIST_SIZE;
2240                 alignment = SZ_64K;
2241                 break;
2242 #endif
2243         default:
2244                 r = -ENODEV;
2245                 goto out;
2246         }
2247
2248         if (vgic->vgic_model != type_needed) {
2249                 r = -ENODEV;
2250                 goto out;
2251         }
2252
2253         if (write) {
2254                 if (!IS_ALIGNED(*addr, alignment))
2255                         r = -EINVAL;
2256                 else
2257                         r = vgic_ioaddr_assign(kvm, addr_ptr, *addr,
2258                                                block_size);
2259         } else {
2260                 *addr = *addr_ptr;
2261         }
2262
2263 out:
2264         mutex_unlock(&kvm->lock);
2265         return r;
2266 }
2267
2268 int vgic_set_common_attr(struct kvm_device *dev, struct kvm_device_attr *attr)
2269 {
2270         int r;
2271
2272         switch (attr->group) {
2273         case KVM_DEV_ARM_VGIC_GRP_ADDR: {
2274                 u64 __user *uaddr = (u64 __user *)(long)attr->addr;
2275                 u64 addr;
2276                 unsigned long type = (unsigned long)attr->attr;
2277
2278                 if (copy_from_user(&addr, uaddr, sizeof(addr)))
2279                         return -EFAULT;
2280
2281                 r = kvm_vgic_addr(dev->kvm, type, &addr, true);
2282                 return (r == -ENODEV) ? -ENXIO : r;
2283         }
2284         case KVM_DEV_ARM_VGIC_GRP_NR_IRQS: {
2285                 u32 __user *uaddr = (u32 __user *)(long)attr->addr;
2286                 u32 val;
2287                 int ret = 0;
2288
2289                 if (get_user(val, uaddr))
2290                         return -EFAULT;
2291
2292                 /*
2293                  * We require:
2294                  * - at least 32 SPIs on top of the 16 SGIs and 16 PPIs
2295                  * - at most 1024 interrupts
2296                  * - a multiple of 32 interrupts
2297                  */
2298                 if (val < (VGIC_NR_PRIVATE_IRQS + 32) ||
2299                     val > VGIC_MAX_IRQS ||
2300                     (val & 31))
2301                         return -EINVAL;
2302
2303                 mutex_lock(&dev->kvm->lock);
2304
2305                 if (vgic_ready(dev->kvm) || dev->kvm->arch.vgic.nr_irqs)
2306                         ret = -EBUSY;
2307                 else
2308                         dev->kvm->arch.vgic.nr_irqs = val;
2309
2310                 mutex_unlock(&dev->kvm->lock);
2311
2312                 return ret;
2313         }
2314         case KVM_DEV_ARM_VGIC_GRP_CTRL: {
2315                 switch (attr->attr) {
2316                 case KVM_DEV_ARM_VGIC_CTRL_INIT:
2317                         r = vgic_init(dev->kvm);
2318                         return r;
2319                 }
2320                 break;
2321         }
2322         }
2323
2324         return -ENXIO;
2325 }
2326
2327 int vgic_get_common_attr(struct kvm_device *dev, struct kvm_device_attr *attr)
2328 {
2329         int r = -ENXIO;
2330
2331         switch (attr->group) {
2332         case KVM_DEV_ARM_VGIC_GRP_ADDR: {
2333                 u64 __user *uaddr = (u64 __user *)(long)attr->addr;
2334                 u64 addr;
2335                 unsigned long type = (unsigned long)attr->attr;
2336
2337                 r = kvm_vgic_addr(dev->kvm, type, &addr, false);
2338                 if (r)
2339                         return (r == -ENODEV) ? -ENXIO : r;
2340
2341                 if (copy_to_user(uaddr, &addr, sizeof(addr)))
2342                         return -EFAULT;
2343                 break;
2344         }
2345         case KVM_DEV_ARM_VGIC_GRP_NR_IRQS: {
2346                 u32 __user *uaddr = (u32 __user *)(long)attr->addr;
2347
2348                 r = put_user(dev->kvm->arch.vgic.nr_irqs, uaddr);
2349                 break;
2350         }
2351
2352         }
2353
2354         return r;
2355 }
2356
2357 int vgic_has_attr_regs(const struct vgic_io_range *ranges, phys_addr_t offset)
2358 {
2359         if (vgic_find_range(ranges, 4, offset))
2360                 return 0;
2361         else
2362                 return -ENXIO;
2363 }
2364
2365 static void vgic_init_maintenance_interrupt(void *info)
2366 {
2367         enable_percpu_irq(vgic->maint_irq, 0);
2368 }
2369
2370 static int vgic_cpu_notify(struct notifier_block *self,
2371                            unsigned long action, void *cpu)
2372 {
2373         switch (action) {
2374         case CPU_STARTING:
2375         case CPU_STARTING_FROZEN:
2376                 vgic_init_maintenance_interrupt(NULL);
2377                 break;
2378         case CPU_DYING:
2379         case CPU_DYING_FROZEN:
2380                 disable_percpu_irq(vgic->maint_irq);
2381                 break;
2382         }
2383
2384         return NOTIFY_OK;
2385 }
2386
2387 static struct notifier_block vgic_cpu_nb = {
2388         .notifier_call = vgic_cpu_notify,
2389 };
2390
2391 static int kvm_vgic_probe(void)
2392 {
2393         const struct gic_kvm_info *gic_kvm_info;
2394         int ret;
2395
2396         gic_kvm_info = gic_get_kvm_info();
2397         if (!gic_kvm_info)
2398                 return -ENODEV;
2399
2400         switch (gic_kvm_info->type) {
2401         case GIC_V2:
2402                 ret = vgic_v2_probe(gic_kvm_info, &vgic_ops, &vgic);
2403                 break;
2404         case GIC_V3:
2405                 ret = vgic_v3_probe(gic_kvm_info, &vgic_ops, &vgic);
2406                 break;
2407         default:
2408                 ret = -ENODEV;
2409         }
2410
2411         return ret;
2412 }
2413
2414 int kvm_vgic_hyp_init(void)
2415 {
2416         int ret;
2417
2418         ret = kvm_vgic_probe();
2419         if (ret) {
2420                 kvm_err("error: KVM vGIC probing failed\n");
2421                 return ret;
2422         }
2423
2424         ret = request_percpu_irq(vgic->maint_irq, vgic_maintenance_handler,
2425                                  "vgic", kvm_get_running_vcpus());
2426         if (ret) {
2427                 kvm_err("Cannot register interrupt %d\n", vgic->maint_irq);
2428                 return ret;
2429         }
2430
2431         ret = __register_cpu_notifier(&vgic_cpu_nb);
2432         if (ret) {
2433                 kvm_err("Cannot register vgic CPU notifier\n");
2434                 goto out_free_irq;
2435         }
2436
2437         on_each_cpu(vgic_init_maintenance_interrupt, NULL, 1);
2438
2439         return 0;
2440
2441 out_free_irq:
2442         free_percpu_irq(vgic->maint_irq, kvm_get_running_vcpus());
2443         return ret;
2444 }
2445
2446 int kvm_irq_map_gsi(struct kvm *kvm,
2447                     struct kvm_kernel_irq_routing_entry *entries,
2448                     int gsi)
2449 {
2450         return 0;
2451 }
2452
2453 int kvm_irq_map_chip_pin(struct kvm *kvm, unsigned irqchip, unsigned pin)
2454 {
2455         return pin;
2456 }
2457
2458 int kvm_set_irq(struct kvm *kvm, int irq_source_id,
2459                 u32 irq, int level, bool line_status)
2460 {
2461         unsigned int spi = irq + VGIC_NR_PRIVATE_IRQS;
2462
2463         trace_kvm_set_irq(irq, level, irq_source_id);
2464
2465         BUG_ON(!vgic_initialized(kvm));
2466
2467         return kvm_vgic_inject_irq(kvm, 0, spi, level);
2468 }
2469
2470 /* MSI not implemented yet */
2471 int kvm_set_msi(struct kvm_kernel_irq_routing_entry *e,
2472                 struct kvm *kvm, int irq_source_id,
2473                 int level, bool line_status)
2474 {
2475         return 0;
2476 }