]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/iommu/arm-smmu-v3.c
fbd4fedd5162d1c58d6775084a0f5e356a0b0d59
[karo-tx-linux.git] / drivers / iommu / arm-smmu-v3.c
1 /*
2  * IOMMU API for ARM architected SMMUv3 implementations.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License version 2 as
6  * published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
15  *
16  * Copyright (C) 2015 ARM Limited
17  *
18  * Author: Will Deacon <will.deacon@arm.com>
19  *
20  * This driver is powered by bad coffee and bombay mix.
21  */
22
23 #include <linux/delay.h>
24 #include <linux/err.h>
25 #include <linux/interrupt.h>
26 #include <linux/iommu.h>
27 #include <linux/iopoll.h>
28 #include <linux/module.h>
29 #include <linux/of.h>
30 #include <linux/of_address.h>
31 #include <linux/pci.h>
32 #include <linux/platform_device.h>
33
34 #include "io-pgtable.h"
35
36 /* MMIO registers */
37 #define ARM_SMMU_IDR0                   0x0
38 #define IDR0_ST_LVL_SHIFT               27
39 #define IDR0_ST_LVL_MASK                0x3
40 #define IDR0_ST_LVL_2LVL                (1 << IDR0_ST_LVL_SHIFT)
41 #define IDR0_STALL_MODEL                (3 << 24)
42 #define IDR0_TTENDIAN_SHIFT             21
43 #define IDR0_TTENDIAN_MASK              0x3
44 #define IDR0_TTENDIAN_LE                (2 << IDR0_TTENDIAN_SHIFT)
45 #define IDR0_TTENDIAN_BE                (3 << IDR0_TTENDIAN_SHIFT)
46 #define IDR0_TTENDIAN_MIXED             (0 << IDR0_TTENDIAN_SHIFT)
47 #define IDR0_CD2L                       (1 << 19)
48 #define IDR0_VMID16                     (1 << 18)
49 #define IDR0_PRI                        (1 << 16)
50 #define IDR0_SEV                        (1 << 14)
51 #define IDR0_MSI                        (1 << 13)
52 #define IDR0_ASID16                     (1 << 12)
53 #define IDR0_ATS                        (1 << 10)
54 #define IDR0_HYP                        (1 << 9)
55 #define IDR0_COHACC                     (1 << 4)
56 #define IDR0_TTF_SHIFT                  2
57 #define IDR0_TTF_MASK                   0x3
58 #define IDR0_TTF_AARCH64                (2 << IDR0_TTF_SHIFT)
59 #define IDR0_S1P                        (1 << 1)
60 #define IDR0_S2P                        (1 << 0)
61
62 #define ARM_SMMU_IDR1                   0x4
63 #define IDR1_TABLES_PRESET              (1 << 30)
64 #define IDR1_QUEUES_PRESET              (1 << 29)
65 #define IDR1_REL                        (1 << 28)
66 #define IDR1_CMDQ_SHIFT                 21
67 #define IDR1_CMDQ_MASK                  0x1f
68 #define IDR1_EVTQ_SHIFT                 16
69 #define IDR1_EVTQ_MASK                  0x1f
70 #define IDR1_PRIQ_SHIFT                 11
71 #define IDR1_PRIQ_MASK                  0x1f
72 #define IDR1_SSID_SHIFT                 6
73 #define IDR1_SSID_MASK                  0x1f
74 #define IDR1_SID_SHIFT                  0
75 #define IDR1_SID_MASK                   0x3f
76
77 #define ARM_SMMU_IDR5                   0x14
78 #define IDR5_STALL_MAX_SHIFT            16
79 #define IDR5_STALL_MAX_MASK             0xffff
80 #define IDR5_GRAN64K                    (1 << 6)
81 #define IDR5_GRAN16K                    (1 << 5)
82 #define IDR5_GRAN4K                     (1 << 4)
83 #define IDR5_OAS_SHIFT                  0
84 #define IDR5_OAS_MASK                   0x7
85 #define IDR5_OAS_32_BIT                 (0 << IDR5_OAS_SHIFT)
86 #define IDR5_OAS_36_BIT                 (1 << IDR5_OAS_SHIFT)
87 #define IDR5_OAS_40_BIT                 (2 << IDR5_OAS_SHIFT)
88 #define IDR5_OAS_42_BIT                 (3 << IDR5_OAS_SHIFT)
89 #define IDR5_OAS_44_BIT                 (4 << IDR5_OAS_SHIFT)
90 #define IDR5_OAS_48_BIT                 (5 << IDR5_OAS_SHIFT)
91
92 #define ARM_SMMU_CR0                    0x20
93 #define CR0_CMDQEN                      (1 << 3)
94 #define CR0_EVTQEN                      (1 << 2)
95 #define CR0_PRIQEN                      (1 << 1)
96 #define CR0_SMMUEN                      (1 << 0)
97
98 #define ARM_SMMU_CR0ACK                 0x24
99
100 #define ARM_SMMU_CR1                    0x28
101 #define CR1_SH_NSH                      0
102 #define CR1_SH_OSH                      2
103 #define CR1_SH_ISH                      3
104 #define CR1_CACHE_NC                    0
105 #define CR1_CACHE_WB                    1
106 #define CR1_CACHE_WT                    2
107 #define CR1_TABLE_SH_SHIFT              10
108 #define CR1_TABLE_OC_SHIFT              8
109 #define CR1_TABLE_IC_SHIFT              6
110 #define CR1_QUEUE_SH_SHIFT              4
111 #define CR1_QUEUE_OC_SHIFT              2
112 #define CR1_QUEUE_IC_SHIFT              0
113
114 #define ARM_SMMU_CR2                    0x2c
115 #define CR2_PTM                         (1 << 2)
116 #define CR2_RECINVSID                   (1 << 1)
117 #define CR2_E2H                         (1 << 0)
118
119 #define ARM_SMMU_IRQ_CTRL               0x50
120 #define IRQ_CTRL_EVTQ_IRQEN             (1 << 2)
121 #define IRQ_CTRL_PRIQ_IRQEN             (1 << 1)
122 #define IRQ_CTRL_GERROR_IRQEN           (1 << 0)
123
124 #define ARM_SMMU_IRQ_CTRLACK            0x54
125
126 #define ARM_SMMU_GERROR                 0x60
127 #define GERROR_SFM_ERR                  (1 << 8)
128 #define GERROR_MSI_GERROR_ABT_ERR       (1 << 7)
129 #define GERROR_MSI_PRIQ_ABT_ERR         (1 << 6)
130 #define GERROR_MSI_EVTQ_ABT_ERR         (1 << 5)
131 #define GERROR_MSI_CMDQ_ABT_ERR         (1 << 4)
132 #define GERROR_PRIQ_ABT_ERR             (1 << 3)
133 #define GERROR_EVTQ_ABT_ERR             (1 << 2)
134 #define GERROR_CMDQ_ERR                 (1 << 0)
135 #define GERROR_ERR_MASK                 0xfd
136
137 #define ARM_SMMU_GERRORN                0x64
138
139 #define ARM_SMMU_GERROR_IRQ_CFG0        0x68
140 #define ARM_SMMU_GERROR_IRQ_CFG1        0x70
141 #define ARM_SMMU_GERROR_IRQ_CFG2        0x74
142
143 #define ARM_SMMU_STRTAB_BASE            0x80
144 #define STRTAB_BASE_RA                  (1UL << 62)
145 #define STRTAB_BASE_ADDR_SHIFT          6
146 #define STRTAB_BASE_ADDR_MASK           0x3ffffffffffUL
147
148 #define ARM_SMMU_STRTAB_BASE_CFG        0x88
149 #define STRTAB_BASE_CFG_LOG2SIZE_SHIFT  0
150 #define STRTAB_BASE_CFG_LOG2SIZE_MASK   0x3f
151 #define STRTAB_BASE_CFG_SPLIT_SHIFT     6
152 #define STRTAB_BASE_CFG_SPLIT_MASK      0x1f
153 #define STRTAB_BASE_CFG_FMT_SHIFT       16
154 #define STRTAB_BASE_CFG_FMT_MASK        0x3
155 #define STRTAB_BASE_CFG_FMT_LINEAR      (0 << STRTAB_BASE_CFG_FMT_SHIFT)
156 #define STRTAB_BASE_CFG_FMT_2LVL        (1 << STRTAB_BASE_CFG_FMT_SHIFT)
157
158 #define ARM_SMMU_CMDQ_BASE              0x90
159 #define ARM_SMMU_CMDQ_PROD              0x98
160 #define ARM_SMMU_CMDQ_CONS              0x9c
161
162 #define ARM_SMMU_EVTQ_BASE              0xa0
163 #define ARM_SMMU_EVTQ_PROD              0x100a8
164 #define ARM_SMMU_EVTQ_CONS              0x100ac
165 #define ARM_SMMU_EVTQ_IRQ_CFG0          0xb0
166 #define ARM_SMMU_EVTQ_IRQ_CFG1          0xb8
167 #define ARM_SMMU_EVTQ_IRQ_CFG2          0xbc
168
169 #define ARM_SMMU_PRIQ_BASE              0xc0
170 #define ARM_SMMU_PRIQ_PROD              0x100c8
171 #define ARM_SMMU_PRIQ_CONS              0x100cc
172 #define ARM_SMMU_PRIQ_IRQ_CFG0          0xd0
173 #define ARM_SMMU_PRIQ_IRQ_CFG1          0xd8
174 #define ARM_SMMU_PRIQ_IRQ_CFG2          0xdc
175
176 /* Common MSI config fields */
177 #define MSI_CFG0_ADDR_SHIFT             2
178 #define MSI_CFG0_ADDR_MASK              0x3fffffffffffUL
179 #define MSI_CFG2_SH_SHIFT               4
180 #define MSI_CFG2_SH_NSH                 (0UL << MSI_CFG2_SH_SHIFT)
181 #define MSI_CFG2_SH_OSH                 (2UL << MSI_CFG2_SH_SHIFT)
182 #define MSI_CFG2_SH_ISH                 (3UL << MSI_CFG2_SH_SHIFT)
183 #define MSI_CFG2_MEMATTR_SHIFT          0
184 #define MSI_CFG2_MEMATTR_DEVICE_nGnRE   (0x1 << MSI_CFG2_MEMATTR_SHIFT)
185
186 #define Q_IDX(q, p)                     ((p) & ((1 << (q)->max_n_shift) - 1))
187 #define Q_WRP(q, p)                     ((p) & (1 << (q)->max_n_shift))
188 #define Q_OVERFLOW_FLAG                 (1 << 31)
189 #define Q_OVF(q, p)                     ((p) & Q_OVERFLOW_FLAG)
190 #define Q_ENT(q, p)                     ((q)->base +                    \
191                                          Q_IDX(q, p) * (q)->ent_dwords)
192
193 #define Q_BASE_RWA                      (1UL << 62)
194 #define Q_BASE_ADDR_SHIFT               5
195 #define Q_BASE_ADDR_MASK                0xfffffffffffUL
196 #define Q_BASE_LOG2SIZE_SHIFT           0
197 #define Q_BASE_LOG2SIZE_MASK            0x1fUL
198
199 /*
200  * Stream table.
201  *
202  * Linear: Enough to cover 1 << IDR1.SIDSIZE entries
203  * 2lvl: 128k L1 entries,
204  *       256 lazy entries per table (each table covers a PCI bus)
205  */
206 #define STRTAB_L1_SZ_SHIFT              20
207 #define STRTAB_SPLIT                    8
208
209 #define STRTAB_L1_DESC_DWORDS           1
210 #define STRTAB_L1_DESC_SPAN_SHIFT       0
211 #define STRTAB_L1_DESC_SPAN_MASK        0x1fUL
212 #define STRTAB_L1_DESC_L2PTR_SHIFT      6
213 #define STRTAB_L1_DESC_L2PTR_MASK       0x3ffffffffffUL
214
215 #define STRTAB_STE_DWORDS               8
216 #define STRTAB_STE_0_V                  (1UL << 0)
217 #define STRTAB_STE_0_CFG_SHIFT          1
218 #define STRTAB_STE_0_CFG_MASK           0x7UL
219 #define STRTAB_STE_0_CFG_ABORT          (0UL << STRTAB_STE_0_CFG_SHIFT)
220 #define STRTAB_STE_0_CFG_BYPASS         (4UL << STRTAB_STE_0_CFG_SHIFT)
221 #define STRTAB_STE_0_CFG_S1_TRANS       (5UL << STRTAB_STE_0_CFG_SHIFT)
222 #define STRTAB_STE_0_CFG_S2_TRANS       (6UL << STRTAB_STE_0_CFG_SHIFT)
223
224 #define STRTAB_STE_0_S1FMT_SHIFT        4
225 #define STRTAB_STE_0_S1FMT_LINEAR       (0UL << STRTAB_STE_0_S1FMT_SHIFT)
226 #define STRTAB_STE_0_S1CTXPTR_SHIFT     6
227 #define STRTAB_STE_0_S1CTXPTR_MASK      0x3ffffffffffUL
228 #define STRTAB_STE_0_S1CDMAX_SHIFT      59
229 #define STRTAB_STE_0_S1CDMAX_MASK       0x1fUL
230
231 #define STRTAB_STE_1_S1C_CACHE_NC       0UL
232 #define STRTAB_STE_1_S1C_CACHE_WBRA     1UL
233 #define STRTAB_STE_1_S1C_CACHE_WT       2UL
234 #define STRTAB_STE_1_S1C_CACHE_WB       3UL
235 #define STRTAB_STE_1_S1C_SH_NSH         0UL
236 #define STRTAB_STE_1_S1C_SH_OSH         2UL
237 #define STRTAB_STE_1_S1C_SH_ISH         3UL
238 #define STRTAB_STE_1_S1CIR_SHIFT        2
239 #define STRTAB_STE_1_S1COR_SHIFT        4
240 #define STRTAB_STE_1_S1CSH_SHIFT        6
241
242 #define STRTAB_STE_1_S1STALLD           (1UL << 27)
243
244 #define STRTAB_STE_1_EATS_ABT           0UL
245 #define STRTAB_STE_1_EATS_TRANS         1UL
246 #define STRTAB_STE_1_EATS_S1CHK         2UL
247 #define STRTAB_STE_1_EATS_SHIFT         28
248
249 #define STRTAB_STE_1_STRW_NSEL1         0UL
250 #define STRTAB_STE_1_STRW_EL2           2UL
251 #define STRTAB_STE_1_STRW_SHIFT         30
252
253 #define STRTAB_STE_2_S2VMID_SHIFT       0
254 #define STRTAB_STE_2_S2VMID_MASK        0xffffUL
255 #define STRTAB_STE_2_VTCR_SHIFT         32
256 #define STRTAB_STE_2_VTCR_MASK          0x7ffffUL
257 #define STRTAB_STE_2_S2AA64             (1UL << 51)
258 #define STRTAB_STE_2_S2ENDI             (1UL << 52)
259 #define STRTAB_STE_2_S2PTW              (1UL << 54)
260 #define STRTAB_STE_2_S2R                (1UL << 58)
261
262 #define STRTAB_STE_3_S2TTB_SHIFT        4
263 #define STRTAB_STE_3_S2TTB_MASK         0xfffffffffffUL
264
265 /* Context descriptor (stage-1 only) */
266 #define CTXDESC_CD_DWORDS               8
267 #define CTXDESC_CD_0_TCR_T0SZ_SHIFT     0
268 #define ARM64_TCR_T0SZ_SHIFT            0
269 #define ARM64_TCR_T0SZ_MASK             0x1fUL
270 #define CTXDESC_CD_0_TCR_TG0_SHIFT      6
271 #define ARM64_TCR_TG0_SHIFT             14
272 #define ARM64_TCR_TG0_MASK              0x3UL
273 #define CTXDESC_CD_0_TCR_IRGN0_SHIFT    8
274 #define ARM64_TCR_IRGN0_SHIFT           8
275 #define ARM64_TCR_IRGN0_MASK            0x3UL
276 #define CTXDESC_CD_0_TCR_ORGN0_SHIFT    10
277 #define ARM64_TCR_ORGN0_SHIFT           10
278 #define ARM64_TCR_ORGN0_MASK            0x3UL
279 #define CTXDESC_CD_0_TCR_SH0_SHIFT      12
280 #define ARM64_TCR_SH0_SHIFT             12
281 #define ARM64_TCR_SH0_MASK              0x3UL
282 #define CTXDESC_CD_0_TCR_EPD0_SHIFT     14
283 #define ARM64_TCR_EPD0_SHIFT            7
284 #define ARM64_TCR_EPD0_MASK             0x1UL
285 #define CTXDESC_CD_0_TCR_EPD1_SHIFT     30
286 #define ARM64_TCR_EPD1_SHIFT            23
287 #define ARM64_TCR_EPD1_MASK             0x1UL
288
289 #define CTXDESC_CD_0_ENDI               (1UL << 15)
290 #define CTXDESC_CD_0_V                  (1UL << 31)
291
292 #define CTXDESC_CD_0_TCR_IPS_SHIFT      32
293 #define ARM64_TCR_IPS_SHIFT             32
294 #define ARM64_TCR_IPS_MASK              0x7UL
295 #define CTXDESC_CD_0_TCR_TBI0_SHIFT     38
296 #define ARM64_TCR_TBI0_SHIFT            37
297 #define ARM64_TCR_TBI0_MASK             0x1UL
298
299 #define CTXDESC_CD_0_AA64               (1UL << 41)
300 #define CTXDESC_CD_0_R                  (1UL << 45)
301 #define CTXDESC_CD_0_A                  (1UL << 46)
302 #define CTXDESC_CD_0_ASET_SHIFT         47
303 #define CTXDESC_CD_0_ASET_SHARED        (0UL << CTXDESC_CD_0_ASET_SHIFT)
304 #define CTXDESC_CD_0_ASET_PRIVATE       (1UL << CTXDESC_CD_0_ASET_SHIFT)
305 #define CTXDESC_CD_0_ASID_SHIFT         48
306 #define CTXDESC_CD_0_ASID_MASK          0xffffUL
307
308 #define CTXDESC_CD_1_TTB0_SHIFT         4
309 #define CTXDESC_CD_1_TTB0_MASK          0xfffffffffffUL
310
311 #define CTXDESC_CD_3_MAIR_SHIFT         0
312
313 /* Convert between AArch64 (CPU) TCR format and SMMU CD format */
314 #define ARM_SMMU_TCR2CD(tcr, fld)                                       \
315         (((tcr) >> ARM64_TCR_##fld##_SHIFT & ARM64_TCR_##fld##_MASK)    \
316          << CTXDESC_CD_0_TCR_##fld##_SHIFT)
317
318 /* Command queue */
319 #define CMDQ_ENT_DWORDS                 2
320 #define CMDQ_MAX_SZ_SHIFT               8
321
322 #define CMDQ_ERR_SHIFT                  24
323 #define CMDQ_ERR_MASK                   0x7f
324 #define CMDQ_ERR_CERROR_NONE_IDX        0
325 #define CMDQ_ERR_CERROR_ILL_IDX         1
326 #define CMDQ_ERR_CERROR_ABT_IDX         2
327
328 #define CMDQ_0_OP_SHIFT                 0
329 #define CMDQ_0_OP_MASK                  0xffUL
330 #define CMDQ_0_SSV                      (1UL << 11)
331
332 #define CMDQ_PREFETCH_0_SID_SHIFT       32
333 #define CMDQ_PREFETCH_1_SIZE_SHIFT      0
334 #define CMDQ_PREFETCH_1_ADDR_MASK       ~0xfffUL
335
336 #define CMDQ_CFGI_0_SID_SHIFT           32
337 #define CMDQ_CFGI_0_SID_MASK            0xffffffffUL
338 #define CMDQ_CFGI_1_LEAF                (1UL << 0)
339 #define CMDQ_CFGI_1_RANGE_SHIFT         0
340 #define CMDQ_CFGI_1_RANGE_MASK          0x1fUL
341
342 #define CMDQ_TLBI_0_VMID_SHIFT          32
343 #define CMDQ_TLBI_0_ASID_SHIFT          48
344 #define CMDQ_TLBI_1_LEAF                (1UL << 0)
345 #define CMDQ_TLBI_1_ADDR_MASK           ~0xfffUL
346
347 #define CMDQ_PRI_0_SSID_SHIFT           12
348 #define CMDQ_PRI_0_SSID_MASK            0xfffffUL
349 #define CMDQ_PRI_0_SID_SHIFT            32
350 #define CMDQ_PRI_0_SID_MASK             0xffffffffUL
351 #define CMDQ_PRI_1_GRPID_SHIFT          0
352 #define CMDQ_PRI_1_GRPID_MASK           0x1ffUL
353 #define CMDQ_PRI_1_RESP_SHIFT           12
354 #define CMDQ_PRI_1_RESP_DENY            (0UL << CMDQ_PRI_1_RESP_SHIFT)
355 #define CMDQ_PRI_1_RESP_FAIL            (1UL << CMDQ_PRI_1_RESP_SHIFT)
356 #define CMDQ_PRI_1_RESP_SUCC            (2UL << CMDQ_PRI_1_RESP_SHIFT)
357
358 #define CMDQ_SYNC_0_CS_SHIFT            12
359 #define CMDQ_SYNC_0_CS_NONE             (0UL << CMDQ_SYNC_0_CS_SHIFT)
360 #define CMDQ_SYNC_0_CS_SEV              (2UL << CMDQ_SYNC_0_CS_SHIFT)
361
362 /* Event queue */
363 #define EVTQ_ENT_DWORDS                 4
364 #define EVTQ_MAX_SZ_SHIFT               7
365
366 #define EVTQ_0_ID_SHIFT                 0
367 #define EVTQ_0_ID_MASK                  0xffUL
368
369 /* PRI queue */
370 #define PRIQ_ENT_DWORDS                 2
371 #define PRIQ_MAX_SZ_SHIFT               8
372
373 #define PRIQ_0_SID_SHIFT                0
374 #define PRIQ_0_SID_MASK                 0xffffffffUL
375 #define PRIQ_0_SSID_SHIFT               32
376 #define PRIQ_0_SSID_MASK                0xfffffUL
377 #define PRIQ_0_OF                       (1UL << 57)
378 #define PRIQ_0_PERM_PRIV                (1UL << 58)
379 #define PRIQ_0_PERM_EXEC                (1UL << 59)
380 #define PRIQ_0_PERM_READ                (1UL << 60)
381 #define PRIQ_0_PERM_WRITE               (1UL << 61)
382 #define PRIQ_0_PRG_LAST                 (1UL << 62)
383 #define PRIQ_0_SSID_V                   (1UL << 63)
384
385 #define PRIQ_1_PRG_IDX_SHIFT            0
386 #define PRIQ_1_PRG_IDX_MASK             0x1ffUL
387 #define PRIQ_1_ADDR_SHIFT               12
388 #define PRIQ_1_ADDR_MASK                0xfffffffffffffUL
389
390 /* High-level queue structures */
391 #define ARM_SMMU_POLL_TIMEOUT_US        100
392
393 static bool disable_bypass;
394 module_param_named(disable_bypass, disable_bypass, bool, S_IRUGO);
395 MODULE_PARM_DESC(disable_bypass,
396         "Disable bypass streams such that incoming transactions from devices that are not attached to an iommu domain will report an abort back to the device and will not be allowed to pass through the SMMU.");
397
398 enum pri_resp {
399         PRI_RESP_DENY,
400         PRI_RESP_FAIL,
401         PRI_RESP_SUCC,
402 };
403
404 struct arm_smmu_cmdq_ent {
405         /* Common fields */
406         u8                              opcode;
407         bool                            substream_valid;
408
409         /* Command-specific fields */
410         union {
411                 #define CMDQ_OP_PREFETCH_CFG    0x1
412                 struct {
413                         u32                     sid;
414                         u8                      size;
415                         u64                     addr;
416                 } prefetch;
417
418                 #define CMDQ_OP_CFGI_STE        0x3
419                 #define CMDQ_OP_CFGI_ALL        0x4
420                 struct {
421                         u32                     sid;
422                         union {
423                                 bool            leaf;
424                                 u8              span;
425                         };
426                 } cfgi;
427
428                 #define CMDQ_OP_TLBI_NH_ASID    0x11
429                 #define CMDQ_OP_TLBI_NH_VA      0x12
430                 #define CMDQ_OP_TLBI_EL2_ALL    0x20
431                 #define CMDQ_OP_TLBI_S12_VMALL  0x28
432                 #define CMDQ_OP_TLBI_S2_IPA     0x2a
433                 #define CMDQ_OP_TLBI_NSNH_ALL   0x30
434                 struct {
435                         u16                     asid;
436                         u16                     vmid;
437                         bool                    leaf;
438                         u64                     addr;
439                 } tlbi;
440
441                 #define CMDQ_OP_PRI_RESP        0x41
442                 struct {
443                         u32                     sid;
444                         u32                     ssid;
445                         u16                     grpid;
446                         enum pri_resp           resp;
447                 } pri;
448
449                 #define CMDQ_OP_CMD_SYNC        0x46
450         };
451 };
452
453 struct arm_smmu_queue {
454         int                             irq; /* Wired interrupt */
455
456         __le64                          *base;
457         dma_addr_t                      base_dma;
458         u64                             q_base;
459
460         size_t                          ent_dwords;
461         u32                             max_n_shift;
462         u32                             prod;
463         u32                             cons;
464
465         u32 __iomem                     *prod_reg;
466         u32 __iomem                     *cons_reg;
467 };
468
469 struct arm_smmu_cmdq {
470         struct arm_smmu_queue           q;
471         spinlock_t                      lock;
472 };
473
474 struct arm_smmu_evtq {
475         struct arm_smmu_queue           q;
476         u32                             max_stalls;
477 };
478
479 struct arm_smmu_priq {
480         struct arm_smmu_queue           q;
481 };
482
483 /* High-level stream table and context descriptor structures */
484 struct arm_smmu_strtab_l1_desc {
485         u8                              span;
486
487         __le64                          *l2ptr;
488         dma_addr_t                      l2ptr_dma;
489 };
490
491 struct arm_smmu_s1_cfg {
492         __le64                          *cdptr;
493         dma_addr_t                      cdptr_dma;
494
495         struct arm_smmu_ctx_desc {
496                 u16     asid;
497                 u64     ttbr;
498                 u64     tcr;
499                 u64     mair;
500         }                               cd;
501 };
502
503 struct arm_smmu_s2_cfg {
504         u16                             vmid;
505         u64                             vttbr;
506         u64                             vtcr;
507 };
508
509 struct arm_smmu_strtab_ent {
510         bool                            valid;
511
512         bool                            bypass; /* Overrides s1/s2 config */
513         struct arm_smmu_s1_cfg          *s1_cfg;
514         struct arm_smmu_s2_cfg          *s2_cfg;
515 };
516
517 struct arm_smmu_strtab_cfg {
518         __le64                          *strtab;
519         dma_addr_t                      strtab_dma;
520         struct arm_smmu_strtab_l1_desc  *l1_desc;
521         unsigned int                    num_l1_ents;
522
523         u64                             strtab_base;
524         u32                             strtab_base_cfg;
525 };
526
527 /* An SMMUv3 instance */
528 struct arm_smmu_device {
529         struct device                   *dev;
530         void __iomem                    *base;
531
532 #define ARM_SMMU_FEAT_2_LVL_STRTAB      (1 << 0)
533 #define ARM_SMMU_FEAT_2_LVL_CDTAB       (1 << 1)
534 #define ARM_SMMU_FEAT_TT_LE             (1 << 2)
535 #define ARM_SMMU_FEAT_TT_BE             (1 << 3)
536 #define ARM_SMMU_FEAT_PRI               (1 << 4)
537 #define ARM_SMMU_FEAT_ATS               (1 << 5)
538 #define ARM_SMMU_FEAT_SEV               (1 << 6)
539 #define ARM_SMMU_FEAT_MSI               (1 << 7)
540 #define ARM_SMMU_FEAT_COHERENCY         (1 << 8)
541 #define ARM_SMMU_FEAT_TRANS_S1          (1 << 9)
542 #define ARM_SMMU_FEAT_TRANS_S2          (1 << 10)
543 #define ARM_SMMU_FEAT_STALLS            (1 << 11)
544 #define ARM_SMMU_FEAT_HYP               (1 << 12)
545         u32                             features;
546
547 #define ARM_SMMU_OPT_SKIP_PREFETCH      (1 << 0)
548         u32                             options;
549
550         struct arm_smmu_cmdq            cmdq;
551         struct arm_smmu_evtq            evtq;
552         struct arm_smmu_priq            priq;
553
554         int                             gerr_irq;
555
556         unsigned long                   ias; /* IPA */
557         unsigned long                   oas; /* PA */
558
559 #define ARM_SMMU_MAX_ASIDS              (1 << 16)
560         unsigned int                    asid_bits;
561         DECLARE_BITMAP(asid_map, ARM_SMMU_MAX_ASIDS);
562
563 #define ARM_SMMU_MAX_VMIDS              (1 << 16)
564         unsigned int                    vmid_bits;
565         DECLARE_BITMAP(vmid_map, ARM_SMMU_MAX_VMIDS);
566
567         unsigned int                    ssid_bits;
568         unsigned int                    sid_bits;
569
570         struct arm_smmu_strtab_cfg      strtab_cfg;
571         struct list_head                list;
572 };
573
574 /* SMMU private data for an IOMMU group */
575 struct arm_smmu_group {
576         struct arm_smmu_device          *smmu;
577         struct arm_smmu_domain          *domain;
578         int                             num_sids;
579         u32                             *sids;
580         struct arm_smmu_strtab_ent      ste;
581 };
582
583 /* SMMU private data for an IOMMU domain */
584 enum arm_smmu_domain_stage {
585         ARM_SMMU_DOMAIN_S1 = 0,
586         ARM_SMMU_DOMAIN_S2,
587         ARM_SMMU_DOMAIN_NESTED,
588 };
589
590 struct arm_smmu_domain {
591         struct arm_smmu_device          *smmu;
592         struct mutex                    init_mutex; /* Protects smmu pointer */
593
594         struct io_pgtable_ops           *pgtbl_ops;
595         spinlock_t                      pgtbl_lock;
596
597         enum arm_smmu_domain_stage      stage;
598         union {
599                 struct arm_smmu_s1_cfg  s1_cfg;
600                 struct arm_smmu_s2_cfg  s2_cfg;
601         };
602
603         struct iommu_domain             domain;
604 };
605
606 /* Our list of SMMU instances */
607 static DEFINE_SPINLOCK(arm_smmu_devices_lock);
608 static LIST_HEAD(arm_smmu_devices);
609
610 struct arm_smmu_option_prop {
611         u32 opt;
612         const char *prop;
613 };
614
615 static struct arm_smmu_option_prop arm_smmu_options[] = {
616         { ARM_SMMU_OPT_SKIP_PREFETCH, "hisilicon,broken-prefetch-cmd" },
617         { 0, NULL},
618 };
619
620 static struct arm_smmu_domain *to_smmu_domain(struct iommu_domain *dom)
621 {
622         return container_of(dom, struct arm_smmu_domain, domain);
623 }
624
625 static void parse_driver_options(struct arm_smmu_device *smmu)
626 {
627         int i = 0;
628
629         do {
630                 if (of_property_read_bool(smmu->dev->of_node,
631                                                 arm_smmu_options[i].prop)) {
632                         smmu->options |= arm_smmu_options[i].opt;
633                         dev_notice(smmu->dev, "option %s\n",
634                                 arm_smmu_options[i].prop);
635                 }
636         } while (arm_smmu_options[++i].opt);
637 }
638
639 /* Low-level queue manipulation functions */
640 static bool queue_full(struct arm_smmu_queue *q)
641 {
642         return Q_IDX(q, q->prod) == Q_IDX(q, q->cons) &&
643                Q_WRP(q, q->prod) != Q_WRP(q, q->cons);
644 }
645
646 static bool queue_empty(struct arm_smmu_queue *q)
647 {
648         return Q_IDX(q, q->prod) == Q_IDX(q, q->cons) &&
649                Q_WRP(q, q->prod) == Q_WRP(q, q->cons);
650 }
651
652 static void queue_sync_cons(struct arm_smmu_queue *q)
653 {
654         q->cons = readl_relaxed(q->cons_reg);
655 }
656
657 static void queue_inc_cons(struct arm_smmu_queue *q)
658 {
659         u32 cons = (Q_WRP(q, q->cons) | Q_IDX(q, q->cons)) + 1;
660
661         q->cons = Q_OVF(q, q->cons) | Q_WRP(q, cons) | Q_IDX(q, cons);
662         writel(q->cons, q->cons_reg);
663 }
664
665 static int queue_sync_prod(struct arm_smmu_queue *q)
666 {
667         int ret = 0;
668         u32 prod = readl_relaxed(q->prod_reg);
669
670         if (Q_OVF(q, prod) != Q_OVF(q, q->prod))
671                 ret = -EOVERFLOW;
672
673         q->prod = prod;
674         return ret;
675 }
676
677 static void queue_inc_prod(struct arm_smmu_queue *q)
678 {
679         u32 prod = (Q_WRP(q, q->prod) | Q_IDX(q, q->prod)) + 1;
680
681         q->prod = Q_OVF(q, q->prod) | Q_WRP(q, prod) | Q_IDX(q, prod);
682         writel(q->prod, q->prod_reg);
683 }
684
685 static bool __queue_cons_before(struct arm_smmu_queue *q, u32 until)
686 {
687         if (Q_WRP(q, q->cons) == Q_WRP(q, until))
688                 return Q_IDX(q, q->cons) < Q_IDX(q, until);
689
690         return Q_IDX(q, q->cons) >= Q_IDX(q, until);
691 }
692
693 static int queue_poll_cons(struct arm_smmu_queue *q, u32 until, bool wfe)
694 {
695         ktime_t timeout = ktime_add_us(ktime_get(), ARM_SMMU_POLL_TIMEOUT_US);
696
697         while (queue_sync_cons(q), __queue_cons_before(q, until)) {
698                 if (ktime_compare(ktime_get(), timeout) > 0)
699                         return -ETIMEDOUT;
700
701                 if (wfe) {
702                         wfe();
703                 } else {
704                         cpu_relax();
705                         udelay(1);
706                 }
707         }
708
709         return 0;
710 }
711
712 static void queue_write(__le64 *dst, u64 *src, size_t n_dwords)
713 {
714         int i;
715
716         for (i = 0; i < n_dwords; ++i)
717                 *dst++ = cpu_to_le64(*src++);
718 }
719
720 static int queue_insert_raw(struct arm_smmu_queue *q, u64 *ent)
721 {
722         if (queue_full(q))
723                 return -ENOSPC;
724
725         queue_write(Q_ENT(q, q->prod), ent, q->ent_dwords);
726         queue_inc_prod(q);
727         return 0;
728 }
729
730 static void queue_read(__le64 *dst, u64 *src, size_t n_dwords)
731 {
732         int i;
733
734         for (i = 0; i < n_dwords; ++i)
735                 *dst++ = le64_to_cpu(*src++);
736 }
737
738 static int queue_remove_raw(struct arm_smmu_queue *q, u64 *ent)
739 {
740         if (queue_empty(q))
741                 return -EAGAIN;
742
743         queue_read(ent, Q_ENT(q, q->cons), q->ent_dwords);
744         queue_inc_cons(q);
745         return 0;
746 }
747
748 /* High-level queue accessors */
749 static int arm_smmu_cmdq_build_cmd(u64 *cmd, struct arm_smmu_cmdq_ent *ent)
750 {
751         memset(cmd, 0, CMDQ_ENT_DWORDS << 3);
752         cmd[0] |= (ent->opcode & CMDQ_0_OP_MASK) << CMDQ_0_OP_SHIFT;
753
754         switch (ent->opcode) {
755         case CMDQ_OP_TLBI_EL2_ALL:
756         case CMDQ_OP_TLBI_NSNH_ALL:
757                 break;
758         case CMDQ_OP_PREFETCH_CFG:
759                 cmd[0] |= (u64)ent->prefetch.sid << CMDQ_PREFETCH_0_SID_SHIFT;
760                 cmd[1] |= ent->prefetch.size << CMDQ_PREFETCH_1_SIZE_SHIFT;
761                 cmd[1] |= ent->prefetch.addr & CMDQ_PREFETCH_1_ADDR_MASK;
762                 break;
763         case CMDQ_OP_CFGI_STE:
764                 cmd[0] |= (u64)ent->cfgi.sid << CMDQ_CFGI_0_SID_SHIFT;
765                 cmd[1] |= ent->cfgi.leaf ? CMDQ_CFGI_1_LEAF : 0;
766                 break;
767         case CMDQ_OP_CFGI_ALL:
768                 /* Cover the entire SID range */
769                 cmd[1] |= CMDQ_CFGI_1_RANGE_MASK << CMDQ_CFGI_1_RANGE_SHIFT;
770                 break;
771         case CMDQ_OP_TLBI_NH_VA:
772                 cmd[0] |= (u64)ent->tlbi.asid << CMDQ_TLBI_0_ASID_SHIFT;
773                 /* Fallthrough */
774         case CMDQ_OP_TLBI_S2_IPA:
775                 cmd[0] |= (u64)ent->tlbi.vmid << CMDQ_TLBI_0_VMID_SHIFT;
776                 cmd[1] |= ent->tlbi.leaf ? CMDQ_TLBI_1_LEAF : 0;
777                 cmd[1] |= ent->tlbi.addr & CMDQ_TLBI_1_ADDR_MASK;
778                 break;
779         case CMDQ_OP_TLBI_NH_ASID:
780                 cmd[0] |= (u64)ent->tlbi.asid << CMDQ_TLBI_0_ASID_SHIFT;
781                 /* Fallthrough */
782         case CMDQ_OP_TLBI_S12_VMALL:
783                 cmd[0] |= (u64)ent->tlbi.vmid << CMDQ_TLBI_0_VMID_SHIFT;
784                 break;
785         case CMDQ_OP_PRI_RESP:
786                 cmd[0] |= ent->substream_valid ? CMDQ_0_SSV : 0;
787                 cmd[0] |= ent->pri.ssid << CMDQ_PRI_0_SSID_SHIFT;
788                 cmd[0] |= (u64)ent->pri.sid << CMDQ_PRI_0_SID_SHIFT;
789                 cmd[1] |= ent->pri.grpid << CMDQ_PRI_1_GRPID_SHIFT;
790                 switch (ent->pri.resp) {
791                 case PRI_RESP_DENY:
792                         cmd[1] |= CMDQ_PRI_1_RESP_DENY;
793                         break;
794                 case PRI_RESP_FAIL:
795                         cmd[1] |= CMDQ_PRI_1_RESP_FAIL;
796                         break;
797                 case PRI_RESP_SUCC:
798                         cmd[1] |= CMDQ_PRI_1_RESP_SUCC;
799                         break;
800                 default:
801                         return -EINVAL;
802                 }
803                 break;
804         case CMDQ_OP_CMD_SYNC:
805                 cmd[0] |= CMDQ_SYNC_0_CS_SEV;
806                 break;
807         default:
808                 return -ENOENT;
809         }
810
811         return 0;
812 }
813
814 static void arm_smmu_cmdq_skip_err(struct arm_smmu_device *smmu)
815 {
816         static const char *cerror_str[] = {
817                 [CMDQ_ERR_CERROR_NONE_IDX]      = "No error",
818                 [CMDQ_ERR_CERROR_ILL_IDX]       = "Illegal command",
819                 [CMDQ_ERR_CERROR_ABT_IDX]       = "Abort on command fetch",
820         };
821
822         int i;
823         u64 cmd[CMDQ_ENT_DWORDS];
824         struct arm_smmu_queue *q = &smmu->cmdq.q;
825         u32 cons = readl_relaxed(q->cons_reg);
826         u32 idx = cons >> CMDQ_ERR_SHIFT & CMDQ_ERR_MASK;
827         struct arm_smmu_cmdq_ent cmd_sync = {
828                 .opcode = CMDQ_OP_CMD_SYNC,
829         };
830
831         dev_err(smmu->dev, "CMDQ error (cons 0x%08x): %s\n", cons,
832                 cerror_str[idx]);
833
834         switch (idx) {
835         case CMDQ_ERR_CERROR_ILL_IDX:
836                 break;
837         case CMDQ_ERR_CERROR_ABT_IDX:
838                 dev_err(smmu->dev, "retrying command fetch\n");
839         case CMDQ_ERR_CERROR_NONE_IDX:
840                 return;
841         }
842
843         /*
844          * We may have concurrent producers, so we need to be careful
845          * not to touch any of the shadow cmdq state.
846          */
847         queue_read(cmd, Q_ENT(q, idx), q->ent_dwords);
848         dev_err(smmu->dev, "skipping command in error state:\n");
849         for (i = 0; i < ARRAY_SIZE(cmd); ++i)
850                 dev_err(smmu->dev, "\t0x%016llx\n", (unsigned long long)cmd[i]);
851
852         /* Convert the erroneous command into a CMD_SYNC */
853         if (arm_smmu_cmdq_build_cmd(cmd, &cmd_sync)) {
854                 dev_err(smmu->dev, "failed to convert to CMD_SYNC\n");
855                 return;
856         }
857
858         queue_write(cmd, Q_ENT(q, idx), q->ent_dwords);
859 }
860
861 static void arm_smmu_cmdq_issue_cmd(struct arm_smmu_device *smmu,
862                                     struct arm_smmu_cmdq_ent *ent)
863 {
864         u32 until;
865         u64 cmd[CMDQ_ENT_DWORDS];
866         bool wfe = !!(smmu->features & ARM_SMMU_FEAT_SEV);
867         struct arm_smmu_queue *q = &smmu->cmdq.q;
868
869         if (arm_smmu_cmdq_build_cmd(cmd, ent)) {
870                 dev_warn(smmu->dev, "ignoring unknown CMDQ opcode 0x%x\n",
871                          ent->opcode);
872                 return;
873         }
874
875         spin_lock(&smmu->cmdq.lock);
876         while (until = q->prod + 1, queue_insert_raw(q, cmd) == -ENOSPC) {
877                 /*
878                  * Keep the queue locked, otherwise the producer could wrap
879                  * twice and we could see a future consumer pointer that looks
880                  * like it's behind us.
881                  */
882                 if (queue_poll_cons(q, until, wfe))
883                         dev_err_ratelimited(smmu->dev, "CMDQ timeout\n");
884         }
885
886         if (ent->opcode == CMDQ_OP_CMD_SYNC && queue_poll_cons(q, until, wfe))
887                 dev_err_ratelimited(smmu->dev, "CMD_SYNC timeout\n");
888         spin_unlock(&smmu->cmdq.lock);
889 }
890
891 /* Context descriptor manipulation functions */
892 static u64 arm_smmu_cpu_tcr_to_cd(u64 tcr)
893 {
894         u64 val = 0;
895
896         /* Repack the TCR. Just care about TTBR0 for now */
897         val |= ARM_SMMU_TCR2CD(tcr, T0SZ);
898         val |= ARM_SMMU_TCR2CD(tcr, TG0);
899         val |= ARM_SMMU_TCR2CD(tcr, IRGN0);
900         val |= ARM_SMMU_TCR2CD(tcr, ORGN0);
901         val |= ARM_SMMU_TCR2CD(tcr, SH0);
902         val |= ARM_SMMU_TCR2CD(tcr, EPD0);
903         val |= ARM_SMMU_TCR2CD(tcr, EPD1);
904         val |= ARM_SMMU_TCR2CD(tcr, IPS);
905         val |= ARM_SMMU_TCR2CD(tcr, TBI0);
906
907         return val;
908 }
909
910 static void arm_smmu_write_ctx_desc(struct arm_smmu_device *smmu,
911                                     struct arm_smmu_s1_cfg *cfg)
912 {
913         u64 val;
914
915         /*
916          * We don't need to issue any invalidation here, as we'll invalidate
917          * the STE when installing the new entry anyway.
918          */
919         val = arm_smmu_cpu_tcr_to_cd(cfg->cd.tcr) |
920 #ifdef __BIG_ENDIAN
921               CTXDESC_CD_0_ENDI |
922 #endif
923               CTXDESC_CD_0_R | CTXDESC_CD_0_A | CTXDESC_CD_0_ASET_PRIVATE |
924               CTXDESC_CD_0_AA64 | (u64)cfg->cd.asid << CTXDESC_CD_0_ASID_SHIFT |
925               CTXDESC_CD_0_V;
926         cfg->cdptr[0] = cpu_to_le64(val);
927
928         val = cfg->cd.ttbr & CTXDESC_CD_1_TTB0_MASK << CTXDESC_CD_1_TTB0_SHIFT;
929         cfg->cdptr[1] = cpu_to_le64(val);
930
931         cfg->cdptr[3] = cpu_to_le64(cfg->cd.mair << CTXDESC_CD_3_MAIR_SHIFT);
932 }
933
934 /* Stream table manipulation functions */
935 static void
936 arm_smmu_write_strtab_l1_desc(__le64 *dst, struct arm_smmu_strtab_l1_desc *desc)
937 {
938         u64 val = 0;
939
940         val |= (desc->span & STRTAB_L1_DESC_SPAN_MASK)
941                 << STRTAB_L1_DESC_SPAN_SHIFT;
942         val |= desc->l2ptr_dma &
943                STRTAB_L1_DESC_L2PTR_MASK << STRTAB_L1_DESC_L2PTR_SHIFT;
944
945         *dst = cpu_to_le64(val);
946 }
947
948 static void arm_smmu_sync_ste_for_sid(struct arm_smmu_device *smmu, u32 sid)
949 {
950         struct arm_smmu_cmdq_ent cmd = {
951                 .opcode = CMDQ_OP_CFGI_STE,
952                 .cfgi   = {
953                         .sid    = sid,
954                         .leaf   = true,
955                 },
956         };
957
958         arm_smmu_cmdq_issue_cmd(smmu, &cmd);
959         cmd.opcode = CMDQ_OP_CMD_SYNC;
960         arm_smmu_cmdq_issue_cmd(smmu, &cmd);
961 }
962
963 static void arm_smmu_write_strtab_ent(struct arm_smmu_device *smmu, u32 sid,
964                                       __le64 *dst, struct arm_smmu_strtab_ent *ste)
965 {
966         /*
967          * This is hideously complicated, but we only really care about
968          * three cases at the moment:
969          *
970          * 1. Invalid (all zero) -> bypass  (init)
971          * 2. Bypass -> translation (attach)
972          * 3. Translation -> bypass (detach)
973          *
974          * Given that we can't update the STE atomically and the SMMU
975          * doesn't read the thing in a defined order, that leaves us
976          * with the following maintenance requirements:
977          *
978          * 1. Update Config, return (init time STEs aren't live)
979          * 2. Write everything apart from dword 0, sync, write dword 0, sync
980          * 3. Update Config, sync
981          */
982         u64 val = le64_to_cpu(dst[0]);
983         bool ste_live = false;
984         struct arm_smmu_cmdq_ent prefetch_cmd = {
985                 .opcode         = CMDQ_OP_PREFETCH_CFG,
986                 .prefetch       = {
987                         .sid    = sid,
988                 },
989         };
990
991         if (val & STRTAB_STE_0_V) {
992                 u64 cfg;
993
994                 cfg = val & STRTAB_STE_0_CFG_MASK << STRTAB_STE_0_CFG_SHIFT;
995                 switch (cfg) {
996                 case STRTAB_STE_0_CFG_BYPASS:
997                         break;
998                 case STRTAB_STE_0_CFG_S1_TRANS:
999                 case STRTAB_STE_0_CFG_S2_TRANS:
1000                         ste_live = true;
1001                         break;
1002                 default:
1003                         BUG(); /* STE corruption */
1004                 }
1005         }
1006
1007         /* Nuke the existing Config, as we're going to rewrite it */
1008         val &= ~(STRTAB_STE_0_CFG_MASK << STRTAB_STE_0_CFG_SHIFT);
1009
1010         if (ste->valid)
1011                 val |= STRTAB_STE_0_V;
1012         else
1013                 val &= ~STRTAB_STE_0_V;
1014
1015         if (ste->bypass) {
1016                 val |= disable_bypass ? STRTAB_STE_0_CFG_ABORT
1017                                       : STRTAB_STE_0_CFG_BYPASS;
1018                 dst[0] = cpu_to_le64(val);
1019                 dst[2] = 0; /* Nuke the VMID */
1020                 if (ste_live)
1021                         arm_smmu_sync_ste_for_sid(smmu, sid);
1022                 return;
1023         }
1024
1025         if (ste->s1_cfg) {
1026                 BUG_ON(ste_live);
1027                 dst[1] = cpu_to_le64(
1028                          STRTAB_STE_1_S1C_CACHE_WBRA
1029                          << STRTAB_STE_1_S1CIR_SHIFT |
1030                          STRTAB_STE_1_S1C_CACHE_WBRA
1031                          << STRTAB_STE_1_S1COR_SHIFT |
1032                          STRTAB_STE_1_S1C_SH_ISH << STRTAB_STE_1_S1CSH_SHIFT |
1033                          STRTAB_STE_1_S1STALLD |
1034 #ifdef CONFIG_PCI_ATS
1035                          STRTAB_STE_1_EATS_TRANS << STRTAB_STE_1_EATS_SHIFT |
1036 #endif
1037                          STRTAB_STE_1_STRW_NSEL1 << STRTAB_STE_1_STRW_SHIFT);
1038
1039                 val |= (ste->s1_cfg->cdptr_dma & STRTAB_STE_0_S1CTXPTR_MASK
1040                         << STRTAB_STE_0_S1CTXPTR_SHIFT) |
1041                         STRTAB_STE_0_CFG_S1_TRANS;
1042
1043         }
1044
1045         if (ste->s2_cfg) {
1046                 BUG_ON(ste_live);
1047                 dst[2] = cpu_to_le64(
1048                          ste->s2_cfg->vmid << STRTAB_STE_2_S2VMID_SHIFT |
1049                          (ste->s2_cfg->vtcr & STRTAB_STE_2_VTCR_MASK)
1050                           << STRTAB_STE_2_VTCR_SHIFT |
1051 #ifdef __BIG_ENDIAN
1052                          STRTAB_STE_2_S2ENDI |
1053 #endif
1054                          STRTAB_STE_2_S2PTW | STRTAB_STE_2_S2AA64 |
1055                          STRTAB_STE_2_S2R);
1056
1057                 dst[3] = cpu_to_le64(ste->s2_cfg->vttbr &
1058                          STRTAB_STE_3_S2TTB_MASK << STRTAB_STE_3_S2TTB_SHIFT);
1059
1060                 val |= STRTAB_STE_0_CFG_S2_TRANS;
1061         }
1062
1063         arm_smmu_sync_ste_for_sid(smmu, sid);
1064         dst[0] = cpu_to_le64(val);
1065         arm_smmu_sync_ste_for_sid(smmu, sid);
1066
1067         /* It's likely that we'll want to use the new STE soon */
1068         if (!(smmu->options & ARM_SMMU_OPT_SKIP_PREFETCH))
1069                 arm_smmu_cmdq_issue_cmd(smmu, &prefetch_cmd);
1070 }
1071
1072 static void arm_smmu_init_bypass_stes(u64 *strtab, unsigned int nent)
1073 {
1074         unsigned int i;
1075         struct arm_smmu_strtab_ent ste = {
1076                 .valid  = true,
1077                 .bypass = true,
1078         };
1079
1080         for (i = 0; i < nent; ++i) {
1081                 arm_smmu_write_strtab_ent(NULL, -1, strtab, &ste);
1082                 strtab += STRTAB_STE_DWORDS;
1083         }
1084 }
1085
1086 static int arm_smmu_init_l2_strtab(struct arm_smmu_device *smmu, u32 sid)
1087 {
1088         size_t size;
1089         void *strtab;
1090         struct arm_smmu_strtab_cfg *cfg = &smmu->strtab_cfg;
1091         struct arm_smmu_strtab_l1_desc *desc = &cfg->l1_desc[sid >> STRTAB_SPLIT];
1092
1093         if (desc->l2ptr)
1094                 return 0;
1095
1096         size = 1 << (STRTAB_SPLIT + ilog2(STRTAB_STE_DWORDS) + 3);
1097         strtab = &cfg->strtab[(sid >> STRTAB_SPLIT) * STRTAB_L1_DESC_DWORDS];
1098
1099         desc->span = STRTAB_SPLIT + 1;
1100         desc->l2ptr = dma_zalloc_coherent(smmu->dev, size, &desc->l2ptr_dma,
1101                                           GFP_KERNEL);
1102         if (!desc->l2ptr) {
1103                 dev_err(smmu->dev,
1104                         "failed to allocate l2 stream table for SID %u\n",
1105                         sid);
1106                 return -ENOMEM;
1107         }
1108
1109         arm_smmu_init_bypass_stes(desc->l2ptr, 1 << STRTAB_SPLIT);
1110         arm_smmu_write_strtab_l1_desc(strtab, desc);
1111         return 0;
1112 }
1113
1114 /* IRQ and event handlers */
1115 static irqreturn_t arm_smmu_evtq_thread(int irq, void *dev)
1116 {
1117         int i;
1118         struct arm_smmu_device *smmu = dev;
1119         struct arm_smmu_queue *q = &smmu->evtq.q;
1120         u64 evt[EVTQ_ENT_DWORDS];
1121
1122         while (!queue_remove_raw(q, evt)) {
1123                 u8 id = evt[0] >> EVTQ_0_ID_SHIFT & EVTQ_0_ID_MASK;
1124
1125                 dev_info(smmu->dev, "event 0x%02x received:\n", id);
1126                 for (i = 0; i < ARRAY_SIZE(evt); ++i)
1127                         dev_info(smmu->dev, "\t0x%016llx\n",
1128                                  (unsigned long long)evt[i]);
1129         }
1130
1131         /* Sync our overflow flag, as we believe we're up to speed */
1132         q->cons = Q_OVF(q, q->prod) | Q_WRP(q, q->cons) | Q_IDX(q, q->cons);
1133         return IRQ_HANDLED;
1134 }
1135
1136 static irqreturn_t arm_smmu_evtq_handler(int irq, void *dev)
1137 {
1138         irqreturn_t ret = IRQ_WAKE_THREAD;
1139         struct arm_smmu_device *smmu = dev;
1140         struct arm_smmu_queue *q = &smmu->evtq.q;
1141
1142         /*
1143          * Not much we can do on overflow, so scream and pretend we're
1144          * trying harder.
1145          */
1146         if (queue_sync_prod(q) == -EOVERFLOW)
1147                 dev_err(smmu->dev, "EVTQ overflow detected -- events lost\n");
1148         else if (queue_empty(q))
1149                 ret = IRQ_NONE;
1150
1151         return ret;
1152 }
1153
1154 static irqreturn_t arm_smmu_priq_thread(int irq, void *dev)
1155 {
1156         struct arm_smmu_device *smmu = dev;
1157         struct arm_smmu_queue *q = &smmu->priq.q;
1158         u64 evt[PRIQ_ENT_DWORDS];
1159
1160         while (!queue_remove_raw(q, evt)) {
1161                 u32 sid, ssid;
1162                 u16 grpid;
1163                 bool ssv, last;
1164
1165                 sid = evt[0] >> PRIQ_0_SID_SHIFT & PRIQ_0_SID_MASK;
1166                 ssv = evt[0] & PRIQ_0_SSID_V;
1167                 ssid = ssv ? evt[0] >> PRIQ_0_SSID_SHIFT & PRIQ_0_SSID_MASK : 0;
1168                 last = evt[0] & PRIQ_0_PRG_LAST;
1169                 grpid = evt[1] >> PRIQ_1_PRG_IDX_SHIFT & PRIQ_1_PRG_IDX_MASK;
1170
1171                 dev_info(smmu->dev, "unexpected PRI request received:\n");
1172                 dev_info(smmu->dev,
1173                          "\tsid 0x%08x.0x%05x: [%u%s] %sprivileged %s%s%s access at iova 0x%016llx\n",
1174                          sid, ssid, grpid, last ? "L" : "",
1175                          evt[0] & PRIQ_0_PERM_PRIV ? "" : "un",
1176                          evt[0] & PRIQ_0_PERM_READ ? "R" : "",
1177                          evt[0] & PRIQ_0_PERM_WRITE ? "W" : "",
1178                          evt[0] & PRIQ_0_PERM_EXEC ? "X" : "",
1179                          evt[1] & PRIQ_1_ADDR_MASK << PRIQ_1_ADDR_SHIFT);
1180
1181                 if (last) {
1182                         struct arm_smmu_cmdq_ent cmd = {
1183                                 .opcode                 = CMDQ_OP_PRI_RESP,
1184                                 .substream_valid        = ssv,
1185                                 .pri                    = {
1186                                         .sid    = sid,
1187                                         .ssid   = ssid,
1188                                         .grpid  = grpid,
1189                                         .resp   = PRI_RESP_DENY,
1190                                 },
1191                         };
1192
1193                         arm_smmu_cmdq_issue_cmd(smmu, &cmd);
1194                 }
1195         }
1196
1197         /* Sync our overflow flag, as we believe we're up to speed */
1198         q->cons = Q_OVF(q, q->prod) | Q_WRP(q, q->cons) | Q_IDX(q, q->cons);
1199         return IRQ_HANDLED;
1200 }
1201
1202 static irqreturn_t arm_smmu_priq_handler(int irq, void *dev)
1203 {
1204         irqreturn_t ret = IRQ_WAKE_THREAD;
1205         struct arm_smmu_device *smmu = dev;
1206         struct arm_smmu_queue *q = &smmu->priq.q;
1207
1208         /* PRIQ overflow indicates a programming error */
1209         if (queue_sync_prod(q) == -EOVERFLOW)
1210                 dev_err(smmu->dev, "PRIQ overflow detected -- requests lost\n");
1211         else if (queue_empty(q))
1212                 ret = IRQ_NONE;
1213
1214         return ret;
1215 }
1216
1217 static irqreturn_t arm_smmu_cmdq_sync_handler(int irq, void *dev)
1218 {
1219         /* We don't actually use CMD_SYNC interrupts for anything */
1220         return IRQ_HANDLED;
1221 }
1222
1223 static int arm_smmu_device_disable(struct arm_smmu_device *smmu);
1224
1225 static irqreturn_t arm_smmu_gerror_handler(int irq, void *dev)
1226 {
1227         u32 gerror, gerrorn;
1228         struct arm_smmu_device *smmu = dev;
1229
1230         gerror = readl_relaxed(smmu->base + ARM_SMMU_GERROR);
1231         gerrorn = readl_relaxed(smmu->base + ARM_SMMU_GERRORN);
1232
1233         gerror ^= gerrorn;
1234         if (!(gerror & GERROR_ERR_MASK))
1235                 return IRQ_NONE; /* No errors pending */
1236
1237         dev_warn(smmu->dev,
1238                  "unexpected global error reported (0x%08x), this could be serious\n",
1239                  gerror);
1240
1241         if (gerror & GERROR_SFM_ERR) {
1242                 dev_err(smmu->dev, "device has entered Service Failure Mode!\n");
1243                 arm_smmu_device_disable(smmu);
1244         }
1245
1246         if (gerror & GERROR_MSI_GERROR_ABT_ERR)
1247                 dev_warn(smmu->dev, "GERROR MSI write aborted\n");
1248
1249         if (gerror & GERROR_MSI_PRIQ_ABT_ERR) {
1250                 dev_warn(smmu->dev, "PRIQ MSI write aborted\n");
1251                 arm_smmu_priq_handler(irq, smmu->dev);
1252         }
1253
1254         if (gerror & GERROR_MSI_EVTQ_ABT_ERR) {
1255                 dev_warn(smmu->dev, "EVTQ MSI write aborted\n");
1256                 arm_smmu_evtq_handler(irq, smmu->dev);
1257         }
1258
1259         if (gerror & GERROR_MSI_CMDQ_ABT_ERR) {
1260                 dev_warn(smmu->dev, "CMDQ MSI write aborted\n");
1261                 arm_smmu_cmdq_sync_handler(irq, smmu->dev);
1262         }
1263
1264         if (gerror & GERROR_PRIQ_ABT_ERR)
1265                 dev_err(smmu->dev, "PRIQ write aborted -- events may have been lost\n");
1266
1267         if (gerror & GERROR_EVTQ_ABT_ERR)
1268                 dev_err(smmu->dev, "EVTQ write aborted -- events may have been lost\n");
1269
1270         if (gerror & GERROR_CMDQ_ERR)
1271                 arm_smmu_cmdq_skip_err(smmu);
1272
1273         writel(gerror, smmu->base + ARM_SMMU_GERRORN);
1274         return IRQ_HANDLED;
1275 }
1276
1277 /* IO_PGTABLE API */
1278 static void __arm_smmu_tlb_sync(struct arm_smmu_device *smmu)
1279 {
1280         struct arm_smmu_cmdq_ent cmd;
1281
1282         cmd.opcode = CMDQ_OP_CMD_SYNC;
1283         arm_smmu_cmdq_issue_cmd(smmu, &cmd);
1284 }
1285
1286 static void arm_smmu_tlb_sync(void *cookie)
1287 {
1288         struct arm_smmu_domain *smmu_domain = cookie;
1289         __arm_smmu_tlb_sync(smmu_domain->smmu);
1290 }
1291
1292 static void arm_smmu_tlb_inv_context(void *cookie)
1293 {
1294         struct arm_smmu_domain *smmu_domain = cookie;
1295         struct arm_smmu_device *smmu = smmu_domain->smmu;
1296         struct arm_smmu_cmdq_ent cmd;
1297
1298         if (smmu_domain->stage == ARM_SMMU_DOMAIN_S1) {
1299                 cmd.opcode      = CMDQ_OP_TLBI_NH_ASID;
1300                 cmd.tlbi.asid   = smmu_domain->s1_cfg.cd.asid;
1301                 cmd.tlbi.vmid   = 0;
1302         } else {
1303                 cmd.opcode      = CMDQ_OP_TLBI_S12_VMALL;
1304                 cmd.tlbi.vmid   = smmu_domain->s2_cfg.vmid;
1305         }
1306
1307         arm_smmu_cmdq_issue_cmd(smmu, &cmd);
1308         __arm_smmu_tlb_sync(smmu);
1309 }
1310
1311 static void arm_smmu_tlb_inv_range_nosync(unsigned long iova, size_t size,
1312                                           bool leaf, void *cookie)
1313 {
1314         struct arm_smmu_domain *smmu_domain = cookie;
1315         struct arm_smmu_device *smmu = smmu_domain->smmu;
1316         struct arm_smmu_cmdq_ent cmd = {
1317                 .tlbi = {
1318                         .leaf   = leaf,
1319                         .addr   = iova,
1320                 },
1321         };
1322
1323         if (smmu_domain->stage == ARM_SMMU_DOMAIN_S1) {
1324                 cmd.opcode      = CMDQ_OP_TLBI_NH_VA;
1325                 cmd.tlbi.asid   = smmu_domain->s1_cfg.cd.asid;
1326         } else {
1327                 cmd.opcode      = CMDQ_OP_TLBI_S2_IPA;
1328                 cmd.tlbi.vmid   = smmu_domain->s2_cfg.vmid;
1329         }
1330
1331         arm_smmu_cmdq_issue_cmd(smmu, &cmd);
1332 }
1333
1334 static struct iommu_gather_ops arm_smmu_gather_ops = {
1335         .tlb_flush_all  = arm_smmu_tlb_inv_context,
1336         .tlb_add_flush  = arm_smmu_tlb_inv_range_nosync,
1337         .tlb_sync       = arm_smmu_tlb_sync,
1338 };
1339
1340 /* IOMMU API */
1341 static bool arm_smmu_capable(enum iommu_cap cap)
1342 {
1343         switch (cap) {
1344         case IOMMU_CAP_CACHE_COHERENCY:
1345                 return true;
1346         case IOMMU_CAP_INTR_REMAP:
1347                 return true; /* MSIs are just memory writes */
1348         case IOMMU_CAP_NOEXEC:
1349                 return true;
1350         default:
1351                 return false;
1352         }
1353 }
1354
1355 static struct iommu_domain *arm_smmu_domain_alloc(unsigned type)
1356 {
1357         struct arm_smmu_domain *smmu_domain;
1358
1359         if (type != IOMMU_DOMAIN_UNMANAGED)
1360                 return NULL;
1361
1362         /*
1363          * Allocate the domain and initialise some of its data structures.
1364          * We can't really do anything meaningful until we've added a
1365          * master.
1366          */
1367         smmu_domain = kzalloc(sizeof(*smmu_domain), GFP_KERNEL);
1368         if (!smmu_domain)
1369                 return NULL;
1370
1371         mutex_init(&smmu_domain->init_mutex);
1372         spin_lock_init(&smmu_domain->pgtbl_lock);
1373         return &smmu_domain->domain;
1374 }
1375
1376 static int arm_smmu_bitmap_alloc(unsigned long *map, int span)
1377 {
1378         int idx, size = 1 << span;
1379
1380         do {
1381                 idx = find_first_zero_bit(map, size);
1382                 if (idx == size)
1383                         return -ENOSPC;
1384         } while (test_and_set_bit(idx, map));
1385
1386         return idx;
1387 }
1388
1389 static void arm_smmu_bitmap_free(unsigned long *map, int idx)
1390 {
1391         clear_bit(idx, map);
1392 }
1393
1394 static void arm_smmu_domain_free(struct iommu_domain *domain)
1395 {
1396         struct arm_smmu_domain *smmu_domain = to_smmu_domain(domain);
1397         struct arm_smmu_device *smmu = smmu_domain->smmu;
1398
1399         free_io_pgtable_ops(smmu_domain->pgtbl_ops);
1400
1401         /* Free the CD and ASID, if we allocated them */
1402         if (smmu_domain->stage == ARM_SMMU_DOMAIN_S1) {
1403                 struct arm_smmu_s1_cfg *cfg = &smmu_domain->s1_cfg;
1404
1405                 if (cfg->cdptr) {
1406                         dma_free_coherent(smmu_domain->smmu->dev,
1407                                           CTXDESC_CD_DWORDS << 3,
1408                                           cfg->cdptr,
1409                                           cfg->cdptr_dma);
1410
1411                         arm_smmu_bitmap_free(smmu->asid_map, cfg->cd.asid);
1412                 }
1413         } else {
1414                 struct arm_smmu_s2_cfg *cfg = &smmu_domain->s2_cfg;
1415                 if (cfg->vmid)
1416                         arm_smmu_bitmap_free(smmu->vmid_map, cfg->vmid);
1417         }
1418
1419         kfree(smmu_domain);
1420 }
1421
1422 static int arm_smmu_domain_finalise_s1(struct arm_smmu_domain *smmu_domain,
1423                                        struct io_pgtable_cfg *pgtbl_cfg)
1424 {
1425         int ret;
1426         u16 asid;
1427         struct arm_smmu_device *smmu = smmu_domain->smmu;
1428         struct arm_smmu_s1_cfg *cfg = &smmu_domain->s1_cfg;
1429
1430         asid = arm_smmu_bitmap_alloc(smmu->asid_map, smmu->asid_bits);
1431         if (IS_ERR_VALUE(asid))
1432                 return asid;
1433
1434         cfg->cdptr = dma_zalloc_coherent(smmu->dev, CTXDESC_CD_DWORDS << 3,
1435                                          &cfg->cdptr_dma, GFP_KERNEL);
1436         if (!cfg->cdptr) {
1437                 dev_warn(smmu->dev, "failed to allocate context descriptor\n");
1438                 goto out_free_asid;
1439         }
1440
1441         cfg->cd.asid    = asid;
1442         cfg->cd.ttbr    = pgtbl_cfg->arm_lpae_s1_cfg.ttbr[0];
1443         cfg->cd.tcr     = pgtbl_cfg->arm_lpae_s1_cfg.tcr;
1444         cfg->cd.mair    = pgtbl_cfg->arm_lpae_s1_cfg.mair[0];
1445         return 0;
1446
1447 out_free_asid:
1448         arm_smmu_bitmap_free(smmu->asid_map, asid);
1449         return ret;
1450 }
1451
1452 static int arm_smmu_domain_finalise_s2(struct arm_smmu_domain *smmu_domain,
1453                                        struct io_pgtable_cfg *pgtbl_cfg)
1454 {
1455         u16 vmid;
1456         struct arm_smmu_device *smmu = smmu_domain->smmu;
1457         struct arm_smmu_s2_cfg *cfg = &smmu_domain->s2_cfg;
1458
1459         vmid = arm_smmu_bitmap_alloc(smmu->vmid_map, smmu->vmid_bits);
1460         if (IS_ERR_VALUE(vmid))
1461                 return vmid;
1462
1463         cfg->vmid       = vmid;
1464         cfg->vttbr      = pgtbl_cfg->arm_lpae_s2_cfg.vttbr;
1465         cfg->vtcr       = pgtbl_cfg->arm_lpae_s2_cfg.vtcr;
1466         return 0;
1467 }
1468
1469 static struct iommu_ops arm_smmu_ops;
1470
1471 static int arm_smmu_domain_finalise(struct iommu_domain *domain)
1472 {
1473         int ret;
1474         unsigned long ias, oas;
1475         enum io_pgtable_fmt fmt;
1476         struct io_pgtable_cfg pgtbl_cfg;
1477         struct io_pgtable_ops *pgtbl_ops;
1478         int (*finalise_stage_fn)(struct arm_smmu_domain *,
1479                                  struct io_pgtable_cfg *);
1480         struct arm_smmu_domain *smmu_domain = to_smmu_domain(domain);
1481         struct arm_smmu_device *smmu = smmu_domain->smmu;
1482
1483         /* Restrict the stage to what we can actually support */
1484         if (!(smmu->features & ARM_SMMU_FEAT_TRANS_S1))
1485                 smmu_domain->stage = ARM_SMMU_DOMAIN_S2;
1486         if (!(smmu->features & ARM_SMMU_FEAT_TRANS_S2))
1487                 smmu_domain->stage = ARM_SMMU_DOMAIN_S1;
1488
1489         switch (smmu_domain->stage) {
1490         case ARM_SMMU_DOMAIN_S1:
1491                 ias = VA_BITS;
1492                 oas = smmu->ias;
1493                 fmt = ARM_64_LPAE_S1;
1494                 finalise_stage_fn = arm_smmu_domain_finalise_s1;
1495                 break;
1496         case ARM_SMMU_DOMAIN_NESTED:
1497         case ARM_SMMU_DOMAIN_S2:
1498                 ias = smmu->ias;
1499                 oas = smmu->oas;
1500                 fmt = ARM_64_LPAE_S2;
1501                 finalise_stage_fn = arm_smmu_domain_finalise_s2;
1502                 break;
1503         default:
1504                 return -EINVAL;
1505         }
1506
1507         pgtbl_cfg = (struct io_pgtable_cfg) {
1508                 .pgsize_bitmap  = arm_smmu_ops.pgsize_bitmap,
1509                 .ias            = ias,
1510                 .oas            = oas,
1511                 .tlb            = &arm_smmu_gather_ops,
1512                 .iommu_dev      = smmu->dev,
1513         };
1514
1515         pgtbl_ops = alloc_io_pgtable_ops(fmt, &pgtbl_cfg, smmu_domain);
1516         if (!pgtbl_ops)
1517                 return -ENOMEM;
1518
1519         arm_smmu_ops.pgsize_bitmap = pgtbl_cfg.pgsize_bitmap;
1520         smmu_domain->pgtbl_ops = pgtbl_ops;
1521
1522         ret = finalise_stage_fn(smmu_domain, &pgtbl_cfg);
1523         if (IS_ERR_VALUE(ret))
1524                 free_io_pgtable_ops(pgtbl_ops);
1525
1526         return ret;
1527 }
1528
1529 static struct arm_smmu_group *arm_smmu_group_get(struct device *dev)
1530 {
1531         struct iommu_group *group;
1532         struct arm_smmu_group *smmu_group;
1533
1534         group = iommu_group_get(dev);
1535         if (!group)
1536                 return NULL;
1537
1538         smmu_group = iommu_group_get_iommudata(group);
1539         iommu_group_put(group);
1540         return smmu_group;
1541 }
1542
1543 static __le64 *arm_smmu_get_step_for_sid(struct arm_smmu_device *smmu, u32 sid)
1544 {
1545         __le64 *step;
1546         struct arm_smmu_strtab_cfg *cfg = &smmu->strtab_cfg;
1547
1548         if (smmu->features & ARM_SMMU_FEAT_2_LVL_STRTAB) {
1549                 struct arm_smmu_strtab_l1_desc *l1_desc;
1550                 int idx;
1551
1552                 /* Two-level walk */
1553                 idx = (sid >> STRTAB_SPLIT) * STRTAB_L1_DESC_DWORDS;
1554                 l1_desc = &cfg->l1_desc[idx];
1555                 idx = (sid & ((1 << STRTAB_SPLIT) - 1)) * STRTAB_STE_DWORDS;
1556                 step = &l1_desc->l2ptr[idx];
1557         } else {
1558                 /* Simple linear lookup */
1559                 step = &cfg->strtab[sid * STRTAB_STE_DWORDS];
1560         }
1561
1562         return step;
1563 }
1564
1565 static int arm_smmu_install_ste_for_group(struct arm_smmu_group *smmu_group)
1566 {
1567         int i;
1568         struct arm_smmu_domain *smmu_domain = smmu_group->domain;
1569         struct arm_smmu_strtab_ent *ste = &smmu_group->ste;
1570         struct arm_smmu_device *smmu = smmu_group->smmu;
1571
1572         if (smmu_domain->stage == ARM_SMMU_DOMAIN_S1) {
1573                 ste->s1_cfg = &smmu_domain->s1_cfg;
1574                 ste->s2_cfg = NULL;
1575                 arm_smmu_write_ctx_desc(smmu, ste->s1_cfg);
1576         } else {
1577                 ste->s1_cfg = NULL;
1578                 ste->s2_cfg = &smmu_domain->s2_cfg;
1579         }
1580
1581         for (i = 0; i < smmu_group->num_sids; ++i) {
1582                 u32 sid = smmu_group->sids[i];
1583                 __le64 *step = arm_smmu_get_step_for_sid(smmu, sid);
1584
1585                 arm_smmu_write_strtab_ent(smmu, sid, step, ste);
1586         }
1587
1588         return 0;
1589 }
1590
1591 static int arm_smmu_attach_dev(struct iommu_domain *domain, struct device *dev)
1592 {
1593         int ret = 0;
1594         struct arm_smmu_device *smmu;
1595         struct arm_smmu_domain *smmu_domain = to_smmu_domain(domain);
1596         struct arm_smmu_group *smmu_group = arm_smmu_group_get(dev);
1597
1598         if (!smmu_group)
1599                 return -ENOENT;
1600
1601         /* Already attached to a different domain? */
1602         if (smmu_group->domain && smmu_group->domain != smmu_domain)
1603                 return -EEXIST;
1604
1605         smmu = smmu_group->smmu;
1606         mutex_lock(&smmu_domain->init_mutex);
1607
1608         if (!smmu_domain->smmu) {
1609                 smmu_domain->smmu = smmu;
1610                 ret = arm_smmu_domain_finalise(domain);
1611                 if (ret) {
1612                         smmu_domain->smmu = NULL;
1613                         goto out_unlock;
1614                 }
1615         } else if (smmu_domain->smmu != smmu) {
1616                 dev_err(dev,
1617                         "cannot attach to SMMU %s (upstream of %s)\n",
1618                         dev_name(smmu_domain->smmu->dev),
1619                         dev_name(smmu->dev));
1620                 ret = -ENXIO;
1621                 goto out_unlock;
1622         }
1623
1624         /* Group already attached to this domain? */
1625         if (smmu_group->domain)
1626                 goto out_unlock;
1627
1628         smmu_group->domain      = smmu_domain;
1629         smmu_group->ste.bypass  = false;
1630
1631         ret = arm_smmu_install_ste_for_group(smmu_group);
1632         if (IS_ERR_VALUE(ret))
1633                 smmu_group->domain = NULL;
1634
1635 out_unlock:
1636         mutex_unlock(&smmu_domain->init_mutex);
1637         return ret;
1638 }
1639
1640 static void arm_smmu_detach_dev(struct iommu_domain *domain, struct device *dev)
1641 {
1642         struct arm_smmu_domain *smmu_domain = to_smmu_domain(domain);
1643         struct arm_smmu_group *smmu_group = arm_smmu_group_get(dev);
1644
1645         BUG_ON(!smmu_domain);
1646         BUG_ON(!smmu_group);
1647
1648         mutex_lock(&smmu_domain->init_mutex);
1649         BUG_ON(smmu_group->domain != smmu_domain);
1650
1651         smmu_group->ste.bypass = true;
1652         if (IS_ERR_VALUE(arm_smmu_install_ste_for_group(smmu_group)))
1653                 dev_warn(dev, "failed to install bypass STE\n");
1654
1655         smmu_group->domain = NULL;
1656         mutex_unlock(&smmu_domain->init_mutex);
1657 }
1658
1659 static int arm_smmu_map(struct iommu_domain *domain, unsigned long iova,
1660                         phys_addr_t paddr, size_t size, int prot)
1661 {
1662         int ret;
1663         unsigned long flags;
1664         struct arm_smmu_domain *smmu_domain = to_smmu_domain(domain);
1665         struct io_pgtable_ops *ops = smmu_domain->pgtbl_ops;
1666
1667         if (!ops)
1668                 return -ENODEV;
1669
1670         spin_lock_irqsave(&smmu_domain->pgtbl_lock, flags);
1671         ret = ops->map(ops, iova, paddr, size, prot);
1672         spin_unlock_irqrestore(&smmu_domain->pgtbl_lock, flags);
1673         return ret;
1674 }
1675
1676 static size_t
1677 arm_smmu_unmap(struct iommu_domain *domain, unsigned long iova, size_t size)
1678 {
1679         size_t ret;
1680         unsigned long flags;
1681         struct arm_smmu_domain *smmu_domain = to_smmu_domain(domain);
1682         struct io_pgtable_ops *ops = smmu_domain->pgtbl_ops;
1683
1684         if (!ops)
1685                 return 0;
1686
1687         spin_lock_irqsave(&smmu_domain->pgtbl_lock, flags);
1688         ret = ops->unmap(ops, iova, size);
1689         spin_unlock_irqrestore(&smmu_domain->pgtbl_lock, flags);
1690         return ret;
1691 }
1692
1693 static phys_addr_t
1694 arm_smmu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
1695 {
1696         phys_addr_t ret;
1697         unsigned long flags;
1698         struct arm_smmu_domain *smmu_domain = to_smmu_domain(domain);
1699         struct io_pgtable_ops *ops = smmu_domain->pgtbl_ops;
1700
1701         if (!ops)
1702                 return 0;
1703
1704         spin_lock_irqsave(&smmu_domain->pgtbl_lock, flags);
1705         ret = ops->iova_to_phys(ops, iova);
1706         spin_unlock_irqrestore(&smmu_domain->pgtbl_lock, flags);
1707
1708         return ret;
1709 }
1710
1711 static int __arm_smmu_get_pci_sid(struct pci_dev *pdev, u16 alias, void *sidp)
1712 {
1713         *(u32 *)sidp = alias;
1714         return 0; /* Continue walking */
1715 }
1716
1717 static void __arm_smmu_release_pci_iommudata(void *data)
1718 {
1719         kfree(data);
1720 }
1721
1722 static struct arm_smmu_device *arm_smmu_get_for_pci_dev(struct pci_dev *pdev)
1723 {
1724         struct device_node *of_node;
1725         struct arm_smmu_device *curr, *smmu = NULL;
1726         struct pci_bus *bus = pdev->bus;
1727
1728         /* Walk up to the root bus */
1729         while (!pci_is_root_bus(bus))
1730                 bus = bus->parent;
1731
1732         /* Follow the "iommus" phandle from the host controller */
1733         of_node = of_parse_phandle(bus->bridge->parent->of_node, "iommus", 0);
1734         if (!of_node)
1735                 return NULL;
1736
1737         /* See if we can find an SMMU corresponding to the phandle */
1738         spin_lock(&arm_smmu_devices_lock);
1739         list_for_each_entry(curr, &arm_smmu_devices, list) {
1740                 if (curr->dev->of_node == of_node) {
1741                         smmu = curr;
1742                         break;
1743                 }
1744         }
1745         spin_unlock(&arm_smmu_devices_lock);
1746         of_node_put(of_node);
1747         return smmu;
1748 }
1749
1750 static bool arm_smmu_sid_in_range(struct arm_smmu_device *smmu, u32 sid)
1751 {
1752         unsigned long limit = smmu->strtab_cfg.num_l1_ents;
1753
1754         if (smmu->features & ARM_SMMU_FEAT_2_LVL_STRTAB)
1755                 limit *= 1UL << STRTAB_SPLIT;
1756
1757         return sid < limit;
1758 }
1759
1760 static int arm_smmu_add_device(struct device *dev)
1761 {
1762         int i, ret;
1763         u32 sid, *sids;
1764         struct pci_dev *pdev;
1765         struct iommu_group *group;
1766         struct arm_smmu_group *smmu_group;
1767         struct arm_smmu_device *smmu;
1768
1769         /* We only support PCI, for now */
1770         if (!dev_is_pci(dev))
1771                 return -ENODEV;
1772
1773         pdev = to_pci_dev(dev);
1774         group = iommu_group_get_for_dev(dev);
1775         if (IS_ERR(group))
1776                 return PTR_ERR(group);
1777
1778         smmu_group = iommu_group_get_iommudata(group);
1779         if (!smmu_group) {
1780                 smmu = arm_smmu_get_for_pci_dev(pdev);
1781                 if (!smmu) {
1782                         ret = -ENOENT;
1783                         goto out_put_group;
1784                 }
1785
1786                 smmu_group = kzalloc(sizeof(*smmu_group), GFP_KERNEL);
1787                 if (!smmu_group) {
1788                         ret = -ENOMEM;
1789                         goto out_put_group;
1790                 }
1791
1792                 smmu_group->ste.valid   = true;
1793                 smmu_group->smmu        = smmu;
1794                 iommu_group_set_iommudata(group, smmu_group,
1795                                           __arm_smmu_release_pci_iommudata);
1796         } else {
1797                 smmu = smmu_group->smmu;
1798         }
1799
1800         /* Assume SID == RID until firmware tells us otherwise */
1801         pci_for_each_dma_alias(pdev, __arm_smmu_get_pci_sid, &sid);
1802         for (i = 0; i < smmu_group->num_sids; ++i) {
1803                 /* If we already know about this SID, then we're done */
1804                 if (smmu_group->sids[i] == sid)
1805                         return 0;
1806         }
1807
1808         /* Check the SID is in range of the SMMU and our stream table */
1809         if (!arm_smmu_sid_in_range(smmu, sid)) {
1810                 ret = -ERANGE;
1811                 goto out_put_group;
1812         }
1813
1814         /* Ensure l2 strtab is initialised */
1815         if (smmu->features & ARM_SMMU_FEAT_2_LVL_STRTAB) {
1816                 ret = arm_smmu_init_l2_strtab(smmu, sid);
1817                 if (ret)
1818                         goto out_put_group;
1819         }
1820
1821         /* Resize the SID array for the group */
1822         smmu_group->num_sids++;
1823         sids = krealloc(smmu_group->sids, smmu_group->num_sids * sizeof(*sids),
1824                         GFP_KERNEL);
1825         if (!sids) {
1826                 smmu_group->num_sids--;
1827                 ret = -ENOMEM;
1828                 goto out_put_group;
1829         }
1830
1831         /* Add the new SID */
1832         sids[smmu_group->num_sids - 1] = sid;
1833         smmu_group->sids = sids;
1834         return 0;
1835
1836 out_put_group:
1837         iommu_group_put(group);
1838         return ret;
1839 }
1840
1841 static void arm_smmu_remove_device(struct device *dev)
1842 {
1843         iommu_group_remove_device(dev);
1844 }
1845
1846 static int arm_smmu_domain_get_attr(struct iommu_domain *domain,
1847                                     enum iommu_attr attr, void *data)
1848 {
1849         struct arm_smmu_domain *smmu_domain = to_smmu_domain(domain);
1850
1851         switch (attr) {
1852         case DOMAIN_ATTR_NESTING:
1853                 *(int *)data = (smmu_domain->stage == ARM_SMMU_DOMAIN_NESTED);
1854                 return 0;
1855         default:
1856                 return -ENODEV;
1857         }
1858 }
1859
1860 static int arm_smmu_domain_set_attr(struct iommu_domain *domain,
1861                                     enum iommu_attr attr, void *data)
1862 {
1863         int ret = 0;
1864         struct arm_smmu_domain *smmu_domain = to_smmu_domain(domain);
1865
1866         mutex_lock(&smmu_domain->init_mutex);
1867
1868         switch (attr) {
1869         case DOMAIN_ATTR_NESTING:
1870                 if (smmu_domain->smmu) {
1871                         ret = -EPERM;
1872                         goto out_unlock;
1873                 }
1874
1875                 if (*(int *)data)
1876                         smmu_domain->stage = ARM_SMMU_DOMAIN_NESTED;
1877                 else
1878                         smmu_domain->stage = ARM_SMMU_DOMAIN_S1;
1879
1880                 break;
1881         default:
1882                 ret = -ENODEV;
1883         }
1884
1885 out_unlock:
1886         mutex_unlock(&smmu_domain->init_mutex);
1887         return ret;
1888 }
1889
1890 static struct iommu_ops arm_smmu_ops = {
1891         .capable                = arm_smmu_capable,
1892         .domain_alloc           = arm_smmu_domain_alloc,
1893         .domain_free            = arm_smmu_domain_free,
1894         .attach_dev             = arm_smmu_attach_dev,
1895         .detach_dev             = arm_smmu_detach_dev,
1896         .map                    = arm_smmu_map,
1897         .unmap                  = arm_smmu_unmap,
1898         .iova_to_phys           = arm_smmu_iova_to_phys,
1899         .add_device             = arm_smmu_add_device,
1900         .remove_device          = arm_smmu_remove_device,
1901         .device_group           = pci_device_group,
1902         .domain_get_attr        = arm_smmu_domain_get_attr,
1903         .domain_set_attr        = arm_smmu_domain_set_attr,
1904         .pgsize_bitmap          = -1UL, /* Restricted during device attach */
1905 };
1906
1907 /* Probing and initialisation functions */
1908 static int arm_smmu_init_one_queue(struct arm_smmu_device *smmu,
1909                                    struct arm_smmu_queue *q,
1910                                    unsigned long prod_off,
1911                                    unsigned long cons_off,
1912                                    size_t dwords)
1913 {
1914         size_t qsz = ((1 << q->max_n_shift) * dwords) << 3;
1915
1916         q->base = dma_alloc_coherent(smmu->dev, qsz, &q->base_dma, GFP_KERNEL);
1917         if (!q->base) {
1918                 dev_err(smmu->dev, "failed to allocate queue (0x%zx bytes)\n",
1919                         qsz);
1920                 return -ENOMEM;
1921         }
1922
1923         q->prod_reg     = smmu->base + prod_off;
1924         q->cons_reg     = smmu->base + cons_off;
1925         q->ent_dwords   = dwords;
1926
1927         q->q_base  = Q_BASE_RWA;
1928         q->q_base |= q->base_dma & Q_BASE_ADDR_MASK << Q_BASE_ADDR_SHIFT;
1929         q->q_base |= (q->max_n_shift & Q_BASE_LOG2SIZE_MASK)
1930                      << Q_BASE_LOG2SIZE_SHIFT;
1931
1932         q->prod = q->cons = 0;
1933         return 0;
1934 }
1935
1936 static void arm_smmu_free_one_queue(struct arm_smmu_device *smmu,
1937                                     struct arm_smmu_queue *q)
1938 {
1939         size_t qsz = ((1 << q->max_n_shift) * q->ent_dwords) << 3;
1940
1941         dma_free_coherent(smmu->dev, qsz, q->base, q->base_dma);
1942 }
1943
1944 static void arm_smmu_free_queues(struct arm_smmu_device *smmu)
1945 {
1946         arm_smmu_free_one_queue(smmu, &smmu->cmdq.q);
1947         arm_smmu_free_one_queue(smmu, &smmu->evtq.q);
1948
1949         if (smmu->features & ARM_SMMU_FEAT_PRI)
1950                 arm_smmu_free_one_queue(smmu, &smmu->priq.q);
1951 }
1952
1953 static int arm_smmu_init_queues(struct arm_smmu_device *smmu)
1954 {
1955         int ret;
1956
1957         /* cmdq */
1958         spin_lock_init(&smmu->cmdq.lock);
1959         ret = arm_smmu_init_one_queue(smmu, &smmu->cmdq.q, ARM_SMMU_CMDQ_PROD,
1960                                       ARM_SMMU_CMDQ_CONS, CMDQ_ENT_DWORDS);
1961         if (ret)
1962                 goto out;
1963
1964         /* evtq */
1965         ret = arm_smmu_init_one_queue(smmu, &smmu->evtq.q, ARM_SMMU_EVTQ_PROD,
1966                                       ARM_SMMU_EVTQ_CONS, EVTQ_ENT_DWORDS);
1967         if (ret)
1968                 goto out_free_cmdq;
1969
1970         /* priq */
1971         if (!(smmu->features & ARM_SMMU_FEAT_PRI))
1972                 return 0;
1973
1974         ret = arm_smmu_init_one_queue(smmu, &smmu->priq.q, ARM_SMMU_PRIQ_PROD,
1975                                       ARM_SMMU_PRIQ_CONS, PRIQ_ENT_DWORDS);
1976         if (ret)
1977                 goto out_free_evtq;
1978
1979         return 0;
1980
1981 out_free_evtq:
1982         arm_smmu_free_one_queue(smmu, &smmu->evtq.q);
1983 out_free_cmdq:
1984         arm_smmu_free_one_queue(smmu, &smmu->cmdq.q);
1985 out:
1986         return ret;
1987 }
1988
1989 static void arm_smmu_free_l2_strtab(struct arm_smmu_device *smmu)
1990 {
1991         int i;
1992         size_t size;
1993         struct arm_smmu_strtab_cfg *cfg = &smmu->strtab_cfg;
1994
1995         size = 1 << (STRTAB_SPLIT + ilog2(STRTAB_STE_DWORDS) + 3);
1996         for (i = 0; i < cfg->num_l1_ents; ++i) {
1997                 struct arm_smmu_strtab_l1_desc *desc = &cfg->l1_desc[i];
1998
1999                 if (!desc->l2ptr)
2000                         continue;
2001
2002                 dma_free_coherent(smmu->dev, size, desc->l2ptr,
2003                                   desc->l2ptr_dma);
2004         }
2005 }
2006
2007 static int arm_smmu_init_l1_strtab(struct arm_smmu_device *smmu)
2008 {
2009         unsigned int i;
2010         struct arm_smmu_strtab_cfg *cfg = &smmu->strtab_cfg;
2011         size_t size = sizeof(*cfg->l1_desc) * cfg->num_l1_ents;
2012         void *strtab = smmu->strtab_cfg.strtab;
2013
2014         cfg->l1_desc = devm_kzalloc(smmu->dev, size, GFP_KERNEL);
2015         if (!cfg->l1_desc) {
2016                 dev_err(smmu->dev, "failed to allocate l1 stream table desc\n");
2017                 return -ENOMEM;
2018         }
2019
2020         for (i = 0; i < cfg->num_l1_ents; ++i) {
2021                 arm_smmu_write_strtab_l1_desc(strtab, &cfg->l1_desc[i]);
2022                 strtab += STRTAB_L1_DESC_DWORDS << 3;
2023         }
2024
2025         return 0;
2026 }
2027
2028 static int arm_smmu_init_strtab_2lvl(struct arm_smmu_device *smmu)
2029 {
2030         void *strtab;
2031         u64 reg;
2032         u32 size, l1size;
2033         int ret;
2034         struct arm_smmu_strtab_cfg *cfg = &smmu->strtab_cfg;
2035
2036         /*
2037          * If we can resolve everything with a single L2 table, then we
2038          * just need a single L1 descriptor. Otherwise, calculate the L1
2039          * size, capped to the SIDSIZE.
2040          */
2041         if (smmu->sid_bits < STRTAB_SPLIT) {
2042                 size = 0;
2043         } else {
2044                 size = STRTAB_L1_SZ_SHIFT - (ilog2(STRTAB_L1_DESC_DWORDS) + 3);
2045                 size = min(size, smmu->sid_bits - STRTAB_SPLIT);
2046         }
2047         cfg->num_l1_ents = 1 << size;
2048
2049         size += STRTAB_SPLIT;
2050         if (size < smmu->sid_bits)
2051                 dev_warn(smmu->dev,
2052                          "2-level strtab only covers %u/%u bits of SID\n",
2053                          size, smmu->sid_bits);
2054
2055         l1size = cfg->num_l1_ents * (STRTAB_L1_DESC_DWORDS << 3);
2056         strtab = dma_zalloc_coherent(smmu->dev, l1size, &cfg->strtab_dma,
2057                                      GFP_KERNEL);
2058         if (!strtab) {
2059                 dev_err(smmu->dev,
2060                         "failed to allocate l1 stream table (%u bytes)\n",
2061                         size);
2062                 return -ENOMEM;
2063         }
2064         cfg->strtab = strtab;
2065
2066         /* Configure strtab_base_cfg for 2 levels */
2067         reg  = STRTAB_BASE_CFG_FMT_2LVL;
2068         reg |= (size & STRTAB_BASE_CFG_LOG2SIZE_MASK)
2069                 << STRTAB_BASE_CFG_LOG2SIZE_SHIFT;
2070         reg |= (STRTAB_SPLIT & STRTAB_BASE_CFG_SPLIT_MASK)
2071                 << STRTAB_BASE_CFG_SPLIT_SHIFT;
2072         cfg->strtab_base_cfg = reg;
2073
2074         ret = arm_smmu_init_l1_strtab(smmu);
2075         if (ret)
2076                 dma_free_coherent(smmu->dev,
2077                                   l1size,
2078                                   strtab,
2079                                   cfg->strtab_dma);
2080         return ret;
2081 }
2082
2083 static int arm_smmu_init_strtab_linear(struct arm_smmu_device *smmu)
2084 {
2085         void *strtab;
2086         u64 reg;
2087         u32 size;
2088         struct arm_smmu_strtab_cfg *cfg = &smmu->strtab_cfg;
2089
2090         size = (1 << smmu->sid_bits) * (STRTAB_STE_DWORDS << 3);
2091         strtab = dma_zalloc_coherent(smmu->dev, size, &cfg->strtab_dma,
2092                                      GFP_KERNEL);
2093         if (!strtab) {
2094                 dev_err(smmu->dev,
2095                         "failed to allocate linear stream table (%u bytes)\n",
2096                         size);
2097                 return -ENOMEM;
2098         }
2099         cfg->strtab = strtab;
2100         cfg->num_l1_ents = 1 << smmu->sid_bits;
2101
2102         /* Configure strtab_base_cfg for a linear table covering all SIDs */
2103         reg  = STRTAB_BASE_CFG_FMT_LINEAR;
2104         reg |= (smmu->sid_bits & STRTAB_BASE_CFG_LOG2SIZE_MASK)
2105                 << STRTAB_BASE_CFG_LOG2SIZE_SHIFT;
2106         cfg->strtab_base_cfg = reg;
2107
2108         arm_smmu_init_bypass_stes(strtab, cfg->num_l1_ents);
2109         return 0;
2110 }
2111
2112 static int arm_smmu_init_strtab(struct arm_smmu_device *smmu)
2113 {
2114         u64 reg;
2115         int ret;
2116
2117         if (smmu->features & ARM_SMMU_FEAT_2_LVL_STRTAB)
2118                 ret = arm_smmu_init_strtab_2lvl(smmu);
2119         else
2120                 ret = arm_smmu_init_strtab_linear(smmu);
2121
2122         if (ret)
2123                 return ret;
2124
2125         /* Set the strtab base address */
2126         reg  = smmu->strtab_cfg.strtab_dma &
2127                STRTAB_BASE_ADDR_MASK << STRTAB_BASE_ADDR_SHIFT;
2128         reg |= STRTAB_BASE_RA;
2129         smmu->strtab_cfg.strtab_base = reg;
2130
2131         /* Allocate the first VMID for stage-2 bypass STEs */
2132         set_bit(0, smmu->vmid_map);
2133         return 0;
2134 }
2135
2136 static void arm_smmu_free_strtab(struct arm_smmu_device *smmu)
2137 {
2138         struct arm_smmu_strtab_cfg *cfg = &smmu->strtab_cfg;
2139         u32 size = cfg->num_l1_ents;
2140
2141         if (smmu->features & ARM_SMMU_FEAT_2_LVL_STRTAB) {
2142                 arm_smmu_free_l2_strtab(smmu);
2143                 size *= STRTAB_L1_DESC_DWORDS << 3;
2144         } else {
2145                 size *= STRTAB_STE_DWORDS * 3;
2146         }
2147
2148         dma_free_coherent(smmu->dev, size, cfg->strtab, cfg->strtab_dma);
2149 }
2150
2151 static int arm_smmu_init_structures(struct arm_smmu_device *smmu)
2152 {
2153         int ret;
2154
2155         ret = arm_smmu_init_queues(smmu);
2156         if (ret)
2157                 return ret;
2158
2159         ret = arm_smmu_init_strtab(smmu);
2160         if (ret)
2161                 goto out_free_queues;
2162
2163         return 0;
2164
2165 out_free_queues:
2166         arm_smmu_free_queues(smmu);
2167         return ret;
2168 }
2169
2170 static void arm_smmu_free_structures(struct arm_smmu_device *smmu)
2171 {
2172         arm_smmu_free_strtab(smmu);
2173         arm_smmu_free_queues(smmu);
2174 }
2175
2176 static int arm_smmu_write_reg_sync(struct arm_smmu_device *smmu, u32 val,
2177                                    unsigned int reg_off, unsigned int ack_off)
2178 {
2179         u32 reg;
2180
2181         writel_relaxed(val, smmu->base + reg_off);
2182         return readl_relaxed_poll_timeout(smmu->base + ack_off, reg, reg == val,
2183                                           1, ARM_SMMU_POLL_TIMEOUT_US);
2184 }
2185
2186 static int arm_smmu_setup_irqs(struct arm_smmu_device *smmu)
2187 {
2188         int ret, irq;
2189         u32 irqen_flags = IRQ_CTRL_EVTQ_IRQEN | IRQ_CTRL_GERROR_IRQEN;
2190
2191         /* Disable IRQs first */
2192         ret = arm_smmu_write_reg_sync(smmu, 0, ARM_SMMU_IRQ_CTRL,
2193                                       ARM_SMMU_IRQ_CTRLACK);
2194         if (ret) {
2195                 dev_err(smmu->dev, "failed to disable irqs\n");
2196                 return ret;
2197         }
2198
2199         /* Clear the MSI address regs */
2200         writeq_relaxed(0, smmu->base + ARM_SMMU_GERROR_IRQ_CFG0);
2201         writeq_relaxed(0, smmu->base + ARM_SMMU_EVTQ_IRQ_CFG0);
2202
2203         /* Request wired interrupt lines */
2204         irq = smmu->evtq.q.irq;
2205         if (irq) {
2206                 ret = devm_request_threaded_irq(smmu->dev, irq,
2207                                                 arm_smmu_evtq_handler,
2208                                                 arm_smmu_evtq_thread,
2209                                                 0, "arm-smmu-v3-evtq", smmu);
2210                 if (IS_ERR_VALUE(ret))
2211                         dev_warn(smmu->dev, "failed to enable evtq irq\n");
2212         }
2213
2214         irq = smmu->cmdq.q.irq;
2215         if (irq) {
2216                 ret = devm_request_irq(smmu->dev, irq,
2217                                        arm_smmu_cmdq_sync_handler, 0,
2218                                        "arm-smmu-v3-cmdq-sync", smmu);
2219                 if (IS_ERR_VALUE(ret))
2220                         dev_warn(smmu->dev, "failed to enable cmdq-sync irq\n");
2221         }
2222
2223         irq = smmu->gerr_irq;
2224         if (irq) {
2225                 ret = devm_request_irq(smmu->dev, irq, arm_smmu_gerror_handler,
2226                                        0, "arm-smmu-v3-gerror", smmu);
2227                 if (IS_ERR_VALUE(ret))
2228                         dev_warn(smmu->dev, "failed to enable gerror irq\n");
2229         }
2230
2231         if (smmu->features & ARM_SMMU_FEAT_PRI) {
2232                 writeq_relaxed(0, smmu->base + ARM_SMMU_PRIQ_IRQ_CFG0);
2233
2234                 irq = smmu->priq.q.irq;
2235                 if (irq) {
2236                         ret = devm_request_threaded_irq(smmu->dev, irq,
2237                                                         arm_smmu_priq_handler,
2238                                                         arm_smmu_priq_thread,
2239                                                         0, "arm-smmu-v3-priq",
2240                                                         smmu);
2241                         if (IS_ERR_VALUE(ret))
2242                                 dev_warn(smmu->dev,
2243                                          "failed to enable priq irq\n");
2244                         else
2245                                 irqen_flags |= IRQ_CTRL_PRIQ_IRQEN;
2246                 }
2247         }
2248
2249         /* Enable interrupt generation on the SMMU */
2250         ret = arm_smmu_write_reg_sync(smmu, irqen_flags,
2251                                       ARM_SMMU_IRQ_CTRL, ARM_SMMU_IRQ_CTRLACK);
2252         if (ret)
2253                 dev_warn(smmu->dev, "failed to enable irqs\n");
2254
2255         return 0;
2256 }
2257
2258 static int arm_smmu_device_disable(struct arm_smmu_device *smmu)
2259 {
2260         int ret;
2261
2262         ret = arm_smmu_write_reg_sync(smmu, 0, ARM_SMMU_CR0, ARM_SMMU_CR0ACK);
2263         if (ret)
2264                 dev_err(smmu->dev, "failed to clear cr0\n");
2265
2266         return ret;
2267 }
2268
2269 static int arm_smmu_device_reset(struct arm_smmu_device *smmu)
2270 {
2271         int ret;
2272         u32 reg, enables;
2273         struct arm_smmu_cmdq_ent cmd;
2274
2275         /* Clear CR0 and sync (disables SMMU and queue processing) */
2276         reg = readl_relaxed(smmu->base + ARM_SMMU_CR0);
2277         if (reg & CR0_SMMUEN)
2278                 dev_warn(smmu->dev, "SMMU currently enabled! Resetting...\n");
2279
2280         ret = arm_smmu_device_disable(smmu);
2281         if (ret)
2282                 return ret;
2283
2284         /* CR1 (table and queue memory attributes) */
2285         reg = (CR1_SH_ISH << CR1_TABLE_SH_SHIFT) |
2286               (CR1_CACHE_WB << CR1_TABLE_OC_SHIFT) |
2287               (CR1_CACHE_WB << CR1_TABLE_IC_SHIFT) |
2288               (CR1_SH_ISH << CR1_QUEUE_SH_SHIFT) |
2289               (CR1_CACHE_WB << CR1_QUEUE_OC_SHIFT) |
2290               (CR1_CACHE_WB << CR1_QUEUE_IC_SHIFT);
2291         writel_relaxed(reg, smmu->base + ARM_SMMU_CR1);
2292
2293         /* CR2 (random crap) */
2294         reg = CR2_PTM | CR2_RECINVSID | CR2_E2H;
2295         writel_relaxed(reg, smmu->base + ARM_SMMU_CR2);
2296
2297         /* Stream table */
2298         writeq_relaxed(smmu->strtab_cfg.strtab_base,
2299                        smmu->base + ARM_SMMU_STRTAB_BASE);
2300         writel_relaxed(smmu->strtab_cfg.strtab_base_cfg,
2301                        smmu->base + ARM_SMMU_STRTAB_BASE_CFG);
2302
2303         /* Command queue */
2304         writeq_relaxed(smmu->cmdq.q.q_base, smmu->base + ARM_SMMU_CMDQ_BASE);
2305         writel_relaxed(smmu->cmdq.q.prod, smmu->base + ARM_SMMU_CMDQ_PROD);
2306         writel_relaxed(smmu->cmdq.q.cons, smmu->base + ARM_SMMU_CMDQ_CONS);
2307
2308         enables = CR0_CMDQEN;
2309         ret = arm_smmu_write_reg_sync(smmu, enables, ARM_SMMU_CR0,
2310                                       ARM_SMMU_CR0ACK);
2311         if (ret) {
2312                 dev_err(smmu->dev, "failed to enable command queue\n");
2313                 return ret;
2314         }
2315
2316         /* Invalidate any cached configuration */
2317         cmd.opcode = CMDQ_OP_CFGI_ALL;
2318         arm_smmu_cmdq_issue_cmd(smmu, &cmd);
2319         cmd.opcode = CMDQ_OP_CMD_SYNC;
2320         arm_smmu_cmdq_issue_cmd(smmu, &cmd);
2321
2322         /* Invalidate any stale TLB entries */
2323         if (smmu->features & ARM_SMMU_FEAT_HYP) {
2324                 cmd.opcode = CMDQ_OP_TLBI_EL2_ALL;
2325                 arm_smmu_cmdq_issue_cmd(smmu, &cmd);
2326         }
2327
2328         cmd.opcode = CMDQ_OP_TLBI_NSNH_ALL;
2329         arm_smmu_cmdq_issue_cmd(smmu, &cmd);
2330         cmd.opcode = CMDQ_OP_CMD_SYNC;
2331         arm_smmu_cmdq_issue_cmd(smmu, &cmd);
2332
2333         /* Event queue */
2334         writeq_relaxed(smmu->evtq.q.q_base, smmu->base + ARM_SMMU_EVTQ_BASE);
2335         writel_relaxed(smmu->evtq.q.prod, smmu->base + ARM_SMMU_EVTQ_PROD);
2336         writel_relaxed(smmu->evtq.q.cons, smmu->base + ARM_SMMU_EVTQ_CONS);
2337
2338         enables |= CR0_EVTQEN;
2339         ret = arm_smmu_write_reg_sync(smmu, enables, ARM_SMMU_CR0,
2340                                       ARM_SMMU_CR0ACK);
2341         if (ret) {
2342                 dev_err(smmu->dev, "failed to enable event queue\n");
2343                 return ret;
2344         }
2345
2346         /* PRI queue */
2347         if (smmu->features & ARM_SMMU_FEAT_PRI) {
2348                 writeq_relaxed(smmu->priq.q.q_base,
2349                                smmu->base + ARM_SMMU_PRIQ_BASE);
2350                 writel_relaxed(smmu->priq.q.prod,
2351                                smmu->base + ARM_SMMU_PRIQ_PROD);
2352                 writel_relaxed(smmu->priq.q.cons,
2353                                smmu->base + ARM_SMMU_PRIQ_CONS);
2354
2355                 enables |= CR0_PRIQEN;
2356                 ret = arm_smmu_write_reg_sync(smmu, enables, ARM_SMMU_CR0,
2357                                               ARM_SMMU_CR0ACK);
2358                 if (ret) {
2359                         dev_err(smmu->dev, "failed to enable PRI queue\n");
2360                         return ret;
2361                 }
2362         }
2363
2364         ret = arm_smmu_setup_irqs(smmu);
2365         if (ret) {
2366                 dev_err(smmu->dev, "failed to setup irqs\n");
2367                 return ret;
2368         }
2369
2370         /* Enable the SMMU interface */
2371         enables |= CR0_SMMUEN;
2372         ret = arm_smmu_write_reg_sync(smmu, enables, ARM_SMMU_CR0,
2373                                       ARM_SMMU_CR0ACK);
2374         if (ret) {
2375                 dev_err(smmu->dev, "failed to enable SMMU interface\n");
2376                 return ret;
2377         }
2378
2379         return 0;
2380 }
2381
2382 static int arm_smmu_device_probe(struct arm_smmu_device *smmu)
2383 {
2384         u32 reg;
2385         bool coherent;
2386         unsigned long pgsize_bitmap = 0;
2387
2388         /* IDR0 */
2389         reg = readl_relaxed(smmu->base + ARM_SMMU_IDR0);
2390
2391         /* 2-level structures */
2392         if ((reg & IDR0_ST_LVL_MASK << IDR0_ST_LVL_SHIFT) == IDR0_ST_LVL_2LVL)
2393                 smmu->features |= ARM_SMMU_FEAT_2_LVL_STRTAB;
2394
2395         if (reg & IDR0_CD2L)
2396                 smmu->features |= ARM_SMMU_FEAT_2_LVL_CDTAB;
2397
2398         /*
2399          * Translation table endianness.
2400          * We currently require the same endianness as the CPU, but this
2401          * could be changed later by adding a new IO_PGTABLE_QUIRK.
2402          */
2403         switch (reg & IDR0_TTENDIAN_MASK << IDR0_TTENDIAN_SHIFT) {
2404         case IDR0_TTENDIAN_MIXED:
2405                 smmu->features |= ARM_SMMU_FEAT_TT_LE | ARM_SMMU_FEAT_TT_BE;
2406                 break;
2407 #ifdef __BIG_ENDIAN
2408         case IDR0_TTENDIAN_BE:
2409                 smmu->features |= ARM_SMMU_FEAT_TT_BE;
2410                 break;
2411 #else
2412         case IDR0_TTENDIAN_LE:
2413                 smmu->features |= ARM_SMMU_FEAT_TT_LE;
2414                 break;
2415 #endif
2416         default:
2417                 dev_err(smmu->dev, "unknown/unsupported TT endianness!\n");
2418                 return -ENXIO;
2419         }
2420
2421         /* Boolean feature flags */
2422         if (IS_ENABLED(CONFIG_PCI_PRI) && reg & IDR0_PRI)
2423                 smmu->features |= ARM_SMMU_FEAT_PRI;
2424
2425         if (IS_ENABLED(CONFIG_PCI_ATS) && reg & IDR0_ATS)
2426                 smmu->features |= ARM_SMMU_FEAT_ATS;
2427
2428         if (reg & IDR0_SEV)
2429                 smmu->features |= ARM_SMMU_FEAT_SEV;
2430
2431         if (reg & IDR0_MSI)
2432                 smmu->features |= ARM_SMMU_FEAT_MSI;
2433
2434         if (reg & IDR0_HYP)
2435                 smmu->features |= ARM_SMMU_FEAT_HYP;
2436
2437         /*
2438          * The dma-coherent property is used in preference to the ID
2439          * register, but warn on mismatch.
2440          */
2441         coherent = of_dma_is_coherent(smmu->dev->of_node);
2442         if (coherent)
2443                 smmu->features |= ARM_SMMU_FEAT_COHERENCY;
2444
2445         if (!!(reg & IDR0_COHACC) != coherent)
2446                 dev_warn(smmu->dev, "IDR0.COHACC overridden by dma-coherent property (%s)\n",
2447                          coherent ? "true" : "false");
2448
2449         if (reg & IDR0_STALL_MODEL)
2450                 smmu->features |= ARM_SMMU_FEAT_STALLS;
2451
2452         if (reg & IDR0_S1P)
2453                 smmu->features |= ARM_SMMU_FEAT_TRANS_S1;
2454
2455         if (reg & IDR0_S2P)
2456                 smmu->features |= ARM_SMMU_FEAT_TRANS_S2;
2457
2458         if (!(reg & (IDR0_S1P | IDR0_S2P))) {
2459                 dev_err(smmu->dev, "no translation support!\n");
2460                 return -ENXIO;
2461         }
2462
2463         /* We only support the AArch64 table format at present */
2464         if ((reg & IDR0_TTF_MASK << IDR0_TTF_SHIFT) < IDR0_TTF_AARCH64) {
2465                 dev_err(smmu->dev, "AArch64 table format not supported!\n");
2466                 return -ENXIO;
2467         }
2468
2469         /* ASID/VMID sizes */
2470         smmu->asid_bits = reg & IDR0_ASID16 ? 16 : 8;
2471         smmu->vmid_bits = reg & IDR0_VMID16 ? 16 : 8;
2472
2473         /* IDR1 */
2474         reg = readl_relaxed(smmu->base + ARM_SMMU_IDR1);
2475         if (reg & (IDR1_TABLES_PRESET | IDR1_QUEUES_PRESET | IDR1_REL)) {
2476                 dev_err(smmu->dev, "embedded implementation not supported\n");
2477                 return -ENXIO;
2478         }
2479
2480         /* Queue sizes, capped at 4k */
2481         smmu->cmdq.q.max_n_shift = min((u32)CMDQ_MAX_SZ_SHIFT,
2482                                        reg >> IDR1_CMDQ_SHIFT & IDR1_CMDQ_MASK);
2483         if (!smmu->cmdq.q.max_n_shift) {
2484                 /* Odd alignment restrictions on the base, so ignore for now */
2485                 dev_err(smmu->dev, "unit-length command queue not supported\n");
2486                 return -ENXIO;
2487         }
2488
2489         smmu->evtq.q.max_n_shift = min((u32)EVTQ_MAX_SZ_SHIFT,
2490                                        reg >> IDR1_EVTQ_SHIFT & IDR1_EVTQ_MASK);
2491         smmu->priq.q.max_n_shift = min((u32)PRIQ_MAX_SZ_SHIFT,
2492                                        reg >> IDR1_PRIQ_SHIFT & IDR1_PRIQ_MASK);
2493
2494         /* SID/SSID sizes */
2495         smmu->ssid_bits = reg >> IDR1_SSID_SHIFT & IDR1_SSID_MASK;
2496         smmu->sid_bits = reg >> IDR1_SID_SHIFT & IDR1_SID_MASK;
2497
2498         /* IDR5 */
2499         reg = readl_relaxed(smmu->base + ARM_SMMU_IDR5);
2500
2501         /* Maximum number of outstanding stalls */
2502         smmu->evtq.max_stalls = reg >> IDR5_STALL_MAX_SHIFT
2503                                 & IDR5_STALL_MAX_MASK;
2504
2505         /* Page sizes */
2506         if (reg & IDR5_GRAN64K)
2507                 pgsize_bitmap |= SZ_64K | SZ_512M;
2508         if (reg & IDR5_GRAN16K)
2509                 pgsize_bitmap |= SZ_16K | SZ_32M;
2510         if (reg & IDR5_GRAN4K)
2511                 pgsize_bitmap |= SZ_4K | SZ_2M | SZ_1G;
2512
2513         arm_smmu_ops.pgsize_bitmap &= pgsize_bitmap;
2514
2515         /* Output address size */
2516         switch (reg & IDR5_OAS_MASK << IDR5_OAS_SHIFT) {
2517         case IDR5_OAS_32_BIT:
2518                 smmu->oas = 32;
2519                 break;
2520         case IDR5_OAS_36_BIT:
2521                 smmu->oas = 36;
2522                 break;
2523         case IDR5_OAS_40_BIT:
2524                 smmu->oas = 40;
2525                 break;
2526         case IDR5_OAS_42_BIT:
2527                 smmu->oas = 42;
2528                 break;
2529         case IDR5_OAS_44_BIT:
2530                 smmu->oas = 44;
2531                 break;
2532         default:
2533                 dev_info(smmu->dev,
2534                         "unknown output address size. Truncating to 48-bit\n");
2535                 /* Fallthrough */
2536         case IDR5_OAS_48_BIT:
2537                 smmu->oas = 48;
2538         }
2539
2540         /* Set the DMA mask for our table walker */
2541         if (dma_set_mask_and_coherent(smmu->dev, DMA_BIT_MASK(smmu->oas)))
2542                 dev_warn(smmu->dev,
2543                          "failed to set DMA mask for table walker\n");
2544
2545         if (!smmu->ias)
2546                 smmu->ias = smmu->oas;
2547
2548         dev_info(smmu->dev, "ias %lu-bit, oas %lu-bit (features 0x%08x)\n",
2549                  smmu->ias, smmu->oas, smmu->features);
2550         return 0;
2551 }
2552
2553 static int arm_smmu_device_dt_probe(struct platform_device *pdev)
2554 {
2555         int irq, ret;
2556         struct resource *res;
2557         struct arm_smmu_device *smmu;
2558         struct device *dev = &pdev->dev;
2559
2560         smmu = devm_kzalloc(dev, sizeof(*smmu), GFP_KERNEL);
2561         if (!smmu) {
2562                 dev_err(dev, "failed to allocate arm_smmu_device\n");
2563                 return -ENOMEM;
2564         }
2565         smmu->dev = dev;
2566
2567         /* Base address */
2568         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
2569         if (resource_size(res) + 1 < SZ_128K) {
2570                 dev_err(dev, "MMIO region too small (%pr)\n", res);
2571                 return -EINVAL;
2572         }
2573
2574         smmu->base = devm_ioremap_resource(dev, res);
2575         if (IS_ERR(smmu->base))
2576                 return PTR_ERR(smmu->base);
2577
2578         /* Interrupt lines */
2579         irq = platform_get_irq_byname(pdev, "eventq");
2580         if (irq > 0)
2581                 smmu->evtq.q.irq = irq;
2582
2583         irq = platform_get_irq_byname(pdev, "priq");
2584         if (irq > 0)
2585                 smmu->priq.q.irq = irq;
2586
2587         irq = platform_get_irq_byname(pdev, "cmdq-sync");
2588         if (irq > 0)
2589                 smmu->cmdq.q.irq = irq;
2590
2591         irq = platform_get_irq_byname(pdev, "gerror");
2592         if (irq > 0)
2593                 smmu->gerr_irq = irq;
2594
2595         parse_driver_options(smmu);
2596
2597         /* Probe the h/w */
2598         ret = arm_smmu_device_probe(smmu);
2599         if (ret)
2600                 return ret;
2601
2602         /* Initialise in-memory data structures */
2603         ret = arm_smmu_init_structures(smmu);
2604         if (ret)
2605                 return ret;
2606
2607         /* Reset the device */
2608         ret = arm_smmu_device_reset(smmu);
2609         if (ret)
2610                 goto out_free_structures;
2611
2612         /* Record our private device structure */
2613         INIT_LIST_HEAD(&smmu->list);
2614         spin_lock(&arm_smmu_devices_lock);
2615         list_add(&smmu->list, &arm_smmu_devices);
2616         spin_unlock(&arm_smmu_devices_lock);
2617         return 0;
2618
2619 out_free_structures:
2620         arm_smmu_free_structures(smmu);
2621         return ret;
2622 }
2623
2624 static int arm_smmu_device_remove(struct platform_device *pdev)
2625 {
2626         struct arm_smmu_device *curr, *smmu = NULL;
2627         struct device *dev = &pdev->dev;
2628
2629         spin_lock(&arm_smmu_devices_lock);
2630         list_for_each_entry(curr, &arm_smmu_devices, list) {
2631                 if (curr->dev == dev) {
2632                         smmu = curr;
2633                         list_del(&smmu->list);
2634                         break;
2635                 }
2636         }
2637         spin_unlock(&arm_smmu_devices_lock);
2638
2639         if (!smmu)
2640                 return -ENODEV;
2641
2642         arm_smmu_device_disable(smmu);
2643         arm_smmu_free_structures(smmu);
2644         return 0;
2645 }
2646
2647 static struct of_device_id arm_smmu_of_match[] = {
2648         { .compatible = "arm,smmu-v3", },
2649         { },
2650 };
2651 MODULE_DEVICE_TABLE(of, arm_smmu_of_match);
2652
2653 static struct platform_driver arm_smmu_driver = {
2654         .driver = {
2655                 .name           = "arm-smmu-v3",
2656                 .of_match_table = of_match_ptr(arm_smmu_of_match),
2657         },
2658         .probe  = arm_smmu_device_dt_probe,
2659         .remove = arm_smmu_device_remove,
2660 };
2661
2662 static int __init arm_smmu_init(void)
2663 {
2664         struct device_node *np;
2665         int ret;
2666
2667         np = of_find_matching_node(NULL, arm_smmu_of_match);
2668         if (!np)
2669                 return 0;
2670
2671         of_node_put(np);
2672
2673         ret = platform_driver_register(&arm_smmu_driver);
2674         if (ret)
2675                 return ret;
2676
2677         return bus_set_iommu(&pci_bus_type, &arm_smmu_ops);
2678 }
2679
2680 static void __exit arm_smmu_exit(void)
2681 {
2682         return platform_driver_unregister(&arm_smmu_driver);
2683 }
2684
2685 subsys_initcall(arm_smmu_init);
2686 module_exit(arm_smmu_exit);
2687
2688 MODULE_DESCRIPTION("IOMMU API for ARM architected SMMUv3 implementations");
2689 MODULE_AUTHOR("Will Deacon <will.deacon@arm.com>");
2690 MODULE_LICENSE("GPL v2");