xref: /petsc/src/sys/memory/hip/mhiphost.hip.cxx (revision d756bedd70a89ca052be956bccd75c5761cb2ab4)
1 #include <petscsys.h>        /*I   "petscsys.h"   I*/
2 #include <petscdevice_hip.h> /* Needed to provide PetscCallHIP() */
3 
4 PETSC_EXTERN PetscErrorCode PetscHIPHostMalloc(size_t a, PetscBool clear, int lineno, const char function[], const char filename[], void **result)
5 {
6   PetscCallHIP(hipHostMalloc(result, a));
7   return PETSC_SUCCESS;
8 }
9 
10 PETSC_EXTERN PetscErrorCode PetscHIPHostFree(void *aa, int lineno, const char function[], const char filename[])
11 {
12   PetscCallHIP(hipHostFree(aa));
13   return PETSC_SUCCESS;
14 }
15 
16 PETSC_EXTERN PetscErrorCode PetscHIPHostRealloc(size_t a, int lineno, const char function[], const char filename[], void **result)
17 {
18   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_MEM, "HIP has no Realloc()");
19 }
20 
21 static PetscErrorCode (*PetscMallocOld)(size_t, PetscBool, int, const char[], const char[], void **);
22 static PetscErrorCode (*PetscReallocOld)(size_t, int, const char[], const char[], void **);
23 static PetscErrorCode (*PetscFreeOld)(void *, int, const char[], const char[]);
24 
25 /*@
26   PetscMallocSetHIPHost - Set `PetscMalloc()` to use `HIPHostMalloc()`
27   Switch the current malloc and free routines to the HIP malloc and free routines
28 
29   Not Collective
30 
31   Level: developer
32 
33   Note:
34   This provides a way to use the HIP malloc and free routines temporarily. One
35   can switch back to the previous choice by calling `PetscMallocResetHIPHost()`.
36 
37 .seealso: `PetscMallocSetCUDAHost()`, `PetscMallocResetHIPHost()`
38 @*/
39 PETSC_EXTERN PetscErrorCode PetscMallocSetHIPHost(void)
40 {
41   PetscFunctionBegin;
42   /* Save the previous choice */
43   PetscMallocOld  = PetscTrMalloc;
44   PetscReallocOld = PetscTrRealloc;
45   PetscFreeOld    = PetscTrFree;
46   PetscTrMalloc   = PetscHIPHostMalloc;
47   PetscTrRealloc  = PetscHIPHostRealloc;
48   PetscTrFree     = PetscHIPHostFree;
49   PetscFunctionReturn(PETSC_SUCCESS);
50 }
51 
52 /*@
53   PetscMallocResetHIPHost - Reset the changes made by `PetscMallocSetHIPHost()`
54 
55   Not Collective
56 
57   Level: developer
58 
59 .seealso: `PetscMallocSetHIPHost()`
60 @*/
61 PETSC_EXTERN PetscErrorCode PetscMallocResetHIPHost(void)
62 {
63   PetscFunctionBegin;
64   PetscTrMalloc  = PetscMallocOld;
65   PetscTrRealloc = PetscReallocOld;
66   PetscTrFree    = PetscFreeOld;
67   PetscFunctionReturn(PETSC_SUCCESS);
68 }
69