This contains my bachelors thesis and associated tex files, code snippets and maybe more. Topic: Data Movement in Heterogeneous Memories with Intel Data Streaming Accelerator
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

350 lines
12 KiB

  1. #pragma once
  2. #include <iostream>
  3. #include <unordered_map>
  4. #include <shared_mutex>
  5. #include <mutex>
  6. #include <memory>
  7. #include <sched.h>
  8. #include <numa.h>
  9. #include <numaif.h>
  10. #include <dml/dml.hpp>
  11. #include "cache-data.hpp"
  12. namespace dsacache {
  13. // singleton which holds the cache workers
  14. // and is the place where work will be submited
  15. class Cache {
  16. public:
  17. // cache policy is defined as a type here to allow flexible usage of the cacher
  18. // given a numa destination node (where the data will be needed), the numa source
  19. // node (current location of the data) and the data size, this function should
  20. // return optimal cache placement
  21. // dst node and returned value can differ if the system, for example, has HBM
  22. // attached accessible directly to node n under a different node id m
  23. typedef int (CachePolicy)(const int numa_dst_node, const int numa_src_node, const size_t data_size);
  24. // copy policy specifies the copy-executing nodes for a given task
  25. // which allows flexibility in assignment for optimizing raw throughput
  26. // or choosing a conservative usage policy
  27. typedef std::vector<int> (CopyPolicy)(const int numa_dst_node, const int numa_src_node);
  28. private:
  29. // mutex for accessing the cache state map
  30. std::shared_mutex cache_mutex_;
  31. // map from [dst-numa-node,map2]
  32. // map2 from [data-ptr,cache-structure]
  33. std::unordered_map<uint8_t, std::unordered_map<uint8_t*, CacheData>> cache_state_;
  34. CachePolicy* cache_policy_function_ = nullptr;
  35. CopyPolicy* copy_policy_function_ = nullptr;
  36. // function used to submit a copy task on a specific node to the dml
  37. // engine on that node - will change the current threads node assignment
  38. // to achieve this so take care to restore this
  39. dml::handler<dml::mem_copy_operation, std::allocator<uint8_t>> ExecuteCopy(
  40. const uint8_t* src, uint8_t* dst, const size_t size, const int node
  41. ) const;
  42. // allocates the required memory on the destination node
  43. // and then submits task to the dml library for processing
  44. // and attaches the handlers to the cache data structure
  45. void SubmitTask(CacheData* task, const int dst_node, const int src_node);
  46. // querries the policy functions for the given data and size
  47. // to obtain destination cache node, also returns the datas
  48. // source node for further usage
  49. // output may depend on the calling threads node assignment
  50. // as this is set as the "optimal placement" node
  51. void GetCacheNode(uint8_t* src, const size_t size, int* OUT_DST_NODE, int* OUT_SRC_NODE) const;
  52. // checks whether the cache contains an entry for
  53. // the given data in the given memory node and
  54. // returns it, otherwise returns nullptr
  55. std::unique_ptr<CacheData> GetFromCache(uint8_t* src, const size_t size, const int dst_node);
  56. public:
  57. // initializes the cache with the two policy functions
  58. // only after this is it safe to use in a threaded environment
  59. void Init(CachePolicy* cache_policy_function, CopyPolicy* copy_policy_function);
  60. // function to perform data access through the cache
  61. std::unique_ptr<CacheData> Access(uint8_t* data, const size_t size);
  62. // flushes the cache of inactive entries
  63. // if node is -1 then the whole cache is
  64. // checked and otherwise the specified
  65. // node - no checks on node validity
  66. void Flush(const int node = -1);
  67. };
  68. }
  69. inline void dsacache::Cache::Init(CachePolicy* cache_policy_function, CopyPolicy* copy_policy_function) {
  70. cache_policy_function_ = cache_policy_function;
  71. copy_policy_function_ = copy_policy_function;
  72. // initialize numa library
  73. numa_available();
  74. // obtain all available nodes
  75. // and those we may allocate
  76. // memory on
  77. const int nodes_max = numa_num_configured_nodes();
  78. const bitmask* valid_nodes = numa_get_mems_allowed();
  79. // prepare the cache state with entries
  80. // for all given nodes
  81. for (int node = 0; node < nodes_max; node++) {
  82. if (numa_bitmask_isbitset(valid_nodes, node)) {
  83. cache_state_.insert({node,{}});
  84. }
  85. }
  86. std::cout << "[-] Cache Initialized" << std::endl;
  87. }
  88. inline std::unique_ptr<dsacache::CacheData> dsacache::Cache::Access(uint8_t* data, const size_t size) {
  89. // get destination numa node for the cache
  90. int dst_node = -1;
  91. int src_node = -1;
  92. GetCacheNode(data, size, &dst_node, &src_node);
  93. // TODO: at this point it could be beneficial to check whether
  94. // TODO: the given destination node is present as an entry
  95. // TODO: in the cache state to see if it is valid
  96. // check whether the data is already cached
  97. std::unique_ptr<CacheData> task = GetFromCache(data, size, dst_node);
  98. if (task != nullptr) {
  99. return std::move(task);
  100. }
  101. // at this point the requested data is not present in cache
  102. // and we create a caching task for it
  103. task = std::make_unique<CacheData>(data, size);
  104. {
  105. std::unique_lock<std::shared_mutex> lock(cache_mutex_);
  106. const auto state = cache_state_[dst_node].emplace(task->src_, *task);
  107. // if state.second is false then no insertion took place
  108. // which means that concurrently whith this thread
  109. // some other thread must have accessed the same
  110. // resource in which case we return the other
  111. // threads data cache structure
  112. if (!state.second) {
  113. std::cout << "[!] Found another cache instance for 0x" << std::hex << (uint64_t)task->src_ << std::dec << std::endl;
  114. return std::move(std::make_unique<CacheData>(state.first->second));
  115. }
  116. }
  117. SubmitTask(task.get(), dst_node, src_node);
  118. return std::move(task);
  119. }
  120. inline void dsacache::Cache::SubmitTask(CacheData* task, const int dst_node, const int src_node) {
  121. std::cout << "[+] Allocating " << task->size_ << "B on node " << dst_node << " for " << std::hex << (uint64_t)task->src_ << std::dec << std::endl;
  122. // allocate data on this node and flush the unused parts of the
  123. // cache if the operation fails and retry once
  124. // TODO: smarter flush strategy could keep some stuff cached
  125. uint8_t* dst = reinterpret_cast<uint8_t*>(numa_alloc_onnode(task->size_, dst_node));
  126. if (dst == nullptr) {
  127. std::cout << "[!] First allocation try failed for " << task->size_ << "B on node " << dst_node << std::endl;
  128. // allocation on dst_node failed so we flush the cache for this
  129. // node hoping to free enough currently unused entries to make
  130. // the second allocation attempt successful
  131. Flush(dst_node);
  132. dst = reinterpret_cast<uint8_t*>(numa_alloc_onnode(task->size_, dst_node));
  133. if (dst == nullptr) {
  134. std::cerr << "[x] Second allocation try failed for " << task->size_ << "B on node " << dst_node << std::endl;
  135. return;
  136. }
  137. }
  138. task->incomplete_cache_ = dst;
  139. // querry copy policy function for the nodes to use for the copy
  140. const std::vector<int> executing_nodes = copy_policy_function_(dst_node, src_node);
  141. const size_t task_count = executing_nodes.size();
  142. // each task will copy one fair part of the total size
  143. // and in case the total size is not a factor of the
  144. // given task count the last node must copy the remainder
  145. const size_t size = task->size_ / task_count;
  146. const size_t last_size = size + task->size_ % task_count;
  147. std::cout << "[-] Splitting Copy into " << task_count << " tasks of " << size << "B 0x" << std::hex << (uint64_t)task->src_ << std::dec << std::endl;
  148. // save the current numa node mask to restore later
  149. // as executing the copy task will place this thread
  150. // on a different node
  151. bitmask* nodemask = numa_get_run_node_mask();
  152. for (uint32_t i = 0; i < task_count; i++) {
  153. const size_t local_size = i + 1 == task_count ? size : last_size;
  154. const size_t local_offset = i * size;
  155. const uint8_t* local_src = task->src_ + local_offset;
  156. uint8_t* local_dst = dst + local_offset;
  157. task->handlers_->emplace_back(ExecuteCopy(local_src, local_dst, local_size, executing_nodes[i]));
  158. }
  159. // restore the previous nodemask
  160. numa_run_on_node_mask(nodemask);
  161. numa_free_nodemask(nodemask);
  162. }
  163. inline dml::handler<dml::mem_copy_operation, std::allocator<uint8_t>> dsacache::Cache::ExecuteCopy(
  164. const uint8_t* src, uint8_t* dst, const size_t size, const int node
  165. ) const {
  166. dml::const_data_view srcv = dml::make_view(src, size);
  167. dml::data_view dstv = dml::make_view(dst, size);
  168. numa_run_on_node(node);
  169. return dml::submit<dml::automatic>(dml::mem_copy.block_on_fault(), srcv, dstv);
  170. }
  171. void dsacache::Cache::GetCacheNode(uint8_t* src, const size_t size, int* OUT_DST_NODE, int* OUT_SRC_NODE) const {
  172. // obtain numa node of current thread to determine where the data is needed
  173. const int current_cpu = sched_getcpu();
  174. const int current_node = numa_node_of_cpu(current_cpu);
  175. // obtain node that the given data pointer is allocated on
  176. *OUT_SRC_NODE = -1;
  177. get_mempolicy(OUT_SRC_NODE, NULL, 0, (void*)src, MPOL_F_NODE | MPOL_F_ADDR);
  178. // querry cache policy function for the destination numa node
  179. *OUT_DST_NODE = cache_policy_function_(current_node, *OUT_SRC_NODE, size);
  180. }
  181. inline void dsacache::Cache::Flush(const int node) {
  182. std::cout << "[-] Flushing Cache for " << (node == -1 ? "all nodes" : "node " + std::to_string(node)) << std::endl;
  183. // this lambda is used because below we have two code paths that
  184. // flush nodes, either one single or all successively
  185. const auto FlushNode = [](std::unordered_map<uint8_t*,CacheData>& map) {
  186. // begin at the front of the map
  187. auto it = map.begin();
  188. // loop until we reach the end of the map
  189. while (it != map.end()) {
  190. // if the iterator points to an inactive element
  191. // then we may erase it
  192. if (it->second.Active() == false) {
  193. // erase the iterator from the map
  194. map.erase(it);
  195. // as the erasure invalidated out iterator
  196. // we must start at the beginning again
  197. it = map.begin();
  198. }
  199. else {
  200. // if element is active just move over to the next one
  201. it++;
  202. }
  203. }
  204. };
  205. {
  206. // we require exclusive lock as we modify the cache state
  207. std::unique_lock<std::shared_mutex> lock(cache_mutex_);
  208. // node == -1 means that cache on all nodes should be flushed
  209. if (node == -1) {
  210. for (auto& nc : cache_state_) {
  211. FlushNode(nc.second);
  212. }
  213. }
  214. else {
  215. FlushNode(cache_state_[node]);
  216. }
  217. }
  218. }
  219. std::unique_ptr<dsacache::CacheData> dsacache::Cache::GetFromCache(uint8_t* src, const size_t size, const int dst_node) {
  220. // the best situation is if this data is already cached
  221. // which we check in an unnamed block in which the cache
  222. // is locked for reading to prevent another thread
  223. // from marking the element we may find as unused and
  224. // clearing it
  225. // lock the cache state in shared-mode because we read
  226. std::shared_lock<std::shared_mutex> lock(cache_mutex_);
  227. // search for the data in our cache state structure at the given node
  228. const auto search = cache_state_[dst_node].find(src);
  229. // if the data is in our structure we continue
  230. if (search != cache_state_[dst_node].end()) {
  231. // now check whether the sizes match
  232. // TODO: second.size_ >= size would also work
  233. if (search->second.size_ == size) {
  234. std::cout << "[+] Found Cached version for 0x" << std::hex << (uint64_t)src << std::dec << std::endl;
  235. // return a unique copy of the entry which uses the object
  236. // lifetime and destructor to safely handle deallocation
  237. return std::move(std::make_unique<CacheData>(search->second));
  238. }
  239. else {
  240. std::cout << "[!] Found Cached version with size missmatch for 0x" << std::hex << (uint64_t)src << std::dec << std::endl;
  241. // if the sizes missmatch then we clear the current entry from cache
  242. // which will cause its deletion only after the last possible outside
  243. // reference is also destroyed
  244. cache_state_[dst_node].erase(search);
  245. }
  246. }
  247. return nullptr;
  248. }