1/*
2 * Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 */
6
7#include <autoconf.h>
8#include <elfloader/gen_config.h>
9
10#include <assembler.h>
11#include <armv/assembler.h>
12
13.text
14
15.extern _boot_pd
16
17BEGIN_FUNC(invalidate_dcache)
18    stmfd   sp!, {r4-r11,lr}
19    dcache  isw
20    ldmfd   sp!, {r4-r11,pc}
21END_FUNC(invalidate_dcache)
22
23BEGIN_FUNC(invalidate_icache)
24    mcr     IIALL(r1)
25    bx      lr
26END_FUNC(invalidate_icache)
27
28BEGIN_FUNC(flush_dcache)
29    stmfd   sp!, {r4-r11,lr}
30    dcache  cisw
31    ldmfd   sp!, {r4-r11,pc}
32END_FUNC(flush_dcache)
33
34/*
35 * Enable the ARM MMU.
36 *
37 * It is expected that the code of this function will be mapped 1:1
38 * virtual/physical in the pagetable we activate.
39 */
40BEGIN_FUNC(arm_enable_mmu)
41    stmfd   sp!, {lr}
42
43    /* Clean D-Cache if enabled */
44    mrc     SCTLR(r1)
45    and     r1, r1, #(1 << 2)
46    cmp     r1, #0
47    beq     1f
48    bl      flush_dcache
491:
50    /* Ensure I-cache, D-cache and mmu are disabled. */
51    mrc     SCTLR(r1)
52    bic     r1, r1, #(1 << 12)      /* Disable I-cache */
53    bic     r1, r1, #(1 << 2)       /* Disable D-Cache */
54    bic     r1, r1, #(1 << 0)       /* Disable MMU     */
55    mcr     SCTLR(r1)
56
57    /* invalidate caches. */
58    bl      invalidate_dcache
59    bl      invalidate_icache
60
61    /* Set up TTBR0, enable caching of pagetables. */
62    bl      get_boot_pd
63    orr     r1, r0, #0x19
64    mcr     TTBR0(r1)
65    mcr     TLBIALL(r1)
66
67    /* Setup client to only have access to domain 0, and setup the DACR. */
68    mov     r1, #1
69    mcr     DACR(r1)
70
71    /* Setup misc MMU. */
72    mov     r1, #0
73    mcr     CONTEXTIDR(r1)  /* set ASID to 0    */
74    mcr     TTBCR(r1)       /* set TTBCR to 0   */
75    mcr     BPIALL(r1)      /* flush branch target cache */
76    isb
77
78    /* Enable MMU, D-cache, and I-cache. */
79    mrc     SCTLR(r0)
80    orr     r0, r0, #(1 << 13)      /* selects the base address of the exception vectors */
81    orr     r0, r0, #(1 << 12)      /* Enable I-cache */
82    orr     r0, r0, #(1 << 2)       /* Enable D-cache */
83    orr     r0, r0, #(1 << 0)       /* Enable MMU */
84    mcr     SCTLR(r0)
85
86    /* Enable/disable Async aborts to drain pending bootloader aborts */
87    cpsie   a
88    dsb
89    isb
90    cpsid   a
91
92    ldmfd   sp!, {pc}
93END_FUNC(arm_enable_mmu)
94
95BEGIN_FUNC(arm_disable_dcaches)
96    stmfd   sp!, {lr}
97
98    /* Clean D-Cache if enabled */
99    mrc     SCTLR(r1)
100    and     r1, r1, #(1 << 2)
101    cmp     r1, #0
102    beq     1f
103    bl      flush_dcache
1041:
105    /* disable D-cache disabled. */
106    mrc     SCTLR(r1)
107    bic     r1, r1, #(1 << 2)       /* Disable D-Cache */
108    mcr     SCTLR(r1)
109
110    /* invalidate dcaches. */
111    bl      invalidate_dcache
112
113    ldmfd   sp!, {pc}
114END_FUNC(arm_disable_dcaches)
115