Debian Codegraph @

drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c

raw
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * IOMMU API for ARM architected SMMUv3 implementations.
4 *
5 * Copyright (C) 2015 ARM Limited
6 *
7 * Author: Will Deacon <[email protected]>
8 *
9 * This driver is powered by bad coffee and bombay mix.
10 */
11
12 #include <linux/acpi.h>
13 #include <linux/acpi_iort.h>
14 #include <linux/bitops.h>
15 #include <linux/crash_dump.h>
16 #include <linux/delay.h>
17 #include <linux/err.h>
18 #include <linux/interrupt.h>
19 #include <linux/io-pgtable.h>
20 #include <linux/iopoll.h>
21 #include <linux/module.h>
22 #include <linux/msi.h>
23 #include <linux/of.h>
24 #include <linux/of_address.h>
25 #include <linux/of_platform.h>
26 #include <linux/pci.h>
27 #include <linux/pci-ats.h>
28 #include <linux/platform_device.h>
29 #include <linux/string_choices.h>
30 #include <kunit/visibility.h>
31 #include <uapi/linux/iommufd.h>
32
33 #include "arm-smmu-v3.h"
34 #include "../../dma-iommu.h"
35
36 static bool disable_msipolling;
37 module_param(disable_msipolling, bool, 0444);
38 MODULE_PARM_DESC(disable_msipolling,
39 "Disable MSI-based polling for CMD_SYNC completion.");
40
41 static const struct iommu_ops arm_smmu_ops;
42 static struct iommu_dirty_ops arm_smmu_dirty_ops;
43
44 enum arm_smmu_msi_index {
45 EVTQ_MSI_INDEX,
46 GERROR_MSI_INDEX,
47 PRIQ_MSI_INDEX,
48 ARM_SMMU_MAX_MSIS,
49 };
50
51 #define NUM_ENTRY_QWORDS 8
52 static_assert(sizeof(struct arm_smmu_ste) == NUM_ENTRY_QWORDS * sizeof(u64));
53 static_assert(sizeof(struct arm_smmu_cd) == NUM_ENTRY_QWORDS * sizeof(u64));
54
55 static phys_addr_t arm_smmu_msi_cfg[ARM_SMMU_MAX_MSIS][3] = {
56 [EVTQ_MSI_INDEX] = {
57 ARM_SMMU_EVTQ_IRQ_CFG0,
58 ARM_SMMU_EVTQ_IRQ_CFG1,
59 ARM_SMMU_EVTQ_IRQ_CFG2,
60 },
61 [GERROR_MSI_INDEX] = {
62 ARM_SMMU_GERROR_IRQ_CFG0,
63 ARM_SMMU_GERROR_IRQ_CFG1,
64 ARM_SMMU_GERROR_IRQ_CFG2,
65 },
66 [PRIQ_MSI_INDEX] = {
67 ARM_SMMU_PRIQ_IRQ_CFG0,
68 ARM_SMMU_PRIQ_IRQ_CFG1,
69 ARM_SMMU_PRIQ_IRQ_CFG2,
70 },
71 };
72
73 struct arm_smmu_option_prop {
74 u32 opt;
75 const char *prop;
76 };
77
78 DEFINE_XARRAY_ALLOC1(arm_smmu_asid_xa);
79 DEFINE_MUTEX(arm_smmu_asid_lock);
80
81 static struct arm_smmu_option_prop arm_smmu_options[] = {
82 { ARM_SMMU_OPT_SKIP_PREFETCH, "hisilicon,broken-prefetch-cmd" },
83 { ARM_SMMU_OPT_PAGE0_REGS_ONLY, "cavium,cn9900-broken-page1-regspace"},
84 { 0, NULL},
85 };
86
87 static const char * const event_str[] = {
88 [EVT_ID_BAD_STREAMID_CONFIG] = "C_BAD_STREAMID",
89 [EVT_ID_STE_FETCH_FAULT] = "F_STE_FETCH",
90 [EVT_ID_BAD_STE_CONFIG] = "C_BAD_STE",
91 [EVT_ID_STREAM_DISABLED_FAULT] = "F_STREAM_DISABLED",
92 [EVT_ID_BAD_SUBSTREAMID_CONFIG] = "C_BAD_SUBSTREAMID",
93 [EVT_ID_CD_FETCH_FAULT] = "F_CD_FETCH",
94 [EVT_ID_BAD_CD_CONFIG] = "C_BAD_CD",
95 [EVT_ID_TRANSLATION_FAULT] = "F_TRANSLATION",
96 [EVT_ID_ADDR_SIZE_FAULT] = "F_ADDR_SIZE",
97 [EVT_ID_ACCESS_FAULT] = "F_ACCESS",
98 [EVT_ID_PERMISSION_FAULT] = "F_PERMISSION",
99 [EVT_ID_VMS_FETCH_FAULT] = "F_VMS_FETCH",
100 };
101
102 static const char * const event_class_str[] = {
103 [0] = "CD fetch",
104 [1] = "Stage 1 translation table fetch",
105 [2] = "Input address caused fault",
106 [3] = "Reserved",
107 };
108
109 static int arm_smmu_alloc_cd_tables(struct arm_smmu_master *master);
110
111 static void parse_driver_options(struct arm_smmu_device *smmu)
112 {
113 int i = 0;
114
115 do {
116 if (of_property_read_bool(smmu->dev->of_node,
117 arm_smmu_options[i].prop)) {
118 smmu->options |= arm_smmu_options[i].opt;
119 dev_notice(smmu->dev, "option %s\n",
120 arm_smmu_options[i].prop);
121 }
122 } while (arm_smmu_options[++i].opt);
123 }
124
125 /* Low-level queue manipulation functions */
126 static bool queue_has_space(struct arm_smmu_ll_queue *q, u32 n)
127 {
128 u32 space, prod, cons;
129
130 prod = Q_IDX(q, q->prod);
131 cons = Q_IDX(q, q->cons);
132
133 if (Q_WRP(q, q->prod) == Q_WRP(q, q->cons))
134 space = (1 << q->max_n_shift) - (prod - cons);
135 else
136 space = cons - prod;
137
138 return space >= n;
139 }
140
141 static bool queue_full(struct arm_smmu_ll_queue *q)
142 {
143 return Q_IDX(q, q->prod) == Q_IDX(q, q->cons) &&
144 Q_WRP(q, q->prod) != Q_WRP(q, q->cons);
145 }
146
147 static bool queue_empty(struct arm_smmu_ll_queue *q)
148 {
149 return Q_IDX(q, q->prod) == Q_IDX(q, q->cons) &&
150 Q_WRP(q, q->prod) == Q_WRP(q, q->cons);
151 }
152
153 static bool queue_consumed(struct arm_smmu_ll_queue *q, u32 prod)
154 {
155 return ((Q_WRP(q, q->cons) == Q_WRP(q, prod)) &&
156 (Q_IDX(q, q->cons) > Q_IDX(q, prod))) ||
157 ((Q_WRP(q, q->cons) != Q_WRP(q, prod)) &&
158 (Q_IDX(q, q->cons) <= Q_IDX(q, prod)));
159 }
160
161 static void queue_sync_cons_out(struct arm_smmu_queue *q)
162 {
163 /*
164 * Ensure that all CPU accesses (reads and writes) to the queue
165 * are complete before we update the cons pointer.
166 */
167 __iomb();
168 writel_relaxed(q->llq.cons, q->cons_reg);
169 }
170
171 static void queue_inc_cons(struct arm_smmu_ll_queue *q)
172 {
173 u32 cons = (Q_WRP(q, q->cons) | Q_IDX(q, q->cons)) + 1;
174 q->cons = Q_OVF(q->cons) | Q_WRP(q, cons) | Q_IDX(q, cons);
175 }
176
177 static void queue_sync_cons_ovf(struct arm_smmu_queue *q)
178 {
179 struct arm_smmu_ll_queue *llq = &q->llq;
180
181 if (likely(Q_OVF(llq->prod) == Q_OVF(llq->cons)))
182 return;
183
184 llq->cons = Q_OVF(llq->prod) | Q_WRP(llq, llq->cons) |
185 Q_IDX(llq, llq->cons);
186 queue_sync_cons_out(q);
187 }
188
189 static int queue_sync_prod_in(struct arm_smmu_queue *q)
190 {
191 u32 prod;
192 int ret = 0;
193
194 /*
195 * We can't use the _relaxed() variant here, as we must prevent
196 * speculative reads of the queue before we have determined that
197 * prod has indeed moved.
198 */
199 prod = readl(q->prod_reg);
200
201 if (Q_OVF(prod) != Q_OVF(q->llq.prod))
202 ret = -EOVERFLOW;
203
204 q->llq.prod = prod;
205 return ret;
206 }
207
208 static u32 queue_inc_prod_n(struct arm_smmu_ll_queue *q, int n)
209 {
210 u32 prod = (Q_WRP(q, q->prod) | Q_IDX(q, q->prod)) + n;
211 return Q_OVF(q->prod) | Q_WRP(q, prod) | Q_IDX(q, prod);
212 }
213
214 static void queue_poll_init(struct arm_smmu_device *smmu,
215 struct arm_smmu_queue_poll *qp)
216 {
217 qp->delay = 1;
218 qp->spin_cnt = 0;
219 qp->wfe = !!(smmu->features & ARM_SMMU_FEAT_SEV);
220 qp->timeout = ktime_add_us(ktime_get(), ARM_SMMU_POLL_TIMEOUT_US);
221 }
222
223 static int queue_poll(struct arm_smmu_queue_poll *qp)
224 {
225 if (ktime_compare(ktime_get(), qp->timeout) > 0)
226 return -ETIMEDOUT;
227
228 if (qp->wfe) {
229 wfe();
230 } else if (++qp->spin_cnt < ARM_SMMU_POLL_SPIN_COUNT) {
231 cpu_relax();
232 } else {
233 udelay(qp->delay);
234 qp->delay *= 2;
235 qp->spin_cnt = 0;
236 }
237
238 return 0;
239 }
240
241 static void queue_write(__le64 *dst, u64 *src, size_t n_dwords)
242 {
243 int i;
244
245 for (i = 0; i < n_dwords; ++i)
246 *dst++ = cpu_to_le64(*src++);
247 }
248
249 static void queue_read(u64 *dst, __le64 *src, size_t n_dwords)
250 {
251 int i;
252
253 for (i = 0; i < n_dwords; ++i)
254 *dst++ = le64_to_cpu(*src++);
255 }
256
257 static int queue_remove_raw(struct arm_smmu_queue *q, u64 *ent)
258 {
259 if (queue_empty(&q->llq))
260 return -EAGAIN;
261
262 queue_read(ent, Q_ENT(q, q->llq.cons), q->ent_dwords);
263 queue_inc_cons(&q->llq);
264 queue_sync_cons_out(q);
265 return 0;
266 }
267
268 /* High-level queue accessors */
269 static int arm_smmu_cmdq_build_cmd(u64 *cmd, struct arm_smmu_cmdq_ent *ent)
270 {
271 memset(cmd, 0, 1 << CMDQ_ENT_SZ_SHIFT);
272 cmd[0] |= FIELD_PREP(CMDQ_0_OP, ent->opcode);
273
274 switch (ent->opcode) {
275 case CMDQ_OP_TLBI_EL2_ALL:
276 case CMDQ_OP_TLBI_NSNH_ALL:
277 break;
278 case CMDQ_OP_PREFETCH_CFG:
279 cmd[0] |= FIELD_PREP(CMDQ_PREFETCH_0_SID, ent->prefetch.sid);
280 break;
281 case CMDQ_OP_CFGI_CD:
282 cmd[0] |= FIELD_PREP(CMDQ_CFGI_0_SSID, ent->cfgi.ssid);
283 fallthrough;
284 case CMDQ_OP_CFGI_STE:
285 cmd[0] |= FIELD_PREP(CMDQ_CFGI_0_SID, ent->cfgi.sid);
286 cmd[1] |= FIELD_PREP(CMDQ_CFGI_1_LEAF, ent->cfgi.leaf);
287 break;
288 case CMDQ_OP_CFGI_CD_ALL:
289 cmd[0] |= FIELD_PREP(CMDQ_CFGI_0_SID, ent->cfgi.sid);
290 break;
291 case CMDQ_OP_CFGI_ALL:
292 /* Cover the entire SID range */
293 cmd[1] |= FIELD_PREP(CMDQ_CFGI_1_RANGE, 31);
294 break;
295 case CMDQ_OP_TLBI_NH_VA:
296 cmd[0] |= FIELD_PREP(CMDQ_TLBI_0_VMID, ent->tlbi.vmid);
297 fallthrough;
298 case CMDQ_OP_TLBI_EL2_VA:
299 cmd[0] |= FIELD_PREP(CMDQ_TLBI_0_NUM, ent->tlbi.num);
300 cmd[0] |= FIELD_PREP(CMDQ_TLBI_0_SCALE, ent->tlbi.scale);
301 cmd[0] |= FIELD_PREP(CMDQ_TLBI_0_ASID, ent->tlbi.asid);
302 cmd[1] |= FIELD_PREP(CMDQ_TLBI_1_LEAF, ent->tlbi.leaf);
303 cmd[1] |= FIELD_PREP(CMDQ_TLBI_1_TTL, ent->tlbi.ttl);
304 cmd[1] |= FIELD_PREP(CMDQ_TLBI_1_TG, ent->tlbi.tg);
305 cmd[1] |= ent->tlbi.addr & CMDQ_TLBI_1_VA_MASK;
306 break;
307 case CMDQ_OP_TLBI_S2_IPA:
308 cmd[0] |= FIELD_PREP(CMDQ_TLBI_0_NUM, ent->tlbi.num);
309 cmd[0] |= FIELD_PREP(CMDQ_TLBI_0_SCALE, ent->tlbi.scale);
310 cmd[0] |= FIELD_PREP(CMDQ_TLBI_0_VMID, ent->tlbi.vmid);
311 cmd[1] |= FIELD_PREP(CMDQ_TLBI_1_LEAF, ent->tlbi.leaf);
312 cmd[1] |= FIELD_PREP(CMDQ_TLBI_1_TTL, ent->tlbi.ttl);
313 cmd[1] |= FIELD_PREP(CMDQ_TLBI_1_TG, ent->tlbi.tg);
314 cmd[1] |= ent->tlbi.addr & CMDQ_TLBI_1_IPA_MASK;
315 break;
316 case CMDQ_OP_TLBI_NH_ASID:
317 cmd[0] |= FIELD_PREP(CMDQ_TLBI_0_ASID, ent->tlbi.asid);
318 fallthrough;
319 case CMDQ_OP_TLBI_NH_ALL:
320 case CMDQ_OP_TLBI_S12_VMALL:
321 cmd[0] |= FIELD_PREP(CMDQ_TLBI_0_VMID, ent->tlbi.vmid);
322 break;
323 case CMDQ_OP_TLBI_EL2_ASID:
324 cmd[0] |= FIELD_PREP(CMDQ_TLBI_0_ASID, ent->tlbi.asid);
325 break;
326 case CMDQ_OP_ATC_INV:
327 cmd[0] |= FIELD_PREP(CMDQ_0_SSV, ent->substream_valid);
328 cmd[0] |= FIELD_PREP(CMDQ_ATC_0_GLOBAL, ent->atc.global);
329 cmd[0] |= FIELD_PREP(CMDQ_ATC_0_SSID, ent->atc.ssid);
330 cmd[0] |= FIELD_PREP(CMDQ_ATC_0_SID, ent->atc.sid);
331 cmd[1] |= FIELD_PREP(CMDQ_ATC_1_SIZE, ent->atc.size);
332 cmd[1] |= ent->atc.addr & CMDQ_ATC_1_ADDR_MASK;
333 break;
334 case CMDQ_OP_PRI_RESP:
335 cmd[0] |= FIELD_PREP(CMDQ_0_SSV, ent->substream_valid);
336 cmd[0] |= FIELD_PREP(CMDQ_PRI_0_SSID, ent->pri.ssid);
337 cmd[0] |= FIELD_PREP(CMDQ_PRI_0_SID, ent->pri.sid);
338 cmd[1] |= FIELD_PREP(CMDQ_PRI_1_GRPID, ent->pri.grpid);
339 switch (ent->pri.resp) {
340 case PRI_RESP_DENY:
341 case PRI_RESP_FAIL:
342 case PRI_RESP_SUCC:
343 break;
344 default:
345 return -EINVAL;
346 }
347 cmd[1] |= FIELD_PREP(CMDQ_PRI_1_RESP, ent->pri.resp);
348 break;
349 case CMDQ_OP_RESUME:
350 cmd[0] |= FIELD_PREP(CMDQ_RESUME_0_SID, ent->resume.sid);
351 cmd[0] |= FIELD_PREP(CMDQ_RESUME_0_RESP, ent->resume.resp);
352 cmd[1] |= FIELD_PREP(CMDQ_RESUME_1_STAG, ent->resume.stag);
353 break;
354 case CMDQ_OP_CMD_SYNC:
355 if (ent->sync.msiaddr) {
356 cmd[0] |= FIELD_PREP(CMDQ_SYNC_0_CS, CMDQ_SYNC_0_CS_IRQ);
357 cmd[1] |= ent->sync.msiaddr & CMDQ_SYNC_1_MSIADDR_MASK;
358 } else {
359 cmd[0] |= FIELD_PREP(CMDQ_SYNC_0_CS, CMDQ_SYNC_0_CS_SEV);
360 }
361 cmd[0] |= FIELD_PREP(CMDQ_SYNC_0_MSH, ARM_SMMU_SH_ISH);
362 cmd[0] |= FIELD_PREP(CMDQ_SYNC_0_MSIATTR, ARM_SMMU_MEMATTR_OIWB);
363 break;
364 default:
365 return -ENOENT;
366 }
367
368 return 0;
369 }
370
371 static struct arm_smmu_cmdq *arm_smmu_get_cmdq(struct arm_smmu_device *smmu,
372 struct arm_smmu_cmdq_ent *ent)
373 {
374 struct arm_smmu_cmdq *cmdq = NULL;
375
376 if (smmu->impl_ops && smmu->impl_ops->get_secondary_cmdq)
377 cmdq = smmu->impl_ops->get_secondary_cmdq(smmu, ent);
378
379 return cmdq ?: &smmu->cmdq;
380 }
381
382 static bool arm_smmu_cmdq_needs_busy_polling(struct arm_smmu_device *smmu,
383 struct arm_smmu_cmdq *cmdq)
384 {
385 if (cmdq == &smmu->cmdq)
386 return false;
387
388 return smmu->options & ARM_SMMU_OPT_TEGRA241_CMDQV;
389 }
390
391 static void arm_smmu_cmdq_build_sync_cmd(u64 *cmd, struct arm_smmu_device *smmu,
392 struct arm_smmu_cmdq *cmdq, u32 prod)
393 {
394 struct arm_smmu_queue *q = &cmdq->q;
395 struct arm_smmu_cmdq_ent ent = {
396 .opcode = CMDQ_OP_CMD_SYNC,
397 };
398
399 /*
400 * Beware that Hi16xx adds an extra 32 bits of goodness to its MSI
401 * payload, so the write will zero the entire command on that platform.
402 */
403 if (smmu->options & ARM_SMMU_OPT_MSIPOLL) {
404 ent.sync.msiaddr = q->base_dma + Q_IDX(&q->llq, prod) *
405 q->ent_dwords * 8;
406 }
407
408 arm_smmu_cmdq_build_cmd(cmd, &ent);
409 if (arm_smmu_cmdq_needs_busy_polling(smmu, cmdq))
410 u64p_replace_bits(cmd, CMDQ_SYNC_0_CS_NONE, CMDQ_SYNC_0_CS);
411 }
412
413 void __arm_smmu_cmdq_skip_err(struct arm_smmu_device *smmu,
414 struct arm_smmu_cmdq *cmdq)
415 {
416 static const char * const cerror_str[] = {
417 [CMDQ_ERR_CERROR_NONE_IDX] = "No error",
418 [CMDQ_ERR_CERROR_ILL_IDX] = "Illegal command",
419 [CMDQ_ERR_CERROR_ABT_IDX] = "Abort on command fetch",
420 [CMDQ_ERR_CERROR_ATC_INV_IDX] = "ATC invalidate timeout",
421 };
422 struct arm_smmu_queue *q = &cmdq->q;
423
424 int i;
425 u64 cmd[CMDQ_ENT_DWORDS];
426 u32 cons = readl_relaxed(q->cons_reg);
427 u32 idx = FIELD_GET(CMDQ_CONS_ERR, cons);
428 struct arm_smmu_cmdq_ent cmd_sync = {
429 .opcode = CMDQ_OP_CMD_SYNC,
430 };
431
432 dev_err(smmu->dev, "CMDQ error (cons 0x%08x): %s\n", cons,
433 idx < ARRAY_SIZE(cerror_str) ? cerror_str[idx] : "Unknown");
434
435 switch (idx) {
436 case CMDQ_ERR_CERROR_ABT_IDX:
437 dev_err(smmu->dev, "retrying command fetch\n");
438 return;
439 case CMDQ_ERR_CERROR_NONE_IDX:
440 return;
441 case CMDQ_ERR_CERROR_ATC_INV_IDX:
442 /*
443 * ATC Invalidation Completion timeout. CONS is still pointing
444 * at the CMD_SYNC. Attempt to complete other pending commands
445 * by repeating the CMD_SYNC, though we might well end up back
446 * here since the ATC invalidation may still be pending.
447 */
448 return;
449 case CMDQ_ERR_CERROR_ILL_IDX:
450 default:
451 break;
452 }
453
454 /*
455 * We may have concurrent producers, so we need to be careful
456 * not to touch any of the shadow cmdq state.
457 */
458 queue_read(cmd, Q_ENT(q, cons), q->ent_dwords);
459 dev_err(smmu->dev, "skipping command in error state:\n");
460 for (i = 0; i < ARRAY_SIZE(cmd); ++i)
461 dev_err(smmu->dev, "\t0x%016llx\n", (unsigned long long)cmd[i]);
462
463 /* Convert the erroneous command into a CMD_SYNC */
464 arm_smmu_cmdq_build_cmd(cmd, &cmd_sync);
465 if (arm_smmu_cmdq_needs_busy_polling(smmu, cmdq))
466 u64p_replace_bits(cmd, CMDQ_SYNC_0_CS_NONE, CMDQ_SYNC_0_CS);
467
468 queue_write(Q_ENT(q, cons), cmd, q->ent_dwords);
469 }
470
471 static void arm_smmu_cmdq_skip_err(struct arm_smmu_device *smmu)
472 {
473 __arm_smmu_cmdq_skip_err(smmu, &smmu->cmdq);
474 }
475
476 /*
477 * Command queue locking.
478 * This is a form of bastardised rwlock with the following major changes:
479 *
480 * - The only LOCK routines are exclusive_trylock() and shared_lock().
481 * Neither have barrier semantics, and instead provide only a control
482 * dependency.
483 *
484 * - The UNLOCK routines are supplemented with shared_tryunlock(), which
485 * fails if the caller appears to be the last lock holder (yes, this is
486 * racy). All successful UNLOCK routines have RELEASE semantics.
487 */
488 static void arm_smmu_cmdq_shared_lock(struct arm_smmu_cmdq *cmdq)
489 {
490 /*
491 * When held in exclusive state, the lock counter is set to INT_MIN
492 * so these increments won't hurt as the value will remain negative.
493 * The increment will also signal the exclusive locker that there are
494 * shared waiters.
495 */
496 if (atomic_fetch_inc_relaxed(&cmdq->lock) >= 0)
497 return;
498
499 /*
500 * Someone else is holding the lock in exclusive state, so wait
501 * for them to finish. Since we already incremented the lock counter,
502 * no exclusive lock can be acquired until we finish. We don't need
503 * the return value since we only care that the exclusive lock is
504 * released (i.e. the lock counter is non-negative).
505 * Once the exclusive locker releases the lock, the sign bit will
506 * be cleared and our increment will make the lock counter positive,
507 * allowing us to proceed.
508 */
509 atomic_cond_read_relaxed(&cmdq->lock, VAL > 0);
510 }
511
512 static void arm_smmu_cmdq_shared_unlock(struct arm_smmu_cmdq *cmdq)
513 {
514 (void)atomic_dec_return_release(&cmdq->lock);
515 }
516
517 static bool arm_smmu_cmdq_shared_tryunlock(struct arm_smmu_cmdq *cmdq)
518 {
519 if (atomic_read(&cmdq->lock) == 1)
520 return false;
521
522 arm_smmu_cmdq_shared_unlock(cmdq);
523 return true;
524 }
525
526 #define arm_smmu_cmdq_exclusive_trylock_irqsave(cmdq, flags) \
527 ({ \
528 bool __ret; \
529 local_irq_save(flags); \
530 __ret = !atomic_cmpxchg_relaxed(&cmdq->lock, 0, INT_MIN); \
531 if (!__ret) \
532 local_irq_restore(flags); \
533 __ret; \
534 })
535
536 /*
537 * Only clear the sign bit when releasing the exclusive lock this will
538 * allow any shared_lock() waiters to proceed without the possibility
539 * of entering the exclusive lock in a tight loop.
540 */
541 #define arm_smmu_cmdq_exclusive_unlock_irqrestore(cmdq, flags) \
542 ({ \
543 atomic_fetch_andnot_release(INT_MIN, &cmdq->lock); \
544 local_irq_restore(flags); \
545 })
546
547
548 /*
549 * Command queue insertion.
550 * This is made fiddly by our attempts to achieve some sort of scalability
551 * since there is one queue shared amongst all of the CPUs in the system. If
552 * you like mixed-size concurrency, dependency ordering and relaxed atomics,
553 * then you'll *love* this monstrosity.
554 *
555 * The basic idea is to split the queue up into ranges of commands that are
556 * owned by a given CPU; the owner may not have written all of the commands
557 * itself, but is responsible for advancing the hardware prod pointer when
558 * the time comes. The algorithm is roughly:
559 *
560 * 1. Allocate some space in the queue. At this point we also discover
561 * whether the head of the queue is currently owned by another CPU,
562 * or whether we are the owner.
563 *
564 * 2. Write our commands into our allocated slots in the queue.
565 *
566 * 3. Mark our slots as valid in arm_smmu_cmdq.valid_map.
567 *
568 * 4. If we are an owner:
569 * a. Wait for the previous owner to finish.
570 * b. Mark the queue head as unowned, which tells us the range
571 * that we are responsible for publishing.
572 * c. Wait for all commands in our owned range to become valid.
573 * d. Advance the hardware prod pointer.
574 * e. Tell the next owner we've finished.
575 *
576 * 5. If we are inserting a CMD_SYNC (we may or may not have been an
577 * owner), then we need to stick around until it has completed:
578 * a. If we have MSIs, the SMMU can write back into the CMD_SYNC
579 * to clear the first 4 bytes.
580 * b. Otherwise, we spin waiting for the hardware cons pointer to
581 * advance past our command.
582 *
583 * The devil is in the details, particularly the use of locking for handling
584 * SYNC completion and freeing up space in the queue before we think that it is
585 * full.
586 */
587 static void __arm_smmu_cmdq_poll_set_valid_map(struct arm_smmu_cmdq *cmdq,
588 u32 sprod, u32 eprod, bool set)
589 {
590 u32 swidx, sbidx, ewidx, ebidx;
591 struct arm_smmu_ll_queue llq = {
592 .max_n_shift = cmdq->q.llq.max_n_shift,
593 .prod = sprod,
594 };
595
596 ewidx = BIT_WORD(Q_IDX(&llq, eprod));
597 ebidx = Q_IDX(&llq, eprod) % BITS_PER_LONG;
598
599 while (llq.prod != eprod) {
600 unsigned long mask;
601 atomic_long_t *ptr;
602 u32 limit = BITS_PER_LONG;
603
604 swidx = BIT_WORD(Q_IDX(&llq, llq.prod));
605 sbidx = Q_IDX(&llq, llq.prod) % BITS_PER_LONG;
606
607 ptr = &cmdq->valid_map[swidx];
608
609 if ((swidx == ewidx) && (sbidx < ebidx))
610 limit = ebidx;
611
612 mask = GENMASK(limit - 1, sbidx);
613
614 /*
615 * The valid bit is the inverse of the wrap bit. This means
616 * that a zero-initialised queue is invalid and, after marking
617 * all entries as valid, they become invalid again when we
618 * wrap.
619 */
620 if (set) {
621 atomic_long_xor(mask, ptr);
622 } else { /* Poll */
623 unsigned long valid;
624
625 valid = (ULONG_MAX + !!Q_WRP(&llq, llq.prod)) & mask;
626 atomic_long_cond_read_relaxed(ptr, (VAL & mask) == valid);
627 }
628
629 llq.prod = queue_inc_prod_n(&llq, limit - sbidx);
630 }
631 }
632
633 /* Mark all entries in the range [sprod, eprod) as valid */
634 static void arm_smmu_cmdq_set_valid_map(struct arm_smmu_cmdq *cmdq,
635 u32 sprod, u32 eprod)
636 {
637 __arm_smmu_cmdq_poll_set_valid_map(cmdq, sprod, eprod, true);
638 }
639
640 /* Wait for all entries in the range [sprod, eprod) to become valid */
641 static void arm_smmu_cmdq_poll_valid_map(struct arm_smmu_cmdq *cmdq,
642 u32 sprod, u32 eprod)
643 {
644 __arm_smmu_cmdq_poll_set_valid_map(cmdq, sprod, eprod, false);
645 }
646
647 /* Wait for the command queue to become non-full */
648 static int arm_smmu_cmdq_poll_until_not_full(struct arm_smmu_device *smmu,
649 struct arm_smmu_cmdq *cmdq,
650 struct arm_smmu_ll_queue *llq)
651 {
652 unsigned long flags;
653 struct arm_smmu_queue_poll qp;
654 int ret = 0;
655
656 /*
657 * Try to update our copy of cons by grabbing exclusive cmdq access. If
658 * that fails, spin until somebody else updates it for us.
659 */
660 if (arm_smmu_cmdq_exclusive_trylock_irqsave(cmdq, flags)) {
661 WRITE_ONCE(cmdq->q.llq.cons, readl_relaxed(cmdq->q.cons_reg));
662 arm_smmu_cmdq_exclusive_unlock_irqrestore(cmdq, flags);
663 llq->val = READ_ONCE(cmdq->q.llq.val);
664 return 0;
665 }
666
667 queue_poll_init(smmu, &qp);
668 do {
669 llq->val = READ_ONCE(cmdq->q.llq.val);
670 if (!queue_full(llq))
671 break;
672
673 ret = queue_poll(&qp);
674 } while (!ret);
675
676 return ret;
677 }
678
679 /*
680 * Wait until the SMMU signals a CMD_SYNC completion MSI.
681 * Must be called with the cmdq lock held in some capacity.
682 */
683 static int __arm_smmu_cmdq_poll_until_msi(struct arm_smmu_device *smmu,
684 struct arm_smmu_cmdq *cmdq,
685 struct arm_smmu_ll_queue *llq)
686 {
687 int ret = 0;
688 struct arm_smmu_queue_poll qp;
689 u32 *cmd = (u32 *)(Q_ENT(&cmdq->q, llq->prod));
690
691 queue_poll_init(smmu, &qp);
692
693 /*
694 * The MSI won't generate an event, since it's being written back
695 * into the command queue.
696 */
697 qp.wfe = false;
698 smp_cond_load_relaxed(cmd, !VAL || (ret = queue_poll(&qp)));
699 llq->cons = ret ? llq->prod : queue_inc_prod_n(llq, 1);
700 return ret;
701 }
702
703 /*
704 * Wait until the SMMU cons index passes llq->prod.
705 * Must be called with the cmdq lock held in some capacity.
706 */
707 static int __arm_smmu_cmdq_poll_until_consumed(struct arm_smmu_device *smmu,
708 struct arm_smmu_cmdq *cmdq,
709 struct arm_smmu_ll_queue *llq)
710 {
711 struct arm_smmu_queue_poll qp;
712 u32 prod = llq->prod;
713 int ret = 0;
714
715 queue_poll_init(smmu, &qp);
716 llq->val = READ_ONCE(cmdq->q.llq.val);
717 do {
718 if (queue_consumed(llq, prod))
719 break;
720
721 ret = queue_poll(&qp);
722
723 /*
724 * This needs to be a readl() so that our subsequent call
725 * to arm_smmu_cmdq_shared_tryunlock() can fail accurately.
726 *
727 * Specifically, we need to ensure that we observe all
728 * shared_lock()s by other CMD_SYNCs that share our owner,
729 * so that a failing call to tryunlock() means that we're
730 * the last one out and therefore we can safely advance
731 * cmdq->q.llq.cons. Roughly speaking:
732 *
733 * CPU 0 CPU1 CPU2 (us)
734 *
735 * if (sync)
736 * shared_lock();
737 *
738 * dma_wmb();
739 * set_valid_map();
740 *
741 * if (owner) {
742 * poll_valid_map();
743 * <control dependency>
744 * writel(prod_reg);
745 *
746 * readl(cons_reg);
747 * tryunlock();
748 *
749 * Requires us to see CPU 0's shared_lock() acquisition.
750 */
751 llq->cons = readl(cmdq->q.cons_reg);
752 } while (!ret);
753
754 return ret;
755 }
756
757 static int arm_smmu_cmdq_poll_until_sync(struct arm_smmu_device *smmu,
758 struct arm_smmu_cmdq *cmdq,
759 struct arm_smmu_ll_queue *llq)
760 {
761 if (smmu->options & ARM_SMMU_OPT_MSIPOLL &&
762 !arm_smmu_cmdq_needs_busy_polling(smmu, cmdq))
763 return __arm_smmu_cmdq_poll_until_msi(smmu, cmdq, llq);
764
765 return __arm_smmu_cmdq_poll_until_consumed(smmu, cmdq, llq);
766 }
767
768 static void arm_smmu_cmdq_write_entries(struct arm_smmu_cmdq *cmdq, u64 *cmds,
769 u32 prod, int n)
770 {
771 int i;
772 struct arm_smmu_ll_queue llq = {
773 .max_n_shift = cmdq->q.llq.max_n_shift,
774 .prod = prod,
775 };
776
777 for (i = 0; i < n; ++i) {
778 u64 *cmd = &cmds[i * CMDQ_ENT_DWORDS];
779
780 prod = queue_inc_prod_n(&llq, i);
781 queue_write(Q_ENT(&cmdq->q, prod), cmd, CMDQ_ENT_DWORDS);
782 }
783 }
784
785 /*
786 * This is the actual insertion function, and provides the following
787 * ordering guarantees to callers:
788 *
789 * - There is a dma_wmb() before publishing any commands to the queue.
790 * This can be relied upon to order prior writes to data structures
791 * in memory (such as a CD or an STE) before the command.
792 *
793 * - On completion of a CMD_SYNC, there is a control dependency.
794 * This can be relied upon to order subsequent writes to memory (e.g.
795 * freeing an IOVA) after completion of the CMD_SYNC.
796 *
797 * - Command insertion is totally ordered, so if two CPUs each race to
798 * insert their own list of commands then all of the commands from one
799 * CPU will appear before any of the commands from the other CPU.
800 */
801 int arm_smmu_cmdq_issue_cmdlist(struct arm_smmu_device *smmu,
802 struct arm_smmu_cmdq *cmdq, u64 *cmds, int n,
803 bool sync)
804 {
805 u64 cmd_sync[CMDQ_ENT_DWORDS];
806 u32 prod;
807 unsigned long flags;
808 bool owner;
809 struct arm_smmu_ll_queue llq, head;
810 int ret = 0;
811
812 llq.max_n_shift = cmdq->q.llq.max_n_shift;
813
814 /* 1. Allocate some space in the queue */
815 local_irq_save(flags);
816 llq.val = READ_ONCE(cmdq->q.llq.val);
817 do {
818 u64 old;
819
820 while (!queue_has_space(&llq, n + sync)) {
821 local_irq_restore(flags);
822 if (arm_smmu_cmdq_poll_until_not_full(smmu, cmdq, &llq))
823 dev_err_ratelimited(smmu->dev, "CMDQ timeout\n");
824 local_irq_save(flags);
825 }
826
827 head.cons = llq.cons;
828 head.prod = queue_inc_prod_n(&llq, n + sync) |
829 CMDQ_PROD_OWNED_FLAG;
830
831 old = cmpxchg_relaxed(&cmdq->q.llq.val, llq.val, head.val);
832 if (old == llq.val)
833 break;
834
835 llq.val = old;
836 } while (1);
837 owner = !(llq.prod & CMDQ_PROD_OWNED_FLAG);
838 head.prod &= ~CMDQ_PROD_OWNED_FLAG;
839 llq.prod &= ~CMDQ_PROD_OWNED_FLAG;
840
841 /*
842 * 2. Write our commands into the queue
843 * Dependency ordering from the cmpxchg() loop above.
844 */
845 arm_smmu_cmdq_write_entries(cmdq, cmds, llq.prod, n);
846 if (sync) {
847 prod = queue_inc_prod_n(&llq, n);
848 arm_smmu_cmdq_build_sync_cmd(cmd_sync, smmu, cmdq, prod);
849 queue_write(Q_ENT(&cmdq->q, prod), cmd_sync, CMDQ_ENT_DWORDS);
850
851 /*
852 * In order to determine completion of our CMD_SYNC, we must
853 * ensure that the queue can't wrap twice without us noticing.
854 * We achieve that by taking the cmdq lock as shared before
855 * marking our slot as valid.
856 */
857 arm_smmu_cmdq_shared_lock(cmdq);
858 }
859
860 /* 3. Mark our slots as valid, ensuring commands are visible first */
861 dma_wmb();
862 arm_smmu_cmdq_set_valid_map(cmdq, llq.prod, head.prod);
863
864 /* 4. If we are the owner, take control of the SMMU hardware */
865 if (owner) {
866 /* a. Wait for previous owner to finish */
867 atomic_cond_read_relaxed(&cmdq->owner_prod, VAL == llq.prod);
868
869 /* b. Stop gathering work by clearing the owned flag */
870 prod = atomic_fetch_andnot_relaxed(CMDQ_PROD_OWNED_FLAG,
871 &cmdq->q.llq.atomic.prod);
872 prod &= ~CMDQ_PROD_OWNED_FLAG;
873
874 /*
875 * c. Wait for any gathered work to be written to the queue.
876 * Note that we read our own entries so that we have the control
877 * dependency required by (d).
878 */
879 arm_smmu_cmdq_poll_valid_map(cmdq, llq.prod, prod);
880
881 /*
882 * d. Advance the hardware prod pointer
883 * Control dependency ordering from the entries becoming valid.
884 */
885 writel_relaxed(prod, cmdq->q.prod_reg);
886
887 /*
888 * e. Tell the next owner we're done
889 * Make sure we've updated the hardware first, so that we don't
890 * race to update prod and potentially move it backwards.
891 */
892 atomic_set_release(&cmdq->owner_prod, prod);
893 }
894
895 /* 5. If we are inserting a CMD_SYNC, we must wait for it to complete */
896 if (sync) {
897 llq.prod = queue_inc_prod_n(&llq, n);
898 ret = arm_smmu_cmdq_poll_until_sync(smmu, cmdq, &llq);
899 if (ret) {
900 dev_err_ratelimited(smmu->dev,
901 "CMD_SYNC timeout at 0x%08x [hwprod 0x%08x, hwcons 0x%08x]\n",
902 llq.prod,
903 readl_relaxed(cmdq->q.prod_reg),
904 readl_relaxed(cmdq->q.cons_reg));
905 }
906
907 /*
908 * Try to unlock the cmdq lock. This will fail if we're the last
909 * reader, in which case we can safely update cmdq->q.llq.cons
910 */
911 if (!arm_smmu_cmdq_shared_tryunlock(cmdq)) {
912 WRITE_ONCE(cmdq->q.llq.cons, llq.cons);
913 arm_smmu_cmdq_shared_unlock(cmdq);
914 }
915 }
916
917 local_irq_restore(flags);
918 return ret;
919 }
920
921 static int __arm_smmu_cmdq_issue_cmd(struct arm_smmu_device *smmu,
922 struct arm_smmu_cmdq_ent *ent,
923 bool sync)
924 {
925 u64 cmd[CMDQ_ENT_DWORDS];
926
927 if (unlikely(arm_smmu_cmdq_build_cmd(cmd, ent))) {
928 dev_warn(smmu->dev, "ignoring unknown CMDQ opcode 0x%x\n",
929 ent->opcode);
930 return -EINVAL;
931 }
932
933 return arm_smmu_cmdq_issue_cmdlist(
934 smmu, arm_smmu_get_cmdq(smmu, ent), cmd, 1, sync);
935 }
936
937 static int arm_smmu_cmdq_issue_cmd(struct arm_smmu_device *smmu,
938 struct arm_smmu_cmdq_ent *ent)
939 {
940 return __arm_smmu_cmdq_issue_cmd(smmu, ent, false);
941 }
942
943 static int arm_smmu_cmdq_issue_cmd_with_sync(struct arm_smmu_device *smmu,
944 struct arm_smmu_cmdq_ent *ent)
945 {
946 return __arm_smmu_cmdq_issue_cmd(smmu, ent, true);
947 }
948
949 static void arm_smmu_cmdq_batch_init(struct arm_smmu_device *smmu,
950 struct arm_smmu_cmdq_batch *cmds,
951 struct arm_smmu_cmdq_ent *ent)
952 {
953 cmds->num = 0;
954 cmds->cmdq = arm_smmu_get_cmdq(smmu, ent);
955 }
956
957 static void arm_smmu_cmdq_batch_add(struct arm_smmu_device *smmu,
958 struct arm_smmu_cmdq_batch *cmds,
959 struct arm_smmu_cmdq_ent *cmd)
960 {
961 bool unsupported_cmd = !arm_smmu_cmdq_supports_cmd(cmds->cmdq, cmd);
962 bool force_sync = (cmds->num == CMDQ_BATCH_ENTRIES - 1) &&
963 (smmu->options & ARM_SMMU_OPT_CMDQ_FORCE_SYNC);
964 int index;
965
966 if (force_sync || unsupported_cmd) {
967 arm_smmu_cmdq_issue_cmdlist(smmu, cmds->cmdq, cmds->cmds,
968 cmds->num, true);
969 arm_smmu_cmdq_batch_init(smmu, cmds, cmd);
970 }
971
972 if (cmds->num == CMDQ_BATCH_ENTRIES) {
973 arm_smmu_cmdq_issue_cmdlist(smmu, cmds->cmdq, cmds->cmds,
974 cmds->num, false);
975 arm_smmu_cmdq_batch_init(smmu, cmds, cmd);
976 }
977
978 index = cmds->num * CMDQ_ENT_DWORDS;
979 if (unlikely(arm_smmu_cmdq_build_cmd(&cmds->cmds[index], cmd))) {
980 dev_warn(smmu->dev, "ignoring unknown CMDQ opcode 0x%x\n",
981 cmd->opcode);
982 return;
983 }
984
985 cmds->num++;
986 }
987
988 static int arm_smmu_cmdq_batch_submit(struct arm_smmu_device *smmu,
989 struct arm_smmu_cmdq_batch *cmds)
990 {
991 return arm_smmu_cmdq_issue_cmdlist(smmu, cmds->cmdq, cmds->cmds,
992 cmds->num, true);
993 }
994
995 static void arm_smmu_page_response(struct device *dev, struct iopf_fault *unused,
996 struct iommu_page_response *resp)
997 {
998 struct arm_smmu_cmdq_ent cmd = {0};
999 struct arm_smmu_master *master = dev_iommu_priv_get(dev);
1000 int sid = master->streams[0].id;
1001
1002 if (WARN_ON(!master->stall_enabled))
1003 return;
1004
1005 cmd.opcode = CMDQ_OP_RESUME;
1006 cmd.resume.sid = sid;
1007 cmd.resume.stag = resp->grpid;
1008 switch (resp->code) {
1009 case IOMMU_PAGE_RESP_INVALID:
1010 case IOMMU_PAGE_RESP_FAILURE:
1011 cmd.resume.resp = CMDQ_RESUME_0_RESP_ABORT;
1012 break;
1013 case IOMMU_PAGE_RESP_SUCCESS:
1014 cmd.resume.resp = CMDQ_RESUME_0_RESP_RETRY;
1015 break;
1016 default:
1017 break;
1018 }
1019
1020 arm_smmu_cmdq_issue_cmd(master->smmu, &cmd);
1021 /*
1022 * Don't send a SYNC, it doesn't do anything for RESUME or PRI_RESP.
1023 * RESUME consumption guarantees that the stalled transaction will be
1024 * terminated... at some point in the future. PRI_RESP is fire and
1025 * forget.
1026 */
1027 }
1028
1029 /* Context descriptor manipulation functions */
1030 void arm_smmu_tlb_inv_asid(struct arm_smmu_device *smmu, u16 asid)
1031 {
1032 struct arm_smmu_cmdq_ent cmd = {
1033 .opcode = smmu->features & ARM_SMMU_FEAT_E2H ?
1034 CMDQ_OP_TLBI_EL2_ASID : CMDQ_OP_TLBI_NH_ASID,
1035 .tlbi.asid = asid,
1036 };
1037
1038 arm_smmu_cmdq_issue_cmd_with_sync(smmu, &cmd);
1039 }
1040
1041 /*
1042 * Based on the value of ent report which bits of the STE the HW will access. It
1043 * would be nice if this was complete according to the spec, but minimally it
1044 * has to capture the bits this driver uses.
1045 */
1046 VISIBLE_IF_KUNIT
1047 void arm_smmu_get_ste_used(const __le64 *ent, __le64 *used_bits)
1048 {
1049 unsigned int cfg = FIELD_GET(STRTAB_STE_0_CFG, le64_to_cpu(ent[0]));
1050
1051 used_bits[0] = cpu_to_le64(STRTAB_STE_0_V);
1052 if (!(ent[0] & cpu_to_le64(STRTAB_STE_0_V)))
1053 return;
1054
1055 used_bits[0] |= cpu_to_le64(STRTAB_STE_0_CFG);
1056
1057 /* S1 translates */
1058 if (cfg & BIT(0)) {
1059 used_bits[0] |= cpu_to_le64(STRTAB_STE_0_S1FMT |
1060 STRTAB_STE_0_S1CTXPTR_MASK |
1061 STRTAB_STE_0_S1CDMAX);
1062 used_bits[1] |=
1063 cpu_to_le64(STRTAB_STE_1_S1DSS | STRTAB_STE_1_S1CIR |
1064 STRTAB_STE_1_S1COR | STRTAB_STE_1_S1CSH |
1065 STRTAB_STE_1_S1STALLD | STRTAB_STE_1_STRW |
1066 STRTAB_STE_1_EATS | STRTAB_STE_1_MEV);
1067 used_bits[2] |= cpu_to_le64(STRTAB_STE_2_S2VMID);
1068
1069 /*
1070 * See 13.5 Summary of attribute/permission configuration fields
1071 * for the SHCFG behavior.
1072 */
1073 if (FIELD_GET(STRTAB_STE_1_S1DSS, le64_to_cpu(ent[1])) ==
1074 STRTAB_STE_1_S1DSS_BYPASS)
1075 used_bits[1] |= cpu_to_le64(STRTAB_STE_1_SHCFG);
1076 }
1077
1078 /* S2 translates */
1079 if (cfg & BIT(1)) {
1080 used_bits[1] |=
1081 cpu_to_le64(STRTAB_STE_1_S2FWB | STRTAB_STE_1_EATS |
1082 STRTAB_STE_1_SHCFG | STRTAB_STE_1_MEV);
1083 used_bits[2] |=
1084 cpu_to_le64(STRTAB_STE_2_S2VMID | STRTAB_STE_2_VTCR |
1085 STRTAB_STE_2_S2AA64 | STRTAB_STE_2_S2ENDI |
1086 STRTAB_STE_2_S2PTW | STRTAB_STE_2_S2S |
1087 STRTAB_STE_2_S2R);
1088 used_bits[3] |= cpu_to_le64(STRTAB_STE_3_S2TTB_MASK);
1089 }
1090
1091 if (cfg == STRTAB_STE_0_CFG_BYPASS)
1092 used_bits[1] |= cpu_to_le64(STRTAB_STE_1_SHCFG);
1093 }
1094 EXPORT_SYMBOL_IF_KUNIT(arm_smmu_get_ste_used);
1095
1096 VISIBLE_IF_KUNIT
1097 void arm_smmu_get_ste_update_safe(const __le64 *cur, const __le64 *target,
1098 __le64 *safe_bits)
1099 {
1100 const __le64 eats_s1chk =
1101 FIELD_PREP(STRTAB_STE_1_EATS, STRTAB_STE_1_EATS_S1CHK);
1102 const __le64 eats_trans =
1103 FIELD_PREP(STRTAB_STE_1_EATS, STRTAB_STE_1_EATS_TRANS);
1104
1105 /*
1106 * When an STE changes EATS_TRANS, the sequencing code in the attach
1107 * logic already will have the PCI cap for ATS disabled. Thus at this
1108 * moment we can expect that the device will not generate ATS queries
1109 * and so we don't care about the sequencing of EATS. The purpose of
1110 * EATS_TRANS is to protect the system from hostile untrusted devices
1111 * that issue ATS when the PCI config space is disabled. However, if
1112 * EATS_TRANS is being changed, then we must have already trusted the
1113 * device as the EATS_TRANS security block is being disabled.
1114 *
1115 * Note: now the EATS_TRANS update is moved to the first entry_set().
1116 * Changing S2S and EATS might transiently result in S2S=1 and EATS=1
1117 * which is a bad STE (see "5.2 Stream Table Entry"). In such a case,
1118 * we can't do a hitless update. Also, it should not be added to the
1119 * safe bits with STRTAB_STE_1_EATS_S1CHK, because EATS=0b11 would be
1120 * effectively an errant 0b00 configuration.
1121 */
1122 if (!((cur[1] | target[1]) & cpu_to_le64(eats_s1chk)) &&
1123 !((cur[2] | target[2]) & cpu_to_le64(STRTAB_STE_2_S2S)))
1124 safe_bits[1] |= cpu_to_le64(eats_trans);
1125
1126 /*
1127 * MEV does not meaningfully impact the operation of the HW, it only
1128 * changes how many fault events are generated, thus we can relax it
1129 * when computing the ordering. The spec notes the device can act like
1130 * MEV=1 anyhow:
1131 *
1132 * Note: Software must expect, and be able to deal with, coalesced
1133 * fault records even when MEV == 0.
1134 */
1135 safe_bits[1] |= cpu_to_le64(STRTAB_STE_1_MEV);
1136 }
1137 EXPORT_SYMBOL_IF_KUNIT(arm_smmu_get_ste_update_safe);
1138
1139 /*
1140 * Figure out if we can do a hitless update of entry to become target. Returns a
1141 * bit mask where 1 indicates that qword needs to be set disruptively.
1142 * unused_update is an intermediate value of entry that has unused bits set to
1143 * their new values.
1144 */
1145 static u8 arm_smmu_entry_qword_diff(struct arm_smmu_entry_writer *writer,
1146 const __le64 *entry, const __le64 *target,
1147 __le64 *unused_update)
1148 {
1149 __le64 target_used[NUM_ENTRY_QWORDS] = {};
1150 __le64 cur_used[NUM_ENTRY_QWORDS] = {};
1151 __le64 safe[NUM_ENTRY_QWORDS] = {};
1152 u8 used_qword_diff = 0;
1153 unsigned int i;
1154
1155 writer->ops->get_used(entry, cur_used);
1156 writer->ops->get_used(target, target_used);
1157 if (writer->ops->get_update_safe)
1158 writer->ops->get_update_safe(entry, target, safe);
1159
1160 for (i = 0; i != NUM_ENTRY_QWORDS; i++) {
1161 /*
1162 * Safe is only used for bits that are used by both entries,
1163 * otherwise it is sequenced according to the unused entry.
1164 */
1165 safe[i] &= target_used[i] & cur_used[i];
1166
1167 /*
1168 * Check that masks are up to date, the make functions are not
1169 * allowed to set a bit to 1 if the used function doesn't say it
1170 * is used.
1171 */
1172 WARN_ON_ONCE(target[i] & ~target_used[i]);
1173
1174 /* Bits can change because they are not currently being used */
1175 cur_used[i] &= ~safe[i];
1176 unused_update[i] = (entry[i] & cur_used[i]) |
1177 (target[i] & ~cur_used[i]);
1178 /*
1179 * Each bit indicates that a used bit in a qword needs to be
1180 * changed after unused_update is applied.
1181 */
1182 if ((unused_update[i] & target_used[i]) != target[i])
1183 used_qword_diff |= 1 << i;
1184 }
1185 return used_qword_diff;
1186 }
1187
1188 static void entry_set(struct arm_smmu_entry_writer *writer, __le64 *entry,
1189 const __le64 *target, unsigned int start,
1190 unsigned int len)
1191 {
1192 bool changed = false;
1193 unsigned int i;
1194
1195 for (i = start; len != 0; len--, i++) {
1196 if (entry[i] != target[i]) {
1197 WRITE_ONCE(entry[i], target[i]);
1198 changed = true;
1199 }
1200 }
1201
1202 if (changed)
1203 writer->ops->sync(writer);
1204 }
1205
1206 /*
1207 * Update the STE/CD to the target configuration. The transition from the
1208 * current entry to the target entry takes place over multiple steps that
1209 * attempts to make the transition hitless if possible. This function takes care
1210 * not to create a situation where the HW can perceive a corrupted entry. HW is
1211 * only required to have a 64 bit atomicity with stores from the CPU, while
1212 * entries are many 64 bit values big.
1213 *
1214 * The difference between the current value and the target value is analyzed to
1215 * determine which of three updates are required - disruptive, hitless or no
1216 * change.
1217 *
1218 * In the most general disruptive case we can make any update in three steps:
1219 * - Disrupting the entry (V=0)
1220 * - Fill now unused qwords, execpt qword 0 which contains V
1221 * - Make qword 0 have the final value and valid (V=1) with a single 64
1222 * bit store
1223 *
1224 * However this disrupts the HW while it is happening. There are several
1225 * interesting cases where a STE/CD can be updated without disturbing the HW
1226 * because only a small number of bits are changing (S1DSS, CONFIG, etc) or
1227 * because the used bits don't intersect. We can detect this by calculating how
1228 * many 64 bit values need update after adjusting the unused bits and skip the
1229 * V=0 process. This relies on the IGNORED behavior described in the
1230 * specification.
1231 */
1232 VISIBLE_IF_KUNIT
1233 void arm_smmu_write_entry(struct arm_smmu_entry_writer *writer, __le64 *entry,
1234 const __le64 *target)
1235 {
1236 __le64 unused_update[NUM_ENTRY_QWORDS];
1237 u8 used_qword_diff;
1238
1239 /*
1240 * Many of the entry structures have pointers to other structures that
1241 * need to have their updates be visible before any writes of the entry
1242 * happen.
1243 */
1244 dma_wmb();
1245
1246 used_qword_diff =
1247 arm_smmu_entry_qword_diff(writer, entry, target, unused_update);
1248 if (hweight8(used_qword_diff) == 1) {
1249 /*
1250 * Only one qword needs its used bits to be changed. This is a
1251 * hitless update, update all bits the current STE/CD is
1252 * ignoring to their new values, then update a single "critical
1253 * qword" to change the STE/CD and finally 0 out any bits that
1254 * are now unused in the target configuration.
1255 */
1256 unsigned int critical_qword_index = ffs(used_qword_diff) - 1;
1257
1258 /*
1259 * Skip writing unused bits in the critical qword since we'll be
1260 * writing it in the next step anyways. This can save a sync
1261 * when the only change is in that qword.
1262 */
1263 unused_update[critical_qword_index] =
1264 entry[critical_qword_index];
1265 entry_set(writer, entry, unused_update, 0, NUM_ENTRY_QWORDS);
1266 entry_set(writer, entry, target, critical_qword_index, 1);
1267 entry_set(writer, entry, target, 0, NUM_ENTRY_QWORDS);
1268 } else if (used_qword_diff) {
1269 /*
1270 * At least two qwords need their inuse bits to be changed. This
1271 * requires a breaking update, zero the V bit, write all qwords
1272 * but 0, then set qword 0
1273 */
1274 unused_update[0] = 0;
1275 entry_set(writer, entry, unused_update, 0, 1);
1276 entry_set(writer, entry, target, 1, NUM_ENTRY_QWORDS - 1);
1277 entry_set(writer, entry, target, 0, 1);
1278 } else {
1279 /*
1280 * No inuse bit changed, though safe bits may have changed.
1281 */
1282 entry_set(writer, entry, target, 0, NUM_ENTRY_QWORDS);
1283 }
1284 }
1285 EXPORT_SYMBOL_IF_KUNIT(arm_smmu_write_entry);
1286
1287 static void arm_smmu_sync_cd(struct arm_smmu_master *master,
1288 int ssid, bool leaf)
1289 {
1290 size_t i;
1291 struct arm_smmu_cmdq_batch cmds;
1292 struct arm_smmu_device *smmu = master->smmu;
1293 struct arm_smmu_cmdq_ent cmd = {
1294 .opcode = CMDQ_OP_CFGI_CD,
1295 .cfgi = {
1296 .ssid = ssid,
1297 .leaf = leaf,
1298 },
1299 };
1300
1301 arm_smmu_cmdq_batch_init(smmu, &cmds, &cmd);
1302 for (i = 0; i < master->num_streams; i++) {
1303 cmd.cfgi.sid = master->streams[i].id;
1304 arm_smmu_cmdq_batch_add(smmu, &cmds, &cmd);
1305 }
1306
1307 arm_smmu_cmdq_batch_submit(smmu, &cmds);
1308 }
1309
1310 static void arm_smmu_write_cd_l1_desc(struct arm_smmu_cdtab_l1 *dst,
1311 dma_addr_t l2ptr_dma)
1312 {
1313 u64 val = (l2ptr_dma & CTXDESC_L1_DESC_L2PTR_MASK) | CTXDESC_L1_DESC_V;
1314
1315 /* The HW has 64 bit atomicity with stores to the L2 CD table */
1316 WRITE_ONCE(dst->l2ptr, cpu_to_le64(val));
1317 }
1318
1319 static dma_addr_t arm_smmu_cd_l1_get_desc(const struct arm_smmu_cdtab_l1 *src)
1320 {
1321 return le64_to_cpu(src->l2ptr) & CTXDESC_L1_DESC_L2PTR_MASK;
1322 }
1323
1324 struct arm_smmu_cd *arm_smmu_get_cd_ptr(struct arm_smmu_master *master,
1325 u32 ssid)
1326 {
1327 struct arm_smmu_cdtab_l2 *l2;
1328 struct arm_smmu_ctx_desc_cfg *cd_table = &master->cd_table;
1329
1330 if (!arm_smmu_cdtab_allocated(cd_table))
1331 return NULL;
1332
1333 if (cd_table->s1fmt == STRTAB_STE_0_S1FMT_LINEAR)
1334 return &cd_table->linear.table[ssid];
1335
1336 l2 = cd_table->l2.l2ptrs[arm_smmu_cdtab_l1_idx(ssid)];
1337 if (!l2)
1338 return NULL;
1339 return &l2->cds[arm_smmu_cdtab_l2_idx(ssid)];
1340 }
1341
1342 static struct arm_smmu_cd *arm_smmu_alloc_cd_ptr(struct arm_smmu_master *master,
1343 u32 ssid)
1344 {
1345 struct arm_smmu_ctx_desc_cfg *cd_table = &master->cd_table;
1346 struct arm_smmu_device *smmu = master->smmu;
1347
1348 might_sleep();
1349 iommu_group_mutex_assert(master->dev);
1350
1351 if (!arm_smmu_cdtab_allocated(cd_table)) {
1352 if (arm_smmu_alloc_cd_tables(master))
1353 return NULL;
1354 }
1355
1356 if (cd_table->s1fmt == STRTAB_STE_0_S1FMT_64K_L2) {
1357 unsigned int idx = arm_smmu_cdtab_l1_idx(ssid);
1358 struct arm_smmu_cdtab_l2 **l2ptr = &cd_table->l2.l2ptrs[idx];
1359
1360 if (!*l2ptr) {
1361 dma_addr_t l2ptr_dma;
1362
1363 *l2ptr = dma_alloc_coherent(smmu->dev, sizeof(**l2ptr),
1364 &l2ptr_dma, GFP_KERNEL);
1365 if (!*l2ptr)
1366 return NULL;
1367
1368 arm_smmu_write_cd_l1_desc(&cd_table->l2.l1tab[idx],
1369 l2ptr_dma);
1370 /* An invalid L1CD can be cached */
1371 arm_smmu_sync_cd(master, ssid, false);
1372 }
1373 }
1374 return arm_smmu_get_cd_ptr(master, ssid);
1375 }
1376
1377 struct arm_smmu_cd_writer {
1378 struct arm_smmu_entry_writer writer;
1379 unsigned int ssid;
1380 };
1381
1382 VISIBLE_IF_KUNIT
1383 void arm_smmu_get_cd_used(const __le64 *ent, __le64 *used_bits)
1384 {
1385 used_bits[0] = cpu_to_le64(CTXDESC_CD_0_V);
1386 if (!(ent[0] & cpu_to_le64(CTXDESC_CD_0_V)))
1387 return;
1388 memset(used_bits, 0xFF, sizeof(struct arm_smmu_cd));
1389
1390 /*
1391 * If EPD0 is set by the make function it means
1392 * T0SZ/TG0/IR0/OR0/SH0/TTB0 are IGNORED
1393 */
1394 if (ent[0] & cpu_to_le64(CTXDESC_CD_0_TCR_EPD0)) {
1395 used_bits[0] &= ~cpu_to_le64(
1396 CTXDESC_CD_0_TCR_T0SZ | CTXDESC_CD_0_TCR_TG0 |
1397 CTXDESC_CD_0_TCR_IRGN0 | CTXDESC_CD_0_TCR_ORGN0 |
1398 CTXDESC_CD_0_TCR_SH0);
1399 used_bits[1] &= ~cpu_to_le64(CTXDESC_CD_1_TTB0_MASK);
1400 }
1401 }
1402 EXPORT_SYMBOL_IF_KUNIT(arm_smmu_get_cd_used);
1403
1404 static void arm_smmu_cd_writer_sync_entry(struct arm_smmu_entry_writer *writer)
1405 {
1406 struct arm_smmu_cd_writer *cd_writer =
1407 container_of(writer, struct arm_smmu_cd_writer, writer);
1408
1409 arm_smmu_sync_cd(writer->master, cd_writer->ssid, true);
1410 }
1411
1412 static const struct arm_smmu_entry_writer_ops arm_smmu_cd_writer_ops = {
1413 .sync = arm_smmu_cd_writer_sync_entry,
1414 .get_used = arm_smmu_get_cd_used,
1415 };
1416
1417 void arm_smmu_write_cd_entry(struct arm_smmu_master *master, int ssid,
1418 struct arm_smmu_cd *cdptr,
1419 const struct arm_smmu_cd *target)
1420 {
1421 bool target_valid = target->data[0] & cpu_to_le64(CTXDESC_CD_0_V);
1422 bool cur_valid = cdptr->data[0] & cpu_to_le64(CTXDESC_CD_0_V);
1423 struct arm_smmu_cd_writer cd_writer = {
1424 .writer = {
1425 .ops = &arm_smmu_cd_writer_ops,
1426 .master = master,
1427 },
1428 .ssid = ssid,
1429 };
1430
1431 if (ssid != IOMMU_NO_PASID && cur_valid != target_valid) {
1432 if (cur_valid)
1433 master->cd_table.used_ssids--;
1434 else
1435 master->cd_table.used_ssids++;
1436 }
1437
1438 arm_smmu_write_entry(&cd_writer.writer, cdptr->data, target->data);
1439 }
1440
1441 void arm_smmu_make_s1_cd(struct arm_smmu_cd *target,
1442 struct arm_smmu_master *master,
1443 struct arm_smmu_domain *smmu_domain)
1444 {
1445 struct arm_smmu_ctx_desc *cd = &smmu_domain->cd;
1446 const struct io_pgtable_cfg *pgtbl_cfg =
1447 &io_pgtable_ops_to_pgtable(smmu_domain->pgtbl_ops)->cfg;
1448 typeof(&pgtbl_cfg->arm_lpae_s1_cfg.tcr) tcr =
1449 &pgtbl_cfg->arm_lpae_s1_cfg.tcr;
1450
1451 memset(target, 0, sizeof(*target));
1452
1453 target->data[0] = cpu_to_le64(
1454 FIELD_PREP(CTXDESC_CD_0_TCR_T0SZ, tcr->tsz) |
1455 FIELD_PREP(CTXDESC_CD_0_TCR_TG0, tcr->tg) |
1456 FIELD_PREP(CTXDESC_CD_0_TCR_IRGN0, tcr->irgn) |
1457 FIELD_PREP(CTXDESC_CD_0_TCR_ORGN0, tcr->orgn) |
1458 FIELD_PREP(CTXDESC_CD_0_TCR_SH0, tcr->sh) |
1459 #ifdef __BIG_ENDIAN
1460 CTXDESC_CD_0_ENDI |
1461 #endif
1462 CTXDESC_CD_0_TCR_EPD1 |
1463 CTXDESC_CD_0_V |
1464 FIELD_PREP(CTXDESC_CD_0_TCR_IPS, tcr->ips) |
1465 CTXDESC_CD_0_AA64 |
1466 (master->stall_enabled ? CTXDESC_CD_0_S : 0) |
1467 CTXDESC_CD_0_R |
1468 CTXDESC_CD_0_A |
1469 CTXDESC_CD_0_ASET |
1470 FIELD_PREP(CTXDESC_CD_0_ASID, cd->asid)
1471 );
1472
1473 /* To enable dirty flag update, set both Access flag and dirty state update */
1474 if (pgtbl_cfg->quirks & IO_PGTABLE_QUIRK_ARM_HD)
1475 target->data[0] |= cpu_to_le64(CTXDESC_CD_0_TCR_HA |
1476 CTXDESC_CD_0_TCR_HD);
1477
1478 target->data[1] = cpu_to_le64(pgtbl_cfg->arm_lpae_s1_cfg.ttbr &
1479 CTXDESC_CD_1_TTB0_MASK);
1480 target->data[3] = cpu_to_le64(pgtbl_cfg->arm_lpae_s1_cfg.mair);
1481 }
1482 EXPORT_SYMBOL_IF_KUNIT(arm_smmu_make_s1_cd);
1483
1484 void arm_smmu_clear_cd(struct arm_smmu_master *master, ioasid_t ssid)
1485 {
1486 struct arm_smmu_cd target = {};
1487 struct arm_smmu_cd *cdptr;
1488
1489 if (!arm_smmu_cdtab_allocated(&master->cd_table))
1490 return;
1491 cdptr = arm_smmu_get_cd_ptr(master, ssid);
1492 if (WARN_ON(!cdptr))
1493 return;
1494 arm_smmu_write_cd_entry(master, ssid, cdptr, &target);
1495 }
1496
1497 static int arm_smmu_alloc_cd_tables(struct arm_smmu_master *master)
1498 {
1499 int ret;
1500 size_t l1size;
1501 size_t max_contexts;
1502 struct arm_smmu_device *smmu = master->smmu;
1503 struct arm_smmu_ctx_desc_cfg *cd_table = &master->cd_table;
1504
1505 cd_table->s1cdmax = master->ssid_bits;
1506 max_contexts = 1 << cd_table->s1cdmax;
1507
1508 if (!(smmu->features & ARM_SMMU_FEAT_2_LVL_CDTAB) ||
1509 max_contexts <= CTXDESC_L2_ENTRIES) {
1510 cd_table->s1fmt = STRTAB_STE_0_S1FMT_LINEAR;
1511 cd_table->linear.num_ents = max_contexts;
1512
1513 l1size = max_contexts * sizeof(struct arm_smmu_cd);
1514 cd_table->linear.table = dma_alloc_coherent(smmu->dev, l1size,
1515 &cd_table->cdtab_dma,
1516 GFP_KERNEL);
1517 if (!cd_table->linear.table)
1518 return -ENOMEM;
1519 } else {
1520 cd_table->s1fmt = STRTAB_STE_0_S1FMT_64K_L2;
1521 cd_table->l2.num_l1_ents =
1522 DIV_ROUND_UP(max_contexts, CTXDESC_L2_ENTRIES);
1523
1524 cd_table->l2.l2ptrs = kzalloc_objs(*cd_table->l2.l2ptrs,
1525 cd_table->l2.num_l1_ents);
1526 if (!cd_table->l2.l2ptrs)
1527 return -ENOMEM;
1528
1529 l1size = cd_table->l2.num_l1_ents * sizeof(struct arm_smmu_cdtab_l1);
1530 cd_table->l2.l1tab = dma_alloc_coherent(smmu->dev, l1size,
1531 &cd_table->cdtab_dma,
1532 GFP_KERNEL);
1533 if (!cd_table->l2.l1tab) {
1534 ret = -ENOMEM;
1535 goto err_free_l2ptrs;
1536 }
1537 }
1538 return 0;
1539
1540 err_free_l2ptrs:
1541 kfree(cd_table->l2.l2ptrs);
1542 cd_table->l2.l2ptrs = NULL;
1543 return ret;
1544 }
1545
1546 static void arm_smmu_free_cd_tables(struct arm_smmu_master *master)
1547 {
1548 int i;
1549 struct arm_smmu_device *smmu = master->smmu;
1550 struct arm_smmu_ctx_desc_cfg *cd_table = &master->cd_table;
1551
1552 if (cd_table->s1fmt != STRTAB_STE_0_S1FMT_LINEAR) {
1553 for (i = 0; i < cd_table->l2.num_l1_ents; i++) {
1554 if (!cd_table->l2.l2ptrs[i])
1555 continue;
1556
1557 dma_free_coherent(smmu->dev,
1558 sizeof(*cd_table->l2.l2ptrs[i]),
1559 cd_table->l2.l2ptrs[i],
1560 arm_smmu_cd_l1_get_desc(&cd_table->l2.l1tab[i]));
1561 }
1562 kfree(cd_table->l2.l2ptrs);
1563
1564 dma_free_coherent(smmu->dev,
1565 cd_table->l2.num_l1_ents *
1566 sizeof(struct arm_smmu_cdtab_l1),
1567 cd_table->l2.l1tab, cd_table->cdtab_dma);
1568 } else {
1569 dma_free_coherent(smmu->dev,
1570 cd_table->linear.num_ents *
1571 sizeof(struct arm_smmu_cd),
1572 cd_table->linear.table, cd_table->cdtab_dma);
1573 }
1574 }
1575
1576 /* Stream table manipulation functions */
1577 static void arm_smmu_write_strtab_l1_desc(struct arm_smmu_strtab_l1 *dst,
1578 dma_addr_t l2ptr_dma)
1579 {
1580 u64 val = 0;
1581
1582 val |= FIELD_PREP(STRTAB_L1_DESC_SPAN, STRTAB_SPLIT + 1);
1583 val |= l2ptr_dma & STRTAB_L1_DESC_L2PTR_MASK;
1584
1585 /* The HW has 64 bit atomicity with stores to the L2 STE table */
1586 WRITE_ONCE(dst->l2ptr, cpu_to_le64(val));
1587 }
1588
1589 struct arm_smmu_ste_writer {
1590 struct arm_smmu_entry_writer writer;
1591 u32 sid;
1592 };
1593
1594 static void arm_smmu_ste_writer_sync_entry(struct arm_smmu_entry_writer *writer)
1595 {
1596 struct arm_smmu_ste_writer *ste_writer =
1597 container_of(writer, struct arm_smmu_ste_writer, writer);
1598 struct arm_smmu_cmdq_ent cmd = {
1599 .opcode = CMDQ_OP_CFGI_STE,
1600 .cfgi = {
1601 .sid = ste_writer->sid,
1602 .leaf = true,
1603 },
1604 };
1605
1606 arm_smmu_cmdq_issue_cmd_with_sync(writer->master->smmu, &cmd);
1607 }
1608
1609 static const struct arm_smmu_entry_writer_ops arm_smmu_ste_writer_ops = {
1610 .sync = arm_smmu_ste_writer_sync_entry,
1611 .get_used = arm_smmu_get_ste_used,
1612 .get_update_safe = arm_smmu_get_ste_update_safe,
1613 };
1614
1615 static void arm_smmu_write_ste(struct arm_smmu_master *master, u32 sid,
1616 struct arm_smmu_ste *ste,
1617 const struct arm_smmu_ste *target)
1618 {
1619 struct arm_smmu_device *smmu = master->smmu;
1620 struct arm_smmu_ste_writer ste_writer = {
1621 .writer = {
1622 .ops = &arm_smmu_ste_writer_ops,
1623 .master = master,
1624 },
1625 .sid = sid,
1626 };
1627
1628 arm_smmu_write_entry(&ste_writer.writer, ste->data, target->data);
1629
1630 /* It's likely that we'll want to use the new STE soon */
1631 if (!(smmu->options & ARM_SMMU_OPT_SKIP_PREFETCH)) {
1632 struct arm_smmu_cmdq_ent
1633 prefetch_cmd = { .opcode = CMDQ_OP_PREFETCH_CFG,
1634 .prefetch = {
1635 .sid = sid,
1636 } };
1637
1638 arm_smmu_cmdq_issue_cmd(smmu, &prefetch_cmd);
1639 }
1640 }
1641
1642 void arm_smmu_make_abort_ste(struct arm_smmu_ste *target)
1643 {
1644 memset(target, 0, sizeof(*target));
1645 target->data[0] = cpu_to_le64(
1646 STRTAB_STE_0_V |
1647 FIELD_PREP(STRTAB_STE_0_CFG, STRTAB_STE_0_CFG_ABORT));
1648 }
1649 EXPORT_SYMBOL_IF_KUNIT(arm_smmu_make_abort_ste);
1650
1651 VISIBLE_IF_KUNIT
1652 void arm_smmu_make_bypass_ste(struct arm_smmu_device *smmu,
1653 struct arm_smmu_ste *target)
1654 {
1655 memset(target, 0, sizeof(*target));
1656 target->data[0] = cpu_to_le64(
1657 STRTAB_STE_0_V |
1658 FIELD_PREP(STRTAB_STE_0_CFG, STRTAB_STE_0_CFG_BYPASS));
1659
1660 if (smmu->features & ARM_SMMU_FEAT_ATTR_TYPES_OVR)
1661 target->data[1] = cpu_to_le64(FIELD_PREP(STRTAB_STE_1_SHCFG,
1662 STRTAB_STE_1_SHCFG_INCOMING));
1663 }
1664 EXPORT_SYMBOL_IF_KUNIT(arm_smmu_make_bypass_ste);
1665
1666 VISIBLE_IF_KUNIT
1667 void arm_smmu_make_cdtable_ste(struct arm_smmu_ste *target,
1668 struct arm_smmu_master *master, bool ats_enabled,
1669 unsigned int s1dss)
1670 {
1671 struct arm_smmu_ctx_desc_cfg *cd_table = &master->cd_table;
1672 struct arm_smmu_device *smmu = master->smmu;
1673
1674 memset(target, 0, sizeof(*target));
1675 target->data[0] = cpu_to_le64(
1676 STRTAB_STE_0_V |
1677 FIELD_PREP(STRTAB_STE_0_CFG, STRTAB_STE_0_CFG_S1_TRANS) |
1678 FIELD_PREP(STRTAB_STE_0_S1FMT, cd_table->s1fmt) |
1679 (cd_table->cdtab_dma & STRTAB_STE_0_S1CTXPTR_MASK) |
1680 FIELD_PREP(STRTAB_STE_0_S1CDMAX, cd_table->s1cdmax));
1681
1682 target->data[1] = cpu_to_le64(
1683 FIELD_PREP(STRTAB_STE_1_S1DSS, s1dss) |
1684 FIELD_PREP(STRTAB_STE_1_S1CIR, STRTAB_STE_1_S1C_CACHE_WBRA) |
1685 FIELD_PREP(STRTAB_STE_1_S1COR, STRTAB_STE_1_S1C_CACHE_WBRA) |
1686 FIELD_PREP(STRTAB_STE_1_S1CSH, ARM_SMMU_SH_ISH) |
1687 ((smmu->features & ARM_SMMU_FEAT_STALLS &&
1688 !master->stall_enabled) ?
1689 STRTAB_STE_1_S1STALLD :
1690 0) |
1691 FIELD_PREP(STRTAB_STE_1_EATS,
1692 ats_enabled ? STRTAB_STE_1_EATS_TRANS : 0));
1693
1694 if ((smmu->features & ARM_SMMU_FEAT_ATTR_TYPES_OVR) &&
1695 s1dss == STRTAB_STE_1_S1DSS_BYPASS)
1696 target->data[1] |= cpu_to_le64(FIELD_PREP(
1697 STRTAB_STE_1_SHCFG, STRTAB_STE_1_SHCFG_INCOMING));
1698
1699 if (smmu->features & ARM_SMMU_FEAT_E2H) {
1700 /*
1701 * To support BTM the streamworld needs to match the
1702 * configuration of the CPU so that the ASID broadcasts are
1703 * properly matched. This means either S/NS-EL2-E2H (hypervisor)
1704 * or NS-EL1 (guest). Since an SVA domain can be installed in a
1705 * PASID this should always use a BTM compatible configuration
1706 * if the HW supports it.
1707 */
1708 target->data[1] |= cpu_to_le64(
1709 FIELD_PREP(STRTAB_STE_1_STRW, STRTAB_STE_1_STRW_EL2));
1710 } else {
1711 target->data[1] |= cpu_to_le64(
1712 FIELD_PREP(STRTAB_STE_1_STRW, STRTAB_STE_1_STRW_NSEL1));
1713
1714 /*
1715 * VMID 0 is reserved for stage-2 bypass EL1 STEs, see
1716 * arm_smmu_domain_alloc_id()
1717 */
1718 target->data[2] =
1719 cpu_to_le64(FIELD_PREP(STRTAB_STE_2_S2VMID, 0));
1720 }
1721 }
1722 EXPORT_SYMBOL_IF_KUNIT(arm_smmu_make_cdtable_ste);
1723
1724 void arm_smmu_make_s2_domain_ste(struct arm_smmu_ste *target,
1725 struct arm_smmu_master *master,
1726 struct arm_smmu_domain *smmu_domain,
1727 bool ats_enabled)
1728 {
1729 struct arm_smmu_s2_cfg *s2_cfg = &smmu_domain->s2_cfg;
1730 const struct io_pgtable_cfg *pgtbl_cfg =
1731 &io_pgtable_ops_to_pgtable(smmu_domain->pgtbl_ops)->cfg;
1732 typeof(&pgtbl_cfg->arm_lpae_s2_cfg.vtcr) vtcr =
1733 &pgtbl_cfg->arm_lpae_s2_cfg.vtcr;
1734 u64 vtcr_val;
1735 struct arm_smmu_device *smmu = master->smmu;
1736
1737 memset(target, 0, sizeof(*target));
1738 target->data[0] = cpu_to_le64(
1739 STRTAB_STE_0_V |
1740 FIELD_PREP(STRTAB_STE_0_CFG, STRTAB_STE_0_CFG_S2_TRANS));
1741
1742 target->data[1] = cpu_to_le64(
1743 FIELD_PREP(STRTAB_STE_1_EATS,
1744 ats_enabled ? STRTAB_STE_1_EATS_TRANS : 0));
1745
1746 if (pgtbl_cfg->quirks & IO_PGTABLE_QUIRK_ARM_S2FWB)
1747 target->data[1] |= cpu_to_le64(STRTAB_STE_1_S2FWB);
1748 if (smmu->features & ARM_SMMU_FEAT_ATTR_TYPES_OVR)
1749 target->data[1] |= cpu_to_le64(FIELD_PREP(STRTAB_STE_1_SHCFG,
1750 STRTAB_STE_1_SHCFG_INCOMING));
1751
1752 vtcr_val = FIELD_PREP(STRTAB_STE_2_VTCR_S2T0SZ, vtcr->tsz) |
1753 FIELD_PREP(STRTAB_STE_2_VTCR_S2SL0, vtcr->sl) |
1754 FIELD_PREP(STRTAB_STE_2_VTCR_S2IR0, vtcr->irgn) |
1755 FIELD_PREP(STRTAB_STE_2_VTCR_S2OR0, vtcr->orgn) |
1756 FIELD_PREP(STRTAB_STE_2_VTCR_S2SH0, vtcr->sh) |
1757 FIELD_PREP(STRTAB_STE_2_VTCR_S2TG, vtcr->tg) |
1758 FIELD_PREP(STRTAB_STE_2_VTCR_S2PS, vtcr->ps);
1759 target->data[2] = cpu_to_le64(
1760 FIELD_PREP(STRTAB_STE_2_S2VMID, s2_cfg->vmid) |
1761 FIELD_PREP(STRTAB_STE_2_VTCR, vtcr_val) |
1762 STRTAB_STE_2_S2AA64 |
1763 #ifdef __BIG_ENDIAN
1764 STRTAB_STE_2_S2ENDI |
1765 #endif
1766 STRTAB_STE_2_S2PTW |
1767 (master->stall_enabled ? STRTAB_STE_2_S2S : 0) |
1768 STRTAB_STE_2_S2R);
1769
1770 target->data[3] = cpu_to_le64(pgtbl_cfg->arm_lpae_s2_cfg.vttbr &
1771 STRTAB_STE_3_S2TTB_MASK);
1772 }
1773 EXPORT_SYMBOL_IF_KUNIT(arm_smmu_make_s2_domain_ste);
1774
1775 /*
1776 * This can safely directly manipulate the STE memory without a sync sequence
1777 * because the STE table has not been installed in the SMMU yet.
1778 */
1779 static void arm_smmu_init_initial_stes(struct arm_smmu_ste *strtab,
1780 unsigned int nent)
1781 {
1782 unsigned int i;
1783
1784 for (i = 0; i < nent; ++i) {
1785 arm_smmu_make_abort_ste(strtab);
1786 strtab++;
1787 }
1788 }
1789
1790 static int arm_smmu_init_l2_strtab(struct arm_smmu_device *smmu, u32 sid)
1791 {
1792 dma_addr_t l2ptr_dma;
1793 struct arm_smmu_strtab_cfg *cfg = &smmu->strtab_cfg;
1794 struct arm_smmu_strtab_l2 **l2table;
1795
1796 l2table = &cfg->l2.l2ptrs[arm_smmu_strtab_l1_idx(sid)];
1797 if (*l2table)
1798 return 0;
1799
1800 *l2table = dmam_alloc_coherent(smmu->dev, sizeof(**l2table),
1801 &l2ptr_dma, GFP_KERNEL);
1802 if (!*l2table) {
1803 dev_err(smmu->dev,
1804 "failed to allocate l2 stream table for SID %u\n",
1805 sid);
1806 return -ENOMEM;
1807 }
1808
1809 arm_smmu_init_initial_stes((*l2table)->stes,
1810 ARRAY_SIZE((*l2table)->stes));
1811 arm_smmu_write_strtab_l1_desc(&cfg->l2.l1tab[arm_smmu_strtab_l1_idx(sid)],
1812 l2ptr_dma);
1813 return 0;
1814 }
1815
1816 static int arm_smmu_streams_cmp_key(const void *lhs, const struct rb_node *rhs)
1817 {
1818 struct arm_smmu_stream *stream_rhs =
1819 rb_entry(rhs, struct arm_smmu_stream, node);
1820 const u32 *sid_lhs = lhs;
1821
1822 if (*sid_lhs < stream_rhs->id)
1823 return -1;
1824 if (*sid_lhs > stream_rhs->id)
1825 return 1;
1826 return 0;
1827 }
1828
1829 static int arm_smmu_streams_cmp_node(struct rb_node *lhs,
1830 const struct rb_node *rhs)
1831 {
1832 return arm_smmu_streams_cmp_key(
1833 &rb_entry(lhs, struct arm_smmu_stream, node)->id, rhs);
1834 }
1835
1836 static struct arm_smmu_master *
1837 arm_smmu_find_master(struct arm_smmu_device *smmu, u32 sid)
1838 {
1839 struct rb_node *node;
1840
1841 lockdep_assert_held(&smmu->streams_mutex);
1842
1843 node = rb_find(&sid, &smmu->streams, arm_smmu_streams_cmp_key);
1844 if (!node)
1845 return NULL;
1846 return rb_entry(node, struct arm_smmu_stream, node)->master;
1847 }
1848
1849 /* IRQ and event handlers */
1850 static void arm_smmu_decode_event(struct arm_smmu_device *smmu, u64 *raw,
1851 struct arm_smmu_event *event)
1852 {
1853 struct arm_smmu_master *master;
1854
1855 event->id = FIELD_GET(EVTQ_0_ID, raw[0]);
1856 event->sid = FIELD_GET(EVTQ_0_SID, raw[0]);
1857 event->ssv = FIELD_GET(EVTQ_0_SSV, raw[0]);
1858 event->ssid = event->ssv ? FIELD_GET(EVTQ_0_SSID, raw[0]) : IOMMU_NO_PASID;
1859 event->privileged = FIELD_GET(EVTQ_1_PnU, raw[1]);
1860 event->instruction = FIELD_GET(EVTQ_1_InD, raw[1]);
1861 event->s2 = FIELD_GET(EVTQ_1_S2, raw[1]);
1862 event->read = FIELD_GET(EVTQ_1_RnW, raw[1]);
1863 event->stag = FIELD_GET(EVTQ_1_STAG, raw[1]);
1864 event->stall = FIELD_GET(EVTQ_1_STALL, raw[1]);
1865 event->class = FIELD_GET(EVTQ_1_CLASS, raw[1]);
1866 event->iova = FIELD_GET(EVTQ_2_ADDR, raw[2]);
1867 event->ipa = raw[3] & EVTQ_3_IPA;
1868 event->fetch_addr = raw[3] & EVTQ_3_FETCH_ADDR;
1869 event->ttrnw = FIELD_GET(EVTQ_1_TT_READ, raw[1]);
1870 event->class_tt = false;
1871 event->dev = NULL;
1872
1873 if (event->id == EVT_ID_PERMISSION_FAULT)
1874 event->class_tt = (event->class == EVTQ_1_CLASS_TT);
1875
1876 mutex_lock(&smmu->streams_mutex);
1877 master = arm_smmu_find_master(smmu, event->sid);
1878 if (master)
1879 event->dev = get_device(master->dev);
1880 mutex_unlock(&smmu->streams_mutex);
1881 }
1882
1883 static int arm_smmu_handle_event(struct arm_smmu_device *smmu, u64 *evt,
1884 struct arm_smmu_event *event)
1885 {
1886 int ret = 0;
1887 u32 perm = 0;
1888 struct arm_smmu_master *master;
1889 struct iopf_fault fault_evt = { };
1890 struct iommu_fault *flt = &fault_evt.fault;
1891
1892 switch (event->id) {
1893 case EVT_ID_BAD_STE_CONFIG:
1894 case EVT_ID_STREAM_DISABLED_FAULT:
1895 case EVT_ID_BAD_SUBSTREAMID_CONFIG:
1896 case EVT_ID_BAD_CD_CONFIG:
1897 case EVT_ID_TRANSLATION_FAULT:
1898 case EVT_ID_ADDR_SIZE_FAULT:
1899 case EVT_ID_ACCESS_FAULT:
1900 case EVT_ID_PERMISSION_FAULT:
1901 break;
1902 default:
1903 return -EOPNOTSUPP;
1904 }
1905
1906 if (event->stall) {
1907 if (event->read)
1908 perm |= IOMMU_FAULT_PERM_READ;
1909 else
1910 perm |= IOMMU_FAULT_PERM_WRITE;
1911
1912 if (event->instruction)
1913 perm |= IOMMU_FAULT_PERM_EXEC;
1914
1915 if (event->privileged)
1916 perm |= IOMMU_FAULT_PERM_PRIV;
1917
1918 flt->type = IOMMU_FAULT_PAGE_REQ;
1919 flt->prm = (struct iommu_fault_page_request){
1920 .flags = IOMMU_FAULT_PAGE_REQUEST_LAST_PAGE,
1921 .grpid = event->stag,
1922 .perm = perm,
1923 .addr = event->iova,
1924 };
1925
1926 if (event->ssv) {
1927 flt->prm.flags |= IOMMU_FAULT_PAGE_REQUEST_PASID_VALID;
1928 flt->prm.pasid = event->ssid;
1929 }
1930 }
1931
1932 mutex_lock(&smmu->streams_mutex);
1933 master = arm_smmu_find_master(smmu, event->sid);
1934 if (!master) {
1935 ret = -EINVAL;
1936 goto out_unlock;
1937 }
1938
1939 if (event->stall)
1940 ret = iommu_report_device_fault(master->dev, &fault_evt);
1941 else if (master->vmaster && !event->s2)
1942 ret = arm_vmaster_report_event(master->vmaster, evt);
1943 else
1944 ret = -EOPNOTSUPP; /* Unhandled events should be pinned */
1945 out_unlock:
1946 mutex_unlock(&smmu->streams_mutex);
1947 return ret;
1948 }
1949
1950 static void arm_smmu_dump_raw_event(struct arm_smmu_device *smmu, u64 *raw,
1951 struct arm_smmu_event *event)
1952 {
1953 int i;
1954
1955 dev_err(smmu->dev, "event 0x%02x received:\n", event->id);
1956
1957 for (i = 0; i < EVTQ_ENT_DWORDS; ++i)
1958 dev_err(smmu->dev, "\t0x%016llx\n", raw[i]);
1959 }
1960
1961 #define ARM_SMMU_EVT_KNOWN(e) ((e)->id < ARRAY_SIZE(event_str) && event_str[(e)->id])
1962 #define ARM_SMMU_LOG_EVT_STR(e) ARM_SMMU_EVT_KNOWN(e) ? event_str[(e)->id] : "UNKNOWN"
1963 #define ARM_SMMU_LOG_CLIENT(e) (e)->dev ? dev_name((e)->dev) : "(unassigned sid)"
1964
1965 static void arm_smmu_dump_event(struct arm_smmu_device *smmu, u64 *raw,
1966 struct arm_smmu_event *evt,
1967 struct ratelimit_state *rs)
1968 {
1969 if (!__ratelimit(rs))
1970 return;
1971
1972 arm_smmu_dump_raw_event(smmu, raw, evt);
1973
1974 switch (evt->id) {
1975 case EVT_ID_TRANSLATION_FAULT:
1976 case EVT_ID_ADDR_SIZE_FAULT:
1977 case EVT_ID_ACCESS_FAULT:
1978 case EVT_ID_PERMISSION_FAULT:
1979 dev_err(smmu->dev, "event: %s client: %s sid: %#x ssid: %#x iova: %#llx ipa: %#llx",
1980 ARM_SMMU_LOG_EVT_STR(evt), ARM_SMMU_LOG_CLIENT(evt),
1981 evt->sid, evt->ssid, evt->iova, evt->ipa);
1982
1983 dev_err(smmu->dev, "%s %s %s %s \"%s\"%s%s stag: %#x",
1984 evt->privileged ? "priv" : "unpriv",
1985 evt->instruction ? "inst" : "data",
1986 str_read_write(evt->read),
1987 evt->s2 ? "s2" : "s1", event_class_str[evt->class],
1988 evt->class_tt ? (evt->ttrnw ? " ttd_read" : " ttd_write") : "",
1989 evt->stall ? " stall" : "", evt->stag);
1990
1991 break;
1992
1993 case EVT_ID_STE_FETCH_FAULT:
1994 case EVT_ID_CD_FETCH_FAULT:
1995 case EVT_ID_VMS_FETCH_FAULT:
1996 dev_err(smmu->dev, "event: %s client: %s sid: %#x ssid: %#x fetch_addr: %#llx",
1997 ARM_SMMU_LOG_EVT_STR(evt), ARM_SMMU_LOG_CLIENT(evt),
1998 evt->sid, evt->ssid, evt->fetch_addr);
1999
2000 break;
2001
2002 default:
2003 dev_err(smmu->dev, "event: %s client: %s sid: %#x ssid: %#x",
2004 ARM_SMMU_LOG_EVT_STR(evt), ARM_SMMU_LOG_CLIENT(evt),
2005 evt->sid, evt->ssid);
2006 }
2007 }
2008
2009 static irqreturn_t arm_smmu_evtq_thread(int irq, void *dev)
2010 {
2011 u64 evt[EVTQ_ENT_DWORDS];
2012 struct arm_smmu_event event = {0};
2013 struct arm_smmu_device *smmu = dev;
2014 struct arm_smmu_queue *q = &smmu->evtq.q;
2015 struct arm_smmu_ll_queue *llq = &q->llq;
2016 static DEFINE_RATELIMIT_STATE(rs, DEFAULT_RATELIMIT_INTERVAL,
2017 DEFAULT_RATELIMIT_BURST);
2018
2019 do {
2020 while (!queue_remove_raw(q, evt)) {
2021 arm_smmu_decode_event(smmu, evt, &event);
2022 if (arm_smmu_handle_event(smmu, evt, &event))
2023 arm_smmu_dump_event(smmu, evt, &event, &rs);
2024
2025 put_device(event.dev);
2026 cond_resched();
2027 }
2028
2029 /*
2030 * Not much we can do on overflow, so scream and pretend we're
2031 * trying harder.
2032 */
2033 if (queue_sync_prod_in(q) == -EOVERFLOW)
2034 dev_err(smmu->dev, "EVTQ overflow detected -- events lost\n");
2035 } while (!queue_empty(llq));
2036
2037 /* Sync our overflow flag, as we believe we're up to speed */
2038 queue_sync_cons_ovf(q);
2039 return IRQ_HANDLED;
2040 }
2041
2042 static void arm_smmu_handle_ppr(struct arm_smmu_device *smmu, u64 *evt)
2043 {
2044 u32 sid, ssid;
2045 u16 grpid;
2046 bool ssv, last;
2047
2048 sid = FIELD_GET(PRIQ_0_SID, evt[0]);
2049 ssv = FIELD_GET(PRIQ_0_SSID_V, evt[0]);
2050 ssid = ssv ? FIELD_GET(PRIQ_0_SSID, evt[0]) : IOMMU_NO_PASID;
2051 last = FIELD_GET(PRIQ_0_PRG_LAST, evt[0]);
2052 grpid = FIELD_GET(PRIQ_1_PRG_IDX, evt[1]);
2053
2054 dev_info(smmu->dev, "unexpected PRI request received:\n");
2055 dev_info(smmu->dev,
2056 "\tsid 0x%08x.0x%05x: [%u%s] %sprivileged %s%s%s access at iova 0x%016llx\n",
2057 sid, ssid, grpid, last ? "L" : "",
2058 evt[0] & PRIQ_0_PERM_PRIV ? "" : "un",
2059 evt[0] & PRIQ_0_PERM_READ ? "R" : "",
2060 evt[0] & PRIQ_0_PERM_WRITE ? "W" : "",
2061 evt[0] & PRIQ_0_PERM_EXEC ? "X" : "",
2062 evt[1] & PRIQ_1_ADDR_MASK);
2063
2064 if (last) {
2065 struct arm_smmu_cmdq_ent cmd = {
2066 .opcode = CMDQ_OP_PRI_RESP,
2067 .substream_valid = ssv,
2068 .pri = {
2069 .sid = sid,
2070 .ssid = ssid,
2071 .grpid = grpid,
2072 .resp = PRI_RESP_DENY,
2073 },
2074 };
2075
2076 arm_smmu_cmdq_issue_cmd(smmu, &cmd);
2077 }
2078 }
2079
2080 static irqreturn_t arm_smmu_priq_thread(int irq, void *dev)
2081 {
2082 struct arm_smmu_device *smmu = dev;
2083 struct arm_smmu_queue *q = &smmu->priq.q;
2084 struct arm_smmu_ll_queue *llq = &q->llq;
2085 u64 evt[PRIQ_ENT_DWORDS];
2086
2087 do {
2088 while (!queue_remove_raw(q, evt))
2089 arm_smmu_handle_ppr(smmu, evt);
2090
2091 if (queue_sync_prod_in(q) == -EOVERFLOW)
2092 dev_err(smmu->dev, "PRIQ overflow detected -- requests lost\n");
2093 } while (!queue_empty(llq));
2094
2095 /* Sync our overflow flag, as we believe we're up to speed */
2096 queue_sync_cons_ovf(q);
2097 return IRQ_HANDLED;
2098 }
2099
2100 static int arm_smmu_device_disable(struct arm_smmu_device *smmu);
2101
2102 static irqreturn_t arm_smmu_gerror_handler(int irq, void *dev)
2103 {
2104 u32 gerror, gerrorn, active;
2105 struct arm_smmu_device *smmu = dev;
2106
2107 gerror = readl_relaxed(smmu->base + ARM_SMMU_GERROR);
2108 gerrorn = readl_relaxed(smmu->base + ARM_SMMU_GERRORN);
2109
2110 active = gerror ^ gerrorn;
2111 if (!(active & GERROR_ERR_MASK))
2112 return IRQ_NONE; /* No errors pending */
2113
2114 dev_warn(smmu->dev,
2115 "unexpected global error reported (0x%08x), this could be serious\n",
2116 active);
2117
2118 if (active & GERROR_SFM_ERR) {
2119 dev_err(smmu->dev, "device has entered Service Failure Mode!\n");
2120 arm_smmu_device_disable(smmu);
2121 }
2122
2123 if (active & GERROR_MSI_GERROR_ABT_ERR)
2124 dev_warn(smmu->dev, "GERROR MSI write aborted\n");
2125
2126 if (active & GERROR_MSI_PRIQ_ABT_ERR)
2127 dev_warn(smmu->dev, "PRIQ MSI write aborted\n");
2128
2129 if (active & GERROR_MSI_EVTQ_ABT_ERR)
2130 dev_warn(smmu->dev, "EVTQ MSI write aborted\n");
2131
2132 if (active & GERROR_MSI_CMDQ_ABT_ERR)
2133 dev_warn(smmu->dev, "CMDQ MSI write aborted\n");
2134
2135 if (active & GERROR_PRIQ_ABT_ERR)
2136 dev_err(smmu->dev, "PRIQ write aborted -- events may have been lost\n");
2137
2138 if (active & GERROR_EVTQ_ABT_ERR)
2139 dev_err(smmu->dev, "EVTQ write aborted -- events may have been lost\n");
2140
2141 if (active & GERROR_CMDQ_ERR)
2142 arm_smmu_cmdq_skip_err(smmu);
2143
2144 writel(gerror, smmu->base + ARM_SMMU_GERRORN);
2145 return IRQ_HANDLED;
2146 }
2147
2148 static irqreturn_t arm_smmu_combined_irq_thread(int irq, void *dev)
2149 {
2150 struct arm_smmu_device *smmu = dev;
2151
2152 arm_smmu_evtq_thread(irq, dev);
2153 if (smmu->features & ARM_SMMU_FEAT_PRI)
2154 arm_smmu_priq_thread(irq, dev);
2155
2156 return IRQ_HANDLED;
2157 }
2158
2159 static irqreturn_t arm_smmu_combined_irq_handler(int irq, void *dev)
2160 {
2161 arm_smmu_gerror_handler(irq, dev);
2162 return IRQ_WAKE_THREAD;
2163 }
2164
2165 static void
2166 arm_smmu_atc_inv_to_cmd(int ssid, unsigned long iova, size_t size,
2167 struct arm_smmu_cmdq_ent *cmd)
2168 {
2169 size_t log2_span;
2170 size_t span_mask;
2171 /* ATC invalidates are always on 4096-bytes pages */
2172 size_t inval_grain_shift = 12;
2173 unsigned long page_start, page_end;
2174
2175 /*
2176 * ATS and PASID:
2177 *
2178 * If substream_valid is clear, the PCIe TLP is sent without a PASID
2179 * prefix. In that case all ATC entries within the address range are
2180 * invalidated, including those that were requested with a PASID! There
2181 * is no way to invalidate only entries without PASID.
2182 *
2183 * When using STRTAB_STE_1_S1DSS_SSID0 (reserving CD 0 for non-PASID
2184 * traffic), translation requests without PASID create ATC entries
2185 * without PASID, which must be invalidated with substream_valid clear.
2186 * This has the unpleasant side-effect of invalidating all PASID-tagged
2187 * ATC entries within the address range.
2188 */
2189 *cmd = (struct arm_smmu_cmdq_ent) {
2190 .opcode = CMDQ_OP_ATC_INV,
2191 .substream_valid = (ssid != IOMMU_NO_PASID),
2192 .atc.ssid = ssid,
2193 };
2194
2195 if (!size) {
2196 cmd->atc.size = ATC_INV_SIZE_ALL;
2197 return;
2198 }
2199
2200 page_start = iova >> inval_grain_shift;
2201 page_end = (iova + size - 1) >> inval_grain_shift;
2202
2203 /*
2204 * In an ATS Invalidate Request, the address must be aligned on the
2205 * range size, which must be a power of two number of page sizes. We
2206 * thus have to choose between grossly over-invalidating the region, or
2207 * splitting the invalidation into multiple commands. For simplicity
2208 * we'll go with the first solution, but should refine it in the future
2209 * if multiple commands are shown to be more efficient.
2210 *
2211 * Find the smallest power of two that covers the range. The most
2212 * significant differing bit between the start and end addresses,
2213 * fls(start ^ end), indicates the required span. For example:
2214 *
2215 * We want to invalidate pages [8; 11]. This is already the ideal range:
2216 * x = 0b1000 ^ 0b1011 = 0b11
2217 * span = 1 << fls(x) = 4
2218 *
2219 * To invalidate pages [7; 10], we need to invalidate [0; 15]:
2220 * x = 0b0111 ^ 0b1010 = 0b1101
2221 * span = 1 << fls(x) = 16
2222 */
2223 log2_span = fls_long(page_start ^ page_end);
2224 span_mask = (1ULL << log2_span) - 1;
2225
2226 page_start &= ~span_mask;
2227
2228 cmd->atc.addr = page_start << inval_grain_shift;
2229 cmd->atc.size = log2_span;
2230 }
2231
2232 static int arm_smmu_atc_inv_master(struct arm_smmu_master *master,
2233 ioasid_t ssid)
2234 {
2235 int i;
2236 struct arm_smmu_cmdq_ent cmd;
2237 struct arm_smmu_cmdq_batch cmds;
2238
2239 arm_smmu_atc_inv_to_cmd(ssid, 0, 0, &cmd);
2240
2241 arm_smmu_cmdq_batch_init(master->smmu, &cmds, &cmd);
2242 for (i = 0; i < master->num_streams; i++) {
2243 cmd.atc.sid = master->streams[i].id;
2244 arm_smmu_cmdq_batch_add(master->smmu, &cmds, &cmd);
2245 }
2246
2247 return arm_smmu_cmdq_batch_submit(master->smmu, &cmds);
2248 }
2249
2250 int arm_smmu_atc_inv_domain(struct arm_smmu_domain *smmu_domain,
2251 unsigned long iova, size_t size)
2252 {
2253 struct arm_smmu_master_domain *master_domain;
2254 int i;
2255 unsigned long flags;
2256 struct arm_smmu_cmdq_ent cmd = {
2257 .opcode = CMDQ_OP_ATC_INV,
2258 };
2259 struct arm_smmu_cmdq_batch cmds;
2260
2261 if (!(smmu_domain->smmu->features & ARM_SMMU_FEAT_ATS))
2262 return 0;
2263
2264 /*
2265 * Ensure that we've completed prior invalidation of the main TLBs
2266 * before we read 'nr_ats_masters' in case of a concurrent call to
2267 * arm_smmu_enable_ats():
2268 *
2269 * // unmap() // arm_smmu_enable_ats()
2270 * TLBI+SYNC atomic_inc(&nr_ats_masters);
2271 * smp_mb(); [...]
2272 * atomic_read(&nr_ats_masters); pci_enable_ats() // writel()
2273 *
2274 * Ensures that we always see the incremented 'nr_ats_masters' count if
2275 * ATS was enabled at the PCI device before completion of the TLBI.
2276 */
2277 smp_mb();
2278 if (!atomic_read(&smmu_domain->nr_ats_masters))
2279 return 0;
2280
2281 arm_smmu_cmdq_batch_init(smmu_domain->smmu, &cmds, &cmd);
2282
2283 spin_lock_irqsave(&smmu_domain->devices_lock, flags);
2284 list_for_each_entry(master_domain, &smmu_domain->devices,
2285 devices_elm) {
2286 struct arm_smmu_master *master = master_domain->master;
2287
2288 if (!master->ats_enabled)
2289 continue;
2290
2291 if (master_domain->nested_ats_flush) {
2292 /*
2293 * If a S2 used as a nesting parent is changed we have
2294 * no option but to completely flush the ATC.
2295 */
2296 arm_smmu_atc_inv_to_cmd(IOMMU_NO_PASID, 0, 0, &cmd);
2297 } else {
2298 arm_smmu_atc_inv_to_cmd(master_domain->ssid, iova, size,
2299 &cmd);
2300 }
2301
2302 for (i = 0; i < master->num_streams; i++) {
2303 cmd.atc.sid = master->streams[i].id;
2304 arm_smmu_cmdq_batch_add(smmu_domain->smmu, &cmds, &cmd);
2305 }
2306 }
2307 spin_unlock_irqrestore(&smmu_domain->devices_lock, flags);
2308
2309 return arm_smmu_cmdq_batch_submit(smmu_domain->smmu, &cmds);
2310 }
2311
2312 /* IO_PGTABLE API */
2313 static void arm_smmu_tlb_inv_context(void *cookie)
2314 {
2315 struct arm_smmu_domain *smmu_domain = cookie;
2316 struct arm_smmu_device *smmu = smmu_domain->smmu;
2317 struct arm_smmu_cmdq_ent cmd;
2318
2319 /*
2320 * NOTE: when io-pgtable is in non-strict mode, we may get here with
2321 * PTEs previously cleared by unmaps on the current CPU not yet visible
2322 * to the SMMU. We are relying on the dma_wmb() implicit during cmd
2323 * insertion to guarantee those are observed before the TLBI. Do be
2324 * careful, 007.
2325 */
2326 if (smmu_domain->stage == ARM_SMMU_DOMAIN_S1) {
2327 arm_smmu_tlb_inv_asid(smmu, smmu_domain->cd.asid);
2328 } else {
2329 cmd.opcode = CMDQ_OP_TLBI_S12_VMALL;
2330 cmd.tlbi.vmid = smmu_domain->s2_cfg.vmid;
2331 arm_smmu_cmdq_issue_cmd_with_sync(smmu, &cmd);
2332 }
2333 arm_smmu_atc_inv_domain(smmu_domain, 0, 0);
2334 }
2335
2336 static void __arm_smmu_tlb_inv_range(struct arm_smmu_cmdq_ent *cmd,
2337 unsigned long iova, size_t size,
2338 size_t granule,
2339 struct arm_smmu_domain *smmu_domain)
2340 {
2341 struct arm_smmu_device *smmu = smmu_domain->smmu;
2342 unsigned long end = iova + size, num_pages = 0, tg = 0;
2343 size_t inv_range = granule;
2344 struct arm_smmu_cmdq_batch cmds;
2345
2346 if (!size)
2347 return;
2348
2349 if (smmu->features & ARM_SMMU_FEAT_RANGE_INV) {
2350 /* Get the leaf page size */
2351 tg = __ffs(smmu_domain->domain.pgsize_bitmap);
2352
2353 num_pages = size >> tg;
2354
2355 /* Convert page size of 12,14,16 (log2) to 1,2,3 */
2356 cmd->tlbi.tg = (tg - 10) / 2;
2357
2358 /*
2359 * Determine what level the granule is at. For non-leaf, both
2360 * io-pgtable and SVA pass a nominal last-level granule because
2361 * they don't know what level(s) actually apply, so ignore that
2362 * and leave TTL=0. However for various errata reasons we still
2363 * want to use a range command, so avoid the SVA corner case
2364 * where both scale and num could be 0 as well.
2365 */
2366 if (cmd->tlbi.leaf)
2367 cmd->tlbi.ttl = 4 - ((ilog2(granule) - 3) / (tg - 3));
2368 else if ((num_pages & CMDQ_TLBI_RANGE_NUM_MAX) == 1)
2369 num_pages++;
2370 }
2371
2372 arm_smmu_cmdq_batch_init(smmu, &cmds, cmd);
2373
2374 while (iova < end) {
2375 if (smmu->features & ARM_SMMU_FEAT_RANGE_INV) {
2376 /*
2377 * On each iteration of the loop, the range is 5 bits
2378 * worth of the aligned size remaining.
2379 * The range in pages is:
2380 *
2381 * range = (num_pages & (0x1f << __ffs(num_pages)))
2382 */
2383 unsigned long scale, num;
2384
2385 /* Determine the power of 2 multiple number of pages */
2386 scale = __ffs(num_pages);
2387 cmd->tlbi.scale = scale;
2388
2389 /* Determine how many chunks of 2^scale size we have */
2390 num = (num_pages >> scale) & CMDQ_TLBI_RANGE_NUM_MAX;
2391 cmd->tlbi.num = num - 1;
2392
2393 /* range is num * 2^scale * pgsize */
2394 inv_range = num << (scale + tg);
2395
2396 /* Clear out the lower order bits for the next iteration */
2397 num_pages -= num << scale;
2398 }
2399
2400 cmd->tlbi.addr = iova;
2401 arm_smmu_cmdq_batch_add(smmu, &cmds, cmd);
2402 iova += inv_range;
2403 }
2404 arm_smmu_cmdq_batch_submit(smmu, &cmds);
2405 }
2406
2407 static void arm_smmu_tlb_inv_range_domain(unsigned long iova, size_t size,
2408 size_t granule, bool leaf,
2409 struct arm_smmu_domain *smmu_domain)
2410 {
2411 struct arm_smmu_cmdq_ent cmd = {
2412 .tlbi = {
2413 .leaf = leaf,
2414 },
2415 };
2416
2417 if (smmu_domain->stage == ARM_SMMU_DOMAIN_S1) {
2418 cmd.opcode = smmu_domain->smmu->features & ARM_SMMU_FEAT_E2H ?
2419 CMDQ_OP_TLBI_EL2_VA : CMDQ_OP_TLBI_NH_VA;
2420 cmd.tlbi.asid = smmu_domain->cd.asid;
2421 } else {
2422 cmd.opcode = CMDQ_OP_TLBI_S2_IPA;
2423 cmd.tlbi.vmid = smmu_domain->s2_cfg.vmid;
2424 }
2425 __arm_smmu_tlb_inv_range(&cmd, iova, size, granule, smmu_domain);
2426
2427 if (smmu_domain->nest_parent) {
2428 /*
2429 * When the S2 domain changes all the nested S1 ASIDs have to be
2430 * flushed too.
2431 */
2432 cmd.opcode = CMDQ_OP_TLBI_NH_ALL;
2433 arm_smmu_cmdq_issue_cmd_with_sync(smmu_domain->smmu, &cmd);
2434 }
2435
2436 /*
2437 * Unfortunately, this can't be leaf-only since we may have
2438 * zapped an entire table.
2439 */
2440 arm_smmu_atc_inv_domain(smmu_domain, iova, size);
2441 }
2442
2443 void arm_smmu_tlb_inv_range_asid(unsigned long iova, size_t size, int asid,
2444 size_t granule, bool leaf,
2445 struct arm_smmu_domain *smmu_domain)
2446 {
2447 struct arm_smmu_cmdq_ent cmd = {
2448 .opcode = smmu_domain->smmu->features & ARM_SMMU_FEAT_E2H ?
2449 CMDQ_OP_TLBI_EL2_VA : CMDQ_OP_TLBI_NH_VA,
2450 .tlbi = {
2451 .asid = asid,
2452 .leaf = leaf,
2453 },
2454 };
2455
2456 __arm_smmu_tlb_inv_range(&cmd, iova, size, granule, smmu_domain);
2457 }
2458
2459 static void arm_smmu_tlb_inv_page_nosync(struct iommu_iotlb_gather *gather,
2460 unsigned long iova, size_t granule,
2461 void *cookie)
2462 {
2463 struct arm_smmu_domain *smmu_domain = cookie;
2464 struct iommu_domain *domain = &smmu_domain->domain;
2465
2466 iommu_iotlb_gather_add_page(domain, gather, iova, granule);
2467 }
2468
2469 static void arm_smmu_tlb_inv_walk(unsigned long iova, size_t size,
2470 size_t granule, void *cookie)
2471 {
2472 arm_smmu_tlb_inv_range_domain(iova, size, granule, false, cookie);
2473 }
2474
2475 static const struct iommu_flush_ops arm_smmu_flush_ops = {
2476 .tlb_flush_all = arm_smmu_tlb_inv_context,
2477 .tlb_flush_walk = arm_smmu_tlb_inv_walk,
2478 .tlb_add_page = arm_smmu_tlb_inv_page_nosync,
2479 };
2480
2481 static bool arm_smmu_dbm_capable(struct arm_smmu_device *smmu)
2482 {
2483 u32 features = (ARM_SMMU_FEAT_HD | ARM_SMMU_FEAT_COHERENCY);
2484
2485 return (smmu->features & features) == features;
2486 }
2487
2488 /* IOMMU API */
2489 static bool arm_smmu_capable(struct device *dev, enum iommu_cap cap)
2490 {
2491 struct arm_smmu_master *master = dev_iommu_priv_get(dev);
2492
2493 switch (cap) {
2494 case IOMMU_CAP_CACHE_COHERENCY:
2495 /* Assume that a coherent TCU implies coherent TBUs */
2496 return master->smmu->features & ARM_SMMU_FEAT_COHERENCY;
2497 case IOMMU_CAP_ENFORCE_CACHE_COHERENCY:
2498 return arm_smmu_master_canwbs(master);
2499 case IOMMU_CAP_NOEXEC:
2500 case IOMMU_CAP_DEFERRED_FLUSH:
2501 return true;
2502 case IOMMU_CAP_DIRTY_TRACKING:
2503 return arm_smmu_dbm_capable(master->smmu);
2504 default:
2505 return false;
2506 }
2507 }
2508
2509 static bool arm_smmu_enforce_cache_coherency(struct iommu_domain *domain)
2510 {
2511 struct arm_smmu_domain *smmu_domain = to_smmu_domain(domain);
2512 struct arm_smmu_master_domain *master_domain;
2513 unsigned long flags;
2514 bool ret = true;
2515
2516 spin_lock_irqsave(&smmu_domain->devices_lock, flags);
2517 list_for_each_entry(master_domain, &smmu_domain->devices,
2518 devices_elm) {
2519 if (!arm_smmu_master_canwbs(master_domain->master)) {
2520 ret = false;
2521 break;
2522 }
2523 }
2524 smmu_domain->enforce_cache_coherency = ret;
2525 spin_unlock_irqrestore(&smmu_domain->devices_lock, flags);
2526 return ret;
2527 }
2528
2529 struct arm_smmu_domain *arm_smmu_domain_alloc(void)
2530 {
2531 struct arm_smmu_domain *smmu_domain;
2532
2533 smmu_domain = kzalloc_obj(*smmu_domain);
2534 if (!smmu_domain)
2535 return ERR_PTR(-ENOMEM);
2536
2537 INIT_LIST_HEAD(&smmu_domain->devices);
2538 spin_lock_init(&smmu_domain->devices_lock);
2539
2540 return smmu_domain;
2541 }
2542
2543 static void arm_smmu_domain_free_paging(struct iommu_domain *domain)
2544 {
2545 struct arm_smmu_domain *smmu_domain = to_smmu_domain(domain);
2546 struct arm_smmu_device *smmu = smmu_domain->smmu;
2547
2548 free_io_pgtable_ops(smmu_domain->pgtbl_ops);
2549
2550 /* Free the ASID or VMID */
2551 if (smmu_domain->stage == ARM_SMMU_DOMAIN_S1) {
2552 /* Prevent SVA from touching the CD while we're freeing it */
2553 mutex_lock(&arm_smmu_asid_lock);
2554 xa_erase(&arm_smmu_asid_xa, smmu_domain->cd.asid);
2555 mutex_unlock(&arm_smmu_asid_lock);
2556 } else {
2557 struct arm_smmu_s2_cfg *cfg = &smmu_domain->s2_cfg;
2558 if (cfg->vmid)
2559 ida_free(&smmu->vmid_map, cfg->vmid);
2560 }
2561
2562 kfree(smmu_domain);
2563 }
2564
2565 static int arm_smmu_domain_finalise_s1(struct arm_smmu_device *smmu,
2566 struct arm_smmu_domain *smmu_domain)
2567 {
2568 int ret;
2569 u32 asid = 0;
2570 struct arm_smmu_ctx_desc *cd = &smmu_domain->cd;
2571
2572 /* Prevent SVA from modifying the ASID until it is written to the CD */
2573 mutex_lock(&arm_smmu_asid_lock);
2574 ret = xa_alloc(&arm_smmu_asid_xa, &asid, smmu_domain,
2575 XA_LIMIT(1, (1 << smmu->asid_bits) - 1), GFP_KERNEL);
2576 cd->asid = (u16)asid;
2577 mutex_unlock(&arm_smmu_asid_lock);
2578 return ret;
2579 }
2580
2581 static int arm_smmu_domain_finalise_s2(struct arm_smmu_device *smmu,
2582 struct arm_smmu_domain *smmu_domain)
2583 {
2584 int vmid;
2585 struct arm_smmu_s2_cfg *cfg = &smmu_domain->s2_cfg;
2586
2587 /* Reserve VMID 0 for stage-2 bypass STEs */
2588 vmid = ida_alloc_range(&smmu->vmid_map, 1, (1 << smmu->vmid_bits) - 1,
2589 GFP_KERNEL);
2590 if (vmid < 0)
2591 return vmid;
2592
2593 cfg->vmid = (u16)vmid;
2594 return 0;
2595 }
2596
2597 static int arm_smmu_domain_finalise(struct arm_smmu_domain *smmu_domain,
2598 struct arm_smmu_device *smmu, u32 flags)
2599 {
2600 int ret;
2601 enum io_pgtable_fmt fmt;
2602 struct io_pgtable_cfg pgtbl_cfg;
2603 struct io_pgtable_ops *pgtbl_ops;
2604 int (*finalise_stage_fn)(struct arm_smmu_device *smmu,
2605 struct arm_smmu_domain *smmu_domain);
2606 bool enable_dirty = flags & IOMMU_HWPT_ALLOC_DIRTY_TRACKING;
2607
2608 pgtbl_cfg = (struct io_pgtable_cfg) {
2609 .pgsize_bitmap = smmu->pgsize_bitmap,
2610 .coherent_walk = smmu->features & ARM_SMMU_FEAT_COHERENCY,
2611 .tlb = &arm_smmu_flush_ops,
2612 .iommu_dev = smmu->dev,
2613 };
2614
2615 switch (smmu_domain->stage) {
2616 case ARM_SMMU_DOMAIN_S1: {
2617 unsigned long ias = (smmu->features &
2618 ARM_SMMU_FEAT_VAX) ? 52 : 48;
2619
2620 pgtbl_cfg.ias = min_t(unsigned long, ias, VA_BITS);
2621 pgtbl_cfg.oas = smmu->oas;
2622 if (enable_dirty)
2623 pgtbl_cfg.quirks |= IO_PGTABLE_QUIRK_ARM_HD;
2624 fmt = ARM_64_LPAE_S1;
2625 finalise_stage_fn = arm_smmu_domain_finalise_s1;
2626 break;
2627 }
2628 case ARM_SMMU_DOMAIN_S2:
2629 if (enable_dirty)
2630 return -EOPNOTSUPP;
2631 pgtbl_cfg.ias = smmu->oas;
2632 pgtbl_cfg.oas = smmu->oas;
2633 fmt = ARM_64_LPAE_S2;
2634 finalise_stage_fn = arm_smmu_domain_finalise_s2;
2635 if ((smmu->features & ARM_SMMU_FEAT_S2FWB) &&
2636 (flags & IOMMU_HWPT_ALLOC_NEST_PARENT))
2637 pgtbl_cfg.quirks |= IO_PGTABLE_QUIRK_ARM_S2FWB;
2638 break;
2639 default:
2640 return -EINVAL;
2641 }
2642
2643 pgtbl_ops = alloc_io_pgtable_ops(fmt, &pgtbl_cfg, smmu_domain);
2644 if (!pgtbl_ops)
2645 return -ENOMEM;
2646
2647 smmu_domain->domain.pgsize_bitmap = pgtbl_cfg.pgsize_bitmap;
2648 smmu_domain->domain.geometry.aperture_end = (1UL << pgtbl_cfg.ias) - 1;
2649 smmu_domain->domain.geometry.force_aperture = true;
2650 if (enable_dirty && smmu_domain->stage == ARM_SMMU_DOMAIN_S1)
2651 smmu_domain->domain.dirty_ops = &arm_smmu_dirty_ops;
2652
2653 ret = finalise_stage_fn(smmu, smmu_domain);
2654 if (ret < 0) {
2655 free_io_pgtable_ops(pgtbl_ops);
2656 return ret;
2657 }
2658
2659 smmu_domain->pgtbl_ops = pgtbl_ops;
2660 smmu_domain->smmu = smmu;
2661 return 0;
2662 }
2663
2664 static struct arm_smmu_ste *
2665 arm_smmu_get_step_for_sid(struct arm_smmu_device *smmu, u32 sid)
2666 {
2667 struct arm_smmu_strtab_cfg *cfg = &smmu->strtab_cfg;
2668
2669 if (smmu->features & ARM_SMMU_FEAT_2_LVL_STRTAB) {
2670 /* Two-level walk */
2671 return &cfg->l2.l2ptrs[arm_smmu_strtab_l1_idx(sid)]
2672 ->stes[arm_smmu_strtab_l2_idx(sid)];
2673 } else {
2674 /* Simple linear lookup */
2675 return &cfg->linear.table[sid];
2676 }
2677 }
2678
2679 void arm_smmu_install_ste_for_dev(struct arm_smmu_master *master,
2680 const struct arm_smmu_ste *target)
2681 {
2682 int i, j;
2683 struct arm_smmu_device *smmu = master->smmu;
2684
2685 master->cd_table.in_ste =
2686 FIELD_GET(STRTAB_STE_0_CFG, le64_to_cpu(target->data[0])) ==
2687 STRTAB_STE_0_CFG_S1_TRANS;
2688 master->ste_ats_enabled =
2689 FIELD_GET(STRTAB_STE_1_EATS, le64_to_cpu(target->data[1])) ==
2690 STRTAB_STE_1_EATS_TRANS;
2691
2692 for (i = 0; i < master->num_streams; ++i) {
2693 u32 sid = master->streams[i].id;
2694 struct arm_smmu_ste *step =
2695 arm_smmu_get_step_for_sid(smmu, sid);
2696
2697 /* Bridged PCI devices may end up with duplicated IDs */
2698 for (j = 0; j < i; j++)
2699 if (master->streams[j].id == sid)
2700 break;
2701 if (j < i)
2702 continue;
2703
2704 arm_smmu_write_ste(master, sid, step, target);
2705 }
2706 }
2707
2708 static bool arm_smmu_ats_supported(struct arm_smmu_master *master)
2709 {
2710 struct device *dev = master->dev;
2711 struct arm_smmu_device *smmu = master->smmu;
2712 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
2713
2714 if (!(smmu->features & ARM_SMMU_FEAT_ATS))
2715 return false;
2716
2717 if (!(fwspec->flags & IOMMU_FWSPEC_PCI_RC_ATS))
2718 return false;
2719
2720 return dev_is_pci(dev) && pci_ats_supported(to_pci_dev(dev));
2721 }
2722
2723 static void arm_smmu_enable_ats(struct arm_smmu_master *master)
2724 {
2725 size_t stu;
2726 struct pci_dev *pdev;
2727 struct arm_smmu_device *smmu = master->smmu;
2728
2729 /* Smallest Translation Unit: log2 of the smallest supported granule */
2730 stu = __ffs(smmu->pgsize_bitmap);
2731 pdev = to_pci_dev(master->dev);
2732
2733 /*
2734 * ATC invalidation of PASID 0 causes the entire ATC to be flushed.
2735 */
2736 arm_smmu_atc_inv_master(master, IOMMU_NO_PASID);
2737 if (pci_enable_ats(pdev, stu))
2738 dev_err(master->dev, "Failed to enable ATS (STU %zu)\n", stu);
2739 }
2740
2741 static int arm_smmu_enable_pasid(struct arm_smmu_master *master)
2742 {
2743 int ret;
2744 int features;
2745 int num_pasids;
2746 struct pci_dev *pdev;
2747
2748 if (!dev_is_pci(master->dev))
2749 return -ENODEV;
2750
2751 pdev = to_pci_dev(master->dev);
2752
2753 features = pci_pasid_features(pdev);
2754 if (features < 0)
2755 return features;
2756
2757 num_pasids = pci_max_pasids(pdev);
2758 if (num_pasids <= 0)
2759 return num_pasids;
2760
2761 ret = pci_enable_pasid(pdev, features);
2762 if (ret) {
2763 dev_err(&pdev->dev, "Failed to enable PASID\n");
2764 return ret;
2765 }
2766
2767 master->ssid_bits = min_t(u8, ilog2(num_pasids),
2768 master->smmu->ssid_bits);
2769 return 0;
2770 }
2771
2772 static void arm_smmu_disable_pasid(struct arm_smmu_master *master)
2773 {
2774 struct pci_dev *pdev;
2775
2776 if (!dev_is_pci(master->dev))
2777 return;
2778
2779 pdev = to_pci_dev(master->dev);
2780
2781 if (!pdev->pasid_enabled)
2782 return;
2783
2784 master->ssid_bits = 0;
2785 pci_disable_pasid(pdev);
2786 }
2787
2788 static struct arm_smmu_master_domain *
2789 arm_smmu_find_master_domain(struct arm_smmu_domain *smmu_domain,
2790 struct iommu_domain *domain,
2791 struct arm_smmu_master *master,
2792 ioasid_t ssid, bool nested_ats_flush)
2793 {
2794 struct arm_smmu_master_domain *master_domain;
2795
2796 lockdep_assert_held(&smmu_domain->devices_lock);
2797
2798 list_for_each_entry(master_domain, &smmu_domain->devices,
2799 devices_elm) {
2800 if (master_domain->master == master &&
2801 master_domain->domain == domain &&
2802 master_domain->ssid == ssid &&
2803 master_domain->nested_ats_flush == nested_ats_flush)
2804 return master_domain;
2805 }
2806 return NULL;
2807 }
2808
2809 /*
2810 * If the domain uses the smmu_domain->devices list return the arm_smmu_domain
2811 * structure, otherwise NULL. These domains track attached devices so they can
2812 * issue invalidations.
2813 */
2814 static struct arm_smmu_domain *
2815 to_smmu_domain_devices(struct iommu_domain *domain)
2816 {
2817 /* The domain can be NULL only when processing the first attach */
2818 if (!domain)
2819 return NULL;
2820 if ((domain->type & __IOMMU_DOMAIN_PAGING) ||
2821 domain->type == IOMMU_DOMAIN_SVA)
2822 return to_smmu_domain(domain);
2823 if (domain->type == IOMMU_DOMAIN_NESTED)
2824 return to_smmu_nested_domain(domain)->vsmmu->s2_parent;
2825 return NULL;
2826 }
2827
2828 static int arm_smmu_enable_iopf(struct arm_smmu_master *master,
2829 struct arm_smmu_master_domain *master_domain)
2830 {
2831 int ret;
2832
2833 iommu_group_mutex_assert(master->dev);
2834
2835 if (!IS_ENABLED(CONFIG_ARM_SMMU_V3_SVA))
2836 return -EOPNOTSUPP;
2837
2838 /*
2839 * Drivers for devices supporting PRI or stall require iopf others have
2840 * device-specific fault handlers and don't need IOPF, so this is not a
2841 * failure.
2842 */
2843 if (!master->stall_enabled)
2844 return 0;
2845
2846 /* We're not keeping track of SIDs in fault events */
2847 if (master->num_streams != 1)
2848 return -EOPNOTSUPP;
2849
2850 if (master->iopf_refcount) {
2851 master->iopf_refcount++;
2852 master_domain->using_iopf = true;
2853 return 0;
2854 }
2855
2856 ret = iopf_queue_add_device(master->smmu->evtq.iopf, master->dev);
2857 if (ret)
2858 return ret;
2859 master->iopf_refcount = 1;
2860 master_domain->using_iopf = true;
2861 return 0;
2862 }
2863
2864 static void arm_smmu_disable_iopf(struct arm_smmu_master *master,
2865 struct arm_smmu_master_domain *master_domain)
2866 {
2867 iommu_group_mutex_assert(master->dev);
2868
2869 if (!IS_ENABLED(CONFIG_ARM_SMMU_V3_SVA))
2870 return;
2871
2872 if (!master_domain || !master_domain->using_iopf)
2873 return;
2874
2875 master->iopf_refcount--;
2876 if (master->iopf_refcount == 0)
2877 iopf_queue_remove_device(master->smmu->evtq.iopf, master->dev);
2878 }
2879
2880 static void arm_smmu_remove_master_domain(struct arm_smmu_master *master,
2881 struct iommu_domain *domain,
2882 ioasid_t ssid)
2883 {
2884 struct arm_smmu_domain *smmu_domain = to_smmu_domain_devices(domain);
2885 struct arm_smmu_master_domain *master_domain;
2886 bool nested_ats_flush = false;
2887 unsigned long flags;
2888
2889 if (!smmu_domain)
2890 return;
2891
2892 if (domain->type == IOMMU_DOMAIN_NESTED)
2893 nested_ats_flush = to_smmu_nested_domain(domain)->enable_ats;
2894
2895 spin_lock_irqsave(&smmu_domain->devices_lock, flags);
2896 master_domain = arm_smmu_find_master_domain(smmu_domain, domain, master,
2897 ssid, nested_ats_flush);
2898 if (master_domain) {
2899 list_del(&master_domain->devices_elm);
2900 if (master->ats_enabled)
2901 atomic_dec(&smmu_domain->nr_ats_masters);
2902 }
2903 spin_unlock_irqrestore(&smmu_domain->devices_lock, flags);
2904
2905 arm_smmu_disable_iopf(master, master_domain);
2906 kfree(master_domain);
2907 }
2908
2909 /*
2910 * Start the sequence to attach a domain to a master. The sequence contains three
2911 * steps:
2912 * arm_smmu_attach_prepare()
2913 * arm_smmu_install_ste_for_dev()
2914 * arm_smmu_attach_commit()
2915 *
2916 * If prepare succeeds then the sequence must be completed. The STE installed
2917 * must set the STE.EATS field according to state.ats_enabled.
2918 *
2919 * If the device supports ATS then this determines if EATS should be enabled
2920 * in the STE, and starts sequencing EATS disable if required.
2921 *
2922 * The change of the EATS in the STE and the PCI ATS config space is managed by
2923 * this sequence to be in the right order so that if PCI ATS is enabled then
2924 * STE.ETAS is enabled.
2925 *
2926 * new_domain can be a non-paging domain. In this case ATS will not be enabled,
2927 * and invalidations won't be tracked.
2928 */
2929 int arm_smmu_attach_prepare(struct arm_smmu_attach_state *state,
2930 struct iommu_domain *new_domain)
2931 {
2932 struct arm_smmu_master *master = state->master;
2933 struct arm_smmu_master_domain *master_domain;
2934 struct arm_smmu_domain *smmu_domain =
2935 to_smmu_domain_devices(new_domain);
2936 unsigned long flags;
2937 int ret;
2938
2939 /*
2940 * arm_smmu_share_asid() must not see two domains pointing to the same
2941 * arm_smmu_master_domain contents otherwise it could randomly write one
2942 * or the other to the CD.
2943 */
2944 lockdep_assert_held(&arm_smmu_asid_lock);
2945
2946 if (smmu_domain || state->cd_needs_ats) {
2947 /*
2948 * The SMMU does not support enabling ATS with bypass/abort.
2949 * When the STE is in bypass (STE.Config[2:0] == 0b100), ATS
2950 * Translation Requests and Translated transactions are denied
2951 * as though ATS is disabled for the stream (STE.EATS == 0b00),
2952 * causing F_BAD_ATS_TREQ and F_TRANSL_FORBIDDEN events
2953 * (IHI0070Ea 5.2 Stream Table Entry).
2954 *
2955 * However, if we have installed a CD table and are using S1DSS
2956 * then ATS will work in S1DSS bypass. See "13.6.4 Full ATS
2957 * skipping stage 1".
2958 *
2959 * Disable ATS if we are going to create a normal 0b100 bypass
2960 * STE.
2961 */
2962 state->ats_enabled = !state->disable_ats &&
2963 arm_smmu_ats_supported(master);
2964 }
2965
2966 if (smmu_domain) {
2967 if (new_domain->type == IOMMU_DOMAIN_NESTED) {
2968 ret = arm_smmu_attach_prepare_vmaster(
2969 state, to_smmu_nested_domain(new_domain));
2970 if (ret)
2971 return ret;
2972 }
2973
2974 master_domain = kzalloc_obj(*master_domain);
2975 if (!master_domain) {
2976 ret = -ENOMEM;
2977 goto err_free_vmaster;
2978 }
2979 master_domain->domain = new_domain;
2980 master_domain->master = master;
2981 master_domain->ssid = state->ssid;
2982 if (new_domain->type == IOMMU_DOMAIN_NESTED)
2983 master_domain->nested_ats_flush =
2984 to_smmu_nested_domain(new_domain)->enable_ats;
2985
2986 if (new_domain->iopf_handler) {
2987 ret = arm_smmu_enable_iopf(master, master_domain);
2988 if (ret)
2989 goto err_free_master_domain;
2990 }
2991
2992 /*
2993 * During prepare we want the current smmu_domain and new
2994 * smmu_domain to be in the devices list before we change any
2995 * HW. This ensures that both domains will send ATS
2996 * invalidations to the master until we are done.
2997 *
2998 * It is tempting to make this list only track masters that are
2999 * using ATS, but arm_smmu_share_asid() also uses this to change
3000 * the ASID of a domain, unrelated to ATS.
3001 *
3002 * Notice if we are re-attaching the same domain then the list
3003 * will have two identical entries and commit will remove only
3004 * one of them.
3005 */
3006 spin_lock_irqsave(&smmu_domain->devices_lock, flags);
3007 if (smmu_domain->enforce_cache_coherency &&
3008 !arm_smmu_master_canwbs(master)) {
3009 spin_unlock_irqrestore(&smmu_domain->devices_lock,
3010 flags);
3011 ret = -EINVAL;
3012 goto err_iopf;
3013 }
3014
3015 if (state->ats_enabled)
3016 atomic_inc(&smmu_domain->nr_ats_masters);
3017 list_add(&master_domain->devices_elm, &smmu_domain->devices);
3018 spin_unlock_irqrestore(&smmu_domain->devices_lock, flags);
3019 }
3020
3021 if (!state->ats_enabled && master->ats_enabled) {
3022 pci_disable_ats(to_pci_dev(master->dev));
3023 /*
3024 * This is probably overkill, but the config write for disabling
3025 * ATS should complete before the STE is configured to generate
3026 * UR to avoid AER noise.
3027 */
3028 wmb();
3029 }
3030 return 0;
3031
3032 err_iopf:
3033 arm_smmu_disable_iopf(master, master_domain);
3034 err_free_master_domain:
3035 kfree(master_domain);
3036 err_free_vmaster:
3037 kfree(state->vmaster);
3038 return ret;
3039 }
3040
3041 /*
3042 * Commit is done after the STE/CD are configured with the EATS setting. It
3043 * completes synchronizing the PCI device's ATC and finishes manipulating the
3044 * smmu_domain->devices list.
3045 */
3046 void arm_smmu_attach_commit(struct arm_smmu_attach_state *state)
3047 {
3048 struct arm_smmu_master *master = state->master;
3049
3050 lockdep_assert_held(&arm_smmu_asid_lock);
3051
3052 arm_smmu_attach_commit_vmaster(state);
3053
3054 if (state->ats_enabled && !master->ats_enabled) {
3055 arm_smmu_enable_ats(master);
3056 } else if (state->ats_enabled && master->ats_enabled) {
3057 /*
3058 * The translation has changed, flush the ATC. At this point the
3059 * SMMU is translating for the new domain and both the old&new
3060 * domain will issue invalidations.
3061 */
3062 arm_smmu_atc_inv_master(master, state->ssid);
3063 } else if (!state->ats_enabled && master->ats_enabled) {
3064 /* ATS is being switched off, invalidate the entire ATC */
3065 arm_smmu_atc_inv_master(master, IOMMU_NO_PASID);
3066 }
3067
3068 arm_smmu_remove_master_domain(master, state->old_domain, state->ssid);
3069 master->ats_enabled = state->ats_enabled;
3070 }
3071
3072 static int arm_smmu_attach_dev(struct iommu_domain *domain, struct device *dev,
3073 struct iommu_domain *old_domain)
3074 {
3075 int ret = 0;
3076 struct arm_smmu_ste target;
3077 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
3078 struct arm_smmu_device *smmu;
3079 struct arm_smmu_domain *smmu_domain = to_smmu_domain(domain);
3080 struct arm_smmu_attach_state state = {
3081 .old_domain = old_domain,
3082 .ssid = IOMMU_NO_PASID,
3083 };
3084 struct arm_smmu_master *master;
3085 struct arm_smmu_cd *cdptr;
3086
3087 if (!fwspec)
3088 return -ENOENT;
3089
3090 state.master = master = dev_iommu_priv_get(dev);
3091 smmu = master->smmu;
3092
3093 if (smmu_domain->smmu != smmu)
3094 return -EINVAL;
3095
3096 if (smmu_domain->stage == ARM_SMMU_DOMAIN_S1) {
3097 cdptr = arm_smmu_alloc_cd_ptr(master, IOMMU_NO_PASID);
3098 if (!cdptr)
3099 return -ENOMEM;
3100 } else if (arm_smmu_ssids_in_use(&master->cd_table))
3101 return -EBUSY;
3102
3103 /*
3104 * Prevent arm_smmu_share_asid() from trying to change the ASID
3105 * of either the old or new domain while we are working on it.
3106 * This allows the STE and the smmu_domain->devices list to
3107 * be inconsistent during this routine.
3108 */
3109 mutex_lock(&arm_smmu_asid_lock);
3110
3111 ret = arm_smmu_attach_prepare(&state, domain);
3112 if (ret) {
3113 mutex_unlock(&arm_smmu_asid_lock);
3114 return ret;
3115 }
3116
3117 switch (smmu_domain->stage) {
3118 case ARM_SMMU_DOMAIN_S1: {
3119 struct arm_smmu_cd target_cd;
3120
3121 arm_smmu_make_s1_cd(&target_cd, master, smmu_domain);
3122 arm_smmu_write_cd_entry(master, IOMMU_NO_PASID, cdptr,
3123 &target_cd);
3124 arm_smmu_make_cdtable_ste(&target, master, state.ats_enabled,
3125 STRTAB_STE_1_S1DSS_SSID0);
3126 arm_smmu_install_ste_for_dev(master, &target);
3127 break;
3128 }
3129 case ARM_SMMU_DOMAIN_S2:
3130 arm_smmu_make_s2_domain_ste(&target, master, smmu_domain,
3131 state.ats_enabled);
3132 arm_smmu_install_ste_for_dev(master, &target);
3133 arm_smmu_clear_cd(master, IOMMU_NO_PASID);
3134 break;
3135 }
3136
3137 arm_smmu_attach_commit(&state);
3138 mutex_unlock(&arm_smmu_asid_lock);
3139 return 0;
3140 }
3141
3142 static int arm_smmu_s1_set_dev_pasid(struct iommu_domain *domain,
3143 struct device *dev, ioasid_t id,
3144 struct iommu_domain *old)
3145 {
3146 struct arm_smmu_domain *smmu_domain = to_smmu_domain(domain);
3147 struct arm_smmu_master *master = dev_iommu_priv_get(dev);
3148 struct arm_smmu_device *smmu = master->smmu;
3149 struct arm_smmu_cd target_cd;
3150
3151 if (smmu_domain->smmu != smmu)
3152 return -EINVAL;
3153
3154 if (smmu_domain->stage != ARM_SMMU_DOMAIN_S1)
3155 return -EINVAL;
3156
3157 /*
3158 * We can read cd.asid outside the lock because arm_smmu_set_pasid()
3159 * will fix it
3160 */
3161 arm_smmu_make_s1_cd(&target_cd, master, smmu_domain);
3162 return arm_smmu_set_pasid(master, to_smmu_domain(domain), id,
3163 &target_cd, old);
3164 }
3165
3166 static void arm_smmu_update_ste(struct arm_smmu_master *master,
3167 struct iommu_domain *sid_domain,
3168 bool ats_enabled)
3169 {
3170 unsigned int s1dss = STRTAB_STE_1_S1DSS_TERMINATE;
3171 struct arm_smmu_ste ste;
3172
3173 if (master->cd_table.in_ste && master->ste_ats_enabled == ats_enabled)
3174 return;
3175
3176 if (sid_domain->type == IOMMU_DOMAIN_IDENTITY)
3177 s1dss = STRTAB_STE_1_S1DSS_BYPASS;
3178 else
3179 WARN_ON(sid_domain->type != IOMMU_DOMAIN_BLOCKED);
3180
3181 /*
3182 * Change the STE into a cdtable one with SID IDENTITY/BLOCKED behavior
3183 * using s1dss if necessary. If the cd_table is already installed then
3184 * the S1DSS is correct and this will just update the EATS. Otherwise it
3185 * installs the entire thing. This will be hitless.
3186 */
3187 arm_smmu_make_cdtable_ste(&ste, master, ats_enabled, s1dss);
3188 arm_smmu_install_ste_for_dev(master, &ste);
3189 }
3190
3191 int arm_smmu_set_pasid(struct arm_smmu_master *master,
3192 struct arm_smmu_domain *smmu_domain, ioasid_t pasid,
3193 struct arm_smmu_cd *cd, struct iommu_domain *old)
3194 {
3195 struct iommu_domain *sid_domain =
3196 iommu_driver_get_domain_for_dev(master->dev);
3197 struct arm_smmu_attach_state state = {
3198 .master = master,
3199 .ssid = pasid,
3200 .old_domain = old,
3201 };
3202 struct arm_smmu_cd *cdptr;
3203 int ret;
3204
3205 /* The core code validates pasid */
3206
3207 if (smmu_domain->smmu != master->smmu)
3208 return -EINVAL;
3209
3210 if (!master->cd_table.in_ste &&
3211 sid_domain->type != IOMMU_DOMAIN_IDENTITY &&
3212 sid_domain->type != IOMMU_DOMAIN_BLOCKED)
3213 return -EINVAL;
3214
3215 cdptr = arm_smmu_alloc_cd_ptr(master, pasid);
3216 if (!cdptr)
3217 return -ENOMEM;
3218
3219 mutex_lock(&arm_smmu_asid_lock);
3220 ret = arm_smmu_attach_prepare(&state, &smmu_domain->domain);
3221 if (ret)
3222 goto out_unlock;
3223
3224 /*
3225 * We don't want to obtain to the asid_lock too early, so fix up the
3226 * caller set ASID under the lock in case it changed.
3227 */
3228 cd->data[0] &= ~cpu_to_le64(CTXDESC_CD_0_ASID);
3229 cd->data[0] |= cpu_to_le64(
3230 FIELD_PREP(CTXDESC_CD_0_ASID, smmu_domain->cd.asid));
3231
3232 arm_smmu_write_cd_entry(master, pasid, cdptr, cd);
3233 arm_smmu_update_ste(master, sid_domain, state.ats_enabled);
3234
3235 arm_smmu_attach_commit(&state);
3236
3237 out_unlock:
3238 mutex_unlock(&arm_smmu_asid_lock);
3239 return ret;
3240 }
3241
3242 static int arm_smmu_blocking_set_dev_pasid(struct iommu_domain *new_domain,
3243 struct device *dev, ioasid_t pasid,
3244 struct iommu_domain *old_domain)
3245 {
3246 struct arm_smmu_domain *smmu_domain = to_smmu_domain(old_domain);
3247 struct arm_smmu_master *master = dev_iommu_priv_get(dev);
3248
3249 mutex_lock(&arm_smmu_asid_lock);
3250 arm_smmu_clear_cd(master, pasid);
3251 if (master->ats_enabled)
3252 arm_smmu_atc_inv_master(master, pasid);
3253 arm_smmu_remove_master_domain(master, &smmu_domain->domain, pasid);
3254 mutex_unlock(&arm_smmu_asid_lock);
3255
3256 /*
3257 * When the last user of the CD table goes away downgrade the STE back
3258 * to a non-cd_table one, by re-attaching its sid_domain.
3259 */
3260 if (!arm_smmu_ssids_in_use(&master->cd_table)) {
3261 struct iommu_domain *sid_domain =
3262 iommu_driver_get_domain_for_dev(master->dev);
3263
3264 if (sid_domain->type == IOMMU_DOMAIN_IDENTITY ||
3265 sid_domain->type == IOMMU_DOMAIN_BLOCKED)
3266 sid_domain->ops->attach_dev(sid_domain, dev,
3267 sid_domain);
3268 }
3269 return 0;
3270 }
3271
3272 static void arm_smmu_attach_dev_ste(struct iommu_domain *domain,
3273 struct iommu_domain *old_domain,
3274 struct device *dev,
3275 struct arm_smmu_ste *ste,
3276 unsigned int s1dss)
3277 {
3278 struct arm_smmu_master *master = dev_iommu_priv_get(dev);
3279 struct arm_smmu_attach_state state = {
3280 .master = master,
3281 .old_domain = old_domain,
3282 .ssid = IOMMU_NO_PASID,
3283 };
3284
3285 /*
3286 * Do not allow any ASID to be changed while are working on the STE,
3287 * otherwise we could miss invalidations.
3288 */
3289 mutex_lock(&arm_smmu_asid_lock);
3290
3291 /*
3292 * If the CD table is not in use we can use the provided STE, otherwise
3293 * we use a cdtable STE with the provided S1DSS.
3294 */
3295 if (arm_smmu_ssids_in_use(&master->cd_table)) {
3296 /*
3297 * If a CD table has to be present then we need to run with ATS
3298 * on because we have to assume a PASID is using ATS. For
3299 * IDENTITY this will setup things so that S1DSS=bypass which
3300 * follows the explanation in "13.6.4 Full ATS skipping stage 1"
3301 * and allows for ATS on the RID to work.
3302 */
3303 state.cd_needs_ats = true;
3304 arm_smmu_attach_prepare(&state, domain);
3305 arm_smmu_make_cdtable_ste(ste, master, state.ats_enabled, s1dss);
3306 } else {
3307 arm_smmu_attach_prepare(&state, domain);
3308 }
3309 arm_smmu_install_ste_for_dev(master, ste);
3310 arm_smmu_attach_commit(&state);
3311 mutex_unlock(&arm_smmu_asid_lock);
3312
3313 /*
3314 * This has to be done after removing the master from the
3315 * arm_smmu_domain->devices to avoid races updating the same context
3316 * descriptor from arm_smmu_share_asid().
3317 */
3318 arm_smmu_clear_cd(master, IOMMU_NO_PASID);
3319 }
3320
3321 static int arm_smmu_attach_dev_identity(struct iommu_domain *domain,
3322 struct device *dev,
3323 struct iommu_domain *old_domain)
3324 {
3325 struct arm_smmu_ste ste;
3326 struct arm_smmu_master *master = dev_iommu_priv_get(dev);
3327
3328 arm_smmu_master_clear_vmaster(master);
3329 arm_smmu_make_bypass_ste(master->smmu, &ste);
3330 arm_smmu_attach_dev_ste(domain, old_domain, dev, &ste,
3331 STRTAB_STE_1_S1DSS_BYPASS);
3332 return 0;
3333 }
3334
3335 static const struct iommu_domain_ops arm_smmu_identity_ops = {
3336 .attach_dev = arm_smmu_attach_dev_identity,
3337 };
3338
3339 static struct iommu_domain arm_smmu_identity_domain = {
3340 .type = IOMMU_DOMAIN_IDENTITY,
3341 .ops = &arm_smmu_identity_ops,
3342 };
3343
3344 static int arm_smmu_attach_dev_blocked(struct iommu_domain *domain,
3345 struct device *dev,
3346 struct iommu_domain *old_domain)
3347 {
3348 struct arm_smmu_ste ste;
3349 struct arm_smmu_master *master = dev_iommu_priv_get(dev);
3350
3351 arm_smmu_master_clear_vmaster(master);
3352 arm_smmu_make_abort_ste(&ste);
3353 arm_smmu_attach_dev_ste(domain, old_domain, dev, &ste,
3354 STRTAB_STE_1_S1DSS_TERMINATE);
3355 return 0;
3356 }
3357
3358 static const struct iommu_domain_ops arm_smmu_blocked_ops = {
3359 .attach_dev = arm_smmu_attach_dev_blocked,
3360 .set_dev_pasid = arm_smmu_blocking_set_dev_pasid,
3361 };
3362
3363 static struct iommu_domain arm_smmu_blocked_domain = {
3364 .type = IOMMU_DOMAIN_BLOCKED,
3365 .ops = &arm_smmu_blocked_ops,
3366 };
3367
3368 static struct iommu_domain *
3369 arm_smmu_domain_alloc_paging_flags(struct device *dev, u32 flags,
3370 const struct iommu_user_data *user_data)
3371 {
3372 struct arm_smmu_master *master = dev_iommu_priv_get(dev);
3373 struct arm_smmu_device *smmu = master->smmu;
3374 const u32 PAGING_FLAGS = IOMMU_HWPT_ALLOC_DIRTY_TRACKING |
3375 IOMMU_HWPT_ALLOC_PASID |
3376 IOMMU_HWPT_ALLOC_NEST_PARENT;
3377 struct arm_smmu_domain *smmu_domain;
3378 int ret;
3379
3380 if (flags & ~PAGING_FLAGS)
3381 return ERR_PTR(-EOPNOTSUPP);
3382 if (user_data)
3383 return ERR_PTR(-EOPNOTSUPP);
3384
3385 smmu_domain = arm_smmu_domain_alloc();
3386 if (IS_ERR(smmu_domain))
3387 return ERR_CAST(smmu_domain);
3388
3389 switch (flags) {
3390 case 0:
3391 /* Prefer S1 if available */
3392 if (smmu->features & ARM_SMMU_FEAT_TRANS_S1)
3393 smmu_domain->stage = ARM_SMMU_DOMAIN_S1;
3394 else
3395 smmu_domain->stage = ARM_SMMU_DOMAIN_S2;
3396 break;
3397 case IOMMU_HWPT_ALLOC_NEST_PARENT:
3398 if (!(smmu->features & ARM_SMMU_FEAT_NESTING)) {
3399 ret = -EOPNOTSUPP;
3400 goto err_free;
3401 }
3402 smmu_domain->stage = ARM_SMMU_DOMAIN_S2;
3403 smmu_domain->nest_parent = true;
3404 break;
3405 case IOMMU_HWPT_ALLOC_DIRTY_TRACKING:
3406 case IOMMU_HWPT_ALLOC_DIRTY_TRACKING | IOMMU_HWPT_ALLOC_PASID:
3407 case IOMMU_HWPT_ALLOC_PASID:
3408 if (!(smmu->features & ARM_SMMU_FEAT_TRANS_S1)) {
3409 ret = -EOPNOTSUPP;
3410 goto err_free;
3411 }
3412 smmu_domain->stage = ARM_SMMU_DOMAIN_S1;
3413 break;
3414 default:
3415 ret = -EOPNOTSUPP;
3416 goto err_free;
3417 }
3418
3419 smmu_domain->domain.type = IOMMU_DOMAIN_UNMANAGED;
3420 smmu_domain->domain.ops = arm_smmu_ops.default_domain_ops;
3421 ret = arm_smmu_domain_finalise(smmu_domain, smmu, flags);
3422 if (ret)
3423 goto err_free;
3424 return &smmu_domain->domain;
3425
3426 err_free:
3427 kfree(smmu_domain);
3428 return ERR_PTR(ret);
3429 }
3430
3431 static int arm_smmu_map_pages(struct iommu_domain *domain, unsigned long iova,
3432 phys_addr_t paddr, size_t pgsize, size_t pgcount,
3433 int prot, gfp_t gfp, size_t *mapped)
3434 {
3435 struct io_pgtable_ops *ops = to_smmu_domain(domain)->pgtbl_ops;
3436
3437 if (!ops)
3438 return -ENODEV;
3439
3440 return ops->map_pages(ops, iova, paddr, pgsize, pgcount, prot, gfp, mapped);
3441 }
3442
3443 static size_t arm_smmu_unmap_pages(struct iommu_domain *domain, unsigned long iova,
3444 size_t pgsize, size_t pgcount,
3445 struct iommu_iotlb_gather *gather)
3446 {
3447 struct arm_smmu_domain *smmu_domain = to_smmu_domain(domain);
3448 struct io_pgtable_ops *ops = smmu_domain->pgtbl_ops;
3449
3450 if (!ops)
3451 return 0;
3452
3453 return ops->unmap_pages(ops, iova, pgsize, pgcount, gather);
3454 }
3455
3456 static void arm_smmu_flush_iotlb_all(struct iommu_domain *domain)
3457 {
3458 struct arm_smmu_domain *smmu_domain = to_smmu_domain(domain);
3459
3460 if (smmu_domain->smmu)
3461 arm_smmu_tlb_inv_context(smmu_domain);
3462 }
3463
3464 static void arm_smmu_iotlb_sync(struct iommu_domain *domain,
3465 struct iommu_iotlb_gather *gather)
3466 {
3467 struct arm_smmu_domain *smmu_domain = to_smmu_domain(domain);
3468
3469 if (!gather->pgsize)
3470 return;
3471
3472 arm_smmu_tlb_inv_range_domain(gather->start,
3473 gather->end - gather->start + 1,
3474 gather->pgsize, true, smmu_domain);
3475 }
3476
3477 static phys_addr_t
3478 arm_smmu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
3479 {
3480 struct io_pgtable_ops *ops = to_smmu_domain(domain)->pgtbl_ops;
3481
3482 if (!ops)
3483 return 0;
3484
3485 return ops->iova_to_phys(ops, iova);
3486 }
3487
3488 static struct platform_driver arm_smmu_driver;
3489
3490 static
3491 struct arm_smmu_device *arm_smmu_get_by_fwnode(struct fwnode_handle *fwnode)
3492 {
3493 struct device *dev = bus_find_device_by_fwnode(&platform_bus_type, fwnode);
3494
3495 put_device(dev);
3496 return dev ? dev_get_drvdata(dev) : NULL;
3497 }
3498
3499 static bool arm_smmu_sid_in_range(struct arm_smmu_device *smmu, u32 sid)
3500 {
3501 if (smmu->features & ARM_SMMU_FEAT_2_LVL_STRTAB)
3502 return arm_smmu_strtab_l1_idx(sid) < smmu->strtab_cfg.l2.num_l1_ents;
3503 return sid < smmu->strtab_cfg.linear.num_ents;
3504 }
3505
3506 static int arm_smmu_init_sid_strtab(struct arm_smmu_device *smmu, u32 sid)
3507 {
3508 /* Check the SIDs are in range of the SMMU and our stream table */
3509 if (!arm_smmu_sid_in_range(smmu, sid))
3510 return -ERANGE;
3511
3512 /* Ensure l2 strtab is initialised */
3513 if (smmu->features & ARM_SMMU_FEAT_2_LVL_STRTAB)
3514 return arm_smmu_init_l2_strtab(smmu, sid);
3515
3516 return 0;
3517 }
3518
3519 static int arm_smmu_insert_master(struct arm_smmu_device *smmu,
3520 struct arm_smmu_master *master)
3521 {
3522 int i;
3523 int ret = 0;
3524 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(master->dev);
3525
3526 master->streams = kzalloc_objs(*master->streams, fwspec->num_ids);
3527 if (!master->streams)
3528 return -ENOMEM;
3529 master->num_streams = fwspec->num_ids;
3530
3531 mutex_lock(&smmu->streams_mutex);
3532 for (i = 0; i < fwspec->num_ids; i++) {
3533 struct arm_smmu_stream *new_stream = &master->streams[i];
3534 struct rb_node *existing;
3535 u32 sid = fwspec->ids[i];
3536
3537 new_stream->id = sid;
3538 new_stream->master = master;
3539
3540 ret = arm_smmu_init_sid_strtab(smmu, sid);
3541 if (ret)
3542 break;
3543
3544 /* Insert into SID tree */
3545 existing = rb_find_add(&new_stream->node, &smmu->streams,
3546 arm_smmu_streams_cmp_node);
3547 if (existing) {
3548 struct arm_smmu_master *existing_master =
3549 rb_entry(existing, struct arm_smmu_stream, node)
3550 ->master;
3551
3552 /* Bridged PCI devices may end up with duplicated IDs */
3553 if (existing_master == master)
3554 continue;
3555
3556 dev_warn(master->dev,
3557 "Aliasing StreamID 0x%x (from %s) unsupported, expect DMA to be broken\n",
3558 sid, dev_name(existing_master->dev));
3559 ret = -ENODEV;
3560 break;
3561 }
3562 }
3563
3564 if (ret) {
3565 for (i--; i >= 0; i--)
3566 rb_erase(&master->streams[i].node, &smmu->streams);
3567 kfree(master->streams);
3568 }
3569 mutex_unlock(&smmu->streams_mutex);
3570
3571 return ret;
3572 }
3573
3574 static void arm_smmu_remove_master(struct arm_smmu_master *master)
3575 {
3576 int i;
3577 struct arm_smmu_device *smmu = master->smmu;
3578 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(master->dev);
3579
3580 if (!smmu || !master->streams)
3581 return;
3582
3583 mutex_lock(&smmu->streams_mutex);
3584 for (i = 0; i < fwspec->num_ids; i++)
3585 rb_erase(&master->streams[i].node, &smmu->streams);
3586 mutex_unlock(&smmu->streams_mutex);
3587
3588 kfree(master->streams);
3589 }
3590
3591 static struct iommu_device *arm_smmu_probe_device(struct device *dev)
3592 {
3593 int ret;
3594 struct arm_smmu_device *smmu;
3595 struct arm_smmu_master *master;
3596 struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
3597
3598 if (WARN_ON_ONCE(dev_iommu_priv_get(dev)))
3599 return ERR_PTR(-EBUSY);
3600
3601 smmu = arm_smmu_get_by_fwnode(fwspec->iommu_fwnode);
3602 if (!smmu)
3603 return ERR_PTR(-ENODEV);
3604
3605 master = kzalloc_obj(*master);
3606 if (!master)
3607 return ERR_PTR(-ENOMEM);
3608
3609 master->dev = dev;
3610 master->smmu = smmu;
3611 dev_iommu_priv_set(dev, master);
3612
3613 ret = arm_smmu_insert_master(smmu, master);
3614 if (ret)
3615 goto err_free_master;
3616
3617 device_property_read_u32(dev, "pasid-num-bits", &master->ssid_bits);
3618 master->ssid_bits = min(smmu->ssid_bits, master->ssid_bits);
3619
3620 /*
3621 * Note that PASID must be enabled before, and disabled after ATS:
3622 * PCI Express Base 4.0r1.0 - 10.5.1.3 ATS Control Register
3623 *
3624 * Behavior is undefined if this bit is Set and the value of the PASID
3625 * Enable, Execute Requested Enable, or Privileged Mode Requested bits
3626 * are changed.
3627 */
3628 arm_smmu_enable_pasid(master);
3629
3630 if (!(smmu->features & ARM_SMMU_FEAT_2_LVL_CDTAB))
3631 master->ssid_bits = min_t(u8, master->ssid_bits,
3632 CTXDESC_LINEAR_CDMAX);
3633
3634 if ((smmu->features & ARM_SMMU_FEAT_STALLS &&
3635 device_property_read_bool(dev, "dma-can-stall")) ||
3636 smmu->features & ARM_SMMU_FEAT_STALL_FORCE)
3637 master->stall_enabled = true;
3638
3639 if (dev_is_pci(dev)) {
3640 unsigned int stu = __ffs(smmu->pgsize_bitmap);
3641
3642 pci_prepare_ats(to_pci_dev(dev), stu);
3643 }
3644
3645 return &smmu->iommu;
3646
3647 err_free_master:
3648 kfree(master);
3649 return ERR_PTR(ret);
3650 }
3651
3652 static void arm_smmu_release_device(struct device *dev)
3653 {
3654 struct arm_smmu_master *master = dev_iommu_priv_get(dev);
3655
3656 WARN_ON(master->iopf_refcount);
3657
3658 arm_smmu_disable_pasid(master);
3659 arm_smmu_remove_master(master);
3660 if (arm_smmu_cdtab_allocated(&master->cd_table))
3661 arm_smmu_free_cd_tables(master);
3662 kfree(master);
3663 }
3664
3665 static int arm_smmu_read_and_clear_dirty(struct iommu_domain *domain,
3666 unsigned long iova, size_t size,
3667 unsigned long flags,
3668 struct iommu_dirty_bitmap *dirty)
3669 {
3670 struct arm_smmu_domain *smmu_domain = to_smmu_domain(domain);
3671 struct io_pgtable_ops *ops = smmu_domain->pgtbl_ops;
3672
3673 return ops->read_and_clear_dirty(ops, iova, size, flags, dirty);
3674 }
3675
3676 static int arm_smmu_set_dirty_tracking(struct iommu_domain *domain,
3677 bool enabled)
3678 {
3679 /*
3680 * Always enabled and the dirty bitmap is cleared prior to
3681 * set_dirty_tracking().
3682 */
3683 return 0;
3684 }
3685
3686 static struct iommu_group *arm_smmu_device_group(struct device *dev)
3687 {
3688 struct iommu_group *group;
3689
3690 /*
3691 * We don't support devices sharing stream IDs other than PCI RID
3692 * aliases, since the necessary ID-to-device lookup becomes rather
3693 * impractical given a potential sparse 32-bit stream ID space.
3694 */
3695 if (dev_is_pci(dev))
3696 group = pci_device_group(dev);
3697 else
3698 group = generic_device_group(dev);
3699
3700 return group;
3701 }
3702
3703 static int arm_smmu_of_xlate(struct device *dev,
3704 const struct of_phandle_args *args)
3705 {
3706 return iommu_fwspec_add_ids(dev, args->args, 1);
3707 }
3708
3709 static void arm_smmu_get_resv_regions(struct device *dev,
3710 struct list_head *head)
3711 {
3712 struct iommu_resv_region *region;
3713 int prot = IOMMU_WRITE | IOMMU_NOEXEC | IOMMU_MMIO;
3714
3715 region = iommu_alloc_resv_region(MSI_IOVA_BASE, MSI_IOVA_LENGTH,
3716 prot, IOMMU_RESV_SW_MSI, GFP_KERNEL);
3717 if (!region)
3718 return;
3719
3720 list_add_tail(&region->list, head);
3721
3722 iommu_dma_get_resv_regions(dev, head);
3723 }
3724
3725 /*
3726 * HiSilicon PCIe tune and trace device can be used to trace TLP headers on the
3727 * PCIe link and save the data to memory by DMA. The hardware is restricted to
3728 * use identity mapping only.
3729 */
3730 #define IS_HISI_PTT_DEVICE(pdev) ((pdev)->vendor == PCI_VENDOR_ID_HUAWEI && \
3731 (pdev)->device == 0xa12e)
3732
3733 static int arm_smmu_def_domain_type(struct device *dev)
3734 {
3735 if (dev_is_pci(dev)) {
3736 struct pci_dev *pdev = to_pci_dev(dev);
3737
3738 if (IS_HISI_PTT_DEVICE(pdev))
3739 return IOMMU_DOMAIN_IDENTITY;
3740 }
3741
3742 return 0;
3743 }
3744
3745 static const struct iommu_ops arm_smmu_ops = {
3746 .identity_domain = &arm_smmu_identity_domain,
3747 .blocked_domain = &arm_smmu_blocked_domain,
3748 .release_domain = &arm_smmu_blocked_domain,
3749 .capable = arm_smmu_capable,
3750 .hw_info = arm_smmu_hw_info,
3751 .domain_alloc_sva = arm_smmu_sva_domain_alloc,
3752 .domain_alloc_paging_flags = arm_smmu_domain_alloc_paging_flags,
3753 .probe_device = arm_smmu_probe_device,
3754 .release_device = arm_smmu_release_device,
3755 .device_group = arm_smmu_device_group,
3756 .of_xlate = arm_smmu_of_xlate,
3757 .get_resv_regions = arm_smmu_get_resv_regions,
3758 .page_response = arm_smmu_page_response,
3759 .def_domain_type = arm_smmu_def_domain_type,
3760 .get_viommu_size = arm_smmu_get_viommu_size,
3761 .viommu_init = arm_vsmmu_init,
3762 .user_pasid_table = 1,
3763 .owner = THIS_MODULE,
3764 .default_domain_ops = &(const struct iommu_domain_ops) {
3765 .attach_dev = arm_smmu_attach_dev,
3766 .enforce_cache_coherency = arm_smmu_enforce_cache_coherency,
3767 .set_dev_pasid = arm_smmu_s1_set_dev_pasid,
3768 .map_pages = arm_smmu_map_pages,
3769 .unmap_pages = arm_smmu_unmap_pages,
3770 .flush_iotlb_all = arm_smmu_flush_iotlb_all,
3771 .iotlb_sync = arm_smmu_iotlb_sync,
3772 .iova_to_phys = arm_smmu_iova_to_phys,
3773 .free = arm_smmu_domain_free_paging,
3774 }
3775 };
3776
3777 static struct iommu_dirty_ops arm_smmu_dirty_ops = {
3778 .read_and_clear_dirty = arm_smmu_read_and_clear_dirty,
3779 .set_dirty_tracking = arm_smmu_set_dirty_tracking,
3780 };
3781
3782 /* Probing and initialisation functions */
3783 int arm_smmu_init_one_queue(struct arm_smmu_device *smmu,
3784 struct arm_smmu_queue *q, void __iomem *page,
3785 unsigned long prod_off, unsigned long cons_off,
3786 size_t dwords, const char *name)
3787 {
3788 size_t qsz;
3789
3790 do {
3791 qsz = ((1 << q->llq.max_n_shift) * dwords) << 3;
3792 q->base = dmam_alloc_coherent(smmu->dev, qsz, &q->base_dma,
3793 GFP_KERNEL);
3794 if (q->base || qsz < PAGE_SIZE)
3795 break;
3796
3797 q->llq.max_n_shift--;
3798 } while (1);
3799
3800 if (!q->base) {
3801 dev_err(smmu->dev,
3802 "failed to allocate queue (0x%zx bytes) for %s\n",
3803 qsz, name);
3804 return -ENOMEM;
3805 }
3806
3807 if (!WARN_ON(q->base_dma & (qsz - 1))) {
3808 dev_info(smmu->dev, "allocated %u entries for %s\n",
3809 1 << q->llq.max_n_shift, name);
3810 }
3811
3812 q->prod_reg = page + prod_off;
3813 q->cons_reg = page + cons_off;
3814 q->ent_dwords = dwords;
3815
3816 q->q_base = Q_BASE_RWA;
3817 q->q_base |= q->base_dma & Q_BASE_ADDR_MASK;
3818 q->q_base |= FIELD_PREP(Q_BASE_LOG2SIZE, q->llq.max_n_shift);
3819
3820 q->llq.prod = q->llq.cons = 0;
3821 return 0;
3822 }
3823
3824 int arm_smmu_cmdq_init(struct arm_smmu_device *smmu,
3825 struct arm_smmu_cmdq *cmdq)
3826 {
3827 unsigned int nents = 1 << cmdq->q.llq.max_n_shift;
3828
3829 atomic_set(&cmdq->owner_prod, 0);
3830 atomic_set(&cmdq->lock, 0);
3831
3832 cmdq->valid_map = (atomic_long_t *)devm_bitmap_zalloc(smmu->dev, nents,
3833 GFP_KERNEL);
3834 if (!cmdq->valid_map)
3835 return -ENOMEM;
3836
3837 return 0;
3838 }
3839
3840 static int arm_smmu_init_queues(struct arm_smmu_device *smmu)
3841 {
3842 int ret;
3843
3844 /* cmdq */
3845 ret = arm_smmu_init_one_queue(smmu, &smmu->cmdq.q, smmu->base,
3846 ARM_SMMU_CMDQ_PROD, ARM_SMMU_CMDQ_CONS,
3847 CMDQ_ENT_DWORDS, "cmdq");
3848 if (ret)
3849 return ret;
3850
3851 ret = arm_smmu_cmdq_init(smmu, &smmu->cmdq);
3852 if (ret)
3853 return ret;
3854
3855 /* evtq */
3856 ret = arm_smmu_init_one_queue(smmu, &smmu->evtq.q, smmu->page1,
3857 ARM_SMMU_EVTQ_PROD, ARM_SMMU_EVTQ_CONS,
3858 EVTQ_ENT_DWORDS, "evtq");
3859 if (ret)
3860 return ret;
3861
3862 if ((smmu->features & ARM_SMMU_FEAT_SVA) &&
3863 (smmu->features & ARM_SMMU_FEAT_STALLS)) {
3864 smmu->evtq.iopf = iopf_queue_alloc(dev_name(smmu->dev));
3865 if (!smmu->evtq.iopf)
3866 return -ENOMEM;
3867 }
3868
3869 /* priq */
3870 if (!(smmu->features & ARM_SMMU_FEAT_PRI))
3871 return 0;
3872
3873 return arm_smmu_init_one_queue(smmu, &smmu->priq.q, smmu->page1,
3874 ARM_SMMU_PRIQ_PROD, ARM_SMMU_PRIQ_CONS,
3875 PRIQ_ENT_DWORDS, "priq");
3876 }
3877
3878 static int arm_smmu_init_strtab_2lvl(struct arm_smmu_device *smmu)
3879 {
3880 u32 l1size;
3881 struct arm_smmu_strtab_cfg *cfg = &smmu->strtab_cfg;
3882 unsigned int last_sid_idx =
3883 arm_smmu_strtab_l1_idx((1ULL << smmu->sid_bits) - 1);
3884
3885 /* Calculate the L1 size, capped to the SIDSIZE. */
3886 cfg->l2.num_l1_ents = min(last_sid_idx + 1, STRTAB_MAX_L1_ENTRIES);
3887 if (cfg->l2.num_l1_ents <= last_sid_idx)
3888 dev_warn(smmu->dev,
3889 "2-level strtab only covers %u/%u bits of SID\n",
3890 ilog2(cfg->l2.num_l1_ents * STRTAB_NUM_L2_STES),
3891 smmu->sid_bits);
3892
3893 l1size = cfg->l2.num_l1_ents * sizeof(struct arm_smmu_strtab_l1);
3894 cfg->l2.l1tab = dmam_alloc_coherent(smmu->dev, l1size, &cfg->l2.l1_dma,
3895 GFP_KERNEL);
3896 if (!cfg->l2.l1tab) {
3897 dev_err(smmu->dev,
3898 "failed to allocate l1 stream table (%u bytes)\n",
3899 l1size);
3900 return -ENOMEM;
3901 }
3902
3903 cfg->l2.l2ptrs = devm_kcalloc(smmu->dev, cfg->l2.num_l1_ents,
3904 sizeof(*cfg->l2.l2ptrs), GFP_KERNEL);
3905 if (!cfg->l2.l2ptrs)
3906 return -ENOMEM;
3907
3908 return 0;
3909 }
3910
3911 static int arm_smmu_init_strtab_linear(struct arm_smmu_device *smmu)
3912 {
3913 u32 size;
3914 struct arm_smmu_strtab_cfg *cfg = &smmu->strtab_cfg;
3915
3916 size = (1 << smmu->sid_bits) * sizeof(struct arm_smmu_ste);
3917 cfg->linear.table = dmam_alloc_coherent(smmu->dev, size,
3918 &cfg->linear.ste_dma,
3919 GFP_KERNEL);
3920 if (!cfg->linear.table) {
3921 dev_err(smmu->dev,
3922 "failed to allocate linear stream table (%u bytes)\n",
3923 size);
3924 return -ENOMEM;
3925 }
3926 cfg->linear.num_ents = 1 << smmu->sid_bits;
3927
3928 arm_smmu_init_initial_stes(cfg->linear.table, cfg->linear.num_ents);
3929 return 0;
3930 }
3931
3932 static int arm_smmu_init_strtab(struct arm_smmu_device *smmu)
3933 {
3934 int ret;
3935
3936 if (smmu->features & ARM_SMMU_FEAT_2_LVL_STRTAB)
3937 ret = arm_smmu_init_strtab_2lvl(smmu);
3938 else
3939 ret = arm_smmu_init_strtab_linear(smmu);
3940 if (ret)
3941 return ret;
3942
3943 ida_init(&smmu->vmid_map);
3944
3945 return 0;
3946 }
3947
3948 static int arm_smmu_init_structures(struct arm_smmu_device *smmu)
3949 {
3950 int ret;
3951
3952 mutex_init(&smmu->streams_mutex);
3953 smmu->streams = RB_ROOT;
3954
3955 ret = arm_smmu_init_queues(smmu);
3956 if (ret)
3957 return ret;
3958
3959 ret = arm_smmu_init_strtab(smmu);
3960 if (ret)
3961 return ret;
3962
3963 if (smmu->impl_ops && smmu->impl_ops->init_structures)
3964 return smmu->impl_ops->init_structures(smmu);
3965
3966 return 0;
3967 }
3968
3969 static int arm_smmu_write_reg_sync(struct arm_smmu_device *smmu, u32 val,
3970 unsigned int reg_off, unsigned int ack_off)
3971 {
3972 u32 reg;
3973
3974 writel_relaxed(val, smmu->base + reg_off);
3975 return readl_relaxed_poll_timeout(smmu->base + ack_off, reg, reg == val,
3976 1, ARM_SMMU_POLL_TIMEOUT_US);
3977 }
3978
3979 /* GBPA is "special" */
3980 static int arm_smmu_update_gbpa(struct arm_smmu_device *smmu, u32 set, u32 clr)
3981 {
3982 int ret;
3983 u32 reg, __iomem *gbpa = smmu->base + ARM_SMMU_GBPA;
3984
3985 ret = readl_relaxed_poll_timeout(gbpa, reg, !(reg & GBPA_UPDATE),
3986 1, ARM_SMMU_POLL_TIMEOUT_US);
3987 if (ret)
3988 return ret;
3989
3990 reg &= ~clr;
3991 reg |= set;
3992 writel_relaxed(reg | GBPA_UPDATE, gbpa);
3993 ret = readl_relaxed_poll_timeout(gbpa, reg, !(reg & GBPA_UPDATE),
3994 1, ARM_SMMU_POLL_TIMEOUT_US);
3995
3996 if (ret)
3997 dev_err(smmu->dev, "GBPA not responding to update\n");
3998 return ret;
3999 }
4000
4001 static void arm_smmu_free_msis(void *data)
4002 {
4003 struct device *dev = data;
4004
4005 platform_device_msi_free_irqs_all(dev);
4006 }
4007
4008 static void arm_smmu_write_msi_msg(struct msi_desc *desc, struct msi_msg *msg)
4009 {
4010 phys_addr_t doorbell;
4011 struct device *dev = msi_desc_to_dev(desc);
4012 struct arm_smmu_device *smmu = dev_get_drvdata(dev);
4013 phys_addr_t *cfg = arm_smmu_msi_cfg[desc->msi_index];
4014
4015 doorbell = (((u64)msg->address_hi) << 32) | msg->address_lo;
4016 doorbell &= MSI_CFG0_ADDR_MASK;
4017
4018 writeq_relaxed(doorbell, smmu->base + cfg[0]);
4019 writel_relaxed(msg->data, smmu->base + cfg[1]);
4020 writel_relaxed(ARM_SMMU_MEMATTR_DEVICE_nGnRE, smmu->base + cfg[2]);
4021 }
4022
4023 static void arm_smmu_setup_msis(struct arm_smmu_device *smmu)
4024 {
4025 int ret, nvec = ARM_SMMU_MAX_MSIS;
4026 struct device *dev = smmu->dev;
4027
4028 /* Clear the MSI address regs */
4029 writeq_relaxed(0, smmu->base + ARM_SMMU_GERROR_IRQ_CFG0);
4030 writeq_relaxed(0, smmu->base + ARM_SMMU_EVTQ_IRQ_CFG0);
4031
4032 if (smmu->features & ARM_SMMU_FEAT_PRI)
4033 writeq_relaxed(0, smmu->base + ARM_SMMU_PRIQ_IRQ_CFG0);
4034 else
4035 nvec--;
4036
4037 if (!(smmu->features & ARM_SMMU_FEAT_MSI))
4038 return;
4039
4040 if (!dev->msi.domain) {
4041 dev_info(smmu->dev, "msi_domain absent - falling back to wired irqs\n");
4042 return;
4043 }
4044
4045 /* Allocate MSIs for evtq, gerror and priq. Ignore cmdq */
4046 ret = platform_device_msi_init_and_alloc_irqs(dev, nvec, arm_smmu_write_msi_msg);
4047 if (ret) {
4048 dev_warn(dev, "failed to allocate MSIs - falling back to wired irqs\n");
4049 return;
4050 }
4051
4052 smmu->evtq.q.irq = msi_get_virq(dev, EVTQ_MSI_INDEX);
4053 smmu->gerr_irq = msi_get_virq(dev, GERROR_MSI_INDEX);
4054 smmu->priq.q.irq = msi_get_virq(dev, PRIQ_MSI_INDEX);
4055
4056 /* Add callback to free MSIs on teardown */
4057 devm_add_action_or_reset(dev, arm_smmu_free_msis, dev);
4058 }
4059
4060 static void arm_smmu_setup_unique_irqs(struct arm_smmu_device *smmu)
4061 {
4062 int irq, ret;
4063
4064 arm_smmu_setup_msis(smmu);
4065
4066 /* Request interrupt lines */
4067 irq = smmu->evtq.q.irq;
4068 if (irq) {
4069 ret = devm_request_threaded_irq(smmu->dev, irq, NULL,
4070 arm_smmu_evtq_thread,
4071 IRQF_ONESHOT,
4072 "arm-smmu-v3-evtq", smmu);
4073 if (ret < 0)
4074 dev_warn(smmu->dev, "failed to enable evtq irq\n");
4075 } else {
4076 dev_warn(smmu->dev, "no evtq irq - events will not be reported!\n");
4077 }
4078
4079 irq = smmu->gerr_irq;
4080 if (irq) {
4081 ret = devm_request_irq(smmu->dev, irq, arm_smmu_gerror_handler,
4082 0, "arm-smmu-v3-gerror", smmu);
4083 if (ret < 0)
4084 dev_warn(smmu->dev, "failed to enable gerror irq\n");
4085 } else {
4086 dev_warn(smmu->dev, "no gerr irq - errors will not be reported!\n");
4087 }
4088
4089 if (smmu->features & ARM_SMMU_FEAT_PRI) {
4090 irq = smmu->priq.q.irq;
4091 if (irq) {
4092 ret = devm_request_threaded_irq(smmu->dev, irq, NULL,
4093 arm_smmu_priq_thread,
4094 IRQF_ONESHOT,
4095 "arm-smmu-v3-priq",
4096 smmu);
4097 if (ret < 0)
4098 dev_warn(smmu->dev,
4099 "failed to enable priq irq\n");
4100 } else {
4101 dev_warn(smmu->dev, "no priq irq - PRI will be broken\n");
4102 }
4103 }
4104 }
4105
4106 static int arm_smmu_setup_irqs(struct arm_smmu_device *smmu)
4107 {
4108 int ret, irq;
4109 u32 irqen_flags = IRQ_CTRL_EVTQ_IRQEN | IRQ_CTRL_GERROR_IRQEN;
4110
4111 /* Disable IRQs first */
4112 ret = arm_smmu_write_reg_sync(smmu, 0, ARM_SMMU_IRQ_CTRL,
4113 ARM_SMMU_IRQ_CTRLACK);
4114 if (ret) {
4115 dev_err(smmu->dev, "failed to disable irqs\n");
4116 return ret;
4117 }
4118
4119 irq = smmu->combined_irq;
4120 if (irq) {
4121 /*
4122 * Cavium ThunderX2 implementation doesn't support unique irq
4123 * lines. Use a single irq line for all the SMMUv3 interrupts.
4124 */
4125 ret = devm_request_threaded_irq(smmu->dev, irq,
4126 arm_smmu_combined_irq_handler,
4127 arm_smmu_combined_irq_thread,
4128 IRQF_ONESHOT,
4129 "arm-smmu-v3-combined-irq", smmu);
4130 if (ret < 0)
4131 dev_warn(smmu->dev, "failed to enable combined irq\n");
4132 } else
4133 arm_smmu_setup_unique_irqs(smmu);
4134
4135 if (smmu->features & ARM_SMMU_FEAT_PRI)
4136 irqen_flags |= IRQ_CTRL_PRIQ_IRQEN;
4137
4138 /* Enable interrupt generation on the SMMU */
4139 ret = arm_smmu_write_reg_sync(smmu, irqen_flags,
4140 ARM_SMMU_IRQ_CTRL, ARM_SMMU_IRQ_CTRLACK);
4141 if (ret)
4142 dev_warn(smmu->dev, "failed to enable irqs\n");
4143
4144 return 0;
4145 }
4146
4147 static int arm_smmu_device_disable(struct arm_smmu_device *smmu)
4148 {
4149 int ret;
4150
4151 ret = arm_smmu_write_reg_sync(smmu, 0, ARM_SMMU_CR0, ARM_SMMU_CR0ACK);
4152 if (ret)
4153 dev_err(smmu->dev, "failed to clear cr0\n");
4154
4155 return ret;
4156 }
4157
4158 static void arm_smmu_write_strtab(struct arm_smmu_device *smmu)
4159 {
4160 struct arm_smmu_strtab_cfg *cfg = &smmu->strtab_cfg;
4161 dma_addr_t dma;
4162 u32 reg;
4163
4164 if (smmu->features & ARM_SMMU_FEAT_2_LVL_STRTAB) {
4165 reg = FIELD_PREP(STRTAB_BASE_CFG_FMT,
4166 STRTAB_BASE_CFG_FMT_2LVL) |
4167 FIELD_PREP(STRTAB_BASE_CFG_LOG2SIZE,
4168 ilog2(cfg->l2.num_l1_ents) + STRTAB_SPLIT) |
4169 FIELD_PREP(STRTAB_BASE_CFG_SPLIT, STRTAB_SPLIT);
4170 dma = cfg->l2.l1_dma;
4171 } else {
4172 reg = FIELD_PREP(STRTAB_BASE_CFG_FMT,
4173 STRTAB_BASE_CFG_FMT_LINEAR) |
4174 FIELD_PREP(STRTAB_BASE_CFG_LOG2SIZE, smmu->sid_bits);
4175 dma = cfg->linear.ste_dma;
4176 }
4177 writeq_relaxed((dma & STRTAB_BASE_ADDR_MASK) | STRTAB_BASE_RA,
4178 smmu->base + ARM_SMMU_STRTAB_BASE);
4179 writel_relaxed(reg, smmu->base + ARM_SMMU_STRTAB_BASE_CFG);
4180 }
4181
4182 static int arm_smmu_device_reset(struct arm_smmu_device *smmu)
4183 {
4184 int ret;
4185 u32 reg, enables;
4186 struct arm_smmu_cmdq_ent cmd;
4187
4188 /* Clear CR0 and sync (disables SMMU and queue processing) */
4189 reg = readl_relaxed(smmu->base + ARM_SMMU_CR0);
4190 if (reg & CR0_SMMUEN) {
4191 dev_warn(smmu->dev, "SMMU currently enabled! Resetting...\n");
4192 arm_smmu_update_gbpa(smmu, GBPA_ABORT, 0);
4193 }
4194
4195 ret = arm_smmu_device_disable(smmu);
4196 if (ret)
4197 return ret;
4198
4199 /* CR1 (table and queue memory attributes) */
4200 reg = FIELD_PREP(CR1_TABLE_SH, ARM_SMMU_SH_ISH) |
4201 FIELD_PREP(CR1_TABLE_OC, CR1_CACHE_WB) |
4202 FIELD_PREP(CR1_TABLE_IC, CR1_CACHE_WB) |
4203 FIELD_PREP(CR1_QUEUE_SH, ARM_SMMU_SH_ISH) |
4204 FIELD_PREP(CR1_QUEUE_OC, CR1_CACHE_WB) |
4205 FIELD_PREP(CR1_QUEUE_IC, CR1_CACHE_WB);
4206 writel_relaxed(reg, smmu->base + ARM_SMMU_CR1);
4207
4208 /* CR2 (random crap) */
4209 reg = CR2_PTM | CR2_RECINVSID;
4210
4211 if (smmu->features & ARM_SMMU_FEAT_E2H)
4212 reg |= CR2_E2H;
4213
4214 writel_relaxed(reg, smmu->base + ARM_SMMU_CR2);
4215
4216 /* Stream table */
4217 arm_smmu_write_strtab(smmu);
4218
4219 /* Command queue */
4220 writeq_relaxed(smmu->cmdq.q.q_base, smmu->base + ARM_SMMU_CMDQ_BASE);
4221 writel_relaxed(smmu->cmdq.q.llq.prod, smmu->base + ARM_SMMU_CMDQ_PROD);
4222 writel_relaxed(smmu->cmdq.q.llq.cons, smmu->base + ARM_SMMU_CMDQ_CONS);
4223
4224 enables = CR0_CMDQEN;
4225 ret = arm_smmu_write_reg_sync(smmu, enables, ARM_SMMU_CR0,
4226 ARM_SMMU_CR0ACK);
4227 if (ret) {
4228 dev_err(smmu->dev, "failed to enable command queue\n");
4229 return ret;
4230 }
4231
4232 /* Invalidate any cached configuration */
4233 cmd.opcode = CMDQ_OP_CFGI_ALL;
4234 arm_smmu_cmdq_issue_cmd_with_sync(smmu, &cmd);
4235
4236 /* Invalidate any stale TLB entries */
4237 if (smmu->features & ARM_SMMU_FEAT_HYP) {
4238 cmd.opcode = CMDQ_OP_TLBI_EL2_ALL;
4239 arm_smmu_cmdq_issue_cmd_with_sync(smmu, &cmd);
4240 }
4241
4242 cmd.opcode = CMDQ_OP_TLBI_NSNH_ALL;
4243 arm_smmu_cmdq_issue_cmd_with_sync(smmu, &cmd);
4244
4245 /* Event queue */
4246 writeq_relaxed(smmu->evtq.q.q_base, smmu->base + ARM_SMMU_EVTQ_BASE);
4247 writel_relaxed(smmu->evtq.q.llq.prod, smmu->page1 + ARM_SMMU_EVTQ_PROD);
4248 writel_relaxed(smmu->evtq.q.llq.cons, smmu->page1 + ARM_SMMU_EVTQ_CONS);
4249
4250 enables |= CR0_EVTQEN;
4251 ret = arm_smmu_write_reg_sync(smmu, enables, ARM_SMMU_CR0,
4252 ARM_SMMU_CR0ACK);
4253 if (ret) {
4254 dev_err(smmu->dev, "failed to enable event queue\n");
4255 return ret;
4256 }
4257
4258 /* PRI queue */
4259 if (smmu->features & ARM_SMMU_FEAT_PRI) {
4260 writeq_relaxed(smmu->priq.q.q_base,
4261 smmu->base + ARM_SMMU_PRIQ_BASE);
4262 writel_relaxed(smmu->priq.q.llq.prod,
4263 smmu->page1 + ARM_SMMU_PRIQ_PROD);
4264 writel_relaxed(smmu->priq.q.llq.cons,
4265 smmu->page1 + ARM_SMMU_PRIQ_CONS);
4266
4267 enables |= CR0_PRIQEN;
4268 ret = arm_smmu_write_reg_sync(smmu, enables, ARM_SMMU_CR0,
4269 ARM_SMMU_CR0ACK);
4270 if (ret) {
4271 dev_err(smmu->dev, "failed to enable PRI queue\n");
4272 return ret;
4273 }
4274 }
4275
4276 if (smmu->features & ARM_SMMU_FEAT_ATS) {
4277 enables |= CR0_ATSCHK;
4278 ret = arm_smmu_write_reg_sync(smmu, enables, ARM_SMMU_CR0,
4279 ARM_SMMU_CR0ACK);
4280 if (ret) {
4281 dev_err(smmu->dev, "failed to enable ATS check\n");
4282 return ret;
4283 }
4284 }
4285
4286 ret = arm_smmu_setup_irqs(smmu);
4287 if (ret) {
4288 dev_err(smmu->dev, "failed to setup irqs\n");
4289 return ret;
4290 }
4291
4292 if (is_kdump_kernel())
4293 enables &= ~(CR0_EVTQEN | CR0_PRIQEN);
4294
4295 /* Enable the SMMU interface */
4296 enables |= CR0_SMMUEN;
4297 ret = arm_smmu_write_reg_sync(smmu, enables, ARM_SMMU_CR0,
4298 ARM_SMMU_CR0ACK);
4299 if (ret) {
4300 dev_err(smmu->dev, "failed to enable SMMU interface\n");
4301 return ret;
4302 }
4303
4304 if (smmu->impl_ops && smmu->impl_ops->device_reset) {
4305 ret = smmu->impl_ops->device_reset(smmu);
4306 if (ret) {
4307 dev_err(smmu->dev, "failed to reset impl\n");
4308 return ret;
4309 }
4310 }
4311
4312 return 0;
4313 }
4314
4315 #define IIDR_IMPLEMENTER_ARM 0x43b
4316 #define IIDR_PRODUCTID_ARM_MMU_600 0x483
4317 #define IIDR_PRODUCTID_ARM_MMU_700 0x487
4318
4319 static void arm_smmu_device_iidr_probe(struct arm_smmu_device *smmu)
4320 {
4321 u32 reg;
4322 unsigned int implementer, productid, variant, revision;
4323
4324 reg = readl_relaxed(smmu->base + ARM_SMMU_IIDR);
4325 implementer = FIELD_GET(IIDR_IMPLEMENTER, reg);
4326 productid = FIELD_GET(IIDR_PRODUCTID, reg);
4327 variant = FIELD_GET(IIDR_VARIANT, reg);
4328 revision = FIELD_GET(IIDR_REVISION, reg);
4329
4330 switch (implementer) {
4331 case IIDR_IMPLEMENTER_ARM:
4332 switch (productid) {
4333 case IIDR_PRODUCTID_ARM_MMU_600:
4334 /* Arm erratum 1076982 */
4335 if (variant == 0 && revision <= 2)
4336 smmu->features &= ~ARM_SMMU_FEAT_SEV;
4337 /* Arm erratum 1209401 */
4338 if (variant < 2)
4339 smmu->features &= ~ARM_SMMU_FEAT_NESTING;
4340 break;
4341 case IIDR_PRODUCTID_ARM_MMU_700:
4342 /* Arm erratum 2812531 */
4343 smmu->features &= ~ARM_SMMU_FEAT_BTM;
4344 smmu->options |= ARM_SMMU_OPT_CMDQ_FORCE_SYNC;
4345 /* Arm errata 2268618, 2812531 */
4346 smmu->features &= ~ARM_SMMU_FEAT_NESTING;
4347 break;
4348 }
4349 break;
4350 }
4351 }
4352
4353 static void arm_smmu_get_httu(struct arm_smmu_device *smmu, u32 reg)
4354 {
4355 u32 fw_features = smmu->features & (ARM_SMMU_FEAT_HA | ARM_SMMU_FEAT_HD);
4356 u32 hw_features = 0;
4357
4358 switch (FIELD_GET(IDR0_HTTU, reg)) {
4359 case IDR0_HTTU_ACCESS_DIRTY:
4360 hw_features |= ARM_SMMU_FEAT_HD;
4361 fallthrough;
4362 case IDR0_HTTU_ACCESS:
4363 hw_features |= ARM_SMMU_FEAT_HA;
4364 }
4365
4366 if (smmu->dev->of_node)
4367 smmu->features |= hw_features;
4368 else if (hw_features != fw_features)
4369 /* ACPI IORT sets the HTTU bits */
4370 dev_warn(smmu->dev,
4371 "IDR0.HTTU features(0x%x) overridden by FW configuration (0x%x)\n",
4372 hw_features, fw_features);
4373 }
4374
4375 static int arm_smmu_device_hw_probe(struct arm_smmu_device *smmu)
4376 {
4377 u32 reg;
4378 bool coherent = smmu->features & ARM_SMMU_FEAT_COHERENCY;
4379
4380 /* IDR0 */
4381 reg = readl_relaxed(smmu->base + ARM_SMMU_IDR0);
4382
4383 /* 2-level structures */
4384 if (FIELD_GET(IDR0_ST_LVL, reg) == IDR0_ST_LVL_2LVL)
4385 smmu->features |= ARM_SMMU_FEAT_2_LVL_STRTAB;
4386
4387 if (reg & IDR0_CD2L)
4388 smmu->features |= ARM_SMMU_FEAT_2_LVL_CDTAB;
4389
4390 /*
4391 * Translation table endianness.
4392 * We currently require the same endianness as the CPU, but this
4393 * could be changed later by adding a new IO_PGTABLE_QUIRK.
4394 */
4395 switch (FIELD_GET(IDR0_TTENDIAN, reg)) {
4396 case IDR0_TTENDIAN_MIXED:
4397 smmu->features |= ARM_SMMU_FEAT_TT_LE | ARM_SMMU_FEAT_TT_BE;
4398 break;
4399 #ifdef __BIG_ENDIAN
4400 case IDR0_TTENDIAN_BE:
4401 smmu->features |= ARM_SMMU_FEAT_TT_BE;
4402 break;
4403 #else
4404 case IDR0_TTENDIAN_LE:
4405 smmu->features |= ARM_SMMU_FEAT_TT_LE;
4406 break;
4407 #endif
4408 default:
4409 dev_err(smmu->dev, "unknown/unsupported TT endianness!\n");
4410 return -ENXIO;
4411 }
4412
4413 /* Boolean feature flags */
4414 if (IS_ENABLED(CONFIG_PCI_PRI) && reg & IDR0_PRI)
4415 smmu->features |= ARM_SMMU_FEAT_PRI;
4416
4417 if (IS_ENABLED(CONFIG_PCI_ATS) && reg & IDR0_ATS)
4418 smmu->features |= ARM_SMMU_FEAT_ATS;
4419
4420 if (reg & IDR0_SEV)
4421 smmu->features |= ARM_SMMU_FEAT_SEV;
4422
4423 if (reg & IDR0_MSI) {
4424 smmu->features |= ARM_SMMU_FEAT_MSI;
4425 if (coherent && !disable_msipolling)
4426 smmu->options |= ARM_SMMU_OPT_MSIPOLL;
4427 }
4428
4429 if (reg & IDR0_HYP) {
4430 smmu->features |= ARM_SMMU_FEAT_HYP;
4431 if (cpus_have_cap(ARM64_HAS_VIRT_HOST_EXTN))
4432 smmu->features |= ARM_SMMU_FEAT_E2H;
4433 }
4434
4435 arm_smmu_get_httu(smmu, reg);
4436
4437 /*
4438 * The coherency feature as set by FW is used in preference to the ID
4439 * register, but warn on mismatch.
4440 */
4441 if (!!(reg & IDR0_COHACC) != coherent)
4442 dev_warn(smmu->dev, "IDR0.COHACC overridden by FW configuration (%s)\n",
4443 str_true_false(coherent));
4444
4445 switch (FIELD_GET(IDR0_STALL_MODEL, reg)) {
4446 case IDR0_STALL_MODEL_FORCE:
4447 smmu->features |= ARM_SMMU_FEAT_STALL_FORCE;
4448 fallthrough;
4449 case IDR0_STALL_MODEL_STALL:
4450 smmu->features |= ARM_SMMU_FEAT_STALLS;
4451 }
4452
4453 if (reg & IDR0_S1P)
4454 smmu->features |= ARM_SMMU_FEAT_TRANS_S1;
4455
4456 if (reg & IDR0_S2P)
4457 smmu->features |= ARM_SMMU_FEAT_TRANS_S2;
4458
4459 if (!(reg & (IDR0_S1P | IDR0_S2P))) {
4460 dev_err(smmu->dev, "no translation support!\n");
4461 return -ENXIO;
4462 }
4463
4464 /* We only support the AArch64 table format at present */
4465 if (!(FIELD_GET(IDR0_TTF, reg) & IDR0_TTF_AARCH64)) {
4466 dev_err(smmu->dev, "AArch64 table format not supported!\n");
4467 return -ENXIO;
4468 }
4469
4470 /* ASID/VMID sizes */
4471 smmu->asid_bits = reg & IDR0_ASID16 ? 16 : 8;
4472 smmu->vmid_bits = reg & IDR0_VMID16 ? 16 : 8;
4473
4474 /* IDR1 */
4475 reg = readl_relaxed(smmu->base + ARM_SMMU_IDR1);
4476 if (reg & (IDR1_TABLES_PRESET | IDR1_QUEUES_PRESET | IDR1_REL)) {
4477 dev_err(smmu->dev, "embedded implementation not supported\n");
4478 return -ENXIO;
4479 }
4480
4481 if (reg & IDR1_ATTR_TYPES_OVR)
4482 smmu->features |= ARM_SMMU_FEAT_ATTR_TYPES_OVR;
4483
4484 /* Queue sizes, capped to ensure natural alignment */
4485 smmu->cmdq.q.llq.max_n_shift = min_t(u32, CMDQ_MAX_SZ_SHIFT,
4486 FIELD_GET(IDR1_CMDQS, reg));
4487 if (smmu->cmdq.q.llq.max_n_shift <= ilog2(CMDQ_BATCH_ENTRIES)) {
4488 /*
4489 * We don't support splitting up batches, so one batch of
4490 * commands plus an extra sync needs to fit inside the command
4491 * queue. There's also no way we can handle the weird alignment
4492 * restrictions on the base pointer for a unit-length queue.
4493 */
4494 dev_err(smmu->dev, "command queue size <= %d entries not supported\n",
4495 CMDQ_BATCH_ENTRIES);
4496 return -ENXIO;
4497 }
4498
4499 smmu->evtq.q.llq.max_n_shift = min_t(u32, EVTQ_MAX_SZ_SHIFT,
4500 FIELD_GET(IDR1_EVTQS, reg));
4501 smmu->priq.q.llq.max_n_shift = min_t(u32, PRIQ_MAX_SZ_SHIFT,
4502 FIELD_GET(IDR1_PRIQS, reg));
4503
4504 /* SID/SSID sizes */
4505 smmu->ssid_bits = FIELD_GET(IDR1_SSIDSIZE, reg);
4506 smmu->sid_bits = FIELD_GET(IDR1_SIDSIZE, reg);
4507 smmu->iommu.max_pasids = 1UL << smmu->ssid_bits;
4508
4509 /*
4510 * If the SMMU supports fewer bits than would fill a single L2 stream
4511 * table, use a linear table instead.
4512 */
4513 if (smmu->sid_bits <= STRTAB_SPLIT)
4514 smmu->features &= ~ARM_SMMU_FEAT_2_LVL_STRTAB;
4515
4516 /* IDR3 */
4517 reg = readl_relaxed(smmu->base + ARM_SMMU_IDR3);
4518 if (FIELD_GET(IDR3_RIL, reg))
4519 smmu->features |= ARM_SMMU_FEAT_RANGE_INV;
4520 if (FIELD_GET(IDR3_FWB, reg))
4521 smmu->features |= ARM_SMMU_FEAT_S2FWB;
4522
4523 if (FIELD_GET(IDR3_BBM, reg) == 2)
4524 smmu->features |= ARM_SMMU_FEAT_BBML2;
4525
4526 /* IDR5 */
4527 reg = readl_relaxed(smmu->base + ARM_SMMU_IDR5);
4528
4529 /* Maximum number of outstanding stalls */
4530 smmu->evtq.max_stalls = FIELD_GET(IDR5_STALL_MAX, reg);
4531
4532 /* Page sizes */
4533 if (reg & IDR5_GRAN64K)
4534 smmu->pgsize_bitmap |= SZ_64K | SZ_512M;
4535 if (reg & IDR5_GRAN16K)
4536 smmu->pgsize_bitmap |= SZ_16K | SZ_32M;
4537 if (reg & IDR5_GRAN4K)
4538 smmu->pgsize_bitmap |= SZ_4K | SZ_2M | SZ_1G;
4539
4540 /* Input address size */
4541 if (FIELD_GET(IDR5_VAX, reg) == IDR5_VAX_52_BIT)
4542 smmu->features |= ARM_SMMU_FEAT_VAX;
4543
4544 /* Output address size */
4545 switch (FIELD_GET(IDR5_OAS, reg)) {
4546 case IDR5_OAS_32_BIT:
4547 smmu->oas = 32;
4548 break;
4549 case IDR5_OAS_36_BIT:
4550 smmu->oas = 36;
4551 break;
4552 case IDR5_OAS_40_BIT:
4553 smmu->oas = 40;
4554 break;
4555 case IDR5_OAS_42_BIT:
4556 smmu->oas = 42;
4557 break;
4558 case IDR5_OAS_44_BIT:
4559 smmu->oas = 44;
4560 break;
4561 case IDR5_OAS_52_BIT:
4562 smmu->oas = 52;
4563 smmu->pgsize_bitmap |= 1ULL << 42; /* 4TB */
4564 break;
4565 default:
4566 dev_info(smmu->dev,
4567 "unknown output address size. Truncating to 48-bit\n");
4568 fallthrough;
4569 case IDR5_OAS_48_BIT:
4570 smmu->oas = 48;
4571 }
4572
4573 /* Set the DMA mask for our table walker */
4574 if (dma_set_mask_and_coherent(smmu->dev, DMA_BIT_MASK(smmu->oas)))
4575 dev_warn(smmu->dev,
4576 "failed to set DMA mask for table walker\n");
4577
4578 if ((smmu->features & ARM_SMMU_FEAT_TRANS_S1) &&
4579 (smmu->features & ARM_SMMU_FEAT_TRANS_S2))
4580 smmu->features |= ARM_SMMU_FEAT_NESTING;
4581
4582 arm_smmu_device_iidr_probe(smmu);
4583
4584 if (arm_smmu_sva_supported(smmu))
4585 smmu->features |= ARM_SMMU_FEAT_SVA;
4586
4587 dev_info(smmu->dev, "oas %lu-bit (features 0x%08x)\n",
4588 smmu->oas, smmu->features);
4589 return 0;
4590 }
4591
4592 #ifdef CONFIG_TEGRA241_CMDQV
4593 static void tegra_cmdqv_dt_probe(struct device_node *smmu_node,
4594 struct arm_smmu_device *smmu)
4595 {
4596 struct platform_device *pdev;
4597 struct device_node *np;
4598
4599 np = of_parse_phandle(smmu_node, "nvidia,cmdqv", 0);
4600 if (!np)
4601 return;
4602
4603 /* Tegra241 CMDQV driver is responsible for put_device() */
4604 pdev = of_find_device_by_node(np);
4605 of_node_put(np);
4606 if (!pdev)
4607 return;
4608
4609 smmu->impl_dev = &pdev->dev;
4610 smmu->options |= ARM_SMMU_OPT_TEGRA241_CMDQV;
4611 dev_dbg(smmu->dev, "found companion CMDQV device: %s\n",
4612 dev_name(smmu->impl_dev));
4613 }
4614 #else
4615 static void tegra_cmdqv_dt_probe(struct device_node *smmu_node,
4616 struct arm_smmu_device *smmu)
4617 {
4618 }
4619 #endif
4620
4621 #ifdef CONFIG_ACPI
4622 #ifdef CONFIG_TEGRA241_CMDQV
4623 static void acpi_smmu_dsdt_probe_tegra241_cmdqv(struct acpi_iort_node *node,
4624 struct arm_smmu_device *smmu)
4625 {
4626 const char *uid = kasprintf(GFP_KERNEL, "%u", node->identifier);
4627 struct acpi_device *adev;
4628
4629 /* Look for an NVDA200C node whose _UID matches the SMMU node ID */
4630 adev = acpi_dev_get_first_match_dev("NVDA200C", uid, -1);
4631 if (adev) {
4632 /* Tegra241 CMDQV driver is responsible for put_device() */
4633 smmu->impl_dev = get_device(acpi_get_first_physical_node(adev));
4634 smmu->options |= ARM_SMMU_OPT_TEGRA241_CMDQV;
4635 dev_info(smmu->dev, "found companion CMDQV device: %s\n",
4636 dev_name(smmu->impl_dev));
4637 acpi_dev_put(adev);
4638 }
4639 kfree(uid);
4640 }
4641 #else
4642 static void acpi_smmu_dsdt_probe_tegra241_cmdqv(struct acpi_iort_node *node,
4643 struct arm_smmu_device *smmu)
4644 {
4645 }
4646 #endif
4647
4648 static int acpi_smmu_iort_probe_model(struct acpi_iort_node *node,
4649 struct arm_smmu_device *smmu)
4650 {
4651 struct acpi_iort_smmu_v3 *iort_smmu =
4652 (struct acpi_iort_smmu_v3 *)node->node_data;
4653
4654 switch (iort_smmu->model) {
4655 case ACPI_IORT_SMMU_V3_CAVIUM_CN99XX:
4656 smmu->options |= ARM_SMMU_OPT_PAGE0_REGS_ONLY;
4657 break;
4658 case ACPI_IORT_SMMU_V3_HISILICON_HI161X:
4659 smmu->options |= ARM_SMMU_OPT_SKIP_PREFETCH;
4660 break;
4661 case ACPI_IORT_SMMU_V3_GENERIC:
4662 /*
4663 * Tegra241 implementation stores its SMMU options and impl_dev
4664 * in DSDT. Thus, go through the ACPI tables unconditionally.
4665 */
4666 acpi_smmu_dsdt_probe_tegra241_cmdqv(node, smmu);
4667 break;
4668 }
4669
4670 dev_notice(smmu->dev, "option mask 0x%x\n", smmu->options);
4671 return 0;
4672 }
4673
4674 static int arm_smmu_device_acpi_probe(struct platform_device *pdev,
4675 struct arm_smmu_device *smmu)
4676 {
4677 struct acpi_iort_smmu_v3 *iort_smmu;
4678 struct device *dev = smmu->dev;
4679 struct acpi_iort_node *node;
4680
4681 node = *(struct acpi_iort_node **)dev_get_platdata(dev);
4682
4683 /* Retrieve SMMUv3 specific data */
4684 iort_smmu = (struct acpi_iort_smmu_v3 *)node->node_data;
4685
4686 if (iort_smmu->flags & ACPI_IORT_SMMU_V3_COHACC_OVERRIDE)
4687 smmu->features |= ARM_SMMU_FEAT_COHERENCY;
4688
4689 switch (FIELD_GET(ACPI_IORT_SMMU_V3_HTTU_OVERRIDE, iort_smmu->flags)) {
4690 case IDR0_HTTU_ACCESS_DIRTY:
4691 smmu->features |= ARM_SMMU_FEAT_HD;
4692 fallthrough;
4693 case IDR0_HTTU_ACCESS:
4694 smmu->features |= ARM_SMMU_FEAT_HA;
4695 }
4696
4697 return acpi_smmu_iort_probe_model(node, smmu);
4698 }
4699 #else
4700 static inline int arm_smmu_device_acpi_probe(struct platform_device *pdev,
4701 struct arm_smmu_device *smmu)
4702 {
4703 return -ENODEV;
4704 }
4705 #endif
4706
4707 static int arm_smmu_device_dt_probe(struct platform_device *pdev,
4708 struct arm_smmu_device *smmu)
4709 {
4710 struct device *dev = &pdev->dev;
4711 u32 cells;
4712 int ret = -EINVAL;
4713
4714 if (of_property_read_u32(dev->of_node, "#iommu-cells", &cells))
4715 dev_err(dev, "missing #iommu-cells property\n");
4716 else if (cells != 1)
4717 dev_err(dev, "invalid #iommu-cells value (%d)\n", cells);
4718 else
4719 ret = 0;
4720
4721 parse_driver_options(smmu);
4722
4723 if (of_dma_is_coherent(dev->of_node))
4724 smmu->features |= ARM_SMMU_FEAT_COHERENCY;
4725
4726 if (of_device_is_compatible(dev->of_node, "nvidia,tegra264-smmu"))
4727 tegra_cmdqv_dt_probe(dev->of_node, smmu);
4728
4729 return ret;
4730 }
4731
4732 static unsigned long arm_smmu_resource_size(struct arm_smmu_device *smmu)
4733 {
4734 if (smmu->options & ARM_SMMU_OPT_PAGE0_REGS_ONLY)
4735 return SZ_64K;
4736 else
4737 return SZ_128K;
4738 }
4739
4740 static void __iomem *arm_smmu_ioremap(struct device *dev, resource_size_t start,
4741 resource_size_t size)
4742 {
4743 struct resource res = DEFINE_RES_MEM(start, size);
4744
4745 return devm_ioremap_resource(dev, &res);
4746 }
4747
4748 static void arm_smmu_rmr_install_bypass_ste(struct arm_smmu_device *smmu)
4749 {
4750 struct list_head rmr_list;
4751 struct iommu_resv_region *e;
4752
4753 INIT_LIST_HEAD(&rmr_list);
4754 iort_get_rmr_sids(dev_fwnode(smmu->dev), &rmr_list);
4755
4756 list_for_each_entry(e, &rmr_list, list) {
4757 struct iommu_iort_rmr_data *rmr;
4758 int ret, i;
4759
4760 rmr = container_of(e, struct iommu_iort_rmr_data, rr);
4761 for (i = 0; i < rmr->num_sids; i++) {
4762 ret = arm_smmu_init_sid_strtab(smmu, rmr->sids[i]);
4763 if (ret) {
4764 dev_err(smmu->dev, "RMR SID(0x%x) bypass failed\n",
4765 rmr->sids[i]);
4766 continue;
4767 }
4768
4769 /*
4770 * STE table is not programmed to HW, see
4771 * arm_smmu_initial_bypass_stes()
4772 */
4773 arm_smmu_make_bypass_ste(smmu,
4774 arm_smmu_get_step_for_sid(smmu, rmr->sids[i]));
4775 }
4776 }
4777
4778 iort_put_rmr_sids(dev_fwnode(smmu->dev), &rmr_list);
4779 }
4780
4781 static void arm_smmu_impl_remove(void *data)
4782 {
4783 struct arm_smmu_device *smmu = data;
4784
4785 if (smmu->impl_ops && smmu->impl_ops->device_remove)
4786 smmu->impl_ops->device_remove(smmu);
4787 }
4788
4789 /*
4790 * Probe all the compiled in implementations. Each one checks to see if it
4791 * matches this HW and if so returns a devm_krealloc'd arm_smmu_device which
4792 * replaces the callers. Otherwise the original is returned or ERR_PTR.
4793 */
4794 static struct arm_smmu_device *arm_smmu_impl_probe(struct arm_smmu_device *smmu)
4795 {
4796 struct arm_smmu_device *new_smmu = ERR_PTR(-ENODEV);
4797 const struct arm_smmu_impl_ops *ops;
4798 int ret;
4799
4800 if (smmu->impl_dev && (smmu->options & ARM_SMMU_OPT_TEGRA241_CMDQV))
4801 new_smmu = tegra241_cmdqv_probe(smmu);
4802
4803 if (new_smmu == ERR_PTR(-ENODEV))
4804 return smmu;
4805 if (IS_ERR(new_smmu))
4806 return new_smmu;
4807
4808 ops = new_smmu->impl_ops;
4809 if (ops) {
4810 /* get_viommu_size and vsmmu_init ops must be paired */
4811 if (WARN_ON(!ops->get_viommu_size != !ops->vsmmu_init)) {
4812 ret = -EINVAL;
4813 goto err_remove;
4814 }
4815 }
4816
4817 ret = devm_add_action_or_reset(new_smmu->dev, arm_smmu_impl_remove,
4818 new_smmu);
4819 if (ret)
4820 return ERR_PTR(ret);
4821 return new_smmu;
4822
4823 err_remove:
4824 arm_smmu_impl_remove(new_smmu);
4825 return ERR_PTR(ret);
4826 }
4827
4828 static int arm_smmu_device_probe(struct platform_device *pdev)
4829 {
4830 int irq, ret;
4831 struct resource *res;
4832 resource_size_t ioaddr;
4833 struct arm_smmu_device *smmu;
4834 struct device *dev = &pdev->dev;
4835
4836 smmu = devm_kzalloc(dev, sizeof(*smmu), GFP_KERNEL);
4837 if (!smmu)
4838 return -ENOMEM;
4839 smmu->dev = dev;
4840
4841 if (dev->of_node) {
4842 ret = arm_smmu_device_dt_probe(pdev, smmu);
4843 } else {
4844 ret = arm_smmu_device_acpi_probe(pdev, smmu);
4845 }
4846 if (ret)
4847 return ret;
4848
4849 smmu = arm_smmu_impl_probe(smmu);
4850 if (IS_ERR(smmu))
4851 return PTR_ERR(smmu);
4852
4853 /* Base address */
4854 res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
4855 if (!res)
4856 return -EINVAL;
4857 if (resource_size(res) < arm_smmu_resource_size(smmu)) {
4858 dev_err(dev, "MMIO region too small (%pr)\n", res);
4859 return -EINVAL;
4860 }
4861 ioaddr = res->start;
4862
4863 /*
4864 * Don't map the IMPLEMENTATION DEFINED regions, since they may contain
4865 * the PMCG registers which are reserved by the PMU driver.
4866 */
4867 smmu->base = arm_smmu_ioremap(dev, ioaddr, ARM_SMMU_REG_SZ);
4868 if (IS_ERR(smmu->base))
4869 return PTR_ERR(smmu->base);
4870
4871 if (arm_smmu_resource_size(smmu) > SZ_64K) {
4872 smmu->page1 = arm_smmu_ioremap(dev, ioaddr + SZ_64K,
4873 ARM_SMMU_REG_SZ);
4874 if (IS_ERR(smmu->page1))
4875 return PTR_ERR(smmu->page1);
4876 } else {
4877 smmu->page1 = smmu->base;
4878 }
4879
4880 /* Interrupt lines */
4881
4882 irq = platform_get_irq_byname_optional(pdev, "combined");
4883 if (irq > 0)
4884 smmu->combined_irq = irq;
4885 else {
4886 irq = platform_get_irq_byname_optional(pdev, "eventq");
4887 if (irq > 0)
4888 smmu->evtq.q.irq = irq;
4889
4890 irq = platform_get_irq_byname_optional(pdev, "priq");
4891 if (irq > 0)
4892 smmu->priq.q.irq = irq;
4893
4894 irq = platform_get_irq_byname_optional(pdev, "gerror");
4895 if (irq > 0)
4896 smmu->gerr_irq = irq;
4897 }
4898 /* Probe the h/w */
4899 ret = arm_smmu_device_hw_probe(smmu);
4900 if (ret)
4901 return ret;
4902
4903 /* Initialise in-memory data structures */
4904 ret = arm_smmu_init_structures(smmu);
4905 if (ret)
4906 goto err_free_iopf;
4907
4908 /* Record our private device structure */
4909 platform_set_drvdata(pdev, smmu);
4910
4911 /* Check for RMRs and install bypass STEs if any */
4912 arm_smmu_rmr_install_bypass_ste(smmu);
4913
4914 /* Reset the device */
4915 ret = arm_smmu_device_reset(smmu);
4916 if (ret)
4917 goto err_disable;
4918
4919 /* And we're up. Go go go! */
4920 ret = iommu_device_sysfs_add(&smmu->iommu, dev, NULL,
4921 "smmu3.%pa", &ioaddr);
4922 if (ret)
4923 goto err_disable;
4924
4925 ret = iommu_device_register(&smmu->iommu, &arm_smmu_ops, dev);
4926 if (ret) {
4927 dev_err(dev, "Failed to register iommu\n");
4928 goto err_free_sysfs;
4929 }
4930
4931 return 0;
4932
4933 err_free_sysfs:
4934 iommu_device_sysfs_remove(&smmu->iommu);
4935 err_disable:
4936 arm_smmu_device_disable(smmu);
4937 err_free_iopf:
4938 iopf_queue_free(smmu->evtq.iopf);
4939 return ret;
4940 }
4941
4942 static void arm_smmu_device_remove(struct platform_device *pdev)
4943 {
4944 struct arm_smmu_device *smmu = platform_get_drvdata(pdev);
4945
4946 iommu_device_unregister(&smmu->iommu);
4947 iommu_device_sysfs_remove(&smmu->iommu);
4948 arm_smmu_device_disable(smmu);
4949 iopf_queue_free(smmu->evtq.iopf);
4950 ida_destroy(&smmu->vmid_map);
4951 }
4952
4953 static void arm_smmu_device_shutdown(struct platform_device *pdev)
4954 {
4955 struct arm_smmu_device *smmu = platform_get_drvdata(pdev);
4956
4957 arm_smmu_device_disable(smmu);
4958 }
4959
4960 static const struct of_device_id arm_smmu_of_match[] = {
4961 { .compatible = "arm,smmu-v3", },
4962 { },
4963 };
4964 MODULE_DEVICE_TABLE(of, arm_smmu_of_match);
4965
4966 static void arm_smmu_driver_unregister(struct platform_driver *drv)
4967 {
4968 arm_smmu_sva_notifier_synchronize();
4969 platform_driver_unregister(drv);
4970 }
4971
4972 static struct platform_driver arm_smmu_driver = {
4973 .driver = {
4974 .name = "arm-smmu-v3",
4975 .of_match_table = arm_smmu_of_match,
4976 .suppress_bind_attrs = true,
4977 },
4978 .probe = arm_smmu_device_probe,
4979 .remove = arm_smmu_device_remove,
4980 .shutdown = arm_smmu_device_shutdown,
4981 };
4982 module_driver(arm_smmu_driver, platform_driver_register,
4983 arm_smmu_driver_unregister);
4984
4985 MODULE_DESCRIPTION("IOMMU API for ARM architected SMMUv3 implementations");
4986 MODULE_AUTHOR("Will Deacon <[email protected]>");
4987 MODULE_ALIAS("platform:arm-smmu-v3");
4988 MODULE_LICENSE("GPL v2");