Linux Audio

Check our new training course

Loading...
v5.9
   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/amba/bus.h>
  11#include <linux/delay.h>
  12#include <linux/dma-iommu.h>
  13#include <linux/freezer.h>
  14#include <linux/interval_tree.h>
  15#include <linux/iommu.h>
  16#include <linux/module.h>
  17#include <linux/of_iommu.h>
  18#include <linux/of_platform.h>
  19#include <linux/pci.h>
  20#include <linux/platform_device.h>
  21#include <linux/virtio.h>
  22#include <linux/virtio_config.h>
  23#include <linux/virtio_ids.h>
  24#include <linux/wait.h>
  25
  26#include <uapi/linux/virtio_iommu.h>
  27
 
 
  28#define MSI_IOVA_BASE			0x8000000
  29#define MSI_IOVA_LENGTH			0x100000
  30
  31#define VIOMMU_REQUEST_VQ		0
  32#define VIOMMU_EVENT_VQ			1
  33#define VIOMMU_NR_VQS			2
  34
  35struct viommu_dev {
  36	struct iommu_device		iommu;
  37	struct device			*dev;
  38	struct virtio_device		*vdev;
  39
  40	struct ida			domain_ids;
  41
  42	struct virtqueue		*vqs[VIOMMU_NR_VQS];
  43	spinlock_t			request_lock;
  44	struct list_head		requests;
  45	void				*evts;
  46
  47	/* Device configuration */
  48	struct iommu_domain_geometry	geometry;
  49	u64				pgsize_bitmap;
  50	u32				first_domain;
  51	u32				last_domain;
  52	/* Supported MAP flags */
  53	u32				map_flags;
  54	u32				probe_size;
  55};
  56
  57struct viommu_mapping {
  58	phys_addr_t			paddr;
  59	struct interval_tree_node	iova;
  60	u32				flags;
  61};
  62
  63struct viommu_domain {
  64	struct iommu_domain		domain;
  65	struct viommu_dev		*viommu;
  66	struct mutex			mutex; /* protects viommu pointer */
  67	unsigned int			id;
  68	u32				map_flags;
  69
  70	spinlock_t			mappings_lock;
  71	struct rb_root_cached		mappings;
  72
  73	unsigned long			nr_endpoints;
 
  74};
  75
  76struct viommu_endpoint {
  77	struct device			*dev;
  78	struct viommu_dev		*viommu;
  79	struct viommu_domain		*vdomain;
  80	struct list_head		resv_regions;
  81};
  82
  83struct 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
  93struct 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
 103static 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
 129static 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
 136static 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 */
 154static 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
 187static 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 */
 217static 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
 259err_free:
 260	kfree(req);
 261	return ret;
 262}
 263
 264static 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 */
 282static 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);
 303out_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 */
 313static int viommu_add_mapping(struct viommu_domain *vdomain, unsigned long iova,
 314			      phys_addr_t paddr, size_t size, 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	= iova + size - 1;
 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 * @size: size of the range. A size of 0 corresponds to the entire address
 341 *	space.
 342 *
 343 * On success, returns the number of unmapped bytes (>= size)
 344 */
 345static size_t viommu_del_mappings(struct viommu_domain *vdomain,
 346				  unsigned long iova, size_t size)
 347{
 348	size_t unmapped = 0;
 349	unsigned long flags;
 350	unsigned long last = iova + size - 1;
 351	struct viommu_mapping *mapping = NULL;
 352	struct interval_tree_node *node, *next;
 353
 354	spin_lock_irqsave(&vdomain->mappings_lock, flags);
 355	next = interval_tree_iter_first(&vdomain->mappings, iova, last);
 356	while (next) {
 357		node = next;
 358		mapping = container_of(node, struct viommu_mapping, iova);
 359		next = interval_tree_iter_next(node, iova, last);
 360
 361		/* Trying to split a mapping? */
 362		if (mapping->iova.start < iova)
 363			break;
 364
 365		/*
 366		 * Virtio-iommu doesn't allow UNMAP to split a mapping created
 367		 * with a single MAP request, so remove the full mapping.
 368		 */
 369		unmapped += mapping->iova.last - mapping->iova.start + 1;
 370
 371		interval_tree_remove(node, &vdomain->mappings);
 372		kfree(mapping);
 373	}
 374	spin_unlock_irqrestore(&vdomain->mappings_lock, flags);
 375
 376	return unmapped;
 377}
 378
 379/*
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 380 * viommu_replay_mappings - re-send MAP requests
 381 *
 382 * When reattaching a domain that was previously detached from all endpoints,
 383 * mappings were deleted from the device. Re-create the mappings available in
 384 * the internal tree.
 385 */
 386static int viommu_replay_mappings(struct viommu_domain *vdomain)
 387{
 388	int ret = 0;
 389	unsigned long flags;
 390	struct viommu_mapping *mapping;
 391	struct interval_tree_node *node;
 392	struct virtio_iommu_req_map map;
 393
 394	spin_lock_irqsave(&vdomain->mappings_lock, flags);
 395	node = interval_tree_iter_first(&vdomain->mappings, 0, -1UL);
 396	while (node) {
 397		mapping = container_of(node, struct viommu_mapping, iova);
 398		map = (struct virtio_iommu_req_map) {
 399			.head.type	= VIRTIO_IOMMU_T_MAP,
 400			.domain		= cpu_to_le32(vdomain->id),
 401			.virt_start	= cpu_to_le64(mapping->iova.start),
 402			.virt_end	= cpu_to_le64(mapping->iova.last),
 403			.phys_start	= cpu_to_le64(mapping->paddr),
 404			.flags		= cpu_to_le32(mapping->flags),
 405		};
 406
 407		ret = viommu_send_req_sync(vdomain->viommu, &map, sizeof(map));
 408		if (ret)
 409			break;
 410
 411		node = interval_tree_iter_next(node, 0, -1UL);
 412	}
 413	spin_unlock_irqrestore(&vdomain->mappings_lock, flags);
 414
 415	return ret;
 416}
 417
 418static int viommu_add_resv_mem(struct viommu_endpoint *vdev,
 419			       struct virtio_iommu_probe_resv_mem *mem,
 420			       size_t len)
 421{
 422	size_t size;
 423	u64 start64, end64;
 424	phys_addr_t start, end;
 425	struct iommu_resv_region *region = NULL;
 426	unsigned long prot = IOMMU_WRITE | IOMMU_NOEXEC | IOMMU_MMIO;
 427
 428	start = start64 = le64_to_cpu(mem->start);
 429	end = end64 = le64_to_cpu(mem->end);
 430	size = end64 - start64 + 1;
 431
 432	/* Catch any overflow, including the unlikely end64 - start64 + 1 = 0 */
 433	if (start != start64 || end != end64 || size < end64 - start64)
 434		return -EOVERFLOW;
 435
 436	if (len < sizeof(*mem))
 437		return -EINVAL;
 438
 439	switch (mem->subtype) {
 440	default:
 441		dev_warn(vdev->dev, "unknown resv mem subtype 0x%x\n",
 442			 mem->subtype);
 443		fallthrough;
 444	case VIRTIO_IOMMU_RESV_MEM_T_RESERVED:
 445		region = iommu_alloc_resv_region(start, size, 0,
 446						 IOMMU_RESV_RESERVED);
 
 447		break;
 448	case VIRTIO_IOMMU_RESV_MEM_T_MSI:
 449		region = iommu_alloc_resv_region(start, size, prot,
 450						 IOMMU_RESV_MSI);
 
 451		break;
 452	}
 453	if (!region)
 454		return -ENOMEM;
 455
 456	list_add(&region->list, &vdev->resv_regions);
 
 
 
 
 
 457	return 0;
 458}
 459
 460static int viommu_probe_endpoint(struct viommu_dev *viommu, struct device *dev)
 461{
 462	int ret;
 463	u16 type, len;
 464	size_t cur = 0;
 465	size_t probe_len;
 466	struct virtio_iommu_req_probe *probe;
 467	struct virtio_iommu_probe_property *prop;
 468	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
 469	struct viommu_endpoint *vdev = dev_iommu_priv_get(dev);
 470
 471	if (!fwspec->num_ids)
 472		return -EINVAL;
 473
 474	probe_len = sizeof(*probe) + viommu->probe_size +
 475		    sizeof(struct virtio_iommu_req_tail);
 476	probe = kzalloc(probe_len, GFP_KERNEL);
 477	if (!probe)
 478		return -ENOMEM;
 479
 480	probe->head.type = VIRTIO_IOMMU_T_PROBE;
 481	/*
 482	 * For now, assume that properties of an endpoint that outputs multiple
 483	 * IDs are consistent. Only probe the first one.
 484	 */
 485	probe->endpoint = cpu_to_le32(fwspec->ids[0]);
 486
 487	ret = viommu_send_req_sync(viommu, probe, probe_len);
 488	if (ret)
 489		goto out_free;
 490
 491	prop = (void *)probe->properties;
 492	type = le16_to_cpu(prop->type) & VIRTIO_IOMMU_PROBE_T_MASK;
 493
 494	while (type != VIRTIO_IOMMU_PROBE_T_NONE &&
 495	       cur < viommu->probe_size) {
 496		len = le16_to_cpu(prop->length) + sizeof(*prop);
 497
 498		switch (type) {
 499		case VIRTIO_IOMMU_PROBE_T_RESV_MEM:
 500			ret = viommu_add_resv_mem(vdev, (void *)prop, len);
 501			break;
 502		default:
 503			dev_err(dev, "unknown viommu prop 0x%x\n", type);
 504		}
 505
 506		if (ret)
 507			dev_err(dev, "failed to parse viommu prop 0x%x\n", type);
 508
 509		cur += len;
 510		if (cur >= viommu->probe_size)
 511			break;
 512
 513		prop = (void *)probe->properties + cur;
 514		type = le16_to_cpu(prop->type) & VIRTIO_IOMMU_PROBE_T_MASK;
 515	}
 516
 517out_free:
 518	kfree(probe);
 519	return ret;
 520}
 521
 522static int viommu_fault_handler(struct viommu_dev *viommu,
 523				struct virtio_iommu_fault *fault)
 524{
 525	char *reason_str;
 526
 527	u8 reason	= fault->reason;
 528	u32 flags	= le32_to_cpu(fault->flags);
 529	u32 endpoint	= le32_to_cpu(fault->endpoint);
 530	u64 address	= le64_to_cpu(fault->address);
 531
 532	switch (reason) {
 533	case VIRTIO_IOMMU_FAULT_R_DOMAIN:
 534		reason_str = "domain";
 535		break;
 536	case VIRTIO_IOMMU_FAULT_R_MAPPING:
 537		reason_str = "page";
 538		break;
 539	case VIRTIO_IOMMU_FAULT_R_UNKNOWN:
 540	default:
 541		reason_str = "unknown";
 542		break;
 543	}
 544
 545	/* TODO: find EP by ID and report_iommu_fault */
 546	if (flags & VIRTIO_IOMMU_FAULT_F_ADDRESS)
 547		dev_err_ratelimited(viommu->dev, "%s fault from EP %u at %#llx [%s%s%s]\n",
 548				    reason_str, endpoint, address,
 549				    flags & VIRTIO_IOMMU_FAULT_F_READ ? "R" : "",
 550				    flags & VIRTIO_IOMMU_FAULT_F_WRITE ? "W" : "",
 551				    flags & VIRTIO_IOMMU_FAULT_F_EXEC ? "X" : "");
 552	else
 553		dev_err_ratelimited(viommu->dev, "%s fault from EP %u\n",
 554				    reason_str, endpoint);
 555	return 0;
 556}
 557
 558static void viommu_event_handler(struct virtqueue *vq)
 559{
 560	int ret;
 561	unsigned int len;
 562	struct scatterlist sg[1];
 563	struct viommu_event *evt;
 564	struct viommu_dev *viommu = vq->vdev->priv;
 565
 566	while ((evt = virtqueue_get_buf(vq, &len)) != NULL) {
 567		if (len > sizeof(*evt)) {
 568			dev_err(viommu->dev,
 569				"invalid event buffer (len %u != %zu)\n",
 570				len, sizeof(*evt));
 571		} else if (!(evt->head & VIOMMU_FAULT_RESV_MASK)) {
 572			viommu_fault_handler(viommu, &evt->fault);
 573		}
 574
 575		sg_init_one(sg, evt, sizeof(*evt));
 576		ret = virtqueue_add_inbuf(vq, sg, 1, evt, GFP_ATOMIC);
 577		if (ret)
 578			dev_err(viommu->dev, "could not add event buffer\n");
 579	}
 580
 581	virtqueue_kick(vq);
 582}
 583
 584/* IOMMU API */
 585
 586static struct iommu_domain *viommu_domain_alloc(unsigned type)
 587{
 588	struct viommu_domain *vdomain;
 589
 590	if (type != IOMMU_DOMAIN_UNMANAGED && type != IOMMU_DOMAIN_DMA)
 
 
 591		return NULL;
 592
 593	vdomain = kzalloc(sizeof(*vdomain), GFP_KERNEL);
 594	if (!vdomain)
 595		return NULL;
 596
 597	mutex_init(&vdomain->mutex);
 598	spin_lock_init(&vdomain->mappings_lock);
 599	vdomain->mappings = RB_ROOT_CACHED;
 600
 601	if (type == IOMMU_DOMAIN_DMA &&
 602	    iommu_get_dma_cookie(&vdomain->domain)) {
 603		kfree(vdomain);
 604		return NULL;
 605	}
 606
 607	return &vdomain->domain;
 608}
 609
 610static int viommu_domain_finalise(struct viommu_endpoint *vdev,
 611				  struct iommu_domain *domain)
 612{
 613	int ret;
 614	unsigned long viommu_page_size;
 615	struct viommu_dev *viommu = vdev->viommu;
 616	struct viommu_domain *vdomain = to_viommu_domain(domain);
 617
 618	viommu_page_size = 1UL << __ffs(viommu->pgsize_bitmap);
 619	if (viommu_page_size > PAGE_SIZE) {
 620		dev_err(vdev->dev,
 621			"granule 0x%lx larger than system page size 0x%lx\n",
 622			viommu_page_size, PAGE_SIZE);
 623		return -EINVAL;
 624	}
 625
 626	ret = ida_alloc_range(&viommu->domain_ids, viommu->first_domain,
 627			      viommu->last_domain, GFP_KERNEL);
 628	if (ret < 0)
 629		return ret;
 630
 631	vdomain->id		= (unsigned int)ret;
 632
 633	domain->pgsize_bitmap	= viommu->pgsize_bitmap;
 634	domain->geometry	= viommu->geometry;
 635
 636	vdomain->map_flags	= viommu->map_flags;
 637	vdomain->viommu		= viommu;
 638
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 639	return 0;
 640}
 641
 642static void viommu_domain_free(struct iommu_domain *domain)
 643{
 644	struct viommu_domain *vdomain = to_viommu_domain(domain);
 645
 646	iommu_put_dma_cookie(domain);
 647
 648	/* Free all remaining mappings (size 2^64) */
 649	viommu_del_mappings(vdomain, 0, 0);
 650
 651	if (vdomain->viommu)
 652		ida_free(&vdomain->viommu->domain_ids, vdomain->id);
 653
 654	kfree(vdomain);
 655}
 656
 657static int viommu_attach_dev(struct iommu_domain *domain, struct device *dev)
 658{
 659	int i;
 660	int ret = 0;
 661	struct virtio_iommu_req_attach req;
 662	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
 663	struct viommu_endpoint *vdev = dev_iommu_priv_get(dev);
 664	struct viommu_domain *vdomain = to_viommu_domain(domain);
 665
 666	mutex_lock(&vdomain->mutex);
 667	if (!vdomain->viommu) {
 668		/*
 669		 * Properly initialize the domain now that we know which viommu
 670		 * owns it.
 671		 */
 672		ret = viommu_domain_finalise(vdev, domain);
 673	} else if (vdomain->viommu != vdev->viommu) {
 674		dev_err(dev, "cannot attach to foreign vIOMMU\n");
 675		ret = -EXDEV;
 676	}
 677	mutex_unlock(&vdomain->mutex);
 678
 679	if (ret)
 680		return ret;
 681
 682	/*
 683	 * In the virtio-iommu device, when attaching the endpoint to a new
 684	 * domain, it is detached from the old one and, if as as a result the
 685	 * old domain isn't attached to any endpoint, all mappings are removed
 686	 * from the old domain and it is freed.
 687	 *
 688	 * In the driver the old domain still exists, and its mappings will be
 689	 * recreated if it gets reattached to an endpoint. Otherwise it will be
 690	 * freed explicitly.
 691	 *
 692	 * vdev->vdomain is protected by group->mutex
 693	 */
 694	if (vdev->vdomain)
 695		vdev->vdomain->nr_endpoints--;
 696
 697	req = (struct virtio_iommu_req_attach) {
 698		.head.type	= VIRTIO_IOMMU_T_ATTACH,
 699		.domain		= cpu_to_le32(vdomain->id),
 700	};
 701
 
 
 
 702	for (i = 0; i < fwspec->num_ids; i++) {
 703		req.endpoint = cpu_to_le32(fwspec->ids[i]);
 704
 705		ret = viommu_send_req_sync(vdomain->viommu, &req, sizeof(req));
 706		if (ret)
 707			return ret;
 708	}
 709
 710	if (!vdomain->nr_endpoints) {
 711		/*
 712		 * This endpoint is the first to be attached to the domain.
 713		 * Replay existing mappings (e.g. SW MSI).
 714		 */
 715		ret = viommu_replay_mappings(vdomain);
 716		if (ret)
 717			return ret;
 718	}
 719
 720	vdomain->nr_endpoints++;
 721	vdev->vdomain = vdomain;
 722
 723	return 0;
 724}
 725
 726static int viommu_map(struct iommu_domain *domain, unsigned long iova,
 727		      phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 728{
 729	int ret;
 730	u32 flags;
 
 
 731	struct virtio_iommu_req_map map;
 732	struct viommu_domain *vdomain = to_viommu_domain(domain);
 733
 734	flags = (prot & IOMMU_READ ? VIRTIO_IOMMU_MAP_F_READ : 0) |
 735		(prot & IOMMU_WRITE ? VIRTIO_IOMMU_MAP_F_WRITE : 0) |
 736		(prot & IOMMU_MMIO ? VIRTIO_IOMMU_MAP_F_MMIO : 0);
 737
 738	if (flags & ~vdomain->map_flags)
 739		return -EINVAL;
 740
 741	ret = viommu_add_mapping(vdomain, iova, paddr, size, flags);
 742	if (ret)
 743		return ret;
 744
 745	map = (struct virtio_iommu_req_map) {
 746		.head.type	= VIRTIO_IOMMU_T_MAP,
 747		.domain		= cpu_to_le32(vdomain->id),
 748		.virt_start	= cpu_to_le64(iova),
 749		.phys_start	= cpu_to_le64(paddr),
 750		.virt_end	= cpu_to_le64(iova + size - 1),
 751		.flags		= cpu_to_le32(flags),
 752	};
 753
 754	if (!vdomain->nr_endpoints)
 755		return 0;
 756
 757	ret = viommu_send_req_sync(vdomain->viommu, &map, sizeof(map));
 758	if (ret)
 759		viommu_del_mappings(vdomain, iova, size);
 
 
 
 
 
 760
 761	return ret;
 762}
 763
 764static size_t viommu_unmap(struct iommu_domain *domain, unsigned long iova,
 765			   size_t size, struct iommu_iotlb_gather *gather)
 
 766{
 767	int ret = 0;
 768	size_t unmapped;
 769	struct virtio_iommu_req_unmap unmap;
 770	struct viommu_domain *vdomain = to_viommu_domain(domain);
 
 771
 772	unmapped = viommu_del_mappings(vdomain, iova, size);
 773	if (unmapped < size)
 774		return 0;
 775
 776	/* Device already removed all mappings after detach. */
 777	if (!vdomain->nr_endpoints)
 778		return unmapped;
 779
 780	unmap = (struct virtio_iommu_req_unmap) {
 781		.head.type	= VIRTIO_IOMMU_T_UNMAP,
 782		.domain		= cpu_to_le32(vdomain->id),
 783		.virt_start	= cpu_to_le64(iova),
 784		.virt_end	= cpu_to_le64(iova + unmapped - 1),
 785	};
 786
 787	ret = viommu_add_req(vdomain->viommu, &unmap, sizeof(unmap));
 788	return ret ? 0 : unmapped;
 789}
 790
 791static phys_addr_t viommu_iova_to_phys(struct iommu_domain *domain,
 792				       dma_addr_t iova)
 793{
 794	u64 paddr = 0;
 795	unsigned long flags;
 796	struct viommu_mapping *mapping;
 797	struct interval_tree_node *node;
 798	struct viommu_domain *vdomain = to_viommu_domain(domain);
 799
 800	spin_lock_irqsave(&vdomain->mappings_lock, flags);
 801	node = interval_tree_iter_first(&vdomain->mappings, iova, iova);
 802	if (node) {
 803		mapping = container_of(node, struct viommu_mapping, iova);
 804		paddr = mapping->paddr + (iova - mapping->iova.start);
 805	}
 806	spin_unlock_irqrestore(&vdomain->mappings_lock, flags);
 807
 808	return paddr;
 809}
 810
 811static void viommu_iotlb_sync(struct iommu_domain *domain,
 812			      struct iommu_iotlb_gather *gather)
 813{
 814	struct viommu_domain *vdomain = to_viommu_domain(domain);
 815
 816	viommu_sync_req(vdomain->viommu);
 817}
 818
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 819static void viommu_get_resv_regions(struct device *dev, struct list_head *head)
 820{
 821	struct iommu_resv_region *entry, *new_entry, *msi = NULL;
 822	struct viommu_endpoint *vdev = dev_iommu_priv_get(dev);
 823	int prot = IOMMU_WRITE | IOMMU_NOEXEC | IOMMU_MMIO;
 824
 825	list_for_each_entry(entry, &vdev->resv_regions, list) {
 826		if (entry->type == IOMMU_RESV_MSI)
 827			msi = entry;
 828
 829		new_entry = kmemdup(entry, sizeof(*entry), GFP_KERNEL);
 830		if (!new_entry)
 831			return;
 832		list_add_tail(&new_entry->list, head);
 833	}
 834
 835	/*
 836	 * If the device didn't register any bypass MSI window, add a
 837	 * software-mapped region.
 838	 */
 839	if (!msi) {
 840		msi = iommu_alloc_resv_region(MSI_IOVA_BASE, MSI_IOVA_LENGTH,
 841					      prot, IOMMU_RESV_SW_MSI);
 
 842		if (!msi)
 843			return;
 844
 845		list_add_tail(&msi->list, head);
 846	}
 847
 848	iommu_dma_get_resv_regions(dev, head);
 849}
 850
 851static struct iommu_ops viommu_ops;
 852static struct virtio_driver virtio_iommu_drv;
 853
 854static int viommu_match_node(struct device *dev, const void *data)
 855{
 856	return dev->parent->fwnode == data;
 857}
 858
 859static struct viommu_dev *viommu_get_by_fwnode(struct fwnode_handle *fwnode)
 860{
 861	struct device *dev = driver_find_device(&virtio_iommu_drv.driver, NULL,
 862						fwnode, viommu_match_node);
 863	put_device(dev);
 864
 865	return dev ? dev_to_virtio(dev)->priv : NULL;
 866}
 867
 868static struct iommu_device *viommu_probe_device(struct device *dev)
 869{
 870	int ret;
 871	struct viommu_endpoint *vdev;
 872	struct viommu_dev *viommu = NULL;
 873	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
 874
 875	if (!fwspec || fwspec->ops != &viommu_ops)
 876		return ERR_PTR(-ENODEV);
 877
 878	viommu = viommu_get_by_fwnode(fwspec->iommu_fwnode);
 879	if (!viommu)
 880		return ERR_PTR(-ENODEV);
 881
 882	vdev = kzalloc(sizeof(*vdev), GFP_KERNEL);
 883	if (!vdev)
 884		return ERR_PTR(-ENOMEM);
 885
 886	vdev->dev = dev;
 887	vdev->viommu = viommu;
 888	INIT_LIST_HEAD(&vdev->resv_regions);
 889	dev_iommu_priv_set(dev, vdev);
 890
 891	if (viommu->probe_size) {
 892		/* Get additional information for this endpoint */
 893		ret = viommu_probe_endpoint(viommu, dev);
 894		if (ret)
 895			goto err_free_dev;
 896	}
 897
 898	return &viommu->iommu;
 899
 900err_free_dev:
 901	generic_iommu_put_resv_regions(dev, &vdev->resv_regions);
 902	kfree(vdev);
 903
 904	return ERR_PTR(ret);
 905}
 906
 907static void viommu_release_device(struct device *dev)
 908{
 909	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
 910	struct viommu_endpoint *vdev;
 911
 912	if (!fwspec || fwspec->ops != &viommu_ops)
 913		return;
 
 914
 915	vdev = dev_iommu_priv_get(dev);
 
 
 916
 917	generic_iommu_put_resv_regions(dev, &vdev->resv_regions);
 
 918	kfree(vdev);
 919}
 920
 921static struct iommu_group *viommu_device_group(struct device *dev)
 922{
 923	if (dev_is_pci(dev))
 924		return pci_device_group(dev);
 925	else
 926		return generic_device_group(dev);
 927}
 928
 929static int viommu_of_xlate(struct device *dev, struct of_phandle_args *args)
 
 930{
 931	return iommu_fwspec_add_ids(dev, args->args, 1);
 932}
 933
 
 
 
 
 
 
 
 
 
 
 
 
 934static struct iommu_ops viommu_ops = {
 
 935	.domain_alloc		= viommu_domain_alloc,
 936	.domain_free		= viommu_domain_free,
 937	.attach_dev		= viommu_attach_dev,
 938	.map			= viommu_map,
 939	.unmap			= viommu_unmap,
 940	.iova_to_phys		= viommu_iova_to_phys,
 941	.iotlb_sync		= viommu_iotlb_sync,
 942	.probe_device		= viommu_probe_device,
 
 943	.release_device		= viommu_release_device,
 944	.device_group		= viommu_device_group,
 945	.get_resv_regions	= viommu_get_resv_regions,
 946	.put_resv_regions	= generic_iommu_put_resv_regions,
 947	.of_xlate		= viommu_of_xlate,
 
 
 
 
 
 
 
 
 
 
 
 948};
 949
 950static int viommu_init_vqs(struct viommu_dev *viommu)
 951{
 952	struct virtio_device *vdev = dev_to_virtio(viommu->dev);
 953	const char *names[] = { "request", "event" };
 954	vq_callback_t *callbacks[] = {
 955		NULL, /* No async requests */
 956		viommu_event_handler,
 957	};
 958
 959	return virtio_find_vqs(vdev, VIOMMU_NR_VQS, viommu->vqs, callbacks,
 960			       names, NULL);
 961}
 962
 963static int viommu_fill_evtq(struct viommu_dev *viommu)
 964{
 965	int i, ret;
 966	struct scatterlist sg[1];
 967	struct viommu_event *evts;
 968	struct virtqueue *vq = viommu->vqs[VIOMMU_EVENT_VQ];
 969	size_t nr_evts = vq->num_free;
 970
 971	viommu->evts = evts = devm_kmalloc_array(viommu->dev, nr_evts,
 972						 sizeof(*evts), GFP_KERNEL);
 973	if (!evts)
 974		return -ENOMEM;
 975
 976	for (i = 0; i < nr_evts; i++) {
 977		sg_init_one(sg, &evts[i], sizeof(*evts));
 978		ret = virtqueue_add_inbuf(vq, sg, 1, &evts[i], GFP_KERNEL);
 979		if (ret)
 980			return ret;
 981	}
 982
 983	return 0;
 984}
 985
 986static int viommu_probe(struct virtio_device *vdev)
 987{
 988	struct device *parent_dev = vdev->dev.parent;
 989	struct viommu_dev *viommu = NULL;
 990	struct device *dev = &vdev->dev;
 991	u64 input_start = 0;
 992	u64 input_end = -1UL;
 993	int ret;
 994
 995	if (!virtio_has_feature(vdev, VIRTIO_F_VERSION_1) ||
 996	    !virtio_has_feature(vdev, VIRTIO_IOMMU_F_MAP_UNMAP))
 997		return -ENODEV;
 998
 999	viommu = devm_kzalloc(dev, sizeof(*viommu), GFP_KERNEL);
1000	if (!viommu)
1001		return -ENOMEM;
1002
1003	spin_lock_init(&viommu->request_lock);
1004	ida_init(&viommu->domain_ids);
1005	viommu->dev = dev;
1006	viommu->vdev = vdev;
1007	INIT_LIST_HEAD(&viommu->requests);
1008
1009	ret = viommu_init_vqs(viommu);
1010	if (ret)
1011		return ret;
1012
1013	virtio_cread_le(vdev, struct virtio_iommu_config, page_size_mask,
1014			&viommu->pgsize_bitmap);
1015
1016	if (!viommu->pgsize_bitmap) {
1017		ret = -EINVAL;
1018		goto err_free_vqs;
1019	}
1020
1021	viommu->map_flags = VIRTIO_IOMMU_MAP_F_READ | VIRTIO_IOMMU_MAP_F_WRITE;
1022	viommu->last_domain = ~0U;
1023
1024	/* Optional features */
1025	virtio_cread_le_feature(vdev, VIRTIO_IOMMU_F_INPUT_RANGE,
1026				struct virtio_iommu_config, input_range.start,
1027				&input_start);
1028
1029	virtio_cread_le_feature(vdev, VIRTIO_IOMMU_F_INPUT_RANGE,
1030				struct virtio_iommu_config, input_range.end,
1031				&input_end);
1032
1033	virtio_cread_le_feature(vdev, VIRTIO_IOMMU_F_DOMAIN_RANGE,
1034				struct virtio_iommu_config, domain_range.start,
1035				&viommu->first_domain);
1036
1037	virtio_cread_le_feature(vdev, VIRTIO_IOMMU_F_DOMAIN_RANGE,
1038				struct virtio_iommu_config, domain_range.end,
1039				&viommu->last_domain);
1040
1041	virtio_cread_le_feature(vdev, VIRTIO_IOMMU_F_PROBE,
1042				struct virtio_iommu_config, probe_size,
1043				&viommu->probe_size);
1044
1045	viommu->geometry = (struct iommu_domain_geometry) {
1046		.aperture_start	= input_start,
1047		.aperture_end	= input_end,
1048		.force_aperture	= true,
1049	};
1050
1051	if (virtio_has_feature(vdev, VIRTIO_IOMMU_F_MMIO))
1052		viommu->map_flags |= VIRTIO_IOMMU_MAP_F_MMIO;
1053
1054	viommu_ops.pgsize_bitmap = viommu->pgsize_bitmap;
1055
1056	virtio_device_ready(vdev);
1057
1058	/* Populate the event queue with buffers */
1059	ret = viommu_fill_evtq(viommu);
1060	if (ret)
1061		goto err_free_vqs;
1062
1063	ret = iommu_device_sysfs_add(&viommu->iommu, dev, NULL, "%s",
1064				     virtio_bus_name(vdev));
1065	if (ret)
1066		goto err_free_vqs;
1067
1068	iommu_device_set_ops(&viommu->iommu, &viommu_ops);
1069	iommu_device_set_fwnode(&viommu->iommu, parent_dev->fwnode);
1070
1071	iommu_device_register(&viommu->iommu);
1072
1073#ifdef CONFIG_PCI
1074	if (pci_bus_type.iommu_ops != &viommu_ops) {
1075		ret = bus_set_iommu(&pci_bus_type, &viommu_ops);
1076		if (ret)
1077			goto err_unregister;
1078	}
1079#endif
1080#ifdef CONFIG_ARM_AMBA
1081	if (amba_bustype.iommu_ops != &viommu_ops) {
1082		ret = bus_set_iommu(&amba_bustype, &viommu_ops);
1083		if (ret)
1084			goto err_unregister;
1085	}
1086#endif
1087	if (platform_bus_type.iommu_ops != &viommu_ops) {
1088		ret = bus_set_iommu(&platform_bus_type, &viommu_ops);
1089		if (ret)
1090			goto err_unregister;
1091	}
1092
1093	vdev->priv = viommu;
1094
1095	dev_info(dev, "input address: %u bits\n",
1096		 order_base_2(viommu->geometry.aperture_end));
1097	dev_info(dev, "page mask: %#llx\n", viommu->pgsize_bitmap);
1098
1099	return 0;
1100
1101err_unregister:
1102	iommu_device_sysfs_remove(&viommu->iommu);
1103	iommu_device_unregister(&viommu->iommu);
1104err_free_vqs:
1105	vdev->config->del_vqs(vdev);
1106
1107	return ret;
1108}
1109
1110static void viommu_remove(struct virtio_device *vdev)
1111{
1112	struct viommu_dev *viommu = vdev->priv;
1113
1114	iommu_device_sysfs_remove(&viommu->iommu);
1115	iommu_device_unregister(&viommu->iommu);
1116
1117	/* Stop all virtqueues */
1118	vdev->config->reset(vdev);
1119	vdev->config->del_vqs(vdev);
1120
1121	dev_info(&vdev->dev, "device removed\n");
1122}
1123
1124static void viommu_config_changed(struct virtio_device *vdev)
1125{
1126	dev_warn(&vdev->dev, "config changed\n");
1127}
1128
1129static unsigned int features[] = {
1130	VIRTIO_IOMMU_F_MAP_UNMAP,
1131	VIRTIO_IOMMU_F_INPUT_RANGE,
1132	VIRTIO_IOMMU_F_DOMAIN_RANGE,
1133	VIRTIO_IOMMU_F_PROBE,
1134	VIRTIO_IOMMU_F_MMIO,
 
1135};
1136
1137static struct virtio_device_id id_table[] = {
1138	{ VIRTIO_ID_IOMMU, VIRTIO_DEV_ANY_ID },
1139	{ 0 },
1140};
 
1141
1142static struct virtio_driver virtio_iommu_drv = {
1143	.driver.name		= KBUILD_MODNAME,
1144	.driver.owner		= THIS_MODULE,
1145	.id_table		= id_table,
1146	.feature_table		= features,
1147	.feature_table_size	= ARRAY_SIZE(features),
1148	.probe			= viommu_probe,
1149	.remove			= viommu_remove,
1150	.config_changed		= viommu_config_changed,
1151};
1152
1153module_virtio_driver(virtio_iommu_drv);
1154
1155MODULE_DESCRIPTION("Virtio IOMMU driver");
1156MODULE_AUTHOR("Jean-Philippe Brucker <jean-philippe.brucker@arm.com>");
1157MODULE_LICENSE("GPL v2");
v6.9.4
   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.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
  34struct 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
  56struct viommu_mapping {
  57	phys_addr_t			paddr;
  58	struct interval_tree_node	iova;
  59	u32				flags;
  60};
  61
  62struct 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
  76struct viommu_endpoint {
  77	struct device			*dev;
  78	struct viommu_dev		*viommu;
  79	struct viommu_domain		*vdomain;
  80	struct list_head		resv_regions;
  81};
  82
  83struct viommu_request {
  84	struct list_head		list;
  85	void				*writeback;
  86	unsigned int			write_offset;
  87	unsigned int			len;
  88	char				buf[] __counted_by(len);
  89};
  90
  91#define VIOMMU_FAULT_RESV_MASK		0xffffff00
  92
  93struct 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
 103static 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
 129static 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
 136static 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 */
 154static 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
 187static 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 */
 217static 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(struct_size(req, buf, 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
 259err_free:
 260	kfree(req);
 261	return ret;
 262}
 263
 264static 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 */
 282static 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);
 303out_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 */
 313static 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 */
 344static 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 */
 381static 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
 421err_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 */
 433static 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
 465static 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						 GFP_KERNEL);
 495		break;
 496	case VIRTIO_IOMMU_RESV_MEM_T_MSI:
 497		region = iommu_alloc_resv_region(start, size, prot,
 498						 IOMMU_RESV_MSI,
 499						 GFP_KERNEL);
 500		break;
 501	}
 502	if (!region)
 503		return -ENOMEM;
 504
 505	/* Keep the list sorted */
 506	list_for_each_entry(next, &vdev->resv_regions, list) {
 507		if (next->start > region->start)
 508			break;
 509	}
 510	list_add_tail(&region->list, &next->list);
 511	return 0;
 512}
 513
 514static int viommu_probe_endpoint(struct viommu_dev *viommu, struct device *dev)
 515{
 516	int ret;
 517	u16 type, len;
 518	size_t cur = 0;
 519	size_t probe_len;
 520	struct virtio_iommu_req_probe *probe;
 521	struct virtio_iommu_probe_property *prop;
 522	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
 523	struct viommu_endpoint *vdev = dev_iommu_priv_get(dev);
 524
 525	if (!fwspec->num_ids)
 526		return -EINVAL;
 527
 528	probe_len = sizeof(*probe) + viommu->probe_size +
 529		    sizeof(struct virtio_iommu_req_tail);
 530	probe = kzalloc(probe_len, GFP_KERNEL);
 531	if (!probe)
 532		return -ENOMEM;
 533
 534	probe->head.type = VIRTIO_IOMMU_T_PROBE;
 535	/*
 536	 * For now, assume that properties of an endpoint that outputs multiple
 537	 * IDs are consistent. Only probe the first one.
 538	 */
 539	probe->endpoint = cpu_to_le32(fwspec->ids[0]);
 540
 541	ret = viommu_send_req_sync(viommu, probe, probe_len);
 542	if (ret)
 543		goto out_free;
 544
 545	prop = (void *)probe->properties;
 546	type = le16_to_cpu(prop->type) & VIRTIO_IOMMU_PROBE_T_MASK;
 547
 548	while (type != VIRTIO_IOMMU_PROBE_T_NONE &&
 549	       cur < viommu->probe_size) {
 550		len = le16_to_cpu(prop->length) + sizeof(*prop);
 551
 552		switch (type) {
 553		case VIRTIO_IOMMU_PROBE_T_RESV_MEM:
 554			ret = viommu_add_resv_mem(vdev, (void *)prop, len);
 555			break;
 556		default:
 557			dev_err(dev, "unknown viommu prop 0x%x\n", type);
 558		}
 559
 560		if (ret)
 561			dev_err(dev, "failed to parse viommu prop 0x%x\n", type);
 562
 563		cur += len;
 564		if (cur >= viommu->probe_size)
 565			break;
 566
 567		prop = (void *)probe->properties + cur;
 568		type = le16_to_cpu(prop->type) & VIRTIO_IOMMU_PROBE_T_MASK;
 569	}
 570
 571out_free:
 572	kfree(probe);
 573	return ret;
 574}
 575
 576static int viommu_fault_handler(struct viommu_dev *viommu,
 577				struct virtio_iommu_fault *fault)
 578{
 579	char *reason_str;
 580
 581	u8 reason	= fault->reason;
 582	u32 flags	= le32_to_cpu(fault->flags);
 583	u32 endpoint	= le32_to_cpu(fault->endpoint);
 584	u64 address	= le64_to_cpu(fault->address);
 585
 586	switch (reason) {
 587	case VIRTIO_IOMMU_FAULT_R_DOMAIN:
 588		reason_str = "domain";
 589		break;
 590	case VIRTIO_IOMMU_FAULT_R_MAPPING:
 591		reason_str = "page";
 592		break;
 593	case VIRTIO_IOMMU_FAULT_R_UNKNOWN:
 594	default:
 595		reason_str = "unknown";
 596		break;
 597	}
 598
 599	/* TODO: find EP by ID and report_iommu_fault */
 600	if (flags & VIRTIO_IOMMU_FAULT_F_ADDRESS)
 601		dev_err_ratelimited(viommu->dev, "%s fault from EP %u at %#llx [%s%s%s]\n",
 602				    reason_str, endpoint, address,
 603				    flags & VIRTIO_IOMMU_FAULT_F_READ ? "R" : "",
 604				    flags & VIRTIO_IOMMU_FAULT_F_WRITE ? "W" : "",
 605				    flags & VIRTIO_IOMMU_FAULT_F_EXEC ? "X" : "");
 606	else
 607		dev_err_ratelimited(viommu->dev, "%s fault from EP %u\n",
 608				    reason_str, endpoint);
 609	return 0;
 610}
 611
 612static void viommu_event_handler(struct virtqueue *vq)
 613{
 614	int ret;
 615	unsigned int len;
 616	struct scatterlist sg[1];
 617	struct viommu_event *evt;
 618	struct viommu_dev *viommu = vq->vdev->priv;
 619
 620	while ((evt = virtqueue_get_buf(vq, &len)) != NULL) {
 621		if (len > sizeof(*evt)) {
 622			dev_err(viommu->dev,
 623				"invalid event buffer (len %u != %zu)\n",
 624				len, sizeof(*evt));
 625		} else if (!(evt->head & VIOMMU_FAULT_RESV_MASK)) {
 626			viommu_fault_handler(viommu, &evt->fault);
 627		}
 628
 629		sg_init_one(sg, evt, sizeof(*evt));
 630		ret = virtqueue_add_inbuf(vq, sg, 1, evt, GFP_ATOMIC);
 631		if (ret)
 632			dev_err(viommu->dev, "could not add event buffer\n");
 633	}
 634
 635	virtqueue_kick(vq);
 636}
 637
 638/* IOMMU API */
 639
 640static struct iommu_domain *viommu_domain_alloc(unsigned type)
 641{
 642	struct viommu_domain *vdomain;
 643
 644	if (type != IOMMU_DOMAIN_UNMANAGED &&
 645	    type != IOMMU_DOMAIN_DMA &&
 646	    type != IOMMU_DOMAIN_IDENTITY)
 647		return NULL;
 648
 649	vdomain = kzalloc(sizeof(*vdomain), GFP_KERNEL);
 650	if (!vdomain)
 651		return NULL;
 652
 653	mutex_init(&vdomain->mutex);
 654	spin_lock_init(&vdomain->mappings_lock);
 655	vdomain->mappings = RB_ROOT_CACHED;
 656
 
 
 
 
 
 
 657	return &vdomain->domain;
 658}
 659
 660static int viommu_domain_finalise(struct viommu_endpoint *vdev,
 661				  struct iommu_domain *domain)
 662{
 663	int ret;
 664	unsigned long viommu_page_size;
 665	struct viommu_dev *viommu = vdev->viommu;
 666	struct viommu_domain *vdomain = to_viommu_domain(domain);
 667
 668	viommu_page_size = 1UL << __ffs(viommu->pgsize_bitmap);
 669	if (viommu_page_size > PAGE_SIZE) {
 670		dev_err(vdev->dev,
 671			"granule 0x%lx larger than system page size 0x%lx\n",
 672			viommu_page_size, PAGE_SIZE);
 673		return -ENODEV;
 674	}
 675
 676	ret = ida_alloc_range(&viommu->domain_ids, viommu->first_domain,
 677			      viommu->last_domain, GFP_KERNEL);
 678	if (ret < 0)
 679		return ret;
 680
 681	vdomain->id		= (unsigned int)ret;
 682
 683	domain->pgsize_bitmap	= viommu->pgsize_bitmap;
 684	domain->geometry	= viommu->geometry;
 685
 686	vdomain->map_flags	= viommu->map_flags;
 687	vdomain->viommu		= viommu;
 688
 689	if (domain->type == IOMMU_DOMAIN_IDENTITY) {
 690		if (virtio_has_feature(viommu->vdev,
 691				       VIRTIO_IOMMU_F_BYPASS_CONFIG)) {
 692			vdomain->bypass = true;
 693			return 0;
 694		}
 695
 696		ret = viommu_domain_map_identity(vdev, vdomain);
 697		if (ret) {
 698			ida_free(&viommu->domain_ids, vdomain->id);
 699			vdomain->viommu = NULL;
 700			return ret;
 701		}
 702	}
 703
 704	return 0;
 705}
 706
 707static void viommu_domain_free(struct iommu_domain *domain)
 708{
 709	struct viommu_domain *vdomain = to_viommu_domain(domain);
 710
 711	/* Free all remaining mappings */
 712	viommu_del_mappings(vdomain, 0, ULLONG_MAX);
 
 
 713
 714	if (vdomain->viommu)
 715		ida_free(&vdomain->viommu->domain_ids, vdomain->id);
 716
 717	kfree(vdomain);
 718}
 719
 720static int viommu_attach_dev(struct iommu_domain *domain, struct device *dev)
 721{
 722	int i;
 723	int ret = 0;
 724	struct virtio_iommu_req_attach req;
 725	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
 726	struct viommu_endpoint *vdev = dev_iommu_priv_get(dev);
 727	struct viommu_domain *vdomain = to_viommu_domain(domain);
 728
 729	mutex_lock(&vdomain->mutex);
 730	if (!vdomain->viommu) {
 731		/*
 732		 * Properly initialize the domain now that we know which viommu
 733		 * owns it.
 734		 */
 735		ret = viommu_domain_finalise(vdev, domain);
 736	} else if (vdomain->viommu != vdev->viommu) {
 737		ret = -EINVAL;
 
 738	}
 739	mutex_unlock(&vdomain->mutex);
 740
 741	if (ret)
 742		return ret;
 743
 744	/*
 745	 * In the virtio-iommu device, when attaching the endpoint to a new
 746	 * domain, it is detached from the old one and, if as a result the
 747	 * old domain isn't attached to any endpoint, all mappings are removed
 748	 * from the old domain and it is freed.
 749	 *
 750	 * In the driver the old domain still exists, and its mappings will be
 751	 * recreated if it gets reattached to an endpoint. Otherwise it will be
 752	 * freed explicitly.
 753	 *
 754	 * vdev->vdomain is protected by group->mutex
 755	 */
 756	if (vdev->vdomain)
 757		vdev->vdomain->nr_endpoints--;
 758
 759	req = (struct virtio_iommu_req_attach) {
 760		.head.type	= VIRTIO_IOMMU_T_ATTACH,
 761		.domain		= cpu_to_le32(vdomain->id),
 762	};
 763
 764	if (vdomain->bypass)
 765		req.flags |= cpu_to_le32(VIRTIO_IOMMU_ATTACH_F_BYPASS);
 766
 767	for (i = 0; i < fwspec->num_ids; i++) {
 768		req.endpoint = cpu_to_le32(fwspec->ids[i]);
 769
 770		ret = viommu_send_req_sync(vdomain->viommu, &req, sizeof(req));
 771		if (ret)
 772			return ret;
 773	}
 774
 775	if (!vdomain->nr_endpoints) {
 776		/*
 777		 * This endpoint is the first to be attached to the domain.
 778		 * Replay existing mappings (e.g. SW MSI).
 779		 */
 780		ret = viommu_replay_mappings(vdomain);
 781		if (ret)
 782			return ret;
 783	}
 784
 785	vdomain->nr_endpoints++;
 786	vdev->vdomain = vdomain;
 787
 788	return 0;
 789}
 790
 791static void viommu_detach_dev(struct viommu_endpoint *vdev)
 792{
 793	int i;
 794	struct virtio_iommu_req_detach req;
 795	struct viommu_domain *vdomain = vdev->vdomain;
 796	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(vdev->dev);
 797
 798	if (!vdomain)
 799		return;
 800
 801	req = (struct virtio_iommu_req_detach) {
 802		.head.type	= VIRTIO_IOMMU_T_DETACH,
 803		.domain		= cpu_to_le32(vdomain->id),
 804	};
 805
 806	for (i = 0; i < fwspec->num_ids; i++) {
 807		req.endpoint = cpu_to_le32(fwspec->ids[i]);
 808		WARN_ON(viommu_send_req_sync(vdev->viommu, &req, sizeof(req)));
 809	}
 810	vdomain->nr_endpoints--;
 811	vdev->vdomain = NULL;
 812}
 813
 814static int viommu_map_pages(struct iommu_domain *domain, unsigned long iova,
 815			    phys_addr_t paddr, size_t pgsize, size_t pgcount,
 816			    int prot, gfp_t gfp, size_t *mapped)
 817{
 818	int ret;
 819	u32 flags;
 820	size_t size = pgsize * pgcount;
 821	u64 end = iova + size - 1;
 822	struct virtio_iommu_req_map map;
 823	struct viommu_domain *vdomain = to_viommu_domain(domain);
 824
 825	flags = (prot & IOMMU_READ ? VIRTIO_IOMMU_MAP_F_READ : 0) |
 826		(prot & IOMMU_WRITE ? VIRTIO_IOMMU_MAP_F_WRITE : 0) |
 827		(prot & IOMMU_MMIO ? VIRTIO_IOMMU_MAP_F_MMIO : 0);
 828
 829	if (flags & ~vdomain->map_flags)
 830		return -EINVAL;
 831
 832	ret = viommu_add_mapping(vdomain, iova, end, paddr, flags);
 833	if (ret)
 834		return ret;
 835
 836	if (vdomain->nr_endpoints) {
 837		map = (struct virtio_iommu_req_map) {
 838			.head.type	= VIRTIO_IOMMU_T_MAP,
 839			.domain		= cpu_to_le32(vdomain->id),
 840			.virt_start	= cpu_to_le64(iova),
 841			.phys_start	= cpu_to_le64(paddr),
 842			.virt_end	= cpu_to_le64(end),
 843			.flags		= cpu_to_le32(flags),
 844		};
 
 
 845
 846		ret = viommu_add_req(vdomain->viommu, &map, sizeof(map));
 847		if (ret) {
 848			viommu_del_mappings(vdomain, iova, end);
 849			return ret;
 850		}
 851	}
 852	if (mapped)
 853		*mapped = size;
 854
 855	return 0;
 856}
 857
 858static size_t viommu_unmap_pages(struct iommu_domain *domain, unsigned long iova,
 859				 size_t pgsize, size_t pgcount,
 860				 struct iommu_iotlb_gather *gather)
 861{
 862	int ret = 0;
 863	size_t unmapped;
 864	struct virtio_iommu_req_unmap unmap;
 865	struct viommu_domain *vdomain = to_viommu_domain(domain);
 866	size_t size = pgsize * pgcount;
 867
 868	unmapped = viommu_del_mappings(vdomain, iova, iova + size - 1);
 869	if (unmapped < size)
 870		return 0;
 871
 872	/* Device already removed all mappings after detach. */
 873	if (!vdomain->nr_endpoints)
 874		return unmapped;
 875
 876	unmap = (struct virtio_iommu_req_unmap) {
 877		.head.type	= VIRTIO_IOMMU_T_UNMAP,
 878		.domain		= cpu_to_le32(vdomain->id),
 879		.virt_start	= cpu_to_le64(iova),
 880		.virt_end	= cpu_to_le64(iova + unmapped - 1),
 881	};
 882
 883	ret = viommu_add_req(vdomain->viommu, &unmap, sizeof(unmap));
 884	return ret ? 0 : unmapped;
 885}
 886
 887static phys_addr_t viommu_iova_to_phys(struct iommu_domain *domain,
 888				       dma_addr_t iova)
 889{
 890	u64 paddr = 0;
 891	unsigned long flags;
 892	struct viommu_mapping *mapping;
 893	struct interval_tree_node *node;
 894	struct viommu_domain *vdomain = to_viommu_domain(domain);
 895
 896	spin_lock_irqsave(&vdomain->mappings_lock, flags);
 897	node = interval_tree_iter_first(&vdomain->mappings, iova, iova);
 898	if (node) {
 899		mapping = container_of(node, struct viommu_mapping, iova);
 900		paddr = mapping->paddr + (iova - mapping->iova.start);
 901	}
 902	spin_unlock_irqrestore(&vdomain->mappings_lock, flags);
 903
 904	return paddr;
 905}
 906
 907static void viommu_iotlb_sync(struct iommu_domain *domain,
 908			      struct iommu_iotlb_gather *gather)
 909{
 910	struct viommu_domain *vdomain = to_viommu_domain(domain);
 911
 912	viommu_sync_req(vdomain->viommu);
 913}
 914
 915static int viommu_iotlb_sync_map(struct iommu_domain *domain,
 916				 unsigned long iova, size_t size)
 917{
 918	struct viommu_domain *vdomain = to_viommu_domain(domain);
 919
 920	/*
 921	 * May be called before the viommu is initialized including
 922	 * while creating direct mapping
 923	 */
 924	if (!vdomain->nr_endpoints)
 925		return 0;
 926	return viommu_sync_req(vdomain->viommu);
 927}
 928
 929static void viommu_flush_iotlb_all(struct iommu_domain *domain)
 930{
 931	struct viommu_domain *vdomain = to_viommu_domain(domain);
 932
 933	/*
 934	 * May be called before the viommu is initialized including
 935	 * while creating direct mapping
 936	 */
 937	if (!vdomain->nr_endpoints)
 938		return;
 939	viommu_sync_req(vdomain->viommu);
 940}
 941
 942static void viommu_get_resv_regions(struct device *dev, struct list_head *head)
 943{
 944	struct iommu_resv_region *entry, *new_entry, *msi = NULL;
 945	struct viommu_endpoint *vdev = dev_iommu_priv_get(dev);
 946	int prot = IOMMU_WRITE | IOMMU_NOEXEC | IOMMU_MMIO;
 947
 948	list_for_each_entry(entry, &vdev->resv_regions, list) {
 949		if (entry->type == IOMMU_RESV_MSI)
 950			msi = entry;
 951
 952		new_entry = kmemdup(entry, sizeof(*entry), GFP_KERNEL);
 953		if (!new_entry)
 954			return;
 955		list_add_tail(&new_entry->list, head);
 956	}
 957
 958	/*
 959	 * If the device didn't register any bypass MSI window, add a
 960	 * software-mapped region.
 961	 */
 962	if (!msi) {
 963		msi = iommu_alloc_resv_region(MSI_IOVA_BASE, MSI_IOVA_LENGTH,
 964					      prot, IOMMU_RESV_SW_MSI,
 965					      GFP_KERNEL);
 966		if (!msi)
 967			return;
 968
 969		list_add_tail(&msi->list, head);
 970	}
 971
 972	iommu_dma_get_resv_regions(dev, head);
 973}
 974
 975static struct iommu_ops viommu_ops;
 976static struct virtio_driver virtio_iommu_drv;
 977
 978static int viommu_match_node(struct device *dev, const void *data)
 979{
 980	return device_match_fwnode(dev->parent, data);
 981}
 982
 983static struct viommu_dev *viommu_get_by_fwnode(struct fwnode_handle *fwnode)
 984{
 985	struct device *dev = driver_find_device(&virtio_iommu_drv.driver, NULL,
 986						fwnode, viommu_match_node);
 987	put_device(dev);
 988
 989	return dev ? dev_to_virtio(dev)->priv : NULL;
 990}
 991
 992static struct iommu_device *viommu_probe_device(struct device *dev)
 993{
 994	int ret;
 995	struct viommu_endpoint *vdev;
 996	struct viommu_dev *viommu = NULL;
 997	struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
 998
 
 
 
 999	viommu = viommu_get_by_fwnode(fwspec->iommu_fwnode);
1000	if (!viommu)
1001		return ERR_PTR(-ENODEV);
1002
1003	vdev = kzalloc(sizeof(*vdev), GFP_KERNEL);
1004	if (!vdev)
1005		return ERR_PTR(-ENOMEM);
1006
1007	vdev->dev = dev;
1008	vdev->viommu = viommu;
1009	INIT_LIST_HEAD(&vdev->resv_regions);
1010	dev_iommu_priv_set(dev, vdev);
1011
1012	if (viommu->probe_size) {
1013		/* Get additional information for this endpoint */
1014		ret = viommu_probe_endpoint(viommu, dev);
1015		if (ret)
1016			goto err_free_dev;
1017	}
1018
1019	return &viommu->iommu;
1020
1021err_free_dev:
1022	iommu_put_resv_regions(dev, &vdev->resv_regions);
1023	kfree(vdev);
1024
1025	return ERR_PTR(ret);
1026}
1027
1028static void viommu_probe_finalize(struct device *dev)
1029{
1030#ifndef CONFIG_ARCH_HAS_SETUP_DMA_OPS
1031	/* First clear the DMA ops in case we're switching from a DMA domain */
1032	set_dma_ops(dev, NULL);
1033	iommu_setup_dma_ops(dev, 0, U64_MAX);
1034#endif
1035}
1036
1037static void viommu_release_device(struct device *dev)
1038{
1039	struct viommu_endpoint *vdev = dev_iommu_priv_get(dev);
1040
1041	viommu_detach_dev(vdev);
1042	iommu_put_resv_regions(dev, &vdev->resv_regions);
1043	kfree(vdev);
1044}
1045
1046static struct iommu_group *viommu_device_group(struct device *dev)
1047{
1048	if (dev_is_pci(dev))
1049		return pci_device_group(dev);
1050	else
1051		return generic_device_group(dev);
1052}
1053
1054static int viommu_of_xlate(struct device *dev,
1055			   const struct of_phandle_args *args)
1056{
1057	return iommu_fwspec_add_ids(dev, args->args, 1);
1058}
1059
1060static bool viommu_capable(struct device *dev, enum iommu_cap cap)
1061{
1062	switch (cap) {
1063	case IOMMU_CAP_CACHE_COHERENCY:
1064		return true;
1065	case IOMMU_CAP_DEFERRED_FLUSH:
1066		return true;
1067	default:
1068		return false;
1069	}
1070}
1071
1072static struct iommu_ops viommu_ops = {
1073	.capable		= viommu_capable,
1074	.domain_alloc		= viommu_domain_alloc,
 
 
 
 
 
 
1075	.probe_device		= viommu_probe_device,
1076	.probe_finalize		= viommu_probe_finalize,
1077	.release_device		= viommu_release_device,
1078	.device_group		= viommu_device_group,
1079	.get_resv_regions	= viommu_get_resv_regions,
 
1080	.of_xlate		= viommu_of_xlate,
1081	.owner			= THIS_MODULE,
1082	.default_domain_ops = &(const struct iommu_domain_ops) {
1083		.attach_dev		= viommu_attach_dev,
1084		.map_pages		= viommu_map_pages,
1085		.unmap_pages		= viommu_unmap_pages,
1086		.iova_to_phys		= viommu_iova_to_phys,
1087		.flush_iotlb_all	= viommu_flush_iotlb_all,
1088		.iotlb_sync		= viommu_iotlb_sync,
1089		.iotlb_sync_map		= viommu_iotlb_sync_map,
1090		.free			= viommu_domain_free,
1091	}
1092};
1093
1094static int viommu_init_vqs(struct viommu_dev *viommu)
1095{
1096	struct virtio_device *vdev = dev_to_virtio(viommu->dev);
1097	const char *names[] = { "request", "event" };
1098	vq_callback_t *callbacks[] = {
1099		NULL, /* No async requests */
1100		viommu_event_handler,
1101	};
1102
1103	return virtio_find_vqs(vdev, VIOMMU_NR_VQS, viommu->vqs, callbacks,
1104			       names, NULL);
1105}
1106
1107static int viommu_fill_evtq(struct viommu_dev *viommu)
1108{
1109	int i, ret;
1110	struct scatterlist sg[1];
1111	struct viommu_event *evts;
1112	struct virtqueue *vq = viommu->vqs[VIOMMU_EVENT_VQ];
1113	size_t nr_evts = vq->num_free;
1114
1115	viommu->evts = evts = devm_kmalloc_array(viommu->dev, nr_evts,
1116						 sizeof(*evts), GFP_KERNEL);
1117	if (!evts)
1118		return -ENOMEM;
1119
1120	for (i = 0; i < nr_evts; i++) {
1121		sg_init_one(sg, &evts[i], sizeof(*evts));
1122		ret = virtqueue_add_inbuf(vq, sg, 1, &evts[i], GFP_KERNEL);
1123		if (ret)
1124			return ret;
1125	}
1126
1127	return 0;
1128}
1129
1130static int viommu_probe(struct virtio_device *vdev)
1131{
1132	struct device *parent_dev = vdev->dev.parent;
1133	struct viommu_dev *viommu = NULL;
1134	struct device *dev = &vdev->dev;
1135	u64 input_start = 0;
1136	u64 input_end = -1UL;
1137	int ret;
1138
1139	if (!virtio_has_feature(vdev, VIRTIO_F_VERSION_1) ||
1140	    !virtio_has_feature(vdev, VIRTIO_IOMMU_F_MAP_UNMAP))
1141		return -ENODEV;
1142
1143	viommu = devm_kzalloc(dev, sizeof(*viommu), GFP_KERNEL);
1144	if (!viommu)
1145		return -ENOMEM;
1146
1147	spin_lock_init(&viommu->request_lock);
1148	ida_init(&viommu->domain_ids);
1149	viommu->dev = dev;
1150	viommu->vdev = vdev;
1151	INIT_LIST_HEAD(&viommu->requests);
1152
1153	ret = viommu_init_vqs(viommu);
1154	if (ret)
1155		return ret;
1156
1157	virtio_cread_le(vdev, struct virtio_iommu_config, page_size_mask,
1158			&viommu->pgsize_bitmap);
1159
1160	if (!viommu->pgsize_bitmap) {
1161		ret = -EINVAL;
1162		goto err_free_vqs;
1163	}
1164
1165	viommu->map_flags = VIRTIO_IOMMU_MAP_F_READ | VIRTIO_IOMMU_MAP_F_WRITE;
1166	viommu->last_domain = ~0U;
1167
1168	/* Optional features */
1169	virtio_cread_le_feature(vdev, VIRTIO_IOMMU_F_INPUT_RANGE,
1170				struct virtio_iommu_config, input_range.start,
1171				&input_start);
1172
1173	virtio_cread_le_feature(vdev, VIRTIO_IOMMU_F_INPUT_RANGE,
1174				struct virtio_iommu_config, input_range.end,
1175				&input_end);
1176
1177	virtio_cread_le_feature(vdev, VIRTIO_IOMMU_F_DOMAIN_RANGE,
1178				struct virtio_iommu_config, domain_range.start,
1179				&viommu->first_domain);
1180
1181	virtio_cread_le_feature(vdev, VIRTIO_IOMMU_F_DOMAIN_RANGE,
1182				struct virtio_iommu_config, domain_range.end,
1183				&viommu->last_domain);
1184
1185	virtio_cread_le_feature(vdev, VIRTIO_IOMMU_F_PROBE,
1186				struct virtio_iommu_config, probe_size,
1187				&viommu->probe_size);
1188
1189	viommu->geometry = (struct iommu_domain_geometry) {
1190		.aperture_start	= input_start,
1191		.aperture_end	= input_end,
1192		.force_aperture	= true,
1193	};
1194
1195	if (virtio_has_feature(vdev, VIRTIO_IOMMU_F_MMIO))
1196		viommu->map_flags |= VIRTIO_IOMMU_MAP_F_MMIO;
1197
1198	viommu_ops.pgsize_bitmap = viommu->pgsize_bitmap;
1199
1200	virtio_device_ready(vdev);
1201
1202	/* Populate the event queue with buffers */
1203	ret = viommu_fill_evtq(viommu);
1204	if (ret)
1205		goto err_free_vqs;
1206
1207	ret = iommu_device_sysfs_add(&viommu->iommu, dev, NULL, "%s",
1208				     virtio_bus_name(vdev));
1209	if (ret)
1210		goto err_free_vqs;
1211
1212	iommu_device_register(&viommu->iommu, &viommu_ops, parent_dev);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1213
1214	vdev->priv = viommu;
1215
1216	dev_info(dev, "input address: %u bits\n",
1217		 order_base_2(viommu->geometry.aperture_end));
1218	dev_info(dev, "page mask: %#llx\n", viommu->pgsize_bitmap);
1219
1220	return 0;
1221
 
 
 
1222err_free_vqs:
1223	vdev->config->del_vqs(vdev);
1224
1225	return ret;
1226}
1227
1228static void viommu_remove(struct virtio_device *vdev)
1229{
1230	struct viommu_dev *viommu = vdev->priv;
1231
1232	iommu_device_sysfs_remove(&viommu->iommu);
1233	iommu_device_unregister(&viommu->iommu);
1234
1235	/* Stop all virtqueues */
1236	virtio_reset_device(vdev);
1237	vdev->config->del_vqs(vdev);
1238
1239	dev_info(&vdev->dev, "device removed\n");
1240}
1241
1242static void viommu_config_changed(struct virtio_device *vdev)
1243{
1244	dev_warn(&vdev->dev, "config changed\n");
1245}
1246
1247static unsigned int features[] = {
1248	VIRTIO_IOMMU_F_MAP_UNMAP,
1249	VIRTIO_IOMMU_F_INPUT_RANGE,
1250	VIRTIO_IOMMU_F_DOMAIN_RANGE,
1251	VIRTIO_IOMMU_F_PROBE,
1252	VIRTIO_IOMMU_F_MMIO,
1253	VIRTIO_IOMMU_F_BYPASS_CONFIG,
1254};
1255
1256static struct virtio_device_id id_table[] = {
1257	{ VIRTIO_ID_IOMMU, VIRTIO_DEV_ANY_ID },
1258	{ 0 },
1259};
1260MODULE_DEVICE_TABLE(virtio, id_table);
1261
1262static struct virtio_driver virtio_iommu_drv = {
1263	.driver.name		= KBUILD_MODNAME,
1264	.driver.owner		= THIS_MODULE,
1265	.id_table		= id_table,
1266	.feature_table		= features,
1267	.feature_table_size	= ARRAY_SIZE(features),
1268	.probe			= viommu_probe,
1269	.remove			= viommu_remove,
1270	.config_changed		= viommu_config_changed,
1271};
1272
1273module_virtio_driver(virtio_iommu_drv);
1274
1275MODULE_DESCRIPTION("Virtio IOMMU driver");
1276MODULE_AUTHOR("Jean-Philippe Brucker <jean-philippe.brucker@arm.com>");
1277MODULE_LICENSE("GPL v2");