• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2019 Collabora, Ltd.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21  * SOFTWARE.
22  *
23  * Authors (Collabora):
24  *   Alyssa Rosenzweig <alyssa.rosenzweig@collabora.com>
25  */
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <pthread.h>
29 #include <stdio.h>
30 #include <xf86drm.h>
31 
32 #include "pan_bo.h"
33 #include "pan_device.h"
34 #include "pan_util.h"
35 #include "wrap.h"
36 
37 #include "util/os_mman.h"
38 
39 #include "util/u_inlines.h"
40 #include "util/u_math.h"
41 
42 /* This file implements a userspace BO cache. Allocating and freeing
43  * GPU-visible buffers is very expensive, and even the extra kernel roundtrips
44  * adds more work than we would like at this point. So caching BOs in userspace
45  * solves both of these problems and does not require kernel updates.
46  *
47  * Cached BOs are sorted into a bucket based on rounding their size down to the
48  * nearest power-of-two. Each bucket contains a linked list of free panfrost_bo
49  * objects. Putting a BO into the cache is accomplished by adding it to the
50  * corresponding bucket. Getting a BO from the cache consists of finding the
51  * appropriate bucket and sorting. A cache eviction is a kernel-level free of a
52  * BO and removing it from the bucket. We special case evicting all BOs from
53  * the cache, since that's what helpful in practice and avoids extra logic
54  * around the linked list.
55  */
56 
57 static uint32_t
to_kmod_bo_flags(uint32_t flags)58 to_kmod_bo_flags(uint32_t flags)
59 {
60    uint32_t kmod_bo_flags = 0;
61 
62    if (flags & PAN_BO_EXECUTE)
63       kmod_bo_flags |= PAN_KMOD_BO_FLAG_EXECUTABLE;
64    if (flags & PAN_BO_GROWABLE)
65       kmod_bo_flags |= PAN_KMOD_BO_FLAG_ALLOC_ON_FAULT;
66    if (flags & PAN_BO_INVISIBLE)
67       kmod_bo_flags |= PAN_KMOD_BO_FLAG_NO_MMAP;
68 
69    return kmod_bo_flags;
70 }
71 
72 static struct panfrost_bo *
panfrost_bo_alloc(struct panfrost_device * dev,size_t size,uint32_t flags,const char * label)73 panfrost_bo_alloc(struct panfrost_device *dev, size_t size, uint32_t flags,
74                   const char *label)
75 {
76    struct pan_kmod_vm *exclusive_vm =
77       !(flags & PAN_BO_SHAREABLE) ? dev->kmod.vm : NULL;
78    struct pan_kmod_bo *kmod_bo;
79    struct panfrost_bo *bo;
80 
81    kmod_bo = pan_kmod_bo_alloc(dev->kmod.dev, exclusive_vm, size,
82                                to_kmod_bo_flags(flags));
83    assert(kmod_bo);
84 
85    bo = pan_lookup_bo(dev, kmod_bo->handle);
86    assert(!memcmp(bo, &((struct panfrost_bo){0}), sizeof(*bo)));
87    bo->kmod_bo = kmod_bo;
88 
89    struct pan_kmod_vm_op vm_op = {
90       .type = PAN_KMOD_VM_OP_TYPE_MAP,
91       .va =
92          {
93             .start = PAN_KMOD_VM_MAP_AUTO_VA,
94             .size = bo->kmod_bo->size,
95          },
96       .map =
97          {
98             .bo = bo->kmod_bo,
99             .bo_offset = 0,
100          },
101    };
102 
103    ASSERTED int ret =
104       pan_kmod_vm_bind(dev->kmod.vm, PAN_KMOD_VM_OP_MODE_IMMEDIATE, &vm_op, 1);
105    assert(!ret);
106 
107    bo->ptr.gpu = vm_op.va.start;
108    bo->flags = flags;
109    bo->dev = dev;
110    bo->label = label;
111    return bo;
112 }
113 
114 static void
panfrost_bo_free(struct panfrost_bo * bo)115 panfrost_bo_free(struct panfrost_bo *bo)
116 {
117    struct pan_kmod_bo *kmod_bo = bo->kmod_bo;
118    struct pan_kmod_vm *vm = bo->dev->kmod.vm;
119    uint64_t gpu_va = bo->ptr.gpu;
120 
121    /* BO will be freed with the sparse array, but zero to indicate free */
122    memset(bo, 0, sizeof(*bo));
123 
124    struct pan_kmod_vm_op vm_op = {
125       .type = PAN_KMOD_VM_OP_TYPE_UNMAP,
126       .va =
127          {
128             .start = gpu_va,
129             .size = kmod_bo->size,
130          },
131    };
132 
133    ASSERTED int ret = pan_kmod_vm_bind(
134       vm, PAN_KMOD_VM_OP_MODE_DEFER_TO_NEXT_IDLE_POINT, &vm_op, 1);
135    assert(!ret);
136 
137    pan_kmod_bo_put(kmod_bo);
138 }
139 
140 /* Returns true if the BO is ready, false otherwise.
141  * access_type is encoding the type of access one wants to ensure is done.
142  * Waiting is always done for writers, but if wait_readers is set then readers
143  * are also waited for.
144  */
145 bool
panfrost_bo_wait(struct panfrost_bo * bo,int64_t timeout_ns,bool wait_readers)146 panfrost_bo_wait(struct panfrost_bo *bo, int64_t timeout_ns, bool wait_readers)
147 {
148    /* If the BO has been exported or imported we can't rely on the cached
149     * state, we need to call the WAIT_BO ioctl.
150     */
151    if (!(bo->flags & PAN_BO_SHARED)) {
152       /* If ->gpu_access is 0, the BO is idle, no need to wait. */
153       if (!bo->gpu_access)
154          return true;
155 
156       /* If the caller only wants to wait for writers and no
157        * writes are pending, we don't have to wait.
158        */
159       if (!wait_readers && !(bo->gpu_access & PAN_BO_ACCESS_WRITE))
160          return true;
161    }
162 
163    if (pan_kmod_bo_wait(bo->kmod_bo, timeout_ns, !wait_readers)) {
164       /* Set gpu_access to 0 so that the next call to bo_wait()
165        * doesn't have to call the WAIT_BO ioctl.
166        */
167       bo->gpu_access = 0;
168       return true;
169    }
170 
171    return false;
172 }
173 
174 /* Helper to calculate the bucket index of a BO */
175 
176 static unsigned
pan_bucket_index(unsigned size)177 pan_bucket_index(unsigned size)
178 {
179    /* Round down to POT to compute a bucket index */
180 
181    unsigned bucket_index = util_logbase2(size);
182 
183    /* Clamp the bucket index; all huge allocations will be
184     * sorted into the largest bucket */
185 
186    bucket_index = CLAMP(bucket_index, MIN_BO_CACHE_BUCKET, MAX_BO_CACHE_BUCKET);
187 
188    /* Reindex from 0 */
189    return (bucket_index - MIN_BO_CACHE_BUCKET);
190 }
191 
192 static struct list_head *
pan_bucket(struct panfrost_device * dev,unsigned size)193 pan_bucket(struct panfrost_device *dev, unsigned size)
194 {
195    return &dev->bo_cache.buckets[pan_bucket_index(size)];
196 }
197 
198 /* Tries to fetch a BO of sufficient size with the appropriate flags from the
199  * BO cache. If it succeeds, it returns that BO and removes the BO from the
200  * cache. If it fails, it returns NULL signaling the caller to allocate a new
201  * BO. */
202 
203 static struct panfrost_bo *
panfrost_bo_cache_fetch(struct panfrost_device * dev,size_t size,uint32_t flags,const char * label,bool dontwait)204 panfrost_bo_cache_fetch(struct panfrost_device *dev, size_t size,
205                         uint32_t flags, const char *label, bool dontwait)
206 {
207    pthread_mutex_lock(&dev->bo_cache.lock);
208    struct list_head *bucket = pan_bucket(dev, size);
209    struct panfrost_bo *bo = NULL;
210 
211    /* Iterate the bucket looking for something suitable */
212    list_for_each_entry_safe(struct panfrost_bo, entry, bucket, bucket_link) {
213       if (panfrost_bo_size(entry) < size || entry->flags != flags)
214          continue;
215 
216       /* If the oldest BO in the cache is busy, likely so is
217        * everything newer, so bail. */
218       if (!panfrost_bo_wait(entry, dontwait ? 0 : INT64_MAX, true))
219          break;
220 
221       /* This one works, splice it out of the cache */
222       list_del(&entry->bucket_link);
223       list_del(&entry->lru_link);
224 
225       if (!pan_kmod_bo_make_unevictable(entry->kmod_bo)) {
226          panfrost_bo_free(entry);
227          continue;
228       }
229       /* Let's go! */
230       bo = entry;
231       bo->label = label;
232       break;
233    }
234    pthread_mutex_unlock(&dev->bo_cache.lock);
235 
236    return bo;
237 }
238 
239 static void
panfrost_bo_cache_evict_stale_bos(struct panfrost_device * dev)240 panfrost_bo_cache_evict_stale_bos(struct panfrost_device *dev)
241 {
242    struct timespec time;
243 
244    clock_gettime(CLOCK_MONOTONIC, &time);
245    list_for_each_entry_safe(struct panfrost_bo, entry, &dev->bo_cache.lru,
246                             lru_link) {
247       /* We want all entries that have been used more than 1 sec
248        * ago to be dropped, others can be kept.
249        * Note the <= 2 check and not <= 1. It's here to account for
250        * the fact that we're only testing ->tv_sec, not ->tv_nsec.
251        * That means we might keep entries that are between 1 and 2
252        * seconds old, but we don't really care, as long as unused BOs
253        * are dropped at some point.
254        */
255       if (time.tv_sec - entry->last_used <= 2)
256          break;
257 
258       list_del(&entry->bucket_link);
259       list_del(&entry->lru_link);
260       panfrost_bo_free(entry);
261    }
262 }
263 
264 /* Tries to add a BO to the cache. Returns if it was
265  * successful */
266 
267 static bool
panfrost_bo_cache_put(struct panfrost_bo * bo)268 panfrost_bo_cache_put(struct panfrost_bo *bo)
269 {
270    struct panfrost_device *dev = bo->dev;
271 
272    if (bo->flags & PAN_BO_SHARED || dev->debug & PAN_DBG_NO_CACHE)
273       return false;
274 
275    /* Must be first */
276    pthread_mutex_lock(&dev->bo_cache.lock);
277 
278    struct list_head *bucket = pan_bucket(dev, MAX2(panfrost_bo_size(bo), 4096));
279    struct timespec time;
280 
281    pan_kmod_bo_make_evictable(bo->kmod_bo);
282 
283    /* Add us to the bucket */
284    list_addtail(&bo->bucket_link, bucket);
285 
286    /* Add us to the LRU list and update the last_used field. */
287    list_addtail(&bo->lru_link, &dev->bo_cache.lru);
288    clock_gettime(CLOCK_MONOTONIC, &time);
289    bo->last_used = time.tv_sec;
290 
291    /* Let's do some cleanup in the BO cache while we hold the
292     * lock.
293     */
294    panfrost_bo_cache_evict_stale_bos(dev);
295 
296    /* Update the label to help debug BO cache memory usage issues */
297    bo->label = "Unused (BO cache)";
298 
299    /* Must be last */
300    pthread_mutex_unlock(&dev->bo_cache.lock);
301    return true;
302 }
303 
304 /* Evicts all BOs from the cache. Called during context
305  * destroy or during low-memory situations (to free up
306  * memory that may be unused by us just sitting in our
307  * cache, but still reserved from the perspective of the
308  * OS) */
309 
310 void
panfrost_bo_cache_evict_all(struct panfrost_device * dev)311 panfrost_bo_cache_evict_all(struct panfrost_device *dev)
312 {
313    pthread_mutex_lock(&dev->bo_cache.lock);
314    for (unsigned i = 0; i < ARRAY_SIZE(dev->bo_cache.buckets); ++i) {
315       struct list_head *bucket = &dev->bo_cache.buckets[i];
316 
317       list_for_each_entry_safe(struct panfrost_bo, entry, bucket, bucket_link) {
318          list_del(&entry->bucket_link);
319          list_del(&entry->lru_link);
320          panfrost_bo_free(entry);
321       }
322    }
323    pthread_mutex_unlock(&dev->bo_cache.lock);
324 }
325 
326 void
panfrost_bo_mmap(struct panfrost_bo * bo)327 panfrost_bo_mmap(struct panfrost_bo *bo)
328 {
329    if (bo->ptr.cpu)
330       return;
331 
332    bo->ptr.cpu = pan_kmod_bo_mmap(bo->kmod_bo, 0, panfrost_bo_size(bo),
333                                   PROT_READ | PROT_WRITE, MAP_SHARED, NULL);
334    if (bo->ptr.cpu == MAP_FAILED) {
335       bo->ptr.cpu = NULL;
336       fprintf(stderr, "mmap failed: result=%p size=0x%llx\n", bo->ptr.cpu,
337               (long long)panfrost_bo_size(bo));
338    }
339 }
340 
341 static void
panfrost_bo_munmap(struct panfrost_bo * bo)342 panfrost_bo_munmap(struct panfrost_bo *bo)
343 {
344    if (!bo->ptr.cpu)
345       return;
346 
347    if (os_munmap((void *)(uintptr_t)bo->ptr.cpu, panfrost_bo_size(bo))) {
348       perror("munmap");
349       abort();
350    }
351 
352    bo->ptr.cpu = NULL;
353 }
354 
355 struct panfrost_bo *
panfrost_bo_create(struct panfrost_device * dev,size_t size,uint32_t flags,const char * label)356 panfrost_bo_create(struct panfrost_device *dev, size_t size, uint32_t flags,
357                    const char *label)
358 {
359    struct panfrost_bo *bo;
360 
361    /* Kernel will fail (confusingly) with EPERM otherwise */
362    assert(size > 0);
363 
364    /* To maximize BO cache usage, don't allocate tiny BOs */
365    size = ALIGN_POT(size, 4096);
366 
367    /* GROWABLE BOs cannot be mmapped */
368    if (flags & PAN_BO_GROWABLE)
369       assert(flags & PAN_BO_INVISIBLE);
370 
371    /* Ideally, we get a BO that's ready in the cache, or allocate a fresh
372     * BO. If allocation fails, we can try waiting for something in the
373     * cache. But if there's no nothing suitable, we should flush the cache
374     * to make space for the new allocation.
375     */
376    bo = panfrost_bo_cache_fetch(dev, size, flags, label, true);
377    if (!bo)
378       bo = panfrost_bo_alloc(dev, size, flags, label);
379    if (!bo)
380       bo = panfrost_bo_cache_fetch(dev, size, flags, label, false);
381    if (!bo) {
382       panfrost_bo_cache_evict_all(dev);
383       bo = panfrost_bo_alloc(dev, size, flags, label);
384    }
385 
386    if (!bo) {
387       unreachable("BO creation failed. We don't handle that yet.");
388       return NULL;
389    }
390 
391    /* Only mmap now if we know we need to. For CPU-invisible buffers, we
392     * never map since we don't care about their contents; they're purely
393     * for GPU-internal use. But we do trace them anyway. */
394 
395    if (!(flags & (PAN_BO_INVISIBLE | PAN_BO_DELAY_MMAP)))
396       panfrost_bo_mmap(bo);
397 
398    p_atomic_set(&bo->refcnt, 1);
399 
400    if (dev->debug & (PAN_DBG_TRACE | PAN_DBG_SYNC)) {
401       if (flags & PAN_BO_INVISIBLE)
402          pandecode_inject_mmap(dev->decode_ctx, bo->ptr.gpu, NULL,
403                                panfrost_bo_size(bo), NULL);
404       else if (!(flags & PAN_BO_DELAY_MMAP))
405          pandecode_inject_mmap(dev->decode_ctx, bo->ptr.gpu, bo->ptr.cpu,
406                                panfrost_bo_size(bo), NULL);
407    }
408 
409    return bo;
410 }
411 
412 void
panfrost_bo_reference(struct panfrost_bo * bo)413 panfrost_bo_reference(struct panfrost_bo *bo)
414 {
415    if (bo) {
416       ASSERTED int count = p_atomic_inc_return(&bo->refcnt);
417       assert(count != 1);
418    }
419 }
420 
421 void
panfrost_bo_unreference(struct panfrost_bo * bo)422 panfrost_bo_unreference(struct panfrost_bo *bo)
423 {
424    if (!bo)
425       return;
426 
427    /* Don't return to cache if there are still references */
428    assert(p_atomic_read(&bo->refcnt) > 0);
429    if (p_atomic_dec_return(&bo->refcnt))
430       return;
431 
432    struct panfrost_device *dev = bo->dev;
433 
434    pthread_mutex_lock(&dev->bo_map_lock);
435 
436    /* Someone might have imported this BO while we were waiting for the
437     * lock, let's make sure it's still not referenced before freeing it.
438     */
439    if (p_atomic_read(&bo->refcnt) == 0) {
440       /* When the reference count goes to zero, we need to cleanup */
441       panfrost_bo_munmap(bo);
442 
443       if (dev->debug & (PAN_DBG_TRACE | PAN_DBG_SYNC))
444          pandecode_inject_free(dev->decode_ctx, bo->ptr.gpu,
445                                panfrost_bo_size(bo));
446 
447       /* Rather than freeing the BO now, we'll cache the BO for later
448        * allocations if we're allowed to.
449        */
450       if (!panfrost_bo_cache_put(bo))
451          panfrost_bo_free(bo);
452    }
453    pthread_mutex_unlock(&dev->bo_map_lock);
454 }
455 
456 struct panfrost_bo *
panfrost_bo_import(struct panfrost_device * dev,int fd)457 panfrost_bo_import(struct panfrost_device *dev, int fd)
458 {
459    struct panfrost_bo *bo;
460    ASSERTED int ret;
461    unsigned gem_handle;
462 
463    pthread_mutex_lock(&dev->bo_map_lock);
464    ret = drmPrimeFDToHandle(dev->kmod.dev->fd, fd, &gem_handle);
465    assert(!ret);
466 
467    bo = pan_lookup_bo(dev, gem_handle);
468 
469    if (!bo->dev) {
470       bo->dev = dev;
471       bo->kmod_bo = pan_kmod_bo_import(dev->kmod.dev, fd, 0);
472 
473       struct pan_kmod_vm_op vm_op = {
474          .type = PAN_KMOD_VM_OP_TYPE_MAP,
475          .va =
476             {
477                .start = PAN_KMOD_VM_MAP_AUTO_VA,
478                .size = bo->kmod_bo->size,
479             },
480          .map =
481             {
482                .bo = bo->kmod_bo,
483                .bo_offset = 0,
484             },
485       };
486 
487       ASSERTED int ret = pan_kmod_vm_bind(
488          dev->kmod.vm, PAN_KMOD_VM_OP_MODE_IMMEDIATE, &vm_op, 1);
489       assert(!ret);
490 
491       bo->ptr.gpu = vm_op.va.start;
492       bo->flags = PAN_BO_SHARED;
493       p_atomic_set(&bo->refcnt, 1);
494    } else {
495       /* bo->refcnt == 0 can happen if the BO
496        * was being released but panfrost_bo_import() acquired the
497        * lock before panfrost_bo_unreference(). In that case, refcnt
498        * is 0 and we can't use panfrost_bo_reference() directly, we
499        * have to re-initialize the refcnt().
500        * Note that panfrost_bo_unreference() checks
501        * refcnt value just after acquiring the lock to
502        * make sure the object is not freed if panfrost_bo_import()
503        * acquired it in the meantime.
504        */
505       if (p_atomic_read(&bo->refcnt) == 0)
506          p_atomic_set(&bo->refcnt, 1);
507       else
508          panfrost_bo_reference(bo);
509    }
510    pthread_mutex_unlock(&dev->bo_map_lock);
511 
512    return bo;
513 }
514 
515 int
panfrost_bo_export(struct panfrost_bo * bo)516 panfrost_bo_export(struct panfrost_bo *bo)
517 {
518    int ret = pan_kmod_bo_export(bo->kmod_bo);
519    if (ret >= 0)
520       bo->flags |= PAN_BO_SHARED;
521 
522    return ret;
523 }
524 
525 struct panfrost_bo *
panfrost_bo_from_kmod_bo(struct panfrost_device * dev,struct pan_kmod_bo * kmod_bo)526 panfrost_bo_from_kmod_bo(struct panfrost_device *dev,
527                          struct pan_kmod_bo *kmod_bo)
528 {
529    if (!kmod_bo)
530       return NULL;
531 
532    struct panfrost_bo *bo = pan_lookup_bo(dev, pan_kmod_bo_handle(kmod_bo));
533    assert(bo->kmod_bo == kmod_bo);
534 
535    return bo;
536 }
537