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 "hsa_api.h"
8 #include "internal.h"
9 #include "machine.h"
10 #include "rt.h"
11 #include <cassert>
12 #include <stdio.h>
13 #include <string.h>
14 #include <vector>
15 
16 using core::TaskImpl;
17 extern ATLMachine g_atl_machine;
18 
19 namespace core {
20 
21 namespace {
22 ATLProcessor &get_processor_by_mem_place(int DeviceId,
23                                          atmi_devtype_t DeviceType) {
24   switch (DeviceType) {
25   case ATMI_DEVTYPE_CPU:
26     return g_atl_machine.processors<ATLCPUProcessor>()[DeviceId];
27   case ATMI_DEVTYPE_GPU:
28     return g_atl_machine.processors<ATLGPUProcessor>()[DeviceId];
29   }
30 }
31 
32 hsa_amd_memory_pool_t get_memory_pool_by_mem_place(int DeviceId,
33                                                    atmi_devtype_t DeviceType) {
34   ATLProcessor &proc = get_processor_by_mem_place(DeviceId, DeviceType);
35   return get_memory_pool(proc, 0 /*Memory Type (always zero) */);
36 }
37 } // namespace
38 
39 hsa_status_t Runtime::DeviceMalloc(void **ptr, size_t size, int DeviceId) {
40   return Runtime::Malloc(ptr, size, DeviceId, ATMI_DEVTYPE_GPU);
41 }
42 
43 hsa_status_t Runtime::HostMalloc(void **ptr, size_t size) {
44   hsa_status_t Err = Runtime::Malloc(ptr, size, 0, ATMI_DEVTYPE_CPU);
45   if (Err == HSA_STATUS_SUCCESS) {
46     Err = core::allow_access_to_all_gpu_agents(*ptr);
47   }
48   return Err;
49 }
50 
51 hsa_status_t Runtime::Malloc(void **ptr, size_t size, int DeviceId,
52                              atmi_devtype_t DeviceType) {
53   hsa_amd_memory_pool_t pool =
54       get_memory_pool_by_mem_place(DeviceId, DeviceType);
55   hsa_status_t err = hsa_amd_memory_pool_allocate(pool, size, 0, ptr);
56   DEBUG_PRINT("Malloced [%s %d] %p\n",
57               DeviceType == ATMI_DEVTYPE_CPU ? "CPU" : "GPU", DeviceId, *ptr);
58   return (err == HSA_STATUS_SUCCESS) ? HSA_STATUS_SUCCESS : HSA_STATUS_ERROR;
59 }
60 
61 hsa_status_t Runtime::Memfree(void *ptr) {
62   hsa_status_t err = hsa_amd_memory_pool_free(ptr);
63   DEBUG_PRINT("Freed %p\n", ptr);
64 
65   return (err == HSA_STATUS_SUCCESS) ? HSA_STATUS_SUCCESS : HSA_STATUS_ERROR;
66 }
67 
68 } // namespace core
69