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.

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