Merge tag 'nfsd-4.19-1' of git://linux-nfs.org/~bfields/linux
[platform/kernel/linux-rpi.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 #include <linux/list_sort.h>
27
28 #include <linux/irqchip/arm-gic-v3.h>
29
30 #include <asm/kvm_emulate.h>
31 #include <asm/kvm_arm.h>
32 #include <asm/kvm_mmu.h>
33
34 #include "vgic.h"
35 #include "vgic-mmio.h"
36
37 static int vgic_its_save_tables_v0(struct vgic_its *its);
38 static int vgic_its_restore_tables_v0(struct vgic_its *its);
39 static int vgic_its_commit_v0(struct vgic_its *its);
40 static int update_lpi_config(struct kvm *kvm, struct vgic_irq *irq,
41                              struct kvm_vcpu *filter_vcpu, bool needs_inv);
42
43 /*
44  * Creates a new (reference to a) struct vgic_irq for a given LPI.
45  * If this LPI is already mapped on another ITS, we increase its refcount
46  * and return a pointer to the existing structure.
47  * If this is a "new" LPI, we allocate and initialize a new struct vgic_irq.
48  * This function returns a pointer to the _unlocked_ structure.
49  */
50 static struct vgic_irq *vgic_add_lpi(struct kvm *kvm, u32 intid,
51                                      struct kvm_vcpu *vcpu)
52 {
53         struct vgic_dist *dist = &kvm->arch.vgic;
54         struct vgic_irq *irq = vgic_get_irq(kvm, NULL, intid), *oldirq;
55         unsigned long flags;
56         int ret;
57
58         /* In this case there is no put, since we keep the reference. */
59         if (irq)
60                 return irq;
61
62         irq = kzalloc(sizeof(struct vgic_irq), GFP_KERNEL);
63         if (!irq)
64                 return ERR_PTR(-ENOMEM);
65
66         INIT_LIST_HEAD(&irq->lpi_list);
67         INIT_LIST_HEAD(&irq->ap_list);
68         spin_lock_init(&irq->irq_lock);
69
70         irq->config = VGIC_CONFIG_EDGE;
71         kref_init(&irq->refcount);
72         irq->intid = intid;
73         irq->target_vcpu = vcpu;
74         irq->group = 1;
75
76         spin_lock_irqsave(&dist->lpi_list_lock, flags);
77
78         /*
79          * There could be a race with another vgic_add_lpi(), so we need to
80          * check that we don't add a second list entry with the same LPI.
81          */
82         list_for_each_entry(oldirq, &dist->lpi_list_head, lpi_list) {
83                 if (oldirq->intid != intid)
84                         continue;
85
86                 /* Someone was faster with adding this LPI, lets use that. */
87                 kfree(irq);
88                 irq = oldirq;
89
90                 /*
91                  * This increases the refcount, the caller is expected to
92                  * call vgic_put_irq() on the returned pointer once it's
93                  * finished with the IRQ.
94                  */
95                 vgic_get_irq_kref(irq);
96
97                 goto out_unlock;
98         }
99
100         list_add_tail(&irq->lpi_list, &dist->lpi_list_head);
101         dist->lpi_list_count++;
102
103 out_unlock:
104         spin_unlock_irqrestore(&dist->lpi_list_lock, flags);
105
106         /*
107          * We "cache" the configuration table entries in our struct vgic_irq's.
108          * However we only have those structs for mapped IRQs, so we read in
109          * the respective config data from memory here upon mapping the LPI.
110          */
111         ret = update_lpi_config(kvm, irq, NULL, false);
112         if (ret)
113                 return ERR_PTR(ret);
114
115         ret = vgic_v3_lpi_sync_pending_status(kvm, irq);
116         if (ret)
117                 return ERR_PTR(ret);
118
119         return irq;
120 }
121
122 struct its_device {
123         struct list_head dev_list;
124
125         /* the head for the list of ITTEs */
126         struct list_head itt_head;
127         u32 num_eventid_bits;
128         gpa_t itt_addr;
129         u32 device_id;
130 };
131
132 #define COLLECTION_NOT_MAPPED ((u32)~0)
133
134 struct its_collection {
135         struct list_head coll_list;
136
137         u32 collection_id;
138         u32 target_addr;
139 };
140
141 #define its_is_collection_mapped(coll) ((coll) && \
142                                 ((coll)->target_addr != COLLECTION_NOT_MAPPED))
143
144 struct its_ite {
145         struct list_head ite_list;
146
147         struct vgic_irq *irq;
148         struct its_collection *collection;
149         u32 event_id;
150 };
151
152 /**
153  * struct vgic_its_abi - ITS abi ops and settings
154  * @cte_esz: collection table entry size
155  * @dte_esz: device table entry size
156  * @ite_esz: interrupt translation table entry size
157  * @save tables: save the ITS tables into guest RAM
158  * @restore_tables: restore the ITS internal structs from tables
159  *  stored in guest RAM
160  * @commit: initialize the registers which expose the ABI settings,
161  *  especially the entry sizes
162  */
163 struct vgic_its_abi {
164         int cte_esz;
165         int dte_esz;
166         int ite_esz;
167         int (*save_tables)(struct vgic_its *its);
168         int (*restore_tables)(struct vgic_its *its);
169         int (*commit)(struct vgic_its *its);
170 };
171
172 #define ABI_0_ESZ       8
173 #define ESZ_MAX         ABI_0_ESZ
174
175 static const struct vgic_its_abi its_table_abi_versions[] = {
176         [0] = {
177          .cte_esz = ABI_0_ESZ,
178          .dte_esz = ABI_0_ESZ,
179          .ite_esz = ABI_0_ESZ,
180          .save_tables = vgic_its_save_tables_v0,
181          .restore_tables = vgic_its_restore_tables_v0,
182          .commit = vgic_its_commit_v0,
183         },
184 };
185
186 #define NR_ITS_ABIS     ARRAY_SIZE(its_table_abi_versions)
187
188 inline const struct vgic_its_abi *vgic_its_get_abi(struct vgic_its *its)
189 {
190         return &its_table_abi_versions[its->abi_rev];
191 }
192
193 static int vgic_its_set_abi(struct vgic_its *its, u32 rev)
194 {
195         const struct vgic_its_abi *abi;
196
197         its->abi_rev = rev;
198         abi = vgic_its_get_abi(its);
199         return abi->commit(its);
200 }
201
202 /*
203  * Find and returns a device in the device table for an ITS.
204  * Must be called with the its_lock mutex held.
205  */
206 static struct its_device *find_its_device(struct vgic_its *its, u32 device_id)
207 {
208         struct its_device *device;
209
210         list_for_each_entry(device, &its->device_list, dev_list)
211                 if (device_id == device->device_id)
212                         return device;
213
214         return NULL;
215 }
216
217 /*
218  * Find and returns an interrupt translation table entry (ITTE) for a given
219  * Device ID/Event ID pair on an ITS.
220  * Must be called with the its_lock mutex held.
221  */
222 static struct its_ite *find_ite(struct vgic_its *its, u32 device_id,
223                                   u32 event_id)
224 {
225         struct its_device *device;
226         struct its_ite *ite;
227
228         device = find_its_device(its, device_id);
229         if (device == NULL)
230                 return NULL;
231
232         list_for_each_entry(ite, &device->itt_head, ite_list)
233                 if (ite->event_id == event_id)
234                         return ite;
235
236         return NULL;
237 }
238
239 /* To be used as an iterator this macro misses the enclosing parentheses */
240 #define for_each_lpi_its(dev, ite, its) \
241         list_for_each_entry(dev, &(its)->device_list, dev_list) \
242                 list_for_each_entry(ite, &(dev)->itt_head, ite_list)
243
244 /*
245  * We only implement 48 bits of PA at the moment, although the ITS
246  * supports more. Let's be restrictive here.
247  */
248 #define BASER_ADDRESS(x)        ((x) & GENMASK_ULL(47, 16))
249 #define CBASER_ADDRESS(x)       ((x) & GENMASK_ULL(47, 12))
250
251 #define GIC_LPI_OFFSET 8192
252
253 #define VITS_TYPER_IDBITS 16
254 #define VITS_TYPER_DEVBITS 16
255 #define VITS_DTE_MAX_DEVID_OFFSET       (BIT(14) - 1)
256 #define VITS_ITE_MAX_EVENTID_OFFSET     (BIT(16) - 1)
257
258 /*
259  * Finds and returns a collection in the ITS collection table.
260  * Must be called with the its_lock mutex held.
261  */
262 static struct its_collection *find_collection(struct vgic_its *its, int coll_id)
263 {
264         struct its_collection *collection;
265
266         list_for_each_entry(collection, &its->collection_list, coll_list) {
267                 if (coll_id == collection->collection_id)
268                         return collection;
269         }
270
271         return NULL;
272 }
273
274 #define LPI_PROP_ENABLE_BIT(p)  ((p) & LPI_PROP_ENABLED)
275 #define LPI_PROP_PRIORITY(p)    ((p) & 0xfc)
276
277 /*
278  * Reads the configuration data for a given LPI from guest memory and
279  * updates the fields in struct vgic_irq.
280  * If filter_vcpu is not NULL, applies only if the IRQ is targeting this
281  * VCPU. Unconditionally applies if filter_vcpu is NULL.
282  */
283 static int update_lpi_config(struct kvm *kvm, struct vgic_irq *irq,
284                              struct kvm_vcpu *filter_vcpu, bool needs_inv)
285 {
286         u64 propbase = GICR_PROPBASER_ADDRESS(kvm->arch.vgic.propbaser);
287         u8 prop;
288         int ret;
289         unsigned long flags;
290
291         ret = kvm_read_guest_lock(kvm, propbase + irq->intid - GIC_LPI_OFFSET,
292                                   &prop, 1);
293
294         if (ret)
295                 return ret;
296
297         spin_lock_irqsave(&irq->irq_lock, flags);
298
299         if (!filter_vcpu || filter_vcpu == irq->target_vcpu) {
300                 irq->priority = LPI_PROP_PRIORITY(prop);
301                 irq->enabled = LPI_PROP_ENABLE_BIT(prop);
302
303                 if (!irq->hw) {
304                         vgic_queue_irq_unlock(kvm, irq, flags);
305                         return 0;
306                 }
307         }
308
309         spin_unlock_irqrestore(&irq->irq_lock, flags);
310
311         if (irq->hw)
312                 return its_prop_update_vlpi(irq->host_irq, prop, needs_inv);
313
314         return 0;
315 }
316
317 /*
318  * Create a snapshot of the current LPIs targeting @vcpu, so that we can
319  * enumerate those LPIs without holding any lock.
320  * Returns their number and puts the kmalloc'ed array into intid_ptr.
321  */
322 int vgic_copy_lpi_list(struct kvm *kvm, struct kvm_vcpu *vcpu, u32 **intid_ptr)
323 {
324         struct vgic_dist *dist = &kvm->arch.vgic;
325         struct vgic_irq *irq;
326         unsigned long flags;
327         u32 *intids;
328         int irq_count, i = 0;
329
330         /*
331          * There is an obvious race between allocating the array and LPIs
332          * being mapped/unmapped. If we ended up here as a result of a
333          * command, we're safe (locks are held, preventing another
334          * command). If coming from another path (such as enabling LPIs),
335          * we must be careful not to overrun the array.
336          */
337         irq_count = READ_ONCE(dist->lpi_list_count);
338         intids = kmalloc_array(irq_count, sizeof(intids[0]), GFP_KERNEL);
339         if (!intids)
340                 return -ENOMEM;
341
342         spin_lock_irqsave(&dist->lpi_list_lock, flags);
343         list_for_each_entry(irq, &dist->lpi_list_head, lpi_list) {
344                 if (i == irq_count)
345                         break;
346                 /* We don't need to "get" the IRQ, as we hold the list lock. */
347                 if (vcpu && irq->target_vcpu != vcpu)
348                         continue;
349                 intids[i++] = irq->intid;
350         }
351         spin_unlock_irqrestore(&dist->lpi_list_lock, flags);
352
353         *intid_ptr = intids;
354         return i;
355 }
356
357 static int update_affinity(struct vgic_irq *irq, struct kvm_vcpu *vcpu)
358 {
359         int ret = 0;
360         unsigned long flags;
361
362         spin_lock_irqsave(&irq->irq_lock, flags);
363         irq->target_vcpu = vcpu;
364         spin_unlock_irqrestore(&irq->irq_lock, flags);
365
366         if (irq->hw) {
367                 struct its_vlpi_map map;
368
369                 ret = its_get_vlpi(irq->host_irq, &map);
370                 if (ret)
371                         return ret;
372
373                 map.vpe = &vcpu->arch.vgic_cpu.vgic_v3.its_vpe;
374
375                 ret = its_map_vlpi(irq->host_irq, &map);
376         }
377
378         return ret;
379 }
380
381 /*
382  * Promotes the ITS view of affinity of an ITTE (which redistributor this LPI
383  * is targeting) to the VGIC's view, which deals with target VCPUs.
384  * Needs to be called whenever either the collection for a LPIs has
385  * changed or the collection itself got retargeted.
386  */
387 static void update_affinity_ite(struct kvm *kvm, struct its_ite *ite)
388 {
389         struct kvm_vcpu *vcpu;
390
391         if (!its_is_collection_mapped(ite->collection))
392                 return;
393
394         vcpu = kvm_get_vcpu(kvm, ite->collection->target_addr);
395         update_affinity(ite->irq, vcpu);
396 }
397
398 /*
399  * Updates the target VCPU for every LPI targeting this collection.
400  * Must be called with the its_lock mutex held.
401  */
402 static void update_affinity_collection(struct kvm *kvm, struct vgic_its *its,
403                                        struct its_collection *coll)
404 {
405         struct its_device *device;
406         struct its_ite *ite;
407
408         for_each_lpi_its(device, ite, its) {
409                 if (!ite->collection || coll != ite->collection)
410                         continue;
411
412                 update_affinity_ite(kvm, ite);
413         }
414 }
415
416 static u32 max_lpis_propbaser(u64 propbaser)
417 {
418         int nr_idbits = (propbaser & 0x1f) + 1;
419
420         return 1U << min(nr_idbits, INTERRUPT_ID_BITS_ITS);
421 }
422
423 /*
424  * Sync the pending table pending bit of LPIs targeting @vcpu
425  * with our own data structures. This relies on the LPI being
426  * mapped before.
427  */
428 static int its_sync_lpi_pending_table(struct kvm_vcpu *vcpu)
429 {
430         gpa_t pendbase = GICR_PENDBASER_ADDRESS(vcpu->arch.vgic_cpu.pendbaser);
431         struct vgic_irq *irq;
432         int last_byte_offset = -1;
433         int ret = 0;
434         u32 *intids;
435         int nr_irqs, i;
436         unsigned long flags;
437         u8 pendmask;
438
439         nr_irqs = vgic_copy_lpi_list(vcpu->kvm, vcpu, &intids);
440         if (nr_irqs < 0)
441                 return nr_irqs;
442
443         for (i = 0; i < nr_irqs; i++) {
444                 int byte_offset, bit_nr;
445
446                 byte_offset = intids[i] / BITS_PER_BYTE;
447                 bit_nr = intids[i] % BITS_PER_BYTE;
448
449                 /*
450                  * For contiguously allocated LPIs chances are we just read
451                  * this very same byte in the last iteration. Reuse that.
452                  */
453                 if (byte_offset != last_byte_offset) {
454                         ret = kvm_read_guest_lock(vcpu->kvm,
455                                                   pendbase + byte_offset,
456                                                   &pendmask, 1);
457                         if (ret) {
458                                 kfree(intids);
459                                 return ret;
460                         }
461                         last_byte_offset = byte_offset;
462                 }
463
464                 irq = vgic_get_irq(vcpu->kvm, NULL, intids[i]);
465                 spin_lock_irqsave(&irq->irq_lock, flags);
466                 irq->pending_latch = pendmask & (1U << bit_nr);
467                 vgic_queue_irq_unlock(vcpu->kvm, irq, flags);
468                 vgic_put_irq(vcpu->kvm, irq);
469         }
470
471         kfree(intids);
472
473         return ret;
474 }
475
476 static unsigned long vgic_mmio_read_its_typer(struct kvm *kvm,
477                                               struct vgic_its *its,
478                                               gpa_t addr, unsigned int len)
479 {
480         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
481         u64 reg = GITS_TYPER_PLPIS;
482
483         /*
484          * We use linear CPU numbers for redistributor addressing,
485          * so GITS_TYPER.PTA is 0.
486          * Also we force all PROPBASER registers to be the same, so
487          * CommonLPIAff is 0 as well.
488          * To avoid memory waste in the guest, we keep the number of IDBits and
489          * DevBits low - as least for the time being.
490          */
491         reg |= GIC_ENCODE_SZ(VITS_TYPER_DEVBITS, 5) << GITS_TYPER_DEVBITS_SHIFT;
492         reg |= GIC_ENCODE_SZ(VITS_TYPER_IDBITS, 5) << GITS_TYPER_IDBITS_SHIFT;
493         reg |= GIC_ENCODE_SZ(abi->ite_esz, 4) << GITS_TYPER_ITT_ENTRY_SIZE_SHIFT;
494
495         return extract_bytes(reg, addr & 7, len);
496 }
497
498 static unsigned long vgic_mmio_read_its_iidr(struct kvm *kvm,
499                                              struct vgic_its *its,
500                                              gpa_t addr, unsigned int len)
501 {
502         u32 val;
503
504         val = (its->abi_rev << GITS_IIDR_REV_SHIFT) & GITS_IIDR_REV_MASK;
505         val |= (PRODUCT_ID_KVM << GITS_IIDR_PRODUCTID_SHIFT) | IMPLEMENTER_ARM;
506         return val;
507 }
508
509 static int vgic_mmio_uaccess_write_its_iidr(struct kvm *kvm,
510                                             struct vgic_its *its,
511                                             gpa_t addr, unsigned int len,
512                                             unsigned long val)
513 {
514         u32 rev = GITS_IIDR_REV(val);
515
516         if (rev >= NR_ITS_ABIS)
517                 return -EINVAL;
518         return vgic_its_set_abi(its, rev);
519 }
520
521 static unsigned long vgic_mmio_read_its_idregs(struct kvm *kvm,
522                                                struct vgic_its *its,
523                                                gpa_t addr, unsigned int len)
524 {
525         switch (addr & 0xffff) {
526         case GITS_PIDR0:
527                 return 0x92;    /* part number, bits[7:0] */
528         case GITS_PIDR1:
529                 return 0xb4;    /* part number, bits[11:8] */
530         case GITS_PIDR2:
531                 return GIC_PIDR2_ARCH_GICv3 | 0x0b;
532         case GITS_PIDR4:
533                 return 0x40;    /* This is a 64K software visible page */
534         /* The following are the ID registers for (any) GIC. */
535         case GITS_CIDR0:
536                 return 0x0d;
537         case GITS_CIDR1:
538                 return 0xf0;
539         case GITS_CIDR2:
540                 return 0x05;
541         case GITS_CIDR3:
542                 return 0xb1;
543         }
544
545         return 0;
546 }
547
548 int vgic_its_resolve_lpi(struct kvm *kvm, struct vgic_its *its,
549                          u32 devid, u32 eventid, struct vgic_irq **irq)
550 {
551         struct kvm_vcpu *vcpu;
552         struct its_ite *ite;
553
554         if (!its->enabled)
555                 return -EBUSY;
556
557         ite = find_ite(its, devid, eventid);
558         if (!ite || !its_is_collection_mapped(ite->collection))
559                 return E_ITS_INT_UNMAPPED_INTERRUPT;
560
561         vcpu = kvm_get_vcpu(kvm, ite->collection->target_addr);
562         if (!vcpu)
563                 return E_ITS_INT_UNMAPPED_INTERRUPT;
564
565         if (!vcpu->arch.vgic_cpu.lpis_enabled)
566                 return -EBUSY;
567
568         *irq = ite->irq;
569         return 0;
570 }
571
572 struct vgic_its *vgic_msi_to_its(struct kvm *kvm, struct kvm_msi *msi)
573 {
574         u64 address;
575         struct kvm_io_device *kvm_io_dev;
576         struct vgic_io_device *iodev;
577
578         if (!vgic_has_its(kvm))
579                 return ERR_PTR(-ENODEV);
580
581         if (!(msi->flags & KVM_MSI_VALID_DEVID))
582                 return ERR_PTR(-EINVAL);
583
584         address = (u64)msi->address_hi << 32 | msi->address_lo;
585
586         kvm_io_dev = kvm_io_bus_get_dev(kvm, KVM_MMIO_BUS, address);
587         if (!kvm_io_dev)
588                 return ERR_PTR(-EINVAL);
589
590         if (kvm_io_dev->ops != &kvm_io_gic_ops)
591                 return ERR_PTR(-EINVAL);
592
593         iodev = container_of(kvm_io_dev, struct vgic_io_device, dev);
594         if (iodev->iodev_type != IODEV_ITS)
595                 return ERR_PTR(-EINVAL);
596
597         return iodev->its;
598 }
599
600 /*
601  * Find the target VCPU and the LPI number for a given devid/eventid pair
602  * and make this IRQ pending, possibly injecting it.
603  * Must be called with the its_lock mutex held.
604  * Returns 0 on success, a positive error value for any ITS mapping
605  * related errors and negative error values for generic errors.
606  */
607 static int vgic_its_trigger_msi(struct kvm *kvm, struct vgic_its *its,
608                                 u32 devid, u32 eventid)
609 {
610         struct vgic_irq *irq = NULL;
611         unsigned long flags;
612         int err;
613
614         err = vgic_its_resolve_lpi(kvm, its, devid, eventid, &irq);
615         if (err)
616                 return err;
617
618         if (irq->hw)
619                 return irq_set_irqchip_state(irq->host_irq,
620                                              IRQCHIP_STATE_PENDING, true);
621
622         spin_lock_irqsave(&irq->irq_lock, flags);
623         irq->pending_latch = true;
624         vgic_queue_irq_unlock(kvm, irq, flags);
625
626         return 0;
627 }
628
629 /*
630  * Queries the KVM IO bus framework to get the ITS pointer from the given
631  * doorbell address.
632  * We then call vgic_its_trigger_msi() with the decoded data.
633  * According to the KVM_SIGNAL_MSI API description returns 1 on success.
634  */
635 int vgic_its_inject_msi(struct kvm *kvm, struct kvm_msi *msi)
636 {
637         struct vgic_its *its;
638         int ret;
639
640         its = vgic_msi_to_its(kvm, msi);
641         if (IS_ERR(its))
642                 return PTR_ERR(its);
643
644         mutex_lock(&its->its_lock);
645         ret = vgic_its_trigger_msi(kvm, its, msi->devid, msi->data);
646         mutex_unlock(&its->its_lock);
647
648         if (ret < 0)
649                 return ret;
650
651         /*
652          * KVM_SIGNAL_MSI demands a return value > 0 for success and 0
653          * if the guest has blocked the MSI. So we map any LPI mapping
654          * related error to that.
655          */
656         if (ret)
657                 return 0;
658         else
659                 return 1;
660 }
661
662 /* Requires the its_lock to be held. */
663 static void its_free_ite(struct kvm *kvm, struct its_ite *ite)
664 {
665         list_del(&ite->ite_list);
666
667         /* This put matches the get in vgic_add_lpi. */
668         if (ite->irq) {
669                 if (ite->irq->hw)
670                         WARN_ON(its_unmap_vlpi(ite->irq->host_irq));
671
672                 vgic_put_irq(kvm, ite->irq);
673         }
674
675         kfree(ite);
676 }
677
678 static u64 its_cmd_mask_field(u64 *its_cmd, int word, int shift, int size)
679 {
680         return (le64_to_cpu(its_cmd[word]) >> shift) & (BIT_ULL(size) - 1);
681 }
682
683 #define its_cmd_get_command(cmd)        its_cmd_mask_field(cmd, 0,  0,  8)
684 #define its_cmd_get_deviceid(cmd)       its_cmd_mask_field(cmd, 0, 32, 32)
685 #define its_cmd_get_size(cmd)           (its_cmd_mask_field(cmd, 1,  0,  5) + 1)
686 #define its_cmd_get_id(cmd)             its_cmd_mask_field(cmd, 1,  0, 32)
687 #define its_cmd_get_physical_id(cmd)    its_cmd_mask_field(cmd, 1, 32, 32)
688 #define its_cmd_get_collection(cmd)     its_cmd_mask_field(cmd, 2,  0, 16)
689 #define its_cmd_get_ittaddr(cmd)        (its_cmd_mask_field(cmd, 2,  8, 44) << 8)
690 #define its_cmd_get_target_addr(cmd)    its_cmd_mask_field(cmd, 2, 16, 32)
691 #define its_cmd_get_validbit(cmd)       its_cmd_mask_field(cmd, 2, 63,  1)
692
693 /*
694  * The DISCARD command frees an Interrupt Translation Table Entry (ITTE).
695  * Must be called with the its_lock mutex held.
696  */
697 static int vgic_its_cmd_handle_discard(struct kvm *kvm, struct vgic_its *its,
698                                        u64 *its_cmd)
699 {
700         u32 device_id = its_cmd_get_deviceid(its_cmd);
701         u32 event_id = its_cmd_get_id(its_cmd);
702         struct its_ite *ite;
703
704
705         ite = find_ite(its, device_id, event_id);
706         if (ite && ite->collection) {
707                 /*
708                  * Though the spec talks about removing the pending state, we
709                  * don't bother here since we clear the ITTE anyway and the
710                  * pending state is a property of the ITTE struct.
711                  */
712                 its_free_ite(kvm, ite);
713                 return 0;
714         }
715
716         return E_ITS_DISCARD_UNMAPPED_INTERRUPT;
717 }
718
719 /*
720  * The MOVI command moves an ITTE to a different collection.
721  * Must be called with the its_lock mutex held.
722  */
723 static int vgic_its_cmd_handle_movi(struct kvm *kvm, struct vgic_its *its,
724                                     u64 *its_cmd)
725 {
726         u32 device_id = its_cmd_get_deviceid(its_cmd);
727         u32 event_id = its_cmd_get_id(its_cmd);
728         u32 coll_id = its_cmd_get_collection(its_cmd);
729         struct kvm_vcpu *vcpu;
730         struct its_ite *ite;
731         struct its_collection *collection;
732
733         ite = find_ite(its, device_id, event_id);
734         if (!ite)
735                 return E_ITS_MOVI_UNMAPPED_INTERRUPT;
736
737         if (!its_is_collection_mapped(ite->collection))
738                 return E_ITS_MOVI_UNMAPPED_COLLECTION;
739
740         collection = find_collection(its, coll_id);
741         if (!its_is_collection_mapped(collection))
742                 return E_ITS_MOVI_UNMAPPED_COLLECTION;
743
744         ite->collection = collection;
745         vcpu = kvm_get_vcpu(kvm, collection->target_addr);
746
747         return update_affinity(ite->irq, vcpu);
748 }
749
750 /*
751  * Check whether an ID can be stored into the corresponding guest table.
752  * For a direct table this is pretty easy, but gets a bit nasty for
753  * indirect tables. We check whether the resulting guest physical address
754  * is actually valid (covered by a memslot and guest accessible).
755  * For this we have to read the respective first level entry.
756  */
757 static bool vgic_its_check_id(struct vgic_its *its, u64 baser, u32 id,
758                               gpa_t *eaddr)
759 {
760         int l1_tbl_size = GITS_BASER_NR_PAGES(baser) * SZ_64K;
761         u64 indirect_ptr, type = GITS_BASER_TYPE(baser);
762         int esz = GITS_BASER_ENTRY_SIZE(baser);
763         int index;
764         gfn_t gfn;
765
766         switch (type) {
767         case GITS_BASER_TYPE_DEVICE:
768                 if (id >= BIT_ULL(VITS_TYPER_DEVBITS))
769                         return false;
770                 break;
771         case GITS_BASER_TYPE_COLLECTION:
772                 /* as GITS_TYPER.CIL == 0, ITS supports 16-bit collection ID */
773                 if (id >= BIT_ULL(16))
774                         return false;
775                 break;
776         default:
777                 return false;
778         }
779
780         if (!(baser & GITS_BASER_INDIRECT)) {
781                 phys_addr_t addr;
782
783                 if (id >= (l1_tbl_size / esz))
784                         return false;
785
786                 addr = BASER_ADDRESS(baser) + id * esz;
787                 gfn = addr >> PAGE_SHIFT;
788
789                 if (eaddr)
790                         *eaddr = addr;
791                 return kvm_is_visible_gfn(its->dev->kvm, gfn);
792         }
793
794         /* calculate and check the index into the 1st level */
795         index = id / (SZ_64K / esz);
796         if (index >= (l1_tbl_size / sizeof(u64)))
797                 return false;
798
799         /* Each 1st level entry is represented by a 64-bit value. */
800         if (kvm_read_guest_lock(its->dev->kvm,
801                            BASER_ADDRESS(baser) + index * sizeof(indirect_ptr),
802                            &indirect_ptr, sizeof(indirect_ptr)))
803                 return false;
804
805         indirect_ptr = le64_to_cpu(indirect_ptr);
806
807         /* check the valid bit of the first level entry */
808         if (!(indirect_ptr & BIT_ULL(63)))
809                 return false;
810
811         /*
812          * Mask the guest physical address and calculate the frame number.
813          * Any address beyond our supported 48 bits of PA will be caught
814          * by the actual check in the final step.
815          */
816         indirect_ptr &= GENMASK_ULL(51, 16);
817
818         /* Find the address of the actual entry */
819         index = id % (SZ_64K / esz);
820         indirect_ptr += index * esz;
821         gfn = indirect_ptr >> PAGE_SHIFT;
822
823         if (eaddr)
824                 *eaddr = indirect_ptr;
825         return kvm_is_visible_gfn(its->dev->kvm, gfn);
826 }
827
828 static int vgic_its_alloc_collection(struct vgic_its *its,
829                                      struct its_collection **colp,
830                                      u32 coll_id)
831 {
832         struct its_collection *collection;
833
834         if (!vgic_its_check_id(its, its->baser_coll_table, coll_id, NULL))
835                 return E_ITS_MAPC_COLLECTION_OOR;
836
837         collection = kzalloc(sizeof(*collection), GFP_KERNEL);
838         if (!collection)
839                 return -ENOMEM;
840
841         collection->collection_id = coll_id;
842         collection->target_addr = COLLECTION_NOT_MAPPED;
843
844         list_add_tail(&collection->coll_list, &its->collection_list);
845         *colp = collection;
846
847         return 0;
848 }
849
850 static void vgic_its_free_collection(struct vgic_its *its, u32 coll_id)
851 {
852         struct its_collection *collection;
853         struct its_device *device;
854         struct its_ite *ite;
855
856         /*
857          * Clearing the mapping for that collection ID removes the
858          * entry from the list. If there wasn't any before, we can
859          * go home early.
860          */
861         collection = find_collection(its, coll_id);
862         if (!collection)
863                 return;
864
865         for_each_lpi_its(device, ite, its)
866                 if (ite->collection &&
867                     ite->collection->collection_id == coll_id)
868                         ite->collection = NULL;
869
870         list_del(&collection->coll_list);
871         kfree(collection);
872 }
873
874 /* Must be called with its_lock mutex held */
875 static struct its_ite *vgic_its_alloc_ite(struct its_device *device,
876                                           struct its_collection *collection,
877                                           u32 event_id)
878 {
879         struct its_ite *ite;
880
881         ite = kzalloc(sizeof(*ite), GFP_KERNEL);
882         if (!ite)
883                 return ERR_PTR(-ENOMEM);
884
885         ite->event_id   = event_id;
886         ite->collection = collection;
887
888         list_add_tail(&ite->ite_list, &device->itt_head);
889         return ite;
890 }
891
892 /*
893  * The MAPTI and MAPI commands map LPIs to ITTEs.
894  * Must be called with its_lock mutex held.
895  */
896 static int vgic_its_cmd_handle_mapi(struct kvm *kvm, struct vgic_its *its,
897                                     u64 *its_cmd)
898 {
899         u32 device_id = its_cmd_get_deviceid(its_cmd);
900         u32 event_id = its_cmd_get_id(its_cmd);
901         u32 coll_id = its_cmd_get_collection(its_cmd);
902         struct its_ite *ite;
903         struct kvm_vcpu *vcpu = NULL;
904         struct its_device *device;
905         struct its_collection *collection, *new_coll = NULL;
906         struct vgic_irq *irq;
907         int lpi_nr;
908
909         device = find_its_device(its, device_id);
910         if (!device)
911                 return E_ITS_MAPTI_UNMAPPED_DEVICE;
912
913         if (event_id >= BIT_ULL(device->num_eventid_bits))
914                 return E_ITS_MAPTI_ID_OOR;
915
916         if (its_cmd_get_command(its_cmd) == GITS_CMD_MAPTI)
917                 lpi_nr = its_cmd_get_physical_id(its_cmd);
918         else
919                 lpi_nr = event_id;
920         if (lpi_nr < GIC_LPI_OFFSET ||
921             lpi_nr >= max_lpis_propbaser(kvm->arch.vgic.propbaser))
922                 return E_ITS_MAPTI_PHYSICALID_OOR;
923
924         /* If there is an existing mapping, behavior is UNPREDICTABLE. */
925         if (find_ite(its, device_id, event_id))
926                 return 0;
927
928         collection = find_collection(its, coll_id);
929         if (!collection) {
930                 int ret = vgic_its_alloc_collection(its, &collection, coll_id);
931                 if (ret)
932                         return ret;
933                 new_coll = collection;
934         }
935
936         ite = vgic_its_alloc_ite(device, collection, event_id);
937         if (IS_ERR(ite)) {
938                 if (new_coll)
939                         vgic_its_free_collection(its, coll_id);
940                 return PTR_ERR(ite);
941         }
942
943         if (its_is_collection_mapped(collection))
944                 vcpu = kvm_get_vcpu(kvm, collection->target_addr);
945
946         irq = vgic_add_lpi(kvm, lpi_nr, vcpu);
947         if (IS_ERR(irq)) {
948                 if (new_coll)
949                         vgic_its_free_collection(its, coll_id);
950                 its_free_ite(kvm, ite);
951                 return PTR_ERR(irq);
952         }
953         ite->irq = irq;
954
955         return 0;
956 }
957
958 /* Requires the its_lock to be held. */
959 static void vgic_its_free_device(struct kvm *kvm, struct its_device *device)
960 {
961         struct its_ite *ite, *temp;
962
963         /*
964          * The spec says that unmapping a device with still valid
965          * ITTEs associated is UNPREDICTABLE. We remove all ITTEs,
966          * since we cannot leave the memory unreferenced.
967          */
968         list_for_each_entry_safe(ite, temp, &device->itt_head, ite_list)
969                 its_free_ite(kvm, ite);
970
971         list_del(&device->dev_list);
972         kfree(device);
973 }
974
975 /* its lock must be held */
976 static void vgic_its_free_device_list(struct kvm *kvm, struct vgic_its *its)
977 {
978         struct its_device *cur, *temp;
979
980         list_for_each_entry_safe(cur, temp, &its->device_list, dev_list)
981                 vgic_its_free_device(kvm, cur);
982 }
983
984 /* its lock must be held */
985 static void vgic_its_free_collection_list(struct kvm *kvm, struct vgic_its *its)
986 {
987         struct its_collection *cur, *temp;
988
989         list_for_each_entry_safe(cur, temp, &its->collection_list, coll_list)
990                 vgic_its_free_collection(its, cur->collection_id);
991 }
992
993 /* Must be called with its_lock mutex held */
994 static struct its_device *vgic_its_alloc_device(struct vgic_its *its,
995                                                 u32 device_id, gpa_t itt_addr,
996                                                 u8 num_eventid_bits)
997 {
998         struct its_device *device;
999
1000         device = kzalloc(sizeof(*device), GFP_KERNEL);
1001         if (!device)
1002                 return ERR_PTR(-ENOMEM);
1003
1004         device->device_id = device_id;
1005         device->itt_addr = itt_addr;
1006         device->num_eventid_bits = num_eventid_bits;
1007         INIT_LIST_HEAD(&device->itt_head);
1008
1009         list_add_tail(&device->dev_list, &its->device_list);
1010         return device;
1011 }
1012
1013 /*
1014  * MAPD maps or unmaps a device ID to Interrupt Translation Tables (ITTs).
1015  * Must be called with the its_lock mutex held.
1016  */
1017 static int vgic_its_cmd_handle_mapd(struct kvm *kvm, struct vgic_its *its,
1018                                     u64 *its_cmd)
1019 {
1020         u32 device_id = its_cmd_get_deviceid(its_cmd);
1021         bool valid = its_cmd_get_validbit(its_cmd);
1022         u8 num_eventid_bits = its_cmd_get_size(its_cmd);
1023         gpa_t itt_addr = its_cmd_get_ittaddr(its_cmd);
1024         struct its_device *device;
1025
1026         if (!vgic_its_check_id(its, its->baser_device_table, device_id, NULL))
1027                 return E_ITS_MAPD_DEVICE_OOR;
1028
1029         if (valid && num_eventid_bits > VITS_TYPER_IDBITS)
1030                 return E_ITS_MAPD_ITTSIZE_OOR;
1031
1032         device = find_its_device(its, device_id);
1033
1034         /*
1035          * The spec says that calling MAPD on an already mapped device
1036          * invalidates all cached data for this device. We implement this
1037          * by removing the mapping and re-establishing it.
1038          */
1039         if (device)
1040                 vgic_its_free_device(kvm, device);
1041
1042         /*
1043          * The spec does not say whether unmapping a not-mapped device
1044          * is an error, so we are done in any case.
1045          */
1046         if (!valid)
1047                 return 0;
1048
1049         device = vgic_its_alloc_device(its, device_id, itt_addr,
1050                                        num_eventid_bits);
1051
1052         return PTR_ERR_OR_ZERO(device);
1053 }
1054
1055 /*
1056  * The MAPC command maps collection IDs to redistributors.
1057  * Must be called with the its_lock mutex held.
1058  */
1059 static int vgic_its_cmd_handle_mapc(struct kvm *kvm, struct vgic_its *its,
1060                                     u64 *its_cmd)
1061 {
1062         u16 coll_id;
1063         u32 target_addr;
1064         struct its_collection *collection;
1065         bool valid;
1066
1067         valid = its_cmd_get_validbit(its_cmd);
1068         coll_id = its_cmd_get_collection(its_cmd);
1069         target_addr = its_cmd_get_target_addr(its_cmd);
1070
1071         if (target_addr >= atomic_read(&kvm->online_vcpus))
1072                 return E_ITS_MAPC_PROCNUM_OOR;
1073
1074         if (!valid) {
1075                 vgic_its_free_collection(its, coll_id);
1076         } else {
1077                 collection = find_collection(its, coll_id);
1078
1079                 if (!collection) {
1080                         int ret;
1081
1082                         ret = vgic_its_alloc_collection(its, &collection,
1083                                                         coll_id);
1084                         if (ret)
1085                                 return ret;
1086                         collection->target_addr = target_addr;
1087                 } else {
1088                         collection->target_addr = target_addr;
1089                         update_affinity_collection(kvm, its, collection);
1090                 }
1091         }
1092
1093         return 0;
1094 }
1095
1096 /*
1097  * The CLEAR command removes the pending state for a particular LPI.
1098  * Must be called with the its_lock mutex held.
1099  */
1100 static int vgic_its_cmd_handle_clear(struct kvm *kvm, struct vgic_its *its,
1101                                      u64 *its_cmd)
1102 {
1103         u32 device_id = its_cmd_get_deviceid(its_cmd);
1104         u32 event_id = its_cmd_get_id(its_cmd);
1105         struct its_ite *ite;
1106
1107
1108         ite = find_ite(its, device_id, event_id);
1109         if (!ite)
1110                 return E_ITS_CLEAR_UNMAPPED_INTERRUPT;
1111
1112         ite->irq->pending_latch = false;
1113
1114         if (ite->irq->hw)
1115                 return irq_set_irqchip_state(ite->irq->host_irq,
1116                                              IRQCHIP_STATE_PENDING, false);
1117
1118         return 0;
1119 }
1120
1121 /*
1122  * The INV command syncs the configuration bits from the memory table.
1123  * Must be called with the its_lock mutex held.
1124  */
1125 static int vgic_its_cmd_handle_inv(struct kvm *kvm, struct vgic_its *its,
1126                                    u64 *its_cmd)
1127 {
1128         u32 device_id = its_cmd_get_deviceid(its_cmd);
1129         u32 event_id = its_cmd_get_id(its_cmd);
1130         struct its_ite *ite;
1131
1132
1133         ite = find_ite(its, device_id, event_id);
1134         if (!ite)
1135                 return E_ITS_INV_UNMAPPED_INTERRUPT;
1136
1137         return update_lpi_config(kvm, ite->irq, NULL, true);
1138 }
1139
1140 /*
1141  * The INVALL command requests flushing of all IRQ data in this collection.
1142  * Find the VCPU mapped to that collection, then iterate over the VM's list
1143  * of mapped LPIs and update the configuration for each IRQ which targets
1144  * the specified vcpu. The configuration will be read from the in-memory
1145  * configuration table.
1146  * Must be called with the its_lock mutex held.
1147  */
1148 static int vgic_its_cmd_handle_invall(struct kvm *kvm, struct vgic_its *its,
1149                                       u64 *its_cmd)
1150 {
1151         u32 coll_id = its_cmd_get_collection(its_cmd);
1152         struct its_collection *collection;
1153         struct kvm_vcpu *vcpu;
1154         struct vgic_irq *irq;
1155         u32 *intids;
1156         int irq_count, i;
1157
1158         collection = find_collection(its, coll_id);
1159         if (!its_is_collection_mapped(collection))
1160                 return E_ITS_INVALL_UNMAPPED_COLLECTION;
1161
1162         vcpu = kvm_get_vcpu(kvm, collection->target_addr);
1163
1164         irq_count = vgic_copy_lpi_list(kvm, vcpu, &intids);
1165         if (irq_count < 0)
1166                 return irq_count;
1167
1168         for (i = 0; i < irq_count; i++) {
1169                 irq = vgic_get_irq(kvm, NULL, intids[i]);
1170                 if (!irq)
1171                         continue;
1172                 update_lpi_config(kvm, irq, vcpu, false);
1173                 vgic_put_irq(kvm, irq);
1174         }
1175
1176         kfree(intids);
1177
1178         if (vcpu->arch.vgic_cpu.vgic_v3.its_vpe.its_vm)
1179                 its_invall_vpe(&vcpu->arch.vgic_cpu.vgic_v3.its_vpe);
1180
1181         return 0;
1182 }
1183
1184 /*
1185  * The MOVALL command moves the pending state of all IRQs targeting one
1186  * redistributor to another. We don't hold the pending state in the VCPUs,
1187  * but in the IRQs instead, so there is really not much to do for us here.
1188  * However the spec says that no IRQ must target the old redistributor
1189  * afterwards, so we make sure that no LPI is using the associated target_vcpu.
1190  * This command affects all LPIs in the system that target that redistributor.
1191  */
1192 static int vgic_its_cmd_handle_movall(struct kvm *kvm, struct vgic_its *its,
1193                                       u64 *its_cmd)
1194 {
1195         u32 target1_addr = its_cmd_get_target_addr(its_cmd);
1196         u32 target2_addr = its_cmd_mask_field(its_cmd, 3, 16, 32);
1197         struct kvm_vcpu *vcpu1, *vcpu2;
1198         struct vgic_irq *irq;
1199         u32 *intids;
1200         int irq_count, i;
1201
1202         if (target1_addr >= atomic_read(&kvm->online_vcpus) ||
1203             target2_addr >= atomic_read(&kvm->online_vcpus))
1204                 return E_ITS_MOVALL_PROCNUM_OOR;
1205
1206         if (target1_addr == target2_addr)
1207                 return 0;
1208
1209         vcpu1 = kvm_get_vcpu(kvm, target1_addr);
1210         vcpu2 = kvm_get_vcpu(kvm, target2_addr);
1211
1212         irq_count = vgic_copy_lpi_list(kvm, vcpu1, &intids);
1213         if (irq_count < 0)
1214                 return irq_count;
1215
1216         for (i = 0; i < irq_count; i++) {
1217                 irq = vgic_get_irq(kvm, NULL, intids[i]);
1218
1219                 update_affinity(irq, vcpu2);
1220
1221                 vgic_put_irq(kvm, irq);
1222         }
1223
1224         kfree(intids);
1225         return 0;
1226 }
1227
1228 /*
1229  * The INT command injects the LPI associated with that DevID/EvID pair.
1230  * Must be called with the its_lock mutex held.
1231  */
1232 static int vgic_its_cmd_handle_int(struct kvm *kvm, struct vgic_its *its,
1233                                    u64 *its_cmd)
1234 {
1235         u32 msi_data = its_cmd_get_id(its_cmd);
1236         u64 msi_devid = its_cmd_get_deviceid(its_cmd);
1237
1238         return vgic_its_trigger_msi(kvm, its, msi_devid, msi_data);
1239 }
1240
1241 /*
1242  * This function is called with the its_cmd lock held, but the ITS data
1243  * structure lock dropped.
1244  */
1245 static int vgic_its_handle_command(struct kvm *kvm, struct vgic_its *its,
1246                                    u64 *its_cmd)
1247 {
1248         int ret = -ENODEV;
1249
1250         mutex_lock(&its->its_lock);
1251         switch (its_cmd_get_command(its_cmd)) {
1252         case GITS_CMD_MAPD:
1253                 ret = vgic_its_cmd_handle_mapd(kvm, its, its_cmd);
1254                 break;
1255         case GITS_CMD_MAPC:
1256                 ret = vgic_its_cmd_handle_mapc(kvm, its, its_cmd);
1257                 break;
1258         case GITS_CMD_MAPI:
1259                 ret = vgic_its_cmd_handle_mapi(kvm, its, its_cmd);
1260                 break;
1261         case GITS_CMD_MAPTI:
1262                 ret = vgic_its_cmd_handle_mapi(kvm, its, its_cmd);
1263                 break;
1264         case GITS_CMD_MOVI:
1265                 ret = vgic_its_cmd_handle_movi(kvm, its, its_cmd);
1266                 break;
1267         case GITS_CMD_DISCARD:
1268                 ret = vgic_its_cmd_handle_discard(kvm, its, its_cmd);
1269                 break;
1270         case GITS_CMD_CLEAR:
1271                 ret = vgic_its_cmd_handle_clear(kvm, its, its_cmd);
1272                 break;
1273         case GITS_CMD_MOVALL:
1274                 ret = vgic_its_cmd_handle_movall(kvm, its, its_cmd);
1275                 break;
1276         case GITS_CMD_INT:
1277                 ret = vgic_its_cmd_handle_int(kvm, its, its_cmd);
1278                 break;
1279         case GITS_CMD_INV:
1280                 ret = vgic_its_cmd_handle_inv(kvm, its, its_cmd);
1281                 break;
1282         case GITS_CMD_INVALL:
1283                 ret = vgic_its_cmd_handle_invall(kvm, its, its_cmd);
1284                 break;
1285         case GITS_CMD_SYNC:
1286                 /* we ignore this command: we are in sync all of the time */
1287                 ret = 0;
1288                 break;
1289         }
1290         mutex_unlock(&its->its_lock);
1291
1292         return ret;
1293 }
1294
1295 static u64 vgic_sanitise_its_baser(u64 reg)
1296 {
1297         reg = vgic_sanitise_field(reg, GITS_BASER_SHAREABILITY_MASK,
1298                                   GITS_BASER_SHAREABILITY_SHIFT,
1299                                   vgic_sanitise_shareability);
1300         reg = vgic_sanitise_field(reg, GITS_BASER_INNER_CACHEABILITY_MASK,
1301                                   GITS_BASER_INNER_CACHEABILITY_SHIFT,
1302                                   vgic_sanitise_inner_cacheability);
1303         reg = vgic_sanitise_field(reg, GITS_BASER_OUTER_CACHEABILITY_MASK,
1304                                   GITS_BASER_OUTER_CACHEABILITY_SHIFT,
1305                                   vgic_sanitise_outer_cacheability);
1306
1307         /* Bits 15:12 contain bits 51:48 of the PA, which we don't support. */
1308         reg &= ~GENMASK_ULL(15, 12);
1309
1310         /* We support only one (ITS) page size: 64K */
1311         reg = (reg & ~GITS_BASER_PAGE_SIZE_MASK) | GITS_BASER_PAGE_SIZE_64K;
1312
1313         return reg;
1314 }
1315
1316 static u64 vgic_sanitise_its_cbaser(u64 reg)
1317 {
1318         reg = vgic_sanitise_field(reg, GITS_CBASER_SHAREABILITY_MASK,
1319                                   GITS_CBASER_SHAREABILITY_SHIFT,
1320                                   vgic_sanitise_shareability);
1321         reg = vgic_sanitise_field(reg, GITS_CBASER_INNER_CACHEABILITY_MASK,
1322                                   GITS_CBASER_INNER_CACHEABILITY_SHIFT,
1323                                   vgic_sanitise_inner_cacheability);
1324         reg = vgic_sanitise_field(reg, GITS_CBASER_OUTER_CACHEABILITY_MASK,
1325                                   GITS_CBASER_OUTER_CACHEABILITY_SHIFT,
1326                                   vgic_sanitise_outer_cacheability);
1327
1328         /*
1329          * Sanitise the physical address to be 64k aligned.
1330          * Also limit the physical addresses to 48 bits.
1331          */
1332         reg &= ~(GENMASK_ULL(51, 48) | GENMASK_ULL(15, 12));
1333
1334         return reg;
1335 }
1336
1337 static unsigned long vgic_mmio_read_its_cbaser(struct kvm *kvm,
1338                                                struct vgic_its *its,
1339                                                gpa_t addr, unsigned int len)
1340 {
1341         return extract_bytes(its->cbaser, addr & 7, len);
1342 }
1343
1344 static void vgic_mmio_write_its_cbaser(struct kvm *kvm, struct vgic_its *its,
1345                                        gpa_t addr, unsigned int len,
1346                                        unsigned long val)
1347 {
1348         /* When GITS_CTLR.Enable is 1, this register is RO. */
1349         if (its->enabled)
1350                 return;
1351
1352         mutex_lock(&its->cmd_lock);
1353         its->cbaser = update_64bit_reg(its->cbaser, addr & 7, len, val);
1354         its->cbaser = vgic_sanitise_its_cbaser(its->cbaser);
1355         its->creadr = 0;
1356         /*
1357          * CWRITER is architecturally UNKNOWN on reset, but we need to reset
1358          * it to CREADR to make sure we start with an empty command buffer.
1359          */
1360         its->cwriter = its->creadr;
1361         mutex_unlock(&its->cmd_lock);
1362 }
1363
1364 #define ITS_CMD_BUFFER_SIZE(baser)      ((((baser) & 0xff) + 1) << 12)
1365 #define ITS_CMD_SIZE                    32
1366 #define ITS_CMD_OFFSET(reg)             ((reg) & GENMASK(19, 5))
1367
1368 /* Must be called with the cmd_lock held. */
1369 static void vgic_its_process_commands(struct kvm *kvm, struct vgic_its *its)
1370 {
1371         gpa_t cbaser;
1372         u64 cmd_buf[4];
1373
1374         /* Commands are only processed when the ITS is enabled. */
1375         if (!its->enabled)
1376                 return;
1377
1378         cbaser = CBASER_ADDRESS(its->cbaser);
1379
1380         while (its->cwriter != its->creadr) {
1381                 int ret = kvm_read_guest_lock(kvm, cbaser + its->creadr,
1382                                               cmd_buf, ITS_CMD_SIZE);
1383                 /*
1384                  * If kvm_read_guest() fails, this could be due to the guest
1385                  * programming a bogus value in CBASER or something else going
1386                  * wrong from which we cannot easily recover.
1387                  * According to section 6.3.2 in the GICv3 spec we can just
1388                  * ignore that command then.
1389                  */
1390                 if (!ret)
1391                         vgic_its_handle_command(kvm, its, cmd_buf);
1392
1393                 its->creadr += ITS_CMD_SIZE;
1394                 if (its->creadr == ITS_CMD_BUFFER_SIZE(its->cbaser))
1395                         its->creadr = 0;
1396         }
1397 }
1398
1399 /*
1400  * By writing to CWRITER the guest announces new commands to be processed.
1401  * To avoid any races in the first place, we take the its_cmd lock, which
1402  * protects our ring buffer variables, so that there is only one user
1403  * per ITS handling commands at a given time.
1404  */
1405 static void vgic_mmio_write_its_cwriter(struct kvm *kvm, struct vgic_its *its,
1406                                         gpa_t addr, unsigned int len,
1407                                         unsigned long val)
1408 {
1409         u64 reg;
1410
1411         if (!its)
1412                 return;
1413
1414         mutex_lock(&its->cmd_lock);
1415
1416         reg = update_64bit_reg(its->cwriter, addr & 7, len, val);
1417         reg = ITS_CMD_OFFSET(reg);
1418         if (reg >= ITS_CMD_BUFFER_SIZE(its->cbaser)) {
1419                 mutex_unlock(&its->cmd_lock);
1420                 return;
1421         }
1422         its->cwriter = reg;
1423
1424         vgic_its_process_commands(kvm, its);
1425
1426         mutex_unlock(&its->cmd_lock);
1427 }
1428
1429 static unsigned long vgic_mmio_read_its_cwriter(struct kvm *kvm,
1430                                                 struct vgic_its *its,
1431                                                 gpa_t addr, unsigned int len)
1432 {
1433         return extract_bytes(its->cwriter, addr & 0x7, len);
1434 }
1435
1436 static unsigned long vgic_mmio_read_its_creadr(struct kvm *kvm,
1437                                                struct vgic_its *its,
1438                                                gpa_t addr, unsigned int len)
1439 {
1440         return extract_bytes(its->creadr, addr & 0x7, len);
1441 }
1442
1443 static int vgic_mmio_uaccess_write_its_creadr(struct kvm *kvm,
1444                                               struct vgic_its *its,
1445                                               gpa_t addr, unsigned int len,
1446                                               unsigned long val)
1447 {
1448         u32 cmd_offset;
1449         int ret = 0;
1450
1451         mutex_lock(&its->cmd_lock);
1452
1453         if (its->enabled) {
1454                 ret = -EBUSY;
1455                 goto out;
1456         }
1457
1458         cmd_offset = ITS_CMD_OFFSET(val);
1459         if (cmd_offset >= ITS_CMD_BUFFER_SIZE(its->cbaser)) {
1460                 ret = -EINVAL;
1461                 goto out;
1462         }
1463
1464         its->creadr = cmd_offset;
1465 out:
1466         mutex_unlock(&its->cmd_lock);
1467         return ret;
1468 }
1469
1470 #define BASER_INDEX(addr) (((addr) / sizeof(u64)) & 0x7)
1471 static unsigned long vgic_mmio_read_its_baser(struct kvm *kvm,
1472                                               struct vgic_its *its,
1473                                               gpa_t addr, unsigned int len)
1474 {
1475         u64 reg;
1476
1477         switch (BASER_INDEX(addr)) {
1478         case 0:
1479                 reg = its->baser_device_table;
1480                 break;
1481         case 1:
1482                 reg = its->baser_coll_table;
1483                 break;
1484         default:
1485                 reg = 0;
1486                 break;
1487         }
1488
1489         return extract_bytes(reg, addr & 7, len);
1490 }
1491
1492 #define GITS_BASER_RO_MASK      (GENMASK_ULL(52, 48) | GENMASK_ULL(58, 56))
1493 static void vgic_mmio_write_its_baser(struct kvm *kvm,
1494                                       struct vgic_its *its,
1495                                       gpa_t addr, unsigned int len,
1496                                       unsigned long val)
1497 {
1498         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
1499         u64 entry_size, table_type;
1500         u64 reg, *regptr, clearbits = 0;
1501
1502         /* When GITS_CTLR.Enable is 1, we ignore write accesses. */
1503         if (its->enabled)
1504                 return;
1505
1506         switch (BASER_INDEX(addr)) {
1507         case 0:
1508                 regptr = &its->baser_device_table;
1509                 entry_size = abi->dte_esz;
1510                 table_type = GITS_BASER_TYPE_DEVICE;
1511                 break;
1512         case 1:
1513                 regptr = &its->baser_coll_table;
1514                 entry_size = abi->cte_esz;
1515                 table_type = GITS_BASER_TYPE_COLLECTION;
1516                 clearbits = GITS_BASER_INDIRECT;
1517                 break;
1518         default:
1519                 return;
1520         }
1521
1522         reg = update_64bit_reg(*regptr, addr & 7, len, val);
1523         reg &= ~GITS_BASER_RO_MASK;
1524         reg &= ~clearbits;
1525
1526         reg |= (entry_size - 1) << GITS_BASER_ENTRY_SIZE_SHIFT;
1527         reg |= table_type << GITS_BASER_TYPE_SHIFT;
1528         reg = vgic_sanitise_its_baser(reg);
1529
1530         *regptr = reg;
1531
1532         if (!(reg & GITS_BASER_VALID)) {
1533                 /* Take the its_lock to prevent a race with a save/restore */
1534                 mutex_lock(&its->its_lock);
1535                 switch (table_type) {
1536                 case GITS_BASER_TYPE_DEVICE:
1537                         vgic_its_free_device_list(kvm, its);
1538                         break;
1539                 case GITS_BASER_TYPE_COLLECTION:
1540                         vgic_its_free_collection_list(kvm, its);
1541                         break;
1542                 }
1543                 mutex_unlock(&its->its_lock);
1544         }
1545 }
1546
1547 static unsigned long vgic_mmio_read_its_ctlr(struct kvm *vcpu,
1548                                              struct vgic_its *its,
1549                                              gpa_t addr, unsigned int len)
1550 {
1551         u32 reg = 0;
1552
1553         mutex_lock(&its->cmd_lock);
1554         if (its->creadr == its->cwriter)
1555                 reg |= GITS_CTLR_QUIESCENT;
1556         if (its->enabled)
1557                 reg |= GITS_CTLR_ENABLE;
1558         mutex_unlock(&its->cmd_lock);
1559
1560         return reg;
1561 }
1562
1563 static void vgic_mmio_write_its_ctlr(struct kvm *kvm, struct vgic_its *its,
1564                                      gpa_t addr, unsigned int len,
1565                                      unsigned long val)
1566 {
1567         mutex_lock(&its->cmd_lock);
1568
1569         /*
1570          * It is UNPREDICTABLE to enable the ITS if any of the CBASER or
1571          * device/collection BASER are invalid
1572          */
1573         if (!its->enabled && (val & GITS_CTLR_ENABLE) &&
1574                 (!(its->baser_device_table & GITS_BASER_VALID) ||
1575                  !(its->baser_coll_table & GITS_BASER_VALID) ||
1576                  !(its->cbaser & GITS_CBASER_VALID)))
1577                 goto out;
1578
1579         its->enabled = !!(val & GITS_CTLR_ENABLE);
1580
1581         /*
1582          * Try to process any pending commands. This function bails out early
1583          * if the ITS is disabled or no commands have been queued.
1584          */
1585         vgic_its_process_commands(kvm, its);
1586
1587 out:
1588         mutex_unlock(&its->cmd_lock);
1589 }
1590
1591 #define REGISTER_ITS_DESC(off, rd, wr, length, acc)             \
1592 {                                                               \
1593         .reg_offset = off,                                      \
1594         .len = length,                                          \
1595         .access_flags = acc,                                    \
1596         .its_read = rd,                                         \
1597         .its_write = wr,                                        \
1598 }
1599
1600 #define REGISTER_ITS_DESC_UACCESS(off, rd, wr, uwr, length, acc)\
1601 {                                                               \
1602         .reg_offset = off,                                      \
1603         .len = length,                                          \
1604         .access_flags = acc,                                    \
1605         .its_read = rd,                                         \
1606         .its_write = wr,                                        \
1607         .uaccess_its_write = uwr,                               \
1608 }
1609
1610 static void its_mmio_write_wi(struct kvm *kvm, struct vgic_its *its,
1611                               gpa_t addr, unsigned int len, unsigned long val)
1612 {
1613         /* Ignore */
1614 }
1615
1616 static struct vgic_register_region its_registers[] = {
1617         REGISTER_ITS_DESC(GITS_CTLR,
1618                 vgic_mmio_read_its_ctlr, vgic_mmio_write_its_ctlr, 4,
1619                 VGIC_ACCESS_32bit),
1620         REGISTER_ITS_DESC_UACCESS(GITS_IIDR,
1621                 vgic_mmio_read_its_iidr, its_mmio_write_wi,
1622                 vgic_mmio_uaccess_write_its_iidr, 4,
1623                 VGIC_ACCESS_32bit),
1624         REGISTER_ITS_DESC(GITS_TYPER,
1625                 vgic_mmio_read_its_typer, its_mmio_write_wi, 8,
1626                 VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1627         REGISTER_ITS_DESC(GITS_CBASER,
1628                 vgic_mmio_read_its_cbaser, vgic_mmio_write_its_cbaser, 8,
1629                 VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1630         REGISTER_ITS_DESC(GITS_CWRITER,
1631                 vgic_mmio_read_its_cwriter, vgic_mmio_write_its_cwriter, 8,
1632                 VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1633         REGISTER_ITS_DESC_UACCESS(GITS_CREADR,
1634                 vgic_mmio_read_its_creadr, its_mmio_write_wi,
1635                 vgic_mmio_uaccess_write_its_creadr, 8,
1636                 VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1637         REGISTER_ITS_DESC(GITS_BASER,
1638                 vgic_mmio_read_its_baser, vgic_mmio_write_its_baser, 0x40,
1639                 VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1640         REGISTER_ITS_DESC(GITS_IDREGS_BASE,
1641                 vgic_mmio_read_its_idregs, its_mmio_write_wi, 0x30,
1642                 VGIC_ACCESS_32bit),
1643 };
1644
1645 /* This is called on setting the LPI enable bit in the redistributor. */
1646 void vgic_enable_lpis(struct kvm_vcpu *vcpu)
1647 {
1648         if (!(vcpu->arch.vgic_cpu.pendbaser & GICR_PENDBASER_PTZ))
1649                 its_sync_lpi_pending_table(vcpu);
1650 }
1651
1652 static int vgic_register_its_iodev(struct kvm *kvm, struct vgic_its *its,
1653                                    u64 addr)
1654 {
1655         struct vgic_io_device *iodev = &its->iodev;
1656         int ret;
1657
1658         mutex_lock(&kvm->slots_lock);
1659         if (!IS_VGIC_ADDR_UNDEF(its->vgic_its_base)) {
1660                 ret = -EBUSY;
1661                 goto out;
1662         }
1663
1664         its->vgic_its_base = addr;
1665         iodev->regions = its_registers;
1666         iodev->nr_regions = ARRAY_SIZE(its_registers);
1667         kvm_iodevice_init(&iodev->dev, &kvm_io_gic_ops);
1668
1669         iodev->base_addr = its->vgic_its_base;
1670         iodev->iodev_type = IODEV_ITS;
1671         iodev->its = its;
1672         ret = kvm_io_bus_register_dev(kvm, KVM_MMIO_BUS, iodev->base_addr,
1673                                       KVM_VGIC_V3_ITS_SIZE, &iodev->dev);
1674 out:
1675         mutex_unlock(&kvm->slots_lock);
1676
1677         return ret;
1678 }
1679
1680 #define INITIAL_BASER_VALUE                                               \
1681         (GIC_BASER_CACHEABILITY(GITS_BASER, INNER, RaWb)                | \
1682          GIC_BASER_CACHEABILITY(GITS_BASER, OUTER, SameAsInner)         | \
1683          GIC_BASER_SHAREABILITY(GITS_BASER, InnerShareable)             | \
1684          GITS_BASER_PAGE_SIZE_64K)
1685
1686 #define INITIAL_PROPBASER_VALUE                                           \
1687         (GIC_BASER_CACHEABILITY(GICR_PROPBASER, INNER, RaWb)            | \
1688          GIC_BASER_CACHEABILITY(GICR_PROPBASER, OUTER, SameAsInner)     | \
1689          GIC_BASER_SHAREABILITY(GICR_PROPBASER, InnerShareable))
1690
1691 static int vgic_its_create(struct kvm_device *dev, u32 type)
1692 {
1693         struct vgic_its *its;
1694
1695         if (type != KVM_DEV_TYPE_ARM_VGIC_ITS)
1696                 return -ENODEV;
1697
1698         its = kzalloc(sizeof(struct vgic_its), GFP_KERNEL);
1699         if (!its)
1700                 return -ENOMEM;
1701
1702         if (vgic_initialized(dev->kvm)) {
1703                 int ret = vgic_v4_init(dev->kvm);
1704                 if (ret < 0) {
1705                         kfree(its);
1706                         return ret;
1707                 }
1708         }
1709
1710         mutex_init(&its->its_lock);
1711         mutex_init(&its->cmd_lock);
1712
1713         its->vgic_its_base = VGIC_ADDR_UNDEF;
1714
1715         INIT_LIST_HEAD(&its->device_list);
1716         INIT_LIST_HEAD(&its->collection_list);
1717
1718         dev->kvm->arch.vgic.msis_require_devid = true;
1719         dev->kvm->arch.vgic.has_its = true;
1720         its->enabled = false;
1721         its->dev = dev;
1722
1723         its->baser_device_table = INITIAL_BASER_VALUE                   |
1724                 ((u64)GITS_BASER_TYPE_DEVICE << GITS_BASER_TYPE_SHIFT);
1725         its->baser_coll_table = INITIAL_BASER_VALUE |
1726                 ((u64)GITS_BASER_TYPE_COLLECTION << GITS_BASER_TYPE_SHIFT);
1727         dev->kvm->arch.vgic.propbaser = INITIAL_PROPBASER_VALUE;
1728
1729         dev->private = its;
1730
1731         return vgic_its_set_abi(its, NR_ITS_ABIS - 1);
1732 }
1733
1734 static void vgic_its_destroy(struct kvm_device *kvm_dev)
1735 {
1736         struct kvm *kvm = kvm_dev->kvm;
1737         struct vgic_its *its = kvm_dev->private;
1738
1739         mutex_lock(&its->its_lock);
1740
1741         vgic_its_free_device_list(kvm, its);
1742         vgic_its_free_collection_list(kvm, its);
1743
1744         mutex_unlock(&its->its_lock);
1745         kfree(its);
1746 }
1747
1748 int vgic_its_has_attr_regs(struct kvm_device *dev,
1749                            struct kvm_device_attr *attr)
1750 {
1751         const struct vgic_register_region *region;
1752         gpa_t offset = attr->attr;
1753         int align;
1754
1755         align = (offset < GITS_TYPER) || (offset >= GITS_PIDR4) ? 0x3 : 0x7;
1756
1757         if (offset & align)
1758                 return -EINVAL;
1759
1760         region = vgic_find_mmio_region(its_registers,
1761                                        ARRAY_SIZE(its_registers),
1762                                        offset);
1763         if (!region)
1764                 return -ENXIO;
1765
1766         return 0;
1767 }
1768
1769 int vgic_its_attr_regs_access(struct kvm_device *dev,
1770                               struct kvm_device_attr *attr,
1771                               u64 *reg, bool is_write)
1772 {
1773         const struct vgic_register_region *region;
1774         struct vgic_its *its;
1775         gpa_t addr, offset;
1776         unsigned int len;
1777         int align, ret = 0;
1778
1779         its = dev->private;
1780         offset = attr->attr;
1781
1782         /*
1783          * Although the spec supports upper/lower 32-bit accesses to
1784          * 64-bit ITS registers, the userspace ABI requires 64-bit
1785          * accesses to all 64-bit wide registers. We therefore only
1786          * support 32-bit accesses to GITS_CTLR, GITS_IIDR and GITS ID
1787          * registers
1788          */
1789         if ((offset < GITS_TYPER) || (offset >= GITS_PIDR4))
1790                 align = 0x3;
1791         else
1792                 align = 0x7;
1793
1794         if (offset & align)
1795                 return -EINVAL;
1796
1797         mutex_lock(&dev->kvm->lock);
1798
1799         if (IS_VGIC_ADDR_UNDEF(its->vgic_its_base)) {
1800                 ret = -ENXIO;
1801                 goto out;
1802         }
1803
1804         region = vgic_find_mmio_region(its_registers,
1805                                        ARRAY_SIZE(its_registers),
1806                                        offset);
1807         if (!region) {
1808                 ret = -ENXIO;
1809                 goto out;
1810         }
1811
1812         if (!lock_all_vcpus(dev->kvm)) {
1813                 ret = -EBUSY;
1814                 goto out;
1815         }
1816
1817         addr = its->vgic_its_base + offset;
1818
1819         len = region->access_flags & VGIC_ACCESS_64bit ? 8 : 4;
1820
1821         if (is_write) {
1822                 if (region->uaccess_its_write)
1823                         ret = region->uaccess_its_write(dev->kvm, its, addr,
1824                                                         len, *reg);
1825                 else
1826                         region->its_write(dev->kvm, its, addr, len, *reg);
1827         } else {
1828                 *reg = region->its_read(dev->kvm, its, addr, len);
1829         }
1830         unlock_all_vcpus(dev->kvm);
1831 out:
1832         mutex_unlock(&dev->kvm->lock);
1833         return ret;
1834 }
1835
1836 static u32 compute_next_devid_offset(struct list_head *h,
1837                                      struct its_device *dev)
1838 {
1839         struct its_device *next;
1840         u32 next_offset;
1841
1842         if (list_is_last(&dev->dev_list, h))
1843                 return 0;
1844         next = list_next_entry(dev, dev_list);
1845         next_offset = next->device_id - dev->device_id;
1846
1847         return min_t(u32, next_offset, VITS_DTE_MAX_DEVID_OFFSET);
1848 }
1849
1850 static u32 compute_next_eventid_offset(struct list_head *h, struct its_ite *ite)
1851 {
1852         struct its_ite *next;
1853         u32 next_offset;
1854
1855         if (list_is_last(&ite->ite_list, h))
1856                 return 0;
1857         next = list_next_entry(ite, ite_list);
1858         next_offset = next->event_id - ite->event_id;
1859
1860         return min_t(u32, next_offset, VITS_ITE_MAX_EVENTID_OFFSET);
1861 }
1862
1863 /**
1864  * entry_fn_t - Callback called on a table entry restore path
1865  * @its: its handle
1866  * @id: id of the entry
1867  * @entry: pointer to the entry
1868  * @opaque: pointer to an opaque data
1869  *
1870  * Return: < 0 on error, 0 if last element was identified, id offset to next
1871  * element otherwise
1872  */
1873 typedef int (*entry_fn_t)(struct vgic_its *its, u32 id, void *entry,
1874                           void *opaque);
1875
1876 /**
1877  * scan_its_table - Scan a contiguous table in guest RAM and applies a function
1878  * to each entry
1879  *
1880  * @its: its handle
1881  * @base: base gpa of the table
1882  * @size: size of the table in bytes
1883  * @esz: entry size in bytes
1884  * @start_id: the ID of the first entry in the table
1885  * (non zero for 2d level tables)
1886  * @fn: function to apply on each entry
1887  *
1888  * Return: < 0 on error, 0 if last element was identified, 1 otherwise
1889  * (the last element may not be found on second level tables)
1890  */
1891 static int scan_its_table(struct vgic_its *its, gpa_t base, int size, u32 esz,
1892                           int start_id, entry_fn_t fn, void *opaque)
1893 {
1894         struct kvm *kvm = its->dev->kvm;
1895         unsigned long len = size;
1896         int id = start_id;
1897         gpa_t gpa = base;
1898         char entry[ESZ_MAX];
1899         int ret;
1900
1901         memset(entry, 0, esz);
1902
1903         while (len > 0) {
1904                 int next_offset;
1905                 size_t byte_offset;
1906
1907                 ret = kvm_read_guest_lock(kvm, gpa, entry, esz);
1908                 if (ret)
1909                         return ret;
1910
1911                 next_offset = fn(its, id, entry, opaque);
1912                 if (next_offset <= 0)
1913                         return next_offset;
1914
1915                 byte_offset = next_offset * esz;
1916                 id += next_offset;
1917                 gpa += byte_offset;
1918                 len -= byte_offset;
1919         }
1920         return 1;
1921 }
1922
1923 /**
1924  * vgic_its_save_ite - Save an interrupt translation entry at @gpa
1925  */
1926 static int vgic_its_save_ite(struct vgic_its *its, struct its_device *dev,
1927                               struct its_ite *ite, gpa_t gpa, int ite_esz)
1928 {
1929         struct kvm *kvm = its->dev->kvm;
1930         u32 next_offset;
1931         u64 val;
1932
1933         next_offset = compute_next_eventid_offset(&dev->itt_head, ite);
1934         val = ((u64)next_offset << KVM_ITS_ITE_NEXT_SHIFT) |
1935                ((u64)ite->irq->intid << KVM_ITS_ITE_PINTID_SHIFT) |
1936                 ite->collection->collection_id;
1937         val = cpu_to_le64(val);
1938         return kvm_write_guest(kvm, gpa, &val, ite_esz);
1939 }
1940
1941 /**
1942  * vgic_its_restore_ite - restore an interrupt translation entry
1943  * @event_id: id used for indexing
1944  * @ptr: pointer to the ITE entry
1945  * @opaque: pointer to the its_device
1946  */
1947 static int vgic_its_restore_ite(struct vgic_its *its, u32 event_id,
1948                                 void *ptr, void *opaque)
1949 {
1950         struct its_device *dev = (struct its_device *)opaque;
1951         struct its_collection *collection;
1952         struct kvm *kvm = its->dev->kvm;
1953         struct kvm_vcpu *vcpu = NULL;
1954         u64 val;
1955         u64 *p = (u64 *)ptr;
1956         struct vgic_irq *irq;
1957         u32 coll_id, lpi_id;
1958         struct its_ite *ite;
1959         u32 offset;
1960
1961         val = *p;
1962
1963         val = le64_to_cpu(val);
1964
1965         coll_id = val & KVM_ITS_ITE_ICID_MASK;
1966         lpi_id = (val & KVM_ITS_ITE_PINTID_MASK) >> KVM_ITS_ITE_PINTID_SHIFT;
1967
1968         if (!lpi_id)
1969                 return 1; /* invalid entry, no choice but to scan next entry */
1970
1971         if (lpi_id < VGIC_MIN_LPI)
1972                 return -EINVAL;
1973
1974         offset = val >> KVM_ITS_ITE_NEXT_SHIFT;
1975         if (event_id + offset >= BIT_ULL(dev->num_eventid_bits))
1976                 return -EINVAL;
1977
1978         collection = find_collection(its, coll_id);
1979         if (!collection)
1980                 return -EINVAL;
1981
1982         ite = vgic_its_alloc_ite(dev, collection, event_id);
1983         if (IS_ERR(ite))
1984                 return PTR_ERR(ite);
1985
1986         if (its_is_collection_mapped(collection))
1987                 vcpu = kvm_get_vcpu(kvm, collection->target_addr);
1988
1989         irq = vgic_add_lpi(kvm, lpi_id, vcpu);
1990         if (IS_ERR(irq))
1991                 return PTR_ERR(irq);
1992         ite->irq = irq;
1993
1994         return offset;
1995 }
1996
1997 static int vgic_its_ite_cmp(void *priv, struct list_head *a,
1998                             struct list_head *b)
1999 {
2000         struct its_ite *itea = container_of(a, struct its_ite, ite_list);
2001         struct its_ite *iteb = container_of(b, struct its_ite, ite_list);
2002
2003         if (itea->event_id < iteb->event_id)
2004                 return -1;
2005         else
2006                 return 1;
2007 }
2008
2009 static int vgic_its_save_itt(struct vgic_its *its, struct its_device *device)
2010 {
2011         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2012         gpa_t base = device->itt_addr;
2013         struct its_ite *ite;
2014         int ret;
2015         int ite_esz = abi->ite_esz;
2016
2017         list_sort(NULL, &device->itt_head, vgic_its_ite_cmp);
2018
2019         list_for_each_entry(ite, &device->itt_head, ite_list) {
2020                 gpa_t gpa = base + ite->event_id * ite_esz;
2021
2022                 /*
2023                  * If an LPI carries the HW bit, this means that this
2024                  * interrupt is controlled by GICv4, and we do not
2025                  * have direct access to that state. Let's simply fail
2026                  * the save operation...
2027                  */
2028                 if (ite->irq->hw)
2029                         return -EACCES;
2030
2031                 ret = vgic_its_save_ite(its, device, ite, gpa, ite_esz);
2032                 if (ret)
2033                         return ret;
2034         }
2035         return 0;
2036 }
2037
2038 /**
2039  * vgic_its_restore_itt - restore the ITT of a device
2040  *
2041  * @its: its handle
2042  * @dev: device handle
2043  *
2044  * Return 0 on success, < 0 on error
2045  */
2046 static int vgic_its_restore_itt(struct vgic_its *its, struct its_device *dev)
2047 {
2048         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2049         gpa_t base = dev->itt_addr;
2050         int ret;
2051         int ite_esz = abi->ite_esz;
2052         size_t max_size = BIT_ULL(dev->num_eventid_bits) * ite_esz;
2053
2054         ret = scan_its_table(its, base, max_size, ite_esz, 0,
2055                              vgic_its_restore_ite, dev);
2056
2057         /* scan_its_table returns +1 if all ITEs are invalid */
2058         if (ret > 0)
2059                 ret = 0;
2060
2061         return ret;
2062 }
2063
2064 /**
2065  * vgic_its_save_dte - Save a device table entry at a given GPA
2066  *
2067  * @its: ITS handle
2068  * @dev: ITS device
2069  * @ptr: GPA
2070  */
2071 static int vgic_its_save_dte(struct vgic_its *its, struct its_device *dev,
2072                              gpa_t ptr, int dte_esz)
2073 {
2074         struct kvm *kvm = its->dev->kvm;
2075         u64 val, itt_addr_field;
2076         u32 next_offset;
2077
2078         itt_addr_field = dev->itt_addr >> 8;
2079         next_offset = compute_next_devid_offset(&its->device_list, dev);
2080         val = (1ULL << KVM_ITS_DTE_VALID_SHIFT |
2081                ((u64)next_offset << KVM_ITS_DTE_NEXT_SHIFT) |
2082                (itt_addr_field << KVM_ITS_DTE_ITTADDR_SHIFT) |
2083                 (dev->num_eventid_bits - 1));
2084         val = cpu_to_le64(val);
2085         return kvm_write_guest(kvm, ptr, &val, dte_esz);
2086 }
2087
2088 /**
2089  * vgic_its_restore_dte - restore a device table entry
2090  *
2091  * @its: its handle
2092  * @id: device id the DTE corresponds to
2093  * @ptr: kernel VA where the 8 byte DTE is located
2094  * @opaque: unused
2095  *
2096  * Return: < 0 on error, 0 if the dte is the last one, id offset to the
2097  * next dte otherwise
2098  */
2099 static int vgic_its_restore_dte(struct vgic_its *its, u32 id,
2100                                 void *ptr, void *opaque)
2101 {
2102         struct its_device *dev;
2103         gpa_t itt_addr;
2104         u8 num_eventid_bits;
2105         u64 entry = *(u64 *)ptr;
2106         bool valid;
2107         u32 offset;
2108         int ret;
2109
2110         entry = le64_to_cpu(entry);
2111
2112         valid = entry >> KVM_ITS_DTE_VALID_SHIFT;
2113         num_eventid_bits = (entry & KVM_ITS_DTE_SIZE_MASK) + 1;
2114         itt_addr = ((entry & KVM_ITS_DTE_ITTADDR_MASK)
2115                         >> KVM_ITS_DTE_ITTADDR_SHIFT) << 8;
2116
2117         if (!valid)
2118                 return 1;
2119
2120         /* dte entry is valid */
2121         offset = (entry & KVM_ITS_DTE_NEXT_MASK) >> KVM_ITS_DTE_NEXT_SHIFT;
2122
2123         dev = vgic_its_alloc_device(its, id, itt_addr, num_eventid_bits);
2124         if (IS_ERR(dev))
2125                 return PTR_ERR(dev);
2126
2127         ret = vgic_its_restore_itt(its, dev);
2128         if (ret) {
2129                 vgic_its_free_device(its->dev->kvm, dev);
2130                 return ret;
2131         }
2132
2133         return offset;
2134 }
2135
2136 static int vgic_its_device_cmp(void *priv, struct list_head *a,
2137                                struct list_head *b)
2138 {
2139         struct its_device *deva = container_of(a, struct its_device, dev_list);
2140         struct its_device *devb = container_of(b, struct its_device, dev_list);
2141
2142         if (deva->device_id < devb->device_id)
2143                 return -1;
2144         else
2145                 return 1;
2146 }
2147
2148 /**
2149  * vgic_its_save_device_tables - Save the device table and all ITT
2150  * into guest RAM
2151  *
2152  * L1/L2 handling is hidden by vgic_its_check_id() helper which directly
2153  * returns the GPA of the device entry
2154  */
2155 static int vgic_its_save_device_tables(struct vgic_its *its)
2156 {
2157         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2158         u64 baser = its->baser_device_table;
2159         struct its_device *dev;
2160         int dte_esz = abi->dte_esz;
2161
2162         if (!(baser & GITS_BASER_VALID))
2163                 return 0;
2164
2165         list_sort(NULL, &its->device_list, vgic_its_device_cmp);
2166
2167         list_for_each_entry(dev, &its->device_list, dev_list) {
2168                 int ret;
2169                 gpa_t eaddr;
2170
2171                 if (!vgic_its_check_id(its, baser,
2172                                        dev->device_id, &eaddr))
2173                         return -EINVAL;
2174
2175                 ret = vgic_its_save_itt(its, dev);
2176                 if (ret)
2177                         return ret;
2178
2179                 ret = vgic_its_save_dte(its, dev, eaddr, dte_esz);
2180                 if (ret)
2181                         return ret;
2182         }
2183         return 0;
2184 }
2185
2186 /**
2187  * handle_l1_dte - callback used for L1 device table entries (2 stage case)
2188  *
2189  * @its: its handle
2190  * @id: index of the entry in the L1 table
2191  * @addr: kernel VA
2192  * @opaque: unused
2193  *
2194  * L1 table entries are scanned by steps of 1 entry
2195  * Return < 0 if error, 0 if last dte was found when scanning the L2
2196  * table, +1 otherwise (meaning next L1 entry must be scanned)
2197  */
2198 static int handle_l1_dte(struct vgic_its *its, u32 id, void *addr,
2199                          void *opaque)
2200 {
2201         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2202         int l2_start_id = id * (SZ_64K / abi->dte_esz);
2203         u64 entry = *(u64 *)addr;
2204         int dte_esz = abi->dte_esz;
2205         gpa_t gpa;
2206         int ret;
2207
2208         entry = le64_to_cpu(entry);
2209
2210         if (!(entry & KVM_ITS_L1E_VALID_MASK))
2211                 return 1;
2212
2213         gpa = entry & KVM_ITS_L1E_ADDR_MASK;
2214
2215         ret = scan_its_table(its, gpa, SZ_64K, dte_esz,
2216                              l2_start_id, vgic_its_restore_dte, NULL);
2217
2218         return ret;
2219 }
2220
2221 /**
2222  * vgic_its_restore_device_tables - Restore the device table and all ITT
2223  * from guest RAM to internal data structs
2224  */
2225 static int vgic_its_restore_device_tables(struct vgic_its *its)
2226 {
2227         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2228         u64 baser = its->baser_device_table;
2229         int l1_esz, ret;
2230         int l1_tbl_size = GITS_BASER_NR_PAGES(baser) * SZ_64K;
2231         gpa_t l1_gpa;
2232
2233         if (!(baser & GITS_BASER_VALID))
2234                 return 0;
2235
2236         l1_gpa = BASER_ADDRESS(baser);
2237
2238         if (baser & GITS_BASER_INDIRECT) {
2239                 l1_esz = GITS_LVL1_ENTRY_SIZE;
2240                 ret = scan_its_table(its, l1_gpa, l1_tbl_size, l1_esz, 0,
2241                                      handle_l1_dte, NULL);
2242         } else {
2243                 l1_esz = abi->dte_esz;
2244                 ret = scan_its_table(its, l1_gpa, l1_tbl_size, l1_esz, 0,
2245                                      vgic_its_restore_dte, NULL);
2246         }
2247
2248         /* scan_its_table returns +1 if all entries are invalid */
2249         if (ret > 0)
2250                 ret = 0;
2251
2252         return ret;
2253 }
2254
2255 static int vgic_its_save_cte(struct vgic_its *its,
2256                              struct its_collection *collection,
2257                              gpa_t gpa, int esz)
2258 {
2259         u64 val;
2260
2261         val = (1ULL << KVM_ITS_CTE_VALID_SHIFT |
2262                ((u64)collection->target_addr << KVM_ITS_CTE_RDBASE_SHIFT) |
2263                collection->collection_id);
2264         val = cpu_to_le64(val);
2265         return kvm_write_guest(its->dev->kvm, gpa, &val, esz);
2266 }
2267
2268 static int vgic_its_restore_cte(struct vgic_its *its, gpa_t gpa, int esz)
2269 {
2270         struct its_collection *collection;
2271         struct kvm *kvm = its->dev->kvm;
2272         u32 target_addr, coll_id;
2273         u64 val;
2274         int ret;
2275
2276         BUG_ON(esz > sizeof(val));
2277         ret = kvm_read_guest_lock(kvm, gpa, &val, esz);
2278         if (ret)
2279                 return ret;
2280         val = le64_to_cpu(val);
2281         if (!(val & KVM_ITS_CTE_VALID_MASK))
2282                 return 0;
2283
2284         target_addr = (u32)(val >> KVM_ITS_CTE_RDBASE_SHIFT);
2285         coll_id = val & KVM_ITS_CTE_ICID_MASK;
2286
2287         if (target_addr >= atomic_read(&kvm->online_vcpus))
2288                 return -EINVAL;
2289
2290         collection = find_collection(its, coll_id);
2291         if (collection)
2292                 return -EEXIST;
2293         ret = vgic_its_alloc_collection(its, &collection, coll_id);
2294         if (ret)
2295                 return ret;
2296         collection->target_addr = target_addr;
2297         return 1;
2298 }
2299
2300 /**
2301  * vgic_its_save_collection_table - Save the collection table into
2302  * guest RAM
2303  */
2304 static int vgic_its_save_collection_table(struct vgic_its *its)
2305 {
2306         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2307         u64 baser = its->baser_coll_table;
2308         gpa_t gpa = BASER_ADDRESS(baser);
2309         struct its_collection *collection;
2310         u64 val;
2311         size_t max_size, filled = 0;
2312         int ret, cte_esz = abi->cte_esz;
2313
2314         if (!(baser & GITS_BASER_VALID))
2315                 return 0;
2316
2317         max_size = GITS_BASER_NR_PAGES(baser) * SZ_64K;
2318
2319         list_for_each_entry(collection, &its->collection_list, coll_list) {
2320                 ret = vgic_its_save_cte(its, collection, gpa, cte_esz);
2321                 if (ret)
2322                         return ret;
2323                 gpa += cte_esz;
2324                 filled += cte_esz;
2325         }
2326
2327         if (filled == max_size)
2328                 return 0;
2329
2330         /*
2331          * table is not fully filled, add a last dummy element
2332          * with valid bit unset
2333          */
2334         val = 0;
2335         BUG_ON(cte_esz > sizeof(val));
2336         ret = kvm_write_guest(its->dev->kvm, gpa, &val, cte_esz);
2337         return ret;
2338 }
2339
2340 /**
2341  * vgic_its_restore_collection_table - reads the collection table
2342  * in guest memory and restores the ITS internal state. Requires the
2343  * BASER registers to be restored before.
2344  */
2345 static int vgic_its_restore_collection_table(struct vgic_its *its)
2346 {
2347         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2348         u64 baser = its->baser_coll_table;
2349         int cte_esz = abi->cte_esz;
2350         size_t max_size, read = 0;
2351         gpa_t gpa;
2352         int ret;
2353
2354         if (!(baser & GITS_BASER_VALID))
2355                 return 0;
2356
2357         gpa = BASER_ADDRESS(baser);
2358
2359         max_size = GITS_BASER_NR_PAGES(baser) * SZ_64K;
2360
2361         while (read < max_size) {
2362                 ret = vgic_its_restore_cte(its, gpa, cte_esz);
2363                 if (ret <= 0)
2364                         break;
2365                 gpa += cte_esz;
2366                 read += cte_esz;
2367         }
2368
2369         if (ret > 0)
2370                 return 0;
2371
2372         return ret;
2373 }
2374
2375 /**
2376  * vgic_its_save_tables_v0 - Save the ITS tables into guest ARM
2377  * according to v0 ABI
2378  */
2379 static int vgic_its_save_tables_v0(struct vgic_its *its)
2380 {
2381         int ret;
2382
2383         ret = vgic_its_save_device_tables(its);
2384         if (ret)
2385                 return ret;
2386
2387         return vgic_its_save_collection_table(its);
2388 }
2389
2390 /**
2391  * vgic_its_restore_tables_v0 - Restore the ITS tables from guest RAM
2392  * to internal data structs according to V0 ABI
2393  *
2394  */
2395 static int vgic_its_restore_tables_v0(struct vgic_its *its)
2396 {
2397         int ret;
2398
2399         ret = vgic_its_restore_collection_table(its);
2400         if (ret)
2401                 return ret;
2402
2403         return vgic_its_restore_device_tables(its);
2404 }
2405
2406 static int vgic_its_commit_v0(struct vgic_its *its)
2407 {
2408         const struct vgic_its_abi *abi;
2409
2410         abi = vgic_its_get_abi(its);
2411         its->baser_coll_table &= ~GITS_BASER_ENTRY_SIZE_MASK;
2412         its->baser_device_table &= ~GITS_BASER_ENTRY_SIZE_MASK;
2413
2414         its->baser_coll_table |= (GIC_ENCODE_SZ(abi->cte_esz, 5)
2415                                         << GITS_BASER_ENTRY_SIZE_SHIFT);
2416
2417         its->baser_device_table |= (GIC_ENCODE_SZ(abi->dte_esz, 5)
2418                                         << GITS_BASER_ENTRY_SIZE_SHIFT);
2419         return 0;
2420 }
2421
2422 static void vgic_its_reset(struct kvm *kvm, struct vgic_its *its)
2423 {
2424         /* We need to keep the ABI specific field values */
2425         its->baser_coll_table &= ~GITS_BASER_VALID;
2426         its->baser_device_table &= ~GITS_BASER_VALID;
2427         its->cbaser = 0;
2428         its->creadr = 0;
2429         its->cwriter = 0;
2430         its->enabled = 0;
2431         vgic_its_free_device_list(kvm, its);
2432         vgic_its_free_collection_list(kvm, its);
2433 }
2434
2435 static int vgic_its_has_attr(struct kvm_device *dev,
2436                              struct kvm_device_attr *attr)
2437 {
2438         switch (attr->group) {
2439         case KVM_DEV_ARM_VGIC_GRP_ADDR:
2440                 switch (attr->attr) {
2441                 case KVM_VGIC_ITS_ADDR_TYPE:
2442                         return 0;
2443                 }
2444                 break;
2445         case KVM_DEV_ARM_VGIC_GRP_CTRL:
2446                 switch (attr->attr) {
2447                 case KVM_DEV_ARM_VGIC_CTRL_INIT:
2448                         return 0;
2449                 case KVM_DEV_ARM_ITS_CTRL_RESET:
2450                         return 0;
2451                 case KVM_DEV_ARM_ITS_SAVE_TABLES:
2452                         return 0;
2453                 case KVM_DEV_ARM_ITS_RESTORE_TABLES:
2454                         return 0;
2455                 }
2456                 break;
2457         case KVM_DEV_ARM_VGIC_GRP_ITS_REGS:
2458                 return vgic_its_has_attr_regs(dev, attr);
2459         }
2460         return -ENXIO;
2461 }
2462
2463 static int vgic_its_ctrl(struct kvm *kvm, struct vgic_its *its, u64 attr)
2464 {
2465         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2466         int ret = 0;
2467
2468         if (attr == KVM_DEV_ARM_VGIC_CTRL_INIT) /* Nothing to do */
2469                 return 0;
2470
2471         mutex_lock(&kvm->lock);
2472         mutex_lock(&its->its_lock);
2473
2474         if (!lock_all_vcpus(kvm)) {
2475                 mutex_unlock(&its->its_lock);
2476                 mutex_unlock(&kvm->lock);
2477                 return -EBUSY;
2478         }
2479
2480         switch (attr) {
2481         case KVM_DEV_ARM_ITS_CTRL_RESET:
2482                 vgic_its_reset(kvm, its);
2483                 break;
2484         case KVM_DEV_ARM_ITS_SAVE_TABLES:
2485                 ret = abi->save_tables(its);
2486                 break;
2487         case KVM_DEV_ARM_ITS_RESTORE_TABLES:
2488                 ret = abi->restore_tables(its);
2489                 break;
2490         }
2491
2492         unlock_all_vcpus(kvm);
2493         mutex_unlock(&its->its_lock);
2494         mutex_unlock(&kvm->lock);
2495         return ret;
2496 }
2497
2498 static int vgic_its_set_attr(struct kvm_device *dev,
2499                              struct kvm_device_attr *attr)
2500 {
2501         struct vgic_its *its = dev->private;
2502         int ret;
2503
2504         switch (attr->group) {
2505         case KVM_DEV_ARM_VGIC_GRP_ADDR: {
2506                 u64 __user *uaddr = (u64 __user *)(long)attr->addr;
2507                 unsigned long type = (unsigned long)attr->attr;
2508                 u64 addr;
2509
2510                 if (type != KVM_VGIC_ITS_ADDR_TYPE)
2511                         return -ENODEV;
2512
2513                 if (copy_from_user(&addr, uaddr, sizeof(addr)))
2514                         return -EFAULT;
2515
2516                 ret = vgic_check_ioaddr(dev->kvm, &its->vgic_its_base,
2517                                         addr, SZ_64K);
2518                 if (ret)
2519                         return ret;
2520
2521                 return vgic_register_its_iodev(dev->kvm, its, addr);
2522         }
2523         case KVM_DEV_ARM_VGIC_GRP_CTRL:
2524                 return vgic_its_ctrl(dev->kvm, its, attr->attr);
2525         case KVM_DEV_ARM_VGIC_GRP_ITS_REGS: {
2526                 u64 __user *uaddr = (u64 __user *)(long)attr->addr;
2527                 u64 reg;
2528
2529                 if (get_user(reg, uaddr))
2530                         return -EFAULT;
2531
2532                 return vgic_its_attr_regs_access(dev, attr, &reg, true);
2533         }
2534         }
2535         return -ENXIO;
2536 }
2537
2538 static int vgic_its_get_attr(struct kvm_device *dev,
2539                              struct kvm_device_attr *attr)
2540 {
2541         switch (attr->group) {
2542         case KVM_DEV_ARM_VGIC_GRP_ADDR: {
2543                 struct vgic_its *its = dev->private;
2544                 u64 addr = its->vgic_its_base;
2545                 u64 __user *uaddr = (u64 __user *)(long)attr->addr;
2546                 unsigned long type = (unsigned long)attr->attr;
2547
2548                 if (type != KVM_VGIC_ITS_ADDR_TYPE)
2549                         return -ENODEV;
2550
2551                 if (copy_to_user(uaddr, &addr, sizeof(addr)))
2552                         return -EFAULT;
2553                 break;
2554         }
2555         case KVM_DEV_ARM_VGIC_GRP_ITS_REGS: {
2556                 u64 __user *uaddr = (u64 __user *)(long)attr->addr;
2557                 u64 reg;
2558                 int ret;
2559
2560                 ret = vgic_its_attr_regs_access(dev, attr, &reg, false);
2561                 if (ret)
2562                         return ret;
2563                 return put_user(reg, uaddr);
2564         }
2565         default:
2566                 return -ENXIO;
2567         }
2568
2569         return 0;
2570 }
2571
2572 static struct kvm_device_ops kvm_arm_vgic_its_ops = {
2573         .name = "kvm-arm-vgic-its",
2574         .create = vgic_its_create,
2575         .destroy = vgic_its_destroy,
2576         .set_attr = vgic_its_set_attr,
2577         .get_attr = vgic_its_get_attr,
2578         .has_attr = vgic_its_has_attr,
2579 };
2580
2581 int kvm_vgic_register_its_device(void)
2582 {
2583         return kvm_register_device_ops(&kvm_arm_vgic_its_ops,
2584                                        KVM_DEV_TYPE_ARM_VGIC_ITS);
2585 }