1/*
2 * Copyright © 2009 Corbin Simpson <MostAwesomeDude@gmail.com>
3 * Copyright © 2009 Joakim Sindholt <opensource@zhasha.com>
4 * Copyright © 2011 Marek Olšák <maraeo@gmail.com>
5 * Copyright © 2015 Advanced Micro Devices, Inc.
6 * All Rights Reserved.
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining
9 * a copy of this software and associated documentation files (the
10 * "Software"), to deal in the Software without restriction, including
11 * without limitation the rights to use, copy, modify, merge, publish,
12 * distribute, sub license, and/or sell copies of the Software, and to
13 * permit persons to whom the Software is furnished to do so, subject to
14 * the following conditions:
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 * NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS, AUTHORS
20 * AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
22 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
23 * USE OR OTHER DEALINGS IN THE SOFTWARE.
24 *
25 * The above copyright notice and this permission notice (including the
26 * next paragraph) shall be included in all copies or substantial portions
27 * of the Software.
28 */
29
30#include "amdgpu_cs.h"
31#include "amdgpu_public.h"
32
33#include "util/u_cpu_detect.h"
34#include "util/u_hash_table.h"
35#include "util/hash_table.h"
36#include "util/xmlconfig.h"
37#include <amdgpu_drm.h>
38#include <xf86drm.h>
39#include <stdio.h>
40#include <sys/stat.h>
41#include "amd/common/ac_llvm_util.h"
42#include "amd/common/sid.h"
43#include "amd/common/gfx9d.h"
44
45#ifndef AMDGPU_INFO_NUM_VRAM_CPU_PAGE_FAULTS
46#define AMDGPU_INFO_NUM_VRAM_CPU_PAGE_FAULTS	0x1E
47#endif
48
49static struct util_hash_table *dev_tab = NULL;
50static simple_mtx_t dev_tab_mutex = _SIMPLE_MTX_INITIALIZER_NP;
51
52DEBUG_GET_ONCE_BOOL_OPTION(all_bos, "RADEON_ALL_BOS", false)
53
54static void handle_env_var_force_family(struct amdgpu_winsys *ws)
55{
56      const char *family = debug_get_option("SI_FORCE_FAMILY", NULL);
57      unsigned i;
58
59      if (!family)
60               return;
61
62      for (i = CHIP_TAHITI; i < CHIP_LAST; i++) {
63         if (!strcmp(family, ac_get_llvm_processor_name(i))) {
64            /* Override family and chip_class. */
65            ws->info.family = i;
66            ws->info.name = "GCN-NOOP";
67
68            if (i >= CHIP_VEGA10)
69               ws->info.chip_class = GFX9;
70            else if (i >= CHIP_TONGA)
71               ws->info.chip_class = VI;
72            else if (i >= CHIP_BONAIRE)
73               ws->info.chip_class = CIK;
74            else
75               ws->info.chip_class = SI;
76
77            /* Don't submit any IBs. */
78            setenv("RADEON_NOOP", "1", 1);
79            return;
80         }
81      }
82
83      fprintf(stderr, "radeonsi: Unknown family: %s\n", family);
84      exit(1);
85}
86
87/* Helper function to do the ioctls needed for setup and init. */
88static bool do_winsys_init(struct amdgpu_winsys *ws,
89                           const struct pipe_screen_config *config,
90                           int fd)
91{
92   if (!ac_query_gpu_info(fd, ws->dev, &ws->info, &ws->amdinfo))
93      goto fail;
94
95   /* TODO: Enable this once the kernel handles it efficiently. */
96   if (ws->info.has_dedicated_vram)
97      ws->info.has_local_buffers = false;
98
99   handle_env_var_force_family(ws);
100
101   ws->addrlib = amdgpu_addr_create(&ws->info, &ws->amdinfo, &ws->info.max_alignment);
102   if (!ws->addrlib) {
103      fprintf(stderr, "amdgpu: Cannot create addrlib.\n");
104      goto fail;
105   }
106
107   ws->check_vm = strstr(debug_get_option("R600_DEBUG", ""), "check_vm") != NULL;
108   ws->debug_all_bos = debug_get_option_all_bos();
109   ws->reserve_vmid = strstr(debug_get_option("R600_DEBUG", ""), "reserve_vmid") != NULL;
110   ws->zero_all_vram_allocs = strstr(debug_get_option("R600_DEBUG", ""), "zerovram") != NULL ||
111      driQueryOptionb(config->options, "radeonsi_zerovram");
112
113   return true;
114
115fail:
116   amdgpu_device_deinitialize(ws->dev);
117   ws->dev = NULL;
118   return false;
119}
120
121static void do_winsys_deinit(struct amdgpu_winsys *ws)
122{
123   AddrDestroy(ws->addrlib);
124   amdgpu_device_deinitialize(ws->dev);
125}
126
127static void amdgpu_winsys_destroy(struct radeon_winsys *rws)
128{
129   struct amdgpu_winsys *ws = (struct amdgpu_winsys*)rws;
130
131   if (ws->reserve_vmid)
132      amdgpu_vm_unreserve_vmid(ws->dev, 0);
133
134   if (util_queue_is_initialized(&ws->cs_queue))
135      util_queue_destroy(&ws->cs_queue);
136
137   simple_mtx_destroy(&ws->bo_fence_lock);
138   for (unsigned i = 0; i < NUM_SLAB_ALLOCATORS; i++) {
139      if (ws->bo_slabs[i].groups)
140         pb_slabs_deinit(&ws->bo_slabs[i]);
141   }
142   pb_cache_deinit(&ws->bo_cache);
143   util_hash_table_destroy(ws->bo_export_table);
144   simple_mtx_destroy(&ws->global_bo_list_lock);
145   simple_mtx_destroy(&ws->bo_export_table_lock);
146   do_winsys_deinit(ws);
147   FREE(rws);
148}
149
150static void amdgpu_winsys_query_info(struct radeon_winsys *rws,
151                                     struct radeon_info *info)
152{
153   *info = ((struct amdgpu_winsys *)rws)->info;
154}
155
156static bool amdgpu_cs_request_feature(struct radeon_cmdbuf *rcs,
157                                      enum radeon_feature_id fid,
158                                      bool enable)
159{
160   return false;
161}
162
163static uint64_t amdgpu_query_value(struct radeon_winsys *rws,
164                                   enum radeon_value_id value)
165{
166   struct amdgpu_winsys *ws = (struct amdgpu_winsys*)rws;
167   struct amdgpu_heap_info heap;
168   uint64_t retval = 0;
169
170   switch (value) {
171   case RADEON_REQUESTED_VRAM_MEMORY:
172      return ws->allocated_vram;
173   case RADEON_REQUESTED_GTT_MEMORY:
174      return ws->allocated_gtt;
175   case RADEON_MAPPED_VRAM:
176      return ws->mapped_vram;
177   case RADEON_MAPPED_GTT:
178      return ws->mapped_gtt;
179   case RADEON_BUFFER_WAIT_TIME_NS:
180      return ws->buffer_wait_time;
181   case RADEON_NUM_MAPPED_BUFFERS:
182      return ws->num_mapped_buffers;
183   case RADEON_TIMESTAMP:
184      amdgpu_query_info(ws->dev, AMDGPU_INFO_TIMESTAMP, 8, &retval);
185      return retval;
186   case RADEON_NUM_GFX_IBS:
187      return ws->num_gfx_IBs;
188   case RADEON_NUM_SDMA_IBS:
189      return ws->num_sdma_IBs;
190   case RADEON_GFX_BO_LIST_COUNTER:
191      return ws->gfx_bo_list_counter;
192   case RADEON_GFX_IB_SIZE_COUNTER:
193      return ws->gfx_ib_size_counter;
194   case RADEON_NUM_BYTES_MOVED:
195      amdgpu_query_info(ws->dev, AMDGPU_INFO_NUM_BYTES_MOVED, 8, &retval);
196      return retval;
197   case RADEON_NUM_EVICTIONS:
198      amdgpu_query_info(ws->dev, AMDGPU_INFO_NUM_EVICTIONS, 8, &retval);
199      return retval;
200   case RADEON_NUM_VRAM_CPU_PAGE_FAULTS:
201      amdgpu_query_info(ws->dev, AMDGPU_INFO_NUM_VRAM_CPU_PAGE_FAULTS, 8, &retval);
202      return retval;
203   case RADEON_VRAM_USAGE:
204      amdgpu_query_heap_info(ws->dev, AMDGPU_GEM_DOMAIN_VRAM, 0, &heap);
205      return heap.heap_usage;
206   case RADEON_VRAM_VIS_USAGE:
207      amdgpu_query_heap_info(ws->dev, AMDGPU_GEM_DOMAIN_VRAM,
208                             AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED, &heap);
209      return heap.heap_usage;
210   case RADEON_GTT_USAGE:
211      amdgpu_query_heap_info(ws->dev, AMDGPU_GEM_DOMAIN_GTT, 0, &heap);
212      return heap.heap_usage;
213   case RADEON_GPU_TEMPERATURE:
214      amdgpu_query_sensor_info(ws->dev, AMDGPU_INFO_SENSOR_GPU_TEMP, 4, &retval);
215      return retval;
216   case RADEON_CURRENT_SCLK:
217      amdgpu_query_sensor_info(ws->dev, AMDGPU_INFO_SENSOR_GFX_SCLK, 4, &retval);
218      return retval;
219   case RADEON_CURRENT_MCLK:
220      amdgpu_query_sensor_info(ws->dev, AMDGPU_INFO_SENSOR_GFX_MCLK, 4, &retval);
221      return retval;
222   case RADEON_GPU_RESET_COUNTER:
223      assert(0);
224      return 0;
225   case RADEON_CS_THREAD_TIME:
226      return util_queue_get_thread_time_nano(&ws->cs_queue, 0);
227   }
228   return 0;
229}
230
231static bool amdgpu_read_registers(struct radeon_winsys *rws,
232                                  unsigned reg_offset,
233                                  unsigned num_registers, uint32_t *out)
234{
235   struct amdgpu_winsys *ws = (struct amdgpu_winsys*)rws;
236
237   return amdgpu_read_mm_registers(ws->dev, reg_offset / 4, num_registers,
238                                   0xffffffff, 0, out) == 0;
239}
240
241static unsigned hash_pointer(void *key)
242{
243   return _mesa_hash_pointer(key);
244}
245
246static int compare_pointers(void *key1, void *key2)
247{
248   return key1 != key2;
249}
250
251static bool amdgpu_winsys_unref(struct radeon_winsys *rws)
252{
253   struct amdgpu_winsys *ws = (struct amdgpu_winsys*)rws;
254   bool destroy;
255
256   /* When the reference counter drops to zero, remove the device pointer
257    * from the table.
258    * This must happen while the mutex is locked, so that
259    * amdgpu_winsys_create in another thread doesn't get the winsys
260    * from the table when the counter drops to 0. */
261   simple_mtx_lock(&dev_tab_mutex);
262
263   destroy = pipe_reference(&ws->reference, NULL);
264   if (destroy && dev_tab) {
265      util_hash_table_remove(dev_tab, ws->dev);
266      if (util_hash_table_count(dev_tab) == 0) {
267         util_hash_table_destroy(dev_tab);
268         dev_tab = NULL;
269      }
270   }
271
272   simple_mtx_unlock(&dev_tab_mutex);
273   return destroy;
274}
275
276static void amdgpu_pin_threads_to_L3_cache(struct radeon_winsys *rws,
277                                           unsigned cache)
278{
279   struct amdgpu_winsys *ws = (struct amdgpu_winsys*)rws;
280
281   util_pin_thread_to_L3(ws->cs_queue.threads[0], cache,
282                         util_cpu_caps.cores_per_L3);
283}
284
285PUBLIC struct radeon_winsys *
286amdgpu_winsys_create(int fd, const struct pipe_screen_config *config,
287		     radeon_screen_create_t screen_create)
288{
289   struct amdgpu_winsys *ws;
290   drmVersionPtr version = drmGetVersion(fd);
291   amdgpu_device_handle dev;
292   uint32_t drm_major, drm_minor, r;
293
294   /* The DRM driver version of amdgpu is 3.x.x. */
295   if (version->version_major != 3) {
296      drmFreeVersion(version);
297      return NULL;
298   }
299   drmFreeVersion(version);
300
301   /* Look up the winsys from the dev table. */
302   simple_mtx_lock(&dev_tab_mutex);
303   if (!dev_tab)
304      dev_tab = util_hash_table_create(hash_pointer, compare_pointers);
305
306   /* Initialize the amdgpu device. This should always return the same pointer
307    * for the same fd. */
308   r = amdgpu_device_initialize(fd, &drm_major, &drm_minor, &dev);
309   if (r) {
310      simple_mtx_unlock(&dev_tab_mutex);
311      fprintf(stderr, "amdgpu: amdgpu_device_initialize failed.\n");
312      return NULL;
313   }
314
315   /* Lookup a winsys if we have already created one for this device. */
316   ws = util_hash_table_get(dev_tab, dev);
317   if (ws) {
318      pipe_reference(NULL, &ws->reference);
319      simple_mtx_unlock(&dev_tab_mutex);
320
321      /* Release the device handle, because we don't need it anymore.
322       * This function is returning an existing winsys instance, which
323       * has its own device handle.
324       */
325      amdgpu_device_deinitialize(dev);
326      return &ws->base;
327   }
328
329   /* Create a new winsys. */
330   ws = CALLOC_STRUCT(amdgpu_winsys);
331   if (!ws)
332      goto fail;
333
334   ws->dev = dev;
335   ws->info.drm_major = drm_major;
336   ws->info.drm_minor = drm_minor;
337
338   if (!do_winsys_init(ws, config, fd))
339      goto fail_alloc;
340
341   /* Create managers. */
342   pb_cache_init(&ws->bo_cache, RADEON_MAX_CACHED_HEAPS,
343                 500000, ws->check_vm ? 1.0f : 2.0f, 0,
344                 (ws->info.vram_size + ws->info.gart_size) / 8,
345                 amdgpu_bo_destroy, amdgpu_bo_can_reclaim);
346
347   unsigned min_slab_order = 9;  /* 512 bytes */
348   unsigned max_slab_order = 18; /* 256 KB - higher numbers increase memory usage */
349   unsigned num_slab_orders_per_allocator = (max_slab_order - min_slab_order) /
350                                            NUM_SLAB_ALLOCATORS;
351
352   /* Divide the size order range among slab managers. */
353   for (unsigned i = 0; i < NUM_SLAB_ALLOCATORS; i++) {
354      unsigned min_order = min_slab_order;
355      unsigned max_order = MIN2(min_order + num_slab_orders_per_allocator,
356                                max_slab_order);
357
358      if (!pb_slabs_init(&ws->bo_slabs[i],
359                         min_order, max_order,
360                         RADEON_MAX_SLAB_HEAPS,
361                         ws,
362                         amdgpu_bo_can_reclaim_slab,
363                         amdgpu_bo_slab_alloc,
364                         amdgpu_bo_slab_free)) {
365         amdgpu_winsys_destroy(&ws->base);
366         simple_mtx_unlock(&dev_tab_mutex);
367         return NULL;
368      }
369
370      min_slab_order = max_order + 1;
371   }
372
373   ws->info.min_alloc_size = 1 << ws->bo_slabs[0].min_order;
374
375   /* init reference */
376   pipe_reference_init(&ws->reference, 1);
377
378   /* Set functions. */
379   ws->base.unref = amdgpu_winsys_unref;
380   ws->base.destroy = amdgpu_winsys_destroy;
381   ws->base.query_info = amdgpu_winsys_query_info;
382   ws->base.cs_request_feature = amdgpu_cs_request_feature;
383   ws->base.query_value = amdgpu_query_value;
384   ws->base.read_registers = amdgpu_read_registers;
385   ws->base.pin_threads_to_L3_cache = amdgpu_pin_threads_to_L3_cache;
386
387   amdgpu_bo_init_functions(ws);
388   amdgpu_cs_init_functions(ws);
389   amdgpu_surface_init_functions(ws);
390
391   LIST_INITHEAD(&ws->global_bo_list);
392   ws->bo_export_table = util_hash_table_create(hash_pointer, compare_pointers);
393
394   (void) simple_mtx_init(&ws->global_bo_list_lock, mtx_plain);
395   (void) simple_mtx_init(&ws->bo_fence_lock, mtx_plain);
396   (void) simple_mtx_init(&ws->bo_export_table_lock, mtx_plain);
397
398   if (!util_queue_init(&ws->cs_queue, "cs", 8, 1,
399                        UTIL_QUEUE_INIT_RESIZE_IF_FULL)) {
400      amdgpu_winsys_destroy(&ws->base);
401      simple_mtx_unlock(&dev_tab_mutex);
402      return NULL;
403   }
404
405   /* Create the screen at the end. The winsys must be initialized
406    * completely.
407    *
408    * Alternatively, we could create the screen based on "ws->gen"
409    * and link all drivers into one binary blob. */
410   ws->base.screen = screen_create(&ws->base, config);
411   if (!ws->base.screen) {
412      amdgpu_winsys_destroy(&ws->base);
413      simple_mtx_unlock(&dev_tab_mutex);
414      return NULL;
415   }
416
417   util_hash_table_set(dev_tab, dev, ws);
418
419   if (ws->reserve_vmid) {
420	   r = amdgpu_vm_reserve_vmid(dev, 0);
421	   if (r) {
422		fprintf(stderr, "amdgpu: amdgpu_vm_reserve_vmid failed. (%i)\n", r);
423		goto fail_cache;
424	   }
425   }
426
427   /* We must unlock the mutex once the winsys is fully initialized, so that
428    * other threads attempting to create the winsys from the same fd will
429    * get a fully initialized winsys and not just half-way initialized. */
430   simple_mtx_unlock(&dev_tab_mutex);
431
432   return &ws->base;
433
434fail_cache:
435   pb_cache_deinit(&ws->bo_cache);
436   do_winsys_deinit(ws);
437fail_alloc:
438   FREE(ws);
439fail:
440   simple_mtx_unlock(&dev_tab_mutex);
441   return NULL;
442}
443