xref: /openbmc/linux/drivers/iommu/ipmmu-vmsa.c (revision 8fdf9062)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * IOMMU API for Renesas VMSA-compatible IPMMU
4  * Author: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
5  *
6  * Copyright (C) 2014 Renesas Electronics Corporation
7  */
8 
9 #include <linux/bitmap.h>
10 #include <linux/delay.h>
11 #include <linux/dma-iommu.h>
12 #include <linux/dma-mapping.h>
13 #include <linux/err.h>
14 #include <linux/export.h>
15 #include <linux/init.h>
16 #include <linux/interrupt.h>
17 #include <linux/io.h>
18 #include <linux/iommu.h>
19 #include <linux/of.h>
20 #include <linux/of_device.h>
21 #include <linux/of_iommu.h>
22 #include <linux/of_platform.h>
23 #include <linux/platform_device.h>
24 #include <linux/sizes.h>
25 #include <linux/slab.h>
26 #include <linux/sys_soc.h>
27 
28 #if defined(CONFIG_ARM) && !defined(CONFIG_IOMMU_DMA)
29 #include <asm/dma-iommu.h>
30 #include <asm/pgalloc.h>
31 #else
32 #define arm_iommu_create_mapping(...)	NULL
33 #define arm_iommu_attach_device(...)	-ENODEV
34 #define arm_iommu_release_mapping(...)	do {} while (0)
35 #define arm_iommu_detach_device(...)	do {} while (0)
36 #endif
37 
38 #include "io-pgtable.h"
39 
40 #define IPMMU_CTX_MAX 8
41 
42 struct ipmmu_features {
43 	bool use_ns_alias_offset;
44 	bool has_cache_leaf_nodes;
45 	unsigned int number_of_contexts;
46 	bool setup_imbuscr;
47 	bool twobit_imttbcr_sl0;
48 	bool reserved_context;
49 };
50 
51 struct ipmmu_vmsa_device {
52 	struct device *dev;
53 	void __iomem *base;
54 	struct iommu_device iommu;
55 	struct ipmmu_vmsa_device *root;
56 	const struct ipmmu_features *features;
57 	unsigned int num_utlbs;
58 	unsigned int num_ctx;
59 	spinlock_t lock;			/* Protects ctx and domains[] */
60 	DECLARE_BITMAP(ctx, IPMMU_CTX_MAX);
61 	struct ipmmu_vmsa_domain *domains[IPMMU_CTX_MAX];
62 
63 	struct iommu_group *group;
64 	struct dma_iommu_mapping *mapping;
65 };
66 
67 struct ipmmu_vmsa_domain {
68 	struct ipmmu_vmsa_device *mmu;
69 	struct iommu_domain io_domain;
70 
71 	struct io_pgtable_cfg cfg;
72 	struct io_pgtable_ops *iop;
73 
74 	unsigned int context_id;
75 	struct mutex mutex;			/* Protects mappings */
76 };
77 
78 static struct ipmmu_vmsa_domain *to_vmsa_domain(struct iommu_domain *dom)
79 {
80 	return container_of(dom, struct ipmmu_vmsa_domain, io_domain);
81 }
82 
83 static struct ipmmu_vmsa_device *to_ipmmu(struct device *dev)
84 {
85 	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
86 
87 	return fwspec ? fwspec->iommu_priv : NULL;
88 }
89 
90 #define TLB_LOOP_TIMEOUT		100	/* 100us */
91 
92 /* -----------------------------------------------------------------------------
93  * Registers Definition
94  */
95 
96 #define IM_NS_ALIAS_OFFSET		0x800
97 
98 #define IM_CTX_SIZE			0x40
99 
100 #define IMCTR				0x0000
101 #define IMCTR_TRE			(1 << 17)
102 #define IMCTR_AFE			(1 << 16)
103 #define IMCTR_RTSEL_MASK		(3 << 4)
104 #define IMCTR_RTSEL_SHIFT		4
105 #define IMCTR_TREN			(1 << 3)
106 #define IMCTR_INTEN			(1 << 2)
107 #define IMCTR_FLUSH			(1 << 1)
108 #define IMCTR_MMUEN			(1 << 0)
109 
110 #define IMCAAR				0x0004
111 
112 #define IMTTBCR				0x0008
113 #define IMTTBCR_EAE			(1 << 31)
114 #define IMTTBCR_PMB			(1 << 30)
115 #define IMTTBCR_SH1_NON_SHAREABLE	(0 << 28)
116 #define IMTTBCR_SH1_OUTER_SHAREABLE	(2 << 28)
117 #define IMTTBCR_SH1_INNER_SHAREABLE	(3 << 28)
118 #define IMTTBCR_SH1_MASK		(3 << 28)
119 #define IMTTBCR_ORGN1_NC		(0 << 26)
120 #define IMTTBCR_ORGN1_WB_WA		(1 << 26)
121 #define IMTTBCR_ORGN1_WT		(2 << 26)
122 #define IMTTBCR_ORGN1_WB		(3 << 26)
123 #define IMTTBCR_ORGN1_MASK		(3 << 26)
124 #define IMTTBCR_IRGN1_NC		(0 << 24)
125 #define IMTTBCR_IRGN1_WB_WA		(1 << 24)
126 #define IMTTBCR_IRGN1_WT		(2 << 24)
127 #define IMTTBCR_IRGN1_WB		(3 << 24)
128 #define IMTTBCR_IRGN1_MASK		(3 << 24)
129 #define IMTTBCR_TSZ1_MASK		(7 << 16)
130 #define IMTTBCR_TSZ1_SHIFT		16
131 #define IMTTBCR_SH0_NON_SHAREABLE	(0 << 12)
132 #define IMTTBCR_SH0_OUTER_SHAREABLE	(2 << 12)
133 #define IMTTBCR_SH0_INNER_SHAREABLE	(3 << 12)
134 #define IMTTBCR_SH0_MASK		(3 << 12)
135 #define IMTTBCR_ORGN0_NC		(0 << 10)
136 #define IMTTBCR_ORGN0_WB_WA		(1 << 10)
137 #define IMTTBCR_ORGN0_WT		(2 << 10)
138 #define IMTTBCR_ORGN0_WB		(3 << 10)
139 #define IMTTBCR_ORGN0_MASK		(3 << 10)
140 #define IMTTBCR_IRGN0_NC		(0 << 8)
141 #define IMTTBCR_IRGN0_WB_WA		(1 << 8)
142 #define IMTTBCR_IRGN0_WT		(2 << 8)
143 #define IMTTBCR_IRGN0_WB		(3 << 8)
144 #define IMTTBCR_IRGN0_MASK		(3 << 8)
145 #define IMTTBCR_SL0_LVL_2		(0 << 4)
146 #define IMTTBCR_SL0_LVL_1		(1 << 4)
147 #define IMTTBCR_TSZ0_MASK		(7 << 0)
148 #define IMTTBCR_TSZ0_SHIFT		O
149 
150 #define IMTTBCR_SL0_TWOBIT_LVL_3	(0 << 6)
151 #define IMTTBCR_SL0_TWOBIT_LVL_2	(1 << 6)
152 #define IMTTBCR_SL0_TWOBIT_LVL_1	(2 << 6)
153 
154 #define IMBUSCR				0x000c
155 #define IMBUSCR_DVM			(1 << 2)
156 #define IMBUSCR_BUSSEL_SYS		(0 << 0)
157 #define IMBUSCR_BUSSEL_CCI		(1 << 0)
158 #define IMBUSCR_BUSSEL_IMCAAR		(2 << 0)
159 #define IMBUSCR_BUSSEL_CCI_IMCAAR	(3 << 0)
160 #define IMBUSCR_BUSSEL_MASK		(3 << 0)
161 
162 #define IMTTLBR0			0x0010
163 #define IMTTUBR0			0x0014
164 #define IMTTLBR1			0x0018
165 #define IMTTUBR1			0x001c
166 
167 #define IMSTR				0x0020
168 #define IMSTR_ERRLVL_MASK		(3 << 12)
169 #define IMSTR_ERRLVL_SHIFT		12
170 #define IMSTR_ERRCODE_TLB_FORMAT	(1 << 8)
171 #define IMSTR_ERRCODE_ACCESS_PERM	(4 << 8)
172 #define IMSTR_ERRCODE_SECURE_ACCESS	(5 << 8)
173 #define IMSTR_ERRCODE_MASK		(7 << 8)
174 #define IMSTR_MHIT			(1 << 4)
175 #define IMSTR_ABORT			(1 << 2)
176 #define IMSTR_PF			(1 << 1)
177 #define IMSTR_TF			(1 << 0)
178 
179 #define IMMAIR0				0x0028
180 #define IMMAIR1				0x002c
181 #define IMMAIR_ATTR_MASK		0xff
182 #define IMMAIR_ATTR_DEVICE		0x04
183 #define IMMAIR_ATTR_NC			0x44
184 #define IMMAIR_ATTR_WBRWA		0xff
185 #define IMMAIR_ATTR_SHIFT(n)		((n) << 3)
186 #define IMMAIR_ATTR_IDX_NC		0
187 #define IMMAIR_ATTR_IDX_WBRWA		1
188 #define IMMAIR_ATTR_IDX_DEV		2
189 
190 #define IMEAR				0x0030
191 
192 #define IMPCTR				0x0200
193 #define IMPSTR				0x0208
194 #define IMPEAR				0x020c
195 #define IMPMBA(n)			(0x0280 + ((n) * 4))
196 #define IMPMBD(n)			(0x02c0 + ((n) * 4))
197 
198 #define IMUCTR(n)			((n) < 32 ? IMUCTR0(n) : IMUCTR32(n))
199 #define IMUCTR0(n)			(0x0300 + ((n) * 16))
200 #define IMUCTR32(n)			(0x0600 + (((n) - 32) * 16))
201 #define IMUCTR_FIXADDEN			(1 << 31)
202 #define IMUCTR_FIXADD_MASK		(0xff << 16)
203 #define IMUCTR_FIXADD_SHIFT		16
204 #define IMUCTR_TTSEL_MMU(n)		((n) << 4)
205 #define IMUCTR_TTSEL_PMB		(8 << 4)
206 #define IMUCTR_TTSEL_MASK		(15 << 4)
207 #define IMUCTR_FLUSH			(1 << 1)
208 #define IMUCTR_MMUEN			(1 << 0)
209 
210 #define IMUASID(n)			((n) < 32 ? IMUASID0(n) : IMUASID32(n))
211 #define IMUASID0(n)			(0x0308 + ((n) * 16))
212 #define IMUASID32(n)			(0x0608 + (((n) - 32) * 16))
213 #define IMUASID_ASID8_MASK		(0xff << 8)
214 #define IMUASID_ASID8_SHIFT		8
215 #define IMUASID_ASID0_MASK		(0xff << 0)
216 #define IMUASID_ASID0_SHIFT		0
217 
218 /* -----------------------------------------------------------------------------
219  * Root device handling
220  */
221 
222 static struct platform_driver ipmmu_driver;
223 
224 static bool ipmmu_is_root(struct ipmmu_vmsa_device *mmu)
225 {
226 	return mmu->root == mmu;
227 }
228 
229 static int __ipmmu_check_device(struct device *dev, void *data)
230 {
231 	struct ipmmu_vmsa_device *mmu = dev_get_drvdata(dev);
232 	struct ipmmu_vmsa_device **rootp = data;
233 
234 	if (ipmmu_is_root(mmu))
235 		*rootp = mmu;
236 
237 	return 0;
238 }
239 
240 static struct ipmmu_vmsa_device *ipmmu_find_root(void)
241 {
242 	struct ipmmu_vmsa_device *root = NULL;
243 
244 	return driver_for_each_device(&ipmmu_driver.driver, NULL, &root,
245 				      __ipmmu_check_device) == 0 ? root : NULL;
246 }
247 
248 /* -----------------------------------------------------------------------------
249  * Read/Write Access
250  */
251 
252 static u32 ipmmu_read(struct ipmmu_vmsa_device *mmu, unsigned int offset)
253 {
254 	return ioread32(mmu->base + offset);
255 }
256 
257 static void ipmmu_write(struct ipmmu_vmsa_device *mmu, unsigned int offset,
258 			u32 data)
259 {
260 	iowrite32(data, mmu->base + offset);
261 }
262 
263 static u32 ipmmu_ctx_read_root(struct ipmmu_vmsa_domain *domain,
264 			       unsigned int reg)
265 {
266 	return ipmmu_read(domain->mmu->root,
267 			  domain->context_id * IM_CTX_SIZE + reg);
268 }
269 
270 static void ipmmu_ctx_write_root(struct ipmmu_vmsa_domain *domain,
271 				 unsigned int reg, u32 data)
272 {
273 	ipmmu_write(domain->mmu->root,
274 		    domain->context_id * IM_CTX_SIZE + reg, data);
275 }
276 
277 static void ipmmu_ctx_write_all(struct ipmmu_vmsa_domain *domain,
278 				unsigned int reg, u32 data)
279 {
280 	if (domain->mmu != domain->mmu->root)
281 		ipmmu_write(domain->mmu,
282 			    domain->context_id * IM_CTX_SIZE + reg, data);
283 
284 	ipmmu_write(domain->mmu->root,
285 		    domain->context_id * IM_CTX_SIZE + reg, data);
286 }
287 
288 /* -----------------------------------------------------------------------------
289  * TLB and microTLB Management
290  */
291 
292 /* Wait for any pending TLB invalidations to complete */
293 static void ipmmu_tlb_sync(struct ipmmu_vmsa_domain *domain)
294 {
295 	unsigned int count = 0;
296 
297 	while (ipmmu_ctx_read_root(domain, IMCTR) & IMCTR_FLUSH) {
298 		cpu_relax();
299 		if (++count == TLB_LOOP_TIMEOUT) {
300 			dev_err_ratelimited(domain->mmu->dev,
301 			"TLB sync timed out -- MMU may be deadlocked\n");
302 			return;
303 		}
304 		udelay(1);
305 	}
306 }
307 
308 static void ipmmu_tlb_invalidate(struct ipmmu_vmsa_domain *domain)
309 {
310 	u32 reg;
311 
312 	reg = ipmmu_ctx_read_root(domain, IMCTR);
313 	reg |= IMCTR_FLUSH;
314 	ipmmu_ctx_write_all(domain, IMCTR, reg);
315 
316 	ipmmu_tlb_sync(domain);
317 }
318 
319 /*
320  * Enable MMU translation for the microTLB.
321  */
322 static void ipmmu_utlb_enable(struct ipmmu_vmsa_domain *domain,
323 			      unsigned int utlb)
324 {
325 	struct ipmmu_vmsa_device *mmu = domain->mmu;
326 
327 	/*
328 	 * TODO: Reference-count the microTLB as several bus masters can be
329 	 * connected to the same microTLB.
330 	 */
331 
332 	/* TODO: What should we set the ASID to ? */
333 	ipmmu_write(mmu, IMUASID(utlb), 0);
334 	/* TODO: Do we need to flush the microTLB ? */
335 	ipmmu_write(mmu, IMUCTR(utlb),
336 		    IMUCTR_TTSEL_MMU(domain->context_id) | IMUCTR_FLUSH |
337 		    IMUCTR_MMUEN);
338 }
339 
340 /*
341  * Disable MMU translation for the microTLB.
342  */
343 static void ipmmu_utlb_disable(struct ipmmu_vmsa_domain *domain,
344 			       unsigned int utlb)
345 {
346 	struct ipmmu_vmsa_device *mmu = domain->mmu;
347 
348 	ipmmu_write(mmu, IMUCTR(utlb), 0);
349 }
350 
351 static void ipmmu_tlb_flush_all(void *cookie)
352 {
353 	struct ipmmu_vmsa_domain *domain = cookie;
354 
355 	ipmmu_tlb_invalidate(domain);
356 }
357 
358 static void ipmmu_tlb_add_flush(unsigned long iova, size_t size,
359 				size_t granule, bool leaf, void *cookie)
360 {
361 	/* The hardware doesn't support selective TLB flush. */
362 }
363 
364 static const struct iommu_gather_ops ipmmu_gather_ops = {
365 	.tlb_flush_all = ipmmu_tlb_flush_all,
366 	.tlb_add_flush = ipmmu_tlb_add_flush,
367 	.tlb_sync = ipmmu_tlb_flush_all,
368 };
369 
370 /* -----------------------------------------------------------------------------
371  * Domain/Context Management
372  */
373 
374 static int ipmmu_domain_allocate_context(struct ipmmu_vmsa_device *mmu,
375 					 struct ipmmu_vmsa_domain *domain)
376 {
377 	unsigned long flags;
378 	int ret;
379 
380 	spin_lock_irqsave(&mmu->lock, flags);
381 
382 	ret = find_first_zero_bit(mmu->ctx, mmu->num_ctx);
383 	if (ret != mmu->num_ctx) {
384 		mmu->domains[ret] = domain;
385 		set_bit(ret, mmu->ctx);
386 	} else
387 		ret = -EBUSY;
388 
389 	spin_unlock_irqrestore(&mmu->lock, flags);
390 
391 	return ret;
392 }
393 
394 static void ipmmu_domain_free_context(struct ipmmu_vmsa_device *mmu,
395 				      unsigned int context_id)
396 {
397 	unsigned long flags;
398 
399 	spin_lock_irqsave(&mmu->lock, flags);
400 
401 	clear_bit(context_id, mmu->ctx);
402 	mmu->domains[context_id] = NULL;
403 
404 	spin_unlock_irqrestore(&mmu->lock, flags);
405 }
406 
407 static int ipmmu_domain_init_context(struct ipmmu_vmsa_domain *domain)
408 {
409 	u64 ttbr;
410 	u32 tmp;
411 	int ret;
412 
413 	/*
414 	 * Allocate the page table operations.
415 	 *
416 	 * VMSA states in section B3.6.3 "Control of Secure or Non-secure memory
417 	 * access, Long-descriptor format" that the NStable bit being set in a
418 	 * table descriptor will result in the NStable and NS bits of all child
419 	 * entries being ignored and considered as being set. The IPMMU seems
420 	 * not to comply with this, as it generates a secure access page fault
421 	 * if any of the NStable and NS bits isn't set when running in
422 	 * non-secure mode.
423 	 */
424 	domain->cfg.quirks = IO_PGTABLE_QUIRK_ARM_NS;
425 	domain->cfg.pgsize_bitmap = SZ_1G | SZ_2M | SZ_4K;
426 	domain->cfg.ias = 32;
427 	domain->cfg.oas = 40;
428 	domain->cfg.tlb = &ipmmu_gather_ops;
429 	domain->io_domain.geometry.aperture_end = DMA_BIT_MASK(32);
430 	domain->io_domain.geometry.force_aperture = true;
431 	/*
432 	 * TODO: Add support for coherent walk through CCI with DVM and remove
433 	 * cache handling. For now, delegate it to the io-pgtable code.
434 	 */
435 	domain->cfg.iommu_dev = domain->mmu->root->dev;
436 
437 	/*
438 	 * Find an unused context.
439 	 */
440 	ret = ipmmu_domain_allocate_context(domain->mmu->root, domain);
441 	if (ret < 0)
442 		return ret;
443 
444 	domain->context_id = ret;
445 
446 	domain->iop = alloc_io_pgtable_ops(ARM_32_LPAE_S1, &domain->cfg,
447 					   domain);
448 	if (!domain->iop) {
449 		ipmmu_domain_free_context(domain->mmu->root,
450 					  domain->context_id);
451 		return -EINVAL;
452 	}
453 
454 	/* TTBR0 */
455 	ttbr = domain->cfg.arm_lpae_s1_cfg.ttbr[0];
456 	ipmmu_ctx_write_root(domain, IMTTLBR0, ttbr);
457 	ipmmu_ctx_write_root(domain, IMTTUBR0, ttbr >> 32);
458 
459 	/*
460 	 * TTBCR
461 	 * We use long descriptors with inner-shareable WBWA tables and allocate
462 	 * the whole 32-bit VA space to TTBR0.
463 	 */
464 	if (domain->mmu->features->twobit_imttbcr_sl0)
465 		tmp = IMTTBCR_SL0_TWOBIT_LVL_1;
466 	else
467 		tmp = IMTTBCR_SL0_LVL_1;
468 
469 	ipmmu_ctx_write_root(domain, IMTTBCR, IMTTBCR_EAE |
470 			     IMTTBCR_SH0_INNER_SHAREABLE | IMTTBCR_ORGN0_WB_WA |
471 			     IMTTBCR_IRGN0_WB_WA | tmp);
472 
473 	/* MAIR0 */
474 	ipmmu_ctx_write_root(domain, IMMAIR0,
475 			     domain->cfg.arm_lpae_s1_cfg.mair[0]);
476 
477 	/* IMBUSCR */
478 	if (domain->mmu->features->setup_imbuscr)
479 		ipmmu_ctx_write_root(domain, IMBUSCR,
480 				     ipmmu_ctx_read_root(domain, IMBUSCR) &
481 				     ~(IMBUSCR_DVM | IMBUSCR_BUSSEL_MASK));
482 
483 	/*
484 	 * IMSTR
485 	 * Clear all interrupt flags.
486 	 */
487 	ipmmu_ctx_write_root(domain, IMSTR, ipmmu_ctx_read_root(domain, IMSTR));
488 
489 	/*
490 	 * IMCTR
491 	 * Enable the MMU and interrupt generation. The long-descriptor
492 	 * translation table format doesn't use TEX remapping. Don't enable AF
493 	 * software management as we have no use for it. Flush the TLB as
494 	 * required when modifying the context registers.
495 	 */
496 	ipmmu_ctx_write_all(domain, IMCTR,
497 			    IMCTR_INTEN | IMCTR_FLUSH | IMCTR_MMUEN);
498 
499 	return 0;
500 }
501 
502 static void ipmmu_domain_destroy_context(struct ipmmu_vmsa_domain *domain)
503 {
504 	if (!domain->mmu)
505 		return;
506 
507 	/*
508 	 * Disable the context. Flush the TLB as required when modifying the
509 	 * context registers.
510 	 *
511 	 * TODO: Is TLB flush really needed ?
512 	 */
513 	ipmmu_ctx_write_all(domain, IMCTR, IMCTR_FLUSH);
514 	ipmmu_tlb_sync(domain);
515 	ipmmu_domain_free_context(domain->mmu->root, domain->context_id);
516 }
517 
518 /* -----------------------------------------------------------------------------
519  * Fault Handling
520  */
521 
522 static irqreturn_t ipmmu_domain_irq(struct ipmmu_vmsa_domain *domain)
523 {
524 	const u32 err_mask = IMSTR_MHIT | IMSTR_ABORT | IMSTR_PF | IMSTR_TF;
525 	struct ipmmu_vmsa_device *mmu = domain->mmu;
526 	u32 status;
527 	u32 iova;
528 
529 	status = ipmmu_ctx_read_root(domain, IMSTR);
530 	if (!(status & err_mask))
531 		return IRQ_NONE;
532 
533 	iova = ipmmu_ctx_read_root(domain, IMEAR);
534 
535 	/*
536 	 * Clear the error status flags. Unlike traditional interrupt flag
537 	 * registers that must be cleared by writing 1, this status register
538 	 * seems to require 0. The error address register must be read before,
539 	 * otherwise its value will be 0.
540 	 */
541 	ipmmu_ctx_write_root(domain, IMSTR, 0);
542 
543 	/* Log fatal errors. */
544 	if (status & IMSTR_MHIT)
545 		dev_err_ratelimited(mmu->dev, "Multiple TLB hits @0x%08x\n",
546 				    iova);
547 	if (status & IMSTR_ABORT)
548 		dev_err_ratelimited(mmu->dev, "Page Table Walk Abort @0x%08x\n",
549 				    iova);
550 
551 	if (!(status & (IMSTR_PF | IMSTR_TF)))
552 		return IRQ_NONE;
553 
554 	/*
555 	 * Try to handle page faults and translation faults.
556 	 *
557 	 * TODO: We need to look up the faulty device based on the I/O VA. Use
558 	 * the IOMMU device for now.
559 	 */
560 	if (!report_iommu_fault(&domain->io_domain, mmu->dev, iova, 0))
561 		return IRQ_HANDLED;
562 
563 	dev_err_ratelimited(mmu->dev,
564 			    "Unhandled fault: status 0x%08x iova 0x%08x\n",
565 			    status, iova);
566 
567 	return IRQ_HANDLED;
568 }
569 
570 static irqreturn_t ipmmu_irq(int irq, void *dev)
571 {
572 	struct ipmmu_vmsa_device *mmu = dev;
573 	irqreturn_t status = IRQ_NONE;
574 	unsigned int i;
575 	unsigned long flags;
576 
577 	spin_lock_irqsave(&mmu->lock, flags);
578 
579 	/*
580 	 * Check interrupts for all active contexts.
581 	 */
582 	for (i = 0; i < mmu->num_ctx; i++) {
583 		if (!mmu->domains[i])
584 			continue;
585 		if (ipmmu_domain_irq(mmu->domains[i]) == IRQ_HANDLED)
586 			status = IRQ_HANDLED;
587 	}
588 
589 	spin_unlock_irqrestore(&mmu->lock, flags);
590 
591 	return status;
592 }
593 
594 /* -----------------------------------------------------------------------------
595  * IOMMU Operations
596  */
597 
598 static struct iommu_domain *__ipmmu_domain_alloc(unsigned type)
599 {
600 	struct ipmmu_vmsa_domain *domain;
601 
602 	domain = kzalloc(sizeof(*domain), GFP_KERNEL);
603 	if (!domain)
604 		return NULL;
605 
606 	mutex_init(&domain->mutex);
607 
608 	return &domain->io_domain;
609 }
610 
611 static struct iommu_domain *ipmmu_domain_alloc(unsigned type)
612 {
613 	struct iommu_domain *io_domain = NULL;
614 
615 	switch (type) {
616 	case IOMMU_DOMAIN_UNMANAGED:
617 		io_domain = __ipmmu_domain_alloc(type);
618 		break;
619 
620 	case IOMMU_DOMAIN_DMA:
621 		io_domain = __ipmmu_domain_alloc(type);
622 		if (io_domain && iommu_get_dma_cookie(io_domain)) {
623 			kfree(io_domain);
624 			io_domain = NULL;
625 		}
626 		break;
627 	}
628 
629 	return io_domain;
630 }
631 
632 static void ipmmu_domain_free(struct iommu_domain *io_domain)
633 {
634 	struct ipmmu_vmsa_domain *domain = to_vmsa_domain(io_domain);
635 
636 	/*
637 	 * Free the domain resources. We assume that all devices have already
638 	 * been detached.
639 	 */
640 	iommu_put_dma_cookie(io_domain);
641 	ipmmu_domain_destroy_context(domain);
642 	free_io_pgtable_ops(domain->iop);
643 	kfree(domain);
644 }
645 
646 static int ipmmu_attach_device(struct iommu_domain *io_domain,
647 			       struct device *dev)
648 {
649 	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
650 	struct ipmmu_vmsa_device *mmu = to_ipmmu(dev);
651 	struct ipmmu_vmsa_domain *domain = to_vmsa_domain(io_domain);
652 	unsigned int i;
653 	int ret = 0;
654 
655 	if (!mmu) {
656 		dev_err(dev, "Cannot attach to IPMMU\n");
657 		return -ENXIO;
658 	}
659 
660 	mutex_lock(&domain->mutex);
661 
662 	if (!domain->mmu) {
663 		/* The domain hasn't been used yet, initialize it. */
664 		domain->mmu = mmu;
665 		ret = ipmmu_domain_init_context(domain);
666 		if (ret < 0) {
667 			dev_err(dev, "Unable to initialize IPMMU context\n");
668 			domain->mmu = NULL;
669 		} else {
670 			dev_info(dev, "Using IPMMU context %u\n",
671 				 domain->context_id);
672 		}
673 	} else if (domain->mmu != mmu) {
674 		/*
675 		 * Something is wrong, we can't attach two devices using
676 		 * different IOMMUs to the same domain.
677 		 */
678 		dev_err(dev, "Can't attach IPMMU %s to domain on IPMMU %s\n",
679 			dev_name(mmu->dev), dev_name(domain->mmu->dev));
680 		ret = -EINVAL;
681 	} else
682 		dev_info(dev, "Reusing IPMMU context %u\n", domain->context_id);
683 
684 	mutex_unlock(&domain->mutex);
685 
686 	if (ret < 0)
687 		return ret;
688 
689 	for (i = 0; i < fwspec->num_ids; ++i)
690 		ipmmu_utlb_enable(domain, fwspec->ids[i]);
691 
692 	return 0;
693 }
694 
695 static void ipmmu_detach_device(struct iommu_domain *io_domain,
696 				struct device *dev)
697 {
698 	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
699 	struct ipmmu_vmsa_domain *domain = to_vmsa_domain(io_domain);
700 	unsigned int i;
701 
702 	for (i = 0; i < fwspec->num_ids; ++i)
703 		ipmmu_utlb_disable(domain, fwspec->ids[i]);
704 
705 	/*
706 	 * TODO: Optimize by disabling the context when no device is attached.
707 	 */
708 }
709 
710 static int ipmmu_map(struct iommu_domain *io_domain, unsigned long iova,
711 		     phys_addr_t paddr, size_t size, int prot)
712 {
713 	struct ipmmu_vmsa_domain *domain = to_vmsa_domain(io_domain);
714 
715 	if (!domain)
716 		return -ENODEV;
717 
718 	return domain->iop->map(domain->iop, iova, paddr, size, prot);
719 }
720 
721 static size_t ipmmu_unmap(struct iommu_domain *io_domain, unsigned long iova,
722 			  size_t size)
723 {
724 	struct ipmmu_vmsa_domain *domain = to_vmsa_domain(io_domain);
725 
726 	return domain->iop->unmap(domain->iop, iova, size);
727 }
728 
729 static void ipmmu_iotlb_sync(struct iommu_domain *io_domain)
730 {
731 	struct ipmmu_vmsa_domain *domain = to_vmsa_domain(io_domain);
732 
733 	if (domain->mmu)
734 		ipmmu_tlb_flush_all(domain);
735 }
736 
737 static phys_addr_t ipmmu_iova_to_phys(struct iommu_domain *io_domain,
738 				      dma_addr_t iova)
739 {
740 	struct ipmmu_vmsa_domain *domain = to_vmsa_domain(io_domain);
741 
742 	/* TODO: Is locking needed ? */
743 
744 	return domain->iop->iova_to_phys(domain->iop, iova);
745 }
746 
747 static int ipmmu_init_platform_device(struct device *dev,
748 				      struct of_phandle_args *args)
749 {
750 	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
751 	struct platform_device *ipmmu_pdev;
752 
753 	ipmmu_pdev = of_find_device_by_node(args->np);
754 	if (!ipmmu_pdev)
755 		return -ENODEV;
756 
757 	fwspec->iommu_priv = platform_get_drvdata(ipmmu_pdev);
758 
759 	return 0;
760 }
761 
762 static const struct soc_device_attribute soc_rcar_gen3[] = {
763 	{ .soc_id = "r8a774a1", },
764 	{ .soc_id = "r8a774c0", },
765 	{ .soc_id = "r8a7795", },
766 	{ .soc_id = "r8a7796", },
767 	{ .soc_id = "r8a77965", },
768 	{ .soc_id = "r8a77970", },
769 	{ .soc_id = "r8a77990", },
770 	{ .soc_id = "r8a77995", },
771 	{ /* sentinel */ }
772 };
773 
774 static const struct soc_device_attribute soc_rcar_gen3_whitelist[] = {
775 	{ .soc_id = "r8a774c0", },
776 	{ .soc_id = "r8a7795", .revision = "ES3.*" },
777 	{ .soc_id = "r8a77965", },
778 	{ .soc_id = "r8a77990", },
779 	{ .soc_id = "r8a77995", },
780 	{ /* sentinel */ }
781 };
782 
783 static const char * const rcar_gen3_slave_whitelist[] = {
784 };
785 
786 static bool ipmmu_slave_whitelist(struct device *dev)
787 {
788 	unsigned int i;
789 
790 	/*
791 	 * For R-Car Gen3 use a white list to opt-in slave devices.
792 	 * For Other SoCs, this returns true anyway.
793 	 */
794 	if (!soc_device_match(soc_rcar_gen3))
795 		return true;
796 
797 	/* Check whether this R-Car Gen3 can use the IPMMU correctly or not */
798 	if (!soc_device_match(soc_rcar_gen3_whitelist))
799 		return false;
800 
801 	/* Check whether this slave device can work with the IPMMU */
802 	for (i = 0; i < ARRAY_SIZE(rcar_gen3_slave_whitelist); i++) {
803 		if (!strcmp(dev_name(dev), rcar_gen3_slave_whitelist[i]))
804 			return true;
805 	}
806 
807 	/* Otherwise, do not allow use of IPMMU */
808 	return false;
809 }
810 
811 static int ipmmu_of_xlate(struct device *dev,
812 			  struct of_phandle_args *spec)
813 {
814 	if (!ipmmu_slave_whitelist(dev))
815 		return -ENODEV;
816 
817 	iommu_fwspec_add_ids(dev, spec->args, 1);
818 
819 	/* Initialize once - xlate() will call multiple times */
820 	if (to_ipmmu(dev))
821 		return 0;
822 
823 	return ipmmu_init_platform_device(dev, spec);
824 }
825 
826 static int ipmmu_init_arm_mapping(struct device *dev)
827 {
828 	struct ipmmu_vmsa_device *mmu = to_ipmmu(dev);
829 	struct iommu_group *group;
830 	int ret;
831 
832 	/* Create a device group and add the device to it. */
833 	group = iommu_group_alloc();
834 	if (IS_ERR(group)) {
835 		dev_err(dev, "Failed to allocate IOMMU group\n");
836 		return PTR_ERR(group);
837 	}
838 
839 	ret = iommu_group_add_device(group, dev);
840 	iommu_group_put(group);
841 
842 	if (ret < 0) {
843 		dev_err(dev, "Failed to add device to IPMMU group\n");
844 		return ret;
845 	}
846 
847 	/*
848 	 * Create the ARM mapping, used by the ARM DMA mapping core to allocate
849 	 * VAs. This will allocate a corresponding IOMMU domain.
850 	 *
851 	 * TODO:
852 	 * - Create one mapping per context (TLB).
853 	 * - Make the mapping size configurable ? We currently use a 2GB mapping
854 	 *   at a 1GB offset to ensure that NULL VAs will fault.
855 	 */
856 	if (!mmu->mapping) {
857 		struct dma_iommu_mapping *mapping;
858 
859 		mapping = arm_iommu_create_mapping(&platform_bus_type,
860 						   SZ_1G, SZ_2G);
861 		if (IS_ERR(mapping)) {
862 			dev_err(mmu->dev, "failed to create ARM IOMMU mapping\n");
863 			ret = PTR_ERR(mapping);
864 			goto error;
865 		}
866 
867 		mmu->mapping = mapping;
868 	}
869 
870 	/* Attach the ARM VA mapping to the device. */
871 	ret = arm_iommu_attach_device(dev, mmu->mapping);
872 	if (ret < 0) {
873 		dev_err(dev, "Failed to attach device to VA mapping\n");
874 		goto error;
875 	}
876 
877 	return 0;
878 
879 error:
880 	iommu_group_remove_device(dev);
881 	if (mmu->mapping)
882 		arm_iommu_release_mapping(mmu->mapping);
883 
884 	return ret;
885 }
886 
887 static int ipmmu_add_device(struct device *dev)
888 {
889 	struct iommu_group *group;
890 
891 	/*
892 	 * Only let through devices that have been verified in xlate()
893 	 */
894 	if (!to_ipmmu(dev))
895 		return -ENODEV;
896 
897 	if (IS_ENABLED(CONFIG_ARM) && !IS_ENABLED(CONFIG_IOMMU_DMA))
898 		return ipmmu_init_arm_mapping(dev);
899 
900 	group = iommu_group_get_for_dev(dev);
901 	if (IS_ERR(group))
902 		return PTR_ERR(group);
903 
904 	iommu_group_put(group);
905 	return 0;
906 }
907 
908 static void ipmmu_remove_device(struct device *dev)
909 {
910 	arm_iommu_detach_device(dev);
911 	iommu_group_remove_device(dev);
912 }
913 
914 static struct iommu_group *ipmmu_find_group(struct device *dev)
915 {
916 	struct ipmmu_vmsa_device *mmu = to_ipmmu(dev);
917 	struct iommu_group *group;
918 
919 	if (mmu->group)
920 		return iommu_group_ref_get(mmu->group);
921 
922 	group = iommu_group_alloc();
923 	if (!IS_ERR(group))
924 		mmu->group = group;
925 
926 	return group;
927 }
928 
929 static const struct iommu_ops ipmmu_ops = {
930 	.domain_alloc = ipmmu_domain_alloc,
931 	.domain_free = ipmmu_domain_free,
932 	.attach_dev = ipmmu_attach_device,
933 	.detach_dev = ipmmu_detach_device,
934 	.map = ipmmu_map,
935 	.unmap = ipmmu_unmap,
936 	.flush_iotlb_all = ipmmu_iotlb_sync,
937 	.iotlb_sync = ipmmu_iotlb_sync,
938 	.iova_to_phys = ipmmu_iova_to_phys,
939 	.add_device = ipmmu_add_device,
940 	.remove_device = ipmmu_remove_device,
941 	.device_group = ipmmu_find_group,
942 	.pgsize_bitmap = SZ_1G | SZ_2M | SZ_4K,
943 	.of_xlate = ipmmu_of_xlate,
944 };
945 
946 /* -----------------------------------------------------------------------------
947  * Probe/remove and init
948  */
949 
950 static void ipmmu_device_reset(struct ipmmu_vmsa_device *mmu)
951 {
952 	unsigned int i;
953 
954 	/* Disable all contexts. */
955 	for (i = 0; i < mmu->num_ctx; ++i)
956 		ipmmu_write(mmu, i * IM_CTX_SIZE + IMCTR, 0);
957 }
958 
959 static const struct ipmmu_features ipmmu_features_default = {
960 	.use_ns_alias_offset = true,
961 	.has_cache_leaf_nodes = false,
962 	.number_of_contexts = 1, /* software only tested with one context */
963 	.setup_imbuscr = true,
964 	.twobit_imttbcr_sl0 = false,
965 	.reserved_context = false,
966 };
967 
968 static const struct ipmmu_features ipmmu_features_rcar_gen3 = {
969 	.use_ns_alias_offset = false,
970 	.has_cache_leaf_nodes = true,
971 	.number_of_contexts = 8,
972 	.setup_imbuscr = false,
973 	.twobit_imttbcr_sl0 = true,
974 	.reserved_context = true,
975 };
976 
977 static const struct of_device_id ipmmu_of_ids[] = {
978 	{
979 		.compatible = "renesas,ipmmu-vmsa",
980 		.data = &ipmmu_features_default,
981 	}, {
982 		.compatible = "renesas,ipmmu-r8a774a1",
983 		.data = &ipmmu_features_rcar_gen3,
984 	}, {
985 		.compatible = "renesas,ipmmu-r8a774c0",
986 		.data = &ipmmu_features_rcar_gen3,
987 	}, {
988 		.compatible = "renesas,ipmmu-r8a7795",
989 		.data = &ipmmu_features_rcar_gen3,
990 	}, {
991 		.compatible = "renesas,ipmmu-r8a7796",
992 		.data = &ipmmu_features_rcar_gen3,
993 	}, {
994 		.compatible = "renesas,ipmmu-r8a77965",
995 		.data = &ipmmu_features_rcar_gen3,
996 	}, {
997 		.compatible = "renesas,ipmmu-r8a77970",
998 		.data = &ipmmu_features_rcar_gen3,
999 	}, {
1000 		.compatible = "renesas,ipmmu-r8a77990",
1001 		.data = &ipmmu_features_rcar_gen3,
1002 	}, {
1003 		.compatible = "renesas,ipmmu-r8a77995",
1004 		.data = &ipmmu_features_rcar_gen3,
1005 	}, {
1006 		/* Terminator */
1007 	},
1008 };
1009 
1010 static int ipmmu_probe(struct platform_device *pdev)
1011 {
1012 	struct ipmmu_vmsa_device *mmu;
1013 	struct resource *res;
1014 	int irq;
1015 	int ret;
1016 
1017 	mmu = devm_kzalloc(&pdev->dev, sizeof(*mmu), GFP_KERNEL);
1018 	if (!mmu) {
1019 		dev_err(&pdev->dev, "cannot allocate device data\n");
1020 		return -ENOMEM;
1021 	}
1022 
1023 	mmu->dev = &pdev->dev;
1024 	mmu->num_utlbs = 48;
1025 	spin_lock_init(&mmu->lock);
1026 	bitmap_zero(mmu->ctx, IPMMU_CTX_MAX);
1027 	mmu->features = of_device_get_match_data(&pdev->dev);
1028 	dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(40));
1029 
1030 	/* Map I/O memory and request IRQ. */
1031 	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1032 	mmu->base = devm_ioremap_resource(&pdev->dev, res);
1033 	if (IS_ERR(mmu->base))
1034 		return PTR_ERR(mmu->base);
1035 
1036 	/*
1037 	 * The IPMMU has two register banks, for secure and non-secure modes.
1038 	 * The bank mapped at the beginning of the IPMMU address space
1039 	 * corresponds to the running mode of the CPU. When running in secure
1040 	 * mode the non-secure register bank is also available at an offset.
1041 	 *
1042 	 * Secure mode operation isn't clearly documented and is thus currently
1043 	 * not implemented in the driver. Furthermore, preliminary tests of
1044 	 * non-secure operation with the main register bank were not successful.
1045 	 * Offset the registers base unconditionally to point to the non-secure
1046 	 * alias space for now.
1047 	 */
1048 	if (mmu->features->use_ns_alias_offset)
1049 		mmu->base += IM_NS_ALIAS_OFFSET;
1050 
1051 	mmu->num_ctx = min_t(unsigned int, IPMMU_CTX_MAX,
1052 			     mmu->features->number_of_contexts);
1053 
1054 	irq = platform_get_irq(pdev, 0);
1055 
1056 	/*
1057 	 * Determine if this IPMMU instance is a root device by checking for
1058 	 * the lack of has_cache_leaf_nodes flag or renesas,ipmmu-main property.
1059 	 */
1060 	if (!mmu->features->has_cache_leaf_nodes ||
1061 	    !of_find_property(pdev->dev.of_node, "renesas,ipmmu-main", NULL))
1062 		mmu->root = mmu;
1063 	else
1064 		mmu->root = ipmmu_find_root();
1065 
1066 	/*
1067 	 * Wait until the root device has been registered for sure.
1068 	 */
1069 	if (!mmu->root)
1070 		return -EPROBE_DEFER;
1071 
1072 	/* Root devices have mandatory IRQs */
1073 	if (ipmmu_is_root(mmu)) {
1074 		if (irq < 0) {
1075 			dev_err(&pdev->dev, "no IRQ found\n");
1076 			return irq;
1077 		}
1078 
1079 		ret = devm_request_irq(&pdev->dev, irq, ipmmu_irq, 0,
1080 				       dev_name(&pdev->dev), mmu);
1081 		if (ret < 0) {
1082 			dev_err(&pdev->dev, "failed to request IRQ %d\n", irq);
1083 			return ret;
1084 		}
1085 
1086 		ipmmu_device_reset(mmu);
1087 
1088 		if (mmu->features->reserved_context) {
1089 			dev_info(&pdev->dev, "IPMMU context 0 is reserved\n");
1090 			set_bit(0, mmu->ctx);
1091 		}
1092 	}
1093 
1094 	/*
1095 	 * Register the IPMMU to the IOMMU subsystem in the following cases:
1096 	 * - R-Car Gen2 IPMMU (all devices registered)
1097 	 * - R-Car Gen3 IPMMU (leaf devices only - skip root IPMMU-MM device)
1098 	 */
1099 	if (!mmu->features->has_cache_leaf_nodes || !ipmmu_is_root(mmu)) {
1100 		ret = iommu_device_sysfs_add(&mmu->iommu, &pdev->dev, NULL,
1101 					     dev_name(&pdev->dev));
1102 		if (ret)
1103 			return ret;
1104 
1105 		iommu_device_set_ops(&mmu->iommu, &ipmmu_ops);
1106 		iommu_device_set_fwnode(&mmu->iommu,
1107 					&pdev->dev.of_node->fwnode);
1108 
1109 		ret = iommu_device_register(&mmu->iommu);
1110 		if (ret)
1111 			return ret;
1112 
1113 #if defined(CONFIG_IOMMU_DMA)
1114 		if (!iommu_present(&platform_bus_type))
1115 			bus_set_iommu(&platform_bus_type, &ipmmu_ops);
1116 #endif
1117 	}
1118 
1119 	/*
1120 	 * We can't create the ARM mapping here as it requires the bus to have
1121 	 * an IOMMU, which only happens when bus_set_iommu() is called in
1122 	 * ipmmu_init() after the probe function returns.
1123 	 */
1124 
1125 	platform_set_drvdata(pdev, mmu);
1126 
1127 	return 0;
1128 }
1129 
1130 static int ipmmu_remove(struct platform_device *pdev)
1131 {
1132 	struct ipmmu_vmsa_device *mmu = platform_get_drvdata(pdev);
1133 
1134 	iommu_device_sysfs_remove(&mmu->iommu);
1135 	iommu_device_unregister(&mmu->iommu);
1136 
1137 	arm_iommu_release_mapping(mmu->mapping);
1138 
1139 	ipmmu_device_reset(mmu);
1140 
1141 	return 0;
1142 }
1143 
1144 static struct platform_driver ipmmu_driver = {
1145 	.driver = {
1146 		.name = "ipmmu-vmsa",
1147 		.of_match_table = of_match_ptr(ipmmu_of_ids),
1148 	},
1149 	.probe = ipmmu_probe,
1150 	.remove	= ipmmu_remove,
1151 };
1152 
1153 static int __init ipmmu_init(void)
1154 {
1155 	struct device_node *np;
1156 	static bool setup_done;
1157 	int ret;
1158 
1159 	if (setup_done)
1160 		return 0;
1161 
1162 	np = of_find_matching_node(NULL, ipmmu_of_ids);
1163 	if (!np)
1164 		return 0;
1165 
1166 	of_node_put(np);
1167 
1168 	ret = platform_driver_register(&ipmmu_driver);
1169 	if (ret < 0)
1170 		return ret;
1171 
1172 #if defined(CONFIG_ARM) && !defined(CONFIG_IOMMU_DMA)
1173 	if (!iommu_present(&platform_bus_type))
1174 		bus_set_iommu(&platform_bus_type, &ipmmu_ops);
1175 #endif
1176 
1177 	setup_done = true;
1178 	return 0;
1179 }
1180 subsys_initcall(ipmmu_init);
1181