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