Unified Memory Group Allocator
MultiPageAllocator.h
Go to the documentation of this file.
1 
5 #include <cmath>
6 #include <functional>
7 #include <mutex>
8 #include <vector>
9 #include <list>
10 #include <utility>
11 #include <cuda_runtime.h>
12 #include "Helper.h"
13 
14 #pragma once
15 
16 namespace groupallocator {
17 
22  public:
23  MultiPageAllocator() = delete;
24 
28  MultiPageAllocator(std::size_t page_size)
29  : PAGE_SIZE(page_size), pagesAllocated(0) {}
30 
35  m.lock();
36  for (auto &e : mem) {
37  gpuAssert(cudaFree((void *) e.first), __FILE__, __LINE__);
38  }
39  m.unlock();
40  }
41 
47  template<class T>
48  void allocate(T **ptr, size_t s, bool forceAligned128) {
49 #ifdef DEBUGALLOC
50  std::clog << "Allocating in MPA " << __FILE__ << ":" << __LINE__ << std::endl;
51 #endif
52  size_t pages_needed = (size_t) ceil(s / (double) PAGE_SIZE);
53  char *c;
54  gpuAssert(cudaMallocManaged((void **) &c, pages_needed * PAGE_SIZE), __FILE__, __LINE__);
55  *ptr = (T *) c;
56  m.lock();
57  pagesAllocated += pages_needed;
58  mem.push_back({c, pages_needed * PAGE_SIZE});
59  m.unlock();
60  }
61 
62  template<class T>
63  void free(T *ptr) {
64  m.lock();
65  for (auto i = mem.begin(); i != mem.end(); i++) {
66  if ((size_t) i->first == (size_t) ptr) {
67  gpuAssert(cudaFree((void *) i->first), __FILE__, __LINE__);
68  mem.erase(i);
69  break;
70  }
71  }
72  m.unlock();
73  }
74 
75  void moveToDevice(int device, cudaStream_t stream) {
76  #ifndef DISABLE_PREFETCH
77  m.lock();
78  for (auto i = mem.begin(); i != mem.end(); i++) {
79  gpuAssert(cudaMemPrefetchAsync(i->first, i->second, device, stream), __FILE__, __LINE__);
80  }
81  m.unlock();
82  #endif
83  }
84 
85  size_t getPages() {
86  std::unique_lock <std::mutex> ul(m);
87  return pagesAllocated;
88  }
89 
90  size_t getPageSize() { return PAGE_SIZE; }
91 
92  private:
93  std::list <std::pair<char *, size_t>> mem;
94  std::mutex m;
95  const size_t PAGE_SIZE;
96  size_t pagesAllocated;
97  };
98 
99 } // namespace groupallocator
groupallocator::MultiPageAllocator::~MultiPageAllocator
~MultiPageAllocator()
Definition: MultiPageAllocator.h:34
groupallocator::gpuAssert
void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
Definition: Helper.h:18
groupallocator::MultiPageAllocator
Definition: MultiPageAllocator.h:21
Helper.h
groupallocator::MultiPageAllocator::allocate
void allocate(T **ptr, size_t s, bool forceAligned128)
Definition: MultiPageAllocator.h:48
groupallocator::MultiPageAllocator::MultiPageAllocator
MultiPageAllocator(std::size_t page_size)
Definition: MultiPageAllocator.h:28