forked from LBL-EESA/HAMR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhamr_cuda_device.cxx
90 lines (77 loc) · 2.35 KB
/
hamr_cuda_device.cxx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include "hamr_cuda_device.h"
#include <iostream>
#include <cuda.h>
#include <cuda_runtime.h>
namespace hamr
{
// **************************************************************************
int get_active_cuda_device(int &dev_id)
{
cudaError_t ierr = cudaSuccess;
if ((ierr = cudaGetDevice(&dev_id)) != cudaSuccess)
{
std::cerr << "Failed to get the active CUDA device. "
<< cudaGetErrorString(ierr) << std::endl;
return -1;
}
return 0;
}
// **************************************************************************
int set_active_cuda_device(int dev_id)
{
cudaError_t ierr = cudaSuccess;
if ((ierr = cudaSetDevice(dev_id)) != cudaSuccess)
{
std::cerr << "Failed to set the active CUDA device. "
<< cudaGetErrorString(ierr) << std::endl;
return -1;
}
return 0;
}
// **************************************************************************
int get_cuda_device(const void *ptr, int &device_id)
{
cudaError_t ierr = cudaSuccess;
cudaPointerAttributes ptrAtts;
ierr = cudaPointerGetAttributes(&ptrAtts, ptr);
// these types of pointers are NOT accessible on the GPU
// cudaErrorInValue occurs when the pointer is unknown to CUDA, as is
// the case with pointers allocated by malloc or new.
if ((ierr == cudaErrorInvalidValue) ||
((ierr == cudaSuccess) && ((ptrAtts.type == cudaMemoryTypeHost) ||
(ptrAtts.type == cudaMemoryTypeUnregistered))))
{
// this is host backed memory not associate with a GPU
device_id = -1;
}
else if (ierr != cudaSuccess)
{
std::cerr << "[" << __FILE__ << ":" << __LINE__ << "] ERROR:"
" Failed to get pointer attributes for " << ptr << std::endl;
return -1;
}
else
{
device_id = ptrAtts.device;
}
return 0;
}
// --------------------------------------------------------------------------
activate_cuda_device::activate_cuda_device(int new_dev) : m_device(-1)
{
int cur_dev = -1;
if (!get_active_cuda_device(cur_dev) && (cur_dev != new_dev) &&
!set_active_cuda_device(new_dev))
{
m_device = cur_dev;
}
}
// --------------------------------------------------------------------------
activate_cuda_device::~activate_cuda_device()
{
if (m_device >= 0)
{
set_active_cuda_device(m_device);
}
}
}