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