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