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.

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