• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * SPDX-License-Identifier: MIT
3  *
4  * Copyright © 2014-2016 Intel Corporation
5  */
6 
7 #include <linux/anon_inodes.h>
8 #include <linux/mman.h>
9 #include <linux/pfn_t.h>
10 #include <linux/sizes.h>
11 
12 #include <drm/drm_cache.h>
13 
14 #include "gt/intel_gt.h"
15 #include "gt/intel_gt_requests.h"
16 
17 #include "i915_drv.h"
18 #include "i915_gem_evict.h"
19 #include "i915_gem_gtt.h"
20 #include "i915_gem_ioctls.h"
21 #include "i915_gem_object.h"
22 #include "i915_gem_mman.h"
23 #include "i915_mm.h"
24 #include "i915_trace.h"
25 #include "i915_user_extensions.h"
26 #include "i915_gem_ttm.h"
27 #include "i915_vma.h"
28 
29 static inline bool
__vma_matches(struct vm_area_struct * vma,struct file * filp,unsigned long addr,unsigned long size)30 __vma_matches(struct vm_area_struct *vma, struct file *filp,
31 	      unsigned long addr, unsigned long size)
32 {
33 	if (vma->vm_file != filp)
34 		return false;
35 
36 	return vma->vm_start == addr &&
37 	       (vma->vm_end - vma->vm_start) == PAGE_ALIGN(size);
38 }
39 
40 /**
41  * i915_gem_mmap_ioctl - Maps the contents of an object, returning the address
42  *			 it is mapped to.
43  * @dev: drm device
44  * @data: ioctl data blob
45  * @file: drm file
46  *
47  * While the mapping holds a reference on the contents of the object, it doesn't
48  * imply a ref on the object itself.
49  *
50  * IMPORTANT:
51  *
52  * DRM driver writers who look a this function as an example for how to do GEM
53  * mmap support, please don't implement mmap support like here. The modern way
54  * to implement DRM mmap support is with an mmap offset ioctl (like
55  * i915_gem_mmap_gtt) and then using the mmap syscall on the DRM fd directly.
56  * That way debug tooling like valgrind will understand what's going on, hiding
57  * the mmap call in a driver private ioctl will break that. The i915 driver only
58  * does cpu mmaps this way because we didn't know better.
59  */
60 int
i915_gem_mmap_ioctl(struct drm_device * dev,void * data,struct drm_file * file)61 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
62 		    struct drm_file *file)
63 {
64 	struct drm_i915_private *i915 = to_i915(dev);
65 	struct drm_i915_gem_mmap *args = data;
66 	struct drm_i915_gem_object *obj;
67 	unsigned long addr;
68 
69 	/*
70 	 * mmap ioctl is disallowed for all discrete platforms,
71 	 * and for all platforms with GRAPHICS_VER > 12.
72 	 */
73 	if (IS_DGFX(i915) || GRAPHICS_VER_FULL(i915) > IP_VER(12, 0))
74 		return -EOPNOTSUPP;
75 
76 	if (args->flags & ~(I915_MMAP_WC))
77 		return -EINVAL;
78 
79 	if (args->flags & I915_MMAP_WC && !pat_enabled())
80 		return -ENODEV;
81 
82 	obj = i915_gem_object_lookup(file, args->handle);
83 	if (!obj)
84 		return -ENOENT;
85 
86 	/* prime objects have no backing filp to GEM mmap
87 	 * pages from.
88 	 */
89 	if (!obj->base.filp) {
90 		addr = -ENXIO;
91 		goto err;
92 	}
93 
94 	if (range_overflows(args->offset, args->size, (u64)obj->base.size)) {
95 		addr = -EINVAL;
96 		goto err;
97 	}
98 
99 	addr = vm_mmap(obj->base.filp, 0, args->size,
100 		       PROT_READ | PROT_WRITE, MAP_SHARED,
101 		       args->offset);
102 	if (IS_ERR_VALUE(addr))
103 		goto err;
104 
105 	if (args->flags & I915_MMAP_WC) {
106 		struct mm_struct *mm = current->mm;
107 		struct vm_area_struct *vma;
108 
109 		if (mmap_write_lock_killable(mm)) {
110 			addr = -EINTR;
111 			goto err;
112 		}
113 		vma = find_vma(mm, addr);
114 		if (vma && __vma_matches(vma, obj->base.filp, addr, args->size))
115 			vma->vm_page_prot =
116 				pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
117 		else
118 			addr = -ENOMEM;
119 		mmap_write_unlock(mm);
120 		if (IS_ERR_VALUE(addr))
121 			goto err;
122 	}
123 	i915_gem_object_put(obj);
124 
125 	args->addr_ptr = (u64)addr;
126 	return 0;
127 
128 err:
129 	i915_gem_object_put(obj);
130 	return addr;
131 }
132 
tile_row_pages(const struct drm_i915_gem_object * obj)133 static unsigned int tile_row_pages(const struct drm_i915_gem_object *obj)
134 {
135 	return i915_gem_object_get_tile_row_size(obj) >> PAGE_SHIFT;
136 }
137 
138 /**
139  * i915_gem_mmap_gtt_version - report the current feature set for GTT mmaps
140  *
141  * A history of the GTT mmap interface:
142  *
143  * 0 - Everything had to fit into the GTT. Both parties of a memcpy had to
144  *     aligned and suitable for fencing, and still fit into the available
145  *     mappable space left by the pinned display objects. A classic problem
146  *     we called the page-fault-of-doom where we would ping-pong between
147  *     two objects that could not fit inside the GTT and so the memcpy
148  *     would page one object in at the expense of the other between every
149  *     single byte.
150  *
151  * 1 - Objects can be any size, and have any compatible fencing (X Y, or none
152  *     as set via i915_gem_set_tiling() [DRM_I915_GEM_SET_TILING]). If the
153  *     object is too large for the available space (or simply too large
154  *     for the mappable aperture!), a view is created instead and faulted
155  *     into userspace. (This view is aligned and sized appropriately for
156  *     fenced access.)
157  *
158  * 2 - Recognise WC as a separate cache domain so that we can flush the
159  *     delayed writes via GTT before performing direct access via WC.
160  *
161  * 3 - Remove implicit set-domain(GTT) and synchronisation on initial
162  *     pagefault; swapin remains transparent.
163  *
164  * 4 - Support multiple fault handlers per object depending on object's
165  *     backing storage (a.k.a. MMAP_OFFSET).
166  *
167  * Restrictions:
168  *
169  *  * snoopable objects cannot be accessed via the GTT. It can cause machine
170  *    hangs on some architectures, corruption on others. An attempt to service
171  *    a GTT page fault from a snoopable object will generate a SIGBUS.
172  *
173  *  * the object must be able to fit into RAM (physical memory, though no
174  *    limited to the mappable aperture).
175  *
176  *
177  * Caveats:
178  *
179  *  * a new GTT page fault will synchronize rendering from the GPU and flush
180  *    all data to system memory. Subsequent access will not be synchronized.
181  *
182  *  * all mappings are revoked on runtime device suspend.
183  *
184  *  * there are only 8, 16 or 32 fence registers to share between all users
185  *    (older machines require fence register for display and blitter access
186  *    as well). Contention of the fence registers will cause the previous users
187  *    to be unmapped and any new access will generate new page faults.
188  *
189  *  * running out of memory while servicing a fault may generate a SIGBUS,
190  *    rather than the expected SIGSEGV.
191  */
i915_gem_mmap_gtt_version(void)192 int i915_gem_mmap_gtt_version(void)
193 {
194 	return 4;
195 }
196 
197 static inline struct i915_gtt_view
compute_partial_view(const struct drm_i915_gem_object * obj,pgoff_t page_offset,unsigned int chunk)198 compute_partial_view(const struct drm_i915_gem_object *obj,
199 		     pgoff_t page_offset,
200 		     unsigned int chunk)
201 {
202 	struct i915_gtt_view view;
203 
204 	if (i915_gem_object_is_tiled(obj))
205 		chunk = roundup(chunk, tile_row_pages(obj) ?: 1);
206 
207 	view.type = I915_GTT_VIEW_PARTIAL;
208 	view.partial.offset = rounddown(page_offset, chunk);
209 	view.partial.size =
210 		min_t(unsigned int, chunk,
211 		      (obj->base.size >> PAGE_SHIFT) - view.partial.offset);
212 
213 	/* If the partial covers the entire object, just create a normal VMA. */
214 	if (chunk >= obj->base.size >> PAGE_SHIFT)
215 		view.type = I915_GTT_VIEW_NORMAL;
216 
217 	return view;
218 }
219 
i915_error_to_vmf_fault(int err)220 static vm_fault_t i915_error_to_vmf_fault(int err)
221 {
222 	switch (err) {
223 	default:
224 		WARN_ONCE(err, "unhandled error in %s: %i\n", __func__, err);
225 		fallthrough;
226 	case -EIO: /* shmemfs failure from swap device */
227 	case -EFAULT: /* purged object */
228 	case -ENODEV: /* bad object, how did you get here! */
229 	case -ENXIO: /* unable to access backing store (on device) */
230 		return VM_FAULT_SIGBUS;
231 
232 	case -ENOMEM: /* our allocation failure */
233 		return VM_FAULT_OOM;
234 
235 	case 0:
236 	case -EAGAIN:
237 	case -ENOSPC: /* transient failure to evict? */
238 	case -ENOBUFS: /* temporarily out of fences? */
239 	case -ERESTARTSYS:
240 	case -EINTR:
241 	case -EBUSY:
242 		/*
243 		 * EBUSY is ok: this just means that another thread
244 		 * already did the job.
245 		 */
246 		return VM_FAULT_NOPAGE;
247 	}
248 }
249 
vm_fault_cpu(struct vm_fault * vmf)250 static vm_fault_t vm_fault_cpu(struct vm_fault *vmf)
251 {
252 	struct vm_area_struct *area = vmf->vma;
253 	struct i915_mmap_offset *mmo = area->vm_private_data;
254 	struct drm_i915_gem_object *obj = mmo->obj;
255 	resource_size_t iomap;
256 	int err;
257 
258 	/* Sanity check that we allow writing into this object */
259 	if (unlikely(i915_gem_object_is_readonly(obj) &&
260 		     area->vm_flags & VM_WRITE))
261 		return VM_FAULT_SIGBUS;
262 
263 	if (i915_gem_object_lock_interruptible(obj, NULL))
264 		return VM_FAULT_NOPAGE;
265 
266 	err = i915_gem_object_pin_pages(obj);
267 	if (err)
268 		goto out;
269 
270 	iomap = -1;
271 	if (!i915_gem_object_has_struct_page(obj)) {
272 		iomap = obj->mm.region->iomap.base;
273 		iomap -= obj->mm.region->region.start;
274 	}
275 
276 	/* PTEs are revoked in obj->ops->put_pages() */
277 	err = remap_io_sg(area,
278 			  area->vm_start, area->vm_end - area->vm_start,
279 			  obj->mm.pages->sgl, iomap);
280 
281 	if (area->vm_flags & VM_WRITE) {
282 		GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
283 		obj->mm.dirty = true;
284 	}
285 
286 	i915_gem_object_unpin_pages(obj);
287 
288 out:
289 	i915_gem_object_unlock(obj);
290 	return i915_error_to_vmf_fault(err);
291 }
292 
vm_fault_gtt(struct vm_fault * vmf)293 static vm_fault_t vm_fault_gtt(struct vm_fault *vmf)
294 {
295 #define MIN_CHUNK_PAGES (SZ_1M >> PAGE_SHIFT)
296 	struct vm_area_struct *area = vmf->vma;
297 	struct i915_mmap_offset *mmo = area->vm_private_data;
298 	struct drm_i915_gem_object *obj = mmo->obj;
299 	struct drm_device *dev = obj->base.dev;
300 	struct drm_i915_private *i915 = to_i915(dev);
301 	struct intel_runtime_pm *rpm = &i915->runtime_pm;
302 	struct i915_ggtt *ggtt = to_gt(i915)->ggtt;
303 	bool write = area->vm_flags & VM_WRITE;
304 	struct i915_gem_ww_ctx ww;
305 	intel_wakeref_t wakeref;
306 	struct i915_vma *vma;
307 	pgoff_t page_offset;
308 	int srcu;
309 	int ret;
310 
311 	/* We don't use vmf->pgoff since that has the fake offset */
312 	page_offset = (vmf->address - area->vm_start) >> PAGE_SHIFT;
313 
314 	trace_i915_gem_object_fault(obj, page_offset, true, write);
315 
316 	wakeref = intel_runtime_pm_get(rpm);
317 
318 	i915_gem_ww_ctx_init(&ww, true);
319 retry:
320 	ret = i915_gem_object_lock(obj, &ww);
321 	if (ret)
322 		goto err_rpm;
323 
324 	/* Sanity check that we allow writing into this object */
325 	if (i915_gem_object_is_readonly(obj) && write) {
326 		ret = -EFAULT;
327 		goto err_rpm;
328 	}
329 
330 	ret = i915_gem_object_pin_pages(obj);
331 	if (ret)
332 		goto err_rpm;
333 
334 	ret = intel_gt_reset_trylock(ggtt->vm.gt, &srcu);
335 	if (ret)
336 		goto err_pages;
337 
338 	/* Now pin it into the GTT as needed */
339 	vma = i915_gem_object_ggtt_pin_ww(obj, &ww, NULL, 0, 0,
340 					  PIN_MAPPABLE |
341 					  PIN_NONBLOCK /* NOWARN */ |
342 					  PIN_NOEVICT);
343 	if (IS_ERR(vma) && vma != ERR_PTR(-EDEADLK)) {
344 		/* Use a partial view if it is bigger than available space */
345 		struct i915_gtt_view view =
346 			compute_partial_view(obj, page_offset, MIN_CHUNK_PAGES);
347 		unsigned int flags;
348 
349 		flags = PIN_MAPPABLE | PIN_NOSEARCH;
350 		if (view.type == I915_GTT_VIEW_NORMAL)
351 			flags |= PIN_NONBLOCK; /* avoid warnings for pinned */
352 
353 		/*
354 		 * Userspace is now writing through an untracked VMA, abandon
355 		 * all hope that the hardware is able to track future writes.
356 		 */
357 
358 		vma = i915_gem_object_ggtt_pin_ww(obj, &ww, &view, 0, 0, flags);
359 		if (IS_ERR(vma) && vma != ERR_PTR(-EDEADLK)) {
360 			flags = PIN_MAPPABLE;
361 			view.type = I915_GTT_VIEW_PARTIAL;
362 			vma = i915_gem_object_ggtt_pin_ww(obj, &ww, &view, 0, 0, flags);
363 		}
364 
365 		/*
366 		 * The entire mappable GGTT is pinned? Unexpected!
367 		 * Try to evict the object we locked too, as normally we skip it
368 		 * due to lack of short term pinning inside execbuf.
369 		 */
370 		if (vma == ERR_PTR(-ENOSPC)) {
371 			ret = mutex_lock_interruptible(&ggtt->vm.mutex);
372 			if (!ret) {
373 				ret = i915_gem_evict_vm(&ggtt->vm, &ww, NULL);
374 				mutex_unlock(&ggtt->vm.mutex);
375 			}
376 			if (ret)
377 				goto err_reset;
378 			vma = i915_gem_object_ggtt_pin_ww(obj, &ww, &view, 0, 0, flags);
379 		}
380 	}
381 	if (IS_ERR(vma)) {
382 		ret = PTR_ERR(vma);
383 		goto err_reset;
384 	}
385 
386 	/* Access to snoopable pages through the GTT is incoherent. */
387 	if (obj->cache_level != I915_CACHE_NONE && !HAS_LLC(i915)) {
388 		ret = -EFAULT;
389 		goto err_unpin;
390 	}
391 
392 	ret = i915_vma_pin_fence(vma);
393 	if (ret)
394 		goto err_unpin;
395 
396 	/* Finally, remap it using the new GTT offset */
397 	ret = remap_io_mapping(area,
398 			       area->vm_start + (vma->gtt_view.partial.offset << PAGE_SHIFT),
399 			       (ggtt->gmadr.start + vma->node.start) >> PAGE_SHIFT,
400 			       min_t(u64, vma->size, area->vm_end - area->vm_start),
401 			       &ggtt->iomap);
402 	if (ret)
403 		goto err_fence;
404 
405 	assert_rpm_wakelock_held(rpm);
406 
407 	/* Mark as being mmapped into userspace for later revocation */
408 	mutex_lock(&to_gt(i915)->ggtt->vm.mutex);
409 	if (!i915_vma_set_userfault(vma) && !obj->userfault_count++)
410 		list_add(&obj->userfault_link, &to_gt(i915)->ggtt->userfault_list);
411 	mutex_unlock(&to_gt(i915)->ggtt->vm.mutex);
412 
413 	/* Track the mmo associated with the fenced vma */
414 	vma->mmo = mmo;
415 
416 	if (CONFIG_DRM_I915_USERFAULT_AUTOSUSPEND)
417 		intel_wakeref_auto(&i915->runtime_pm.userfault_wakeref,
418 				   msecs_to_jiffies_timeout(CONFIG_DRM_I915_USERFAULT_AUTOSUSPEND));
419 
420 	if (write) {
421 		GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
422 		i915_vma_set_ggtt_write(vma);
423 		obj->mm.dirty = true;
424 	}
425 
426 err_fence:
427 	i915_vma_unpin_fence(vma);
428 err_unpin:
429 	__i915_vma_unpin(vma);
430 err_reset:
431 	intel_gt_reset_unlock(ggtt->vm.gt, srcu);
432 err_pages:
433 	i915_gem_object_unpin_pages(obj);
434 err_rpm:
435 	if (ret == -EDEADLK) {
436 		ret = i915_gem_ww_ctx_backoff(&ww);
437 		if (!ret)
438 			goto retry;
439 	}
440 	i915_gem_ww_ctx_fini(&ww);
441 	intel_runtime_pm_put(rpm, wakeref);
442 	return i915_error_to_vmf_fault(ret);
443 }
444 
445 static int
vm_access(struct vm_area_struct * area,unsigned long addr,void * buf,int len,int write)446 vm_access(struct vm_area_struct *area, unsigned long addr,
447 	  void *buf, int len, int write)
448 {
449 	struct i915_mmap_offset *mmo = area->vm_private_data;
450 	struct drm_i915_gem_object *obj = mmo->obj;
451 	struct i915_gem_ww_ctx ww;
452 	void *vaddr;
453 	int err = 0;
454 
455 	if (i915_gem_object_is_readonly(obj) && write)
456 		return -EACCES;
457 
458 	addr -= area->vm_start;
459 	if (range_overflows_t(u64, addr, len, obj->base.size))
460 		return -EINVAL;
461 
462 	i915_gem_ww_ctx_init(&ww, true);
463 retry:
464 	err = i915_gem_object_lock(obj, &ww);
465 	if (err)
466 		goto out;
467 
468 	/* As this is primarily for debugging, let's focus on simplicity */
469 	vaddr = i915_gem_object_pin_map(obj, I915_MAP_FORCE_WC);
470 	if (IS_ERR(vaddr)) {
471 		err = PTR_ERR(vaddr);
472 		goto out;
473 	}
474 
475 	if (write) {
476 		memcpy(vaddr + addr, buf, len);
477 		__i915_gem_object_flush_map(obj, addr, len);
478 	} else {
479 		memcpy(buf, vaddr + addr, len);
480 	}
481 
482 	i915_gem_object_unpin_map(obj);
483 out:
484 	if (err == -EDEADLK) {
485 		err = i915_gem_ww_ctx_backoff(&ww);
486 		if (!err)
487 			goto retry;
488 	}
489 	i915_gem_ww_ctx_fini(&ww);
490 
491 	if (err)
492 		return err;
493 
494 	return len;
495 }
496 
__i915_gem_object_release_mmap_gtt(struct drm_i915_gem_object * obj)497 void __i915_gem_object_release_mmap_gtt(struct drm_i915_gem_object *obj)
498 {
499 	struct i915_vma *vma;
500 
501 	GEM_BUG_ON(!obj->userfault_count);
502 
503 	for_each_ggtt_vma(vma, obj)
504 		i915_vma_revoke_mmap(vma);
505 
506 	GEM_BUG_ON(obj->userfault_count);
507 }
508 
509 /*
510  * It is vital that we remove the page mapping if we have mapped a tiled
511  * object through the GTT and then lose the fence register due to
512  * resource pressure. Similarly if the object has been moved out of the
513  * aperture, than pages mapped into userspace must be revoked. Removing the
514  * mapping will then trigger a page fault on the next user access, allowing
515  * fixup by vm_fault_gtt().
516  */
i915_gem_object_release_mmap_gtt(struct drm_i915_gem_object * obj)517 void i915_gem_object_release_mmap_gtt(struct drm_i915_gem_object *obj)
518 {
519 	struct drm_i915_private *i915 = to_i915(obj->base.dev);
520 	intel_wakeref_t wakeref;
521 
522 	/*
523 	 * Serialisation between user GTT access and our code depends upon
524 	 * revoking the CPU's PTE whilst the mutex is held. The next user
525 	 * pagefault then has to wait until we release the mutex.
526 	 *
527 	 * Note that RPM complicates somewhat by adding an additional
528 	 * requirement that operations to the GGTT be made holding the RPM
529 	 * wakeref.
530 	 */
531 	wakeref = intel_runtime_pm_get(&i915->runtime_pm);
532 	mutex_lock(&to_gt(i915)->ggtt->vm.mutex);
533 
534 	if (!obj->userfault_count)
535 		goto out;
536 
537 	__i915_gem_object_release_mmap_gtt(obj);
538 
539 	/*
540 	 * Ensure that the CPU's PTE are revoked and there are not outstanding
541 	 * memory transactions from userspace before we return. The TLB
542 	 * flushing implied above by changing the PTE above *should* be
543 	 * sufficient, an extra barrier here just provides us with a bit
544 	 * of paranoid documentation about our requirement to serialise
545 	 * memory writes before touching registers / GSM.
546 	 */
547 	wmb();
548 
549 out:
550 	mutex_unlock(&to_gt(i915)->ggtt->vm.mutex);
551 	intel_runtime_pm_put(&i915->runtime_pm, wakeref);
552 }
553 
i915_gem_object_runtime_pm_release_mmap_offset(struct drm_i915_gem_object * obj)554 void i915_gem_object_runtime_pm_release_mmap_offset(struct drm_i915_gem_object *obj)
555 {
556 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
557 	struct ttm_device *bdev = bo->bdev;
558 
559 	drm_vma_node_unmap(&bo->base.vma_node, bdev->dev_mapping);
560 
561 	/*
562 	 * We have exclusive access here via runtime suspend. All other callers
563 	 * must first grab the rpm wakeref.
564 	 */
565 	GEM_BUG_ON(!obj->userfault_count);
566 	list_del(&obj->userfault_link);
567 	obj->userfault_count = 0;
568 }
569 
i915_gem_object_release_mmap_offset(struct drm_i915_gem_object * obj)570 void i915_gem_object_release_mmap_offset(struct drm_i915_gem_object *obj)
571 {
572 	struct i915_mmap_offset *mmo, *mn;
573 
574 	if (obj->ops->unmap_virtual)
575 		obj->ops->unmap_virtual(obj);
576 
577 	spin_lock(&obj->mmo.lock);
578 	rbtree_postorder_for_each_entry_safe(mmo, mn,
579 					     &obj->mmo.offsets, offset) {
580 		/*
581 		 * vma_node_unmap for GTT mmaps handled already in
582 		 * __i915_gem_object_release_mmap_gtt
583 		 */
584 		if (mmo->mmap_type == I915_MMAP_TYPE_GTT)
585 			continue;
586 
587 		spin_unlock(&obj->mmo.lock);
588 		drm_vma_node_unmap(&mmo->vma_node,
589 				   obj->base.dev->anon_inode->i_mapping);
590 		spin_lock(&obj->mmo.lock);
591 	}
592 	spin_unlock(&obj->mmo.lock);
593 }
594 
595 static struct i915_mmap_offset *
lookup_mmo(struct drm_i915_gem_object * obj,enum i915_mmap_type mmap_type)596 lookup_mmo(struct drm_i915_gem_object *obj,
597 	   enum i915_mmap_type mmap_type)
598 {
599 	struct rb_node *rb;
600 
601 	spin_lock(&obj->mmo.lock);
602 	rb = obj->mmo.offsets.rb_node;
603 	while (rb) {
604 		struct i915_mmap_offset *mmo =
605 			rb_entry(rb, typeof(*mmo), offset);
606 
607 		if (mmo->mmap_type == mmap_type) {
608 			spin_unlock(&obj->mmo.lock);
609 			return mmo;
610 		}
611 
612 		if (mmo->mmap_type < mmap_type)
613 			rb = rb->rb_right;
614 		else
615 			rb = rb->rb_left;
616 	}
617 	spin_unlock(&obj->mmo.lock);
618 
619 	return NULL;
620 }
621 
622 static struct i915_mmap_offset *
insert_mmo(struct drm_i915_gem_object * obj,struct i915_mmap_offset * mmo)623 insert_mmo(struct drm_i915_gem_object *obj, struct i915_mmap_offset *mmo)
624 {
625 	struct rb_node *rb, **p;
626 
627 	spin_lock(&obj->mmo.lock);
628 	rb = NULL;
629 	p = &obj->mmo.offsets.rb_node;
630 	while (*p) {
631 		struct i915_mmap_offset *pos;
632 
633 		rb = *p;
634 		pos = rb_entry(rb, typeof(*pos), offset);
635 
636 		if (pos->mmap_type == mmo->mmap_type) {
637 			spin_unlock(&obj->mmo.lock);
638 			drm_vma_offset_remove(obj->base.dev->vma_offset_manager,
639 					      &mmo->vma_node);
640 			kfree(mmo);
641 			return pos;
642 		}
643 
644 		if (pos->mmap_type < mmo->mmap_type)
645 			p = &rb->rb_right;
646 		else
647 			p = &rb->rb_left;
648 	}
649 	rb_link_node(&mmo->offset, rb, p);
650 	rb_insert_color(&mmo->offset, &obj->mmo.offsets);
651 	spin_unlock(&obj->mmo.lock);
652 
653 	return mmo;
654 }
655 
656 static struct i915_mmap_offset *
mmap_offset_attach(struct drm_i915_gem_object * obj,enum i915_mmap_type mmap_type,struct drm_file * file)657 mmap_offset_attach(struct drm_i915_gem_object *obj,
658 		   enum i915_mmap_type mmap_type,
659 		   struct drm_file *file)
660 {
661 	struct drm_i915_private *i915 = to_i915(obj->base.dev);
662 	struct i915_mmap_offset *mmo;
663 	int err;
664 
665 	GEM_BUG_ON(obj->ops->mmap_offset || obj->ops->mmap_ops);
666 
667 	mmo = lookup_mmo(obj, mmap_type);
668 	if (mmo)
669 		goto out;
670 
671 	mmo = kmalloc(sizeof(*mmo), GFP_KERNEL);
672 	if (!mmo)
673 		return ERR_PTR(-ENOMEM);
674 
675 	mmo->obj = obj;
676 	mmo->mmap_type = mmap_type;
677 	drm_vma_node_reset(&mmo->vma_node);
678 
679 	err = drm_vma_offset_add(obj->base.dev->vma_offset_manager,
680 				 &mmo->vma_node, obj->base.size / PAGE_SIZE);
681 	if (likely(!err))
682 		goto insert;
683 
684 	/* Attempt to reap some mmap space from dead objects */
685 	err = intel_gt_retire_requests_timeout(to_gt(i915), MAX_SCHEDULE_TIMEOUT,
686 					       NULL);
687 	if (err)
688 		goto err;
689 
690 	i915_gem_drain_freed_objects(i915);
691 	err = drm_vma_offset_add(obj->base.dev->vma_offset_manager,
692 				 &mmo->vma_node, obj->base.size / PAGE_SIZE);
693 	if (err)
694 		goto err;
695 
696 insert:
697 	mmo = insert_mmo(obj, mmo);
698 	GEM_BUG_ON(lookup_mmo(obj, mmap_type) != mmo);
699 out:
700 	if (file)
701 		drm_vma_node_allow_once(&mmo->vma_node, file);
702 	return mmo;
703 
704 err:
705 	kfree(mmo);
706 	return ERR_PTR(err);
707 }
708 
709 static int
__assign_mmap_offset(struct drm_i915_gem_object * obj,enum i915_mmap_type mmap_type,u64 * offset,struct drm_file * file)710 __assign_mmap_offset(struct drm_i915_gem_object *obj,
711 		     enum i915_mmap_type mmap_type,
712 		     u64 *offset, struct drm_file *file)
713 {
714 	struct i915_mmap_offset *mmo;
715 
716 	if (i915_gem_object_never_mmap(obj))
717 		return -ENODEV;
718 
719 	if (obj->ops->mmap_offset)  {
720 		if (mmap_type != I915_MMAP_TYPE_FIXED)
721 			return -ENODEV;
722 
723 		*offset = obj->ops->mmap_offset(obj);
724 		return 0;
725 	}
726 
727 	if (mmap_type == I915_MMAP_TYPE_FIXED)
728 		return -ENODEV;
729 
730 	if (mmap_type != I915_MMAP_TYPE_GTT &&
731 	    !i915_gem_object_has_struct_page(obj) &&
732 	    !i915_gem_object_has_iomem(obj))
733 		return -ENODEV;
734 
735 	mmo = mmap_offset_attach(obj, mmap_type, file);
736 	if (IS_ERR(mmo))
737 		return PTR_ERR(mmo);
738 
739 	*offset = drm_vma_node_offset_addr(&mmo->vma_node);
740 	return 0;
741 }
742 
743 static int
__assign_mmap_offset_handle(struct drm_file * file,u32 handle,enum i915_mmap_type mmap_type,u64 * offset)744 __assign_mmap_offset_handle(struct drm_file *file,
745 			    u32 handle,
746 			    enum i915_mmap_type mmap_type,
747 			    u64 *offset)
748 {
749 	struct drm_i915_gem_object *obj;
750 	int err;
751 
752 	obj = i915_gem_object_lookup(file, handle);
753 	if (!obj)
754 		return -ENOENT;
755 
756 	err = i915_gem_object_lock_interruptible(obj, NULL);
757 	if (err)
758 		goto out_put;
759 	err = __assign_mmap_offset(obj, mmap_type, offset, file);
760 	i915_gem_object_unlock(obj);
761 out_put:
762 	i915_gem_object_put(obj);
763 	return err;
764 }
765 
766 int
i915_gem_dumb_mmap_offset(struct drm_file * file,struct drm_device * dev,u32 handle,u64 * offset)767 i915_gem_dumb_mmap_offset(struct drm_file *file,
768 			  struct drm_device *dev,
769 			  u32 handle,
770 			  u64 *offset)
771 {
772 	struct drm_i915_private *i915 = to_i915(dev);
773 	enum i915_mmap_type mmap_type;
774 
775 	if (HAS_LMEM(to_i915(dev)))
776 		mmap_type = I915_MMAP_TYPE_FIXED;
777 	else if (pat_enabled())
778 		mmap_type = I915_MMAP_TYPE_WC;
779 	else if (!i915_ggtt_has_aperture(to_gt(i915)->ggtt))
780 		return -ENODEV;
781 	else
782 		mmap_type = I915_MMAP_TYPE_GTT;
783 
784 	return __assign_mmap_offset_handle(file, handle, mmap_type, offset);
785 }
786 
787 /**
788  * i915_gem_mmap_offset_ioctl - prepare an object for GTT mmap'ing
789  * @dev: DRM device
790  * @data: GTT mapping ioctl data
791  * @file: GEM object info
792  *
793  * Simply returns the fake offset to userspace so it can mmap it.
794  * The mmap call will end up in drm_gem_mmap(), which will set things
795  * up so we can get faults in the handler above.
796  *
797  * The fault handler will take care of binding the object into the GTT
798  * (since it may have been evicted to make room for something), allocating
799  * a fence register, and mapping the appropriate aperture address into
800  * userspace.
801  */
802 int
i915_gem_mmap_offset_ioctl(struct drm_device * dev,void * data,struct drm_file * file)803 i915_gem_mmap_offset_ioctl(struct drm_device *dev, void *data,
804 			   struct drm_file *file)
805 {
806 	struct drm_i915_private *i915 = to_i915(dev);
807 	struct drm_i915_gem_mmap_offset *args = data;
808 	enum i915_mmap_type type;
809 	int err;
810 
811 	/*
812 	 * Historically we failed to check args.pad and args.offset
813 	 * and so we cannot use those fields for user input and we cannot
814 	 * add -EINVAL for them as the ABI is fixed, i.e. old userspace
815 	 * may be feeding in garbage in those fields.
816 	 *
817 	 * if (args->pad) return -EINVAL; is verbotten!
818 	 */
819 
820 	err = i915_user_extensions(u64_to_user_ptr(args->extensions),
821 				   NULL, 0, NULL);
822 	if (err)
823 		return err;
824 
825 	switch (args->flags) {
826 	case I915_MMAP_OFFSET_GTT:
827 		if (!i915_ggtt_has_aperture(to_gt(i915)->ggtt))
828 			return -ENODEV;
829 		type = I915_MMAP_TYPE_GTT;
830 		break;
831 
832 	case I915_MMAP_OFFSET_WC:
833 		if (!pat_enabled())
834 			return -ENODEV;
835 		type = I915_MMAP_TYPE_WC;
836 		break;
837 
838 	case I915_MMAP_OFFSET_WB:
839 		type = I915_MMAP_TYPE_WB;
840 		break;
841 
842 	case I915_MMAP_OFFSET_UC:
843 		if (!pat_enabled())
844 			return -ENODEV;
845 		type = I915_MMAP_TYPE_UC;
846 		break;
847 
848 	case I915_MMAP_OFFSET_FIXED:
849 		type = I915_MMAP_TYPE_FIXED;
850 		break;
851 
852 	default:
853 		return -EINVAL;
854 	}
855 
856 	return __assign_mmap_offset_handle(file, args->handle, type, &args->offset);
857 }
858 
vm_open(struct vm_area_struct * vma)859 static void vm_open(struct vm_area_struct *vma)
860 {
861 	struct i915_mmap_offset *mmo = vma->vm_private_data;
862 	struct drm_i915_gem_object *obj = mmo->obj;
863 
864 	GEM_BUG_ON(!obj);
865 	i915_gem_object_get(obj);
866 }
867 
vm_close(struct vm_area_struct * vma)868 static void vm_close(struct vm_area_struct *vma)
869 {
870 	struct i915_mmap_offset *mmo = vma->vm_private_data;
871 	struct drm_i915_gem_object *obj = mmo->obj;
872 
873 	GEM_BUG_ON(!obj);
874 	i915_gem_object_put(obj);
875 }
876 
877 static const struct vm_operations_struct vm_ops_gtt = {
878 	.fault = vm_fault_gtt,
879 	.access = vm_access,
880 	.open = vm_open,
881 	.close = vm_close,
882 };
883 
884 static const struct vm_operations_struct vm_ops_cpu = {
885 	.fault = vm_fault_cpu,
886 	.access = vm_access,
887 	.open = vm_open,
888 	.close = vm_close,
889 };
890 
singleton_release(struct inode * inode,struct file * file)891 static int singleton_release(struct inode *inode, struct file *file)
892 {
893 	struct drm_i915_private *i915 = file->private_data;
894 
895 	cmpxchg(&i915->gem.mmap_singleton, file, NULL);
896 	drm_dev_put(&i915->drm);
897 
898 	return 0;
899 }
900 
901 static const struct file_operations singleton_fops = {
902 	.owner = THIS_MODULE,
903 	.release = singleton_release,
904 };
905 
mmap_singleton(struct drm_i915_private * i915)906 static struct file *mmap_singleton(struct drm_i915_private *i915)
907 {
908 	struct file *file;
909 
910 	rcu_read_lock();
911 	file = READ_ONCE(i915->gem.mmap_singleton);
912 	if (file && !get_file_rcu(file))
913 		file = NULL;
914 	rcu_read_unlock();
915 	if (file)
916 		return file;
917 
918 	file = anon_inode_getfile("i915.gem", &singleton_fops, i915, O_RDWR);
919 	if (IS_ERR(file))
920 		return file;
921 
922 	/* Everyone shares a single global address space */
923 	file->f_mapping = i915->drm.anon_inode->i_mapping;
924 
925 	smp_store_mb(i915->gem.mmap_singleton, file);
926 	drm_dev_get(&i915->drm);
927 
928 	return file;
929 }
930 
931 /*
932  * This overcomes the limitation in drm_gem_mmap's assignment of a
933  * drm_gem_object as the vma->vm_private_data. Since we need to
934  * be able to resolve multiple mmap offsets which could be tied
935  * to a single gem object.
936  */
i915_gem_mmap(struct file * filp,struct vm_area_struct * vma)937 int i915_gem_mmap(struct file *filp, struct vm_area_struct *vma)
938 {
939 	struct drm_vma_offset_node *node;
940 	struct drm_file *priv = filp->private_data;
941 	struct drm_device *dev = priv->minor->dev;
942 	struct drm_i915_gem_object *obj = NULL;
943 	struct i915_mmap_offset *mmo = NULL;
944 	struct file *anon;
945 
946 	if (drm_dev_is_unplugged(dev))
947 		return -ENODEV;
948 
949 	rcu_read_lock();
950 	drm_vma_offset_lock_lookup(dev->vma_offset_manager);
951 	node = drm_vma_offset_exact_lookup_locked(dev->vma_offset_manager,
952 						  vma->vm_pgoff,
953 						  vma_pages(vma));
954 	if (node && drm_vma_node_is_allowed(node, priv)) {
955 		/*
956 		 * Skip 0-refcnted objects as it is in the process of being
957 		 * destroyed and will be invalid when the vma manager lock
958 		 * is released.
959 		 */
960 		if (!node->driver_private) {
961 			mmo = container_of(node, struct i915_mmap_offset, vma_node);
962 			obj = i915_gem_object_get_rcu(mmo->obj);
963 
964 			GEM_BUG_ON(obj && obj->ops->mmap_ops);
965 		} else {
966 			obj = i915_gem_object_get_rcu
967 				(container_of(node, struct drm_i915_gem_object,
968 					      base.vma_node));
969 
970 			GEM_BUG_ON(obj && !obj->ops->mmap_ops);
971 		}
972 	}
973 	drm_vma_offset_unlock_lookup(dev->vma_offset_manager);
974 	rcu_read_unlock();
975 	if (!obj)
976 		return node ? -EACCES : -EINVAL;
977 
978 	if (i915_gem_object_is_readonly(obj)) {
979 		if (vma->vm_flags & VM_WRITE) {
980 			i915_gem_object_put(obj);
981 			return -EINVAL;
982 		}
983 		vm_flags_clear(vma, VM_MAYWRITE);
984 	}
985 
986 	anon = mmap_singleton(to_i915(dev));
987 	if (IS_ERR(anon)) {
988 		i915_gem_object_put(obj);
989 		return PTR_ERR(anon);
990 	}
991 
992 	vm_flags_set(vma, VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP | VM_IO);
993 
994 	/*
995 	 * We keep the ref on mmo->obj, not vm_file, but we require
996 	 * vma->vm_file->f_mapping, see vma_link(), for later revocation.
997 	 * Our userspace is accustomed to having per-file resource cleanup
998 	 * (i.e. contexts, objects and requests) on their close(fd), which
999 	 * requires avoiding extraneous references to their filp, hence why
1000 	 * we prefer to use an anonymous file for their mmaps.
1001 	 */
1002 	vma_set_file(vma, anon);
1003 	/* Drop the initial creation reference, the vma is now holding one. */
1004 	fput(anon);
1005 
1006 	if (obj->ops->mmap_ops) {
1007 		vma->vm_page_prot = pgprot_decrypted(vm_get_page_prot(vma->vm_flags));
1008 		vma->vm_ops = obj->ops->mmap_ops;
1009 		vma->vm_private_data = node->driver_private;
1010 		return 0;
1011 	}
1012 
1013 	vma->vm_private_data = mmo;
1014 
1015 	switch (mmo->mmap_type) {
1016 	case I915_MMAP_TYPE_WC:
1017 		vma->vm_page_prot =
1018 			pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
1019 		vma->vm_ops = &vm_ops_cpu;
1020 		break;
1021 
1022 	case I915_MMAP_TYPE_FIXED:
1023 		GEM_WARN_ON(1);
1024 		fallthrough;
1025 	case I915_MMAP_TYPE_WB:
1026 		vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
1027 		vma->vm_ops = &vm_ops_cpu;
1028 		break;
1029 
1030 	case I915_MMAP_TYPE_UC:
1031 		vma->vm_page_prot =
1032 			pgprot_noncached(vm_get_page_prot(vma->vm_flags));
1033 		vma->vm_ops = &vm_ops_cpu;
1034 		break;
1035 
1036 	case I915_MMAP_TYPE_GTT:
1037 		vma->vm_page_prot =
1038 			pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
1039 		vma->vm_ops = &vm_ops_gtt;
1040 		break;
1041 	}
1042 	vma->vm_page_prot = pgprot_decrypted(vma->vm_page_prot);
1043 
1044 	return 0;
1045 }
1046 
1047 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
1048 #include "selftests/i915_gem_mman.c"
1049 #endif
1050