LSLab
device_allocator.h
1 #include "../lslab.h"
2 #include "../mutex.h"
3 #include <stdexcept>
4 
5 #pragma once
6 
7 namespace lslab {
8 
9 template<typename T>
10 LSLAB_HOST device_allocator<T>::device_allocator(size_t stack_size_) : stack_size(stack_size_) {
11  gpuErrchk(cudaMalloc(&loc, sizeof(cuda::std::atomic<uint64_t>)));
12  gpuErrchk(cudaMemset(loc, 0, sizeof(cuda::std::atomic<uint64_t>)));
13  gpuErrchk(cudaMalloc(&mempool, sizeof(T) * stack_size));
14 }
15 
16 template<typename T>
17 LSLAB_HOST_DEVICE device_allocator<T>::device_allocator(const device_allocator<T>& self) : stack_size(self.stack_size), loc(self.loc), mempool(self.mempool) {}
18 
19 template<typename T>
20 LSLAB_HOST_DEVICE device_allocator<T>::device_allocator(device_allocator&& other) {
21  stack_size = other.stack_size;
22  loc = other.loc;
23  mempool = other.mempool;
24 
25  other.loc = nullptr;
26  other.mempool = nullptr;
27 }
28 
29 template<typename T>
30 LSLAB_HOST_DEVICE device_allocator<T>& device_allocator<T>::operator=(device_allocator<T>&& other) {
31  #if defined(__CUDA_ARCH__)
32  if(loc != nullptr || mempool != nullptr)
33  __trap();
34  #else
35  if(loc != nullptr)
36  gpuErrchk(cudaFree(loc));
37  if(mempool != nullptr)
38  gpuErrchk(cudaFree(mempool));
39  #endif
40 
41  stack_size = other.stack_size;
42  loc = other.loc;
43  mempool = other.mempool;
44 
45  other.loc = nullptr;
46  other.mempool = nullptr;
47 }
48 
49 template<typename T>
50 LSLAB_HOST_DEVICE device_allocator<T>::~device_allocator() {
51 
52  // we let it leak for now
53 
54  //#if !defined(__CUDA_ARCH__)
55  // if(loc != nullptr)
56  // gpuErrchk(cudaFree(static_cast<void*>(loc)));
57  // if(mempool != nullptr)
58  // gpuErrchk(cudaFree(mempool));
59  //#endif
60 }
61 
62 template<typename T>
63 LSLAB_DEVICE T* device_allocator<T>::allocate(size_t n) {
64  auto idx = loc->fetch_add(n);
65  if(idx >= stack_size) {
66  printf("At idx %llu\n", idx);
67  __trap();
68  }
69  return mempool + idx;
70 }
71 
72 template<typename T>
73 LSLAB_HOST_DEVICE void device_allocator<T>::deallocate(T* ptr, size_t n) {}
74 
75 }