1 /*===--------------------------------------------------------------------------
2  *              ATMI (Asynchronous Task and Memory Interface)
3  *
4  * This file is distributed under the MIT License. See LICENSE.txt for details.
5  *===------------------------------------------------------------------------*/
6 #include "atmi_runtime.h"
7 #include "internal.h"
8 #include "machine.h"
9 #include "rt.h"
10 #include <cassert>
11 #include <hsa.h>
12 #include <hsa_ext_amd.h>
13 #include <iostream>
14 #include <stdio.h>
15 #include <string.h>
16 #include <thread>
17 #include <vector>
18 
19 using core::TaskImpl;
20 extern ATLMachine g_atl_machine;
21 
22 namespace core {
23 
24 namespace {
25 ATLProcessor &get_processor_by_mem_place(atmi_mem_place_t place) {
26   int dev_id = place.dev_id;
27   switch (place.dev_type) {
28   case ATMI_DEVTYPE_CPU:
29     return g_atl_machine.processors<ATLCPUProcessor>()[dev_id];
30   case ATMI_DEVTYPE_GPU:
31     return g_atl_machine.processors<ATLGPUProcessor>()[dev_id];
32   }
33 }
34 
35 hsa_amd_memory_pool_t get_memory_pool_by_mem_place(atmi_mem_place_t place) {
36   ATLProcessor &proc = get_processor_by_mem_place(place);
37   return get_memory_pool(proc, place.mem_id);
38 }
39 } // namespace
40 
41 hsa_status_t register_allocation(void *ptr, size_t size,
42                                  atmi_mem_place_t place) {
43   if (place.dev_type == ATMI_DEVTYPE_CPU)
44     return allow_access_to_all_gpu_agents(ptr);
45   else
46     return HSA_STATUS_SUCCESS;
47 }
48 
49 atmi_status_t Runtime::Malloc(void **ptr, size_t size, atmi_mem_place_t place) {
50   hsa_amd_memory_pool_t pool = get_memory_pool_by_mem_place(place);
51   hsa_status_t err = hsa_amd_memory_pool_allocate(pool, size, 0, ptr);
52   DEBUG_PRINT("Malloced [%s %d] %p\n",
53               place.dev_type == ATMI_DEVTYPE_CPU ? "CPU" : "GPU", place.dev_id,
54               *ptr);
55 
56   if (err == HSA_STATUS_SUCCESS) {
57     err = register_allocation(*ptr, size, place);
58   }
59 
60   return (err == HSA_STATUS_SUCCESS) ? ATMI_STATUS_SUCCESS : ATMI_STATUS_ERROR;
61 }
62 
63 atmi_status_t Runtime::Memfree(void *ptr) {
64   hsa_status_t err = hsa_amd_memory_pool_free(ptr);
65   DEBUG_PRINT("Freed %p\n", ptr);
66 
67   return (err == HSA_STATUS_SUCCESS) ? ATMI_STATUS_SUCCESS : ATMI_STATUS_ERROR;
68 }
69 
70 } // namespace core
71