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.

816 lines
31 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. inline bool CheckFlag(const uint64_t value, const uint64_t flag) {
  37. return (value & flag) != 0;
  38. }
  39. inline uint64_t UnsetFlag(const uint64_t value, const uint64_t flag) {
  40. return value & (~flag);
  41. }
  42. inline uint64_t SetFlag(const uint64_t value, const uint64_t flag) {
  43. return value | flag;
  44. }
  45. constexpr uint64_t FLAG_WAIT_WEAK = 0b1ULL << 63;
  46. constexpr uint64_t FLAG_HANDLE_PF = 0b1ULL << 62;
  47. constexpr uint64_t FLAG_ACCESS_WEAK = 0b1ULL << 61;
  48. constexpr uint64_t FLAG_FORCE_MAP_PAGES = 0b1ULL << 60;
  49. constexpr uint64_t FLAG_DEFAULT = 0ULL;
  50. class Cache;
  51. // cache policy is defined as a type here to allow flexible usage of the cacher
  52. // given a numa destination node (where the data will be needed), the numa source
  53. // node (current location of the data) and the data size, this function should
  54. // return optimal cache placement
  55. // dst node and returned value can differ if the system, for example, has HBM
  56. // attached accessible directly to node n under a different node id m
  57. typedef int (CachePolicy)(const int numa_dst_node, const int numa_src_node, const size_t data_size);
  58. // copy policy specifies the copy-executing nodes for a given task
  59. // which allows flexibility in assignment for optimizing raw throughput
  60. // or choosing a conservative usage policy
  61. typedef std::vector<int> (CopyPolicy)(const int numa_dst_node, const int numa_src_node, const size_t data_size);
  62. // memory allocation is a complex topic but can have big performance
  63. // impact, we therefore do not handle it in the cache. must return
  64. // pointer to a block of at least the given size, cache will also
  65. // not handle deallocation but signal that the block is free
  66. typedef uint8_t* (MemoryAllocator_Allocate)(const int numa_node, const size_t size);
  67. // signals that the given memory block will not be used by cache anymore
  68. typedef void (MemoryAllocator_Free)(uint8_t* pointer, const size_t size);
  69. /*
  70. * Class Description:
  71. * Holds all required information on one cache entry and is used
  72. * both internally by the Cache and externally by the user.
  73. *
  74. * Important Usage Notes:
  75. * The pointer is only updated in WaitOnCompletion() which
  76. * therefore must be called by the user at some point in order
  77. * to use the cached data. Using this class as T for
  78. * std::shared_ptr<T> is not recommended as references are
  79. * already counted internally.
  80. *
  81. * Cache Lifetime:
  82. * As long as the instance is referenced, the pointer it stores
  83. * is guaranteed to be either nullptr or pointing to a valid copy.
  84. *
  85. * Implementation Detail:
  86. * Performs self-reference counting with a shared atomic integer.
  87. * Therefore on creating a copy the reference count is increased
  88. * and with the destructor it is deacresed. If the last copy is
  89. * destroyed the actual underlying data is freed and all shared
  90. * variables deleted.
  91. *
  92. * Notes on Thread Safety:
  93. * Class is thread safe in any possible state and performs
  94. * reference counting and deallocation itself entirely atomically.
  95. */
  96. class CacheData {
  97. public:
  98. using dml_handler = dml::handler<dml::mem_copy_operation, std::allocator<uint8_t>>;
  99. private:
  100. // set to false if we do not own the cache pointer
  101. bool delete_ = false;
  102. MemoryAllocator_Free* memory_free_function_;
  103. // data source and size of the block
  104. uint8_t* src_;
  105. size_t size_;
  106. // global reference counting object
  107. std::atomic<int32_t>* active_;
  108. // global cache-location pointer
  109. std::atomic<uint8_t*>* cache_;
  110. // object-local incomplete cache location pointer
  111. // contract: only access when being in sole posession of handlers
  112. uint8_t** incomplete_cache_;
  113. // flags inherited from parent cache
  114. uint64_t flags_ = 0;
  115. // dml handler vector pointer which is used
  116. // to wait on caching task completion
  117. std::atomic<std::vector<dml_handler>*>* handlers_;
  118. // invalid handlers pointer as we need a secondary
  119. // invalid state due to issues with waiting
  120. std::vector<dml_handler>* invalid_handlers_;
  121. // deallocates the global cache-location
  122. // and invalidates it
  123. void Deallocate();
  124. size_t GetSize() const { return size_; }
  125. uint8_t* GetSource() const { return src_; }
  126. int32_t GetRefCount() const { return active_->load(); }
  127. void SetInvalidHandlersAndCacheToSource();
  128. void SetTaskHandlersAndCache(uint8_t* cache, std::vector<dml_handler>* handlers);
  129. // initializes the class after which it is thread safe
  130. // but may only be destroyed safely after setting handlers
  131. // afterwards either SetTaskHandlersAndCache or
  132. // SetCacheToSource must be called to prevent deadlocks
  133. void Init(std::vector<dml_handler>* invalid_handlers);
  134. friend Cache;
  135. public:
  136. CacheData(uint8_t* data, const size_t size, MemoryAllocator_Free* free);
  137. CacheData(const CacheData& other);
  138. ~CacheData();
  139. // waits on completion of caching operations
  140. // for this task and is safe to be called in
  141. // any state of the object, if the flag
  142. // FLAG_WAIT_WEAK is set for this instance
  143. // (can also be inherited from the creating
  144. // Cache-Instance or on copy from another
  145. // CacheData-Instance), WaitOnCompletion
  146. // provides no validity guarantees to the
  147. // cache pointer (GetDataLocation() may
  148. // return nullptr even after return
  149. // of the wait function). On error this
  150. // function will set the cache pointer
  151. // to the source to provide validity
  152. // guarantees after returning.
  153. void WaitOnCompletion();
  154. // returns the cache data location for this
  155. // instance which is valid as long as the
  156. // instance is alive
  157. // !!! this may also return a nullptr !!!
  158. // see WaitOnCompletion() for how to achieve
  159. // validity guarantees if required
  160. uint8_t* GetDataLocation() const { return cache_->load(); }
  161. void SetFlags(const uint64_t flags) { flags_ = flags; }
  162. uint64_t GetFlags() const { return flags_; }
  163. };
  164. /*
  165. * Class Description:
  166. * Class will handle access to data through internal copies.
  167. * These are obtained via work submission to the Intel DSA which takes
  168. * care of asynchronously duplicating the data. The user will define
  169. * where these copies lie and which system nodes will perform the copy.
  170. * This is done through policy functions set during initialization.
  171. *
  172. * Placement Policy:
  173. * The Placement Policy Function decides on which node a particular
  174. * entry is to be placed, given the current executing node and the
  175. * data source node and data size. This in turn means that for one
  176. * datum, multiple cached copies may exist at one time.
  177. *
  178. * Cache Lifetime:
  179. * When accessing the cache, a CacheData-object will be returned.
  180. * As long as this object lives, the pointer which it holds is
  181. * guaranteed to be either nullptr or a valid copy. When destroyed
  182. * the entry is marked for deletion which is only carried out
  183. * when system memory pressure drives an automated cache flush.
  184. *
  185. * Restrictions:
  186. * - Overlapping Pointers may lead to undefined behaviour during
  187. * manual cache invalidation which should not be used if you
  188. * intend to have these types of pointers
  189. * - Cache Invalidation may only be performed manually and gives
  190. * no ordering guarantees. Therefore, it is the users responsibility
  191. * to ensure that results after invalidation have been generated
  192. * using the latest state of data. The cache is best suited
  193. * to static data.
  194. *
  195. * Notes on Thread Safety:
  196. * - Cache is completely thread-safe after initialization
  197. * - CacheData-class will handle deallocation of data itself by
  198. * performing self-reference-counting atomically and only
  199. * deallocating if the last reference is destroyed
  200. * - The internal cache state has one lock which is either
  201. * acquired shared for reading the state (upon accessing an already
  202. * cached element) or unique (accessing a new element, flushing, invalidating)
  203. * - Waiting on copy completion is done over an atomic-wait in copies
  204. * of the original CacheData-instance
  205. * - Overall this class may experience performance issues due to the use
  206. * of locking (in any configuration), lock contention (worsens with higher
  207. * core count, node count and utilization) and atomics (worse in the same
  208. * situations as lock contention)
  209. *
  210. * Improving Performance:
  211. * When data is never shared between threads or memory size for the cache is
  212. * not an issue you may consider having one Cache-instance per thread and removing
  213. * the lock in Cache and modifying the reference counting and waiting mechanisms
  214. * of CacheData accordingly (although this is high effort and will yield little due
  215. * to the atomics not being shared among cores/nodes).
  216. * Otherwise, one Cache-instance per node could also be considered. This will allow
  217. * the placement policy function to be barebones and reduces the lock contention and
  218. * synchronization impact of the atomic variables.
  219. */
  220. class Cache {
  221. private:
  222. // flags to store options duh
  223. uint64_t flags_ = 0;
  224. // secondary invalid handlers vector
  225. // needed due to wake-up issues in CacheData::WaitOnCompletion
  226. std::vector<CacheData::dml_handler> invalid_handlers_;
  227. // map from [dst-numa-node,map2]
  228. // map2 from [data-ptr,cache-structure]
  229. struct LockedNodeCacheState {
  230. std::shared_mutex cache_mutex_;
  231. std::unordered_map<uint8_t*, CacheData> node_cache_state_;
  232. };
  233. std::unordered_map<uint8_t, LockedNodeCacheState*> cache_state_;
  234. CachePolicy* cache_policy_function_ = nullptr;
  235. CopyPolicy* copy_policy_function_ = nullptr;
  236. MemoryAllocator_Allocate* memory_allocate_function_ = nullptr;
  237. MemoryAllocator_Free* memory_free_function_ = nullptr;
  238. // function used to submit a copy task on a specific node to the dml
  239. // engine on that node - will change the current threads node assignment
  240. // to achieve this so take care to restore this
  241. dml::handler<dml::mem_copy_operation, std::allocator<uint8_t>> ExecuteCopy(
  242. const uint8_t* src, uint8_t* dst, const size_t size, const int node
  243. ) const;
  244. // allocates the required memory on the destination node
  245. // and then submits task to the dml library for processing
  246. // and attaches the handlers to the cache data structure
  247. void SubmitTask(CacheData* task, const int dst_node, const int src_node);
  248. // querries the policy functions for the given data and size
  249. // to obtain destination cache node, also returns the datas
  250. // source node for further usage
  251. // output may depend on the calling threads node assignment
  252. // as this is set as the "optimal placement" node
  253. // TODO: it would be better to not handle any decisions regarding nodes in the cache
  254. // TODO: and leave this entirely to the user, however, this idea came to me 3 days before
  255. // TODO: submission date and there are more important things to do
  256. void GetCacheNode(uint8_t* src, const size_t size, int* OUT_DST_NODE, int* OUT_SRC_NODE) const;
  257. // checks whether the cache contains an entry for
  258. // the given data in the given memory node and
  259. // returns it, otherwise returns nullptr
  260. std::unique_ptr<CacheData> GetFromCache(uint8_t* src, const size_t size, const int dst_node);
  261. public:
  262. ~Cache();
  263. Cache() = default;
  264. Cache(const Cache& other) = delete;
  265. // initializes the cache with the two policy functions
  266. // only after this is it safe to use in a threaded environment
  267. void Init(
  268. CachePolicy* cache_policy_function, CopyPolicy* copy_policy_function,
  269. MemoryAllocator_Allocate* memory_allocate_function,
  270. MemoryAllocator_Free* memory_free_function
  271. );
  272. // function to perform data access through the cache, behaviour depends
  273. // on flags, by default will also perform prefetch, otherwise with
  274. // FLAG_ACCESS_WEAK set will not perform prefetch and instead return
  275. // a cache entry with the data source as cache location on cache miss,
  276. // this flag must be set for each invocation, the flags set for the
  277. // entire cache will not be evaluated for this
  278. std::unique_ptr<CacheData> Access(uint8_t* data, const size_t size, const uint64_t flags = FLAG_DEFAULT);
  279. // flushes the cache of inactive entries
  280. // if node is -1 then the whole cache is
  281. // checked and otherwise the specified
  282. // node - no checks on node validity
  283. void Flush(const int node = -1);
  284. // forces out all entries from the
  285. // cache and therefore will also "forget"
  286. // still-in-use entries, these will still
  287. // be properly deleted, but the cache
  288. // will be fresh - use for testing
  289. void Clear();
  290. void Invalidate(uint8_t* data);
  291. void SetFlags(const uint64_t flags) { flags_ = flags; }
  292. uint64_t GetFlags() { return flags_; }
  293. };
  294. }
  295. inline void dsacache::Cache::Clear() {
  296. for (auto& nc : cache_state_) {
  297. std::unique_lock<std::shared_mutex> lock(nc.second->cache_mutex_);
  298. nc.second->node_cache_state_.clear();
  299. }
  300. }
  301. inline void dsacache::Cache::Init(
  302. CachePolicy* cache_policy_function, CopyPolicy* copy_policy_function,
  303. MemoryAllocator_Allocate* memory_allocate_function,
  304. MemoryAllocator_Free* memory_free_function
  305. ) {
  306. cache_policy_function_ = cache_policy_function;
  307. copy_policy_function_ = copy_policy_function;
  308. memory_allocate_function_ = memory_allocate_function;
  309. memory_free_function_ = memory_free_function;
  310. // initialize numa library
  311. numa_available();
  312. // obtain all available nodes
  313. // and those we may allocate
  314. // memory on
  315. const int nodes_max = numa_num_configured_nodes();
  316. const bitmask* valid_nodes = numa_get_mems_allowed();
  317. // prepare the cache state with entries
  318. // for all given nodes
  319. for (int node = 0; node < nodes_max; node++) {
  320. if (numa_bitmask_isbitset(valid_nodes, node)) {
  321. void* block = numa_alloc_onnode(sizeof(LockedNodeCacheState), node);
  322. auto* state = new(block)LockedNodeCacheState;
  323. cache_state_.insert({node,state});
  324. }
  325. }
  326. }
  327. inline std::unique_ptr<dsacache::CacheData> dsacache::Cache::Access(uint8_t* data, const size_t size, const uint64_t flags) {
  328. // get destination numa node for the cache
  329. int dst_node = -1;
  330. int src_node = -1;
  331. GetCacheNode(data, size, &dst_node, &src_node);
  332. // check whether the data is already cached
  333. std::unique_ptr<CacheData> task = GetFromCache(data, size, dst_node);
  334. if (task != nullptr) {
  335. return std::move(task);
  336. }
  337. // at this point the requested data is not present in cache
  338. // and we create a caching task for it, copying our current flags
  339. task = std::make_unique<CacheData>(data, size, memory_free_function_);
  340. task->SetFlags(flags_);
  341. // when the ACCESS_WEAK flag is set for the flags parameter (!)
  342. // and we have reached this point, there was no cache entry
  343. // present for the requested data and therefore we abort
  344. // but to keep validity, we return the previously created
  345. // CacheData struct, setting the cache variable to the
  346. // data source location
  347. if (CheckFlag(flags, FLAG_ACCESS_WEAK)) {
  348. task->SetInvalidHandlersAndCacheToSource();
  349. return std::move(task);
  350. }
  351. // the following operation adds the task to the cache state
  352. // which requires unique locking of the current nodes entry
  353. {
  354. LockedNodeCacheState* local_cache_state = cache_state_[dst_node];
  355. std::unique_lock<std::shared_mutex> lock(local_cache_state->cache_mutex_);
  356. const auto state = local_cache_state->node_cache_state_.emplace(task->GetSource(), *task);
  357. // if state.second is false then no insertion took place
  358. // which means that concurrently whith this thread
  359. // some other thread must have accessed the same
  360. // resource in which case we return the other
  361. // threads data cache structure
  362. if (!state.second) {
  363. return std::move(std::make_unique<CacheData>(state.first->second));
  364. }
  365. // initialize the task now for thread safety
  366. // as we are now sure that we will submit work
  367. // to it and will not delete it beforehand
  368. // of the one in cache state - must be
  369. // performed for the local and cache-state
  370. // instance as Init will modify values that
  371. // are not shared but copied on copy-construct
  372. state.first->second.Init(&invalid_handlers_);
  373. task->Init(&invalid_handlers_);
  374. }
  375. SubmitTask(task.get(), dst_node, src_node);
  376. return std::move(task);
  377. }
  378. inline void dsacache::Cache::SubmitTask(CacheData* task, const int dst_node, const int src_node) {
  379. uint8_t* dst = memory_allocate_function_(dst_node, task->GetSize());
  380. if (dst == nullptr) {
  381. // allocation failure encountered, therefore submission is aborted
  382. // which necessitates making the CacheData instance safe for usage
  383. task->SetInvalidHandlersAndCacheToSource();
  384. return;
  385. }
  386. // querry copy policy function for the nodes to use for the copy
  387. const std::vector<int> executing_nodes = copy_policy_function_(dst_node, src_node, task->GetSize());
  388. const size_t task_count = executing_nodes.size();
  389. // each task will copy one fair part of the total size
  390. // and in case the total size is not a factor of the
  391. // given task count the last node must copy the remainder
  392. const size_t size = task->GetSize() / task_count;
  393. const size_t last_size = size + task->GetSize() % task_count;
  394. // save the current numa node mask to restore later
  395. // as executing the copy task will place this thread
  396. // on a different node
  397. auto handlers = new std::vector<CacheData::dml_handler>();
  398. for (uint32_t i = 0; i < task_count; i++) {
  399. const size_t local_size = i + 1 == task_count ? size : last_size;
  400. const size_t local_offset = i * size;
  401. const uint8_t* local_src = task->GetSource() + local_offset;
  402. uint8_t* local_dst = dst + local_offset;
  403. handlers->emplace_back(ExecuteCopy(local_src, local_dst, local_size, executing_nodes[i]));
  404. }
  405. task->SetTaskHandlersAndCache(dst, handlers);
  406. }
  407. inline dml::handler<dml::mem_copy_operation, std::allocator<uint8_t>> dsacache::Cache::ExecuteCopy(
  408. const uint8_t* src, uint8_t* dst, const size_t size, const int node
  409. ) const {
  410. dml::const_data_view srcv = dml::make_view(src, size);
  411. dml::data_view dstv = dml::make_view(dst, size);
  412. if (CheckFlag(flags_, FLAG_HANDLE_PF)) {
  413. return dml::submit<dml::hardware>(
  414. dml::mem_copy.block_on_fault(), srcv, dstv,
  415. dml::execution_interface<dml::hardware,std::allocator<uint8_t>>(), node
  416. );
  417. }
  418. else {
  419. return dml::submit<dml::hardware>(
  420. dml::mem_copy, srcv, dstv,
  421. dml::execution_interface<dml::hardware,std::allocator<uint8_t>>(), node
  422. );
  423. }
  424. }
  425. inline void dsacache::Cache::GetCacheNode(uint8_t* src, const size_t size, int* OUT_DST_NODE, int* OUT_SRC_NODE) const {
  426. // obtain numa node of current thread to determine where the data is needed
  427. const int current_cpu = sched_getcpu();
  428. const int current_node = numa_node_of_cpu(current_cpu);
  429. // obtain node that the given data pointer is allocated on
  430. *OUT_SRC_NODE = -1;
  431. get_mempolicy(OUT_SRC_NODE, NULL, 0, (void*)src, MPOL_F_NODE | MPOL_F_ADDR);
  432. // querry cache policy function for the destination numa node
  433. *OUT_DST_NODE = cache_policy_function_(current_node, *OUT_SRC_NODE, size);
  434. }
  435. inline void dsacache::Cache::Flush(const int node) {
  436. // this lambda is used because below we have two code paths that
  437. // flush nodes, either one single or all successively
  438. const auto FlushNode = [](std::unordered_map<uint8_t*,CacheData>& map) {
  439. // begin at the front of the map
  440. auto it = map.begin();
  441. // loop until we reach the end of the map
  442. while (it != map.end()) {
  443. // if the iterator points to an inactive element
  444. // then we may erase it
  445. if (it->second.GetRefCount() <= 1) {
  446. // erase the iterator from the map
  447. map.erase(it);
  448. // as the erasure invalidated out iterator
  449. // we must start at the beginning again
  450. it = map.begin();
  451. }
  452. else {
  453. // if element is active just move over to the next one
  454. it++;
  455. }
  456. }
  457. };
  458. // we require exclusive lock as we modify the cache state
  459. // node == -1 means that cache on all nodes should be flushed
  460. if (node == -1) {
  461. for (auto& nc : cache_state_) {
  462. std::unique_lock<std::shared_mutex> lock(nc.second->cache_mutex_);
  463. FlushNode(nc.second->node_cache_state_);
  464. }
  465. }
  466. else {
  467. std::unique_lock<std::shared_mutex> lock(cache_state_[node]->cache_mutex_);
  468. FlushNode(cache_state_[node]->node_cache_state_);
  469. }
  470. }
  471. inline std::unique_ptr<dsacache::CacheData> dsacache::Cache::GetFromCache(uint8_t* src, const size_t size, const int dst_node) {
  472. // the best situation is if this data is already cached
  473. // which we check in an unnamed block in which the cache
  474. // is locked for reading to prevent another thread
  475. // from marking the element we may find as unused and
  476. // clearing it
  477. LockedNodeCacheState* local_cache_state = cache_state_[dst_node];
  478. // lock the cache state in shared-mode because we read
  479. std::shared_lock<std::shared_mutex> lock(local_cache_state->cache_mutex_);
  480. // search for the data in our cache state structure at the given node
  481. const auto search = local_cache_state->node_cache_state_.find(src);
  482. // if the data is in our structure we continue
  483. if (search != local_cache_state->node_cache_state_.end()) {
  484. // now check whether the sizes match
  485. if (search->second.GetSize() >= size) {
  486. // return a unique copy of the entry which uses the object
  487. // lifetime and destructor to safely handle deallocation
  488. return std::move(std::make_unique<CacheData>(search->second));
  489. }
  490. else {
  491. // if the sizes missmatch then we clear the current entry from cache
  492. // which will cause its deletion only after the last possible outside
  493. // reference is also destroyed
  494. local_cache_state->node_cache_state_.erase(search);
  495. }
  496. }
  497. return nullptr;
  498. }
  499. void dsacache::Cache::Invalidate(uint8_t* data) {
  500. // as the cache is modified we must obtain a unique writers lock
  501. // loop through all per-node-caches available
  502. for (auto node : cache_state_) {
  503. std::unique_lock<std::shared_mutex> lock(node.second->cache_mutex_);
  504. // search for an entry for the given data pointer
  505. auto search = node.second->node_cache_state_.find(data);
  506. if (search != node.second->node_cache_state_.end()) {
  507. // if the data is represented in-cache
  508. // then it will be erased to re-trigger
  509. // caching on next access
  510. node.second->node_cache_state_.erase(search);
  511. }
  512. }
  513. }
  514. inline dsacache::Cache::~Cache() {
  515. for (auto node : cache_state_) {
  516. node.second->~LockedNodeCacheState();
  517. numa_free(reinterpret_cast<void*>(node.second), sizeof(LockedNodeCacheState));
  518. }
  519. }
  520. inline dsacache::CacheData::CacheData(uint8_t* data, const size_t size, MemoryAllocator_Free* free) {
  521. src_ = data;
  522. size_ = size;
  523. delete_ = false;
  524. memory_free_function_ = free;
  525. active_ = new std::atomic<int32_t>(1);
  526. cache_ = new std::atomic<uint8_t*>(data);
  527. handlers_ = new std::atomic<std::vector<dml_handler>*>();
  528. incomplete_cache_ = new uint8_t*(nullptr);
  529. }
  530. inline dsacache::CacheData::CacheData(const dsacache::CacheData& other) {
  531. // we copy the ptr to the global atomic reference counter
  532. // and increase the amount of active references
  533. active_ = other.active_;
  534. const int current_active = active_->fetch_add(1);
  535. src_ = other.src_;
  536. size_ = other.size_;
  537. cache_ = other.cache_;
  538. flags_ = other.flags_;
  539. memory_free_function_ = other.memory_free_function_;
  540. incomplete_cache_ = other.incomplete_cache_;
  541. handlers_ = other.handlers_;
  542. invalid_handlers_ = other.invalid_handlers_;
  543. }
  544. inline dsacache::CacheData::~CacheData() {
  545. // due to fetch_sub returning the preivously held value
  546. // we must subtract one locally to get the current value
  547. const int32_t v = active_->fetch_sub(1) - 1;
  548. // if the returned value is zero or lower
  549. // then we must execute proper deletion
  550. // as this was the last reference
  551. if (v == 0) {
  552. // on deletion we must ensure that all offloaded
  553. // operations have completed successfully
  554. // for this we must unset the possibly active
  555. // flag for weak waiting as we wish completion
  556. // guarantees afterwards
  557. flags_ = UnsetFlag(flags_, FLAG_WAIT_WEAK);
  558. WaitOnCompletion();
  559. // only then can we deallocate the memory
  560. Deallocate();
  561. delete active_;
  562. delete cache_;
  563. delete handlers_;
  564. delete incomplete_cache_;
  565. }
  566. }
  567. inline void dsacache::CacheData::Deallocate() {
  568. // although deallocate should only be called from
  569. // a safe context to do so, it can not hurt to
  570. // defensively perform the operation atomically
  571. // and check for incomplete cache if no deallocation
  572. // takes place for the retrieved local cache
  573. uint8_t* cache_local = cache_->exchange(nullptr);
  574. if (cache_local != nullptr && delete_) memory_free_function_(cache_local, size_);
  575. else if (*incomplete_cache_ != nullptr) memory_free_function_(*incomplete_cache_, size_);
  576. else;
  577. }
  578. inline void dsacache::CacheData::WaitOnCompletion() {
  579. // first check if waiting is even neccessary as a valid
  580. // cache pointer signals that no waiting is to be performed
  581. if (cache_->load() != nullptr) {
  582. return;
  583. }
  584. // then check if the handlers are available
  585. handlers_->wait(nullptr);
  586. // exchange the global handlers pointer with nullptr to have a local
  587. // copy - this signals that this thread is the sole owner and therefore
  588. // responsible for waiting for them. we can not set to nullptr here but
  589. // set to secondary invalid value in order to prevent deadlocks from
  590. // the above waiting construct, where threads may miss the short period
  591. // in which the handlers are not nullptr. we could use double width cas
  592. // which however is more expensive and therefore introduce the second
  593. // invalid state to solve the aba occurring here
  594. // see https://en.wikipedia.org/wiki/ABA_problem for more info
  595. std::vector<dml_handler>* local_handlers = handlers_->exchange(invalid_handlers_);
  596. // ensure that no other thread snatched the handlers before us
  597. // and in case one did, wait again and then return
  598. if (local_handlers == invalid_handlers_) {
  599. cache_->wait(nullptr);
  600. return;
  601. }
  602. // at this point we are responsible for waiting for the handlers
  603. // and handling any error that comes through them gracefully
  604. bool error = false;
  605. for (auto& handler : *local_handlers) {
  606. if (CheckFlag(flags_, FLAG_WAIT_WEAK) && !handler.is_finished()) {
  607. handlers_->store(local_handlers);
  608. return;
  609. }
  610. auto result = handler.get();
  611. if (result.status != dml::status_code::ok) {
  612. std::cerr << "[x] ERROR (" << dml::StatusCodeToString(result.status) << ") FOUND FOR TASK IN WAIT!" << std::endl;
  613. error = true;
  614. }
  615. }
  616. // at this point all handlers have been waited for
  617. // and therefore may be decomissioned
  618. delete local_handlers;
  619. // handle errors now by aborting the cache
  620. if (error) {
  621. cache_->store(src_);
  622. memory_free_function_(*incomplete_cache_, size_);
  623. delete_ = false;
  624. *incomplete_cache_ = nullptr;
  625. }
  626. else {
  627. cache_->store(*incomplete_cache_);
  628. }
  629. // notify all waiting threads so they wake up quickly
  630. cache_->notify_all();
  631. handlers_->notify_all();
  632. }
  633. void dsacache::CacheData::SetTaskHandlersAndCache(uint8_t* cache, std::vector<dml_handler>* handlers) {
  634. *incomplete_cache_ = cache;
  635. handlers_->store(handlers);
  636. handlers_->notify_one();
  637. }
  638. void dsacache::CacheData::SetInvalidHandlersAndCacheToSource() {
  639. cache_->store(src_);
  640. delete_ = false;
  641. handlers_->store(invalid_handlers_);
  642. handlers_->notify_all();
  643. }
  644. void dsacache::CacheData::Init(std::vector<dml_handler>* invalid_handlers) {
  645. cache_->store(nullptr);
  646. delete_ = true;
  647. invalid_handlers_ = invalid_handlers;
  648. }