]> asedeno.scripts.mit.edu Git - linux.git/blob - virt/kvm/arm/vgic/vgic-its.c
bd1362e9c214bad96bc8c1d25ad8cc8d210a606b
[linux.git] / virt / kvm / arm / vgic / vgic-its.c
1 /*
2  * GICv3 ITS emulation
3  *
4  * Copyright (C) 2015,2016 ARM Ltd.
5  * Author: Andre Przywara <andre.przywara@arm.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <linux/cpu.h>
21 #include <linux/kvm.h>
22 #include <linux/kvm_host.h>
23 #include <linux/interrupt.h>
24 #include <linux/list.h>
25 #include <linux/uaccess.h>
26
27 #include <linux/irqchip/arm-gic-v3.h>
28
29 #include <asm/kvm_emulate.h>
30 #include <asm/kvm_arm.h>
31 #include <asm/kvm_mmu.h>
32
33 #include "vgic.h"
34 #include "vgic-mmio.h"
35
36 static int vgic_its_save_tables_v0(struct vgic_its *its);
37 static int vgic_its_restore_tables_v0(struct vgic_its *its);
38 static int vgic_its_commit_v0(struct vgic_its *its);
39
40 /*
41  * Creates a new (reference to a) struct vgic_irq for a given LPI.
42  * If this LPI is already mapped on another ITS, we increase its refcount
43  * and return a pointer to the existing structure.
44  * If this is a "new" LPI, we allocate and initialize a new struct vgic_irq.
45  * This function returns a pointer to the _unlocked_ structure.
46  */
47 static struct vgic_irq *vgic_add_lpi(struct kvm *kvm, u32 intid)
48 {
49         struct vgic_dist *dist = &kvm->arch.vgic;
50         struct vgic_irq *irq = vgic_get_irq(kvm, NULL, intid), *oldirq;
51
52         /* In this case there is no put, since we keep the reference. */
53         if (irq)
54                 return irq;
55
56         irq = kzalloc(sizeof(struct vgic_irq), GFP_KERNEL);
57         if (!irq)
58                 return ERR_PTR(-ENOMEM);
59
60         INIT_LIST_HEAD(&irq->lpi_list);
61         INIT_LIST_HEAD(&irq->ap_list);
62         spin_lock_init(&irq->irq_lock);
63
64         irq->config = VGIC_CONFIG_EDGE;
65         kref_init(&irq->refcount);
66         irq->intid = intid;
67
68         spin_lock(&dist->lpi_list_lock);
69
70         /*
71          * There could be a race with another vgic_add_lpi(), so we need to
72          * check that we don't add a second list entry with the same LPI.
73          */
74         list_for_each_entry(oldirq, &dist->lpi_list_head, lpi_list) {
75                 if (oldirq->intid != intid)
76                         continue;
77
78                 /* Someone was faster with adding this LPI, lets use that. */
79                 kfree(irq);
80                 irq = oldirq;
81
82                 /*
83                  * This increases the refcount, the caller is expected to
84                  * call vgic_put_irq() on the returned pointer once it's
85                  * finished with the IRQ.
86                  */
87                 vgic_get_irq_kref(irq);
88
89                 goto out_unlock;
90         }
91
92         list_add_tail(&irq->lpi_list, &dist->lpi_list_head);
93         dist->lpi_list_count++;
94
95 out_unlock:
96         spin_unlock(&dist->lpi_list_lock);
97
98         return irq;
99 }
100
101 struct its_device {
102         struct list_head dev_list;
103
104         /* the head for the list of ITTEs */
105         struct list_head itt_head;
106         u32 num_eventid_bits;
107         gpa_t itt_addr;
108         u32 device_id;
109 };
110
111 #define COLLECTION_NOT_MAPPED ((u32)~0)
112
113 struct its_collection {
114         struct list_head coll_list;
115
116         u32 collection_id;
117         u32 target_addr;
118 };
119
120 #define its_is_collection_mapped(coll) ((coll) && \
121                                 ((coll)->target_addr != COLLECTION_NOT_MAPPED))
122
123 struct its_ite {
124         struct list_head ite_list;
125
126         struct vgic_irq *irq;
127         struct its_collection *collection;
128         u32 lpi;
129         u32 event_id;
130 };
131
132 /**
133  * struct vgic_its_abi - ITS abi ops and settings
134  * @cte_esz: collection table entry size
135  * @dte_esz: device table entry size
136  * @ite_esz: interrupt translation table entry size
137  * @save tables: save the ITS tables into guest RAM
138  * @restore_tables: restore the ITS internal structs from tables
139  *  stored in guest RAM
140  * @commit: initialize the registers which expose the ABI settings,
141  *  especially the entry sizes
142  */
143 struct vgic_its_abi {
144         int cte_esz;
145         int dte_esz;
146         int ite_esz;
147         int (*save_tables)(struct vgic_its *its);
148         int (*restore_tables)(struct vgic_its *its);
149         int (*commit)(struct vgic_its *its);
150 };
151
152 static const struct vgic_its_abi its_table_abi_versions[] = {
153         [0] = {.cte_esz = 8, .dte_esz = 8, .ite_esz = 8,
154          .save_tables = vgic_its_save_tables_v0,
155          .restore_tables = vgic_its_restore_tables_v0,
156          .commit = vgic_its_commit_v0,
157         },
158 };
159
160 #define NR_ITS_ABIS     ARRAY_SIZE(its_table_abi_versions)
161
162 inline const struct vgic_its_abi *vgic_its_get_abi(struct vgic_its *its)
163 {
164         return &its_table_abi_versions[its->abi_rev];
165 }
166
167 int vgic_its_set_abi(struct vgic_its *its, int rev)
168 {
169         const struct vgic_its_abi *abi;
170
171         its->abi_rev = rev;
172         abi = vgic_its_get_abi(its);
173         return abi->commit(its);
174 }
175
176 /*
177  * Find and returns a device in the device table for an ITS.
178  * Must be called with the its_lock mutex held.
179  */
180 static struct its_device *find_its_device(struct vgic_its *its, u32 device_id)
181 {
182         struct its_device *device;
183
184         list_for_each_entry(device, &its->device_list, dev_list)
185                 if (device_id == device->device_id)
186                         return device;
187
188         return NULL;
189 }
190
191 /*
192  * Find and returns an interrupt translation table entry (ITTE) for a given
193  * Device ID/Event ID pair on an ITS.
194  * Must be called with the its_lock mutex held.
195  */
196 static struct its_ite *find_ite(struct vgic_its *its, u32 device_id,
197                                   u32 event_id)
198 {
199         struct its_device *device;
200         struct its_ite *ite;
201
202         device = find_its_device(its, device_id);
203         if (device == NULL)
204                 return NULL;
205
206         list_for_each_entry(ite, &device->itt_head, ite_list)
207                 if (ite->event_id == event_id)
208                         return ite;
209
210         return NULL;
211 }
212
213 /* To be used as an iterator this macro misses the enclosing parentheses */
214 #define for_each_lpi_its(dev, ite, its) \
215         list_for_each_entry(dev, &(its)->device_list, dev_list) \
216                 list_for_each_entry(ite, &(dev)->itt_head, ite_list)
217
218 /*
219  * We only implement 48 bits of PA at the moment, although the ITS
220  * supports more. Let's be restrictive here.
221  */
222 #define BASER_ADDRESS(x)        ((x) & GENMASK_ULL(47, 16))
223 #define CBASER_ADDRESS(x)       ((x) & GENMASK_ULL(47, 12))
224 #define PENDBASER_ADDRESS(x)    ((x) & GENMASK_ULL(47, 16))
225 #define PROPBASER_ADDRESS(x)    ((x) & GENMASK_ULL(47, 12))
226
227 #define GIC_LPI_OFFSET 8192
228
229 #define VITS_TYPER_IDBITS 16
230 #define VITS_TYPER_DEVBITS 16
231
232 /*
233  * Finds and returns a collection in the ITS collection table.
234  * Must be called with the its_lock mutex held.
235  */
236 static struct its_collection *find_collection(struct vgic_its *its, int coll_id)
237 {
238         struct its_collection *collection;
239
240         list_for_each_entry(collection, &its->collection_list, coll_list) {
241                 if (coll_id == collection->collection_id)
242                         return collection;
243         }
244
245         return NULL;
246 }
247
248 #define LPI_PROP_ENABLE_BIT(p)  ((p) & LPI_PROP_ENABLED)
249 #define LPI_PROP_PRIORITY(p)    ((p) & 0xfc)
250
251 /*
252  * Reads the configuration data for a given LPI from guest memory and
253  * updates the fields in struct vgic_irq.
254  * If filter_vcpu is not NULL, applies only if the IRQ is targeting this
255  * VCPU. Unconditionally applies if filter_vcpu is NULL.
256  */
257 static int update_lpi_config(struct kvm *kvm, struct vgic_irq *irq,
258                              struct kvm_vcpu *filter_vcpu)
259 {
260         u64 propbase = PROPBASER_ADDRESS(kvm->arch.vgic.propbaser);
261         u8 prop;
262         int ret;
263
264         ret = kvm_read_guest(kvm, propbase + irq->intid - GIC_LPI_OFFSET,
265                              &prop, 1);
266
267         if (ret)
268                 return ret;
269
270         spin_lock(&irq->irq_lock);
271
272         if (!filter_vcpu || filter_vcpu == irq->target_vcpu) {
273                 irq->priority = LPI_PROP_PRIORITY(prop);
274                 irq->enabled = LPI_PROP_ENABLE_BIT(prop);
275
276                 vgic_queue_irq_unlock(kvm, irq);
277         } else {
278                 spin_unlock(&irq->irq_lock);
279         }
280
281         return 0;
282 }
283
284 /*
285  * Create a snapshot of the current LPI list, so that we can enumerate all
286  * LPIs without holding any lock.
287  * Returns the array length and puts the kmalloc'ed array into intid_ptr.
288  */
289 static int vgic_copy_lpi_list(struct kvm *kvm, u32 **intid_ptr)
290 {
291         struct vgic_dist *dist = &kvm->arch.vgic;
292         struct vgic_irq *irq;
293         u32 *intids;
294         int irq_count = dist->lpi_list_count, i = 0;
295
296         /*
297          * We use the current value of the list length, which may change
298          * after the kmalloc. We don't care, because the guest shouldn't
299          * change anything while the command handling is still running,
300          * and in the worst case we would miss a new IRQ, which one wouldn't
301          * expect to be covered by this command anyway.
302          */
303         intids = kmalloc_array(irq_count, sizeof(intids[0]), GFP_KERNEL);
304         if (!intids)
305                 return -ENOMEM;
306
307         spin_lock(&dist->lpi_list_lock);
308         list_for_each_entry(irq, &dist->lpi_list_head, lpi_list) {
309                 /* We don't need to "get" the IRQ, as we hold the list lock. */
310                 intids[i] = irq->intid;
311                 if (++i == irq_count)
312                         break;
313         }
314         spin_unlock(&dist->lpi_list_lock);
315
316         *intid_ptr = intids;
317         return irq_count;
318 }
319
320 /*
321  * Promotes the ITS view of affinity of an ITTE (which redistributor this LPI
322  * is targeting) to the VGIC's view, which deals with target VCPUs.
323  * Needs to be called whenever either the collection for a LPIs has
324  * changed or the collection itself got retargeted.
325  */
326 static void update_affinity_ite(struct kvm *kvm, struct its_ite *ite)
327 {
328         struct kvm_vcpu *vcpu;
329
330         if (!its_is_collection_mapped(ite->collection))
331                 return;
332
333         vcpu = kvm_get_vcpu(kvm, ite->collection->target_addr);
334
335         spin_lock(&ite->irq->irq_lock);
336         ite->irq->target_vcpu = vcpu;
337         spin_unlock(&ite->irq->irq_lock);
338 }
339
340 /*
341  * Updates the target VCPU for every LPI targeting this collection.
342  * Must be called with the its_lock mutex held.
343  */
344 static void update_affinity_collection(struct kvm *kvm, struct vgic_its *its,
345                                        struct its_collection *coll)
346 {
347         struct its_device *device;
348         struct its_ite *ite;
349
350         for_each_lpi_its(device, ite, its) {
351                 if (!ite->collection || coll != ite->collection)
352                         continue;
353
354                 update_affinity_ite(kvm, ite);
355         }
356 }
357
358 static u32 max_lpis_propbaser(u64 propbaser)
359 {
360         int nr_idbits = (propbaser & 0x1f) + 1;
361
362         return 1U << min(nr_idbits, INTERRUPT_ID_BITS_ITS);
363 }
364
365 /*
366  * Scan the whole LPI pending table and sync the pending bit in there
367  * with our own data structures. This relies on the LPI being
368  * mapped before.
369  */
370 static int its_sync_lpi_pending_table(struct kvm_vcpu *vcpu)
371 {
372         gpa_t pendbase = PENDBASER_ADDRESS(vcpu->arch.vgic_cpu.pendbaser);
373         struct vgic_irq *irq;
374         int last_byte_offset = -1;
375         int ret = 0;
376         u32 *intids;
377         int nr_irqs, i;
378
379         nr_irqs = vgic_copy_lpi_list(vcpu->kvm, &intids);
380         if (nr_irqs < 0)
381                 return nr_irqs;
382
383         for (i = 0; i < nr_irqs; i++) {
384                 int byte_offset, bit_nr;
385                 u8 pendmask;
386
387                 byte_offset = intids[i] / BITS_PER_BYTE;
388                 bit_nr = intids[i] % BITS_PER_BYTE;
389
390                 /*
391                  * For contiguously allocated LPIs chances are we just read
392                  * this very same byte in the last iteration. Reuse that.
393                  */
394                 if (byte_offset != last_byte_offset) {
395                         ret = kvm_read_guest(vcpu->kvm, pendbase + byte_offset,
396                                              &pendmask, 1);
397                         if (ret) {
398                                 kfree(intids);
399                                 return ret;
400                         }
401                         last_byte_offset = byte_offset;
402                 }
403
404                 irq = vgic_get_irq(vcpu->kvm, NULL, intids[i]);
405                 spin_lock(&irq->irq_lock);
406                 irq->pending_latch = pendmask & (1U << bit_nr);
407                 vgic_queue_irq_unlock(vcpu->kvm, irq);
408                 vgic_put_irq(vcpu->kvm, irq);
409         }
410
411         kfree(intids);
412
413         return ret;
414 }
415
416 static unsigned long vgic_mmio_read_its_typer(struct kvm *kvm,
417                                               struct vgic_its *its,
418                                               gpa_t addr, unsigned int len)
419 {
420         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
421         u64 reg = GITS_TYPER_PLPIS;
422
423         /*
424          * We use linear CPU numbers for redistributor addressing,
425          * so GITS_TYPER.PTA is 0.
426          * Also we force all PROPBASER registers to be the same, so
427          * CommonLPIAff is 0 as well.
428          * To avoid memory waste in the guest, we keep the number of IDBits and
429          * DevBits low - as least for the time being.
430          */
431         reg |= GIC_ENCODE_SZ(VITS_TYPER_DEVBITS, 5) << GITS_TYPER_DEVBITS_SHIFT;
432         reg |= GIC_ENCODE_SZ(VITS_TYPER_IDBITS, 5) << GITS_TYPER_IDBITS_SHIFT;
433         reg |= GIC_ENCODE_SZ(abi->ite_esz, 4) << GITS_TYPER_ITT_ENTRY_SIZE_SHIFT;
434
435         return extract_bytes(reg, addr & 7, len);
436 }
437
438 static unsigned long vgic_mmio_read_its_iidr(struct kvm *kvm,
439                                              struct vgic_its *its,
440                                              gpa_t addr, unsigned int len)
441 {
442         u32 val;
443
444         val = (its->abi_rev << GITS_IIDR_REV_SHIFT) & GITS_IIDR_REV_MASK;
445         val |= (PRODUCT_ID_KVM << GITS_IIDR_PRODUCTID_SHIFT) | IMPLEMENTER_ARM;
446         return val;
447 }
448
449 static int vgic_mmio_uaccess_write_its_iidr(struct kvm *kvm,
450                                             struct vgic_its *its,
451                                             gpa_t addr, unsigned int len,
452                                             unsigned long val)
453 {
454         u32 rev = GITS_IIDR_REV(val);
455
456         if (rev >= NR_ITS_ABIS)
457                 return -EINVAL;
458         return vgic_its_set_abi(its, rev);
459 }
460
461 static unsigned long vgic_mmio_read_its_idregs(struct kvm *kvm,
462                                                struct vgic_its *its,
463                                                gpa_t addr, unsigned int len)
464 {
465         switch (addr & 0xffff) {
466         case GITS_PIDR0:
467                 return 0x92;    /* part number, bits[7:0] */
468         case GITS_PIDR1:
469                 return 0xb4;    /* part number, bits[11:8] */
470         case GITS_PIDR2:
471                 return GIC_PIDR2_ARCH_GICv3 | 0x0b;
472         case GITS_PIDR4:
473                 return 0x40;    /* This is a 64K software visible page */
474         /* The following are the ID registers for (any) GIC. */
475         case GITS_CIDR0:
476                 return 0x0d;
477         case GITS_CIDR1:
478                 return 0xf0;
479         case GITS_CIDR2:
480                 return 0x05;
481         case GITS_CIDR3:
482                 return 0xb1;
483         }
484
485         return 0;
486 }
487
488 /*
489  * Find the target VCPU and the LPI number for a given devid/eventid pair
490  * and make this IRQ pending, possibly injecting it.
491  * Must be called with the its_lock mutex held.
492  * Returns 0 on success, a positive error value for any ITS mapping
493  * related errors and negative error values for generic errors.
494  */
495 static int vgic_its_trigger_msi(struct kvm *kvm, struct vgic_its *its,
496                                 u32 devid, u32 eventid)
497 {
498         struct kvm_vcpu *vcpu;
499         struct its_ite *ite;
500
501         if (!its->enabled)
502                 return -EBUSY;
503
504         ite = find_ite(its, devid, eventid);
505         if (!ite || !its_is_collection_mapped(ite->collection))
506                 return E_ITS_INT_UNMAPPED_INTERRUPT;
507
508         vcpu = kvm_get_vcpu(kvm, ite->collection->target_addr);
509         if (!vcpu)
510                 return E_ITS_INT_UNMAPPED_INTERRUPT;
511
512         if (!vcpu->arch.vgic_cpu.lpis_enabled)
513                 return -EBUSY;
514
515         spin_lock(&ite->irq->irq_lock);
516         ite->irq->pending_latch = true;
517         vgic_queue_irq_unlock(kvm, ite->irq);
518
519         return 0;
520 }
521
522 static struct vgic_io_device *vgic_get_its_iodev(struct kvm_io_device *dev)
523 {
524         struct vgic_io_device *iodev;
525
526         if (dev->ops != &kvm_io_gic_ops)
527                 return NULL;
528
529         iodev = container_of(dev, struct vgic_io_device, dev);
530
531         if (iodev->iodev_type != IODEV_ITS)
532                 return NULL;
533
534         return iodev;
535 }
536
537 /*
538  * Queries the KVM IO bus framework to get the ITS pointer from the given
539  * doorbell address.
540  * We then call vgic_its_trigger_msi() with the decoded data.
541  * According to the KVM_SIGNAL_MSI API description returns 1 on success.
542  */
543 int vgic_its_inject_msi(struct kvm *kvm, struct kvm_msi *msi)
544 {
545         u64 address;
546         struct kvm_io_device *kvm_io_dev;
547         struct vgic_io_device *iodev;
548         int ret;
549
550         if (!vgic_has_its(kvm))
551                 return -ENODEV;
552
553         if (!(msi->flags & KVM_MSI_VALID_DEVID))
554                 return -EINVAL;
555
556         address = (u64)msi->address_hi << 32 | msi->address_lo;
557
558         kvm_io_dev = kvm_io_bus_get_dev(kvm, KVM_MMIO_BUS, address);
559         if (!kvm_io_dev)
560                 return -EINVAL;
561
562         iodev = vgic_get_its_iodev(kvm_io_dev);
563         if (!iodev)
564                 return -EINVAL;
565
566         mutex_lock(&iodev->its->its_lock);
567         ret = vgic_its_trigger_msi(kvm, iodev->its, msi->devid, msi->data);
568         mutex_unlock(&iodev->its->its_lock);
569
570         if (ret < 0)
571                 return ret;
572
573         /*
574          * KVM_SIGNAL_MSI demands a return value > 0 for success and 0
575          * if the guest has blocked the MSI. So we map any LPI mapping
576          * related error to that.
577          */
578         if (ret)
579                 return 0;
580         else
581                 return 1;
582 }
583
584 /* Requires the its_lock to be held. */
585 static void its_free_ite(struct kvm *kvm, struct its_ite *ite)
586 {
587         list_del(&ite->ite_list);
588
589         /* This put matches the get in vgic_add_lpi. */
590         if (ite->irq)
591                 vgic_put_irq(kvm, ite->irq);
592
593         kfree(ite);
594 }
595
596 static u64 its_cmd_mask_field(u64 *its_cmd, int word, int shift, int size)
597 {
598         return (le64_to_cpu(its_cmd[word]) >> shift) & (BIT_ULL(size) - 1);
599 }
600
601 #define its_cmd_get_command(cmd)        its_cmd_mask_field(cmd, 0,  0,  8)
602 #define its_cmd_get_deviceid(cmd)       its_cmd_mask_field(cmd, 0, 32, 32)
603 #define its_cmd_get_size(cmd)           (its_cmd_mask_field(cmd, 1,  0,  5) + 1)
604 #define its_cmd_get_id(cmd)             its_cmd_mask_field(cmd, 1,  0, 32)
605 #define its_cmd_get_physical_id(cmd)    its_cmd_mask_field(cmd, 1, 32, 32)
606 #define its_cmd_get_collection(cmd)     its_cmd_mask_field(cmd, 2,  0, 16)
607 #define its_cmd_get_ittaddr(cmd)        (its_cmd_mask_field(cmd, 2,  8, 44) << 8)
608 #define its_cmd_get_target_addr(cmd)    its_cmd_mask_field(cmd, 2, 16, 32)
609 #define its_cmd_get_validbit(cmd)       its_cmd_mask_field(cmd, 2, 63,  1)
610
611 /*
612  * The DISCARD command frees an Interrupt Translation Table Entry (ITTE).
613  * Must be called with the its_lock mutex held.
614  */
615 static int vgic_its_cmd_handle_discard(struct kvm *kvm, struct vgic_its *its,
616                                        u64 *its_cmd)
617 {
618         u32 device_id = its_cmd_get_deviceid(its_cmd);
619         u32 event_id = its_cmd_get_id(its_cmd);
620         struct its_ite *ite;
621
622
623         ite = find_ite(its, device_id, event_id);
624         if (ite && ite->collection) {
625                 /*
626                  * Though the spec talks about removing the pending state, we
627                  * don't bother here since we clear the ITTE anyway and the
628                  * pending state is a property of the ITTE struct.
629                  */
630                 its_free_ite(kvm, ite);
631                 return 0;
632         }
633
634         return E_ITS_DISCARD_UNMAPPED_INTERRUPT;
635 }
636
637 /*
638  * The MOVI command moves an ITTE to a different collection.
639  * Must be called with the its_lock mutex held.
640  */
641 static int vgic_its_cmd_handle_movi(struct kvm *kvm, struct vgic_its *its,
642                                     u64 *its_cmd)
643 {
644         u32 device_id = its_cmd_get_deviceid(its_cmd);
645         u32 event_id = its_cmd_get_id(its_cmd);
646         u32 coll_id = its_cmd_get_collection(its_cmd);
647         struct kvm_vcpu *vcpu;
648         struct its_ite *ite;
649         struct its_collection *collection;
650
651         ite = find_ite(its, device_id, event_id);
652         if (!ite)
653                 return E_ITS_MOVI_UNMAPPED_INTERRUPT;
654
655         if (!its_is_collection_mapped(ite->collection))
656                 return E_ITS_MOVI_UNMAPPED_COLLECTION;
657
658         collection = find_collection(its, coll_id);
659         if (!its_is_collection_mapped(collection))
660                 return E_ITS_MOVI_UNMAPPED_COLLECTION;
661
662         ite->collection = collection;
663         vcpu = kvm_get_vcpu(kvm, collection->target_addr);
664
665         spin_lock(&ite->irq->irq_lock);
666         ite->irq->target_vcpu = vcpu;
667         spin_unlock(&ite->irq->irq_lock);
668
669         return 0;
670 }
671
672 /*
673  * Check whether an ID can be stored into the corresponding guest table.
674  * For a direct table this is pretty easy, but gets a bit nasty for
675  * indirect tables. We check whether the resulting guest physical address
676  * is actually valid (covered by a memslot and guest accessible).
677  * For this we have to read the respective first level entry.
678  */
679 static bool vgic_its_check_id(struct vgic_its *its, u64 baser, u32 id)
680 {
681         int l1_tbl_size = GITS_BASER_NR_PAGES(baser) * SZ_64K;
682         u64 indirect_ptr, type = GITS_BASER_TYPE(baser);
683         int esz = GITS_BASER_ENTRY_SIZE(baser);
684         int index;
685         gfn_t gfn;
686
687         switch (type) {
688         case GITS_BASER_TYPE_DEVICE:
689                 if (id >= BIT_ULL(VITS_TYPER_DEVBITS))
690                         return false;
691                 break;
692         case GITS_BASER_TYPE_COLLECTION:
693                 /* as GITS_TYPER.CIL == 0, ITS supports 16-bit collection ID */
694                 if (id >= BIT_ULL(16))
695                         return false;
696                 break;
697         default:
698                 return false;
699         }
700
701         if (!(baser & GITS_BASER_INDIRECT)) {
702                 phys_addr_t addr;
703
704                 if (id >= (l1_tbl_size / esz))
705                         return false;
706
707                 addr = BASER_ADDRESS(baser) + id * esz;
708                 gfn = addr >> PAGE_SHIFT;
709
710                 return kvm_is_visible_gfn(its->dev->kvm, gfn);
711         }
712
713         /* calculate and check the index into the 1st level */
714         index = id / (SZ_64K / esz);
715         if (index >= (l1_tbl_size / sizeof(u64)))
716                 return false;
717
718         /* Each 1st level entry is represented by a 64-bit value. */
719         if (kvm_read_guest(its->dev->kvm,
720                            BASER_ADDRESS(baser) + index * sizeof(indirect_ptr),
721                            &indirect_ptr, sizeof(indirect_ptr)))
722                 return false;
723
724         indirect_ptr = le64_to_cpu(indirect_ptr);
725
726         /* check the valid bit of the first level entry */
727         if (!(indirect_ptr & BIT_ULL(63)))
728                 return false;
729
730         /*
731          * Mask the guest physical address and calculate the frame number.
732          * Any address beyond our supported 48 bits of PA will be caught
733          * by the actual check in the final step.
734          */
735         indirect_ptr &= GENMASK_ULL(51, 16);
736
737         /* Find the address of the actual entry */
738         index = id % (SZ_64K / esz);
739         indirect_ptr += index * esz;
740         gfn = indirect_ptr >> PAGE_SHIFT;
741
742         return kvm_is_visible_gfn(its->dev->kvm, gfn);
743 }
744
745 static int vgic_its_alloc_collection(struct vgic_its *its,
746                                      struct its_collection **colp,
747                                      u32 coll_id)
748 {
749         struct its_collection *collection;
750
751         if (!vgic_its_check_id(its, its->baser_coll_table, coll_id))
752                 return E_ITS_MAPC_COLLECTION_OOR;
753
754         collection = kzalloc(sizeof(*collection), GFP_KERNEL);
755
756         collection->collection_id = coll_id;
757         collection->target_addr = COLLECTION_NOT_MAPPED;
758
759         list_add_tail(&collection->coll_list, &its->collection_list);
760         *colp = collection;
761
762         return 0;
763 }
764
765 static void vgic_its_free_collection(struct vgic_its *its, u32 coll_id)
766 {
767         struct its_collection *collection;
768         struct its_device *device;
769         struct its_ite *ite;
770
771         /*
772          * Clearing the mapping for that collection ID removes the
773          * entry from the list. If there wasn't any before, we can
774          * go home early.
775          */
776         collection = find_collection(its, coll_id);
777         if (!collection)
778                 return;
779
780         for_each_lpi_its(device, ite, its)
781                 if (ite->collection &&
782                     ite->collection->collection_id == coll_id)
783                         ite->collection = NULL;
784
785         list_del(&collection->coll_list);
786         kfree(collection);
787 }
788
789 /*
790  * The MAPTI and MAPI commands map LPIs to ITTEs.
791  * Must be called with its_lock mutex held.
792  */
793 static int vgic_its_cmd_handle_mapi(struct kvm *kvm, struct vgic_its *its,
794                                     u64 *its_cmd)
795 {
796         u32 device_id = its_cmd_get_deviceid(its_cmd);
797         u32 event_id = its_cmd_get_id(its_cmd);
798         u32 coll_id = its_cmd_get_collection(its_cmd);
799         struct its_ite *ite;
800         struct its_device *device;
801         struct its_collection *collection, *new_coll = NULL;
802         int lpi_nr;
803         struct vgic_irq *irq;
804
805         device = find_its_device(its, device_id);
806         if (!device)
807                 return E_ITS_MAPTI_UNMAPPED_DEVICE;
808
809         if (event_id >= BIT_ULL(device->num_eventid_bits))
810                 return E_ITS_MAPTI_ID_OOR;
811
812         if (its_cmd_get_command(its_cmd) == GITS_CMD_MAPTI)
813                 lpi_nr = its_cmd_get_physical_id(its_cmd);
814         else
815                 lpi_nr = event_id;
816         if (lpi_nr < GIC_LPI_OFFSET ||
817             lpi_nr >= max_lpis_propbaser(kvm->arch.vgic.propbaser))
818                 return E_ITS_MAPTI_PHYSICALID_OOR;
819
820         /* If there is an existing mapping, behavior is UNPREDICTABLE. */
821         if (find_ite(its, device_id, event_id))
822                 return 0;
823
824         collection = find_collection(its, coll_id);
825         if (!collection) {
826                 int ret = vgic_its_alloc_collection(its, &collection, coll_id);
827                 if (ret)
828                         return ret;
829                 new_coll = collection;
830         }
831
832         ite = kzalloc(sizeof(struct its_ite), GFP_KERNEL);
833         if (!ite) {
834                 if (new_coll)
835                         vgic_its_free_collection(its, coll_id);
836                 return -ENOMEM;
837         }
838
839         ite->event_id   = event_id;
840         list_add_tail(&ite->ite_list, &device->itt_head);
841
842         ite->collection = collection;
843         ite->lpi = lpi_nr;
844
845         irq = vgic_add_lpi(kvm, lpi_nr);
846         if (IS_ERR(irq)) {
847                 if (new_coll)
848                         vgic_its_free_collection(its, coll_id);
849                 its_free_ite(kvm, ite);
850                 return PTR_ERR(irq);
851         }
852         ite->irq = irq;
853
854         update_affinity_ite(kvm, ite);
855
856         /*
857          * We "cache" the configuration table entries in out struct vgic_irq's.
858          * However we only have those structs for mapped IRQs, so we read in
859          * the respective config data from memory here upon mapping the LPI.
860          */
861         update_lpi_config(kvm, ite->irq, NULL);
862
863         return 0;
864 }
865
866 /* Requires the its_lock to be held. */
867 static void vgic_its_unmap_device(struct kvm *kvm, struct its_device *device)
868 {
869         struct its_ite *ite, *temp;
870
871         /*
872          * The spec says that unmapping a device with still valid
873          * ITTEs associated is UNPREDICTABLE. We remove all ITTEs,
874          * since we cannot leave the memory unreferenced.
875          */
876         list_for_each_entry_safe(ite, temp, &device->itt_head, ite_list)
877                 its_free_ite(kvm, ite);
878
879         list_del(&device->dev_list);
880         kfree(device);
881 }
882
883 /*
884  * MAPD maps or unmaps a device ID to Interrupt Translation Tables (ITTs).
885  * Must be called with the its_lock mutex held.
886  */
887 static int vgic_its_cmd_handle_mapd(struct kvm *kvm, struct vgic_its *its,
888                                     u64 *its_cmd)
889 {
890         u32 device_id = its_cmd_get_deviceid(its_cmd);
891         bool valid = its_cmd_get_validbit(its_cmd);
892         u8 num_eventid_bits = its_cmd_get_size(its_cmd);
893         gpa_t itt_addr = its_cmd_get_ittaddr(its_cmd);
894         struct its_device *device;
895
896         if (!vgic_its_check_id(its, its->baser_device_table, device_id))
897                 return E_ITS_MAPD_DEVICE_OOR;
898
899         if (valid && num_eventid_bits > VITS_TYPER_IDBITS)
900                 return E_ITS_MAPD_ITTSIZE_OOR;
901
902         device = find_its_device(its, device_id);
903
904         /*
905          * The spec says that calling MAPD on an already mapped device
906          * invalidates all cached data for this device. We implement this
907          * by removing the mapping and re-establishing it.
908          */
909         if (device)
910                 vgic_its_unmap_device(kvm, device);
911
912         /*
913          * The spec does not say whether unmapping a not-mapped device
914          * is an error, so we are done in any case.
915          */
916         if (!valid)
917                 return 0;
918
919         device = kzalloc(sizeof(struct its_device), GFP_KERNEL);
920         if (!device)
921                 return -ENOMEM;
922
923         device->device_id = device_id;
924         device->num_eventid_bits = num_eventid_bits;
925         device->itt_addr = itt_addr;
926
927         INIT_LIST_HEAD(&device->itt_head);
928
929         list_add_tail(&device->dev_list, &its->device_list);
930
931         return 0;
932 }
933
934 /*
935  * The MAPC command maps collection IDs to redistributors.
936  * Must be called with the its_lock mutex held.
937  */
938 static int vgic_its_cmd_handle_mapc(struct kvm *kvm, struct vgic_its *its,
939                                     u64 *its_cmd)
940 {
941         u16 coll_id;
942         u32 target_addr;
943         struct its_collection *collection;
944         bool valid;
945
946         valid = its_cmd_get_validbit(its_cmd);
947         coll_id = its_cmd_get_collection(its_cmd);
948         target_addr = its_cmd_get_target_addr(its_cmd);
949
950         if (target_addr >= atomic_read(&kvm->online_vcpus))
951                 return E_ITS_MAPC_PROCNUM_OOR;
952
953         if (!valid) {
954                 vgic_its_free_collection(its, coll_id);
955         } else {
956                 collection = find_collection(its, coll_id);
957
958                 if (!collection) {
959                         int ret;
960
961                         ret = vgic_its_alloc_collection(its, &collection,
962                                                         coll_id);
963                         if (ret)
964                                 return ret;
965                         collection->target_addr = target_addr;
966                 } else {
967                         collection->target_addr = target_addr;
968                         update_affinity_collection(kvm, its, collection);
969                 }
970         }
971
972         return 0;
973 }
974
975 /*
976  * The CLEAR command removes the pending state for a particular LPI.
977  * Must be called with the its_lock mutex held.
978  */
979 static int vgic_its_cmd_handle_clear(struct kvm *kvm, struct vgic_its *its,
980                                      u64 *its_cmd)
981 {
982         u32 device_id = its_cmd_get_deviceid(its_cmd);
983         u32 event_id = its_cmd_get_id(its_cmd);
984         struct its_ite *ite;
985
986
987         ite = find_ite(its, device_id, event_id);
988         if (!ite)
989                 return E_ITS_CLEAR_UNMAPPED_INTERRUPT;
990
991         ite->irq->pending_latch = false;
992
993         return 0;
994 }
995
996 /*
997  * The INV command syncs the configuration bits from the memory table.
998  * Must be called with the its_lock mutex held.
999  */
1000 static int vgic_its_cmd_handle_inv(struct kvm *kvm, struct vgic_its *its,
1001                                    u64 *its_cmd)
1002 {
1003         u32 device_id = its_cmd_get_deviceid(its_cmd);
1004         u32 event_id = its_cmd_get_id(its_cmd);
1005         struct its_ite *ite;
1006
1007
1008         ite = find_ite(its, device_id, event_id);
1009         if (!ite)
1010                 return E_ITS_INV_UNMAPPED_INTERRUPT;
1011
1012         return update_lpi_config(kvm, ite->irq, NULL);
1013 }
1014
1015 /*
1016  * The INVALL command requests flushing of all IRQ data in this collection.
1017  * Find the VCPU mapped to that collection, then iterate over the VM's list
1018  * of mapped LPIs and update the configuration for each IRQ which targets
1019  * the specified vcpu. The configuration will be read from the in-memory
1020  * configuration table.
1021  * Must be called with the its_lock mutex held.
1022  */
1023 static int vgic_its_cmd_handle_invall(struct kvm *kvm, struct vgic_its *its,
1024                                       u64 *its_cmd)
1025 {
1026         u32 coll_id = its_cmd_get_collection(its_cmd);
1027         struct its_collection *collection;
1028         struct kvm_vcpu *vcpu;
1029         struct vgic_irq *irq;
1030         u32 *intids;
1031         int irq_count, i;
1032
1033         collection = find_collection(its, coll_id);
1034         if (!its_is_collection_mapped(collection))
1035                 return E_ITS_INVALL_UNMAPPED_COLLECTION;
1036
1037         vcpu = kvm_get_vcpu(kvm, collection->target_addr);
1038
1039         irq_count = vgic_copy_lpi_list(kvm, &intids);
1040         if (irq_count < 0)
1041                 return irq_count;
1042
1043         for (i = 0; i < irq_count; i++) {
1044                 irq = vgic_get_irq(kvm, NULL, intids[i]);
1045                 if (!irq)
1046                         continue;
1047                 update_lpi_config(kvm, irq, vcpu);
1048                 vgic_put_irq(kvm, irq);
1049         }
1050
1051         kfree(intids);
1052
1053         return 0;
1054 }
1055
1056 /*
1057  * The MOVALL command moves the pending state of all IRQs targeting one
1058  * redistributor to another. We don't hold the pending state in the VCPUs,
1059  * but in the IRQs instead, so there is really not much to do for us here.
1060  * However the spec says that no IRQ must target the old redistributor
1061  * afterwards, so we make sure that no LPI is using the associated target_vcpu.
1062  * This command affects all LPIs in the system that target that redistributor.
1063  */
1064 static int vgic_its_cmd_handle_movall(struct kvm *kvm, struct vgic_its *its,
1065                                       u64 *its_cmd)
1066 {
1067         struct vgic_dist *dist = &kvm->arch.vgic;
1068         u32 target1_addr = its_cmd_get_target_addr(its_cmd);
1069         u32 target2_addr = its_cmd_mask_field(its_cmd, 3, 16, 32);
1070         struct kvm_vcpu *vcpu1, *vcpu2;
1071         struct vgic_irq *irq;
1072
1073         if (target1_addr >= atomic_read(&kvm->online_vcpus) ||
1074             target2_addr >= atomic_read(&kvm->online_vcpus))
1075                 return E_ITS_MOVALL_PROCNUM_OOR;
1076
1077         if (target1_addr == target2_addr)
1078                 return 0;
1079
1080         vcpu1 = kvm_get_vcpu(kvm, target1_addr);
1081         vcpu2 = kvm_get_vcpu(kvm, target2_addr);
1082
1083         spin_lock(&dist->lpi_list_lock);
1084
1085         list_for_each_entry(irq, &dist->lpi_list_head, lpi_list) {
1086                 spin_lock(&irq->irq_lock);
1087
1088                 if (irq->target_vcpu == vcpu1)
1089                         irq->target_vcpu = vcpu2;
1090
1091                 spin_unlock(&irq->irq_lock);
1092         }
1093
1094         spin_unlock(&dist->lpi_list_lock);
1095
1096         return 0;
1097 }
1098
1099 /*
1100  * The INT command injects the LPI associated with that DevID/EvID pair.
1101  * Must be called with the its_lock mutex held.
1102  */
1103 static int vgic_its_cmd_handle_int(struct kvm *kvm, struct vgic_its *its,
1104                                    u64 *its_cmd)
1105 {
1106         u32 msi_data = its_cmd_get_id(its_cmd);
1107         u64 msi_devid = its_cmd_get_deviceid(its_cmd);
1108
1109         return vgic_its_trigger_msi(kvm, its, msi_devid, msi_data);
1110 }
1111
1112 /*
1113  * This function is called with the its_cmd lock held, but the ITS data
1114  * structure lock dropped.
1115  */
1116 static int vgic_its_handle_command(struct kvm *kvm, struct vgic_its *its,
1117                                    u64 *its_cmd)
1118 {
1119         int ret = -ENODEV;
1120
1121         mutex_lock(&its->its_lock);
1122         switch (its_cmd_get_command(its_cmd)) {
1123         case GITS_CMD_MAPD:
1124                 ret = vgic_its_cmd_handle_mapd(kvm, its, its_cmd);
1125                 break;
1126         case GITS_CMD_MAPC:
1127                 ret = vgic_its_cmd_handle_mapc(kvm, its, its_cmd);
1128                 break;
1129         case GITS_CMD_MAPI:
1130                 ret = vgic_its_cmd_handle_mapi(kvm, its, its_cmd);
1131                 break;
1132         case GITS_CMD_MAPTI:
1133                 ret = vgic_its_cmd_handle_mapi(kvm, its, its_cmd);
1134                 break;
1135         case GITS_CMD_MOVI:
1136                 ret = vgic_its_cmd_handle_movi(kvm, its, its_cmd);
1137                 break;
1138         case GITS_CMD_DISCARD:
1139                 ret = vgic_its_cmd_handle_discard(kvm, its, its_cmd);
1140                 break;
1141         case GITS_CMD_CLEAR:
1142                 ret = vgic_its_cmd_handle_clear(kvm, its, its_cmd);
1143                 break;
1144         case GITS_CMD_MOVALL:
1145                 ret = vgic_its_cmd_handle_movall(kvm, its, its_cmd);
1146                 break;
1147         case GITS_CMD_INT:
1148                 ret = vgic_its_cmd_handle_int(kvm, its, its_cmd);
1149                 break;
1150         case GITS_CMD_INV:
1151                 ret = vgic_its_cmd_handle_inv(kvm, its, its_cmd);
1152                 break;
1153         case GITS_CMD_INVALL:
1154                 ret = vgic_its_cmd_handle_invall(kvm, its, its_cmd);
1155                 break;
1156         case GITS_CMD_SYNC:
1157                 /* we ignore this command: we are in sync all of the time */
1158                 ret = 0;
1159                 break;
1160         }
1161         mutex_unlock(&its->its_lock);
1162
1163         return ret;
1164 }
1165
1166 static u64 vgic_sanitise_its_baser(u64 reg)
1167 {
1168         reg = vgic_sanitise_field(reg, GITS_BASER_SHAREABILITY_MASK,
1169                                   GITS_BASER_SHAREABILITY_SHIFT,
1170                                   vgic_sanitise_shareability);
1171         reg = vgic_sanitise_field(reg, GITS_BASER_INNER_CACHEABILITY_MASK,
1172                                   GITS_BASER_INNER_CACHEABILITY_SHIFT,
1173                                   vgic_sanitise_inner_cacheability);
1174         reg = vgic_sanitise_field(reg, GITS_BASER_OUTER_CACHEABILITY_MASK,
1175                                   GITS_BASER_OUTER_CACHEABILITY_SHIFT,
1176                                   vgic_sanitise_outer_cacheability);
1177
1178         /* Bits 15:12 contain bits 51:48 of the PA, which we don't support. */
1179         reg &= ~GENMASK_ULL(15, 12);
1180
1181         /* We support only one (ITS) page size: 64K */
1182         reg = (reg & ~GITS_BASER_PAGE_SIZE_MASK) | GITS_BASER_PAGE_SIZE_64K;
1183
1184         return reg;
1185 }
1186
1187 static u64 vgic_sanitise_its_cbaser(u64 reg)
1188 {
1189         reg = vgic_sanitise_field(reg, GITS_CBASER_SHAREABILITY_MASK,
1190                                   GITS_CBASER_SHAREABILITY_SHIFT,
1191                                   vgic_sanitise_shareability);
1192         reg = vgic_sanitise_field(reg, GITS_CBASER_INNER_CACHEABILITY_MASK,
1193                                   GITS_CBASER_INNER_CACHEABILITY_SHIFT,
1194                                   vgic_sanitise_inner_cacheability);
1195         reg = vgic_sanitise_field(reg, GITS_CBASER_OUTER_CACHEABILITY_MASK,
1196                                   GITS_CBASER_OUTER_CACHEABILITY_SHIFT,
1197                                   vgic_sanitise_outer_cacheability);
1198
1199         /*
1200          * Sanitise the physical address to be 64k aligned.
1201          * Also limit the physical addresses to 48 bits.
1202          */
1203         reg &= ~(GENMASK_ULL(51, 48) | GENMASK_ULL(15, 12));
1204
1205         return reg;
1206 }
1207
1208 static unsigned long vgic_mmio_read_its_cbaser(struct kvm *kvm,
1209                                                struct vgic_its *its,
1210                                                gpa_t addr, unsigned int len)
1211 {
1212         return extract_bytes(its->cbaser, addr & 7, len);
1213 }
1214
1215 static void vgic_mmio_write_its_cbaser(struct kvm *kvm, struct vgic_its *its,
1216                                        gpa_t addr, unsigned int len,
1217                                        unsigned long val)
1218 {
1219         /* When GITS_CTLR.Enable is 1, this register is RO. */
1220         if (its->enabled)
1221                 return;
1222
1223         mutex_lock(&its->cmd_lock);
1224         its->cbaser = update_64bit_reg(its->cbaser, addr & 7, len, val);
1225         its->cbaser = vgic_sanitise_its_cbaser(its->cbaser);
1226         its->creadr = 0;
1227         /*
1228          * CWRITER is architecturally UNKNOWN on reset, but we need to reset
1229          * it to CREADR to make sure we start with an empty command buffer.
1230          */
1231         its->cwriter = its->creadr;
1232         mutex_unlock(&its->cmd_lock);
1233 }
1234
1235 #define ITS_CMD_BUFFER_SIZE(baser)      ((((baser) & 0xff) + 1) << 12)
1236 #define ITS_CMD_SIZE                    32
1237 #define ITS_CMD_OFFSET(reg)             ((reg) & GENMASK(19, 5))
1238
1239 /* Must be called with the cmd_lock held. */
1240 static void vgic_its_process_commands(struct kvm *kvm, struct vgic_its *its)
1241 {
1242         gpa_t cbaser;
1243         u64 cmd_buf[4];
1244
1245         /* Commands are only processed when the ITS is enabled. */
1246         if (!its->enabled)
1247                 return;
1248
1249         cbaser = CBASER_ADDRESS(its->cbaser);
1250
1251         while (its->cwriter != its->creadr) {
1252                 int ret = kvm_read_guest(kvm, cbaser + its->creadr,
1253                                          cmd_buf, ITS_CMD_SIZE);
1254                 /*
1255                  * If kvm_read_guest() fails, this could be due to the guest
1256                  * programming a bogus value in CBASER or something else going
1257                  * wrong from which we cannot easily recover.
1258                  * According to section 6.3.2 in the GICv3 spec we can just
1259                  * ignore that command then.
1260                  */
1261                 if (!ret)
1262                         vgic_its_handle_command(kvm, its, cmd_buf);
1263
1264                 its->creadr += ITS_CMD_SIZE;
1265                 if (its->creadr == ITS_CMD_BUFFER_SIZE(its->cbaser))
1266                         its->creadr = 0;
1267         }
1268 }
1269
1270 /*
1271  * By writing to CWRITER the guest announces new commands to be processed.
1272  * To avoid any races in the first place, we take the its_cmd lock, which
1273  * protects our ring buffer variables, so that there is only one user
1274  * per ITS handling commands at a given time.
1275  */
1276 static void vgic_mmio_write_its_cwriter(struct kvm *kvm, struct vgic_its *its,
1277                                         gpa_t addr, unsigned int len,
1278                                         unsigned long val)
1279 {
1280         u64 reg;
1281
1282         if (!its)
1283                 return;
1284
1285         mutex_lock(&its->cmd_lock);
1286
1287         reg = update_64bit_reg(its->cwriter, addr & 7, len, val);
1288         reg = ITS_CMD_OFFSET(reg);
1289         if (reg >= ITS_CMD_BUFFER_SIZE(its->cbaser)) {
1290                 mutex_unlock(&its->cmd_lock);
1291                 return;
1292         }
1293         its->cwriter = reg;
1294
1295         vgic_its_process_commands(kvm, its);
1296
1297         mutex_unlock(&its->cmd_lock);
1298 }
1299
1300 static unsigned long vgic_mmio_read_its_cwriter(struct kvm *kvm,
1301                                                 struct vgic_its *its,
1302                                                 gpa_t addr, unsigned int len)
1303 {
1304         return extract_bytes(its->cwriter, addr & 0x7, len);
1305 }
1306
1307 static unsigned long vgic_mmio_read_its_creadr(struct kvm *kvm,
1308                                                struct vgic_its *its,
1309                                                gpa_t addr, unsigned int len)
1310 {
1311         return extract_bytes(its->creadr, addr & 0x7, len);
1312 }
1313
1314 static int vgic_mmio_uaccess_write_its_creadr(struct kvm *kvm,
1315                                               struct vgic_its *its,
1316                                               gpa_t addr, unsigned int len,
1317                                               unsigned long val)
1318 {
1319         u32 cmd_offset;
1320         int ret = 0;
1321
1322         mutex_lock(&its->cmd_lock);
1323
1324         if (its->enabled) {
1325                 ret = -EBUSY;
1326                 goto out;
1327         }
1328
1329         cmd_offset = ITS_CMD_OFFSET(val);
1330         if (cmd_offset >= ITS_CMD_BUFFER_SIZE(its->cbaser)) {
1331                 ret = -EINVAL;
1332                 goto out;
1333         }
1334
1335         its->creadr = cmd_offset;
1336 out:
1337         mutex_unlock(&its->cmd_lock);
1338         return ret;
1339 }
1340
1341 #define BASER_INDEX(addr) (((addr) / sizeof(u64)) & 0x7)
1342 static unsigned long vgic_mmio_read_its_baser(struct kvm *kvm,
1343                                               struct vgic_its *its,
1344                                               gpa_t addr, unsigned int len)
1345 {
1346         u64 reg;
1347
1348         switch (BASER_INDEX(addr)) {
1349         case 0:
1350                 reg = its->baser_device_table;
1351                 break;
1352         case 1:
1353                 reg = its->baser_coll_table;
1354                 break;
1355         default:
1356                 reg = 0;
1357                 break;
1358         }
1359
1360         return extract_bytes(reg, addr & 7, len);
1361 }
1362
1363 #define GITS_BASER_RO_MASK      (GENMASK_ULL(52, 48) | GENMASK_ULL(58, 56))
1364 static void vgic_mmio_write_its_baser(struct kvm *kvm,
1365                                       struct vgic_its *its,
1366                                       gpa_t addr, unsigned int len,
1367                                       unsigned long val)
1368 {
1369         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
1370         u64 entry_size, device_type;
1371         u64 reg, *regptr, clearbits = 0;
1372
1373         /* When GITS_CTLR.Enable is 1, we ignore write accesses. */
1374         if (its->enabled)
1375                 return;
1376
1377         switch (BASER_INDEX(addr)) {
1378         case 0:
1379                 regptr = &its->baser_device_table;
1380                 entry_size = abi->dte_esz;
1381                 device_type = GITS_BASER_TYPE_DEVICE;
1382                 break;
1383         case 1:
1384                 regptr = &its->baser_coll_table;
1385                 entry_size = abi->cte_esz;
1386                 device_type = GITS_BASER_TYPE_COLLECTION;
1387                 clearbits = GITS_BASER_INDIRECT;
1388                 break;
1389         default:
1390                 return;
1391         }
1392
1393         reg = update_64bit_reg(*regptr, addr & 7, len, val);
1394         reg &= ~GITS_BASER_RO_MASK;
1395         reg &= ~clearbits;
1396
1397         reg |= (entry_size - 1) << GITS_BASER_ENTRY_SIZE_SHIFT;
1398         reg |= device_type << GITS_BASER_TYPE_SHIFT;
1399         reg = vgic_sanitise_its_baser(reg);
1400
1401         *regptr = reg;
1402 }
1403
1404 static unsigned long vgic_mmio_read_its_ctlr(struct kvm *vcpu,
1405                                              struct vgic_its *its,
1406                                              gpa_t addr, unsigned int len)
1407 {
1408         u32 reg = 0;
1409
1410         mutex_lock(&its->cmd_lock);
1411         if (its->creadr == its->cwriter)
1412                 reg |= GITS_CTLR_QUIESCENT;
1413         if (its->enabled)
1414                 reg |= GITS_CTLR_ENABLE;
1415         mutex_unlock(&its->cmd_lock);
1416
1417         return reg;
1418 }
1419
1420 static void vgic_mmio_write_its_ctlr(struct kvm *kvm, struct vgic_its *its,
1421                                      gpa_t addr, unsigned int len,
1422                                      unsigned long val)
1423 {
1424         mutex_lock(&its->cmd_lock);
1425
1426         its->enabled = !!(val & GITS_CTLR_ENABLE);
1427
1428         /*
1429          * Try to process any pending commands. This function bails out early
1430          * if the ITS is disabled or no commands have been queued.
1431          */
1432         vgic_its_process_commands(kvm, its);
1433
1434         mutex_unlock(&its->cmd_lock);
1435 }
1436
1437 #define REGISTER_ITS_DESC(off, rd, wr, length, acc)             \
1438 {                                                               \
1439         .reg_offset = off,                                      \
1440         .len = length,                                          \
1441         .access_flags = acc,                                    \
1442         .its_read = rd,                                         \
1443         .its_write = wr,                                        \
1444 }
1445
1446 #define REGISTER_ITS_DESC_UACCESS(off, rd, wr, uwr, length, acc)\
1447 {                                                               \
1448         .reg_offset = off,                                      \
1449         .len = length,                                          \
1450         .access_flags = acc,                                    \
1451         .its_read = rd,                                         \
1452         .its_write = wr,                                        \
1453         .uaccess_its_write = uwr,                               \
1454 }
1455
1456 static void its_mmio_write_wi(struct kvm *kvm, struct vgic_its *its,
1457                               gpa_t addr, unsigned int len, unsigned long val)
1458 {
1459         /* Ignore */
1460 }
1461
1462 static struct vgic_register_region its_registers[] = {
1463         REGISTER_ITS_DESC(GITS_CTLR,
1464                 vgic_mmio_read_its_ctlr, vgic_mmio_write_its_ctlr, 4,
1465                 VGIC_ACCESS_32bit),
1466         REGISTER_ITS_DESC_UACCESS(GITS_IIDR,
1467                 vgic_mmio_read_its_iidr, its_mmio_write_wi,
1468                 vgic_mmio_uaccess_write_its_iidr, 4,
1469                 VGIC_ACCESS_32bit),
1470         REGISTER_ITS_DESC(GITS_TYPER,
1471                 vgic_mmio_read_its_typer, its_mmio_write_wi, 8,
1472                 VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1473         REGISTER_ITS_DESC(GITS_CBASER,
1474                 vgic_mmio_read_its_cbaser, vgic_mmio_write_its_cbaser, 8,
1475                 VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1476         REGISTER_ITS_DESC(GITS_CWRITER,
1477                 vgic_mmio_read_its_cwriter, vgic_mmio_write_its_cwriter, 8,
1478                 VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1479         REGISTER_ITS_DESC_UACCESS(GITS_CREADR,
1480                 vgic_mmio_read_its_creadr, its_mmio_write_wi,
1481                 vgic_mmio_uaccess_write_its_creadr, 8,
1482                 VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1483         REGISTER_ITS_DESC(GITS_BASER,
1484                 vgic_mmio_read_its_baser, vgic_mmio_write_its_baser, 0x40,
1485                 VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1486         REGISTER_ITS_DESC(GITS_IDREGS_BASE,
1487                 vgic_mmio_read_its_idregs, its_mmio_write_wi, 0x30,
1488                 VGIC_ACCESS_32bit),
1489 };
1490
1491 /* This is called on setting the LPI enable bit in the redistributor. */
1492 void vgic_enable_lpis(struct kvm_vcpu *vcpu)
1493 {
1494         if (!(vcpu->arch.vgic_cpu.pendbaser & GICR_PENDBASER_PTZ))
1495                 its_sync_lpi_pending_table(vcpu);
1496 }
1497
1498 static int vgic_register_its_iodev(struct kvm *kvm, struct vgic_its *its)
1499 {
1500         struct vgic_io_device *iodev = &its->iodev;
1501         int ret;
1502
1503         if (!its->initialized)
1504                 return -EBUSY;
1505
1506         if (IS_VGIC_ADDR_UNDEF(its->vgic_its_base))
1507                 return -ENXIO;
1508
1509         iodev->regions = its_registers;
1510         iodev->nr_regions = ARRAY_SIZE(its_registers);
1511         kvm_iodevice_init(&iodev->dev, &kvm_io_gic_ops);
1512
1513         iodev->base_addr = its->vgic_its_base;
1514         iodev->iodev_type = IODEV_ITS;
1515         iodev->its = its;
1516         mutex_lock(&kvm->slots_lock);
1517         ret = kvm_io_bus_register_dev(kvm, KVM_MMIO_BUS, iodev->base_addr,
1518                                       KVM_VGIC_V3_ITS_SIZE, &iodev->dev);
1519         mutex_unlock(&kvm->slots_lock);
1520
1521         return ret;
1522 }
1523
1524 #define INITIAL_BASER_VALUE                                               \
1525         (GIC_BASER_CACHEABILITY(GITS_BASER, INNER, RaWb)                | \
1526          GIC_BASER_CACHEABILITY(GITS_BASER, OUTER, SameAsInner)         | \
1527          GIC_BASER_SHAREABILITY(GITS_BASER, InnerShareable)             | \
1528          GITS_BASER_PAGE_SIZE_64K)
1529
1530 #define INITIAL_PROPBASER_VALUE                                           \
1531         (GIC_BASER_CACHEABILITY(GICR_PROPBASER, INNER, RaWb)            | \
1532          GIC_BASER_CACHEABILITY(GICR_PROPBASER, OUTER, SameAsInner)     | \
1533          GIC_BASER_SHAREABILITY(GICR_PROPBASER, InnerShareable))
1534
1535 static int vgic_its_create(struct kvm_device *dev, u32 type)
1536 {
1537         struct vgic_its *its;
1538
1539         if (type != KVM_DEV_TYPE_ARM_VGIC_ITS)
1540                 return -ENODEV;
1541
1542         its = kzalloc(sizeof(struct vgic_its), GFP_KERNEL);
1543         if (!its)
1544                 return -ENOMEM;
1545
1546         mutex_init(&its->its_lock);
1547         mutex_init(&its->cmd_lock);
1548
1549         its->vgic_its_base = VGIC_ADDR_UNDEF;
1550
1551         INIT_LIST_HEAD(&its->device_list);
1552         INIT_LIST_HEAD(&its->collection_list);
1553
1554         dev->kvm->arch.vgic.has_its = true;
1555         its->initialized = false;
1556         its->enabled = false;
1557         its->dev = dev;
1558
1559         its->baser_device_table = INITIAL_BASER_VALUE                   |
1560                 ((u64)GITS_BASER_TYPE_DEVICE << GITS_BASER_TYPE_SHIFT);
1561         its->baser_coll_table = INITIAL_BASER_VALUE |
1562                 ((u64)GITS_BASER_TYPE_COLLECTION << GITS_BASER_TYPE_SHIFT);
1563         dev->kvm->arch.vgic.propbaser = INITIAL_PROPBASER_VALUE;
1564
1565         dev->private = its;
1566
1567         return vgic_its_set_abi(its, NR_ITS_ABIS - 1);
1568 }
1569
1570 static void vgic_its_destroy(struct kvm_device *kvm_dev)
1571 {
1572         struct kvm *kvm = kvm_dev->kvm;
1573         struct vgic_its *its = kvm_dev->private;
1574         struct its_device *dev;
1575         struct its_ite *ite;
1576         struct list_head *dev_cur, *dev_temp;
1577         struct list_head *cur, *temp;
1578
1579         /*
1580          * We may end up here without the lists ever having been initialized.
1581          * Check this and bail out early to avoid dereferencing a NULL pointer.
1582          */
1583         if (!its->device_list.next)
1584                 return;
1585
1586         mutex_lock(&its->its_lock);
1587         list_for_each_safe(dev_cur, dev_temp, &its->device_list) {
1588                 dev = container_of(dev_cur, struct its_device, dev_list);
1589                 list_for_each_safe(cur, temp, &dev->itt_head) {
1590                         ite = (container_of(cur, struct its_ite, ite_list));
1591                         its_free_ite(kvm, ite);
1592                 }
1593                 list_del(dev_cur);
1594                 kfree(dev);
1595         }
1596
1597         list_for_each_safe(cur, temp, &its->collection_list) {
1598                 list_del(cur);
1599                 kfree(container_of(cur, struct its_collection, coll_list));
1600         }
1601         mutex_unlock(&its->its_lock);
1602
1603         kfree(its);
1604 }
1605
1606 int vgic_its_has_attr_regs(struct kvm_device *dev,
1607                            struct kvm_device_attr *attr)
1608 {
1609         const struct vgic_register_region *region;
1610         gpa_t offset = attr->attr;
1611         int align;
1612
1613         align = (offset < GITS_TYPER) || (offset >= GITS_PIDR4) ? 0x3 : 0x7;
1614
1615         if (offset & align)
1616                 return -EINVAL;
1617
1618         region = vgic_find_mmio_region(its_registers,
1619                                        ARRAY_SIZE(its_registers),
1620                                        offset);
1621         if (!region)
1622                 return -ENXIO;
1623
1624         return 0;
1625 }
1626
1627 int vgic_its_attr_regs_access(struct kvm_device *dev,
1628                               struct kvm_device_attr *attr,
1629                               u64 *reg, bool is_write)
1630 {
1631         const struct vgic_register_region *region;
1632         struct vgic_its *its;
1633         gpa_t addr, offset;
1634         unsigned int len;
1635         int align, ret = 0;
1636
1637         its = dev->private;
1638         offset = attr->attr;
1639
1640         /*
1641          * Although the spec supports upper/lower 32-bit accesses to
1642          * 64-bit ITS registers, the userspace ABI requires 64-bit
1643          * accesses to all 64-bit wide registers. We therefore only
1644          * support 32-bit accesses to GITS_CTLR, GITS_IIDR and GITS ID
1645          * registers
1646          */
1647         if ((offset < GITS_TYPER) || (offset >= GITS_PIDR4))
1648                 align = 0x3;
1649         else
1650                 align = 0x7;
1651
1652         if (offset & align)
1653                 return -EINVAL;
1654
1655         mutex_lock(&dev->kvm->lock);
1656
1657         if (IS_VGIC_ADDR_UNDEF(its->vgic_its_base)) {
1658                 ret = -ENXIO;
1659                 goto out;
1660         }
1661
1662         region = vgic_find_mmio_region(its_registers,
1663                                        ARRAY_SIZE(its_registers),
1664                                        offset);
1665         if (!region) {
1666                 ret = -ENXIO;
1667                 goto out;
1668         }
1669
1670         if (!lock_all_vcpus(dev->kvm)) {
1671                 ret = -EBUSY;
1672                 goto out;
1673         }
1674
1675         addr = its->vgic_its_base + offset;
1676
1677         len = region->access_flags & VGIC_ACCESS_64bit ? 8 : 4;
1678
1679         if (is_write) {
1680                 if (region->uaccess_its_write)
1681                         ret = region->uaccess_its_write(dev->kvm, its, addr,
1682                                                         len, *reg);
1683                 else
1684                         region->its_write(dev->kvm, its, addr, len, *reg);
1685         } else {
1686                 *reg = region->its_read(dev->kvm, its, addr, len);
1687         }
1688         unlock_all_vcpus(dev->kvm);
1689 out:
1690         mutex_unlock(&dev->kvm->lock);
1691         return ret;
1692 }
1693
1694 /**
1695  * vgic_its_save_tables_v0 - Save the ITS tables into guest ARM
1696  * according to v0 ABI
1697  */
1698 static int vgic_its_save_tables_v0(struct vgic_its *its)
1699 {
1700         return -ENXIO;
1701 }
1702
1703 /**
1704  * vgic_its_restore_tables_v0 - Restore the ITS tables from guest RAM
1705  * to internal data structs according to V0 ABI
1706  *
1707  */
1708 static int vgic_its_restore_tables_v0(struct vgic_its *its)
1709 {
1710         return -ENXIO;
1711 }
1712
1713 static int vgic_its_commit_v0(struct vgic_its *its)
1714 {
1715         const struct vgic_its_abi *abi;
1716
1717         abi = vgic_its_get_abi(its);
1718         its->baser_coll_table &= ~GITS_BASER_ENTRY_SIZE_MASK;
1719         its->baser_device_table &= ~GITS_BASER_ENTRY_SIZE_MASK;
1720
1721         its->baser_coll_table |= (GIC_ENCODE_SZ(abi->cte_esz, 5)
1722                                         << GITS_BASER_ENTRY_SIZE_SHIFT);
1723
1724         its->baser_device_table |= (GIC_ENCODE_SZ(abi->dte_esz, 5)
1725                                         << GITS_BASER_ENTRY_SIZE_SHIFT);
1726         return 0;
1727 }
1728
1729 static int vgic_its_has_attr(struct kvm_device *dev,
1730                              struct kvm_device_attr *attr)
1731 {
1732         switch (attr->group) {
1733         case KVM_DEV_ARM_VGIC_GRP_ADDR:
1734                 switch (attr->attr) {
1735                 case KVM_VGIC_ITS_ADDR_TYPE:
1736                         return 0;
1737                 }
1738                 break;
1739         case KVM_DEV_ARM_VGIC_GRP_CTRL:
1740                 switch (attr->attr) {
1741                 case KVM_DEV_ARM_VGIC_CTRL_INIT:
1742                         return 0;
1743                 }
1744                 break;
1745         case KVM_DEV_ARM_VGIC_GRP_ITS_REGS:
1746                 return vgic_its_has_attr_regs(dev, attr);
1747         }
1748         return -ENXIO;
1749 }
1750
1751 static int vgic_its_set_attr(struct kvm_device *dev,
1752                              struct kvm_device_attr *attr)
1753 {
1754         struct vgic_its *its = dev->private;
1755         int ret;
1756
1757         switch (attr->group) {
1758         case KVM_DEV_ARM_VGIC_GRP_ADDR: {
1759                 u64 __user *uaddr = (u64 __user *)(long)attr->addr;
1760                 unsigned long type = (unsigned long)attr->attr;
1761                 u64 addr;
1762
1763                 if (type != KVM_VGIC_ITS_ADDR_TYPE)
1764                         return -ENODEV;
1765
1766                 if (copy_from_user(&addr, uaddr, sizeof(addr)))
1767                         return -EFAULT;
1768
1769                 ret = vgic_check_ioaddr(dev->kvm, &its->vgic_its_base,
1770                                         addr, SZ_64K);
1771                 if (ret)
1772                         return ret;
1773
1774                 its->vgic_its_base = addr;
1775
1776                 return 0;
1777         }
1778         case KVM_DEV_ARM_VGIC_GRP_CTRL:
1779                 switch (attr->attr) {
1780                 case KVM_DEV_ARM_VGIC_CTRL_INIT:
1781                         its->initialized = true;
1782
1783                         return 0;
1784                 }
1785                 break;
1786         case KVM_DEV_ARM_VGIC_GRP_ITS_REGS: {
1787                 u64 __user *uaddr = (u64 __user *)(long)attr->addr;
1788                 u64 reg;
1789
1790                 if (get_user(reg, uaddr))
1791                         return -EFAULT;
1792
1793                 return vgic_its_attr_regs_access(dev, attr, &reg, true);
1794         }
1795         }
1796         return -ENXIO;
1797 }
1798
1799 static int vgic_its_get_attr(struct kvm_device *dev,
1800                              struct kvm_device_attr *attr)
1801 {
1802         switch (attr->group) {
1803         case KVM_DEV_ARM_VGIC_GRP_ADDR: {
1804                 struct vgic_its *its = dev->private;
1805                 u64 addr = its->vgic_its_base;
1806                 u64 __user *uaddr = (u64 __user *)(long)attr->addr;
1807                 unsigned long type = (unsigned long)attr->attr;
1808
1809                 if (type != KVM_VGIC_ITS_ADDR_TYPE)
1810                         return -ENODEV;
1811
1812                 if (copy_to_user(uaddr, &addr, sizeof(addr)))
1813                         return -EFAULT;
1814                 break;
1815         }
1816         case KVM_DEV_ARM_VGIC_GRP_ITS_REGS: {
1817                 u64 __user *uaddr = (u64 __user *)(long)attr->addr;
1818                 u64 reg;
1819                 int ret;
1820
1821                 ret = vgic_its_attr_regs_access(dev, attr, &reg, false);
1822                 if (ret)
1823                         return ret;
1824                 return put_user(reg, uaddr);
1825         }
1826         default:
1827                 return -ENXIO;
1828         }
1829
1830         return 0;
1831 }
1832
1833 static struct kvm_device_ops kvm_arm_vgic_its_ops = {
1834         .name = "kvm-arm-vgic-its",
1835         .create = vgic_its_create,
1836         .destroy = vgic_its_destroy,
1837         .set_attr = vgic_its_set_attr,
1838         .get_attr = vgic_its_get_attr,
1839         .has_attr = vgic_its_has_attr,
1840 };
1841
1842 int kvm_vgic_register_its_device(void)
1843 {
1844         return kvm_register_device_ops(&kvm_arm_vgic_its_ops,
1845                                        KVM_DEV_TYPE_ARM_VGIC_ITS);
1846 }
1847
1848 /*
1849  * Registers all ITSes with the kvm_io_bus framework.
1850  * To follow the existing VGIC initialization sequence, this has to be
1851  * done as late as possible, just before the first VCPU runs.
1852  */
1853 int vgic_register_its_iodevs(struct kvm *kvm)
1854 {
1855         struct kvm_device *dev;
1856         int ret = 0;
1857
1858         list_for_each_entry(dev, &kvm->devices, vm_node) {
1859                 if (dev->ops != &kvm_arm_vgic_its_ops)
1860                         continue;
1861
1862                 ret = vgic_register_its_iodev(kvm, dev->private);
1863                 if (ret)
1864                         return ret;
1865                 /*
1866                  * We don't need to care about tearing down previously
1867                  * registered ITSes, as the kvm_io_bus framework removes
1868                  * them for us if the VM gets destroyed.
1869                  */
1870         }
1871
1872         return ret;
1873 }