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.

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