1 /*
2  * Copyright © 2019 Raspberry Pi
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
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  */
23 
24 #include "v3dv_private.h"
25 
26 #include <errno.h>
27 #include <sys/mman.h>
28 
29 #include "drm-uapi/v3d_drm.h"
30 #include "util/u_memory.h"
31 
32 /* Default max size of the bo cache, in MB.
33  *
34  * FIXME: we got this value when testing some apps using the rpi4 with 4GB,
35  * but it should depend on the total amount of RAM. But for that we would need
36  * to test on real hw with different amount of RAM. Using this value for now.
37  */
38 #define DEFAULT_MAX_BO_CACHE_SIZE 512
39 
40 /* Discarded to use a V3D_DEBUG for this, as it would mean adding a run-time
41  * check for most of the calls
42  */
43 static const bool dump_stats = false;
44 
45 static void
bo_dump_stats(struct v3dv_device * device)46 bo_dump_stats(struct v3dv_device *device)
47 {
48    struct v3dv_bo_cache *cache = &device->bo_cache;
49 
50    fprintf(stderr, "  BOs allocated:   %d\n", device->bo_count);
51    fprintf(stderr, "  BOs size:        %dkb\n", device->bo_size / 1024);
52    fprintf(stderr, "  BOs cached:      %d\n", cache->cache_count);
53    fprintf(stderr, "  BOs cached size: %dkb\n", cache->cache_size / 1024);
54 
55    if (!list_is_empty(&cache->time_list)) {
56       struct v3dv_bo *first = list_first_entry(&cache->time_list,
57                                               struct v3dv_bo,
58                                               time_list);
59       struct v3dv_bo *last = list_last_entry(&cache->time_list,
60                                             struct v3dv_bo,
61                                             time_list);
62 
63       fprintf(stderr, "  oldest cache time: %ld\n",
64               (long)first->free_time);
65       fprintf(stderr, "  newest cache time: %ld\n",
66               (long)last->free_time);
67 
68       struct timespec time;
69       clock_gettime(CLOCK_MONOTONIC, &time);
70       fprintf(stderr, "  now:               %ld\n",
71               time.tv_sec);
72    }
73 
74    if (cache->size_list_size) {
75       uint32_t empty_size_list = 0;
76       for (uint32_t i = 0; i < cache->size_list_size; i++) {
77          if (list_is_empty(&cache->size_list[i]))
78             empty_size_list++;
79       }
80       fprintf(stderr, "  Empty size_list lists: %d\n", empty_size_list);
81    }
82 }
83 
84 static void
bo_remove_from_cache(struct v3dv_bo_cache * cache,struct v3dv_bo * bo)85 bo_remove_from_cache(struct v3dv_bo_cache *cache, struct v3dv_bo *bo)
86 {
87    list_del(&bo->time_list);
88    list_del(&bo->size_list);
89 
90    cache->cache_count--;
91    cache->cache_size -= bo->size;
92 }
93 
94 static struct v3dv_bo *
bo_from_cache(struct v3dv_device * device,uint32_t size,const char * name)95 bo_from_cache(struct v3dv_device *device, uint32_t size, const char *name)
96 {
97    struct v3dv_bo_cache *cache = &device->bo_cache;
98    uint32_t page_index = size / 4096 - 1;
99 
100    if (cache->size_list_size <= page_index)
101       return NULL;
102 
103    struct v3dv_bo *bo = NULL;
104 
105    mtx_lock(&cache->lock);
106    if (!list_is_empty(&cache->size_list[page_index])) {
107       bo = list_first_entry(&cache->size_list[page_index],
108                             struct v3dv_bo, size_list);
109 
110       /* Check that the BO has gone idle.  If not, then we want to
111        * allocate something new instead, since we assume that the
112        * user will proceed to CPU map it and fill it with stuff.
113        */
114       if (!v3dv_bo_wait(device, bo, 0)) {
115          mtx_unlock(&cache->lock);
116          return NULL;
117       }
118 
119       bo_remove_from_cache(cache, bo);
120 
121       bo->name = name;
122    }
123    mtx_unlock(&cache->lock);
124    return bo;
125 }
126 
127 static bool
bo_free(struct v3dv_device * device,struct v3dv_bo * bo)128 bo_free(struct v3dv_device *device,
129         struct v3dv_bo *bo)
130 {
131    if (!bo)
132       return true;
133 
134    if (bo->map)
135       v3dv_bo_unmap(device, bo);
136 
137    struct drm_gem_close c;
138    memset(&c, 0, sizeof(c));
139    c.handle = bo->handle;
140    int ret = v3dv_ioctl(device->render_fd, DRM_IOCTL_GEM_CLOSE, &c);
141    if (ret != 0)
142       fprintf(stderr, "close object %d: %s\n", bo->handle, strerror(errno));
143 
144    device->bo_count--;
145    device->bo_size -= bo->size;
146 
147    if (dump_stats) {
148       fprintf(stderr, "Freed %s%s%dkb:\n",
149               bo->name ? bo->name : "",
150               bo->name ? " " : "",
151               bo->size / 1024);
152       bo_dump_stats(device);
153    }
154 
155    vk_free(&device->alloc, bo);
156 
157    return ret == 0;
158 }
159 
160 static void
bo_cache_free_all(struct v3dv_device * device,bool with_lock)161 bo_cache_free_all(struct v3dv_device *device,
162                        bool with_lock)
163 {
164    struct v3dv_bo_cache *cache = &device->bo_cache;
165 
166    if (with_lock)
167       mtx_lock(&cache->lock);
168    list_for_each_entry_safe(struct v3dv_bo, bo, &cache->time_list,
169                             time_list) {
170       bo_remove_from_cache(cache, bo);
171       bo_free(device, bo);
172    }
173    if (with_lock)
174       mtx_unlock(&cache->lock);
175 
176 }
177 
178 void
v3dv_bo_init(struct v3dv_bo * bo,uint32_t handle,uint32_t size,uint32_t offset,const char * name,bool private)179 v3dv_bo_init(struct v3dv_bo *bo,
180              uint32_t handle,
181              uint32_t size,
182              uint32_t offset,
183              const char *name,
184              bool private)
185 {
186    bo->handle = handle;
187    bo->size = size;
188    bo->offset = offset;
189    bo->map = NULL;
190    bo->map_size = 0;
191    bo->name = name;
192    bo->private = private;
193    bo->dumb_handle = -1;
194    list_inithead(&bo->list_link);
195 }
196 
197 struct v3dv_bo *
v3dv_bo_alloc(struct v3dv_device * device,uint32_t size,const char * name,bool private)198 v3dv_bo_alloc(struct v3dv_device *device,
199               uint32_t size,
200               const char *name,
201               bool private)
202 {
203    struct v3dv_bo *bo;
204 
205    const uint32_t page_align = 4096; /* Always allocate full pages */
206    size = align(size, page_align);
207 
208    if (private) {
209       bo = bo_from_cache(device, size, name);
210       if (bo) {
211          if (dump_stats) {
212             fprintf(stderr, "Allocated %s %dkb from cache:\n",
213                     name, size / 1024);
214             bo_dump_stats(device);
215          }
216          return bo;
217       }
218    }
219 
220    bo = vk_alloc(&device->alloc, sizeof(struct v3dv_bo), 8,
221                  VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
222 
223    if (!bo) {
224       fprintf(stderr, "Failed to allocate host memory for BO\n");
225       return NULL;
226    }
227 
228  retry:
229    ;
230 
231    bool cleared_and_retried = false;
232    struct drm_v3d_create_bo create = {
233       .size = size
234    };
235 
236    int ret = v3dv_ioctl(device->render_fd, DRM_IOCTL_V3D_CREATE_BO, &create);
237    if (ret != 0) {
238       if (!list_is_empty(&device->bo_cache.time_list) &&
239           !cleared_and_retried) {
240          cleared_and_retried = true;
241          bo_cache_free_all(device, true);
242          goto retry;
243       }
244 
245       vk_free(&device->alloc, bo);
246       fprintf(stderr, "Failed to allocate device memory for BO\n");
247       return NULL;
248    }
249 
250    assert(create.offset % page_align == 0);
251    assert((create.offset & 0xffffffff) == create.offset);
252 
253    v3dv_bo_init(bo, create.handle, size, create.offset, name, private);
254 
255    device->bo_count++;
256    device->bo_size += bo->size;
257    if (dump_stats) {
258       fprintf(stderr, "Allocated %s %dkb:\n", name, size / 1024);
259       bo_dump_stats(device);
260    }
261 
262    return bo;
263 }
264 
265 bool
v3dv_bo_map_unsynchronized(struct v3dv_device * device,struct v3dv_bo * bo,uint32_t size)266 v3dv_bo_map_unsynchronized(struct v3dv_device *device,
267                            struct v3dv_bo *bo,
268                            uint32_t size)
269 {
270    assert(bo != NULL && size <= bo->size);
271 
272    if (bo->map)
273       return bo->map;
274 
275    struct drm_v3d_mmap_bo map;
276    memset(&map, 0, sizeof(map));
277    map.handle = bo->handle;
278    int ret = v3dv_ioctl(device->render_fd, DRM_IOCTL_V3D_MMAP_BO, &map);
279    if (ret != 0) {
280       fprintf(stderr, "map ioctl failure\n");
281       return false;
282    }
283 
284    bo->map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED,
285                   device->render_fd, map.offset);
286    if (bo->map == MAP_FAILED) {
287       fprintf(stderr, "mmap of bo %d (offset 0x%016llx, size %d) failed\n",
288               bo->handle, (long long)map.offset, (uint32_t)bo->size);
289       return false;
290    }
291    VG(VALGRIND_MALLOCLIKE_BLOCK(bo->map, bo->size, 0, false));
292 
293    bo->map_size = size;
294 
295    return true;
296 }
297 
298 bool
v3dv_bo_wait(struct v3dv_device * device,struct v3dv_bo * bo,uint64_t timeout_ns)299 v3dv_bo_wait(struct v3dv_device *device,
300              struct v3dv_bo *bo,
301              uint64_t timeout_ns)
302 {
303    struct drm_v3d_wait_bo wait = {
304       .handle = bo->handle,
305       .timeout_ns = timeout_ns,
306    };
307    return v3dv_ioctl(device->render_fd, DRM_IOCTL_V3D_WAIT_BO, &wait) == 0;
308 }
309 
310 bool
v3dv_bo_map(struct v3dv_device * device,struct v3dv_bo * bo,uint32_t size)311 v3dv_bo_map(struct v3dv_device *device, struct v3dv_bo *bo, uint32_t size)
312 {
313    assert(bo && size <= bo->size);
314 
315    bool ok = v3dv_bo_map_unsynchronized(device, bo, size);
316    if (!ok)
317       return false;
318 
319    const uint64_t infinite = 0xffffffffffffffffull;
320    ok = v3dv_bo_wait(device, bo, infinite);
321    if (!ok) {
322       fprintf(stderr, "memory wait for map failed\n");
323       return false;
324    }
325 
326    return true;
327 }
328 
329 void
v3dv_bo_unmap(struct v3dv_device * device,struct v3dv_bo * bo)330 v3dv_bo_unmap(struct v3dv_device *device, struct v3dv_bo *bo)
331 {
332    assert(bo && bo->map && bo->map_size > 0);
333 
334    munmap(bo->map, bo->map_size);
335    VG(VALGRIND_FREELIKE_BLOCK(bo->map, 0));
336    bo->map = NULL;
337    bo->map_size = 0;
338 }
339 
340 static boolean
reallocate_size_list(struct v3dv_bo_cache * cache,struct v3dv_device * device,uint32_t size)341 reallocate_size_list(struct v3dv_bo_cache *cache,
342                      struct v3dv_device *device,
343                      uint32_t size)
344 {
345    struct list_head *new_list =
346       vk_alloc(&device->alloc, sizeof(struct list_head) * size, 8,
347                VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
348 
349    if (!new_list) {
350       fprintf(stderr, "Failed to allocate host memory for cache bo list\n");
351       return false;
352    }
353    struct list_head *old_list = cache->size_list;
354 
355    /* Move old list contents over (since the array has moved, and
356     * therefore the pointers to the list heads have to change).
357     */
358    for (int i = 0; i < cache->size_list_size; i++) {
359       struct list_head *old_head = &cache->size_list[i];
360       if (list_is_empty(old_head)) {
361          list_inithead(&new_list[i]);
362       } else {
363          new_list[i].next = old_head->next;
364          new_list[i].prev = old_head->prev;
365          new_list[i].next->prev = &new_list[i];
366          new_list[i].prev->next = &new_list[i];
367       }
368    }
369    for (int i = cache->size_list_size; i < size; i++)
370       list_inithead(&new_list[i]);
371 
372    cache->size_list = new_list;
373    cache->size_list_size = size;
374    vk_free(&device->alloc, old_list);
375 
376    return true;
377 }
378 
379 void
v3dv_bo_cache_init(struct v3dv_device * device)380 v3dv_bo_cache_init(struct v3dv_device *device)
381 {
382    device->bo_size = 0;
383    device->bo_count = 0;
384    list_inithead(&device->bo_cache.time_list);
385    /* FIXME: perhaps set a initial size for the size-list, to avoid run-time
386     * reallocations
387     */
388    device->bo_cache.size_list_size = 0;
389 
390    const char *max_cache_size_str = getenv("V3DV_MAX_BO_CACHE_SIZE");
391    if (max_cache_size_str == NULL)
392       device->bo_cache.max_cache_size = DEFAULT_MAX_BO_CACHE_SIZE;
393    else
394       device->bo_cache.max_cache_size = atoll(max_cache_size_str);
395 
396    if (dump_stats) {
397       fprintf(stderr, "MAX BO CACHE SIZE: %iMB\n", device->bo_cache.max_cache_size);
398    }
399 
400    device->bo_cache.max_cache_size *= 1024 * 1024;
401    device->bo_cache.cache_count = 0;
402    device->bo_cache.cache_size = 0;
403 }
404 
405 void
v3dv_bo_cache_destroy(struct v3dv_device * device)406 v3dv_bo_cache_destroy(struct v3dv_device *device)
407 {
408    bo_cache_free_all(device, true);
409    vk_free(&device->alloc, device->bo_cache.size_list);
410 
411    if (dump_stats) {
412       fprintf(stderr, "BO stats after screen destroy:\n");
413       bo_dump_stats(device);
414    }
415 }
416 
417 
418 static void
free_stale_bos(struct v3dv_device * device,time_t time)419 free_stale_bos(struct v3dv_device *device,
420                time_t time)
421 {
422    struct v3dv_bo_cache *cache = &device->bo_cache;
423    bool freed_any = false;
424 
425    list_for_each_entry_safe(struct v3dv_bo, bo, &cache->time_list,
426                             time_list) {
427       /* If it's more than a second old, free it. */
428       if (time - bo->free_time > 2) {
429          if (dump_stats && !freed_any) {
430             fprintf(stderr, "Freeing stale BOs:\n");
431             bo_dump_stats(device);
432             freed_any = true;
433          }
434 
435          bo_remove_from_cache(cache, bo);
436          bo_free(device, bo);
437       } else {
438          break;
439       }
440    }
441 
442    if (dump_stats && freed_any) {
443       fprintf(stderr, "Freed stale BOs:\n");
444       bo_dump_stats(device);
445    }
446 }
447 
448 bool
v3dv_bo_free(struct v3dv_device * device,struct v3dv_bo * bo)449 v3dv_bo_free(struct v3dv_device *device,
450              struct v3dv_bo *bo)
451 {
452    if (!bo)
453       return true;
454 
455    struct timespec time;
456    struct v3dv_bo_cache *cache = &device->bo_cache;
457    uint32_t page_index = bo->size / 4096 - 1;
458 
459    if (bo->private &&
460        bo->size > cache->max_cache_size - cache->cache_size) {
461       clock_gettime(CLOCK_MONOTONIC, &time);
462       mtx_lock(&cache->lock);
463       free_stale_bos(device, time.tv_sec);
464       mtx_unlock(&cache->lock);
465    }
466 
467    if (!bo->private ||
468        bo->size > cache->max_cache_size - cache->cache_size) {
469       return bo_free(device, bo);
470    }
471 
472    clock_gettime(CLOCK_MONOTONIC, &time);
473    mtx_lock(&cache->lock);
474 
475    if (cache->size_list_size <= page_index) {
476       if (!reallocate_size_list(cache, device, page_index + 1)) {
477          bool outcome = bo_free(device, bo);
478          /* If the reallocation failed, it usually means that we are out of
479           * memory, so we also free all the bo cache. We need to call it to
480           * not use the cache lock, as we are already under it.
481           */
482          bo_cache_free_all(device, false);
483          mtx_unlock(&cache->lock);
484          return outcome;
485       }
486    }
487 
488    bo->free_time = time.tv_sec;
489    list_addtail(&bo->size_list, &cache->size_list[page_index]);
490    list_addtail(&bo->time_list, &cache->time_list);
491 
492    cache->cache_count++;
493    cache->cache_size += bo->size;
494 
495    if (dump_stats) {
496       fprintf(stderr, "Freed %s %dkb to cache:\n",
497               bo->name, bo->size / 1024);
498       bo_dump_stats(device);
499    }
500    bo->name = NULL;
501 
502    free_stale_bos(device, time.tv_sec);
503 
504    mtx_unlock(&cache->lock);
505 
506    return true;
507 }
508