xref: /linux/drivers/iommu/iommufd/main.c (revision 9cebfe6504488198b012e746bc6b313f88b95439)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (C) 2021 Intel Corporation
3  * Copyright (c) 2021-2022, NVIDIA CORPORATION & AFFILIATES
4  *
5  * iommufd provides control over the IOMMU HW objects created by IOMMU kernel
6  * drivers. IOMMU HW objects revolve around IO page tables that map incoming DMA
7  * addresses (IOVA) to CPU addresses.
8  */
9 #define pr_fmt(fmt) "iommufd: " fmt
10 
11 #include <linux/bug.h>
12 #include <linux/file.h>
13 #include <linux/fs.h>
14 #include <linux/iommufd.h>
15 #include <linux/miscdevice.h>
16 #include <linux/module.h>
17 #include <linux/mutex.h>
18 #include <linux/slab.h>
19 #include <uapi/linux/iommufd.h>
20 
21 #include "io_pagetable.h"
22 #include "iommufd_private.h"
23 #include "iommufd_test.h"
24 
25 struct iommufd_object_ops {
26 	size_t file_offset;
27 	void (*pre_destroy)(struct iommufd_object *obj);
28 	void (*destroy)(struct iommufd_object *obj);
29 	void (*abort)(struct iommufd_object *obj);
30 };
31 static const struct iommufd_object_ops iommufd_object_ops[];
32 static struct miscdevice vfio_misc_dev;
33 
34 struct iommufd_object *_iommufd_object_alloc(struct iommufd_ctx *ictx,
35 					     size_t size,
36 					     enum iommufd_object_type type)
37 {
38 	struct iommufd_object *obj;
39 	int rc;
40 
41 	obj = kzalloc(size, GFP_KERNEL_ACCOUNT);
42 	if (!obj)
43 		return ERR_PTR(-ENOMEM);
44 	obj->type = type;
45 	/* Starts out bias'd by 1 until it is removed from the xarray */
46 	refcount_set(&obj->wait_cnt, 1);
47 	refcount_set(&obj->users, 1);
48 
49 	/*
50 	 * Reserve an ID in the xarray but do not publish the pointer yet since
51 	 * the caller hasn't initialized it yet. Once the pointer is published
52 	 * in the xarray and visible to other threads we can't reliably destroy
53 	 * it anymore, so the caller must complete all errorable operations
54 	 * before calling iommufd_object_finalize().
55 	 */
56 	rc = xa_alloc(&ictx->objects, &obj->id, XA_ZERO_ENTRY, xa_limit_31b,
57 		      GFP_KERNEL_ACCOUNT);
58 	if (rc)
59 		goto out_free;
60 	return obj;
61 out_free:
62 	kfree(obj);
63 	return ERR_PTR(rc);
64 }
65 
66 struct iommufd_object *_iommufd_object_alloc_ucmd(struct iommufd_ucmd *ucmd,
67 						  size_t size,
68 						  enum iommufd_object_type type)
69 {
70 	struct iommufd_object *new_obj;
71 
72 	/* Something is coded wrong if this is hit */
73 	if (WARN_ON(ucmd->new_obj))
74 		return ERR_PTR(-EBUSY);
75 
76 	/*
77 	 * An abort op means that its caller needs to invoke it within a lock in
78 	 * the caller. So it doesn't work with _iommufd_object_alloc_ucmd() that
79 	 * will invoke the abort op in iommufd_object_abort_and_destroy(), which
80 	 * must be outside the caller's lock.
81 	 */
82 	if (WARN_ON(iommufd_object_ops[type].abort))
83 		return ERR_PTR(-EOPNOTSUPP);
84 
85 	new_obj = _iommufd_object_alloc(ucmd->ictx, size, type);
86 	if (IS_ERR(new_obj))
87 		return new_obj;
88 
89 	ucmd->new_obj = new_obj;
90 	return new_obj;
91 }
92 
93 /*
94  * Allow concurrent access to the object.
95  *
96  * Once another thread can see the object pointer it can prevent object
97  * destruction. Expect for special kernel-only objects there is no in-kernel way
98  * to reliably destroy a single object. Thus all APIs that are creating objects
99  * must use iommufd_object_abort() to handle their errors and only call
100  * iommufd_object_finalize() once object creation cannot fail.
101  */
102 void iommufd_object_finalize(struct iommufd_ctx *ictx,
103 			     struct iommufd_object *obj)
104 {
105 	XA_STATE(xas, &ictx->objects, obj->id);
106 	void *old;
107 
108 	xa_lock(&ictx->objects);
109 	old = xas_store(&xas, obj);
110 	xa_unlock(&ictx->objects);
111 	/* obj->id was returned from xa_alloc() so the xas_store() cannot fail */
112 	WARN_ON(old != XA_ZERO_ENTRY);
113 }
114 
115 /* Undo _iommufd_object_alloc() if iommufd_object_finalize() was not called */
116 void iommufd_object_abort(struct iommufd_ctx *ictx, struct iommufd_object *obj)
117 {
118 	XA_STATE(xas, &ictx->objects, obj->id);
119 	void *old;
120 
121 	xa_lock(&ictx->objects);
122 	old = xas_store(&xas, NULL);
123 	xa_unlock(&ictx->objects);
124 	WARN_ON(old != XA_ZERO_ENTRY);
125 
126 	if (WARN_ON(!refcount_dec_and_test(&obj->users)))
127 		return;
128 
129 	kfree(obj);
130 }
131 
132 /*
133  * Abort an object that has been fully initialized and needs destroy, but has
134  * not been finalized.
135  */
136 void iommufd_object_abort_and_destroy(struct iommufd_ctx *ictx,
137 				      struct iommufd_object *obj)
138 {
139 	const struct iommufd_object_ops *ops = &iommufd_object_ops[obj->type];
140 
141 	if (ops->file_offset) {
142 		struct file **filep = ((void *)obj) + ops->file_offset;
143 
144 		/*
145 		 * A file should hold a users refcount while the file is open
146 		 * and put it back in its release. The file should hold a
147 		 * pointer to obj in their private data. Normal fput() is
148 		 * deferred to a workqueue and can get out of order with the
149 		 * following kfree(obj). Using the sync version ensures the
150 		 * release happens immediately. During abort we require the file
151 		 * refcount is one at this point - meaning the object alloc
152 		 * function cannot do anything to allow another thread to take a
153 		 * refcount prior to a guaranteed success.
154 		 */
155 		if (*filep)
156 			__fput_sync(*filep);
157 	}
158 
159 	if (ops->abort)
160 		ops->abort(obj);
161 	else
162 		ops->destroy(obj);
163 	iommufd_object_abort(ictx, obj);
164 }
165 
166 struct iommufd_object *iommufd_get_object(struct iommufd_ctx *ictx, u32 id,
167 					  enum iommufd_object_type type)
168 {
169 	struct iommufd_object *obj;
170 
171 	if (iommufd_should_fail())
172 		return ERR_PTR(-ENOENT);
173 
174 	xa_lock(&ictx->objects);
175 	obj = xa_load(&ictx->objects, id);
176 	if (!obj || (type != IOMMUFD_OBJ_ANY && obj->type != type) ||
177 	    !iommufd_lock_obj(obj))
178 		obj = ERR_PTR(-ENOENT);
179 	xa_unlock(&ictx->objects);
180 	return obj;
181 }
182 
183 /*
184  * Increment the users count of an object outside the context of an ioctl that
185  * has already locked it. The users refcount cannot be increased on an already
186  * created object unless the object is installed in the xarray, otherwise things
187  * are racing with a parallel destruction.
188  */
189 int iommufd_try_inc_users(struct iommufd_ctx *ictx, struct iommufd_object *obj)
190 {
191 	struct iommufd_object *cur;
192 
193 	xa_lock(&ictx->objects);
194 	cur = xa_load(&ictx->objects, obj->id);
195 	if (cur == obj)
196 		refcount_inc(&obj->users);
197 	xa_unlock(&ictx->objects);
198 	if (cur != obj)
199 		return -EBUSY;
200 	return 0;
201 }
202 
203 static int iommufd_object_dec_wait(struct iommufd_ctx *ictx,
204 				   struct iommufd_object *to_destroy)
205 {
206 	if (refcount_dec_and_test(&to_destroy->wait_cnt))
207 		return 0;
208 
209 	if (iommufd_object_ops[to_destroy->type].pre_destroy)
210 		iommufd_object_ops[to_destroy->type].pre_destroy(to_destroy);
211 
212 	if (wait_event_timeout(ictx->destroy_wait,
213 			       refcount_read(&to_destroy->wait_cnt) == 0,
214 			       msecs_to_jiffies(60000)))
215 		return 0;
216 
217 	pr_crit("Time out waiting for iommufd object to become free\n");
218 	refcount_inc(&to_destroy->wait_cnt);
219 	return -EBUSY;
220 }
221 
222 /*
223  * Remove the given object id from the xarray if the only reference to the
224  * object is held by the xarray.
225  */
226 int iommufd_object_remove(struct iommufd_ctx *ictx,
227 			  struct iommufd_object *to_destroy, u32 id,
228 			  unsigned int flags)
229 {
230 	struct iommufd_object *obj;
231 	XA_STATE(xas, &ictx->objects, id);
232 	bool zerod_wait_cnt = false;
233 	int ret;
234 
235 	/*
236 	 * The purpose of the wait_cnt is to ensure deterministic destruction
237 	 * of objects used by external drivers and destroyed by this function.
238 	 * Incrementing this wait_cnt should either be short lived, such as
239 	 * during ioctl execution, or be revoked and blocked during
240 	 * pre_destroy(), such as vdev holding the idev's refcount.
241 	 */
242 	if (flags & REMOVE_WAIT) {
243 		ret = iommufd_object_dec_wait(ictx, to_destroy);
244 		if (ret) {
245 			/*
246 			 * We have a bug. Put back the callers reference and
247 			 * defer cleaning this object until close.
248 			 */
249 			refcount_dec(&to_destroy->users);
250 			return ret;
251 		}
252 		zerod_wait_cnt = true;
253 	}
254 
255 	xa_lock(&ictx->objects);
256 	obj = xas_load(&xas);
257 	if (to_destroy) {
258 		/*
259 		 * If the caller is holding a ref on obj we put it here under
260 		 * the spinlock.
261 		 */
262 		refcount_dec(&obj->users);
263 
264 		if (WARN_ON(obj != to_destroy)) {
265 			ret = -ENOENT;
266 			goto err_xa;
267 		}
268 	} else if (xa_is_zero(obj) || !obj) {
269 		ret = -ENOENT;
270 		goto err_xa;
271 	}
272 
273 	if (!refcount_dec_if_one(&obj->users)) {
274 		ret = -EBUSY;
275 		goto err_xa;
276 	}
277 
278 	xas_store(&xas, (flags & REMOVE_OBJ_TOMBSTONE) ? XA_ZERO_ENTRY : NULL);
279 	if (ictx->vfio_ioas == container_of(obj, struct iommufd_ioas, obj))
280 		ictx->vfio_ioas = NULL;
281 	xa_unlock(&ictx->objects);
282 
283 	/*
284 	 * Since users is zero any positive wait_cnt must be racing
285 	 * iommufd_put_object(), or we have a bug.
286 	 */
287 	if (!zerod_wait_cnt) {
288 		ret = iommufd_object_dec_wait(ictx, obj);
289 		if (WARN_ON(ret))
290 			return ret;
291 	}
292 
293 	iommufd_object_ops[obj->type].destroy(obj);
294 	kfree(obj);
295 	return 0;
296 
297 err_xa:
298 	if (zerod_wait_cnt) {
299 		/* Restore the xarray owned reference */
300 		refcount_set(&obj->wait_cnt, 1);
301 	}
302 	xa_unlock(&ictx->objects);
303 
304 	/* The returned object reference count is zero */
305 	return ret;
306 }
307 
308 static int iommufd_destroy(struct iommufd_ucmd *ucmd)
309 {
310 	struct iommu_destroy *cmd = ucmd->cmd;
311 
312 	return iommufd_object_remove(ucmd->ictx, NULL, cmd->id, 0);
313 }
314 
315 static int iommufd_fops_open(struct inode *inode, struct file *filp)
316 {
317 	struct iommufd_ctx *ictx;
318 
319 	ictx = kzalloc_obj(*ictx, GFP_KERNEL_ACCOUNT);
320 	if (!ictx)
321 		return -ENOMEM;
322 
323 	/*
324 	 * For compatibility with VFIO when /dev/vfio/vfio is opened we default
325 	 * to the same rlimit accounting as vfio uses.
326 	 */
327 	if (IS_ENABLED(CONFIG_IOMMUFD_VFIO_CONTAINER) &&
328 	    filp->private_data == &vfio_misc_dev) {
329 		ictx->account_mode = IOPT_PAGES_ACCOUNT_MM;
330 		pr_info_once("IOMMUFD is providing /dev/vfio/vfio, not VFIO.\n");
331 	}
332 
333 	init_rwsem(&ictx->ioas_creation_lock);
334 	xa_init_flags(&ictx->objects, XA_FLAGS_ALLOC1 | XA_FLAGS_ACCOUNT);
335 	xa_init(&ictx->groups);
336 	ictx->file = filp;
337 	mt_init_flags(&ictx->mt_mmap, MT_FLAGS_ALLOC_RANGE);
338 	init_waitqueue_head(&ictx->destroy_wait);
339 	mutex_init(&ictx->sw_msi_lock);
340 	INIT_LIST_HEAD(&ictx->sw_msi_list);
341 	filp->private_data = ictx;
342 	return 0;
343 }
344 
345 static int iommufd_fops_release(struct inode *inode, struct file *filp)
346 {
347 	struct iommufd_ctx *ictx = filp->private_data;
348 	struct iommufd_sw_msi_map *next;
349 	struct iommufd_sw_msi_map *cur;
350 	struct iommufd_object *obj;
351 
352 	/*
353 	 * The objects in the xarray form a graph of "users" counts, and we have
354 	 * to destroy them in a depth first manner. Leaf objects will reduce the
355 	 * users count of interior objects when they are destroyed.
356 	 *
357 	 * Repeatedly destroying all the "1 users" leaf objects will progress
358 	 * until the entire list is destroyed. If this can't progress then there
359 	 * is some bug related to object refcounting.
360 	 */
361 	while (!xa_empty(&ictx->objects)) {
362 		unsigned int destroyed = 0;
363 		unsigned long index;
364 		bool empty = true;
365 
366 		/*
367 		 * We can't use xa_empty() to end the loop as the tombstones
368 		 * are stored as XA_ZERO_ENTRY in the xarray. However
369 		 * xa_for_each() automatically converts them to NULL and skips
370 		 * them causing xa_empty() to be kept false. Thus once
371 		 * xa_for_each() finds no further !NULL entries the loop is
372 		 * done.
373 		 */
374 		xa_for_each(&ictx->objects, index, obj) {
375 			empty = false;
376 			if (!refcount_dec_if_one(&obj->users))
377 				continue;
378 
379 			destroyed++;
380 			xa_erase(&ictx->objects, index);
381 			iommufd_object_ops[obj->type].destroy(obj);
382 			kfree(obj);
383 		}
384 
385 		if (empty)
386 			break;
387 
388 		/* Bug related to users refcount */
389 		if (WARN_ON(!destroyed))
390 			break;
391 	}
392 
393 	/*
394 	 * There may be some tombstones left over from
395 	 * iommufd_object_tombstone_user()
396 	 */
397 	xa_destroy(&ictx->objects);
398 
399 	WARN_ON(!xa_empty(&ictx->groups));
400 
401 	mutex_destroy(&ictx->sw_msi_lock);
402 	list_for_each_entry_safe(cur, next, &ictx->sw_msi_list, sw_msi_item)
403 		kfree(cur);
404 
405 	kfree(ictx);
406 	return 0;
407 }
408 
409 static int iommufd_option(struct iommufd_ucmd *ucmd)
410 {
411 	struct iommu_option *cmd = ucmd->cmd;
412 	int rc;
413 
414 	if (cmd->__reserved)
415 		return -EOPNOTSUPP;
416 
417 	switch (cmd->option_id) {
418 	case IOMMU_OPTION_RLIMIT_MODE:
419 		rc = iommufd_option_rlimit_mode(cmd, ucmd->ictx);
420 		break;
421 	case IOMMU_OPTION_HUGE_PAGES:
422 		rc = iommufd_ioas_option(ucmd);
423 		break;
424 	default:
425 		return -EOPNOTSUPP;
426 	}
427 	if (rc)
428 		return rc;
429 	if (copy_to_user(&((struct iommu_option __user *)ucmd->ubuffer)->val64,
430 			 &cmd->val64, sizeof(cmd->val64)))
431 		return -EFAULT;
432 	return 0;
433 }
434 
435 union ucmd_buffer {
436 	struct iommu_destroy destroy;
437 	struct iommu_fault_alloc fault;
438 	struct iommu_hw_info info;
439 	struct iommu_hw_queue_alloc hw_queue;
440 	struct iommu_hwpt_alloc hwpt;
441 	struct iommu_hwpt_get_dirty_bitmap get_dirty_bitmap;
442 	struct iommu_hwpt_invalidate cache;
443 	struct iommu_hwpt_set_dirty_tracking set_dirty_tracking;
444 	struct iommu_ioas_alloc alloc;
445 	struct iommu_ioas_allow_iovas allow_iovas;
446 	struct iommu_ioas_copy ioas_copy;
447 	struct iommu_ioas_noiommu_get_pa noiommu_get_pa;
448 	struct iommu_ioas_iova_ranges iova_ranges;
449 	struct iommu_ioas_map map;
450 	struct iommu_ioas_unmap unmap;
451 	struct iommu_option option;
452 	struct iommu_vdevice_alloc vdev;
453 	struct iommu_veventq_alloc veventq;
454 	struct iommu_vfio_ioas vfio_ioas;
455 	struct iommu_viommu_alloc viommu;
456 #ifdef CONFIG_IOMMUFD_TEST
457 	struct iommu_test_cmd test;
458 #endif
459 };
460 
461 struct iommufd_ioctl_op {
462 	unsigned int size;
463 	unsigned int min_size;
464 	unsigned int ioctl_num;
465 	int (*execute)(struct iommufd_ucmd *ucmd);
466 };
467 
468 #define IOCTL_OP(_ioctl, _fn, _struct, _last)                                  \
469 	[_IOC_NR(_ioctl) - IOMMUFD_CMD_BASE] = {                               \
470 		.size = sizeof(_struct) +                                      \
471 			BUILD_BUG_ON_ZERO(sizeof(union ucmd_buffer) <          \
472 					  sizeof(_struct)),                    \
473 		.min_size = offsetofend(_struct, _last),                       \
474 		.ioctl_num = _ioctl,                                           \
475 		.execute = _fn,                                                \
476 	}
477 static const struct iommufd_ioctl_op iommufd_ioctl_ops[] = {
478 	IOCTL_OP(IOMMU_DESTROY, iommufd_destroy, struct iommu_destroy, id),
479 	IOCTL_OP(IOMMU_FAULT_QUEUE_ALLOC, iommufd_fault_alloc,
480 		 struct iommu_fault_alloc, out_fault_fd),
481 	IOCTL_OP(IOMMU_GET_HW_INFO, iommufd_get_hw_info, struct iommu_hw_info,
482 		 __reserved),
483 	IOCTL_OP(IOMMU_HW_QUEUE_ALLOC, iommufd_hw_queue_alloc_ioctl,
484 		 struct iommu_hw_queue_alloc, length),
485 	IOCTL_OP(IOMMU_HWPT_ALLOC, iommufd_hwpt_alloc, struct iommu_hwpt_alloc,
486 		 __reserved),
487 	IOCTL_OP(IOMMU_HWPT_GET_DIRTY_BITMAP, iommufd_hwpt_get_dirty_bitmap,
488 		 struct iommu_hwpt_get_dirty_bitmap, data),
489 	IOCTL_OP(IOMMU_HWPT_INVALIDATE, iommufd_hwpt_invalidate,
490 		 struct iommu_hwpt_invalidate, __reserved),
491 	IOCTL_OP(IOMMU_HWPT_SET_DIRTY_TRACKING, iommufd_hwpt_set_dirty_tracking,
492 		 struct iommu_hwpt_set_dirty_tracking, __reserved),
493 	IOCTL_OP(IOMMU_IOAS_ALLOC, iommufd_ioas_alloc_ioctl,
494 		 struct iommu_ioas_alloc, out_ioas_id),
495 	IOCTL_OP(IOMMU_IOAS_ALLOW_IOVAS, iommufd_ioas_allow_iovas,
496 		 struct iommu_ioas_allow_iovas, allowed_iovas),
497 	IOCTL_OP(IOMMU_IOAS_CHANGE_PROCESS, iommufd_ioas_change_process,
498 		 struct iommu_ioas_change_process, __reserved),
499 	IOCTL_OP(IOMMU_IOAS_COPY, iommufd_ioas_copy, struct iommu_ioas_copy,
500 		 src_iova),
501 	IOCTL_OP(IOMMU_IOAS_IOVA_RANGES, iommufd_ioas_iova_ranges,
502 		 struct iommu_ioas_iova_ranges, out_iova_alignment),
503 	IOCTL_OP(IOMMU_IOAS_MAP, iommufd_ioas_map, struct iommu_ioas_map, iova),
504 	IOCTL_OP(IOMMU_IOAS_MAP_FILE, iommufd_ioas_map_file,
505 		 struct iommu_ioas_map_file, iova),
506 	IOCTL_OP(IOMMU_IOAS_NOIOMMU_GET_PA, iommufd_ioas_noiommu_get_pa, struct iommu_ioas_noiommu_get_pa,
507 		 out_phys),
508 	IOCTL_OP(IOMMU_IOAS_UNMAP, iommufd_ioas_unmap, struct iommu_ioas_unmap,
509 		 length),
510 	IOCTL_OP(IOMMU_OPTION, iommufd_option, struct iommu_option, val64),
511 	IOCTL_OP(IOMMU_VDEVICE_ALLOC, iommufd_vdevice_alloc_ioctl,
512 		 struct iommu_vdevice_alloc, virt_id),
513 	IOCTL_OP(IOMMU_VEVENTQ_ALLOC, iommufd_veventq_alloc,
514 		 struct iommu_veventq_alloc, out_veventq_fd),
515 	IOCTL_OP(IOMMU_VFIO_IOAS, iommufd_vfio_ioas, struct iommu_vfio_ioas,
516 		 __reserved),
517 	IOCTL_OP(IOMMU_VIOMMU_ALLOC, iommufd_viommu_alloc_ioctl,
518 		 struct iommu_viommu_alloc, out_viommu_id),
519 #ifdef CONFIG_IOMMUFD_TEST
520 	IOCTL_OP(IOMMU_TEST_CMD, iommufd_test, struct iommu_test_cmd, last),
521 #endif
522 };
523 
524 static long iommufd_fops_ioctl(struct file *filp, unsigned int cmd,
525 			       unsigned long arg)
526 {
527 	struct iommufd_ctx *ictx = filp->private_data;
528 	const struct iommufd_ioctl_op *op;
529 	struct iommufd_ucmd ucmd = {};
530 	union ucmd_buffer buf;
531 	unsigned int nr;
532 	int ret;
533 
534 	nr = _IOC_NR(cmd);
535 	if (nr < IOMMUFD_CMD_BASE ||
536 	    (nr - IOMMUFD_CMD_BASE) >= ARRAY_SIZE(iommufd_ioctl_ops))
537 		return iommufd_vfio_ioctl(ictx, cmd, arg);
538 
539 	ucmd.ictx = ictx;
540 	ucmd.ubuffer = (void __user *)arg;
541 	ret = get_user(ucmd.user_size, (u32 __user *)ucmd.ubuffer);
542 	if (ret)
543 		return ret;
544 
545 	op = &iommufd_ioctl_ops[nr - IOMMUFD_CMD_BASE];
546 	if (op->ioctl_num != cmd)
547 		return -ENOIOCTLCMD;
548 	if (ucmd.user_size < op->min_size)
549 		return -EINVAL;
550 
551 	ucmd.cmd = &buf;
552 	ret = copy_struct_from_user(ucmd.cmd, op->size, ucmd.ubuffer,
553 				    ucmd.user_size);
554 	if (ret)
555 		return ret;
556 	ret = op->execute(&ucmd);
557 
558 	if (ucmd.new_obj) {
559 		if (ret)
560 			iommufd_object_abort_and_destroy(ictx, ucmd.new_obj);
561 		else
562 			iommufd_object_finalize(ictx, ucmd.new_obj);
563 	}
564 	return ret;
565 }
566 
567 static void iommufd_fops_vma_open(struct vm_area_struct *vma)
568 {
569 	struct iommufd_mmap *immap = vma->vm_private_data;
570 
571 	refcount_inc(&immap->owner->users);
572 }
573 
574 static void iommufd_fops_vma_close(struct vm_area_struct *vma)
575 {
576 	struct iommufd_mmap *immap = vma->vm_private_data;
577 
578 	refcount_dec(&immap->owner->users);
579 }
580 
581 static const struct vm_operations_struct iommufd_vma_ops = {
582 	.open = iommufd_fops_vma_open,
583 	.close = iommufd_fops_vma_close,
584 };
585 
586 /* The vm_pgoff must be pre-allocated from mt_mmap, and given to user space */
587 static int iommufd_fops_mmap(struct file *filp, struct vm_area_struct *vma)
588 {
589 	struct iommufd_ctx *ictx = filp->private_data;
590 	size_t length = vma->vm_end - vma->vm_start;
591 	struct iommufd_mmap *immap;
592 	int rc;
593 
594 	if (!PAGE_ALIGNED(length))
595 		return -EINVAL;
596 	if (!(vma->vm_flags & VM_SHARED))
597 		return -EINVAL;
598 	if (vma->vm_flags & VM_EXEC)
599 		return -EPERM;
600 
601 	mtree_lock(&ictx->mt_mmap);
602 	/* vma->vm_pgoff carries a page-shifted start position to an immap */
603 	immap = mtree_load(&ictx->mt_mmap, vma->vm_pgoff << PAGE_SHIFT);
604 	if (!immap || !refcount_inc_not_zero(&immap->owner->users)) {
605 		mtree_unlock(&ictx->mt_mmap);
606 		return -ENXIO;
607 	}
608 	mtree_unlock(&ictx->mt_mmap);
609 
610 	/*
611 	 * mtree_load() returns the immap for any contained mmio_addr, so only
612 	 * allow the exact immap thing to be mapped
613 	 */
614 	if (vma->vm_pgoff != immap->vm_pgoff || length != immap->length) {
615 		rc = -ENXIO;
616 		goto err_refcount;
617 	}
618 
619 	vma->vm_pgoff = 0;
620 	vma->vm_private_data = immap;
621 	vma->vm_ops = &iommufd_vma_ops;
622 	vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
623 
624 	rc = io_remap_pfn_range(vma, vma->vm_start,
625 				immap->mmio_addr >> PAGE_SHIFT, length,
626 				vma->vm_page_prot);
627 	if (rc)
628 		goto err_refcount;
629 	return 0;
630 
631 err_refcount:
632 	refcount_dec(&immap->owner->users);
633 	return rc;
634 }
635 
636 static const struct file_operations iommufd_fops = {
637 	.owner = THIS_MODULE,
638 	.open = iommufd_fops_open,
639 	.release = iommufd_fops_release,
640 	.unlocked_ioctl = iommufd_fops_ioctl,
641 	.mmap = iommufd_fops_mmap,
642 };
643 
644 /**
645  * iommufd_ctx_get - Get a context reference
646  * @ictx: Context to get
647  *
648  * The caller must already hold a valid reference to ictx.
649  */
650 void iommufd_ctx_get(struct iommufd_ctx *ictx)
651 {
652 	get_file(ictx->file);
653 }
654 EXPORT_SYMBOL_NS_GPL(iommufd_ctx_get, "IOMMUFD");
655 
656 /**
657  * iommufd_ctx_from_file - Acquires a reference to the iommufd context
658  * @file: File to obtain the reference from
659  *
660  * Returns a pointer to the iommufd_ctx, otherwise ERR_PTR. The struct file
661  * remains owned by the caller and the caller must still do fput. On success
662  * the caller is responsible to call iommufd_ctx_put().
663  */
664 struct iommufd_ctx *iommufd_ctx_from_file(struct file *file)
665 {
666 	struct iommufd_ctx *ictx;
667 
668 	if (file->f_op != &iommufd_fops)
669 		return ERR_PTR(-EBADFD);
670 	ictx = file->private_data;
671 	iommufd_ctx_get(ictx);
672 	return ictx;
673 }
674 EXPORT_SYMBOL_NS_GPL(iommufd_ctx_from_file, "IOMMUFD");
675 
676 /**
677  * iommufd_ctx_from_fd - Acquires a reference to the iommufd context
678  * @fd: File descriptor to obtain the reference from
679  *
680  * Returns a pointer to the iommufd_ctx, otherwise ERR_PTR. On success
681  * the caller is responsible to call iommufd_ctx_put().
682  */
683 struct iommufd_ctx *iommufd_ctx_from_fd(int fd)
684 {
685 	struct file *file;
686 
687 	file = fget(fd);
688 	if (!file)
689 		return ERR_PTR(-EBADF);
690 
691 	if (file->f_op != &iommufd_fops) {
692 		fput(file);
693 		return ERR_PTR(-EBADFD);
694 	}
695 	/* fget is the same as iommufd_ctx_get() */
696 	return file->private_data;
697 }
698 EXPORT_SYMBOL_NS_GPL(iommufd_ctx_from_fd, "IOMMUFD");
699 
700 /**
701  * iommufd_ctx_put - Put back a reference
702  * @ictx: Context to put back
703  */
704 void iommufd_ctx_put(struct iommufd_ctx *ictx)
705 {
706 	fput(ictx->file);
707 }
708 EXPORT_SYMBOL_NS_GPL(iommufd_ctx_put, "IOMMUFD");
709 
710 #define IOMMUFD_FILE_OFFSET(_struct, _filep, _obj)                           \
711 	.file_offset = (offsetof(_struct, _filep) +                          \
712 			BUILD_BUG_ON_ZERO(!__same_type(                      \
713 				struct file *, ((_struct *)NULL)->_filep)) + \
714 			BUILD_BUG_ON_ZERO(offsetof(_struct, _obj)))
715 
716 static const struct iommufd_object_ops iommufd_object_ops[] = {
717 	[IOMMUFD_OBJ_ACCESS] = {
718 		.destroy = iommufd_access_destroy_object,
719 	},
720 	[IOMMUFD_OBJ_DEVICE] = {
721 		.pre_destroy = iommufd_device_pre_destroy,
722 		.destroy = iommufd_device_destroy,
723 	},
724 	[IOMMUFD_OBJ_FAULT] = {
725 		.destroy = iommufd_fault_destroy,
726 		IOMMUFD_FILE_OFFSET(struct iommufd_fault, common.filep, common.obj),
727 	},
728 	[IOMMUFD_OBJ_HW_QUEUE] = {
729 		.destroy = iommufd_hw_queue_destroy,
730 	},
731 	[IOMMUFD_OBJ_HWPT_PAGING] = {
732 		.destroy = iommufd_hwpt_paging_destroy,
733 		.abort = iommufd_hwpt_paging_abort,
734 	},
735 	[IOMMUFD_OBJ_HWPT_NESTED] = {
736 		.destroy = iommufd_hwpt_nested_destroy,
737 		.abort = iommufd_hwpt_nested_abort,
738 	},
739 	[IOMMUFD_OBJ_IOAS] = {
740 		.destroy = iommufd_ioas_destroy,
741 	},
742 	[IOMMUFD_OBJ_VDEVICE] = {
743 		.destroy = iommufd_vdevice_destroy,
744 		.abort = iommufd_vdevice_abort,
745 	},
746 	[IOMMUFD_OBJ_VEVENTQ] = {
747 		.destroy = iommufd_veventq_destroy,
748 		.abort = iommufd_veventq_abort,
749 		IOMMUFD_FILE_OFFSET(struct iommufd_veventq, common.filep, common.obj),
750 	},
751 	[IOMMUFD_OBJ_VIOMMU] = {
752 		.destroy = iommufd_viommu_destroy,
753 	},
754 #ifdef CONFIG_IOMMUFD_TEST
755 	[IOMMUFD_OBJ_SELFTEST] = {
756 		.destroy = iommufd_selftest_destroy,
757 	},
758 #endif
759 };
760 
761 static struct miscdevice iommu_misc_dev = {
762 	.minor = MISC_DYNAMIC_MINOR,
763 	.name = "iommu",
764 	.fops = &iommufd_fops,
765 	.nodename = "iommu",
766 	.mode = 0660,
767 };
768 
769 static struct miscdevice vfio_misc_dev = {
770 	.minor = VFIO_MINOR,
771 	.name = "vfio",
772 	.fops = &iommufd_fops,
773 	.nodename = "vfio/vfio",
774 	.mode = 0666,
775 };
776 
777 /*
778  * Used only by DMABUF, returns a valid struct device to use as a dummy struct
779  * device for attachment.
780  */
781 struct device *iommufd_global_device(void)
782 {
783 	return iommu_misc_dev.this_device;
784 }
785 
786 static int __init iommufd_init(void)
787 {
788 	int ret;
789 
790 	ret = misc_register(&iommu_misc_dev);
791 	if (ret)
792 		return ret;
793 
794 	if (IS_ENABLED(CONFIG_IOMMUFD_VFIO_CONTAINER)) {
795 		ret = misc_register(&vfio_misc_dev);
796 		if (ret)
797 			goto err_misc;
798 	}
799 	ret = iommufd_test_init();
800 	if (ret)
801 		goto err_vfio_misc;
802 	return 0;
803 
804 err_vfio_misc:
805 	if (IS_ENABLED(CONFIG_IOMMUFD_VFIO_CONTAINER))
806 		misc_deregister(&vfio_misc_dev);
807 err_misc:
808 	misc_deregister(&iommu_misc_dev);
809 	return ret;
810 }
811 
812 static void __exit iommufd_exit(void)
813 {
814 	iommufd_test_exit();
815 	if (IS_ENABLED(CONFIG_IOMMUFD_VFIO_CONTAINER))
816 		misc_deregister(&vfio_misc_dev);
817 	misc_deregister(&iommu_misc_dev);
818 }
819 
820 module_init(iommufd_init);
821 module_exit(iommufd_exit);
822 
823 #if IS_ENABLED(CONFIG_IOMMUFD_VFIO_CONTAINER)
824 MODULE_ALIAS_MISCDEV(VFIO_MINOR);
825 MODULE_ALIAS("devname:vfio/vfio");
826 #endif
827 MODULE_IMPORT_NS("IOMMUFD_INTERNAL");
828 MODULE_IMPORT_NS("IOMMUFD");
829 MODULE_IMPORT_NS("DMA_BUF");
830 MODULE_IMPORT_NS("GENERIC_PT_IOMMU");
831 MODULE_DESCRIPTION("I/O Address Space Management for passthrough devices");
832 MODULE_LICENSE("GPL");
833