xref: /openbmc/linux/drivers/iommu/virtio-iommu.c (revision 6863aaa8)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Virtio driver for the paravirtualized IOMMU
4  *
5  * Copyright (C) 2019 Arm Limited
6  */
7 
8 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
9 
10 #include <linux/delay.h>
11 #include <linux/dma-map-ops.h>
12 #include <linux/freezer.h>
13 #include <linux/interval_tree.h>
14 #include <linux/iommu.h>
15 #include <linux/module.h>
16 #include <linux/of_platform.h>
17 #include <linux/pci.h>
18 #include <linux/virtio.h>
19 #include <linux/virtio_config.h>
20 #include <linux/virtio_ids.h>
21 #include <linux/wait.h>
22 
23 #include <uapi/linux/virtio_iommu.h>
24 
25 #include "dma-iommu.h"
26 
27 #define MSI_IOVA_BASE			0x8000000
28 #define MSI_IOVA_LENGTH			0x100000
29 
30 #define VIOMMU_REQUEST_VQ		0
31 #define VIOMMU_EVENT_VQ			1
32 #define VIOMMU_NR_VQS			2
33 
34 struct viommu_dev {
35 	struct iommu_device		iommu;
36 	struct device			*dev;
37 	struct virtio_device		*vdev;
38 
39 	struct ida			domain_ids;
40 
41 	struct virtqueue		*vqs[VIOMMU_NR_VQS];
42 	spinlock_t			request_lock;
43 	struct list_head		requests;
44 	void				*evts;
45 
46 	/* Device configuration */
47 	struct iommu_domain_geometry	geometry;
48 	u64				pgsize_bitmap;
49 	u32				first_domain;
50 	u32				last_domain;
51 	/* Supported MAP flags */
52 	u32				map_flags;
53 	u32				probe_size;
54 };
55 
56 struct viommu_mapping {
57 	phys_addr_t			paddr;
58 	struct interval_tree_node	iova;
59 	u32				flags;
60 };
61 
62 struct viommu_domain {
63 	struct iommu_domain		domain;
64 	struct viommu_dev		*viommu;
65 	struct mutex			mutex; /* protects viommu pointer */
66 	unsigned int			id;
67 	u32				map_flags;
68 
69 	spinlock_t			mappings_lock;
70 	struct rb_root_cached		mappings;
71 
72 	unsigned long			nr_endpoints;
73 	bool				bypass;
74 };
75 
76 struct viommu_endpoint {
77 	struct device			*dev;
78 	struct viommu_dev		*viommu;
79 	struct viommu_domain		*vdomain;
80 	struct list_head		resv_regions;
81 };
82 
83 struct viommu_request {
84 	struct list_head		list;
85 	void				*writeback;
86 	unsigned int			write_offset;
87 	unsigned int			len;
88 	char				buf[];
89 };
90 
91 #define VIOMMU_FAULT_RESV_MASK		0xffffff00
92 
93 struct viommu_event {
94 	union {
95 		u32			head;
96 		struct virtio_iommu_fault fault;
97 	};
98 };
99 
100 #define to_viommu_domain(domain)	\
101 	container_of(domain, struct viommu_domain, domain)
102 
103 static int viommu_get_req_errno(void *buf, size_t len)
104 {
105 	struct virtio_iommu_req_tail *tail = buf + len - sizeof(*tail);
106 
107 	switch (tail->status) {
108 	case VIRTIO_IOMMU_S_OK:
109 		return 0;
110 	case VIRTIO_IOMMU_S_UNSUPP:
111 		return -ENOSYS;
112 	case VIRTIO_IOMMU_S_INVAL:
113 		return -EINVAL;
114 	case VIRTIO_IOMMU_S_RANGE:
115 		return -ERANGE;
116 	case VIRTIO_IOMMU_S_NOENT:
117 		return -ENOENT;
118 	case VIRTIO_IOMMU_S_FAULT:
119 		return -EFAULT;
120 	case VIRTIO_IOMMU_S_NOMEM:
121 		return -ENOMEM;
122 	case VIRTIO_IOMMU_S_IOERR:
123 	case VIRTIO_IOMMU_S_DEVERR:
124 	default:
125 		return -EIO;
126 	}
127 }
128 
129 static void viommu_set_req_status(void *buf, size_t len, int status)
130 {
131 	struct virtio_iommu_req_tail *tail = buf + len - sizeof(*tail);
132 
133 	tail->status = status;
134 }
135 
136 static off_t viommu_get_write_desc_offset(struct viommu_dev *viommu,
137 					  struct virtio_iommu_req_head *req,
138 					  size_t len)
139 {
140 	size_t tail_size = sizeof(struct virtio_iommu_req_tail);
141 
142 	if (req->type == VIRTIO_IOMMU_T_PROBE)
143 		return len - viommu->probe_size - tail_size;
144 
145 	return len - tail_size;
146 }
147 
148 /*
149  * __viommu_sync_req - Complete all in-flight requests
150  *
151  * Wait for all added requests to complete. When this function returns, all
152  * requests that were in-flight at the time of the call have completed.
153  */
154 static int __viommu_sync_req(struct viommu_dev *viommu)
155 {
156 	unsigned int len;
157 	size_t write_len;
158 	struct viommu_request *req;
159 	struct virtqueue *vq = viommu->vqs[VIOMMU_REQUEST_VQ];
160 
161 	assert_spin_locked(&viommu->request_lock);
162 
163 	virtqueue_kick(vq);
164 
165 	while (!list_empty(&viommu->requests)) {
166 		len = 0;
167 		req = virtqueue_get_buf(vq, &len);
168 		if (!req)
169 			continue;
170 
171 		if (!len)
172 			viommu_set_req_status(req->buf, req->len,
173 					      VIRTIO_IOMMU_S_IOERR);
174 
175 		write_len = req->len - req->write_offset;
176 		if (req->writeback && len == write_len)
177 			memcpy(req->writeback, req->buf + req->write_offset,
178 			       write_len);
179 
180 		list_del(&req->list);
181 		kfree(req);
182 	}
183 
184 	return 0;
185 }
186 
187 static int viommu_sync_req(struct viommu_dev *viommu)
188 {
189 	int ret;
190 	unsigned long flags;
191 
192 	spin_lock_irqsave(&viommu->request_lock, flags);
193 	ret = __viommu_sync_req(viommu);
194 	if (ret)
195 		dev_dbg(viommu->dev, "could not sync requests (%d)\n", ret);
196 	spin_unlock_irqrestore(&viommu->request_lock, flags);
197 
198 	return ret;
199 }
200 
201 /*
202  * __viommu_add_request - Add one request to the queue
203  * @buf: pointer to the request buffer
204  * @len: length of the request buffer
205  * @writeback: copy data back to the buffer when the request completes.
206  *
207  * Add a request to the queue. Only synchronize the queue if it's already full.
208  * Otherwise don't kick the queue nor wait for requests to complete.
209  *
210  * When @writeback is true, data written by the device, including the request
211  * status, is copied into @buf after the request completes. This is unsafe if
212  * the caller allocates @buf on stack and drops the lock between add_req() and
213  * sync_req().
214  *
215  * Return 0 if the request was successfully added to the queue.
216  */
217 static int __viommu_add_req(struct viommu_dev *viommu, void *buf, size_t len,
218 			    bool writeback)
219 {
220 	int ret;
221 	off_t write_offset;
222 	struct viommu_request *req;
223 	struct scatterlist top_sg, bottom_sg;
224 	struct scatterlist *sg[2] = { &top_sg, &bottom_sg };
225 	struct virtqueue *vq = viommu->vqs[VIOMMU_REQUEST_VQ];
226 
227 	assert_spin_locked(&viommu->request_lock);
228 
229 	write_offset = viommu_get_write_desc_offset(viommu, buf, len);
230 	if (write_offset <= 0)
231 		return -EINVAL;
232 
233 	req = kzalloc(sizeof(*req) + len, GFP_ATOMIC);
234 	if (!req)
235 		return -ENOMEM;
236 
237 	req->len = len;
238 	if (writeback) {
239 		req->writeback = buf + write_offset;
240 		req->write_offset = write_offset;
241 	}
242 	memcpy(&req->buf, buf, write_offset);
243 
244 	sg_init_one(&top_sg, req->buf, write_offset);
245 	sg_init_one(&bottom_sg, req->buf + write_offset, len - write_offset);
246 
247 	ret = virtqueue_add_sgs(vq, sg, 1, 1, req, GFP_ATOMIC);
248 	if (ret == -ENOSPC) {
249 		/* If the queue is full, sync and retry */
250 		if (!__viommu_sync_req(viommu))
251 			ret = virtqueue_add_sgs(vq, sg, 1, 1, req, GFP_ATOMIC);
252 	}
253 	if (ret)
254 		goto err_free;
255 
256 	list_add_tail(&req->list, &viommu->requests);
257 	return 0;
258 
259 err_free:
260 	kfree(req);
261 	return ret;
262 }
263 
264 static int viommu_add_req(struct viommu_dev *viommu, void *buf, size_t len)
265 {
266 	int ret;
267 	unsigned long flags;
268 
269 	spin_lock_irqsave(&viommu->request_lock, flags);
270 	ret = __viommu_add_req(viommu, buf, len, false);
271 	if (ret)
272 		dev_dbg(viommu->dev, "could not add request: %d\n", ret);
273 	spin_unlock_irqrestore(&viommu->request_lock, flags);
274 
275 	return ret;
276 }
277 
278 /*
279  * Send a request and wait for it to complete. Return the request status (as an
280  * errno)
281  */
282 static int viommu_send_req_sync(struct viommu_dev *viommu, void *buf,
283 				size_t len)
284 {
285 	int ret;
286 	unsigned long flags;
287 
288 	spin_lock_irqsave(&viommu->request_lock, flags);
289 
290 	ret = __viommu_add_req(viommu, buf, len, true);
291 	if (ret) {
292 		dev_dbg(viommu->dev, "could not add request (%d)\n", ret);
293 		goto out_unlock;
294 	}
295 
296 	ret = __viommu_sync_req(viommu);
297 	if (ret) {
298 		dev_dbg(viommu->dev, "could not sync requests (%d)\n", ret);
299 		/* Fall-through (get the actual request status) */
300 	}
301 
302 	ret = viommu_get_req_errno(buf, len);
303 out_unlock:
304 	spin_unlock_irqrestore(&viommu->request_lock, flags);
305 	return ret;
306 }
307 
308 /*
309  * viommu_add_mapping - add a mapping to the internal tree
310  *
311  * On success, return the new mapping. Otherwise return NULL.
312  */
313 static int viommu_add_mapping(struct viommu_domain *vdomain, u64 iova, u64 end,
314 			      phys_addr_t paddr, u32 flags)
315 {
316 	unsigned long irqflags;
317 	struct viommu_mapping *mapping;
318 
319 	mapping = kzalloc(sizeof(*mapping), GFP_ATOMIC);
320 	if (!mapping)
321 		return -ENOMEM;
322 
323 	mapping->paddr		= paddr;
324 	mapping->iova.start	= iova;
325 	mapping->iova.last	= end;
326 	mapping->flags		= flags;
327 
328 	spin_lock_irqsave(&vdomain->mappings_lock, irqflags);
329 	interval_tree_insert(&mapping->iova, &vdomain->mappings);
330 	spin_unlock_irqrestore(&vdomain->mappings_lock, irqflags);
331 
332 	return 0;
333 }
334 
335 /*
336  * viommu_del_mappings - remove mappings from the internal tree
337  *
338  * @vdomain: the domain
339  * @iova: start of the range
340  * @end: end of the range
341  *
342  * On success, returns the number of unmapped bytes
343  */
344 static size_t viommu_del_mappings(struct viommu_domain *vdomain,
345 				  u64 iova, u64 end)
346 {
347 	size_t unmapped = 0;
348 	unsigned long flags;
349 	struct viommu_mapping *mapping = NULL;
350 	struct interval_tree_node *node, *next;
351 
352 	spin_lock_irqsave(&vdomain->mappings_lock, flags);
353 	next = interval_tree_iter_first(&vdomain->mappings, iova, end);
354 	while (next) {
355 		node = next;
356 		mapping = container_of(node, struct viommu_mapping, iova);
357 		next = interval_tree_iter_next(node, iova, end);
358 
359 		/* Trying to split a mapping? */
360 		if (mapping->iova.start < iova)
361 			break;
362 
363 		/*
364 		 * Virtio-iommu doesn't allow UNMAP to split a mapping created
365 		 * with a single MAP request, so remove the full mapping.
366 		 */
367 		unmapped += mapping->iova.last - mapping->iova.start + 1;
368 
369 		interval_tree_remove(node, &vdomain->mappings);
370 		kfree(mapping);
371 	}
372 	spin_unlock_irqrestore(&vdomain->mappings_lock, flags);
373 
374 	return unmapped;
375 }
376 
377 /*
378  * Fill the domain with identity mappings, skipping the device's reserved
379  * regions.
380  */
381 static int viommu_domain_map_identity(struct viommu_endpoint *vdev,
382 				      struct viommu_domain *vdomain)
383 {
384 	int ret;
385 	struct iommu_resv_region *resv;
386 	u64 iova = vdomain->domain.geometry.aperture_start;
387 	u64 limit = vdomain->domain.geometry.aperture_end;
388 	u32 flags = VIRTIO_IOMMU_MAP_F_READ | VIRTIO_IOMMU_MAP_F_WRITE;
389 	unsigned long granule = 1UL << __ffs(vdomain->domain.pgsize_bitmap);
390 
391 	iova = ALIGN(iova, granule);
392 	limit = ALIGN_DOWN(limit + 1, granule) - 1;
393 
394 	list_for_each_entry(resv, &vdev->resv_regions, list) {
395 		u64 resv_start = ALIGN_DOWN(resv->start, granule);
396 		u64 resv_end = ALIGN(resv->start + resv->length, granule) - 1;
397 
398 		if (resv_end < iova || resv_start > limit)
399 			/* No overlap */
400 			continue;
401 
402 		if (resv_start > iova) {
403 			ret = viommu_add_mapping(vdomain, iova, resv_start - 1,
404 						 (phys_addr_t)iova, flags);
405 			if (ret)
406 				goto err_unmap;
407 		}
408 
409 		if (resv_end >= limit)
410 			return 0;
411 
412 		iova = resv_end + 1;
413 	}
414 
415 	ret = viommu_add_mapping(vdomain, iova, limit, (phys_addr_t)iova,
416 				 flags);
417 	if (ret)
418 		goto err_unmap;
419 	return 0;
420 
421 err_unmap:
422 	viommu_del_mappings(vdomain, 0, iova);
423 	return ret;
424 }
425 
426 /*
427  * viommu_replay_mappings - re-send MAP requests
428  *
429  * When reattaching a domain that was previously detached from all endpoints,
430  * mappings were deleted from the device. Re-create the mappings available in
431  * the internal tree.
432  */
433 static int viommu_replay_mappings(struct viommu_domain *vdomain)
434 {
435 	int ret = 0;
436 	unsigned long flags;
437 	struct viommu_mapping *mapping;
438 	struct interval_tree_node *node;
439 	struct virtio_iommu_req_map map;
440 
441 	spin_lock_irqsave(&vdomain->mappings_lock, flags);
442 	node = interval_tree_iter_first(&vdomain->mappings, 0, -1UL);
443 	while (node) {
444 		mapping = container_of(node, struct viommu_mapping, iova);
445 		map = (struct virtio_iommu_req_map) {
446 			.head.type	= VIRTIO_IOMMU_T_MAP,
447 			.domain		= cpu_to_le32(vdomain->id),
448 			.virt_start	= cpu_to_le64(mapping->iova.start),
449 			.virt_end	= cpu_to_le64(mapping->iova.last),
450 			.phys_start	= cpu_to_le64(mapping->paddr),
451 			.flags		= cpu_to_le32(mapping->flags),
452 		};
453 
454 		ret = viommu_send_req_sync(vdomain->viommu, &map, sizeof(map));
455 		if (ret)
456 			break;
457 
458 		node = interval_tree_iter_next(node, 0, -1UL);
459 	}
460 	spin_unlock_irqrestore(&vdomain->mappings_lock, flags);
461 
462 	return ret;
463 }
464 
465 static int viommu_add_resv_mem(struct viommu_endpoint *vdev,
466 			       struct virtio_iommu_probe_resv_mem *mem,
467 			       size_t len)
468 {
469 	size_t size;
470 	u64 start64, end64;
471 	phys_addr_t start, end;
472 	struct iommu_resv_region *region = NULL, *next;
473 	unsigned long prot = IOMMU_WRITE | IOMMU_NOEXEC | IOMMU_MMIO;
474 
475 	start = start64 = le64_to_cpu(mem->start);
476 	end = end64 = le64_to_cpu(mem->end);
477 	size = end64 - start64 + 1;
478 
479 	/* Catch any overflow, including the unlikely end64 - start64 + 1 = 0 */
480 	if (start != start64 || end != end64 || size < end64 - start64)
481 		return -EOVERFLOW;
482 
483 	if (len < sizeof(*mem))
484 		return -EINVAL;
485 
486 	switch (mem->subtype) {
487 	default:
488 		dev_warn(vdev->dev, "unknown resv mem subtype 0x%x\n",
489 			 mem->subtype);
490 		fallthrough;
491 	case VIRTIO_IOMMU_RESV_MEM_T_RESERVED:
492 		region = iommu_alloc_resv_region(start, size, 0,
493 						 IOMMU_RESV_RESERVED);
494 		break;
495 	case VIRTIO_IOMMU_RESV_MEM_T_MSI:
496 		region = iommu_alloc_resv_region(start, size, prot,
497 						 IOMMU_RESV_MSI);
498 		break;
499 	}
500 	if (!region)
501 		return -ENOMEM;
502 
503 	/* Keep the list sorted */
504 	list_for_each_entry(next, &vdev->resv_regions, list) {
505 		if (next->start > region->start)
506 			break;
507 	}
508 	list_add_tail(&region->list, &next->list);
509 	return 0;
510 }
511 
512 static int viommu_probe_endpoint(struct viommu_dev *viommu, struct device *dev)
513 {
514 	int ret;
515 	u16 type, len;
516 	size_t cur = 0;
517 	size_t probe_len;
518 	struct virtio_iommu_req_probe *probe;
519 	struct virtio_iommu_probe_property *prop;
520 	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
521 	struct viommu_endpoint *vdev = dev_iommu_priv_get(dev);
522 
523 	if (!fwspec->num_ids)
524 		return -EINVAL;
525 
526 	probe_len = sizeof(*probe) + viommu->probe_size +
527 		    sizeof(struct virtio_iommu_req_tail);
528 	probe = kzalloc(probe_len, GFP_KERNEL);
529 	if (!probe)
530 		return -ENOMEM;
531 
532 	probe->head.type = VIRTIO_IOMMU_T_PROBE;
533 	/*
534 	 * For now, assume that properties of an endpoint that outputs multiple
535 	 * IDs are consistent. Only probe the first one.
536 	 */
537 	probe->endpoint = cpu_to_le32(fwspec->ids[0]);
538 
539 	ret = viommu_send_req_sync(viommu, probe, probe_len);
540 	if (ret)
541 		goto out_free;
542 
543 	prop = (void *)probe->properties;
544 	type = le16_to_cpu(prop->type) & VIRTIO_IOMMU_PROBE_T_MASK;
545 
546 	while (type != VIRTIO_IOMMU_PROBE_T_NONE &&
547 	       cur < viommu->probe_size) {
548 		len = le16_to_cpu(prop->length) + sizeof(*prop);
549 
550 		switch (type) {
551 		case VIRTIO_IOMMU_PROBE_T_RESV_MEM:
552 			ret = viommu_add_resv_mem(vdev, (void *)prop, len);
553 			break;
554 		default:
555 			dev_err(dev, "unknown viommu prop 0x%x\n", type);
556 		}
557 
558 		if (ret)
559 			dev_err(dev, "failed to parse viommu prop 0x%x\n", type);
560 
561 		cur += len;
562 		if (cur >= viommu->probe_size)
563 			break;
564 
565 		prop = (void *)probe->properties + cur;
566 		type = le16_to_cpu(prop->type) & VIRTIO_IOMMU_PROBE_T_MASK;
567 	}
568 
569 out_free:
570 	kfree(probe);
571 	return ret;
572 }
573 
574 static int viommu_fault_handler(struct viommu_dev *viommu,
575 				struct virtio_iommu_fault *fault)
576 {
577 	char *reason_str;
578 
579 	u8 reason	= fault->reason;
580 	u32 flags	= le32_to_cpu(fault->flags);
581 	u32 endpoint	= le32_to_cpu(fault->endpoint);
582 	u64 address	= le64_to_cpu(fault->address);
583 
584 	switch (reason) {
585 	case VIRTIO_IOMMU_FAULT_R_DOMAIN:
586 		reason_str = "domain";
587 		break;
588 	case VIRTIO_IOMMU_FAULT_R_MAPPING:
589 		reason_str = "page";
590 		break;
591 	case VIRTIO_IOMMU_FAULT_R_UNKNOWN:
592 	default:
593 		reason_str = "unknown";
594 		break;
595 	}
596 
597 	/* TODO: find EP by ID and report_iommu_fault */
598 	if (flags & VIRTIO_IOMMU_FAULT_F_ADDRESS)
599 		dev_err_ratelimited(viommu->dev, "%s fault from EP %u at %#llx [%s%s%s]\n",
600 				    reason_str, endpoint, address,
601 				    flags & VIRTIO_IOMMU_FAULT_F_READ ? "R" : "",
602 				    flags & VIRTIO_IOMMU_FAULT_F_WRITE ? "W" : "",
603 				    flags & VIRTIO_IOMMU_FAULT_F_EXEC ? "X" : "");
604 	else
605 		dev_err_ratelimited(viommu->dev, "%s fault from EP %u\n",
606 				    reason_str, endpoint);
607 	return 0;
608 }
609 
610 static void viommu_event_handler(struct virtqueue *vq)
611 {
612 	int ret;
613 	unsigned int len;
614 	struct scatterlist sg[1];
615 	struct viommu_event *evt;
616 	struct viommu_dev *viommu = vq->vdev->priv;
617 
618 	while ((evt = virtqueue_get_buf(vq, &len)) != NULL) {
619 		if (len > sizeof(*evt)) {
620 			dev_err(viommu->dev,
621 				"invalid event buffer (len %u != %zu)\n",
622 				len, sizeof(*evt));
623 		} else if (!(evt->head & VIOMMU_FAULT_RESV_MASK)) {
624 			viommu_fault_handler(viommu, &evt->fault);
625 		}
626 
627 		sg_init_one(sg, evt, sizeof(*evt));
628 		ret = virtqueue_add_inbuf(vq, sg, 1, evt, GFP_ATOMIC);
629 		if (ret)
630 			dev_err(viommu->dev, "could not add event buffer\n");
631 	}
632 
633 	virtqueue_kick(vq);
634 }
635 
636 /* IOMMU API */
637 
638 static struct iommu_domain *viommu_domain_alloc(unsigned type)
639 {
640 	struct viommu_domain *vdomain;
641 
642 	if (type != IOMMU_DOMAIN_UNMANAGED &&
643 	    type != IOMMU_DOMAIN_DMA &&
644 	    type != IOMMU_DOMAIN_IDENTITY)
645 		return NULL;
646 
647 	vdomain = kzalloc(sizeof(*vdomain), GFP_KERNEL);
648 	if (!vdomain)
649 		return NULL;
650 
651 	mutex_init(&vdomain->mutex);
652 	spin_lock_init(&vdomain->mappings_lock);
653 	vdomain->mappings = RB_ROOT_CACHED;
654 
655 	return &vdomain->domain;
656 }
657 
658 static int viommu_domain_finalise(struct viommu_endpoint *vdev,
659 				  struct iommu_domain *domain)
660 {
661 	int ret;
662 	unsigned long viommu_page_size;
663 	struct viommu_dev *viommu = vdev->viommu;
664 	struct viommu_domain *vdomain = to_viommu_domain(domain);
665 
666 	viommu_page_size = 1UL << __ffs(viommu->pgsize_bitmap);
667 	if (viommu_page_size > PAGE_SIZE) {
668 		dev_err(vdev->dev,
669 			"granule 0x%lx larger than system page size 0x%lx\n",
670 			viommu_page_size, PAGE_SIZE);
671 		return -EINVAL;
672 	}
673 
674 	ret = ida_alloc_range(&viommu->domain_ids, viommu->first_domain,
675 			      viommu->last_domain, GFP_KERNEL);
676 	if (ret < 0)
677 		return ret;
678 
679 	vdomain->id		= (unsigned int)ret;
680 
681 	domain->pgsize_bitmap	= viommu->pgsize_bitmap;
682 	domain->geometry	= viommu->geometry;
683 
684 	vdomain->map_flags	= viommu->map_flags;
685 	vdomain->viommu		= viommu;
686 
687 	if (domain->type == IOMMU_DOMAIN_IDENTITY) {
688 		if (virtio_has_feature(viommu->vdev,
689 				       VIRTIO_IOMMU_F_BYPASS_CONFIG)) {
690 			vdomain->bypass = true;
691 			return 0;
692 		}
693 
694 		ret = viommu_domain_map_identity(vdev, vdomain);
695 		if (ret) {
696 			ida_free(&viommu->domain_ids, vdomain->id);
697 			vdomain->viommu = NULL;
698 			return -EOPNOTSUPP;
699 		}
700 	}
701 
702 	return 0;
703 }
704 
705 static void viommu_domain_free(struct iommu_domain *domain)
706 {
707 	struct viommu_domain *vdomain = to_viommu_domain(domain);
708 
709 	/* Free all remaining mappings */
710 	viommu_del_mappings(vdomain, 0, ULLONG_MAX);
711 
712 	if (vdomain->viommu)
713 		ida_free(&vdomain->viommu->domain_ids, vdomain->id);
714 
715 	kfree(vdomain);
716 }
717 
718 static int viommu_attach_dev(struct iommu_domain *domain, struct device *dev)
719 {
720 	int i;
721 	int ret = 0;
722 	struct virtio_iommu_req_attach req;
723 	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
724 	struct viommu_endpoint *vdev = dev_iommu_priv_get(dev);
725 	struct viommu_domain *vdomain = to_viommu_domain(domain);
726 
727 	mutex_lock(&vdomain->mutex);
728 	if (!vdomain->viommu) {
729 		/*
730 		 * Properly initialize the domain now that we know which viommu
731 		 * owns it.
732 		 */
733 		ret = viommu_domain_finalise(vdev, domain);
734 	} else if (vdomain->viommu != vdev->viommu) {
735 		dev_err(dev, "cannot attach to foreign vIOMMU\n");
736 		ret = -EXDEV;
737 	}
738 	mutex_unlock(&vdomain->mutex);
739 
740 	if (ret)
741 		return ret;
742 
743 	/*
744 	 * In the virtio-iommu device, when attaching the endpoint to a new
745 	 * domain, it is detached from the old one and, if as a result the
746 	 * old domain isn't attached to any endpoint, all mappings are removed
747 	 * from the old domain and it is freed.
748 	 *
749 	 * In the driver the old domain still exists, and its mappings will be
750 	 * recreated if it gets reattached to an endpoint. Otherwise it will be
751 	 * freed explicitly.
752 	 *
753 	 * vdev->vdomain is protected by group->mutex
754 	 */
755 	if (vdev->vdomain)
756 		vdev->vdomain->nr_endpoints--;
757 
758 	req = (struct virtio_iommu_req_attach) {
759 		.head.type	= VIRTIO_IOMMU_T_ATTACH,
760 		.domain		= cpu_to_le32(vdomain->id),
761 	};
762 
763 	if (vdomain->bypass)
764 		req.flags |= cpu_to_le32(VIRTIO_IOMMU_ATTACH_F_BYPASS);
765 
766 	for (i = 0; i < fwspec->num_ids; i++) {
767 		req.endpoint = cpu_to_le32(fwspec->ids[i]);
768 
769 		ret = viommu_send_req_sync(vdomain->viommu, &req, sizeof(req));
770 		if (ret)
771 			return ret;
772 	}
773 
774 	if (!vdomain->nr_endpoints) {
775 		/*
776 		 * This endpoint is the first to be attached to the domain.
777 		 * Replay existing mappings (e.g. SW MSI).
778 		 */
779 		ret = viommu_replay_mappings(vdomain);
780 		if (ret)
781 			return ret;
782 	}
783 
784 	vdomain->nr_endpoints++;
785 	vdev->vdomain = vdomain;
786 
787 	return 0;
788 }
789 
790 static int viommu_map_pages(struct iommu_domain *domain, unsigned long iova,
791 			    phys_addr_t paddr, size_t pgsize, size_t pgcount,
792 			    int prot, gfp_t gfp, size_t *mapped)
793 {
794 	int ret;
795 	u32 flags;
796 	size_t size = pgsize * pgcount;
797 	u64 end = iova + size - 1;
798 	struct virtio_iommu_req_map map;
799 	struct viommu_domain *vdomain = to_viommu_domain(domain);
800 
801 	flags = (prot & IOMMU_READ ? VIRTIO_IOMMU_MAP_F_READ : 0) |
802 		(prot & IOMMU_WRITE ? VIRTIO_IOMMU_MAP_F_WRITE : 0) |
803 		(prot & IOMMU_MMIO ? VIRTIO_IOMMU_MAP_F_MMIO : 0);
804 
805 	if (flags & ~vdomain->map_flags)
806 		return -EINVAL;
807 
808 	ret = viommu_add_mapping(vdomain, iova, end, paddr, flags);
809 	if (ret)
810 		return ret;
811 
812 	map = (struct virtio_iommu_req_map) {
813 		.head.type	= VIRTIO_IOMMU_T_MAP,
814 		.domain		= cpu_to_le32(vdomain->id),
815 		.virt_start	= cpu_to_le64(iova),
816 		.phys_start	= cpu_to_le64(paddr),
817 		.virt_end	= cpu_to_le64(end),
818 		.flags		= cpu_to_le32(flags),
819 	};
820 
821 	if (!vdomain->nr_endpoints)
822 		return 0;
823 
824 	ret = viommu_send_req_sync(vdomain->viommu, &map, sizeof(map));
825 	if (ret)
826 		viommu_del_mappings(vdomain, iova, end);
827 	else if (mapped)
828 		*mapped = size;
829 
830 	return ret;
831 }
832 
833 static size_t viommu_unmap_pages(struct iommu_domain *domain, unsigned long iova,
834 				 size_t pgsize, size_t pgcount,
835 				 struct iommu_iotlb_gather *gather)
836 {
837 	int ret = 0;
838 	size_t unmapped;
839 	struct virtio_iommu_req_unmap unmap;
840 	struct viommu_domain *vdomain = to_viommu_domain(domain);
841 	size_t size = pgsize * pgcount;
842 
843 	unmapped = viommu_del_mappings(vdomain, iova, iova + size - 1);
844 	if (unmapped < size)
845 		return 0;
846 
847 	/* Device already removed all mappings after detach. */
848 	if (!vdomain->nr_endpoints)
849 		return unmapped;
850 
851 	unmap = (struct virtio_iommu_req_unmap) {
852 		.head.type	= VIRTIO_IOMMU_T_UNMAP,
853 		.domain		= cpu_to_le32(vdomain->id),
854 		.virt_start	= cpu_to_le64(iova),
855 		.virt_end	= cpu_to_le64(iova + unmapped - 1),
856 	};
857 
858 	ret = viommu_add_req(vdomain->viommu, &unmap, sizeof(unmap));
859 	return ret ? 0 : unmapped;
860 }
861 
862 static phys_addr_t viommu_iova_to_phys(struct iommu_domain *domain,
863 				       dma_addr_t iova)
864 {
865 	u64 paddr = 0;
866 	unsigned long flags;
867 	struct viommu_mapping *mapping;
868 	struct interval_tree_node *node;
869 	struct viommu_domain *vdomain = to_viommu_domain(domain);
870 
871 	spin_lock_irqsave(&vdomain->mappings_lock, flags);
872 	node = interval_tree_iter_first(&vdomain->mappings, iova, iova);
873 	if (node) {
874 		mapping = container_of(node, struct viommu_mapping, iova);
875 		paddr = mapping->paddr + (iova - mapping->iova.start);
876 	}
877 	spin_unlock_irqrestore(&vdomain->mappings_lock, flags);
878 
879 	return paddr;
880 }
881 
882 static void viommu_iotlb_sync(struct iommu_domain *domain,
883 			      struct iommu_iotlb_gather *gather)
884 {
885 	struct viommu_domain *vdomain = to_viommu_domain(domain);
886 
887 	viommu_sync_req(vdomain->viommu);
888 }
889 
890 static void viommu_get_resv_regions(struct device *dev, struct list_head *head)
891 {
892 	struct iommu_resv_region *entry, *new_entry, *msi = NULL;
893 	struct viommu_endpoint *vdev = dev_iommu_priv_get(dev);
894 	int prot = IOMMU_WRITE | IOMMU_NOEXEC | IOMMU_MMIO;
895 
896 	list_for_each_entry(entry, &vdev->resv_regions, list) {
897 		if (entry->type == IOMMU_RESV_MSI)
898 			msi = entry;
899 
900 		new_entry = kmemdup(entry, sizeof(*entry), GFP_KERNEL);
901 		if (!new_entry)
902 			return;
903 		list_add_tail(&new_entry->list, head);
904 	}
905 
906 	/*
907 	 * If the device didn't register any bypass MSI window, add a
908 	 * software-mapped region.
909 	 */
910 	if (!msi) {
911 		msi = iommu_alloc_resv_region(MSI_IOVA_BASE, MSI_IOVA_LENGTH,
912 					      prot, IOMMU_RESV_SW_MSI);
913 		if (!msi)
914 			return;
915 
916 		list_add_tail(&msi->list, head);
917 	}
918 
919 	iommu_dma_get_resv_regions(dev, head);
920 }
921 
922 static struct iommu_ops viommu_ops;
923 static struct virtio_driver virtio_iommu_drv;
924 
925 static int viommu_match_node(struct device *dev, const void *data)
926 {
927 	return device_match_fwnode(dev->parent, data);
928 }
929 
930 static struct viommu_dev *viommu_get_by_fwnode(struct fwnode_handle *fwnode)
931 {
932 	struct device *dev = driver_find_device(&virtio_iommu_drv.driver, NULL,
933 						fwnode, viommu_match_node);
934 	put_device(dev);
935 
936 	return dev ? dev_to_virtio(dev)->priv : NULL;
937 }
938 
939 static struct iommu_device *viommu_probe_device(struct device *dev)
940 {
941 	int ret;
942 	struct viommu_endpoint *vdev;
943 	struct viommu_dev *viommu = NULL;
944 	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
945 
946 	if (!fwspec || fwspec->ops != &viommu_ops)
947 		return ERR_PTR(-ENODEV);
948 
949 	viommu = viommu_get_by_fwnode(fwspec->iommu_fwnode);
950 	if (!viommu)
951 		return ERR_PTR(-ENODEV);
952 
953 	vdev = kzalloc(sizeof(*vdev), GFP_KERNEL);
954 	if (!vdev)
955 		return ERR_PTR(-ENOMEM);
956 
957 	vdev->dev = dev;
958 	vdev->viommu = viommu;
959 	INIT_LIST_HEAD(&vdev->resv_regions);
960 	dev_iommu_priv_set(dev, vdev);
961 
962 	if (viommu->probe_size) {
963 		/* Get additional information for this endpoint */
964 		ret = viommu_probe_endpoint(viommu, dev);
965 		if (ret)
966 			goto err_free_dev;
967 	}
968 
969 	return &viommu->iommu;
970 
971 err_free_dev:
972 	iommu_put_resv_regions(dev, &vdev->resv_regions);
973 	kfree(vdev);
974 
975 	return ERR_PTR(ret);
976 }
977 
978 static void viommu_probe_finalize(struct device *dev)
979 {
980 #ifndef CONFIG_ARCH_HAS_SETUP_DMA_OPS
981 	/* First clear the DMA ops in case we're switching from a DMA domain */
982 	set_dma_ops(dev, NULL);
983 	iommu_setup_dma_ops(dev, 0, U64_MAX);
984 #endif
985 }
986 
987 static void viommu_release_device(struct device *dev)
988 {
989 	struct viommu_endpoint *vdev = dev_iommu_priv_get(dev);
990 
991 	iommu_put_resv_regions(dev, &vdev->resv_regions);
992 	kfree(vdev);
993 }
994 
995 static struct iommu_group *viommu_device_group(struct device *dev)
996 {
997 	if (dev_is_pci(dev))
998 		return pci_device_group(dev);
999 	else
1000 		return generic_device_group(dev);
1001 }
1002 
1003 static int viommu_of_xlate(struct device *dev, struct of_phandle_args *args)
1004 {
1005 	return iommu_fwspec_add_ids(dev, args->args, 1);
1006 }
1007 
1008 static bool viommu_capable(struct device *dev, enum iommu_cap cap)
1009 {
1010 	switch (cap) {
1011 	case IOMMU_CAP_CACHE_COHERENCY:
1012 		return true;
1013 	default:
1014 		return false;
1015 	}
1016 }
1017 
1018 static struct iommu_ops viommu_ops = {
1019 	.capable		= viommu_capable,
1020 	.domain_alloc		= viommu_domain_alloc,
1021 	.probe_device		= viommu_probe_device,
1022 	.probe_finalize		= viommu_probe_finalize,
1023 	.release_device		= viommu_release_device,
1024 	.device_group		= viommu_device_group,
1025 	.get_resv_regions	= viommu_get_resv_regions,
1026 	.of_xlate		= viommu_of_xlate,
1027 	.owner			= THIS_MODULE,
1028 	.default_domain_ops = &(const struct iommu_domain_ops) {
1029 		.attach_dev		= viommu_attach_dev,
1030 		.map_pages		= viommu_map_pages,
1031 		.unmap_pages		= viommu_unmap_pages,
1032 		.iova_to_phys		= viommu_iova_to_phys,
1033 		.iotlb_sync		= viommu_iotlb_sync,
1034 		.free			= viommu_domain_free,
1035 	}
1036 };
1037 
1038 static int viommu_init_vqs(struct viommu_dev *viommu)
1039 {
1040 	struct virtio_device *vdev = dev_to_virtio(viommu->dev);
1041 	const char *names[] = { "request", "event" };
1042 	vq_callback_t *callbacks[] = {
1043 		NULL, /* No async requests */
1044 		viommu_event_handler,
1045 	};
1046 
1047 	return virtio_find_vqs(vdev, VIOMMU_NR_VQS, viommu->vqs, callbacks,
1048 			       names, NULL);
1049 }
1050 
1051 static int viommu_fill_evtq(struct viommu_dev *viommu)
1052 {
1053 	int i, ret;
1054 	struct scatterlist sg[1];
1055 	struct viommu_event *evts;
1056 	struct virtqueue *vq = viommu->vqs[VIOMMU_EVENT_VQ];
1057 	size_t nr_evts = vq->num_free;
1058 
1059 	viommu->evts = evts = devm_kmalloc_array(viommu->dev, nr_evts,
1060 						 sizeof(*evts), GFP_KERNEL);
1061 	if (!evts)
1062 		return -ENOMEM;
1063 
1064 	for (i = 0; i < nr_evts; i++) {
1065 		sg_init_one(sg, &evts[i], sizeof(*evts));
1066 		ret = virtqueue_add_inbuf(vq, sg, 1, &evts[i], GFP_KERNEL);
1067 		if (ret)
1068 			return ret;
1069 	}
1070 
1071 	return 0;
1072 }
1073 
1074 static int viommu_probe(struct virtio_device *vdev)
1075 {
1076 	struct device *parent_dev = vdev->dev.parent;
1077 	struct viommu_dev *viommu = NULL;
1078 	struct device *dev = &vdev->dev;
1079 	u64 input_start = 0;
1080 	u64 input_end = -1UL;
1081 	int ret;
1082 
1083 	if (!virtio_has_feature(vdev, VIRTIO_F_VERSION_1) ||
1084 	    !virtio_has_feature(vdev, VIRTIO_IOMMU_F_MAP_UNMAP))
1085 		return -ENODEV;
1086 
1087 	viommu = devm_kzalloc(dev, sizeof(*viommu), GFP_KERNEL);
1088 	if (!viommu)
1089 		return -ENOMEM;
1090 
1091 	spin_lock_init(&viommu->request_lock);
1092 	ida_init(&viommu->domain_ids);
1093 	viommu->dev = dev;
1094 	viommu->vdev = vdev;
1095 	INIT_LIST_HEAD(&viommu->requests);
1096 
1097 	ret = viommu_init_vqs(viommu);
1098 	if (ret)
1099 		return ret;
1100 
1101 	virtio_cread_le(vdev, struct virtio_iommu_config, page_size_mask,
1102 			&viommu->pgsize_bitmap);
1103 
1104 	if (!viommu->pgsize_bitmap) {
1105 		ret = -EINVAL;
1106 		goto err_free_vqs;
1107 	}
1108 
1109 	viommu->map_flags = VIRTIO_IOMMU_MAP_F_READ | VIRTIO_IOMMU_MAP_F_WRITE;
1110 	viommu->last_domain = ~0U;
1111 
1112 	/* Optional features */
1113 	virtio_cread_le_feature(vdev, VIRTIO_IOMMU_F_INPUT_RANGE,
1114 				struct virtio_iommu_config, input_range.start,
1115 				&input_start);
1116 
1117 	virtio_cread_le_feature(vdev, VIRTIO_IOMMU_F_INPUT_RANGE,
1118 				struct virtio_iommu_config, input_range.end,
1119 				&input_end);
1120 
1121 	virtio_cread_le_feature(vdev, VIRTIO_IOMMU_F_DOMAIN_RANGE,
1122 				struct virtio_iommu_config, domain_range.start,
1123 				&viommu->first_domain);
1124 
1125 	virtio_cread_le_feature(vdev, VIRTIO_IOMMU_F_DOMAIN_RANGE,
1126 				struct virtio_iommu_config, domain_range.end,
1127 				&viommu->last_domain);
1128 
1129 	virtio_cread_le_feature(vdev, VIRTIO_IOMMU_F_PROBE,
1130 				struct virtio_iommu_config, probe_size,
1131 				&viommu->probe_size);
1132 
1133 	viommu->geometry = (struct iommu_domain_geometry) {
1134 		.aperture_start	= input_start,
1135 		.aperture_end	= input_end,
1136 		.force_aperture	= true,
1137 	};
1138 
1139 	if (virtio_has_feature(vdev, VIRTIO_IOMMU_F_MMIO))
1140 		viommu->map_flags |= VIRTIO_IOMMU_MAP_F_MMIO;
1141 
1142 	viommu_ops.pgsize_bitmap = viommu->pgsize_bitmap;
1143 
1144 	virtio_device_ready(vdev);
1145 
1146 	/* Populate the event queue with buffers */
1147 	ret = viommu_fill_evtq(viommu);
1148 	if (ret)
1149 		goto err_free_vqs;
1150 
1151 	ret = iommu_device_sysfs_add(&viommu->iommu, dev, NULL, "%s",
1152 				     virtio_bus_name(vdev));
1153 	if (ret)
1154 		goto err_free_vqs;
1155 
1156 	iommu_device_register(&viommu->iommu, &viommu_ops, parent_dev);
1157 
1158 	vdev->priv = viommu;
1159 
1160 	dev_info(dev, "input address: %u bits\n",
1161 		 order_base_2(viommu->geometry.aperture_end));
1162 	dev_info(dev, "page mask: %#llx\n", viommu->pgsize_bitmap);
1163 
1164 	return 0;
1165 
1166 err_free_vqs:
1167 	vdev->config->del_vqs(vdev);
1168 
1169 	return ret;
1170 }
1171 
1172 static void viommu_remove(struct virtio_device *vdev)
1173 {
1174 	struct viommu_dev *viommu = vdev->priv;
1175 
1176 	iommu_device_sysfs_remove(&viommu->iommu);
1177 	iommu_device_unregister(&viommu->iommu);
1178 
1179 	/* Stop all virtqueues */
1180 	virtio_reset_device(vdev);
1181 	vdev->config->del_vqs(vdev);
1182 
1183 	dev_info(&vdev->dev, "device removed\n");
1184 }
1185 
1186 static void viommu_config_changed(struct virtio_device *vdev)
1187 {
1188 	dev_warn(&vdev->dev, "config changed\n");
1189 }
1190 
1191 static unsigned int features[] = {
1192 	VIRTIO_IOMMU_F_MAP_UNMAP,
1193 	VIRTIO_IOMMU_F_INPUT_RANGE,
1194 	VIRTIO_IOMMU_F_DOMAIN_RANGE,
1195 	VIRTIO_IOMMU_F_PROBE,
1196 	VIRTIO_IOMMU_F_MMIO,
1197 	VIRTIO_IOMMU_F_BYPASS_CONFIG,
1198 };
1199 
1200 static struct virtio_device_id id_table[] = {
1201 	{ VIRTIO_ID_IOMMU, VIRTIO_DEV_ANY_ID },
1202 	{ 0 },
1203 };
1204 MODULE_DEVICE_TABLE(virtio, id_table);
1205 
1206 static struct virtio_driver virtio_iommu_drv = {
1207 	.driver.name		= KBUILD_MODNAME,
1208 	.driver.owner		= THIS_MODULE,
1209 	.id_table		= id_table,
1210 	.feature_table		= features,
1211 	.feature_table_size	= ARRAY_SIZE(features),
1212 	.probe			= viommu_probe,
1213 	.remove			= viommu_remove,
1214 	.config_changed		= viommu_config_changed,
1215 };
1216 
1217 module_virtio_driver(virtio_iommu_drv);
1218 
1219 MODULE_DESCRIPTION("Virtio IOMMU driver");
1220 MODULE_AUTHOR("Jean-Philippe Brucker <jean-philippe.brucker@arm.com>");
1221 MODULE_LICENSE("GPL v2");
1222