1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Permission is hereby granted, free of charge, to any person
5  * obtaining a copy of this software and associated documentation
6  * files (the "Software"), to deal in the Software without
7  * restriction, including without limitation the rights to use, copy,
8  * modify, merge, publish, distribute, sublicense, and/or sell copies
9  * of the Software, and to permit persons to whom the Software is
10  * furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be
13  * included in all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
19  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 
25 #include <test-runner-arch.h>
26 
27 #include <assert.h>
28 #include <stdbool.h>
29 #include <stddef.h>
30 #include <stdint.h>
31 #include <trusty/smc.h>
32 #include <trusty/smcall.h>
33 
34 #if GIC_VERSION > 2
35 #define GICD_BASE (0x08000000)
36 #define GICD_CTLR (GICD_BASE + 0x000)
37 
38 #define GICR_BASE (0x080A0000)
39 #define GICR_SGI_BASE (GICR_BASE + 0x10000)
40 #define GICR_ISENABLER0 (GICR_SGI_BASE + 0x0100)
41 #define GICR_CPU_OFFSET(cpu) ((cpu)*0x20000)
42 
43 #define REG32(addr) ((volatile uint32_t*)(uintptr_t)(addr))
44 #define GICDREG_READ(reg) (*REG32((reg)))
45 #define GICDREG_WRITE(reg, val) (*REG32((reg)) = (val))
46 
47 #define GICRREG_READ(cpu, reg) (*REG32((reg) + GICR_CPU_OFFSET(cpu)))
48 #define GICRREG_WRITE(cpu, reg, val) \
49     (*REG32((reg) + GICR_CPU_OFFSET(cpu)) = (val))
50 
51 static uint32_t doorbell_irq;
52 #endif
53 
arch_gic_init(int cpu)54 int arch_gic_init(int cpu) {
55 #if GIC_VERSION > 2
56     if (!cpu) {
57         GICDREG_WRITE(GICD_CTLR, 2); /* Enable Non-secure group 1 interrupt */
58         doorbell_irq = smc(SMC_FC_GET_NEXT_IRQ, 0, TRUSTY_IRQ_TYPE_DOORBELL, 0);
59     }
60     if (doorbell_irq >= 32) {
61         /*
62          * We only support per-cpu doorbell interrupts which are all enabled by
63          * GICR_ISENABLER0.
64          */
65         return -1;
66     }
67     GICRREG_WRITE(cpu, GICR_ISENABLER0, 1U << doorbell_irq);
68     GICRREG_WRITE(cpu, GICR_ISENABLER0, 1U << 0); /* skip_cpu0_wfi interrupt */
69     __asm__ volatile("msr icc_igrpen1_el1, %0" ::"r"(1UL));
70 #endif
71 
72     return 0;
73 }
74