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