xref: /petsc/src/sys/memory/cuda/mcudahost.cu (revision c4762a1b19cd2af06abeed90e8f9d34fb975dd94)
1 #include <petscsys.h>             /*I   "petscsys.h"   I*/
2 #include <petsccublas.h>          /* Needed to provide CHKERRCUDA() */
3 
4 static PetscErrorCode PetscCudaHostMalloc(size_t a,PetscBool clear,int lineno,const char function[],const char filename[],void **result)
5 {
6   cudaError_t ierr;
7   ierr = cudaMallocHost(result,a);CHKERRCUDA(ierr);
8   return 0;
9 }
10 
11 static PetscErrorCode PetscCudaHostFree(void *aa,int lineno,const char function[],const char filename[])
12 {
13   cudaError_t ierr;
14   ierr = cudaFreeHost(aa);CHKERRCUDA(ierr);
15   return 0;
16 }
17 
18 static PetscErrorCode PetscCudaHostRealloc(size_t a,int lineno,const char function[],const char filename[],void **result)
19 {
20   SETERRQ(PETSC_COMM_SELF,PETSC_ERR_MEM,"CUDA has no Realloc()");
21   return 0;
22 }
23 
24 static PetscErrorCode (*PetscMallocOld)(size_t,PetscBool,int,const char[],const char[],void**);
25 static PetscErrorCode (*PetscReallocOld)(size_t,int,const char[],const char[],void**);
26 static PetscErrorCode (*PetscFreeOld)(void*,int,const char[],const char[]);
27 
28 /*@C
29    PetscMallocSetCUDAHost - Set PetscMalloc to use CUDAHostMalloc
30      Switch the current malloc and free routines to the CUDA malloc and free routines
31 
32    Not Collective
33 
34    Level: developer
35 
36    Notes:
37      This provides a way to use the CUDA malloc and free routines temporarily. One
38      can switch back to the previous choice by calling PetscMallocResetCUDAHost().
39 
40 .seealso: PetscMallocResetCUDAHost()
41 @*/
42 PetscErrorCode PetscMallocSetCUDAHost(void)
43 {
44   PetscFunctionBegin;
45   /* Save the previous choice */
46   PetscMallocOld  = PetscTrMalloc;
47   PetscReallocOld = PetscTrRealloc;
48   PetscFreeOld    = PetscTrFree;
49   PetscTrMalloc   = PetscCudaHostMalloc;
50   PetscTrRealloc  = PetscCudaHostRealloc;
51   PetscTrFree     = PetscCudaHostFree;
52   PetscFunctionReturn(0);
53 }
54 
55 /*@C
56    PetscMallocResetCUDAHost - Reset the changes made by PetscMallocSetCUDAHost
57 
58    Not Collective
59 
60    Level: developer
61 
62 .seealso: PetscMallocSetCUDAHost()
63 @*/
64 PetscErrorCode PetscMallocResetCUDAHost(void)
65 {
66   PetscFunctionBegin;
67   PetscTrMalloc  = PetscMallocOld;
68   PetscTrRealloc = PetscReallocOld;
69   PetscTrFree    = PetscFreeOld;
70   PetscFunctionReturn(0);
71 }
72