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
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
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 
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  */
192 int i915_gem_mmap_gtt_version(void)
193 {
194 	return 4;
195 }
196 
197 static inline struct i915_gtt_view
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 
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 -ERESTARTSYS:
239 	case -EINTR:
240 	case -EBUSY:
241 		/*
242 		 * EBUSY is ok: this just means that another thread
243 		 * already did the job.
244 		 */
245 		return VM_FAULT_NOPAGE;
246 	}
247 }
248 
249 static vm_fault_t vm_fault_cpu(struct vm_fault *vmf)
250 {
251 	struct vm_area_struct *area = vmf->vma;
252 	struct i915_mmap_offset *mmo = area->vm_private_data;
253 	struct drm_i915_gem_object *obj = mmo->obj;
254 	resource_size_t iomap;
255 	int err;
256 
257 	/* Sanity check that we allow writing into this object */
258 	if (unlikely(i915_gem_object_is_readonly(obj) &&
259 		     area->vm_flags & VM_WRITE))
260 		return VM_FAULT_SIGBUS;
261 
262 	if (i915_gem_object_lock_interruptible(obj, NULL))
263 		return VM_FAULT_NOPAGE;
264 
265 	err = i915_gem_object_pin_pages(obj);
266 	if (err)
267 		goto out;
268 
269 	iomap = -1;
270 	if (!i915_gem_object_has_struct_page(obj)) {
271 		iomap = obj->mm.region->iomap.base;
272 		iomap -= obj->mm.region->region.start;
273 	}
274 
275 	/* PTEs are revoked in obj->ops->put_pages() */
276 	err = remap_io_sg(area,
277 			  area->vm_start, area->vm_end - area->vm_start,
278 			  obj->mm.pages->sgl, iomap);
279 
280 	if (area->vm_flags & VM_WRITE) {
281 		GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
282 		obj->mm.dirty = true;
283 	}
284 
285 	i915_gem_object_unpin_pages(obj);
286 
287 out:
288 	i915_gem_object_unlock(obj);
289 	return i915_error_to_vmf_fault(err);
290 }
291 
292 static vm_fault_t vm_fault_gtt(struct vm_fault *vmf)
293 {
294 #define MIN_CHUNK_PAGES (SZ_1M >> PAGE_SHIFT)
295 	struct vm_area_struct *area = vmf->vma;
296 	struct i915_mmap_offset *mmo = area->vm_private_data;
297 	struct drm_i915_gem_object *obj = mmo->obj;
298 	struct drm_device *dev = obj->base.dev;
299 	struct drm_i915_private *i915 = to_i915(dev);
300 	struct intel_runtime_pm *rpm = &i915->runtime_pm;
301 	struct i915_ggtt *ggtt = to_gt(i915)->ggtt;
302 	bool write = area->vm_flags & VM_WRITE;
303 	struct i915_gem_ww_ctx ww;
304 	intel_wakeref_t wakeref;
305 	struct i915_vma *vma;
306 	pgoff_t page_offset;
307 	int srcu;
308 	int ret;
309 
310 	/* We don't use vmf->pgoff since that has the fake offset */
311 	page_offset = (vmf->address - area->vm_start) >> PAGE_SHIFT;
312 
313 	trace_i915_gem_object_fault(obj, page_offset, true, write);
314 
315 	wakeref = intel_runtime_pm_get(rpm);
316 
317 	i915_gem_ww_ctx_init(&ww, true);
318 retry:
319 	ret = i915_gem_object_lock(obj, &ww);
320 	if (ret)
321 		goto err_rpm;
322 
323 	/* Sanity check that we allow writing into this object */
324 	if (i915_gem_object_is_readonly(obj) && write) {
325 		ret = -EFAULT;
326 		goto err_rpm;
327 	}
328 
329 	ret = i915_gem_object_pin_pages(obj);
330 	if (ret)
331 		goto err_rpm;
332 
333 	ret = intel_gt_reset_lock_interruptible(ggtt->vm.gt, &srcu);
334 	if (ret)
335 		goto err_pages;
336 
337 	/* Now pin it into the GTT as needed */
338 	vma = i915_gem_object_ggtt_pin_ww(obj, &ww, NULL, 0, 0,
339 					  PIN_MAPPABLE |
340 					  PIN_NONBLOCK /* NOWARN */ |
341 					  PIN_NOEVICT);
342 	if (IS_ERR(vma) && vma != ERR_PTR(-EDEADLK)) {
343 		/* Use a partial view if it is bigger than available space */
344 		struct i915_gtt_view view =
345 			compute_partial_view(obj, page_offset, MIN_CHUNK_PAGES);
346 		unsigned int flags;
347 
348 		flags = PIN_MAPPABLE | PIN_NOSEARCH;
349 		if (view.type == I915_GTT_VIEW_NORMAL)
350 			flags |= PIN_NONBLOCK; /* avoid warnings for pinned */
351 
352 		/*
353 		 * Userspace is now writing through an untracked VMA, abandon
354 		 * all hope that the hardware is able to track future writes.
355 		 */
356 
357 		vma = i915_gem_object_ggtt_pin_ww(obj, &ww, &view, 0, 0, flags);
358 		if (IS_ERR(vma) && vma != ERR_PTR(-EDEADLK)) {
359 			flags = PIN_MAPPABLE;
360 			view.type = I915_GTT_VIEW_PARTIAL;
361 			vma = i915_gem_object_ggtt_pin_ww(obj, &ww, &view, 0, 0, flags);
362 		}
363 
364 		/*
365 		 * The entire mappable GGTT is pinned? Unexpected!
366 		 * Try to evict the object we locked too, as normally we skip it
367 		 * due to lack of short term pinning inside execbuf.
368 		 */
369 		if (vma == ERR_PTR(-ENOSPC)) {
370 			ret = mutex_lock_interruptible(&ggtt->vm.mutex);
371 			if (!ret) {
372 				ret = i915_gem_evict_vm(&ggtt->vm, &ww, NULL);
373 				mutex_unlock(&ggtt->vm.mutex);
374 			}
375 			if (ret)
376 				goto err_reset;
377 			vma = i915_gem_object_ggtt_pin_ww(obj, &ww, &view, 0, 0, flags);
378 		}
379 	}
380 	if (IS_ERR(vma)) {
381 		ret = PTR_ERR(vma);
382 		goto err_reset;
383 	}
384 
385 	/* Access to snoopable pages through the GTT is incoherent. */
386 	/*
387 	 * For objects created by userspace through GEM_CREATE with pat_index
388 	 * set by set_pat extension, coherency is managed by userspace, make
389 	 * sure we don't fail handling the vm fault by calling
390 	 * i915_gem_object_has_cache_level() which always return true for such
391 	 * objects. Otherwise this helper function would fall back to checking
392 	 * whether the object is un-cached.
393 	 */
394 	if (!(i915_gem_object_has_cache_level(obj, I915_CACHE_NONE) ||
395 	      HAS_LLC(i915))) {
396 		ret = -EFAULT;
397 		goto err_unpin;
398 	}
399 
400 	ret = i915_vma_pin_fence(vma);
401 	if (ret)
402 		goto err_unpin;
403 
404 	/* Finally, remap it using the new GTT offset */
405 	ret = remap_io_mapping(area,
406 			       area->vm_start + (vma->gtt_view.partial.offset << PAGE_SHIFT),
407 			       (ggtt->gmadr.start + i915_ggtt_offset(vma)) >> PAGE_SHIFT,
408 			       min_t(u64, vma->size, area->vm_end - area->vm_start),
409 			       &ggtt->iomap);
410 	if (ret)
411 		goto err_fence;
412 
413 	assert_rpm_wakelock_held(rpm);
414 
415 	/* Mark as being mmapped into userspace for later revocation */
416 	mutex_lock(&to_gt(i915)->ggtt->vm.mutex);
417 	if (!i915_vma_set_userfault(vma) && !obj->userfault_count++)
418 		list_add(&obj->userfault_link, &to_gt(i915)->ggtt->userfault_list);
419 	mutex_unlock(&to_gt(i915)->ggtt->vm.mutex);
420 
421 	/* Track the mmo associated with the fenced vma */
422 	vma->mmo = mmo;
423 
424 	if (CONFIG_DRM_I915_USERFAULT_AUTOSUSPEND)
425 		intel_wakeref_auto(&i915->runtime_pm.userfault_wakeref,
426 				   msecs_to_jiffies_timeout(CONFIG_DRM_I915_USERFAULT_AUTOSUSPEND));
427 
428 	if (write) {
429 		GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
430 		i915_vma_set_ggtt_write(vma);
431 		obj->mm.dirty = true;
432 	}
433 
434 err_fence:
435 	i915_vma_unpin_fence(vma);
436 err_unpin:
437 	__i915_vma_unpin(vma);
438 err_reset:
439 	intel_gt_reset_unlock(ggtt->vm.gt, srcu);
440 err_pages:
441 	i915_gem_object_unpin_pages(obj);
442 err_rpm:
443 	if (ret == -EDEADLK) {
444 		ret = i915_gem_ww_ctx_backoff(&ww);
445 		if (!ret)
446 			goto retry;
447 	}
448 	i915_gem_ww_ctx_fini(&ww);
449 	intel_runtime_pm_put(rpm, wakeref);
450 	return i915_error_to_vmf_fault(ret);
451 }
452 
453 static int
454 vm_access(struct vm_area_struct *area, unsigned long addr,
455 	  void *buf, int len, int write)
456 {
457 	struct i915_mmap_offset *mmo = area->vm_private_data;
458 	struct drm_i915_gem_object *obj = mmo->obj;
459 	struct i915_gem_ww_ctx ww;
460 	void *vaddr;
461 	int err = 0;
462 
463 	if (i915_gem_object_is_readonly(obj) && write)
464 		return -EACCES;
465 
466 	addr -= area->vm_start;
467 	if (range_overflows_t(u64, addr, len, obj->base.size))
468 		return -EINVAL;
469 
470 	i915_gem_ww_ctx_init(&ww, true);
471 retry:
472 	err = i915_gem_object_lock(obj, &ww);
473 	if (err)
474 		goto out;
475 
476 	/* As this is primarily for debugging, let's focus on simplicity */
477 	vaddr = i915_gem_object_pin_map(obj, I915_MAP_FORCE_WC);
478 	if (IS_ERR(vaddr)) {
479 		err = PTR_ERR(vaddr);
480 		goto out;
481 	}
482 
483 	if (write) {
484 		memcpy(vaddr + addr, buf, len);
485 		__i915_gem_object_flush_map(obj, addr, len);
486 	} else {
487 		memcpy(buf, vaddr + addr, len);
488 	}
489 
490 	i915_gem_object_unpin_map(obj);
491 out:
492 	if (err == -EDEADLK) {
493 		err = i915_gem_ww_ctx_backoff(&ww);
494 		if (!err)
495 			goto retry;
496 	}
497 	i915_gem_ww_ctx_fini(&ww);
498 
499 	if (err)
500 		return err;
501 
502 	return len;
503 }
504 
505 void __i915_gem_object_release_mmap_gtt(struct drm_i915_gem_object *obj)
506 {
507 	struct i915_vma *vma;
508 
509 	GEM_BUG_ON(!obj->userfault_count);
510 
511 	for_each_ggtt_vma(vma, obj)
512 		i915_vma_revoke_mmap(vma);
513 
514 	GEM_BUG_ON(obj->userfault_count);
515 }
516 
517 /*
518  * It is vital that we remove the page mapping if we have mapped a tiled
519  * object through the GTT and then lose the fence register due to
520  * resource pressure. Similarly if the object has been moved out of the
521  * aperture, than pages mapped into userspace must be revoked. Removing the
522  * mapping will then trigger a page fault on the next user access, allowing
523  * fixup by vm_fault_gtt().
524  */
525 void i915_gem_object_release_mmap_gtt(struct drm_i915_gem_object *obj)
526 {
527 	struct drm_i915_private *i915 = to_i915(obj->base.dev);
528 	intel_wakeref_t wakeref;
529 
530 	/*
531 	 * Serialisation between user GTT access and our code depends upon
532 	 * revoking the CPU's PTE whilst the mutex is held. The next user
533 	 * pagefault then has to wait until we release the mutex.
534 	 *
535 	 * Note that RPM complicates somewhat by adding an additional
536 	 * requirement that operations to the GGTT be made holding the RPM
537 	 * wakeref.
538 	 */
539 	wakeref = intel_runtime_pm_get(&i915->runtime_pm);
540 	mutex_lock(&to_gt(i915)->ggtt->vm.mutex);
541 
542 	if (!obj->userfault_count)
543 		goto out;
544 
545 	__i915_gem_object_release_mmap_gtt(obj);
546 
547 	/*
548 	 * Ensure that the CPU's PTE are revoked and there are not outstanding
549 	 * memory transactions from userspace before we return. The TLB
550 	 * flushing implied above by changing the PTE above *should* be
551 	 * sufficient, an extra barrier here just provides us with a bit
552 	 * of paranoid documentation about our requirement to serialise
553 	 * memory writes before touching registers / GSM.
554 	 */
555 	wmb();
556 
557 out:
558 	mutex_unlock(&to_gt(i915)->ggtt->vm.mutex);
559 	intel_runtime_pm_put(&i915->runtime_pm, wakeref);
560 }
561 
562 void i915_gem_object_runtime_pm_release_mmap_offset(struct drm_i915_gem_object *obj)
563 {
564 	struct ttm_buffer_object *bo = i915_gem_to_ttm(obj);
565 	struct ttm_device *bdev = bo->bdev;
566 
567 	drm_vma_node_unmap(&bo->base.vma_node, bdev->dev_mapping);
568 
569 	/*
570 	 * We have exclusive access here via runtime suspend. All other callers
571 	 * must first grab the rpm wakeref.
572 	 */
573 	GEM_BUG_ON(!obj->userfault_count);
574 	list_del(&obj->userfault_link);
575 	obj->userfault_count = 0;
576 }
577 
578 void i915_gem_object_release_mmap_offset(struct drm_i915_gem_object *obj)
579 {
580 	struct i915_mmap_offset *mmo, *mn;
581 
582 	if (obj->ops->unmap_virtual)
583 		obj->ops->unmap_virtual(obj);
584 
585 	spin_lock(&obj->mmo.lock);
586 	rbtree_postorder_for_each_entry_safe(mmo, mn,
587 					     &obj->mmo.offsets, offset) {
588 		/*
589 		 * vma_node_unmap for GTT mmaps handled already in
590 		 * __i915_gem_object_release_mmap_gtt
591 		 */
592 		if (mmo->mmap_type == I915_MMAP_TYPE_GTT)
593 			continue;
594 
595 		spin_unlock(&obj->mmo.lock);
596 		drm_vma_node_unmap(&mmo->vma_node,
597 				   obj->base.dev->anon_inode->i_mapping);
598 		spin_lock(&obj->mmo.lock);
599 	}
600 	spin_unlock(&obj->mmo.lock);
601 }
602 
603 static struct i915_mmap_offset *
604 lookup_mmo(struct drm_i915_gem_object *obj,
605 	   enum i915_mmap_type mmap_type)
606 {
607 	struct rb_node *rb;
608 
609 	spin_lock(&obj->mmo.lock);
610 	rb = obj->mmo.offsets.rb_node;
611 	while (rb) {
612 		struct i915_mmap_offset *mmo =
613 			rb_entry(rb, typeof(*mmo), offset);
614 
615 		if (mmo->mmap_type == mmap_type) {
616 			spin_unlock(&obj->mmo.lock);
617 			return mmo;
618 		}
619 
620 		if (mmo->mmap_type < mmap_type)
621 			rb = rb->rb_right;
622 		else
623 			rb = rb->rb_left;
624 	}
625 	spin_unlock(&obj->mmo.lock);
626 
627 	return NULL;
628 }
629 
630 static struct i915_mmap_offset *
631 insert_mmo(struct drm_i915_gem_object *obj, struct i915_mmap_offset *mmo)
632 {
633 	struct rb_node *rb, **p;
634 
635 	spin_lock(&obj->mmo.lock);
636 	rb = NULL;
637 	p = &obj->mmo.offsets.rb_node;
638 	while (*p) {
639 		struct i915_mmap_offset *pos;
640 
641 		rb = *p;
642 		pos = rb_entry(rb, typeof(*pos), offset);
643 
644 		if (pos->mmap_type == mmo->mmap_type) {
645 			spin_unlock(&obj->mmo.lock);
646 			drm_vma_offset_remove(obj->base.dev->vma_offset_manager,
647 					      &mmo->vma_node);
648 			kfree(mmo);
649 			return pos;
650 		}
651 
652 		if (pos->mmap_type < mmo->mmap_type)
653 			p = &rb->rb_right;
654 		else
655 			p = &rb->rb_left;
656 	}
657 	rb_link_node(&mmo->offset, rb, p);
658 	rb_insert_color(&mmo->offset, &obj->mmo.offsets);
659 	spin_unlock(&obj->mmo.lock);
660 
661 	return mmo;
662 }
663 
664 static struct i915_mmap_offset *
665 mmap_offset_attach(struct drm_i915_gem_object *obj,
666 		   enum i915_mmap_type mmap_type,
667 		   struct drm_file *file)
668 {
669 	struct drm_i915_private *i915 = to_i915(obj->base.dev);
670 	struct i915_mmap_offset *mmo;
671 	int err;
672 
673 	GEM_BUG_ON(obj->ops->mmap_offset || obj->ops->mmap_ops);
674 
675 	mmo = lookup_mmo(obj, mmap_type);
676 	if (mmo)
677 		goto out;
678 
679 	mmo = kmalloc(sizeof(*mmo), GFP_KERNEL);
680 	if (!mmo)
681 		return ERR_PTR(-ENOMEM);
682 
683 	mmo->obj = obj;
684 	mmo->mmap_type = mmap_type;
685 	drm_vma_node_reset(&mmo->vma_node);
686 
687 	err = drm_vma_offset_add(obj->base.dev->vma_offset_manager,
688 				 &mmo->vma_node, obj->base.size / PAGE_SIZE);
689 	if (likely(!err))
690 		goto insert;
691 
692 	/* Attempt to reap some mmap space from dead objects */
693 	err = intel_gt_retire_requests_timeout(to_gt(i915), MAX_SCHEDULE_TIMEOUT,
694 					       NULL);
695 	if (err)
696 		goto err;
697 
698 	i915_gem_drain_freed_objects(i915);
699 	err = drm_vma_offset_add(obj->base.dev->vma_offset_manager,
700 				 &mmo->vma_node, obj->base.size / PAGE_SIZE);
701 	if (err)
702 		goto err;
703 
704 insert:
705 	mmo = insert_mmo(obj, mmo);
706 	GEM_BUG_ON(lookup_mmo(obj, mmap_type) != mmo);
707 out:
708 	if (file)
709 		drm_vma_node_allow_once(&mmo->vma_node, file);
710 	return mmo;
711 
712 err:
713 	kfree(mmo);
714 	return ERR_PTR(err);
715 }
716 
717 static int
718 __assign_mmap_offset(struct drm_i915_gem_object *obj,
719 		     enum i915_mmap_type mmap_type,
720 		     u64 *offset, struct drm_file *file)
721 {
722 	struct i915_mmap_offset *mmo;
723 
724 	if (i915_gem_object_never_mmap(obj))
725 		return -ENODEV;
726 
727 	if (obj->ops->mmap_offset)  {
728 		if (mmap_type != I915_MMAP_TYPE_FIXED)
729 			return -ENODEV;
730 
731 		*offset = obj->ops->mmap_offset(obj);
732 		return 0;
733 	}
734 
735 	if (mmap_type == I915_MMAP_TYPE_FIXED)
736 		return -ENODEV;
737 
738 	if (mmap_type != I915_MMAP_TYPE_GTT &&
739 	    !i915_gem_object_has_struct_page(obj) &&
740 	    !i915_gem_object_has_iomem(obj))
741 		return -ENODEV;
742 
743 	mmo = mmap_offset_attach(obj, mmap_type, file);
744 	if (IS_ERR(mmo))
745 		return PTR_ERR(mmo);
746 
747 	*offset = drm_vma_node_offset_addr(&mmo->vma_node);
748 	return 0;
749 }
750 
751 static int
752 __assign_mmap_offset_handle(struct drm_file *file,
753 			    u32 handle,
754 			    enum i915_mmap_type mmap_type,
755 			    u64 *offset)
756 {
757 	struct drm_i915_gem_object *obj;
758 	int err;
759 
760 	obj = i915_gem_object_lookup(file, handle);
761 	if (!obj)
762 		return -ENOENT;
763 
764 	err = i915_gem_object_lock_interruptible(obj, NULL);
765 	if (err)
766 		goto out_put;
767 	err = __assign_mmap_offset(obj, mmap_type, offset, file);
768 	i915_gem_object_unlock(obj);
769 out_put:
770 	i915_gem_object_put(obj);
771 	return err;
772 }
773 
774 int
775 i915_gem_dumb_mmap_offset(struct drm_file *file,
776 			  struct drm_device *dev,
777 			  u32 handle,
778 			  u64 *offset)
779 {
780 	struct drm_i915_private *i915 = to_i915(dev);
781 	enum i915_mmap_type mmap_type;
782 
783 	if (HAS_LMEM(to_i915(dev)))
784 		mmap_type = I915_MMAP_TYPE_FIXED;
785 	else if (pat_enabled())
786 		mmap_type = I915_MMAP_TYPE_WC;
787 	else if (!i915_ggtt_has_aperture(to_gt(i915)->ggtt))
788 		return -ENODEV;
789 	else
790 		mmap_type = I915_MMAP_TYPE_GTT;
791 
792 	return __assign_mmap_offset_handle(file, handle, mmap_type, offset);
793 }
794 
795 /**
796  * i915_gem_mmap_offset_ioctl - prepare an object for GTT mmap'ing
797  * @dev: DRM device
798  * @data: GTT mapping ioctl data
799  * @file: GEM object info
800  *
801  * Simply returns the fake offset to userspace so it can mmap it.
802  * The mmap call will end up in drm_gem_mmap(), which will set things
803  * up so we can get faults in the handler above.
804  *
805  * The fault handler will take care of binding the object into the GTT
806  * (since it may have been evicted to make room for something), allocating
807  * a fence register, and mapping the appropriate aperture address into
808  * userspace.
809  */
810 int
811 i915_gem_mmap_offset_ioctl(struct drm_device *dev, void *data,
812 			   struct drm_file *file)
813 {
814 	struct drm_i915_private *i915 = to_i915(dev);
815 	struct drm_i915_gem_mmap_offset *args = data;
816 	enum i915_mmap_type type;
817 	int err;
818 
819 	/*
820 	 * Historically we failed to check args.pad and args.offset
821 	 * and so we cannot use those fields for user input and we cannot
822 	 * add -EINVAL for them as the ABI is fixed, i.e. old userspace
823 	 * may be feeding in garbage in those fields.
824 	 *
825 	 * if (args->pad) return -EINVAL; is verbotten!
826 	 */
827 
828 	err = i915_user_extensions(u64_to_user_ptr(args->extensions),
829 				   NULL, 0, NULL);
830 	if (err)
831 		return err;
832 
833 	switch (args->flags) {
834 	case I915_MMAP_OFFSET_GTT:
835 		if (!i915_ggtt_has_aperture(to_gt(i915)->ggtt))
836 			return -ENODEV;
837 		type = I915_MMAP_TYPE_GTT;
838 		break;
839 
840 	case I915_MMAP_OFFSET_WC:
841 		if (!pat_enabled())
842 			return -ENODEV;
843 		type = I915_MMAP_TYPE_WC;
844 		break;
845 
846 	case I915_MMAP_OFFSET_WB:
847 		type = I915_MMAP_TYPE_WB;
848 		break;
849 
850 	case I915_MMAP_OFFSET_UC:
851 		if (!pat_enabled())
852 			return -ENODEV;
853 		type = I915_MMAP_TYPE_UC;
854 		break;
855 
856 	case I915_MMAP_OFFSET_FIXED:
857 		type = I915_MMAP_TYPE_FIXED;
858 		break;
859 
860 	default:
861 		return -EINVAL;
862 	}
863 
864 	return __assign_mmap_offset_handle(file, args->handle, type, &args->offset);
865 }
866 
867 static void vm_open(struct vm_area_struct *vma)
868 {
869 	struct i915_mmap_offset *mmo = vma->vm_private_data;
870 	struct drm_i915_gem_object *obj = mmo->obj;
871 
872 	GEM_BUG_ON(!obj);
873 	i915_gem_object_get(obj);
874 }
875 
876 static void vm_close(struct vm_area_struct *vma)
877 {
878 	struct i915_mmap_offset *mmo = vma->vm_private_data;
879 	struct drm_i915_gem_object *obj = mmo->obj;
880 
881 	GEM_BUG_ON(!obj);
882 	i915_gem_object_put(obj);
883 }
884 
885 static const struct vm_operations_struct vm_ops_gtt = {
886 	.fault = vm_fault_gtt,
887 	.access = vm_access,
888 	.open = vm_open,
889 	.close = vm_close,
890 };
891 
892 static const struct vm_operations_struct vm_ops_cpu = {
893 	.fault = vm_fault_cpu,
894 	.access = vm_access,
895 	.open = vm_open,
896 	.close = vm_close,
897 };
898 
899 static int singleton_release(struct inode *inode, struct file *file)
900 {
901 	struct drm_i915_private *i915 = file->private_data;
902 
903 	cmpxchg(&i915->gem.mmap_singleton, file, NULL);
904 	drm_dev_put(&i915->drm);
905 
906 	return 0;
907 }
908 
909 static const struct file_operations singleton_fops = {
910 	.owner = THIS_MODULE,
911 	.release = singleton_release,
912 };
913 
914 static struct file *mmap_singleton(struct drm_i915_private *i915)
915 {
916 	struct file *file;
917 
918 	rcu_read_lock();
919 	file = READ_ONCE(i915->gem.mmap_singleton);
920 	if (file && !get_file_rcu(file))
921 		file = NULL;
922 	rcu_read_unlock();
923 	if (file)
924 		return file;
925 
926 	file = anon_inode_getfile("i915.gem", &singleton_fops, i915, O_RDWR);
927 	if (IS_ERR(file))
928 		return file;
929 
930 	/* Everyone shares a single global address space */
931 	file->f_mapping = i915->drm.anon_inode->i_mapping;
932 
933 	smp_store_mb(i915->gem.mmap_singleton, file);
934 	drm_dev_get(&i915->drm);
935 
936 	return file;
937 }
938 
939 static int
940 i915_gem_object_mmap(struct drm_i915_gem_object *obj,
941 		     struct i915_mmap_offset *mmo,
942 		     struct vm_area_struct *vma)
943 {
944 	struct drm_i915_private *i915 = to_i915(obj->base.dev);
945 	struct drm_device *dev = &i915->drm;
946 	struct file *anon;
947 
948 	if (i915_gem_object_is_readonly(obj)) {
949 		if (vma->vm_flags & VM_WRITE) {
950 			i915_gem_object_put(obj);
951 			return -EINVAL;
952 		}
953 		vm_flags_clear(vma, VM_MAYWRITE);
954 	}
955 
956 	anon = mmap_singleton(to_i915(dev));
957 	if (IS_ERR(anon)) {
958 		i915_gem_object_put(obj);
959 		return PTR_ERR(anon);
960 	}
961 
962 	vm_flags_set(vma, VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP | VM_IO);
963 
964 	/*
965 	 * We keep the ref on mmo->obj, not vm_file, but we require
966 	 * vma->vm_file->f_mapping, see vma_link(), for later revocation.
967 	 * Our userspace is accustomed to having per-file resource cleanup
968 	 * (i.e. contexts, objects and requests) on their close(fd), which
969 	 * requires avoiding extraneous references to their filp, hence why
970 	 * we prefer to use an anonymous file for their mmaps.
971 	 */
972 	vma_set_file(vma, anon);
973 	/* Drop the initial creation reference, the vma is now holding one. */
974 	fput(anon);
975 
976 	if (obj->ops->mmap_ops) {
977 		vma->vm_page_prot = pgprot_decrypted(vm_get_page_prot(vma->vm_flags));
978 		vma->vm_ops = obj->ops->mmap_ops;
979 		vma->vm_private_data = obj->base.vma_node.driver_private;
980 		return 0;
981 	}
982 
983 	vma->vm_private_data = mmo;
984 
985 	switch (mmo->mmap_type) {
986 	case I915_MMAP_TYPE_WC:
987 		vma->vm_page_prot =
988 			pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
989 		vma->vm_ops = &vm_ops_cpu;
990 		break;
991 
992 	case I915_MMAP_TYPE_FIXED:
993 		GEM_WARN_ON(1);
994 		fallthrough;
995 	case I915_MMAP_TYPE_WB:
996 		vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
997 		vma->vm_ops = &vm_ops_cpu;
998 		break;
999 
1000 	case I915_MMAP_TYPE_UC:
1001 		vma->vm_page_prot =
1002 			pgprot_noncached(vm_get_page_prot(vma->vm_flags));
1003 		vma->vm_ops = &vm_ops_cpu;
1004 		break;
1005 
1006 	case I915_MMAP_TYPE_GTT:
1007 		vma->vm_page_prot =
1008 			pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
1009 		vma->vm_ops = &vm_ops_gtt;
1010 		break;
1011 	}
1012 	vma->vm_page_prot = pgprot_decrypted(vma->vm_page_prot);
1013 
1014 	return 0;
1015 }
1016 
1017 /*
1018  * This overcomes the limitation in drm_gem_mmap's assignment of a
1019  * drm_gem_object as the vma->vm_private_data. Since we need to
1020  * be able to resolve multiple mmap offsets which could be tied
1021  * to a single gem object.
1022  */
1023 int i915_gem_mmap(struct file *filp, struct vm_area_struct *vma)
1024 {
1025 	struct drm_vma_offset_node *node;
1026 	struct drm_file *priv = filp->private_data;
1027 	struct drm_device *dev = priv->minor->dev;
1028 	struct drm_i915_gem_object *obj = NULL;
1029 	struct i915_mmap_offset *mmo = NULL;
1030 
1031 	if (drm_dev_is_unplugged(dev))
1032 		return -ENODEV;
1033 
1034 	rcu_read_lock();
1035 	drm_vma_offset_lock_lookup(dev->vma_offset_manager);
1036 	node = drm_vma_offset_exact_lookup_locked(dev->vma_offset_manager,
1037 						  vma->vm_pgoff,
1038 						  vma_pages(vma));
1039 	if (node && drm_vma_node_is_allowed(node, priv)) {
1040 		/*
1041 		 * Skip 0-refcnted objects as it is in the process of being
1042 		 * destroyed and will be invalid when the vma manager lock
1043 		 * is released.
1044 		 */
1045 		if (!node->driver_private) {
1046 			mmo = container_of(node, struct i915_mmap_offset, vma_node);
1047 			obj = i915_gem_object_get_rcu(mmo->obj);
1048 
1049 			GEM_BUG_ON(obj && obj->ops->mmap_ops);
1050 		} else {
1051 			obj = i915_gem_object_get_rcu
1052 				(container_of(node, struct drm_i915_gem_object,
1053 					      base.vma_node));
1054 
1055 			GEM_BUG_ON(obj && !obj->ops->mmap_ops);
1056 		}
1057 	}
1058 	drm_vma_offset_unlock_lookup(dev->vma_offset_manager);
1059 	rcu_read_unlock();
1060 	if (!obj)
1061 		return node ? -EACCES : -EINVAL;
1062 
1063 	return i915_gem_object_mmap(obj, mmo, vma);
1064 }
1065 
1066 int i915_gem_fb_mmap(struct drm_i915_gem_object *obj, struct vm_area_struct *vma)
1067 {
1068 	struct drm_i915_private *i915 = to_i915(obj->base.dev);
1069 	struct drm_device *dev = &i915->drm;
1070 	struct i915_mmap_offset *mmo = NULL;
1071 	enum i915_mmap_type mmap_type;
1072 	struct i915_ggtt *ggtt = to_gt(i915)->ggtt;
1073 
1074 	if (drm_dev_is_unplugged(dev))
1075 		return -ENODEV;
1076 
1077 	/* handle ttm object */
1078 	if (obj->ops->mmap_ops) {
1079 		/*
1080 		 * ttm fault handler, ttm_bo_vm_fault_reserved() uses fake offset
1081 		 * to calculate page offset so set that up.
1082 		 */
1083 		vma->vm_pgoff += drm_vma_node_start(&obj->base.vma_node);
1084 	} else {
1085 		/* handle stolen and smem objects */
1086 		mmap_type = i915_ggtt_has_aperture(ggtt) ? I915_MMAP_TYPE_GTT : I915_MMAP_TYPE_WC;
1087 		mmo = mmap_offset_attach(obj, mmap_type, NULL);
1088 		if (IS_ERR(mmo))
1089 			return PTR_ERR(mmo);
1090 	}
1091 
1092 	/*
1093 	 * When we install vm_ops for mmap we are too late for
1094 	 * the vm_ops->open() which increases the ref_count of
1095 	 * this obj and then it gets decreased by the vm_ops->close().
1096 	 * To balance this increase the obj ref_count here.
1097 	 */
1098 	obj = i915_gem_object_get(obj);
1099 	return i915_gem_object_mmap(obj, mmo, vma);
1100 }
1101 
1102 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
1103 #include "selftests/i915_gem_mman.c"
1104 #endif
1105