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