xref: /openbmc/linux/drivers/gpu/drm/ttm/ttm_bo_vm.c (revision 70a59dd8)
1 /* SPDX-License-Identifier: GPL-2.0 OR MIT */
2 /**************************************************************************
3  *
4  * Copyright (c) 2006-2009 VMware, Inc., Palo Alto, CA., USA
5  * All Rights Reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a
8  * copy of this software and associated documentation files (the
9  * "Software"), to deal in the Software without restriction, including
10  * without limitation the rights to use, copy, modify, merge, publish,
11  * distribute, sub license, and/or sell copies of the Software, and to
12  * permit persons to whom the Software is furnished to do so, subject to
13  * the following conditions:
14  *
15  * The above copyright notice and this permission notice (including the
16  * next paragraph) shall be included in all copies or substantial portions
17  * of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
22  * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
23  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
24  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
25  * USE OR OTHER DEALINGS IN THE SOFTWARE.
26  *
27  **************************************************************************/
28 /*
29  * Authors: Thomas Hellstrom <thellstrom-at-vmware-dot-com>
30  */
31 
32 #define pr_fmt(fmt) "[TTM] " fmt
33 
34 #include <drm/ttm/ttm_module.h>
35 #include <drm/ttm/ttm_bo_driver.h>
36 #include <drm/ttm/ttm_placement.h>
37 #include <drm/drm_vma_manager.h>
38 #include <linux/mm.h>
39 #include <linux/pfn_t.h>
40 #include <linux/rbtree.h>
41 #include <linux/module.h>
42 #include <linux/uaccess.h>
43 #include <linux/mem_encrypt.h>
44 
45 static vm_fault_t ttm_bo_vm_fault_idle(struct ttm_buffer_object *bo,
46 				struct vm_fault *vmf)
47 {
48 	vm_fault_t ret = 0;
49 	int err = 0;
50 
51 	if (likely(!bo->moving))
52 		goto out_unlock;
53 
54 	/*
55 	 * Quick non-stalling check for idle.
56 	 */
57 	if (dma_fence_is_signaled(bo->moving))
58 		goto out_clear;
59 
60 	/*
61 	 * If possible, avoid waiting for GPU with mmap_lock
62 	 * held.  We only do this if the fault allows retry and this
63 	 * is the first attempt.
64 	 */
65 	if (fault_flag_allow_retry_first(vmf->flags)) {
66 		ret = VM_FAULT_RETRY;
67 		if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
68 			goto out_unlock;
69 
70 		ttm_bo_get(bo);
71 		mmap_read_unlock(vmf->vma->vm_mm);
72 		(void) dma_fence_wait(bo->moving, true);
73 		dma_resv_unlock(bo->base.resv);
74 		ttm_bo_put(bo);
75 		goto out_unlock;
76 	}
77 
78 	/*
79 	 * Ordinary wait.
80 	 */
81 	err = dma_fence_wait(bo->moving, true);
82 	if (unlikely(err != 0)) {
83 		ret = (err != -ERESTARTSYS) ? VM_FAULT_SIGBUS :
84 			VM_FAULT_NOPAGE;
85 		goto out_unlock;
86 	}
87 
88 out_clear:
89 	dma_fence_put(bo->moving);
90 	bo->moving = NULL;
91 
92 out_unlock:
93 	return ret;
94 }
95 
96 static unsigned long ttm_bo_io_mem_pfn(struct ttm_buffer_object *bo,
97 				       unsigned long page_offset)
98 {
99 	struct ttm_bo_device *bdev = bo->bdev;
100 
101 	if (bdev->driver->io_mem_pfn)
102 		return bdev->driver->io_mem_pfn(bo, page_offset);
103 
104 	return (bo->mem.bus.offset >> PAGE_SHIFT) + page_offset;
105 }
106 
107 /**
108  * ttm_bo_vm_reserve - Reserve a buffer object in a retryable vm callback
109  * @bo: The buffer object
110  * @vmf: The fault structure handed to the callback
111  *
112  * vm callbacks like fault() and *_mkwrite() allow for the mm_sem to be dropped
113  * during long waits, and after the wait the callback will be restarted. This
114  * is to allow other threads using the same virtual memory space concurrent
115  * access to map(), unmap() completely unrelated buffer objects. TTM buffer
116  * object reservations sometimes wait for GPU and should therefore be
117  * considered long waits. This function reserves the buffer object interruptibly
118  * taking this into account. Starvation is avoided by the vm system not
119  * allowing too many repeated restarts.
120  * This function is intended to be used in customized fault() and _mkwrite()
121  * handlers.
122  *
123  * Return:
124  *    0 on success and the bo was reserved.
125  *    VM_FAULT_RETRY if blocking wait.
126  *    VM_FAULT_NOPAGE if blocking wait and retrying was not allowed.
127  */
128 vm_fault_t ttm_bo_vm_reserve(struct ttm_buffer_object *bo,
129 			     struct vm_fault *vmf)
130 {
131 	/*
132 	 * Work around locking order reversal in fault / nopfn
133 	 * between mmap_lock and bo_reserve: Perform a trylock operation
134 	 * for reserve, and if it fails, retry the fault after waiting
135 	 * for the buffer to become unreserved.
136 	 */
137 	if (unlikely(!dma_resv_trylock(bo->base.resv))) {
138 		/*
139 		 * If the fault allows retry and this is the first
140 		 * fault attempt, we try to release the mmap_lock
141 		 * before waiting
142 		 */
143 		if (fault_flag_allow_retry_first(vmf->flags)) {
144 			if (!(vmf->flags & FAULT_FLAG_RETRY_NOWAIT)) {
145 				ttm_bo_get(bo);
146 				mmap_read_unlock(vmf->vma->vm_mm);
147 				if (!dma_resv_lock_interruptible(bo->base.resv,
148 								 NULL))
149 					dma_resv_unlock(bo->base.resv);
150 				ttm_bo_put(bo);
151 			}
152 
153 			return VM_FAULT_RETRY;
154 		}
155 
156 		if (dma_resv_lock_interruptible(bo->base.resv, NULL))
157 			return VM_FAULT_NOPAGE;
158 	}
159 
160 	/*
161 	 * Refuse to fault imported pages. This should be handled
162 	 * (if at all) by redirecting mmap to the exporter.
163 	 */
164 	if (bo->ttm && (bo->ttm->page_flags & TTM_PAGE_FLAG_SG)) {
165 		dma_resv_unlock(bo->base.resv);
166 		return VM_FAULT_SIGBUS;
167 	}
168 
169 	return 0;
170 }
171 EXPORT_SYMBOL(ttm_bo_vm_reserve);
172 
173 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
174 /**
175  * ttm_bo_vm_insert_huge - Insert a pfn for PUD or PMD faults
176  * @vmf: Fault data
177  * @bo: The buffer object
178  * @page_offset: Page offset from bo start
179  * @fault_page_size: The size of the fault in pages.
180  * @pgprot: The page protections.
181  * Does additional checking whether it's possible to insert a PUD or PMD
182  * pfn and performs the insertion.
183  *
184  * Return: VM_FAULT_NOPAGE on successful insertion, VM_FAULT_FALLBACK if
185  * a huge fault was not possible, or on insertion error.
186  */
187 static vm_fault_t ttm_bo_vm_insert_huge(struct vm_fault *vmf,
188 					struct ttm_buffer_object *bo,
189 					pgoff_t page_offset,
190 					pgoff_t fault_page_size,
191 					pgprot_t pgprot)
192 {
193 	pgoff_t i;
194 	vm_fault_t ret;
195 	unsigned long pfn;
196 	pfn_t pfnt;
197 	struct ttm_tt *ttm = bo->ttm;
198 	bool write = vmf->flags & FAULT_FLAG_WRITE;
199 
200 	/* Fault should not cross bo boundary. */
201 	page_offset &= ~(fault_page_size - 1);
202 	if (page_offset + fault_page_size > bo->num_pages)
203 		goto out_fallback;
204 
205 	if (bo->mem.bus.is_iomem)
206 		pfn = ttm_bo_io_mem_pfn(bo, page_offset);
207 	else
208 		pfn = page_to_pfn(ttm->pages[page_offset]);
209 
210 	/* pfn must be fault_page_size aligned. */
211 	if ((pfn & (fault_page_size - 1)) != 0)
212 		goto out_fallback;
213 
214 	/* Check that memory is contiguous. */
215 	if (!bo->mem.bus.is_iomem) {
216 		for (i = 1; i < fault_page_size; ++i) {
217 			if (page_to_pfn(ttm->pages[page_offset + i]) != pfn + i)
218 				goto out_fallback;
219 		}
220 	} else if (bo->bdev->driver->io_mem_pfn) {
221 		for (i = 1; i < fault_page_size; ++i) {
222 			if (ttm_bo_io_mem_pfn(bo, page_offset + i) != pfn + i)
223 				goto out_fallback;
224 		}
225 	}
226 
227 	pfnt = __pfn_to_pfn_t(pfn, PFN_DEV);
228 	if (fault_page_size == (HPAGE_PMD_SIZE >> PAGE_SHIFT))
229 		ret = vmf_insert_pfn_pmd_prot(vmf, pfnt, pgprot, write);
230 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
231 	else if (fault_page_size == (HPAGE_PUD_SIZE >> PAGE_SHIFT))
232 		ret = vmf_insert_pfn_pud_prot(vmf, pfnt, pgprot, write);
233 #endif
234 	else
235 		WARN_ON_ONCE(ret = VM_FAULT_FALLBACK);
236 
237 	if (ret != VM_FAULT_NOPAGE)
238 		goto out_fallback;
239 
240 	return VM_FAULT_NOPAGE;
241 out_fallback:
242 	count_vm_event(THP_FAULT_FALLBACK);
243 	return VM_FAULT_FALLBACK;
244 }
245 #else
246 static vm_fault_t ttm_bo_vm_insert_huge(struct vm_fault *vmf,
247 					struct ttm_buffer_object *bo,
248 					pgoff_t page_offset,
249 					pgoff_t fault_page_size,
250 					pgprot_t pgprot)
251 {
252 	return VM_FAULT_FALLBACK;
253 }
254 #endif
255 
256 /**
257  * ttm_bo_vm_fault_reserved - TTM fault helper
258  * @vmf: The struct vm_fault given as argument to the fault callback
259  * @prot: The page protection to be used for this memory area.
260  * @num_prefault: Maximum number of prefault pages. The caller may want to
261  * specify this based on madvice settings and the size of the GPU object
262  * backed by the memory.
263  * @fault_page_size: The size of the fault in pages.
264  *
265  * This function inserts one or more page table entries pointing to the
266  * memory backing the buffer object, and then returns a return code
267  * instructing the caller to retry the page access.
268  *
269  * Return:
270  *   VM_FAULT_NOPAGE on success or pending signal
271  *   VM_FAULT_SIGBUS on unspecified error
272  *   VM_FAULT_OOM on out-of-memory
273  *   VM_FAULT_RETRY if retryable wait
274  */
275 vm_fault_t ttm_bo_vm_fault_reserved(struct vm_fault *vmf,
276 				    pgprot_t prot,
277 				    pgoff_t num_prefault,
278 				    pgoff_t fault_page_size)
279 {
280 	struct vm_area_struct *vma = vmf->vma;
281 	struct ttm_buffer_object *bo = vma->vm_private_data;
282 	struct ttm_bo_device *bdev = bo->bdev;
283 	unsigned long page_offset;
284 	unsigned long page_last;
285 	unsigned long pfn;
286 	struct ttm_tt *ttm = NULL;
287 	struct page *page;
288 	int err;
289 	pgoff_t i;
290 	vm_fault_t ret = VM_FAULT_NOPAGE;
291 	unsigned long address = vmf->address;
292 
293 	/*
294 	 * Wait for buffer data in transit, due to a pipelined
295 	 * move.
296 	 */
297 	ret = ttm_bo_vm_fault_idle(bo, vmf);
298 	if (unlikely(ret != 0))
299 		return ret;
300 
301 	err = ttm_mem_io_reserve(bdev, &bo->mem);
302 	if (unlikely(err != 0))
303 		return VM_FAULT_SIGBUS;
304 
305 	page_offset = ((address - vma->vm_start) >> PAGE_SHIFT) +
306 		vma->vm_pgoff - drm_vma_node_start(&bo->base.vma_node);
307 	page_last = vma_pages(vma) + vma->vm_pgoff -
308 		drm_vma_node_start(&bo->base.vma_node);
309 
310 	if (unlikely(page_offset >= bo->num_pages))
311 		return VM_FAULT_SIGBUS;
312 
313 	prot = ttm_io_prot(bo, &bo->mem, prot);
314 	if (!bo->mem.bus.is_iomem) {
315 		struct ttm_operation_ctx ctx = {
316 			.interruptible = false,
317 			.no_wait_gpu = false,
318 			.force_alloc = true
319 		};
320 
321 		ttm = bo->ttm;
322 		if (ttm_tt_populate(bdev, bo->ttm, &ctx))
323 			return VM_FAULT_OOM;
324 	} else {
325 		/* Iomem should not be marked encrypted */
326 		prot = pgprot_decrypted(prot);
327 	}
328 
329 	/* We don't prefault on huge faults. Yet. */
330 	if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && fault_page_size != 1)
331 		return ttm_bo_vm_insert_huge(vmf, bo, page_offset,
332 					     fault_page_size, prot);
333 
334 	/*
335 	 * Speculatively prefault a number of pages. Only error on
336 	 * first page.
337 	 */
338 	for (i = 0; i < num_prefault; ++i) {
339 		if (bo->mem.bus.is_iomem) {
340 			pfn = ttm_bo_io_mem_pfn(bo, page_offset);
341 		} else {
342 			page = ttm->pages[page_offset];
343 			if (unlikely(!page && i == 0)) {
344 				return VM_FAULT_OOM;
345 			} else if (unlikely(!page)) {
346 				break;
347 			}
348 			page->index = drm_vma_node_start(&bo->base.vma_node) +
349 				page_offset;
350 			pfn = page_to_pfn(page);
351 		}
352 
353 		/*
354 		 * Note that the value of @prot at this point may differ from
355 		 * the value of @vma->vm_page_prot in the caching- and
356 		 * encryption bits. This is because the exact location of the
357 		 * data may not be known at mmap() time and may also change
358 		 * at arbitrary times while the data is mmap'ed.
359 		 * See vmf_insert_mixed_prot() for a discussion.
360 		 */
361 		if (vma->vm_flags & VM_MIXEDMAP)
362 			ret = vmf_insert_mixed_prot(vma, address,
363 						    __pfn_to_pfn_t(pfn, PFN_DEV),
364 						    prot);
365 		else
366 			ret = vmf_insert_pfn_prot(vma, address, pfn, prot);
367 
368 		/* Never error on prefaulted PTEs */
369 		if (unlikely((ret & VM_FAULT_ERROR))) {
370 			if (i == 0)
371 				return VM_FAULT_NOPAGE;
372 			else
373 				break;
374 		}
375 
376 		address += PAGE_SIZE;
377 		if (unlikely(++page_offset >= page_last))
378 			break;
379 	}
380 	return ret;
381 }
382 EXPORT_SYMBOL(ttm_bo_vm_fault_reserved);
383 
384 vm_fault_t ttm_bo_vm_fault(struct vm_fault *vmf)
385 {
386 	struct vm_area_struct *vma = vmf->vma;
387 	pgprot_t prot;
388 	struct ttm_buffer_object *bo = vma->vm_private_data;
389 	vm_fault_t ret;
390 
391 	ret = ttm_bo_vm_reserve(bo, vmf);
392 	if (ret)
393 		return ret;
394 
395 	prot = vma->vm_page_prot;
396 	ret = ttm_bo_vm_fault_reserved(vmf, prot, TTM_BO_VM_NUM_PREFAULT, 1);
397 	if (ret == VM_FAULT_RETRY && !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT))
398 		return ret;
399 
400 	dma_resv_unlock(bo->base.resv);
401 
402 	return ret;
403 }
404 EXPORT_SYMBOL(ttm_bo_vm_fault);
405 
406 void ttm_bo_vm_open(struct vm_area_struct *vma)
407 {
408 	struct ttm_buffer_object *bo = vma->vm_private_data;
409 
410 	WARN_ON(bo->bdev->dev_mapping != vma->vm_file->f_mapping);
411 
412 	ttm_bo_get(bo);
413 }
414 EXPORT_SYMBOL(ttm_bo_vm_open);
415 
416 void ttm_bo_vm_close(struct vm_area_struct *vma)
417 {
418 	struct ttm_buffer_object *bo = vma->vm_private_data;
419 
420 	ttm_bo_put(bo);
421 	vma->vm_private_data = NULL;
422 }
423 EXPORT_SYMBOL(ttm_bo_vm_close);
424 
425 static int ttm_bo_vm_access_kmap(struct ttm_buffer_object *bo,
426 				 unsigned long offset,
427 				 uint8_t *buf, int len, int write)
428 {
429 	unsigned long page = offset >> PAGE_SHIFT;
430 	unsigned long bytes_left = len;
431 	int ret;
432 
433 	/* Copy a page at a time, that way no extra virtual address
434 	 * mapping is needed
435 	 */
436 	offset -= page << PAGE_SHIFT;
437 	do {
438 		unsigned long bytes = min(bytes_left, PAGE_SIZE - offset);
439 		struct ttm_bo_kmap_obj map;
440 		void *ptr;
441 		bool is_iomem;
442 
443 		ret = ttm_bo_kmap(bo, page, 1, &map);
444 		if (ret)
445 			return ret;
446 
447 		ptr = (uint8_t *)ttm_kmap_obj_virtual(&map, &is_iomem) + offset;
448 		WARN_ON_ONCE(is_iomem);
449 		if (write)
450 			memcpy(ptr, buf, bytes);
451 		else
452 			memcpy(buf, ptr, bytes);
453 		ttm_bo_kunmap(&map);
454 
455 		page++;
456 		buf += bytes;
457 		bytes_left -= bytes;
458 		offset = 0;
459 	} while (bytes_left);
460 
461 	return len;
462 }
463 
464 int ttm_bo_vm_access(struct vm_area_struct *vma, unsigned long addr,
465 		     void *buf, int len, int write)
466 {
467 	struct ttm_buffer_object *bo = vma->vm_private_data;
468 	unsigned long offset = (addr) - vma->vm_start +
469 		((vma->vm_pgoff - drm_vma_node_start(&bo->base.vma_node))
470 		 << PAGE_SHIFT);
471 	int ret;
472 
473 	if (len < 1 || (offset + len) >> PAGE_SHIFT > bo->num_pages)
474 		return -EIO;
475 
476 	ret = ttm_bo_reserve(bo, true, false, NULL);
477 	if (ret)
478 		return ret;
479 
480 	switch (bo->mem.mem_type) {
481 	case TTM_PL_SYSTEM:
482 		if (unlikely(bo->ttm->page_flags & TTM_PAGE_FLAG_SWAPPED)) {
483 			ret = ttm_tt_swapin(bo->ttm);
484 			if (unlikely(ret != 0))
485 				return ret;
486 		}
487 		fallthrough;
488 	case TTM_PL_TT:
489 		ret = ttm_bo_vm_access_kmap(bo, offset, buf, len, write);
490 		break;
491 	default:
492 		if (bo->bdev->driver->access_memory)
493 			ret = bo->bdev->driver->access_memory(
494 				bo, offset, buf, len, write);
495 		else
496 			ret = -EIO;
497 	}
498 
499 	ttm_bo_unreserve(bo);
500 
501 	return ret;
502 }
503 EXPORT_SYMBOL(ttm_bo_vm_access);
504 
505 static const struct vm_operations_struct ttm_bo_vm_ops = {
506 	.fault = ttm_bo_vm_fault,
507 	.open = ttm_bo_vm_open,
508 	.close = ttm_bo_vm_close,
509 	.access = ttm_bo_vm_access,
510 };
511 
512 static struct ttm_buffer_object *ttm_bo_vm_lookup(struct ttm_bo_device *bdev,
513 						  unsigned long offset,
514 						  unsigned long pages)
515 {
516 	struct drm_vma_offset_node *node;
517 	struct ttm_buffer_object *bo = NULL;
518 
519 	drm_vma_offset_lock_lookup(bdev->vma_manager);
520 
521 	node = drm_vma_offset_lookup_locked(bdev->vma_manager, offset, pages);
522 	if (likely(node)) {
523 		bo = container_of(node, struct ttm_buffer_object,
524 				  base.vma_node);
525 		bo = ttm_bo_get_unless_zero(bo);
526 	}
527 
528 	drm_vma_offset_unlock_lookup(bdev->vma_manager);
529 
530 	if (!bo)
531 		pr_err("Could not find buffer object to map\n");
532 
533 	return bo;
534 }
535 
536 static void ttm_bo_mmap_vma_setup(struct ttm_buffer_object *bo, struct vm_area_struct *vma)
537 {
538 	vma->vm_ops = &ttm_bo_vm_ops;
539 
540 	/*
541 	 * Note: We're transferring the bo reference to
542 	 * vma->vm_private_data here.
543 	 */
544 
545 	vma->vm_private_data = bo;
546 
547 	/*
548 	 * We'd like to use VM_PFNMAP on shared mappings, where
549 	 * (vma->vm_flags & VM_SHARED) != 0, for performance reasons,
550 	 * but for some reason VM_PFNMAP + x86 PAT + write-combine is very
551 	 * bad for performance. Until that has been sorted out, use
552 	 * VM_MIXEDMAP on all mappings. See freedesktop.org bug #75719
553 	 */
554 	vma->vm_flags |= VM_MIXEDMAP;
555 	vma->vm_flags |= VM_IO | VM_DONTEXPAND | VM_DONTDUMP;
556 }
557 
558 int ttm_bo_mmap(struct file *filp, struct vm_area_struct *vma,
559 		struct ttm_bo_device *bdev)
560 {
561 	struct ttm_bo_driver *driver;
562 	struct ttm_buffer_object *bo;
563 	int ret;
564 
565 	if (unlikely(vma->vm_pgoff < DRM_FILE_PAGE_OFFSET_START))
566 		return -EINVAL;
567 
568 	bo = ttm_bo_vm_lookup(bdev, vma->vm_pgoff, vma_pages(vma));
569 	if (unlikely(!bo))
570 		return -EINVAL;
571 
572 	driver = bo->bdev->driver;
573 	if (unlikely(!driver->verify_access)) {
574 		ret = -EPERM;
575 		goto out_unref;
576 	}
577 	ret = driver->verify_access(bo, filp);
578 	if (unlikely(ret != 0))
579 		goto out_unref;
580 
581 	ttm_bo_mmap_vma_setup(bo, vma);
582 	return 0;
583 out_unref:
584 	ttm_bo_put(bo);
585 	return ret;
586 }
587 EXPORT_SYMBOL(ttm_bo_mmap);
588 
589 int ttm_bo_mmap_obj(struct vm_area_struct *vma, struct ttm_buffer_object *bo)
590 {
591 	ttm_bo_get(bo);
592 	ttm_bo_mmap_vma_setup(bo, vma);
593 	return 0;
594 }
595 EXPORT_SYMBOL(ttm_bo_mmap_obj);
596