Merge branches 'clk-doc', 'clk-more-critical', 'clk-meson' and 'clk-basic-be' into...
[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, idx;
758         gfn_t gfn;
759         bool ret;
760
761         switch (type) {
762         case GITS_BASER_TYPE_DEVICE:
763                 if (id >= BIT_ULL(VITS_TYPER_DEVBITS))
764                         return false;
765                 break;
766         case GITS_BASER_TYPE_COLLECTION:
767                 /* as GITS_TYPER.CIL == 0, ITS supports 16-bit collection ID */
768                 if (id >= BIT_ULL(16))
769                         return false;
770                 break;
771         default:
772                 return false;
773         }
774
775         if (!(baser & GITS_BASER_INDIRECT)) {
776                 phys_addr_t addr;
777
778                 if (id >= (l1_tbl_size / esz))
779                         return false;
780
781                 addr = base + id * esz;
782                 gfn = addr >> PAGE_SHIFT;
783
784                 if (eaddr)
785                         *eaddr = addr;
786
787                 goto out;
788         }
789
790         /* calculate and check the index into the 1st level */
791         index = id / (SZ_64K / esz);
792         if (index >= (l1_tbl_size / sizeof(u64)))
793                 return false;
794
795         /* Each 1st level entry is represented by a 64-bit value. */
796         if (kvm_read_guest_lock(its->dev->kvm,
797                            base + index * sizeof(indirect_ptr),
798                            &indirect_ptr, sizeof(indirect_ptr)))
799                 return false;
800
801         indirect_ptr = le64_to_cpu(indirect_ptr);
802
803         /* check the valid bit of the first level entry */
804         if (!(indirect_ptr & BIT_ULL(63)))
805                 return false;
806
807         /* Mask the guest physical address and calculate the frame number. */
808         indirect_ptr &= GENMASK_ULL(51, 16);
809
810         /* Find the address of the actual entry */
811         index = id % (SZ_64K / esz);
812         indirect_ptr += index * esz;
813         gfn = indirect_ptr >> PAGE_SHIFT;
814
815         if (eaddr)
816                 *eaddr = indirect_ptr;
817
818 out:
819         idx = srcu_read_lock(&its->dev->kvm->srcu);
820         ret = kvm_is_visible_gfn(its->dev->kvm, gfn);
821         srcu_read_unlock(&its->dev->kvm->srcu, idx);
822         return ret;
823 }
824
825 static int vgic_its_alloc_collection(struct vgic_its *its,
826                                      struct its_collection **colp,
827                                      u32 coll_id)
828 {
829         struct its_collection *collection;
830
831         if (!vgic_its_check_id(its, its->baser_coll_table, coll_id, NULL))
832                 return E_ITS_MAPC_COLLECTION_OOR;
833
834         collection = kzalloc(sizeof(*collection), GFP_KERNEL);
835         if (!collection)
836                 return -ENOMEM;
837
838         collection->collection_id = coll_id;
839         collection->target_addr = COLLECTION_NOT_MAPPED;
840
841         list_add_tail(&collection->coll_list, &its->collection_list);
842         *colp = collection;
843
844         return 0;
845 }
846
847 static void vgic_its_free_collection(struct vgic_its *its, u32 coll_id)
848 {
849         struct its_collection *collection;
850         struct its_device *device;
851         struct its_ite *ite;
852
853         /*
854          * Clearing the mapping for that collection ID removes the
855          * entry from the list. If there wasn't any before, we can
856          * go home early.
857          */
858         collection = find_collection(its, coll_id);
859         if (!collection)
860                 return;
861
862         for_each_lpi_its(device, ite, its)
863                 if (ite->collection &&
864                     ite->collection->collection_id == coll_id)
865                         ite->collection = NULL;
866
867         list_del(&collection->coll_list);
868         kfree(collection);
869 }
870
871 /* Must be called with its_lock mutex held */
872 static struct its_ite *vgic_its_alloc_ite(struct its_device *device,
873                                           struct its_collection *collection,
874                                           u32 event_id)
875 {
876         struct its_ite *ite;
877
878         ite = kzalloc(sizeof(*ite), GFP_KERNEL);
879         if (!ite)
880                 return ERR_PTR(-ENOMEM);
881
882         ite->event_id   = event_id;
883         ite->collection = collection;
884
885         list_add_tail(&ite->ite_list, &device->itt_head);
886         return ite;
887 }
888
889 /*
890  * The MAPTI and MAPI commands map LPIs to ITTEs.
891  * Must be called with its_lock mutex held.
892  */
893 static int vgic_its_cmd_handle_mapi(struct kvm *kvm, struct vgic_its *its,
894                                     u64 *its_cmd)
895 {
896         u32 device_id = its_cmd_get_deviceid(its_cmd);
897         u32 event_id = its_cmd_get_id(its_cmd);
898         u32 coll_id = its_cmd_get_collection(its_cmd);
899         struct its_ite *ite;
900         struct kvm_vcpu *vcpu = NULL;
901         struct its_device *device;
902         struct its_collection *collection, *new_coll = NULL;
903         struct vgic_irq *irq;
904         int lpi_nr;
905
906         device = find_its_device(its, device_id);
907         if (!device)
908                 return E_ITS_MAPTI_UNMAPPED_DEVICE;
909
910         if (event_id >= BIT_ULL(device->num_eventid_bits))
911                 return E_ITS_MAPTI_ID_OOR;
912
913         if (its_cmd_get_command(its_cmd) == GITS_CMD_MAPTI)
914                 lpi_nr = its_cmd_get_physical_id(its_cmd);
915         else
916                 lpi_nr = event_id;
917         if (lpi_nr < GIC_LPI_OFFSET ||
918             lpi_nr >= max_lpis_propbaser(kvm->arch.vgic.propbaser))
919                 return E_ITS_MAPTI_PHYSICALID_OOR;
920
921         /* If there is an existing mapping, behavior is UNPREDICTABLE. */
922         if (find_ite(its, device_id, event_id))
923                 return 0;
924
925         collection = find_collection(its, coll_id);
926         if (!collection) {
927                 int ret = vgic_its_alloc_collection(its, &collection, coll_id);
928                 if (ret)
929                         return ret;
930                 new_coll = collection;
931         }
932
933         ite = vgic_its_alloc_ite(device, collection, event_id);
934         if (IS_ERR(ite)) {
935                 if (new_coll)
936                         vgic_its_free_collection(its, coll_id);
937                 return PTR_ERR(ite);
938         }
939
940         if (its_is_collection_mapped(collection))
941                 vcpu = kvm_get_vcpu(kvm, collection->target_addr);
942
943         irq = vgic_add_lpi(kvm, lpi_nr, vcpu);
944         if (IS_ERR(irq)) {
945                 if (new_coll)
946                         vgic_its_free_collection(its, coll_id);
947                 its_free_ite(kvm, ite);
948                 return PTR_ERR(irq);
949         }
950         ite->irq = irq;
951
952         return 0;
953 }
954
955 /* Requires the its_lock to be held. */
956 static void vgic_its_free_device(struct kvm *kvm, struct its_device *device)
957 {
958         struct its_ite *ite, *temp;
959
960         /*
961          * The spec says that unmapping a device with still valid
962          * ITTEs associated is UNPREDICTABLE. We remove all ITTEs,
963          * since we cannot leave the memory unreferenced.
964          */
965         list_for_each_entry_safe(ite, temp, &device->itt_head, ite_list)
966                 its_free_ite(kvm, ite);
967
968         list_del(&device->dev_list);
969         kfree(device);
970 }
971
972 /* its lock must be held */
973 static void vgic_its_free_device_list(struct kvm *kvm, struct vgic_its *its)
974 {
975         struct its_device *cur, *temp;
976
977         list_for_each_entry_safe(cur, temp, &its->device_list, dev_list)
978                 vgic_its_free_device(kvm, cur);
979 }
980
981 /* its lock must be held */
982 static void vgic_its_free_collection_list(struct kvm *kvm, struct vgic_its *its)
983 {
984         struct its_collection *cur, *temp;
985
986         list_for_each_entry_safe(cur, temp, &its->collection_list, coll_list)
987                 vgic_its_free_collection(its, cur->collection_id);
988 }
989
990 /* Must be called with its_lock mutex held */
991 static struct its_device *vgic_its_alloc_device(struct vgic_its *its,
992                                                 u32 device_id, gpa_t itt_addr,
993                                                 u8 num_eventid_bits)
994 {
995         struct its_device *device;
996
997         device = kzalloc(sizeof(*device), GFP_KERNEL);
998         if (!device)
999                 return ERR_PTR(-ENOMEM);
1000
1001         device->device_id = device_id;
1002         device->itt_addr = itt_addr;
1003         device->num_eventid_bits = num_eventid_bits;
1004         INIT_LIST_HEAD(&device->itt_head);
1005
1006         list_add_tail(&device->dev_list, &its->device_list);
1007         return device;
1008 }
1009
1010 /*
1011  * MAPD maps or unmaps a device ID to Interrupt Translation Tables (ITTs).
1012  * Must be called with the its_lock mutex held.
1013  */
1014 static int vgic_its_cmd_handle_mapd(struct kvm *kvm, struct vgic_its *its,
1015                                     u64 *its_cmd)
1016 {
1017         u32 device_id = its_cmd_get_deviceid(its_cmd);
1018         bool valid = its_cmd_get_validbit(its_cmd);
1019         u8 num_eventid_bits = its_cmd_get_size(its_cmd);
1020         gpa_t itt_addr = its_cmd_get_ittaddr(its_cmd);
1021         struct its_device *device;
1022
1023         if (!vgic_its_check_id(its, its->baser_device_table, device_id, NULL))
1024                 return E_ITS_MAPD_DEVICE_OOR;
1025
1026         if (valid && num_eventid_bits > VITS_TYPER_IDBITS)
1027                 return E_ITS_MAPD_ITTSIZE_OOR;
1028
1029         device = find_its_device(its, device_id);
1030
1031         /*
1032          * The spec says that calling MAPD on an already mapped device
1033          * invalidates all cached data for this device. We implement this
1034          * by removing the mapping and re-establishing it.
1035          */
1036         if (device)
1037                 vgic_its_free_device(kvm, device);
1038
1039         /*
1040          * The spec does not say whether unmapping a not-mapped device
1041          * is an error, so we are done in any case.
1042          */
1043         if (!valid)
1044                 return 0;
1045
1046         device = vgic_its_alloc_device(its, device_id, itt_addr,
1047                                        num_eventid_bits);
1048
1049         return PTR_ERR_OR_ZERO(device);
1050 }
1051
1052 /*
1053  * The MAPC command maps collection IDs to redistributors.
1054  * Must be called with the its_lock mutex held.
1055  */
1056 static int vgic_its_cmd_handle_mapc(struct kvm *kvm, struct vgic_its *its,
1057                                     u64 *its_cmd)
1058 {
1059         u16 coll_id;
1060         u32 target_addr;
1061         struct its_collection *collection;
1062         bool valid;
1063
1064         valid = its_cmd_get_validbit(its_cmd);
1065         coll_id = its_cmd_get_collection(its_cmd);
1066         target_addr = its_cmd_get_target_addr(its_cmd);
1067
1068         if (target_addr >= atomic_read(&kvm->online_vcpus))
1069                 return E_ITS_MAPC_PROCNUM_OOR;
1070
1071         if (!valid) {
1072                 vgic_its_free_collection(its, coll_id);
1073         } else {
1074                 collection = find_collection(its, coll_id);
1075
1076                 if (!collection) {
1077                         int ret;
1078
1079                         ret = vgic_its_alloc_collection(its, &collection,
1080                                                         coll_id);
1081                         if (ret)
1082                                 return ret;
1083                         collection->target_addr = target_addr;
1084                 } else {
1085                         collection->target_addr = target_addr;
1086                         update_affinity_collection(kvm, its, collection);
1087                 }
1088         }
1089
1090         return 0;
1091 }
1092
1093 /*
1094  * The CLEAR command removes the pending state for a particular LPI.
1095  * Must be called with the its_lock mutex held.
1096  */
1097 static int vgic_its_cmd_handle_clear(struct kvm *kvm, struct vgic_its *its,
1098                                      u64 *its_cmd)
1099 {
1100         u32 device_id = its_cmd_get_deviceid(its_cmd);
1101         u32 event_id = its_cmd_get_id(its_cmd);
1102         struct its_ite *ite;
1103
1104
1105         ite = find_ite(its, device_id, event_id);
1106         if (!ite)
1107                 return E_ITS_CLEAR_UNMAPPED_INTERRUPT;
1108
1109         ite->irq->pending_latch = false;
1110
1111         if (ite->irq->hw)
1112                 return irq_set_irqchip_state(ite->irq->host_irq,
1113                                              IRQCHIP_STATE_PENDING, false);
1114
1115         return 0;
1116 }
1117
1118 /*
1119  * The INV command syncs the configuration bits from the memory table.
1120  * Must be called with the its_lock mutex held.
1121  */
1122 static int vgic_its_cmd_handle_inv(struct kvm *kvm, struct vgic_its *its,
1123                                    u64 *its_cmd)
1124 {
1125         u32 device_id = its_cmd_get_deviceid(its_cmd);
1126         u32 event_id = its_cmd_get_id(its_cmd);
1127         struct its_ite *ite;
1128
1129
1130         ite = find_ite(its, device_id, event_id);
1131         if (!ite)
1132                 return E_ITS_INV_UNMAPPED_INTERRUPT;
1133
1134         return update_lpi_config(kvm, ite->irq, NULL, true);
1135 }
1136
1137 /*
1138  * The INVALL command requests flushing of all IRQ data in this collection.
1139  * Find the VCPU mapped to that collection, then iterate over the VM's list
1140  * of mapped LPIs and update the configuration for each IRQ which targets
1141  * the specified vcpu. The configuration will be read from the in-memory
1142  * configuration table.
1143  * Must be called with the its_lock mutex held.
1144  */
1145 static int vgic_its_cmd_handle_invall(struct kvm *kvm, struct vgic_its *its,
1146                                       u64 *its_cmd)
1147 {
1148         u32 coll_id = its_cmd_get_collection(its_cmd);
1149         struct its_collection *collection;
1150         struct kvm_vcpu *vcpu;
1151         struct vgic_irq *irq;
1152         u32 *intids;
1153         int irq_count, i;
1154
1155         collection = find_collection(its, coll_id);
1156         if (!its_is_collection_mapped(collection))
1157                 return E_ITS_INVALL_UNMAPPED_COLLECTION;
1158
1159         vcpu = kvm_get_vcpu(kvm, collection->target_addr);
1160
1161         irq_count = vgic_copy_lpi_list(kvm, vcpu, &intids);
1162         if (irq_count < 0)
1163                 return irq_count;
1164
1165         for (i = 0; i < irq_count; i++) {
1166                 irq = vgic_get_irq(kvm, NULL, intids[i]);
1167                 if (!irq)
1168                         continue;
1169                 update_lpi_config(kvm, irq, vcpu, false);
1170                 vgic_put_irq(kvm, irq);
1171         }
1172
1173         kfree(intids);
1174
1175         if (vcpu->arch.vgic_cpu.vgic_v3.its_vpe.its_vm)
1176                 its_invall_vpe(&vcpu->arch.vgic_cpu.vgic_v3.its_vpe);
1177
1178         return 0;
1179 }
1180
1181 /*
1182  * The MOVALL command moves the pending state of all IRQs targeting one
1183  * redistributor to another. We don't hold the pending state in the VCPUs,
1184  * but in the IRQs instead, so there is really not much to do for us here.
1185  * However the spec says that no IRQ must target the old redistributor
1186  * afterwards, so we make sure that no LPI is using the associated target_vcpu.
1187  * This command affects all LPIs in the system that target that redistributor.
1188  */
1189 static int vgic_its_cmd_handle_movall(struct kvm *kvm, struct vgic_its *its,
1190                                       u64 *its_cmd)
1191 {
1192         u32 target1_addr = its_cmd_get_target_addr(its_cmd);
1193         u32 target2_addr = its_cmd_mask_field(its_cmd, 3, 16, 32);
1194         struct kvm_vcpu *vcpu1, *vcpu2;
1195         struct vgic_irq *irq;
1196         u32 *intids;
1197         int irq_count, i;
1198
1199         if (target1_addr >= atomic_read(&kvm->online_vcpus) ||
1200             target2_addr >= atomic_read(&kvm->online_vcpus))
1201                 return E_ITS_MOVALL_PROCNUM_OOR;
1202
1203         if (target1_addr == target2_addr)
1204                 return 0;
1205
1206         vcpu1 = kvm_get_vcpu(kvm, target1_addr);
1207         vcpu2 = kvm_get_vcpu(kvm, target2_addr);
1208
1209         irq_count = vgic_copy_lpi_list(kvm, vcpu1, &intids);
1210         if (irq_count < 0)
1211                 return irq_count;
1212
1213         for (i = 0; i < irq_count; i++) {
1214                 irq = vgic_get_irq(kvm, NULL, intids[i]);
1215
1216                 update_affinity(irq, vcpu2);
1217
1218                 vgic_put_irq(kvm, irq);
1219         }
1220
1221         kfree(intids);
1222         return 0;
1223 }
1224
1225 /*
1226  * The INT command injects the LPI associated with that DevID/EvID pair.
1227  * Must be called with the its_lock mutex held.
1228  */
1229 static int vgic_its_cmd_handle_int(struct kvm *kvm, struct vgic_its *its,
1230                                    u64 *its_cmd)
1231 {
1232         u32 msi_data = its_cmd_get_id(its_cmd);
1233         u64 msi_devid = its_cmd_get_deviceid(its_cmd);
1234
1235         return vgic_its_trigger_msi(kvm, its, msi_devid, msi_data);
1236 }
1237
1238 /*
1239  * This function is called with the its_cmd lock held, but the ITS data
1240  * structure lock dropped.
1241  */
1242 static int vgic_its_handle_command(struct kvm *kvm, struct vgic_its *its,
1243                                    u64 *its_cmd)
1244 {
1245         int ret = -ENODEV;
1246
1247         mutex_lock(&its->its_lock);
1248         switch (its_cmd_get_command(its_cmd)) {
1249         case GITS_CMD_MAPD:
1250                 ret = vgic_its_cmd_handle_mapd(kvm, its, its_cmd);
1251                 break;
1252         case GITS_CMD_MAPC:
1253                 ret = vgic_its_cmd_handle_mapc(kvm, its, its_cmd);
1254                 break;
1255         case GITS_CMD_MAPI:
1256                 ret = vgic_its_cmd_handle_mapi(kvm, its, its_cmd);
1257                 break;
1258         case GITS_CMD_MAPTI:
1259                 ret = vgic_its_cmd_handle_mapi(kvm, its, its_cmd);
1260                 break;
1261         case GITS_CMD_MOVI:
1262                 ret = vgic_its_cmd_handle_movi(kvm, its, its_cmd);
1263                 break;
1264         case GITS_CMD_DISCARD:
1265                 ret = vgic_its_cmd_handle_discard(kvm, its, its_cmd);
1266                 break;
1267         case GITS_CMD_CLEAR:
1268                 ret = vgic_its_cmd_handle_clear(kvm, its, its_cmd);
1269                 break;
1270         case GITS_CMD_MOVALL:
1271                 ret = vgic_its_cmd_handle_movall(kvm, its, its_cmd);
1272                 break;
1273         case GITS_CMD_INT:
1274                 ret = vgic_its_cmd_handle_int(kvm, its, its_cmd);
1275                 break;
1276         case GITS_CMD_INV:
1277                 ret = vgic_its_cmd_handle_inv(kvm, its, its_cmd);
1278                 break;
1279         case GITS_CMD_INVALL:
1280                 ret = vgic_its_cmd_handle_invall(kvm, its, its_cmd);
1281                 break;
1282         case GITS_CMD_SYNC:
1283                 /* we ignore this command: we are in sync all of the time */
1284                 ret = 0;
1285                 break;
1286         }
1287         mutex_unlock(&its->its_lock);
1288
1289         return ret;
1290 }
1291
1292 static u64 vgic_sanitise_its_baser(u64 reg)
1293 {
1294         reg = vgic_sanitise_field(reg, GITS_BASER_SHAREABILITY_MASK,
1295                                   GITS_BASER_SHAREABILITY_SHIFT,
1296                                   vgic_sanitise_shareability);
1297         reg = vgic_sanitise_field(reg, GITS_BASER_INNER_CACHEABILITY_MASK,
1298                                   GITS_BASER_INNER_CACHEABILITY_SHIFT,
1299                                   vgic_sanitise_inner_cacheability);
1300         reg = vgic_sanitise_field(reg, GITS_BASER_OUTER_CACHEABILITY_MASK,
1301                                   GITS_BASER_OUTER_CACHEABILITY_SHIFT,
1302                                   vgic_sanitise_outer_cacheability);
1303
1304         /* We support only one (ITS) page size: 64K */
1305         reg = (reg & ~GITS_BASER_PAGE_SIZE_MASK) | GITS_BASER_PAGE_SIZE_64K;
1306
1307         return reg;
1308 }
1309
1310 static u64 vgic_sanitise_its_cbaser(u64 reg)
1311 {
1312         reg = vgic_sanitise_field(reg, GITS_CBASER_SHAREABILITY_MASK,
1313                                   GITS_CBASER_SHAREABILITY_SHIFT,
1314                                   vgic_sanitise_shareability);
1315         reg = vgic_sanitise_field(reg, GITS_CBASER_INNER_CACHEABILITY_MASK,
1316                                   GITS_CBASER_INNER_CACHEABILITY_SHIFT,
1317                                   vgic_sanitise_inner_cacheability);
1318         reg = vgic_sanitise_field(reg, GITS_CBASER_OUTER_CACHEABILITY_MASK,
1319                                   GITS_CBASER_OUTER_CACHEABILITY_SHIFT,
1320                                   vgic_sanitise_outer_cacheability);
1321
1322         /* Sanitise the physical address to be 64k aligned. */
1323         reg &= ~GENMASK_ULL(15, 12);
1324
1325         return reg;
1326 }
1327
1328 static unsigned long vgic_mmio_read_its_cbaser(struct kvm *kvm,
1329                                                struct vgic_its *its,
1330                                                gpa_t addr, unsigned int len)
1331 {
1332         return extract_bytes(its->cbaser, addr & 7, len);
1333 }
1334
1335 static void vgic_mmio_write_its_cbaser(struct kvm *kvm, struct vgic_its *its,
1336                                        gpa_t addr, unsigned int len,
1337                                        unsigned long val)
1338 {
1339         /* When GITS_CTLR.Enable is 1, this register is RO. */
1340         if (its->enabled)
1341                 return;
1342
1343         mutex_lock(&its->cmd_lock);
1344         its->cbaser = update_64bit_reg(its->cbaser, addr & 7, len, val);
1345         its->cbaser = vgic_sanitise_its_cbaser(its->cbaser);
1346         its->creadr = 0;
1347         /*
1348          * CWRITER is architecturally UNKNOWN on reset, but we need to reset
1349          * it to CREADR to make sure we start with an empty command buffer.
1350          */
1351         its->cwriter = its->creadr;
1352         mutex_unlock(&its->cmd_lock);
1353 }
1354
1355 #define ITS_CMD_BUFFER_SIZE(baser)      ((((baser) & 0xff) + 1) << 12)
1356 #define ITS_CMD_SIZE                    32
1357 #define ITS_CMD_OFFSET(reg)             ((reg) & GENMASK(19, 5))
1358
1359 /* Must be called with the cmd_lock held. */
1360 static void vgic_its_process_commands(struct kvm *kvm, struct vgic_its *its)
1361 {
1362         gpa_t cbaser;
1363         u64 cmd_buf[4];
1364
1365         /* Commands are only processed when the ITS is enabled. */
1366         if (!its->enabled)
1367                 return;
1368
1369         cbaser = GITS_CBASER_ADDRESS(its->cbaser);
1370
1371         while (its->cwriter != its->creadr) {
1372                 int ret = kvm_read_guest_lock(kvm, cbaser + its->creadr,
1373                                               cmd_buf, ITS_CMD_SIZE);
1374                 /*
1375                  * If kvm_read_guest() fails, this could be due to the guest
1376                  * programming a bogus value in CBASER or something else going
1377                  * wrong from which we cannot easily recover.
1378                  * According to section 6.3.2 in the GICv3 spec we can just
1379                  * ignore that command then.
1380                  */
1381                 if (!ret)
1382                         vgic_its_handle_command(kvm, its, cmd_buf);
1383
1384                 its->creadr += ITS_CMD_SIZE;
1385                 if (its->creadr == ITS_CMD_BUFFER_SIZE(its->cbaser))
1386                         its->creadr = 0;
1387         }
1388 }
1389
1390 /*
1391  * By writing to CWRITER the guest announces new commands to be processed.
1392  * To avoid any races in the first place, we take the its_cmd lock, which
1393  * protects our ring buffer variables, so that there is only one user
1394  * per ITS handling commands at a given time.
1395  */
1396 static void vgic_mmio_write_its_cwriter(struct kvm *kvm, struct vgic_its *its,
1397                                         gpa_t addr, unsigned int len,
1398                                         unsigned long val)
1399 {
1400         u64 reg;
1401
1402         if (!its)
1403                 return;
1404
1405         mutex_lock(&its->cmd_lock);
1406
1407         reg = update_64bit_reg(its->cwriter, addr & 7, len, val);
1408         reg = ITS_CMD_OFFSET(reg);
1409         if (reg >= ITS_CMD_BUFFER_SIZE(its->cbaser)) {
1410                 mutex_unlock(&its->cmd_lock);
1411                 return;
1412         }
1413         its->cwriter = reg;
1414
1415         vgic_its_process_commands(kvm, its);
1416
1417         mutex_unlock(&its->cmd_lock);
1418 }
1419
1420 static unsigned long vgic_mmio_read_its_cwriter(struct kvm *kvm,
1421                                                 struct vgic_its *its,
1422                                                 gpa_t addr, unsigned int len)
1423 {
1424         return extract_bytes(its->cwriter, addr & 0x7, len);
1425 }
1426
1427 static unsigned long vgic_mmio_read_its_creadr(struct kvm *kvm,
1428                                                struct vgic_its *its,
1429                                                gpa_t addr, unsigned int len)
1430 {
1431         return extract_bytes(its->creadr, addr & 0x7, len);
1432 }
1433
1434 static int vgic_mmio_uaccess_write_its_creadr(struct kvm *kvm,
1435                                               struct vgic_its *its,
1436                                               gpa_t addr, unsigned int len,
1437                                               unsigned long val)
1438 {
1439         u32 cmd_offset;
1440         int ret = 0;
1441
1442         mutex_lock(&its->cmd_lock);
1443
1444         if (its->enabled) {
1445                 ret = -EBUSY;
1446                 goto out;
1447         }
1448
1449         cmd_offset = ITS_CMD_OFFSET(val);
1450         if (cmd_offset >= ITS_CMD_BUFFER_SIZE(its->cbaser)) {
1451                 ret = -EINVAL;
1452                 goto out;
1453         }
1454
1455         its->creadr = cmd_offset;
1456 out:
1457         mutex_unlock(&its->cmd_lock);
1458         return ret;
1459 }
1460
1461 #define BASER_INDEX(addr) (((addr) / sizeof(u64)) & 0x7)
1462 static unsigned long vgic_mmio_read_its_baser(struct kvm *kvm,
1463                                               struct vgic_its *its,
1464                                               gpa_t addr, unsigned int len)
1465 {
1466         u64 reg;
1467
1468         switch (BASER_INDEX(addr)) {
1469         case 0:
1470                 reg = its->baser_device_table;
1471                 break;
1472         case 1:
1473                 reg = its->baser_coll_table;
1474                 break;
1475         default:
1476                 reg = 0;
1477                 break;
1478         }
1479
1480         return extract_bytes(reg, addr & 7, len);
1481 }
1482
1483 #define GITS_BASER_RO_MASK      (GENMASK_ULL(52, 48) | GENMASK_ULL(58, 56))
1484 static void vgic_mmio_write_its_baser(struct kvm *kvm,
1485                                       struct vgic_its *its,
1486                                       gpa_t addr, unsigned int len,
1487                                       unsigned long val)
1488 {
1489         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
1490         u64 entry_size, table_type;
1491         u64 reg, *regptr, clearbits = 0;
1492
1493         /* When GITS_CTLR.Enable is 1, we ignore write accesses. */
1494         if (its->enabled)
1495                 return;
1496
1497         switch (BASER_INDEX(addr)) {
1498         case 0:
1499                 regptr = &its->baser_device_table;
1500                 entry_size = abi->dte_esz;
1501                 table_type = GITS_BASER_TYPE_DEVICE;
1502                 break;
1503         case 1:
1504                 regptr = &its->baser_coll_table;
1505                 entry_size = abi->cte_esz;
1506                 table_type = GITS_BASER_TYPE_COLLECTION;
1507                 clearbits = GITS_BASER_INDIRECT;
1508                 break;
1509         default:
1510                 return;
1511         }
1512
1513         reg = update_64bit_reg(*regptr, addr & 7, len, val);
1514         reg &= ~GITS_BASER_RO_MASK;
1515         reg &= ~clearbits;
1516
1517         reg |= (entry_size - 1) << GITS_BASER_ENTRY_SIZE_SHIFT;
1518         reg |= table_type << GITS_BASER_TYPE_SHIFT;
1519         reg = vgic_sanitise_its_baser(reg);
1520
1521         *regptr = reg;
1522
1523         if (!(reg & GITS_BASER_VALID)) {
1524                 /* Take the its_lock to prevent a race with a save/restore */
1525                 mutex_lock(&its->its_lock);
1526                 switch (table_type) {
1527                 case GITS_BASER_TYPE_DEVICE:
1528                         vgic_its_free_device_list(kvm, its);
1529                         break;
1530                 case GITS_BASER_TYPE_COLLECTION:
1531                         vgic_its_free_collection_list(kvm, its);
1532                         break;
1533                 }
1534                 mutex_unlock(&its->its_lock);
1535         }
1536 }
1537
1538 static unsigned long vgic_mmio_read_its_ctlr(struct kvm *vcpu,
1539                                              struct vgic_its *its,
1540                                              gpa_t addr, unsigned int len)
1541 {
1542         u32 reg = 0;
1543
1544         mutex_lock(&its->cmd_lock);
1545         if (its->creadr == its->cwriter)
1546                 reg |= GITS_CTLR_QUIESCENT;
1547         if (its->enabled)
1548                 reg |= GITS_CTLR_ENABLE;
1549         mutex_unlock(&its->cmd_lock);
1550
1551         return reg;
1552 }
1553
1554 static void vgic_mmio_write_its_ctlr(struct kvm *kvm, struct vgic_its *its,
1555                                      gpa_t addr, unsigned int len,
1556                                      unsigned long val)
1557 {
1558         mutex_lock(&its->cmd_lock);
1559
1560         /*
1561          * It is UNPREDICTABLE to enable the ITS if any of the CBASER or
1562          * device/collection BASER are invalid
1563          */
1564         if (!its->enabled && (val & GITS_CTLR_ENABLE) &&
1565                 (!(its->baser_device_table & GITS_BASER_VALID) ||
1566                  !(its->baser_coll_table & GITS_BASER_VALID) ||
1567                  !(its->cbaser & GITS_CBASER_VALID)))
1568                 goto out;
1569
1570         its->enabled = !!(val & GITS_CTLR_ENABLE);
1571
1572         /*
1573          * Try to process any pending commands. This function bails out early
1574          * if the ITS is disabled or no commands have been queued.
1575          */
1576         vgic_its_process_commands(kvm, its);
1577
1578 out:
1579         mutex_unlock(&its->cmd_lock);
1580 }
1581
1582 #define REGISTER_ITS_DESC(off, rd, wr, length, acc)             \
1583 {                                                               \
1584         .reg_offset = off,                                      \
1585         .len = length,                                          \
1586         .access_flags = acc,                                    \
1587         .its_read = rd,                                         \
1588         .its_write = wr,                                        \
1589 }
1590
1591 #define REGISTER_ITS_DESC_UACCESS(off, rd, wr, uwr, length, acc)\
1592 {                                                               \
1593         .reg_offset = off,                                      \
1594         .len = length,                                          \
1595         .access_flags = acc,                                    \
1596         .its_read = rd,                                         \
1597         .its_write = wr,                                        \
1598         .uaccess_its_write = uwr,                               \
1599 }
1600
1601 static void its_mmio_write_wi(struct kvm *kvm, struct vgic_its *its,
1602                               gpa_t addr, unsigned int len, unsigned long val)
1603 {
1604         /* Ignore */
1605 }
1606
1607 static struct vgic_register_region its_registers[] = {
1608         REGISTER_ITS_DESC(GITS_CTLR,
1609                 vgic_mmio_read_its_ctlr, vgic_mmio_write_its_ctlr, 4,
1610                 VGIC_ACCESS_32bit),
1611         REGISTER_ITS_DESC_UACCESS(GITS_IIDR,
1612                 vgic_mmio_read_its_iidr, its_mmio_write_wi,
1613                 vgic_mmio_uaccess_write_its_iidr, 4,
1614                 VGIC_ACCESS_32bit),
1615         REGISTER_ITS_DESC(GITS_TYPER,
1616                 vgic_mmio_read_its_typer, its_mmio_write_wi, 8,
1617                 VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1618         REGISTER_ITS_DESC(GITS_CBASER,
1619                 vgic_mmio_read_its_cbaser, vgic_mmio_write_its_cbaser, 8,
1620                 VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1621         REGISTER_ITS_DESC(GITS_CWRITER,
1622                 vgic_mmio_read_its_cwriter, vgic_mmio_write_its_cwriter, 8,
1623                 VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1624         REGISTER_ITS_DESC_UACCESS(GITS_CREADR,
1625                 vgic_mmio_read_its_creadr, its_mmio_write_wi,
1626                 vgic_mmio_uaccess_write_its_creadr, 8,
1627                 VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1628         REGISTER_ITS_DESC(GITS_BASER,
1629                 vgic_mmio_read_its_baser, vgic_mmio_write_its_baser, 0x40,
1630                 VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1631         REGISTER_ITS_DESC(GITS_IDREGS_BASE,
1632                 vgic_mmio_read_its_idregs, its_mmio_write_wi, 0x30,
1633                 VGIC_ACCESS_32bit),
1634 };
1635
1636 /* This is called on setting the LPI enable bit in the redistributor. */
1637 void vgic_enable_lpis(struct kvm_vcpu *vcpu)
1638 {
1639         if (!(vcpu->arch.vgic_cpu.pendbaser & GICR_PENDBASER_PTZ))
1640                 its_sync_lpi_pending_table(vcpu);
1641 }
1642
1643 static int vgic_register_its_iodev(struct kvm *kvm, struct vgic_its *its,
1644                                    u64 addr)
1645 {
1646         struct vgic_io_device *iodev = &its->iodev;
1647         int ret;
1648
1649         mutex_lock(&kvm->slots_lock);
1650         if (!IS_VGIC_ADDR_UNDEF(its->vgic_its_base)) {
1651                 ret = -EBUSY;
1652                 goto out;
1653         }
1654
1655         its->vgic_its_base = addr;
1656         iodev->regions = its_registers;
1657         iodev->nr_regions = ARRAY_SIZE(its_registers);
1658         kvm_iodevice_init(&iodev->dev, &kvm_io_gic_ops);
1659
1660         iodev->base_addr = its->vgic_its_base;
1661         iodev->iodev_type = IODEV_ITS;
1662         iodev->its = its;
1663         ret = kvm_io_bus_register_dev(kvm, KVM_MMIO_BUS, iodev->base_addr,
1664                                       KVM_VGIC_V3_ITS_SIZE, &iodev->dev);
1665 out:
1666         mutex_unlock(&kvm->slots_lock);
1667
1668         return ret;
1669 }
1670
1671 #define INITIAL_BASER_VALUE                                               \
1672         (GIC_BASER_CACHEABILITY(GITS_BASER, INNER, RaWb)                | \
1673          GIC_BASER_CACHEABILITY(GITS_BASER, OUTER, SameAsInner)         | \
1674          GIC_BASER_SHAREABILITY(GITS_BASER, InnerShareable)             | \
1675          GITS_BASER_PAGE_SIZE_64K)
1676
1677 #define INITIAL_PROPBASER_VALUE                                           \
1678         (GIC_BASER_CACHEABILITY(GICR_PROPBASER, INNER, RaWb)            | \
1679          GIC_BASER_CACHEABILITY(GICR_PROPBASER, OUTER, SameAsInner)     | \
1680          GIC_BASER_SHAREABILITY(GICR_PROPBASER, InnerShareable))
1681
1682 static int vgic_its_create(struct kvm_device *dev, u32 type)
1683 {
1684         struct vgic_its *its;
1685
1686         if (type != KVM_DEV_TYPE_ARM_VGIC_ITS)
1687                 return -ENODEV;
1688
1689         its = kzalloc(sizeof(struct vgic_its), GFP_KERNEL);
1690         if (!its)
1691                 return -ENOMEM;
1692
1693         if (vgic_initialized(dev->kvm)) {
1694                 int ret = vgic_v4_init(dev->kvm);
1695                 if (ret < 0) {
1696                         kfree(its);
1697                         return ret;
1698                 }
1699         }
1700
1701         mutex_init(&its->its_lock);
1702         mutex_init(&its->cmd_lock);
1703
1704         its->vgic_its_base = VGIC_ADDR_UNDEF;
1705
1706         INIT_LIST_HEAD(&its->device_list);
1707         INIT_LIST_HEAD(&its->collection_list);
1708
1709         dev->kvm->arch.vgic.msis_require_devid = true;
1710         dev->kvm->arch.vgic.has_its = true;
1711         its->enabled = false;
1712         its->dev = dev;
1713
1714         its->baser_device_table = INITIAL_BASER_VALUE                   |
1715                 ((u64)GITS_BASER_TYPE_DEVICE << GITS_BASER_TYPE_SHIFT);
1716         its->baser_coll_table = INITIAL_BASER_VALUE |
1717                 ((u64)GITS_BASER_TYPE_COLLECTION << GITS_BASER_TYPE_SHIFT);
1718         dev->kvm->arch.vgic.propbaser = INITIAL_PROPBASER_VALUE;
1719
1720         dev->private = its;
1721
1722         return vgic_its_set_abi(its, NR_ITS_ABIS - 1);
1723 }
1724
1725 static void vgic_its_destroy(struct kvm_device *kvm_dev)
1726 {
1727         struct kvm *kvm = kvm_dev->kvm;
1728         struct vgic_its *its = kvm_dev->private;
1729
1730         mutex_lock(&its->its_lock);
1731
1732         vgic_its_free_device_list(kvm, its);
1733         vgic_its_free_collection_list(kvm, its);
1734
1735         mutex_unlock(&its->its_lock);
1736         kfree(its);
1737 }
1738
1739 static int vgic_its_has_attr_regs(struct kvm_device *dev,
1740                                   struct kvm_device_attr *attr)
1741 {
1742         const struct vgic_register_region *region;
1743         gpa_t offset = attr->attr;
1744         int align;
1745
1746         align = (offset < GITS_TYPER) || (offset >= GITS_PIDR4) ? 0x3 : 0x7;
1747
1748         if (offset & align)
1749                 return -EINVAL;
1750
1751         region = vgic_find_mmio_region(its_registers,
1752                                        ARRAY_SIZE(its_registers),
1753                                        offset);
1754         if (!region)
1755                 return -ENXIO;
1756
1757         return 0;
1758 }
1759
1760 static int vgic_its_attr_regs_access(struct kvm_device *dev,
1761                                      struct kvm_device_attr *attr,
1762                                      u64 *reg, bool is_write)
1763 {
1764         const struct vgic_register_region *region;
1765         struct vgic_its *its;
1766         gpa_t addr, offset;
1767         unsigned int len;
1768         int align, ret = 0;
1769
1770         its = dev->private;
1771         offset = attr->attr;
1772
1773         /*
1774          * Although the spec supports upper/lower 32-bit accesses to
1775          * 64-bit ITS registers, the userspace ABI requires 64-bit
1776          * accesses to all 64-bit wide registers. We therefore only
1777          * support 32-bit accesses to GITS_CTLR, GITS_IIDR and GITS ID
1778          * registers
1779          */
1780         if ((offset < GITS_TYPER) || (offset >= GITS_PIDR4))
1781                 align = 0x3;
1782         else
1783                 align = 0x7;
1784
1785         if (offset & align)
1786                 return -EINVAL;
1787
1788         mutex_lock(&dev->kvm->lock);
1789
1790         if (IS_VGIC_ADDR_UNDEF(its->vgic_its_base)) {
1791                 ret = -ENXIO;
1792                 goto out;
1793         }
1794
1795         region = vgic_find_mmio_region(its_registers,
1796                                        ARRAY_SIZE(its_registers),
1797                                        offset);
1798         if (!region) {
1799                 ret = -ENXIO;
1800                 goto out;
1801         }
1802
1803         if (!lock_all_vcpus(dev->kvm)) {
1804                 ret = -EBUSY;
1805                 goto out;
1806         }
1807
1808         addr = its->vgic_its_base + offset;
1809
1810         len = region->access_flags & VGIC_ACCESS_64bit ? 8 : 4;
1811
1812         if (is_write) {
1813                 if (region->uaccess_its_write)
1814                         ret = region->uaccess_its_write(dev->kvm, its, addr,
1815                                                         len, *reg);
1816                 else
1817                         region->its_write(dev->kvm, its, addr, len, *reg);
1818         } else {
1819                 *reg = region->its_read(dev->kvm, its, addr, len);
1820         }
1821         unlock_all_vcpus(dev->kvm);
1822 out:
1823         mutex_unlock(&dev->kvm->lock);
1824         return ret;
1825 }
1826
1827 static u32 compute_next_devid_offset(struct list_head *h,
1828                                      struct its_device *dev)
1829 {
1830         struct its_device *next;
1831         u32 next_offset;
1832
1833         if (list_is_last(&dev->dev_list, h))
1834                 return 0;
1835         next = list_next_entry(dev, dev_list);
1836         next_offset = next->device_id - dev->device_id;
1837
1838         return min_t(u32, next_offset, VITS_DTE_MAX_DEVID_OFFSET);
1839 }
1840
1841 static u32 compute_next_eventid_offset(struct list_head *h, struct its_ite *ite)
1842 {
1843         struct its_ite *next;
1844         u32 next_offset;
1845
1846         if (list_is_last(&ite->ite_list, h))
1847                 return 0;
1848         next = list_next_entry(ite, ite_list);
1849         next_offset = next->event_id - ite->event_id;
1850
1851         return min_t(u32, next_offset, VITS_ITE_MAX_EVENTID_OFFSET);
1852 }
1853
1854 /**
1855  * entry_fn_t - Callback called on a table entry restore path
1856  * @its: its handle
1857  * @id: id of the entry
1858  * @entry: pointer to the entry
1859  * @opaque: pointer to an opaque data
1860  *
1861  * Return: < 0 on error, 0 if last element was identified, id offset to next
1862  * element otherwise
1863  */
1864 typedef int (*entry_fn_t)(struct vgic_its *its, u32 id, void *entry,
1865                           void *opaque);
1866
1867 /**
1868  * scan_its_table - Scan a contiguous table in guest RAM and applies a function
1869  * to each entry
1870  *
1871  * @its: its handle
1872  * @base: base gpa of the table
1873  * @size: size of the table in bytes
1874  * @esz: entry size in bytes
1875  * @start_id: the ID of the first entry in the table
1876  * (non zero for 2d level tables)
1877  * @fn: function to apply on each entry
1878  *
1879  * Return: < 0 on error, 0 if last element was identified, 1 otherwise
1880  * (the last element may not be found on second level tables)
1881  */
1882 static int scan_its_table(struct vgic_its *its, gpa_t base, int size, u32 esz,
1883                           int start_id, entry_fn_t fn, void *opaque)
1884 {
1885         struct kvm *kvm = its->dev->kvm;
1886         unsigned long len = size;
1887         int id = start_id;
1888         gpa_t gpa = base;
1889         char entry[ESZ_MAX];
1890         int ret;
1891
1892         memset(entry, 0, esz);
1893
1894         while (len > 0) {
1895                 int next_offset;
1896                 size_t byte_offset;
1897
1898                 ret = kvm_read_guest_lock(kvm, gpa, entry, esz);
1899                 if (ret)
1900                         return ret;
1901
1902                 next_offset = fn(its, id, entry, opaque);
1903                 if (next_offset <= 0)
1904                         return next_offset;
1905
1906                 byte_offset = next_offset * esz;
1907                 id += next_offset;
1908                 gpa += byte_offset;
1909                 len -= byte_offset;
1910         }
1911         return 1;
1912 }
1913
1914 /**
1915  * vgic_its_save_ite - Save an interrupt translation entry at @gpa
1916  */
1917 static int vgic_its_save_ite(struct vgic_its *its, struct its_device *dev,
1918                               struct its_ite *ite, gpa_t gpa, int ite_esz)
1919 {
1920         struct kvm *kvm = its->dev->kvm;
1921         u32 next_offset;
1922         u64 val;
1923
1924         next_offset = compute_next_eventid_offset(&dev->itt_head, ite);
1925         val = ((u64)next_offset << KVM_ITS_ITE_NEXT_SHIFT) |
1926                ((u64)ite->irq->intid << KVM_ITS_ITE_PINTID_SHIFT) |
1927                 ite->collection->collection_id;
1928         val = cpu_to_le64(val);
1929         return kvm_write_guest_lock(kvm, gpa, &val, ite_esz);
1930 }
1931
1932 /**
1933  * vgic_its_restore_ite - restore an interrupt translation entry
1934  * @event_id: id used for indexing
1935  * @ptr: pointer to the ITE entry
1936  * @opaque: pointer to the its_device
1937  */
1938 static int vgic_its_restore_ite(struct vgic_its *its, u32 event_id,
1939                                 void *ptr, void *opaque)
1940 {
1941         struct its_device *dev = (struct its_device *)opaque;
1942         struct its_collection *collection;
1943         struct kvm *kvm = its->dev->kvm;
1944         struct kvm_vcpu *vcpu = NULL;
1945         u64 val;
1946         u64 *p = (u64 *)ptr;
1947         struct vgic_irq *irq;
1948         u32 coll_id, lpi_id;
1949         struct its_ite *ite;
1950         u32 offset;
1951
1952         val = *p;
1953
1954         val = le64_to_cpu(val);
1955
1956         coll_id = val & KVM_ITS_ITE_ICID_MASK;
1957         lpi_id = (val & KVM_ITS_ITE_PINTID_MASK) >> KVM_ITS_ITE_PINTID_SHIFT;
1958
1959         if (!lpi_id)
1960                 return 1; /* invalid entry, no choice but to scan next entry */
1961
1962         if (lpi_id < VGIC_MIN_LPI)
1963                 return -EINVAL;
1964
1965         offset = val >> KVM_ITS_ITE_NEXT_SHIFT;
1966         if (event_id + offset >= BIT_ULL(dev->num_eventid_bits))
1967                 return -EINVAL;
1968
1969         collection = find_collection(its, coll_id);
1970         if (!collection)
1971                 return -EINVAL;
1972
1973         ite = vgic_its_alloc_ite(dev, collection, event_id);
1974         if (IS_ERR(ite))
1975                 return PTR_ERR(ite);
1976
1977         if (its_is_collection_mapped(collection))
1978                 vcpu = kvm_get_vcpu(kvm, collection->target_addr);
1979
1980         irq = vgic_add_lpi(kvm, lpi_id, vcpu);
1981         if (IS_ERR(irq))
1982                 return PTR_ERR(irq);
1983         ite->irq = irq;
1984
1985         return offset;
1986 }
1987
1988 static int vgic_its_ite_cmp(void *priv, struct list_head *a,
1989                             struct list_head *b)
1990 {
1991         struct its_ite *itea = container_of(a, struct its_ite, ite_list);
1992         struct its_ite *iteb = container_of(b, struct its_ite, ite_list);
1993
1994         if (itea->event_id < iteb->event_id)
1995                 return -1;
1996         else
1997                 return 1;
1998 }
1999
2000 static int vgic_its_save_itt(struct vgic_its *its, struct its_device *device)
2001 {
2002         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2003         gpa_t base = device->itt_addr;
2004         struct its_ite *ite;
2005         int ret;
2006         int ite_esz = abi->ite_esz;
2007
2008         list_sort(NULL, &device->itt_head, vgic_its_ite_cmp);
2009
2010         list_for_each_entry(ite, &device->itt_head, ite_list) {
2011                 gpa_t gpa = base + ite->event_id * ite_esz;
2012
2013                 /*
2014                  * If an LPI carries the HW bit, this means that this
2015                  * interrupt is controlled by GICv4, and we do not
2016                  * have direct access to that state. Let's simply fail
2017                  * the save operation...
2018                  */
2019                 if (ite->irq->hw)
2020                         return -EACCES;
2021
2022                 ret = vgic_its_save_ite(its, device, ite, gpa, ite_esz);
2023                 if (ret)
2024                         return ret;
2025         }
2026         return 0;
2027 }
2028
2029 /**
2030  * vgic_its_restore_itt - restore the ITT of a device
2031  *
2032  * @its: its handle
2033  * @dev: device handle
2034  *
2035  * Return 0 on success, < 0 on error
2036  */
2037 static int vgic_its_restore_itt(struct vgic_its *its, struct its_device *dev)
2038 {
2039         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2040         gpa_t base = dev->itt_addr;
2041         int ret;
2042         int ite_esz = abi->ite_esz;
2043         size_t max_size = BIT_ULL(dev->num_eventid_bits) * ite_esz;
2044
2045         ret = scan_its_table(its, base, max_size, ite_esz, 0,
2046                              vgic_its_restore_ite, dev);
2047
2048         /* scan_its_table returns +1 if all ITEs are invalid */
2049         if (ret > 0)
2050                 ret = 0;
2051
2052         return ret;
2053 }
2054
2055 /**
2056  * vgic_its_save_dte - Save a device table entry at a given GPA
2057  *
2058  * @its: ITS handle
2059  * @dev: ITS device
2060  * @ptr: GPA
2061  */
2062 static int vgic_its_save_dte(struct vgic_its *its, struct its_device *dev,
2063                              gpa_t ptr, int dte_esz)
2064 {
2065         struct kvm *kvm = its->dev->kvm;
2066         u64 val, itt_addr_field;
2067         u32 next_offset;
2068
2069         itt_addr_field = dev->itt_addr >> 8;
2070         next_offset = compute_next_devid_offset(&its->device_list, dev);
2071         val = (1ULL << KVM_ITS_DTE_VALID_SHIFT |
2072                ((u64)next_offset << KVM_ITS_DTE_NEXT_SHIFT) |
2073                (itt_addr_field << KVM_ITS_DTE_ITTADDR_SHIFT) |
2074                 (dev->num_eventid_bits - 1));
2075         val = cpu_to_le64(val);
2076         return kvm_write_guest_lock(kvm, ptr, &val, dte_esz);
2077 }
2078
2079 /**
2080  * vgic_its_restore_dte - restore a device table entry
2081  *
2082  * @its: its handle
2083  * @id: device id the DTE corresponds to
2084  * @ptr: kernel VA where the 8 byte DTE is located
2085  * @opaque: unused
2086  *
2087  * Return: < 0 on error, 0 if the dte is the last one, id offset to the
2088  * next dte otherwise
2089  */
2090 static int vgic_its_restore_dte(struct vgic_its *its, u32 id,
2091                                 void *ptr, void *opaque)
2092 {
2093         struct its_device *dev;
2094         gpa_t itt_addr;
2095         u8 num_eventid_bits;
2096         u64 entry = *(u64 *)ptr;
2097         bool valid;
2098         u32 offset;
2099         int ret;
2100
2101         entry = le64_to_cpu(entry);
2102
2103         valid = entry >> KVM_ITS_DTE_VALID_SHIFT;
2104         num_eventid_bits = (entry & KVM_ITS_DTE_SIZE_MASK) + 1;
2105         itt_addr = ((entry & KVM_ITS_DTE_ITTADDR_MASK)
2106                         >> KVM_ITS_DTE_ITTADDR_SHIFT) << 8;
2107
2108         if (!valid)
2109                 return 1;
2110
2111         /* dte entry is valid */
2112         offset = (entry & KVM_ITS_DTE_NEXT_MASK) >> KVM_ITS_DTE_NEXT_SHIFT;
2113
2114         dev = vgic_its_alloc_device(its, id, itt_addr, num_eventid_bits);
2115         if (IS_ERR(dev))
2116                 return PTR_ERR(dev);
2117
2118         ret = vgic_its_restore_itt(its, dev);
2119         if (ret) {
2120                 vgic_its_free_device(its->dev->kvm, dev);
2121                 return ret;
2122         }
2123
2124         return offset;
2125 }
2126
2127 static int vgic_its_device_cmp(void *priv, struct list_head *a,
2128                                struct list_head *b)
2129 {
2130         struct its_device *deva = container_of(a, struct its_device, dev_list);
2131         struct its_device *devb = container_of(b, struct its_device, dev_list);
2132
2133         if (deva->device_id < devb->device_id)
2134                 return -1;
2135         else
2136                 return 1;
2137 }
2138
2139 /**
2140  * vgic_its_save_device_tables - Save the device table and all ITT
2141  * into guest RAM
2142  *
2143  * L1/L2 handling is hidden by vgic_its_check_id() helper which directly
2144  * returns the GPA of the device entry
2145  */
2146 static int vgic_its_save_device_tables(struct vgic_its *its)
2147 {
2148         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2149         u64 baser = its->baser_device_table;
2150         struct its_device *dev;
2151         int dte_esz = abi->dte_esz;
2152
2153         if (!(baser & GITS_BASER_VALID))
2154                 return 0;
2155
2156         list_sort(NULL, &its->device_list, vgic_its_device_cmp);
2157
2158         list_for_each_entry(dev, &its->device_list, dev_list) {
2159                 int ret;
2160                 gpa_t eaddr;
2161
2162                 if (!vgic_its_check_id(its, baser,
2163                                        dev->device_id, &eaddr))
2164                         return -EINVAL;
2165
2166                 ret = vgic_its_save_itt(its, dev);
2167                 if (ret)
2168                         return ret;
2169
2170                 ret = vgic_its_save_dte(its, dev, eaddr, dte_esz);
2171                 if (ret)
2172                         return ret;
2173         }
2174         return 0;
2175 }
2176
2177 /**
2178  * handle_l1_dte - callback used for L1 device table entries (2 stage case)
2179  *
2180  * @its: its handle
2181  * @id: index of the entry in the L1 table
2182  * @addr: kernel VA
2183  * @opaque: unused
2184  *
2185  * L1 table entries are scanned by steps of 1 entry
2186  * Return < 0 if error, 0 if last dte was found when scanning the L2
2187  * table, +1 otherwise (meaning next L1 entry must be scanned)
2188  */
2189 static int handle_l1_dte(struct vgic_its *its, u32 id, void *addr,
2190                          void *opaque)
2191 {
2192         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2193         int l2_start_id = id * (SZ_64K / abi->dte_esz);
2194         u64 entry = *(u64 *)addr;
2195         int dte_esz = abi->dte_esz;
2196         gpa_t gpa;
2197         int ret;
2198
2199         entry = le64_to_cpu(entry);
2200
2201         if (!(entry & KVM_ITS_L1E_VALID_MASK))
2202                 return 1;
2203
2204         gpa = entry & KVM_ITS_L1E_ADDR_MASK;
2205
2206         ret = scan_its_table(its, gpa, SZ_64K, dte_esz,
2207                              l2_start_id, vgic_its_restore_dte, NULL);
2208
2209         return ret;
2210 }
2211
2212 /**
2213  * vgic_its_restore_device_tables - Restore the device table and all ITT
2214  * from guest RAM to internal data structs
2215  */
2216 static int vgic_its_restore_device_tables(struct vgic_its *its)
2217 {
2218         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2219         u64 baser = its->baser_device_table;
2220         int l1_esz, ret;
2221         int l1_tbl_size = GITS_BASER_NR_PAGES(baser) * SZ_64K;
2222         gpa_t l1_gpa;
2223
2224         if (!(baser & GITS_BASER_VALID))
2225                 return 0;
2226
2227         l1_gpa = GITS_BASER_ADDR_48_to_52(baser);
2228
2229         if (baser & GITS_BASER_INDIRECT) {
2230                 l1_esz = GITS_LVL1_ENTRY_SIZE;
2231                 ret = scan_its_table(its, l1_gpa, l1_tbl_size, l1_esz, 0,
2232                                      handle_l1_dte, NULL);
2233         } else {
2234                 l1_esz = abi->dte_esz;
2235                 ret = scan_its_table(its, l1_gpa, l1_tbl_size, l1_esz, 0,
2236                                      vgic_its_restore_dte, NULL);
2237         }
2238
2239         /* scan_its_table returns +1 if all entries are invalid */
2240         if (ret > 0)
2241                 ret = 0;
2242
2243         return ret;
2244 }
2245
2246 static int vgic_its_save_cte(struct vgic_its *its,
2247                              struct its_collection *collection,
2248                              gpa_t gpa, int esz)
2249 {
2250         u64 val;
2251
2252         val = (1ULL << KVM_ITS_CTE_VALID_SHIFT |
2253                ((u64)collection->target_addr << KVM_ITS_CTE_RDBASE_SHIFT) |
2254                collection->collection_id);
2255         val = cpu_to_le64(val);
2256         return kvm_write_guest_lock(its->dev->kvm, gpa, &val, esz);
2257 }
2258
2259 static int vgic_its_restore_cte(struct vgic_its *its, gpa_t gpa, int esz)
2260 {
2261         struct its_collection *collection;
2262         struct kvm *kvm = its->dev->kvm;
2263         u32 target_addr, coll_id;
2264         u64 val;
2265         int ret;
2266
2267         BUG_ON(esz > sizeof(val));
2268         ret = kvm_read_guest_lock(kvm, gpa, &val, esz);
2269         if (ret)
2270                 return ret;
2271         val = le64_to_cpu(val);
2272         if (!(val & KVM_ITS_CTE_VALID_MASK))
2273                 return 0;
2274
2275         target_addr = (u32)(val >> KVM_ITS_CTE_RDBASE_SHIFT);
2276         coll_id = val & KVM_ITS_CTE_ICID_MASK;
2277
2278         if (target_addr >= atomic_read(&kvm->online_vcpus))
2279                 return -EINVAL;
2280
2281         collection = find_collection(its, coll_id);
2282         if (collection)
2283                 return -EEXIST;
2284         ret = vgic_its_alloc_collection(its, &collection, coll_id);
2285         if (ret)
2286                 return ret;
2287         collection->target_addr = target_addr;
2288         return 1;
2289 }
2290
2291 /**
2292  * vgic_its_save_collection_table - Save the collection table into
2293  * guest RAM
2294  */
2295 static int vgic_its_save_collection_table(struct vgic_its *its)
2296 {
2297         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2298         u64 baser = its->baser_coll_table;
2299         gpa_t gpa = GITS_BASER_ADDR_48_to_52(baser);
2300         struct its_collection *collection;
2301         u64 val;
2302         size_t max_size, filled = 0;
2303         int ret, cte_esz = abi->cte_esz;
2304
2305         if (!(baser & GITS_BASER_VALID))
2306                 return 0;
2307
2308         max_size = GITS_BASER_NR_PAGES(baser) * SZ_64K;
2309
2310         list_for_each_entry(collection, &its->collection_list, coll_list) {
2311                 ret = vgic_its_save_cte(its, collection, gpa, cte_esz);
2312                 if (ret)
2313                         return ret;
2314                 gpa += cte_esz;
2315                 filled += cte_esz;
2316         }
2317
2318         if (filled == max_size)
2319                 return 0;
2320
2321         /*
2322          * table is not fully filled, add a last dummy element
2323          * with valid bit unset
2324          */
2325         val = 0;
2326         BUG_ON(cte_esz > sizeof(val));
2327         ret = kvm_write_guest_lock(its->dev->kvm, gpa, &val, cte_esz);
2328         return ret;
2329 }
2330
2331 /**
2332  * vgic_its_restore_collection_table - reads the collection table
2333  * in guest memory and restores the ITS internal state. Requires the
2334  * BASER registers to be restored before.
2335  */
2336 static int vgic_its_restore_collection_table(struct vgic_its *its)
2337 {
2338         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2339         u64 baser = its->baser_coll_table;
2340         int cte_esz = abi->cte_esz;
2341         size_t max_size, read = 0;
2342         gpa_t gpa;
2343         int ret;
2344
2345         if (!(baser & GITS_BASER_VALID))
2346                 return 0;
2347
2348         gpa = GITS_BASER_ADDR_48_to_52(baser);
2349
2350         max_size = GITS_BASER_NR_PAGES(baser) * SZ_64K;
2351
2352         while (read < max_size) {
2353                 ret = vgic_its_restore_cte(its, gpa, cte_esz);
2354                 if (ret <= 0)
2355                         break;
2356                 gpa += cte_esz;
2357                 read += cte_esz;
2358         }
2359
2360         if (ret > 0)
2361                 return 0;
2362
2363         return ret;
2364 }
2365
2366 /**
2367  * vgic_its_save_tables_v0 - Save the ITS tables into guest ARM
2368  * according to v0 ABI
2369  */
2370 static int vgic_its_save_tables_v0(struct vgic_its *its)
2371 {
2372         int ret;
2373
2374         ret = vgic_its_save_device_tables(its);
2375         if (ret)
2376                 return ret;
2377
2378         return vgic_its_save_collection_table(its);
2379 }
2380
2381 /**
2382  * vgic_its_restore_tables_v0 - Restore the ITS tables from guest RAM
2383  * to internal data structs according to V0 ABI
2384  *
2385  */
2386 static int vgic_its_restore_tables_v0(struct vgic_its *its)
2387 {
2388         int ret;
2389
2390         ret = vgic_its_restore_collection_table(its);
2391         if (ret)
2392                 return ret;
2393
2394         return vgic_its_restore_device_tables(its);
2395 }
2396
2397 static int vgic_its_commit_v0(struct vgic_its *its)
2398 {
2399         const struct vgic_its_abi *abi;
2400
2401         abi = vgic_its_get_abi(its);
2402         its->baser_coll_table &= ~GITS_BASER_ENTRY_SIZE_MASK;
2403         its->baser_device_table &= ~GITS_BASER_ENTRY_SIZE_MASK;
2404
2405         its->baser_coll_table |= (GIC_ENCODE_SZ(abi->cte_esz, 5)
2406                                         << GITS_BASER_ENTRY_SIZE_SHIFT);
2407
2408         its->baser_device_table |= (GIC_ENCODE_SZ(abi->dte_esz, 5)
2409                                         << GITS_BASER_ENTRY_SIZE_SHIFT);
2410         return 0;
2411 }
2412
2413 static void vgic_its_reset(struct kvm *kvm, struct vgic_its *its)
2414 {
2415         /* We need to keep the ABI specific field values */
2416         its->baser_coll_table &= ~GITS_BASER_VALID;
2417         its->baser_device_table &= ~GITS_BASER_VALID;
2418         its->cbaser = 0;
2419         its->creadr = 0;
2420         its->cwriter = 0;
2421         its->enabled = 0;
2422         vgic_its_free_device_list(kvm, its);
2423         vgic_its_free_collection_list(kvm, its);
2424 }
2425
2426 static int vgic_its_has_attr(struct kvm_device *dev,
2427                              struct kvm_device_attr *attr)
2428 {
2429         switch (attr->group) {
2430         case KVM_DEV_ARM_VGIC_GRP_ADDR:
2431                 switch (attr->attr) {
2432                 case KVM_VGIC_ITS_ADDR_TYPE:
2433                         return 0;
2434                 }
2435                 break;
2436         case KVM_DEV_ARM_VGIC_GRP_CTRL:
2437                 switch (attr->attr) {
2438                 case KVM_DEV_ARM_VGIC_CTRL_INIT:
2439                         return 0;
2440                 case KVM_DEV_ARM_ITS_CTRL_RESET:
2441                         return 0;
2442                 case KVM_DEV_ARM_ITS_SAVE_TABLES:
2443                         return 0;
2444                 case KVM_DEV_ARM_ITS_RESTORE_TABLES:
2445                         return 0;
2446                 }
2447                 break;
2448         case KVM_DEV_ARM_VGIC_GRP_ITS_REGS:
2449                 return vgic_its_has_attr_regs(dev, attr);
2450         }
2451         return -ENXIO;
2452 }
2453
2454 static int vgic_its_ctrl(struct kvm *kvm, struct vgic_its *its, u64 attr)
2455 {
2456         const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2457         int ret = 0;
2458
2459         if (attr == KVM_DEV_ARM_VGIC_CTRL_INIT) /* Nothing to do */
2460                 return 0;
2461
2462         mutex_lock(&kvm->lock);
2463         mutex_lock(&its->its_lock);
2464
2465         if (!lock_all_vcpus(kvm)) {
2466                 mutex_unlock(&its->its_lock);
2467                 mutex_unlock(&kvm->lock);
2468                 return -EBUSY;
2469         }
2470
2471         switch (attr) {
2472         case KVM_DEV_ARM_ITS_CTRL_RESET:
2473                 vgic_its_reset(kvm, its);
2474                 break;
2475         case KVM_DEV_ARM_ITS_SAVE_TABLES:
2476                 ret = abi->save_tables(its);
2477                 break;
2478         case KVM_DEV_ARM_ITS_RESTORE_TABLES:
2479                 ret = abi->restore_tables(its);
2480                 break;
2481         }
2482
2483         unlock_all_vcpus(kvm);
2484         mutex_unlock(&its->its_lock);
2485         mutex_unlock(&kvm->lock);
2486         return ret;
2487 }
2488
2489 static int vgic_its_set_attr(struct kvm_device *dev,
2490                              struct kvm_device_attr *attr)
2491 {
2492         struct vgic_its *its = dev->private;
2493         int ret;
2494
2495         switch (attr->group) {
2496         case KVM_DEV_ARM_VGIC_GRP_ADDR: {
2497                 u64 __user *uaddr = (u64 __user *)(long)attr->addr;
2498                 unsigned long type = (unsigned long)attr->attr;
2499                 u64 addr;
2500
2501                 if (type != KVM_VGIC_ITS_ADDR_TYPE)
2502                         return -ENODEV;
2503
2504                 if (copy_from_user(&addr, uaddr, sizeof(addr)))
2505                         return -EFAULT;
2506
2507                 ret = vgic_check_ioaddr(dev->kvm, &its->vgic_its_base,
2508                                         addr, SZ_64K);
2509                 if (ret)
2510                         return ret;
2511
2512                 return vgic_register_its_iodev(dev->kvm, its, addr);
2513         }
2514         case KVM_DEV_ARM_VGIC_GRP_CTRL:
2515                 return vgic_its_ctrl(dev->kvm, its, attr->attr);
2516         case KVM_DEV_ARM_VGIC_GRP_ITS_REGS: {
2517                 u64 __user *uaddr = (u64 __user *)(long)attr->addr;
2518                 u64 reg;
2519
2520                 if (get_user(reg, uaddr))
2521                         return -EFAULT;
2522
2523                 return vgic_its_attr_regs_access(dev, attr, &reg, true);
2524         }
2525         }
2526         return -ENXIO;
2527 }
2528
2529 static int vgic_its_get_attr(struct kvm_device *dev,
2530                              struct kvm_device_attr *attr)
2531 {
2532         switch (attr->group) {
2533         case KVM_DEV_ARM_VGIC_GRP_ADDR: {
2534                 struct vgic_its *its = dev->private;
2535                 u64 addr = its->vgic_its_base;
2536                 u64 __user *uaddr = (u64 __user *)(long)attr->addr;
2537                 unsigned long type = (unsigned long)attr->attr;
2538
2539                 if (type != KVM_VGIC_ITS_ADDR_TYPE)
2540                         return -ENODEV;
2541
2542                 if (copy_to_user(uaddr, &addr, sizeof(addr)))
2543                         return -EFAULT;
2544                 break;
2545         }
2546         case KVM_DEV_ARM_VGIC_GRP_ITS_REGS: {
2547                 u64 __user *uaddr = (u64 __user *)(long)attr->addr;
2548                 u64 reg;
2549                 int ret;
2550
2551                 ret = vgic_its_attr_regs_access(dev, attr, &reg, false);
2552                 if (ret)
2553                         return ret;
2554                 return put_user(reg, uaddr);
2555         }
2556         default:
2557                 return -ENXIO;
2558         }
2559
2560         return 0;
2561 }
2562
2563 static struct kvm_device_ops kvm_arm_vgic_its_ops = {
2564         .name = "kvm-arm-vgic-its",
2565         .create = vgic_its_create,
2566         .destroy = vgic_its_destroy,
2567         .set_attr = vgic_its_set_attr,
2568         .get_attr = vgic_its_get_attr,
2569         .has_attr = vgic_its_has_attr,
2570 };
2571
2572 int kvm_vgic_register_its_device(void)
2573 {
2574         return kvm_register_device_ops(&kvm_arm_vgic_its_ops,
2575                                        KVM_DEV_TYPE_ARM_VGIC_ITS);
2576 }