PSCF v1.4.0
DeviceMemory.cu
1/*
2* PSCF - Polymer Self-Consistent Field
3*
4* Copyright 2015 - 2025, The Regents of the University of Minnesota
5* Distributed under the terms of the GNU General Public License.
6*/
7
8#include "DeviceMemory.h"
9#include "cudaErrorCheck.h"
10#include <util/misc/CountedReference.h>
11#include <util/global.h>
12#include <cuda_runtime.h>
13
14namespace Pscf {
15
16 using namespace Util;
17
18 /*
19 * Default constructor.
20 */
22 : dataPtr_(nullptr),
23 capacity_(0),
24 refCounter_()
25 {}
26
27 /*
28 * Allocating constructor.
29 */
31 : dataPtr_(nullptr),
32 capacity_(0),
33 refCounter_()
34 { allocate(capacity); }
35
36 /*
37 * Destructor.
38 */
40 {
41 if (isAllocated()) {
42 if (refCounter_.hasRefs()) {
43 std::cout << "Error - destruction of DeviceMemory with"
44 << "external references" << std::endl;
45 }
46 cudaFree(dataPtr_);
47 capacity_ = 0;
48 }
49 }
50
51 /*
52 * Allocate the underlying C array.
53 */
55 {
56 if (capacity <= 0) {
57 UTIL_THROW("Attempt to allocate with capacity <= 0");
58 }
59 if (isAllocated()) {
60 UTIL_THROW("Attempt to re-allocate a DeviceMemory");
61 }
62 cudaErrorCheck( cudaMalloc( &dataPtr_, capacity ) );
63 capacity_ = capacity;
64 }
65
66 /*
67 * Deallocate the underlying C array.
68 */
70 {
71 UTIL_CHECK(!refCounter_.hasRefs());
72 if (isAllocated()) {
73 cudaErrorCheck( cudaFree(dataPtr_) );
74 }
75 dataPtr_ = nullptr;
76 capacity_ = 0;
77 }
78
79 /*
80 * Reallocate if necessary to increase capacity.
81 */
83 {
84 if (capacity <= 0) {
85 UTIL_THROW("Attempt to resize DeviceMemory with capacity <= 0");
86 }
87 if (capacity > capacity_) {
88 deallocate();
90 }
91 }
92
93 /*
94 * Associate a CountedReference with the reference counter member.
95 */
97 { ref.associate(refCounter_); }
98
99 /*
100 * Get a pointer to the underlying C array.
101 */
103 {
104 UTIL_CHECK(dataPtr_);
105 return dataPtr_;
106 }
107
108} // namespace Pscf
virtual ~DeviceMemory()
Destructor.
void deallocate()
Dellocate the underlying C array, if any.
void addReference(CountedReference &reference)
Associate a reference with the reference counter.
bool isAllocated() const
Return true if the array has been allocated, false otherwise.
DeviceMemory()
Default constructor.
void * cArray() const
Return pointer to underlying C array.
void allocate(int capacity)
Allocate the underlying C array on the device.
int capacity() const
Return allocated capacity.
void resize(int capacity)
Re-allocate if necessary to increase capacity.
Reference to a shared resource.
void associate(ReferenceCounter &counter)
Create an association with a ReferenceCounter.
File containing preprocessor macros for error handling.
#define UTIL_CHECK(condition)
Assertion macro suitable for serial or parallel production code.
Definition global.h:68
#define UTIL_THROW(msg)
Macro for throwing an Exception, reporting function, file and line number.
Definition global.h:49
PSCF package top-level namespace.