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.

641 lines
21 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. namespace dml {
  12. inline const std::string StatusCodeToString(const dml::status_code code) {
  13. switch (code) {
  14. case dml::status_code::ok:
  15. return "ok";
  16. case dml::status_code::false_predicate:
  17. return "false predicate";
  18. case dml::status_code::partial_completion:
  19. return "partial completion";
  20. case dml::status_code::nullptr_error:
  21. return "nullptr error";
  22. case dml::status_code::bad_size:
  23. return "bad size";
  24. case dml::status_code::bad_length:
  25. return "bad length";
  26. case dml::status_code::inconsistent_size:
  27. return "inconsistent size";
  28. case dml::status_code::dualcast_bad_padding:
  29. return "dualcast bad padding";
  30. case dml::status_code::bad_alignment:
  31. return "bad alignment";
  32. case dml::status_code::buffers_overlapping:
  33. return "buffers overlapping";
  34. case dml::status_code::delta_delta_empty:
  35. return "delta delta empty";
  36. case dml::status_code::batch_overflow:
  37. return "batch overflow";
  38. case dml::status_code::execution_failed:
  39. return "execution failed";
  40. case dml::status_code::unsupported_operation:
  41. return "unsupported operation";
  42. case dml::status_code::queue_busy:
  43. return "queue busy";
  44. case dml::status_code::error:
  45. return "unknown error";
  46. case dml::status_code::config_error:
  47. return "config error";
  48. default:
  49. return "unhandled error";
  50. }
  51. }
  52. }
  53. namespace dsacache {
  54. class Cache;
  55. // cache data holds all required information on
  56. // one cache entry and will both be stored
  57. // internally by the cache and handed out
  58. // as copies to the user
  59. // this class uses its object lifetime and
  60. // a global reference counter to allow
  61. // thread-safe copies and resource management
  62. class CacheData {
  63. public:
  64. using dml_handler = dml::handler<dml::mem_copy_operation, std::allocator<uint8_t>>;
  65. private:
  66. // data source and size of the block
  67. uint8_t* src_;
  68. size_t size_;
  69. // global reference counting object
  70. std::atomic<int32_t>* active_;
  71. // global cache-location pointer
  72. std::atomic<uint8_t*>* cache_;
  73. // object-local incomplete cache location pointer
  74. // which is only available in the first instance
  75. uint8_t* incomplete_cache_;
  76. // dml handler vector pointer which is only
  77. // available in the first instance
  78. std::unique_ptr<std::vector<dml_handler>> handlers_;
  79. // deallocates the global cache-location
  80. // and invalidates it
  81. void Deallocate();
  82. // checks whether there are at least two
  83. // valid references to this object which
  84. // is done as the cache always has one
  85. // internally to any living instance
  86. bool Active() const;
  87. friend Cache;
  88. public:
  89. CacheData(uint8_t* data, const size_t size);
  90. CacheData(const CacheData& other);
  91. ~CacheData();
  92. // waits on completion of caching operations
  93. // for this task and is safe to be called in
  94. // any state of the object
  95. void WaitOnCompletion();
  96. // returns the cache data location for this
  97. // instance which is valid as long as the
  98. // instance is alive - !!! this may also
  99. // yield a nullptr !!!
  100. uint8_t* GetDataLocation() const;
  101. };
  102. // cache class will handle access to data through the cache
  103. // by managing the cache through work submission, it sticks
  104. // to user-defined caching and copy policies, is thread
  105. // safe after initialization and returns copies of
  106. // cache data class to the user
  107. class Cache {
  108. public:
  109. // cache policy is defined as a type here to allow flexible usage of the cacher
  110. // given a numa destination node (where the data will be needed), the numa source
  111. // node (current location of the data) and the data size, this function should
  112. // return optimal cache placement
  113. // dst node and returned value can differ if the system, for example, has HBM
  114. // attached accessible directly to node n under a different node id m
  115. typedef int (CachePolicy)(const int numa_dst_node, const int numa_src_node, const size_t data_size);
  116. // copy policy specifies the copy-executing nodes for a given task
  117. // which allows flexibility in assignment for optimizing raw throughput
  118. // or choosing a conservative usage policy
  119. typedef std::vector<int> (CopyPolicy)(const int numa_dst_node, const int numa_src_node);
  120. private:
  121. // mutex for accessing the cache state map
  122. std::shared_mutex cache_mutex_;
  123. // map from [dst-numa-node,map2]
  124. // map2 from [data-ptr,cache-structure]
  125. std::unordered_map<uint8_t, std::unordered_map<uint8_t*, CacheData>> cache_state_;
  126. CachePolicy* cache_policy_function_ = nullptr;
  127. CopyPolicy* copy_policy_function_ = nullptr;
  128. // function used to submit a copy task on a specific node to the dml
  129. // engine on that node - will change the current threads node assignment
  130. // to achieve this so take care to restore this
  131. dml::handler<dml::mem_copy_operation, std::allocator<uint8_t>> ExecuteCopy(
  132. const uint8_t* src, uint8_t* dst, const size_t size, const int node
  133. ) const;
  134. // allocates the required memory on the destination node
  135. // and then submits task to the dml library for processing
  136. // and attaches the handlers to the cache data structure
  137. void SubmitTask(CacheData* task, const int dst_node, const int src_node);
  138. // querries the policy functions for the given data and size
  139. // to obtain destination cache node, also returns the datas
  140. // source node for further usage
  141. // output may depend on the calling threads node assignment
  142. // as this is set as the "optimal placement" node
  143. void GetCacheNode(uint8_t* src, const size_t size, int* OUT_DST_NODE, int* OUT_SRC_NODE) const;
  144. // allocates memory of size "size" on the numa node "node"
  145. // and returns nullptr if this is not possible, also may
  146. // try to flush the cache of the requested node to
  147. // alleviate encountered shortage
  148. uint8_t* AllocOnNode(const size_t size, const int node);
  149. // checks whether the cache contains an entry for
  150. // the given data in the given memory node and
  151. // returns it, otherwise returns nullptr
  152. std::unique_ptr<CacheData> GetFromCache(uint8_t* src, const size_t size, const int dst_node);
  153. public:
  154. // initializes the cache with the two policy functions
  155. // only after this is it safe to use in a threaded environment
  156. void Init(CachePolicy* cache_policy_function, CopyPolicy* copy_policy_function);
  157. // function to perform data access through the cache
  158. std::unique_ptr<CacheData> Access(uint8_t* data, const size_t size);
  159. // flushes the cache of inactive entries
  160. // if node is -1 then the whole cache is
  161. // checked and otherwise the specified
  162. // node - no checks on node validity
  163. void Flush(const int node = -1);
  164. // forces out all entries from the
  165. // cache and therefore will also "forget"
  166. // still-in-use entries, these will still
  167. // be properly deleted, but the cache
  168. // will be fresh - use for testing
  169. void Clear();
  170. };
  171. }
  172. inline void dsacache::Cache::Clear() {
  173. std::unique_lock<std::shared_mutex> lock(cache_mutex_);
  174. cache_state_.clear();
  175. Init(cache_policy_function_, copy_policy_function_);
  176. }
  177. inline void dsacache::Cache::Init(CachePolicy* cache_policy_function, CopyPolicy* copy_policy_function) {
  178. cache_policy_function_ = cache_policy_function;
  179. copy_policy_function_ = copy_policy_function;
  180. // initialize numa library
  181. numa_available();
  182. // obtain all available nodes
  183. // and those we may allocate
  184. // memory on
  185. const int nodes_max = numa_num_configured_nodes();
  186. const bitmask* valid_nodes = numa_get_mems_allowed();
  187. // prepare the cache state with entries
  188. // for all given nodes
  189. for (int node = 0; node < nodes_max; node++) {
  190. if (numa_bitmask_isbitset(valid_nodes, node)) {
  191. cache_state_.insert({node,{}});
  192. }
  193. }
  194. }
  195. inline std::unique_ptr<dsacache::CacheData> dsacache::Cache::Access(uint8_t* data, const size_t size) {
  196. // get destination numa node for the cache
  197. int dst_node = -1;
  198. int src_node = -1;
  199. GetCacheNode(data, size, &dst_node, &src_node);
  200. // TODO: at this point it could be beneficial to check whether
  201. // TODO: the given destination node is present as an entry
  202. // TODO: in the cache state to see if it is valid
  203. // check whether the data is already cached
  204. std::unique_ptr<CacheData> task = GetFromCache(data, size, dst_node);
  205. if (task != nullptr) {
  206. return std::move(task);
  207. }
  208. // at this point the requested data is not present in cache
  209. // and we create a caching task for it
  210. task = std::make_unique<CacheData>(data, size);
  211. {
  212. std::unique_lock<std::shared_mutex> lock(cache_mutex_);
  213. const auto state = cache_state_[dst_node].emplace(task->src_, *task);
  214. // if state.second is false then no insertion took place
  215. // which means that concurrently whith this thread
  216. // some other thread must have accessed the same
  217. // resource in which case we return the other
  218. // threads data cache structure
  219. if (!state.second) {
  220. std::cout << "[!] Found another cache instance for 0x" << std::hex << (uint64_t)task->src_ << std::dec << std::endl;
  221. return std::move(std::make_unique<CacheData>(state.first->second));
  222. }
  223. }
  224. SubmitTask(task.get(), dst_node, src_node);
  225. return std::move(task);
  226. }
  227. inline uint8_t* dsacache::Cache::AllocOnNode(const size_t size, const int node) {
  228. // allocate data on this node and flush the unused parts of the
  229. // cache if the operation fails and retry once
  230. // TODO: smarter flush strategy could keep some stuff cached
  231. // check currently free memory to see if the data fits
  232. long long int free_space = 0;
  233. numa_node_size64(node, &free_space);
  234. if (free_space < size) {
  235. std::cout << "[!] Memory shortage when allocating " << size << "B on node " << node << std::endl;
  236. // dst node lacks memory space so we flush the cache for this
  237. // node hoping to free enough currently unused entries to make
  238. // the second allocation attempt successful
  239. Flush(node);
  240. // re-test by getting the free space and checking again
  241. numa_node_size64(node, &free_space);
  242. if (free_space < size) {
  243. std::cout << "[x] Memory shortage after flush when allocating " << size << "B on node " << node << std::endl;
  244. return nullptr;
  245. }
  246. }
  247. uint8_t* dst = reinterpret_cast<uint8_t*>(numa_alloc_onnode(size, node));
  248. if (dst == nullptr) {
  249. std::cout << "[x] Allocation try failed for " << size << "B on node " << node << std::endl;
  250. return nullptr;
  251. }
  252. return dst;
  253. }
  254. inline void dsacache::Cache::SubmitTask(CacheData* task, const int dst_node, const int src_node) {
  255. uint8_t* dst = AllocOnNode(task->size_, dst_node);
  256. if (dst == nullptr) {
  257. std::cout << "[x] Allocation failed so we can not cache" << std::endl;
  258. return;
  259. }
  260. task->incomplete_cache_ = dst;
  261. // querry copy policy function for the nodes to use for the copy
  262. const std::vector<int> executing_nodes = copy_policy_function_(dst_node, src_node);
  263. const size_t task_count = executing_nodes.size();
  264. // each task will copy one fair part of the total size
  265. // and in case the total size is not a factor of the
  266. // given task count the last node must copy the remainder
  267. const size_t size = task->size_ / task_count;
  268. const size_t last_size = size + task->size_ % task_count;
  269. // save the current numa node mask to restore later
  270. // as executing the copy task will place this thread
  271. // on a different node
  272. bitmask* nodemask = numa_get_run_node_mask();
  273. for (uint32_t i = 0; i < task_count; i++) {
  274. const size_t local_size = i + 1 == task_count ? size : last_size;
  275. const size_t local_offset = i * size;
  276. const uint8_t* local_src = task->src_ + local_offset;
  277. uint8_t* local_dst = dst + local_offset;
  278. task->handlers_->emplace_back(ExecuteCopy(local_src, local_dst, local_size, executing_nodes[i]));
  279. }
  280. // restore the previous nodemask
  281. numa_run_on_node_mask(nodemask);
  282. numa_free_nodemask(nodemask);
  283. }
  284. inline dml::handler<dml::mem_copy_operation, std::allocator<uint8_t>> dsacache::Cache::ExecuteCopy(
  285. const uint8_t* src, uint8_t* dst, const size_t size, const int node
  286. ) const {
  287. dml::const_data_view srcv = dml::make_view(src, size);
  288. dml::data_view dstv = dml::make_view(dst, size);
  289. numa_run_on_node(node);
  290. return dml::submit<dml::automatic>(dml::mem_copy.block_on_fault(), srcv, dstv);
  291. }
  292. inline void dsacache::Cache::GetCacheNode(uint8_t* src, const size_t size, int* OUT_DST_NODE, int* OUT_SRC_NODE) const {
  293. // obtain numa node of current thread to determine where the data is needed
  294. const int current_cpu = sched_getcpu();
  295. const int current_node = numa_node_of_cpu(current_cpu);
  296. // obtain node that the given data pointer is allocated on
  297. *OUT_SRC_NODE = -1;
  298. get_mempolicy(OUT_SRC_NODE, NULL, 0, (void*)src, MPOL_F_NODE | MPOL_F_ADDR);
  299. // querry cache policy function for the destination numa node
  300. *OUT_DST_NODE = cache_policy_function_(current_node, *OUT_SRC_NODE, size);
  301. }
  302. inline void dsacache::Cache::Flush(const int node) {
  303. // this lambda is used because below we have two code paths that
  304. // flush nodes, either one single or all successively
  305. const auto FlushNode = [](std::unordered_map<uint8_t*,CacheData>& map) {
  306. // begin at the front of the map
  307. auto it = map.begin();
  308. // loop until we reach the end of the map
  309. while (it != map.end()) {
  310. // if the iterator points to an inactive element
  311. // then we may erase it
  312. if (it->second.Active() == false) {
  313. // erase the iterator from the map
  314. map.erase(it);
  315. // as the erasure invalidated out iterator
  316. // we must start at the beginning again
  317. it = map.begin();
  318. }
  319. else {
  320. // if element is active just move over to the next one
  321. it++;
  322. }
  323. }
  324. };
  325. {
  326. // we require exclusive lock as we modify the cache state
  327. std::unique_lock<std::shared_mutex> lock(cache_mutex_);
  328. // node == -1 means that cache on all nodes should be flushed
  329. if (node == -1) {
  330. for (auto& nc : cache_state_) {
  331. FlushNode(nc.second);
  332. }
  333. }
  334. else {
  335. FlushNode(cache_state_[node]);
  336. }
  337. }
  338. }
  339. inline std::unique_ptr<dsacache::CacheData> dsacache::Cache::GetFromCache(uint8_t* src, const size_t size, const int dst_node) {
  340. // the best situation is if this data is already cached
  341. // which we check in an unnamed block in which the cache
  342. // is locked for reading to prevent another thread
  343. // from marking the element we may find as unused and
  344. // clearing it
  345. // lock the cache state in shared-mode because we read
  346. std::shared_lock<std::shared_mutex> lock(cache_mutex_);
  347. // search for the data in our cache state structure at the given node
  348. const auto search = cache_state_[dst_node].find(src);
  349. // if the data is in our structure we continue
  350. if (search != cache_state_[dst_node].end()) {
  351. // now check whether the sizes match
  352. if (search->second.size_ >= size) {
  353. // return a unique copy of the entry which uses the object
  354. // lifetime and destructor to safely handle deallocation
  355. return std::move(std::make_unique<CacheData>(search->second));
  356. }
  357. else {
  358. // if the sizes missmatch then we clear the current entry from cache
  359. // which will cause its deletion only after the last possible outside
  360. // reference is also destroyed
  361. cache_state_[dst_node].erase(search);
  362. }
  363. }
  364. return nullptr;
  365. }
  366. inline dsacache::CacheData::CacheData(uint8_t* data, const size_t size) {
  367. src_ = data;
  368. size_ = size;
  369. active_ = new std::atomic<int32_t>(1);
  370. cache_ = new std::atomic<uint8_t*>();
  371. incomplete_cache_ = nullptr;
  372. handlers_ = std::make_unique<std::vector<dml_handler>>();
  373. }
  374. inline dsacache::CacheData::CacheData(const dsacache::CacheData& other) {
  375. // we copy the ptr to the global atomic reference counter
  376. // and increase the amount of active references
  377. active_ = other.active_;
  378. const int current_active = active_->fetch_add(1);
  379. // source and size will be copied too
  380. // as well as the reference to the global
  381. // atomic cache pointer
  382. src_ = other.src_;
  383. size_ = other.size_;
  384. cache_ = other.cache_;
  385. // incomplete cache and handlers will not
  386. // be copied because only the first instance
  387. // will wait on the completion of handlers
  388. incomplete_cache_ = nullptr;
  389. handlers_ = nullptr;
  390. }
  391. inline dsacache::CacheData::~CacheData() {
  392. // if this is the first instance of this cache structure
  393. // and it has not been waited on and is now being destroyed
  394. // we must wait on completion here to ensure the cache
  395. // remains in a valid state
  396. if (handlers_ != nullptr) {
  397. WaitOnCompletion();
  398. }
  399. // due to fetch_sub returning the preivously held value
  400. // we must subtract one locally to get the current value
  401. const int32_t v = active_->fetch_sub(1) - 1;
  402. // if the returned value is zero or lower
  403. // then we must execute proper deletion
  404. // as this was the last reference
  405. if (v <= 0) {
  406. Deallocate();
  407. delete active_;
  408. delete cache_;
  409. }
  410. }
  411. inline void dsacache::CacheData::Deallocate() {
  412. // although deallocate should only be called from
  413. // a safe context to do so, it can not hurt to
  414. // defensively perform the operation atomically
  415. uint8_t* cache_local = cache_->exchange(nullptr);
  416. if (cache_local != nullptr) numa_free(cache_local, size_);
  417. }
  418. inline uint8_t* dsacache::CacheData::GetDataLocation() const {
  419. return cache_->load();
  420. }
  421. inline bool dsacache::CacheData::Active() const {
  422. // this entry is active if more than one
  423. // reference exists to it, as the Cache
  424. // will always keep one internally until
  425. // the entry is cleared from cache
  426. return active_->load() > 1;
  427. }
  428. inline void dsacache::CacheData::WaitOnCompletion() {
  429. // the cache data entry can be in two states
  430. // either it is the original one which has not
  431. // been waited for in which case the handlers
  432. // are non-null or it is not
  433. if (handlers_ == nullptr) {
  434. // when no handlers are attached to this cache entry we wait on a
  435. // value change for the cache structure from nullptr to non-null
  436. // which will either go through immediately if the cache is valid
  437. // already or wait until the handler-owning thread notifies us
  438. cache_->wait(nullptr);
  439. }
  440. else {
  441. // when the handlers are non-null there are some DSA task handlers
  442. // available on which we must wait here
  443. // abort is set if any operation encountered an error
  444. bool abort = false;
  445. for (auto& handler : *handlers_) {
  446. auto result = handler.get();
  447. if (result.status != dml::status_code::ok) {
  448. std::cerr << "[x] Encountered bad status code for operation: " << dml::StatusCodeToString(result.status) << std::endl;
  449. // if one of the copy tasks failed we abort the whole task
  450. // after all operations are completed on it
  451. abort = true;
  452. }
  453. }
  454. // the handlers are cleared after all have completed
  455. handlers_ = nullptr;
  456. // now we act depending on whether an abort has been
  457. // called for which signals operation incomplete
  458. if (abort) {
  459. // store nullptr in the cache location
  460. cache_->store(nullptr);
  461. // then free the now incomplete cache
  462. // TODO: it would be possible to salvage the
  463. // TODO: operation at this point but this
  464. // TODO: is quite complicated so we just abort
  465. numa_free(incomplete_cache_, size_);
  466. }
  467. else {
  468. // incomplete cache is now safe to use and therefore we
  469. // swap it with the global cache state of this entry
  470. // and notify potentially waiting threads
  471. cache_->store(incomplete_cache_);
  472. }
  473. // as a last step all waiting threads must
  474. // be notified (copies of this will wait on value
  475. // change of the cache) and the incomplete cache
  476. // is cleared to nullptr as it is not incomplete
  477. cache_->notify_all();
  478. incomplete_cache_ = nullptr;
  479. }
  480. }