xref: /linux/drivers/gpu/drm/ttm/ttm_bo_vm.c (revision 3a2c4d55e32ad65efebdb6de44eef3bfa08bb49d)
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 <linux/export.h>
35 #include <linux/pagemap.h>
36 
37 #include <drm/ttm/ttm_bo.h>
38 #include <drm/ttm/ttm_placement.h>
39 #include <drm/ttm/ttm_tt.h>
40 
41 #include <drm/drm_drv.h>
42 #include <drm/drm_managed.h>
43 
44 static vm_fault_t ttm_bo_vm_fault_idle(struct ttm_buffer_object *bo,
45 				struct vm_fault *vmf)
46 {
47 	long err = 0;
48 
49 	/*
50 	 * Quick non-stalling check for idle.
51 	 */
52 	if (dma_resv_test_signaled(bo->base.resv, DMA_RESV_USAGE_KERNEL))
53 		return 0;
54 
55 	/*
56 	 * If possible, avoid waiting for GPU with mmap_lock
57 	 * held.  We only do this if the fault allows retry and this
58 	 * is the first attempt.
59 	 */
60 	if (fault_flag_allow_retry_first(vmf->flags)) {
61 		if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
62 			return VM_FAULT_RETRY;
63 
64 		drm_gem_object_get(&bo->base);
65 		mmap_read_unlock(vmf->vma->vm_mm);
66 		(void)dma_resv_wait_timeout(bo->base.resv,
67 					    DMA_RESV_USAGE_KERNEL, true,
68 					    MAX_SCHEDULE_TIMEOUT);
69 		dma_resv_unlock(bo->base.resv);
70 		drm_gem_object_put(&bo->base);
71 		return VM_FAULT_RETRY;
72 	}
73 
74 	/*
75 	 * Ordinary wait.
76 	 */
77 	err = dma_resv_wait_timeout(bo->base.resv, DMA_RESV_USAGE_KERNEL, true,
78 				    MAX_SCHEDULE_TIMEOUT);
79 	if (unlikely(err < 0)) {
80 		return (err != -ERESTARTSYS) ? VM_FAULT_SIGBUS :
81 			VM_FAULT_NOPAGE;
82 	}
83 
84 	return 0;
85 }
86 
87 static unsigned long ttm_bo_io_mem_pfn(struct ttm_buffer_object *bo,
88 				       unsigned long page_offset)
89 {
90 	struct ttm_device *bdev = bo->bdev;
91 
92 	if (bdev->funcs->io_mem_pfn)
93 		return bdev->funcs->io_mem_pfn(bo, page_offset);
94 
95 	return (bo->resource->bus.offset >> PAGE_SHIFT) + page_offset;
96 }
97 
98 /**
99  * ttm_bo_vm_reserve - Reserve a buffer object in a retryable vm callback
100  * @bo: The buffer object
101  * @vmf: The fault structure handed to the callback
102  *
103  * vm callbacks like fault() and *_mkwrite() allow for the mmap_lock to be dropped
104  * during long waits, and after the wait the callback will be restarted. This
105  * is to allow other threads using the same virtual memory space concurrent
106  * access to map(), unmap() completely unrelated buffer objects. TTM buffer
107  * object reservations sometimes wait for GPU and should therefore be
108  * considered long waits. This function reserves the buffer object interruptibly
109  * taking this into account. Starvation is avoided by the vm system not
110  * allowing too many repeated restarts.
111  * This function is intended to be used in customized fault() and _mkwrite()
112  * handlers.
113  *
114  * Return:
115  *    0 on success and the bo was reserved.
116  *    VM_FAULT_RETRY if blocking wait.
117  *    VM_FAULT_NOPAGE if blocking wait and retrying was not allowed.
118  */
119 vm_fault_t ttm_bo_vm_reserve(struct ttm_buffer_object *bo,
120 			     struct vm_fault *vmf)
121 {
122 	/*
123 	 * Work around locking order reversal in fault / nopfn
124 	 * between mmap_lock and bo_reserve: Perform a trylock operation
125 	 * for reserve, and if it fails, retry the fault after waiting
126 	 * for the buffer to become unreserved.
127 	 */
128 	if (unlikely(!dma_resv_trylock(bo->base.resv))) {
129 		/*
130 		 * If the fault allows retry and this is the first
131 		 * fault attempt, we try to release the mmap_lock
132 		 * before waiting
133 		 */
134 		if (fault_flag_allow_retry_first(vmf->flags)) {
135 			if (!(vmf->flags & FAULT_FLAG_RETRY_NOWAIT)) {
136 				drm_gem_object_get(&bo->base);
137 				mmap_read_unlock(vmf->vma->vm_mm);
138 				if (!dma_resv_lock_interruptible(bo->base.resv,
139 								 NULL))
140 					dma_resv_unlock(bo->base.resv);
141 				drm_gem_object_put(&bo->base);
142 			}
143 
144 			return VM_FAULT_RETRY;
145 		}
146 
147 		if (dma_resv_lock_interruptible(bo->base.resv, NULL))
148 			return VM_FAULT_NOPAGE;
149 	}
150 
151 	/*
152 	 * Refuse to fault imported pages. This should be handled
153 	 * (if at all) by redirecting mmap to the exporter.
154 	 */
155 	if (bo->ttm && (bo->ttm->page_flags & TTM_TT_FLAG_EXTERNAL)) {
156 		if (!(bo->ttm->page_flags & TTM_TT_FLAG_EXTERNAL_MAPPABLE)) {
157 			dma_resv_unlock(bo->base.resv);
158 			return VM_FAULT_SIGBUS;
159 		}
160 	}
161 
162 	return 0;
163 }
164 EXPORT_SYMBOL(ttm_bo_vm_reserve);
165 
166 /**
167  * ttm_bo_vm_fault_reserved - TTM fault helper
168  * @vmf: The struct vm_fault given as argument to the fault callback
169  * @prot: The page protection to be used for this memory area.
170  * @num_prefault: Maximum number of prefault pages. The caller may want to
171  * specify this based on madvice settings and the size of the GPU object
172  * backed by the memory.
173  *
174  * This function inserts one or more page table entries pointing to the
175  * memory backing the buffer object, and then returns a return code
176  * instructing the caller to retry the page access.
177  *
178  * Return:
179  *   VM_FAULT_NOPAGE on success or pending signal
180  *   VM_FAULT_SIGBUS on unspecified error
181  *   VM_FAULT_OOM on out-of-memory
182  *   VM_FAULT_RETRY if retryable wait
183  */
184 vm_fault_t ttm_bo_vm_fault_reserved(struct vm_fault *vmf,
185 				    pgprot_t prot,
186 				    pgoff_t num_prefault)
187 {
188 	struct vm_area_struct *vma = vmf->vma;
189 	struct ttm_buffer_object *bo = vma->vm_private_data;
190 	unsigned long page_offset;
191 	unsigned long page_last;
192 	unsigned long pfn;
193 	struct ttm_tt *ttm = NULL;
194 	struct page *page;
195 	int err;
196 	pgoff_t i;
197 	vm_fault_t ret = VM_FAULT_NOPAGE;
198 	unsigned long address = vmf->address;
199 
200 	/*
201 	 * Wait for buffer data in transit, due to a pipelined
202 	 * move.
203 	 */
204 	ret = ttm_bo_vm_fault_idle(bo, vmf);
205 	if (unlikely(ret != 0))
206 		return ret;
207 
208 	err = ttm_mem_io_reserve(bo->bdev, bo->resource);
209 	if (unlikely(err != 0))
210 		return VM_FAULT_SIGBUS;
211 
212 	page_offset = linear_page_index(vma, address) -
213 		drm_vma_node_start(&bo->base.vma_node);
214 	page_last = vma_end_pgoff(vma) -
215 		drm_vma_node_start(&bo->base.vma_node);
216 
217 	if (unlikely(page_offset >= PFN_UP(bo->base.size)))
218 		return VM_FAULT_SIGBUS;
219 
220 	prot = ttm_io_prot(bo, bo->resource, prot);
221 	if (!bo->resource->bus.is_iomem) {
222 		struct ttm_operation_ctx ctx = {
223 			.interruptible = true,
224 			.no_wait_gpu = false,
225 		};
226 
227 		ttm = bo->ttm;
228 		err = ttm_bo_populate(bo, &ctx);
229 		if (err) {
230 			if (err == -EINTR || err == -ERESTARTSYS ||
231 			    err == -EAGAIN)
232 				return VM_FAULT_NOPAGE;
233 
234 			pr_debug("TTM fault hit %pe.\n", ERR_PTR(err));
235 			return VM_FAULT_SIGBUS;
236 		}
237 	} else {
238 		/* Iomem should not be marked encrypted */
239 		prot = pgprot_decrypted(prot);
240 	}
241 
242 	/*
243 	 * Speculatively prefault a number of pages. Only error on
244 	 * first page.
245 	 */
246 	for (i = 0; i < num_prefault; ++i) {
247 		if (bo->resource->bus.is_iomem) {
248 			pfn = ttm_bo_io_mem_pfn(bo, page_offset);
249 		} else {
250 			page = ttm->pages[page_offset];
251 			if (unlikely(!page && i == 0)) {
252 				return VM_FAULT_OOM;
253 			} else if (unlikely(!page)) {
254 				break;
255 			}
256 			pfn = page_to_pfn(page);
257 		}
258 
259 		/*
260 		 * Note that the value of @prot at this point may differ from
261 		 * the value of @vma->vm_page_prot in the caching- and
262 		 * encryption bits. This is because the exact location of the
263 		 * data may not be known at mmap() time and may also change
264 		 * at arbitrary times while the data is mmap'ed.
265 		 * See vmf_insert_pfn_prot() for a discussion.
266 		 */
267 		ret = vmf_insert_pfn_prot(vma, address, pfn, prot);
268 
269 		/* Never error on prefaulted PTEs */
270 		if (unlikely((ret & VM_FAULT_ERROR))) {
271 			if (i == 0)
272 				return VM_FAULT_NOPAGE;
273 			else
274 				break;
275 		}
276 
277 		address += PAGE_SIZE;
278 		if (unlikely(++page_offset >= page_last))
279 			break;
280 	}
281 	return ret;
282 }
283 EXPORT_SYMBOL(ttm_bo_vm_fault_reserved);
284 
285 static void ttm_bo_release_dummy_page(struct drm_device *dev, void *res)
286 {
287 	struct page *dummy_page = (struct page *)res;
288 
289 	__free_page(dummy_page);
290 }
291 
292 vm_fault_t ttm_bo_vm_dummy_page(struct vm_fault *vmf, pgprot_t prot)
293 {
294 	struct vm_area_struct *vma = vmf->vma;
295 	struct ttm_buffer_object *bo = vma->vm_private_data;
296 	vm_fault_t ret = VM_FAULT_NOPAGE;
297 	unsigned long address;
298 	unsigned long pfn;
299 	struct page *page;
300 
301 	/* Allocate new dummy page to map all the VA range in this VMA to it*/
302 	page = alloc_page(GFP_KERNEL | __GFP_ZERO);
303 	if (!page)
304 		return VM_FAULT_OOM;
305 
306 	/* Set the page to be freed using drmm release action */
307 	if (drmm_add_action_or_reset(bo->base.dev, ttm_bo_release_dummy_page,
308 				     page))
309 		return VM_FAULT_OOM;
310 
311 	pfn = page_to_pfn(page);
312 
313 	/* Prefault the entire VMA range right away to avoid further faults */
314 	for (address = vma->vm_start; address < vma->vm_end;
315 	     address += PAGE_SIZE)
316 		ret = vmf_insert_pfn_prot(vma, address, pfn, prot);
317 
318 	return ret;
319 }
320 EXPORT_SYMBOL(ttm_bo_vm_dummy_page);
321 
322 vm_fault_t ttm_bo_vm_fault(struct vm_fault *vmf)
323 {
324 	struct vm_area_struct *vma = vmf->vma;
325 	struct ttm_buffer_object *bo = vma->vm_private_data;
326 	vm_fault_t ret;
327 	pgprot_t prot;
328 	int idx;
329 
330 	ret = ttm_bo_vm_reserve(bo, vmf);
331 	if (ret)
332 		return ret;
333 
334 	prot = vma->vm_page_prot;
335 	if (drm_dev_enter(bo->base.dev, &idx)) {
336 		ret = ttm_bo_vm_fault_reserved(vmf, prot, TTM_BO_VM_NUM_PREFAULT);
337 		drm_dev_exit(idx);
338 	} else {
339 		ret = ttm_bo_vm_dummy_page(vmf, prot);
340 	}
341 	if (ret == VM_FAULT_RETRY && !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT))
342 		return ret;
343 
344 	dma_resv_unlock(bo->base.resv);
345 
346 	return ret;
347 }
348 EXPORT_SYMBOL(ttm_bo_vm_fault);
349 
350 void ttm_bo_vm_open(struct vm_area_struct *vma)
351 {
352 	struct ttm_buffer_object *bo = vma->vm_private_data;
353 
354 	WARN_ON(bo->bdev->dev_mapping != vma->vm_file->f_mapping);
355 
356 	drm_gem_object_get(&bo->base);
357 }
358 EXPORT_SYMBOL(ttm_bo_vm_open);
359 
360 void ttm_bo_vm_close(struct vm_area_struct *vma)
361 {
362 	struct ttm_buffer_object *bo = vma->vm_private_data;
363 
364 	drm_gem_object_put(&bo->base);
365 	vma->vm_private_data = NULL;
366 }
367 EXPORT_SYMBOL(ttm_bo_vm_close);
368 
369 static int ttm_bo_vm_access_kmap(struct ttm_buffer_object *bo,
370 				 unsigned long offset,
371 				 uint8_t *buf, int len, int write)
372 {
373 	unsigned long page = offset >> PAGE_SHIFT;
374 	unsigned long bytes_left = len;
375 	int ret;
376 
377 	/* Copy a page at a time, that way no extra virtual address
378 	 * mapping is needed
379 	 */
380 	offset -= page << PAGE_SHIFT;
381 	do {
382 		unsigned long bytes = min(bytes_left, PAGE_SIZE - offset);
383 		struct ttm_bo_kmap_obj map;
384 		void *ptr;
385 		bool is_iomem;
386 
387 		ret = ttm_bo_kmap(bo, page, 1, &map);
388 		if (ret)
389 			return ret;
390 
391 		ptr = (uint8_t *)ttm_kmap_obj_virtual(&map, &is_iomem) + offset;
392 		WARN_ON_ONCE(is_iomem);
393 		if (write)
394 			memcpy(ptr, buf, bytes);
395 		else
396 			memcpy(buf, ptr, bytes);
397 		ttm_bo_kunmap(&map);
398 
399 		page++;
400 		buf += bytes;
401 		bytes_left -= bytes;
402 		offset = 0;
403 	} while (bytes_left);
404 
405 	return len;
406 }
407 
408 /**
409  * ttm_bo_access - Helper to access a buffer object
410  *
411  * @bo: ttm buffer object
412  * @offset: access offset into buffer object
413  * @buf: pointer to caller memory to read into or write from
414  * @len: length of access
415  * @write: write access
416  *
417  * Utility function to access a buffer object. Useful when buffer object cannot
418  * be easily mapped (non-contiguous, non-visible, etc...). Should not directly
419  * be exported to user space via a peak / poke interface.
420  *
421  * Returns:
422  * @len if successful, negative error code on failure.
423  */
424 int ttm_bo_access(struct ttm_buffer_object *bo, unsigned long offset,
425 		  void *buf, int len, int write)
426 {
427 	int ret;
428 
429 	if (len < 1 || (offset + len) > bo->base.size)
430 		return -EIO;
431 
432 	ret = ttm_bo_reserve(bo, true, false, NULL);
433 	if (ret)
434 		return ret;
435 
436 	if (!bo->resource) {
437 		ret = -ENODATA;
438 		goto unlock;
439 	}
440 
441 	switch (bo->resource->mem_type) {
442 	case TTM_PL_SYSTEM:
443 		fallthrough;
444 	case TTM_PL_TT:
445 		ret = ttm_bo_vm_access_kmap(bo, offset, buf, len, write);
446 		break;
447 	default:
448 		if (bo->bdev->funcs->access_memory)
449 			ret = bo->bdev->funcs->access_memory
450 				(bo, offset, buf, len, write);
451 		else
452 			ret = -EIO;
453 	}
454 
455 unlock:
456 	ttm_bo_unreserve(bo);
457 
458 	return ret;
459 }
460 EXPORT_SYMBOL(ttm_bo_access);
461 
462 int ttm_bo_vm_access(struct vm_area_struct *vma, unsigned long addr,
463 		     void *buf, int len, int write)
464 {
465 	struct ttm_buffer_object *bo = vma->vm_private_data;
466 	unsigned long offset = (addr) - vma->vm_start +
467 		((vma->vm_pgoff - drm_vma_node_start(&bo->base.vma_node))
468 		 << PAGE_SHIFT);
469 
470 	return ttm_bo_access(bo, offset, buf, len, write);
471 }
472 EXPORT_SYMBOL(ttm_bo_vm_access);
473 
474 static const struct vm_operations_struct ttm_bo_vm_ops = {
475 	.fault = ttm_bo_vm_fault,
476 	.open = ttm_bo_vm_open,
477 	.close = ttm_bo_vm_close,
478 	.access = ttm_bo_vm_access,
479 };
480 
481 /**
482  * ttm_bo_mmap_obj - mmap memory backed by a ttm buffer object.
483  *
484  * @vma:       vma as input from the fbdev mmap method.
485  * @bo:        The bo backing the address space.
486  *
487  * Maps a buffer object.
488  */
489 int ttm_bo_mmap_obj(struct vm_area_struct *vma, struct ttm_buffer_object *bo)
490 {
491 	/* Enforce no COW since would have really strange behavior with it. */
492 	if (vma_is_cow_mapping(vma))
493 		return -EINVAL;
494 
495 	drm_gem_object_get(&bo->base);
496 
497 	/*
498 	 * Drivers may want to override the vm_ops field. Otherwise we
499 	 * use TTM's default callbacks.
500 	 */
501 	if (!vma->vm_ops)
502 		vma->vm_ops = &ttm_bo_vm_ops;
503 
504 	/*
505 	 * Note: We're transferring the bo reference to
506 	 * vma->vm_private_data here.
507 	 */
508 
509 	vma->vm_private_data = bo;
510 
511 	vm_flags_set(vma, VM_PFNMAP | VM_IO | VM_DONTEXPAND | VM_DONTDUMP);
512 	return 0;
513 }
514 EXPORT_SYMBOL(ttm_bo_mmap_obj);
515