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.

726 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(const Cache& other) = delete;
  208. // initializes the cache with the two policy functions
  209. // only after this is it safe to use in a threaded environment
  210. void Init(CachePolicy* cache_policy_function, CopyPolicy* copy_policy_function);
  211. // function to perform data access through the cache
  212. std::unique_ptr<CacheData> Access(uint8_t* data, const size_t size);
  213. // flushes the cache of inactive entries
  214. // if node is -1 then the whole cache is
  215. // checked and otherwise the specified
  216. // node - no checks on node validity
  217. void Flush(const int node = -1);
  218. // forces out all entries from the
  219. // cache and therefore will also "forget"
  220. // still-in-use entries, these will still
  221. // be properly deleted, but the cache
  222. // will be fresh - use for testing
  223. void Clear();
  224. void Invalidate(uint8_t* data);
  225. };
  226. }
  227. inline void dsacache::Cache::Clear() {
  228. std::unique_lock<std::shared_mutex> lock(cache_mutex_);
  229. cache_state_.clear();
  230. Init(cache_policy_function_, copy_policy_function_);
  231. }
  232. inline void dsacache::Cache::Init(CachePolicy* cache_policy_function, CopyPolicy* copy_policy_function) {
  233. cache_policy_function_ = cache_policy_function;
  234. copy_policy_function_ = copy_policy_function;
  235. // initialize numa library
  236. numa_available();
  237. // obtain all available nodes
  238. // and those we may allocate
  239. // memory on
  240. const int nodes_max = numa_num_configured_nodes();
  241. const bitmask* valid_nodes = numa_get_mems_allowed();
  242. // prepare the cache state with entries
  243. // for all given nodes
  244. for (int node = 0; node < nodes_max; node++) {
  245. if (numa_bitmask_isbitset(valid_nodes, node)) {
  246. cache_state_.insert({node,{}});
  247. }
  248. }
  249. }
  250. inline std::unique_ptr<dsacache::CacheData> dsacache::Cache::Access(uint8_t* data, const size_t size) {
  251. // get destination numa node for the cache
  252. int dst_node = -1;
  253. int src_node = -1;
  254. GetCacheNode(data, size, &dst_node, &src_node);
  255. // TODO: at this point it could be beneficial to check whether
  256. // TODO: the given destination node is present as an entry
  257. // TODO: in the cache state to see if it is valid
  258. // check whether the data is already cached
  259. std::unique_ptr<CacheData> task = GetFromCache(data, size, dst_node);
  260. if (task != nullptr) {
  261. return std::move(task);
  262. }
  263. // at this point the requested data is not present in cache
  264. // and we create a caching task for it
  265. task = std::make_unique<CacheData>(data, size);
  266. {
  267. std::unique_lock<std::shared_mutex> lock(cache_mutex_);
  268. const auto state = cache_state_[dst_node].emplace(task->src_, *task);
  269. // if state.second is false then no insertion took place
  270. // which means that concurrently whith this thread
  271. // some other thread must have accessed the same
  272. // resource in which case we return the other
  273. // threads data cache structure
  274. if (!state.second) {
  275. std::cout << "[!] Found another cache instance for 0x" << std::hex << (uint64_t)task->src_ << std::dec << std::endl;
  276. return std::move(std::make_unique<CacheData>(state.first->second));
  277. }
  278. }
  279. SubmitTask(task.get(), dst_node, src_node);
  280. return std::move(task);
  281. }
  282. inline uint8_t* dsacache::Cache::AllocOnNode(const size_t size, const int node) {
  283. // allocate data on this node and flush the unused parts of the
  284. // cache if the operation fails and retry once
  285. // TODO: smarter flush strategy could keep some stuff cached
  286. // check currently free memory to see if the data fits
  287. long long int free_space = 0;
  288. numa_node_size64(node, &free_space);
  289. if (free_space < size) {
  290. std::cout << "[!] Memory shortage when allocating " << size << "B on node " << node << std::endl;
  291. // dst node lacks memory space so we flush the cache for this
  292. // node hoping to free enough currently unused entries to make
  293. // the second allocation attempt successful
  294. Flush(node);
  295. // re-test by getting the free space and checking again
  296. numa_node_size64(node, &free_space);
  297. if (free_space < size) {
  298. std::cout << "[x] Memory shortage after flush when allocating " << size << "B on node " << node << std::endl;
  299. return nullptr;
  300. }
  301. }
  302. uint8_t* dst = reinterpret_cast<uint8_t*>(numa_alloc_onnode(size, node));
  303. if (dst == nullptr) {
  304. std::cout << "[x] Allocation try failed for " << size << "B on node " << node << std::endl;
  305. return nullptr;
  306. }
  307. return dst;
  308. }
  309. inline void dsacache::Cache::SubmitTask(CacheData* task, const int dst_node, const int src_node) {
  310. uint8_t* dst = AllocOnNode(task->size_, dst_node);
  311. if (dst == nullptr) {
  312. std::cout << "[x] Allocation failed so we can not cache" << std::endl;
  313. return;
  314. }
  315. task->incomplete_cache_ = dst;
  316. // querry copy policy function for the nodes to use for the copy
  317. const std::vector<int> executing_nodes = copy_policy_function_(dst_node, src_node, task->size_);
  318. const size_t task_count = executing_nodes.size();
  319. // each task will copy one fair part of the total size
  320. // and in case the total size is not a factor of the
  321. // given task count the last node must copy the remainder
  322. const size_t size = task->size_ / task_count;
  323. const size_t last_size = size + task->size_ % task_count;
  324. // save the current numa node mask to restore later
  325. // as executing the copy task will place this thread
  326. // on a different node
  327. bitmask* nodemask = numa_get_run_node_mask();
  328. for (uint32_t i = 0; i < task_count; i++) {
  329. const size_t local_size = i + 1 == task_count ? size : last_size;
  330. const size_t local_offset = i * size;
  331. const uint8_t* local_src = task->src_ + local_offset;
  332. uint8_t* local_dst = dst + local_offset;
  333. task->handlers_->emplace_back(ExecuteCopy(local_src, local_dst, local_size, executing_nodes[i]));
  334. }
  335. // restore the previous nodemask
  336. numa_run_on_node_mask(nodemask);
  337. numa_free_nodemask(nodemask);
  338. }
  339. inline dml::handler<dml::mem_copy_operation, std::allocator<uint8_t>> dsacache::Cache::ExecuteCopy(
  340. const uint8_t* src, uint8_t* dst, const size_t size, const int node
  341. ) const {
  342. dml::const_data_view srcv = dml::make_view(src, size);
  343. dml::data_view dstv = dml::make_view(dst, size);
  344. numa_run_on_node(node);
  345. return dml::submit<dml::automatic>(dml::mem_copy.block_on_fault(), srcv, dstv);
  346. }
  347. inline void dsacache::Cache::GetCacheNode(uint8_t* src, const size_t size, int* OUT_DST_NODE, int* OUT_SRC_NODE) const {
  348. // obtain numa node of current thread to determine where the data is needed
  349. const int current_cpu = sched_getcpu();
  350. const int current_node = numa_node_of_cpu(current_cpu);
  351. // obtain node that the given data pointer is allocated on
  352. *OUT_SRC_NODE = -1;
  353. get_mempolicy(OUT_SRC_NODE, NULL, 0, (void*)src, MPOL_F_NODE | MPOL_F_ADDR);
  354. // querry cache policy function for the destination numa node
  355. *OUT_DST_NODE = cache_policy_function_(current_node, *OUT_SRC_NODE, size);
  356. }
  357. inline void dsacache::Cache::Flush(const int node) {
  358. // this lambda is used because below we have two code paths that
  359. // flush nodes, either one single or all successively
  360. const auto FlushNode = [](std::unordered_map<uint8_t*,CacheData>& map) {
  361. // begin at the front of the map
  362. auto it = map.begin();
  363. // loop until we reach the end of the map
  364. while (it != map.end()) {
  365. // if the iterator points to an inactive element
  366. // then we may erase it
  367. if (it->second.Active() == false) {
  368. // erase the iterator from the map
  369. map.erase(it);
  370. // as the erasure invalidated out iterator
  371. // we must start at the beginning again
  372. it = map.begin();
  373. }
  374. else {
  375. // if element is active just move over to the next one
  376. it++;
  377. }
  378. }
  379. };
  380. {
  381. // we require exclusive lock as we modify the cache state
  382. std::unique_lock<std::shared_mutex> lock(cache_mutex_);
  383. // node == -1 means that cache on all nodes should be flushed
  384. if (node == -1) {
  385. for (auto& nc : cache_state_) {
  386. FlushNode(nc.second);
  387. }
  388. }
  389. else {
  390. FlushNode(cache_state_[node]);
  391. }
  392. }
  393. }
  394. inline std::unique_ptr<dsacache::CacheData> dsacache::Cache::GetFromCache(uint8_t* src, const size_t size, const int dst_node) {
  395. // the best situation is if this data is already cached
  396. // which we check in an unnamed block in which the cache
  397. // is locked for reading to prevent another thread
  398. // from marking the element we may find as unused and
  399. // clearing it
  400. // lock the cache state in shared-mode because we read
  401. std::shared_lock<std::shared_mutex> lock(cache_mutex_);
  402. // search for the data in our cache state structure at the given node
  403. const auto search = cache_state_[dst_node].find(src);
  404. // if the data is in our structure we continue
  405. if (search != cache_state_[dst_node].end()) {
  406. // now check whether the sizes match
  407. if (search->second.size_ >= size) {
  408. // return a unique copy of the entry which uses the object
  409. // lifetime and destructor to safely handle deallocation
  410. return std::move(std::make_unique<CacheData>(search->second));
  411. }
  412. else {
  413. // if the sizes missmatch then we clear the current entry from cache
  414. // which will cause its deletion only after the last possible outside
  415. // reference is also destroyed
  416. cache_state_[dst_node].erase(search);
  417. }
  418. }
  419. return nullptr;
  420. }
  421. void dsacache::Cache::Invalidate(uint8_t* data) {
  422. // as the cache is modified we must obtain a unique writers lock
  423. std::unique_lock<std::shared_mutex> lock(cache_mutex_);
  424. // loop through all per-node-caches available
  425. for (auto node : cache_state_) {
  426. // search for an entry for the given data pointer
  427. auto search = node.second.find(data);
  428. if (search != node.second.end()) {
  429. // if the data is represented in-cache
  430. // then it will be erased to re-trigger
  431. // caching on next access
  432. node.second.erase(search);
  433. }
  434. }
  435. }
  436. inline dsacache::CacheData::CacheData(uint8_t* data, const size_t size) {
  437. src_ = data;
  438. size_ = size;
  439. active_ = new std::atomic<int32_t>(1);
  440. cache_ = new std::atomic<uint8_t*>();
  441. incomplete_cache_ = nullptr;
  442. handlers_ = std::make_unique<std::vector<dml_handler>>();
  443. }
  444. inline dsacache::CacheData::CacheData(const dsacache::CacheData& other) {
  445. // we copy the ptr to the global atomic reference counter
  446. // and increase the amount of active references
  447. active_ = other.active_;
  448. const int current_active = active_->fetch_add(1);
  449. // source and size will be copied too
  450. // as well as the reference to the global
  451. // atomic cache pointer
  452. src_ = other.src_;
  453. size_ = other.size_;
  454. cache_ = other.cache_;
  455. // incomplete cache and handlers will not
  456. // be copied because only the first instance
  457. // will wait on the completion of handlers
  458. incomplete_cache_ = nullptr;
  459. handlers_ = nullptr;
  460. }
  461. inline dsacache::CacheData::~CacheData() {
  462. // if this is the first instance of this cache structure
  463. // and it has not been waited on and is now being destroyed
  464. // we must wait on completion here to ensure the cache
  465. // remains in a valid state
  466. if (handlers_ != nullptr) {
  467. WaitOnCompletion();
  468. }
  469. // due to fetch_sub returning the preivously held value
  470. // we must subtract one locally to get the current value
  471. const int32_t v = active_->fetch_sub(1) - 1;
  472. // if the returned value is zero or lower
  473. // then we must execute proper deletion
  474. // as this was the last reference
  475. if (v <= 0) {
  476. Deallocate();
  477. delete active_;
  478. delete cache_;
  479. }
  480. }
  481. inline void dsacache::CacheData::Deallocate() {
  482. // although deallocate should only be called from
  483. // a safe context to do so, it can not hurt to
  484. // defensively perform the operation atomically
  485. uint8_t* cache_local = cache_->exchange(nullptr);
  486. if (cache_local != nullptr) numa_free(cache_local, size_);
  487. // if the cache was never waited for then incomplete_cache_
  488. // may still contain a valid pointer which has to be freed
  489. if (incomplete_cache_ != nullptr) numa_free(incomplete_cache_, size_);
  490. }
  491. inline uint8_t* dsacache::CacheData::GetDataLocation() const {
  492. return cache_->load();
  493. }
  494. inline bool dsacache::CacheData::Active() const {
  495. // this entry is active if more than one
  496. // reference exists to it, as the Cache
  497. // will always keep one internally until
  498. // the entry is cleared from cache
  499. return active_->load() > 1;
  500. }
  501. inline void dsacache::CacheData::WaitOnCompletion() {
  502. // the cache data entry can be in two states
  503. // either it is the original one which has not
  504. // been waited for in which case the handlers
  505. // are non-null or it is not
  506. if (handlers_ == nullptr) {
  507. // when no handlers are attached to this cache entry we wait on a
  508. // value change for the cache structure from nullptr to non-null
  509. // which will either go through immediately if the cache is valid
  510. // already or wait until the handler-owning thread notifies us
  511. cache_->wait(nullptr);
  512. }
  513. else {
  514. // when the handlers are non-null there are some DSA task handlers
  515. // available on which we must wait here
  516. // abort is set if any operation encountered an error
  517. bool abort = false;
  518. for (auto& handler : *handlers_) {
  519. auto result = handler.get();
  520. if (result.status != dml::status_code::ok) {
  521. std::cerr << "[x] Encountered bad status code for operation: " << dml::StatusCodeToString(result.status) << std::endl;
  522. // if one of the copy tasks failed we abort the whole task
  523. // after all operations are completed on it
  524. abort = true;
  525. }
  526. }
  527. // the handlers are cleared after all have completed
  528. handlers_ = nullptr;
  529. // now we act depending on whether an abort has been
  530. // called for which signals operation incomplete
  531. if (abort) {
  532. // store nullptr in the cache location
  533. cache_->store(nullptr);
  534. // then free the now incomplete cache
  535. // TODO: it would be possible to salvage the
  536. // TODO: operation at this point but this
  537. // TODO: is quite complicated so we just abort
  538. numa_free(incomplete_cache_, size_);
  539. }
  540. else {
  541. // incomplete cache is now safe to use and therefore we
  542. // swap it with the global cache state of this entry
  543. // and notify potentially waiting threads
  544. cache_->store(incomplete_cache_);
  545. }
  546. // as a last step all waiting threads must
  547. // be notified (copies of this will wait on value
  548. // change of the cache) and the incomplete cache
  549. // is cleared to nullptr as it is not incomplete
  550. cache_->notify_all();
  551. incomplete_cache_ = nullptr;
  552. }
  553. }