rid_owner.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. /**************************************************************************/
  2. /* rid_owner.h */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #pragma once
  31. #include "core/os/memory.h"
  32. #include "core/os/mutex.h"
  33. #include "core/string/print_string.h"
  34. #include "core/templates/local_vector.h"
  35. #include "core/templates/rid.h"
  36. #include "core/templates/safe_refcount.h"
  37. #include <cstdio>
  38. #include <typeinfo> // IWYU pragma: keep // Used in macro.
  39. #ifdef SANITIZERS_ENABLED
  40. #ifdef __has_feature
  41. #if __has_feature(thread_sanitizer)
  42. #define TSAN_ENABLED
  43. #endif
  44. #elif defined(__SANITIZE_THREAD__)
  45. #define TSAN_ENABLED
  46. #endif
  47. #endif
  48. #ifdef TSAN_ENABLED
  49. #include <sanitizer/tsan_interface.h>
  50. #endif
  51. // The following macros would need to be implemented somehow
  52. // for purely weakly ordered architectures. There's a test case
  53. // ("[RID_Owner] Thread safety") with potential to catch issues
  54. // on such architectures if these primitives fail to be implemented.
  55. // For now, they will be just markers about needs that may arise.
  56. #define WEAK_MEMORY_ORDER 0
  57. #if WEAK_MEMORY_ORDER
  58. // Ideally, we'd have implementations that collaborate with the
  59. // sync mechanism used (e.g., the mutex) so instead of some full
  60. // memory barriers being issued, some acquire-release on the
  61. // primitive itself. However, these implementations will at least
  62. // provide correctness.
  63. #define SYNC_ACQUIRE std::atomic_thread_fence(std::memory_order_acquire);
  64. #define SYNC_RELEASE std::atomic_thread_fence(std::memory_order_release);
  65. #else
  66. // Compiler barriers are enough in this case.
  67. #define SYNC_ACQUIRE std::atomic_signal_fence(std::memory_order_acquire);
  68. #define SYNC_RELEASE std::atomic_signal_fence(std::memory_order_release);
  69. #endif
  70. class RID_AllocBase {
  71. static SafeNumeric<uint64_t> base_id;
  72. protected:
  73. static RID _make_from_id(uint64_t p_id) {
  74. RID rid;
  75. rid._id = p_id;
  76. return rid;
  77. }
  78. static RID _gen_rid() {
  79. return _make_from_id(_gen_id());
  80. }
  81. friend struct VariantUtilityFunctions;
  82. static uint64_t _gen_id() {
  83. return base_id.increment();
  84. }
  85. public:
  86. virtual ~RID_AllocBase() {}
  87. };
  88. template <typename T, bool THREAD_SAFE = false>
  89. class RID_Alloc : public RID_AllocBase {
  90. struct Chunk {
  91. T data;
  92. uint32_t validator;
  93. };
  94. Chunk **chunks = nullptr;
  95. uint32_t **free_list_chunks = nullptr;
  96. uint32_t elements_in_chunk;
  97. uint32_t max_alloc = 0;
  98. uint32_t alloc_count = 0;
  99. uint32_t chunk_limit = 0;
  100. const char *description = nullptr;
  101. mutable Mutex mutex;
  102. _FORCE_INLINE_ RID _allocate_rid() {
  103. if constexpr (THREAD_SAFE) {
  104. mutex.lock();
  105. }
  106. if (alloc_count == max_alloc) {
  107. //allocate a new chunk
  108. uint32_t chunk_count = alloc_count == 0 ? 0 : (max_alloc / elements_in_chunk);
  109. if (THREAD_SAFE && chunk_count == chunk_limit) {
  110. mutex.unlock();
  111. if (description != nullptr) {
  112. ERR_FAIL_V_MSG(RID(), vformat("Element limit for RID of type '%s' reached.", String(description)));
  113. } else {
  114. ERR_FAIL_V_MSG(RID(), "Element limit reached.");
  115. }
  116. }
  117. //grow chunks
  118. if constexpr (!THREAD_SAFE) {
  119. chunks = (Chunk **)memrealloc(chunks, sizeof(Chunk *) * (chunk_count + 1));
  120. }
  121. chunks[chunk_count] = (Chunk *)memalloc(sizeof(Chunk) * elements_in_chunk); //but don't initialize
  122. //grow free lists
  123. if constexpr (!THREAD_SAFE) {
  124. free_list_chunks = (uint32_t **)memrealloc(free_list_chunks, sizeof(uint32_t *) * (chunk_count + 1));
  125. }
  126. free_list_chunks[chunk_count] = (uint32_t *)memalloc(sizeof(uint32_t) * elements_in_chunk);
  127. //initialize
  128. for (uint32_t i = 0; i < elements_in_chunk; i++) {
  129. // Don't initialize chunk.
  130. chunks[chunk_count][i].validator = 0xFFFFFFFF;
  131. free_list_chunks[chunk_count][i] = alloc_count + i;
  132. }
  133. if constexpr (THREAD_SAFE) {
  134. // Store atomically to avoid data race with the load in get_or_null().
  135. ((std::atomic<uint32_t> *)&max_alloc)->store(max_alloc + elements_in_chunk, std::memory_order_relaxed);
  136. } else {
  137. max_alloc += elements_in_chunk;
  138. }
  139. }
  140. uint32_t free_index = free_list_chunks[alloc_count / elements_in_chunk][alloc_count % elements_in_chunk];
  141. uint32_t free_chunk = free_index / elements_in_chunk;
  142. uint32_t free_element = free_index % elements_in_chunk;
  143. uint32_t validator = 1 + (uint32_t)(_gen_id() % 0x7FFFFFFF);
  144. uint64_t id = validator;
  145. id <<= 32;
  146. id |= free_index;
  147. chunks[free_chunk][free_element].validator = validator;
  148. chunks[free_chunk][free_element].validator |= 0x80000000; //mark uninitialized bit
  149. alloc_count++;
  150. if constexpr (THREAD_SAFE) {
  151. mutex.unlock();
  152. }
  153. return _make_from_id(id);
  154. }
  155. public:
  156. RID make_rid() {
  157. RID rid = _allocate_rid();
  158. initialize_rid(rid);
  159. return rid;
  160. }
  161. RID make_rid(const T &p_value) {
  162. RID rid = _allocate_rid();
  163. initialize_rid(rid, p_value);
  164. return rid;
  165. }
  166. //allocate but don't initialize, use initialize_rid afterwards
  167. RID allocate_rid() {
  168. return _allocate_rid();
  169. }
  170. _FORCE_INLINE_ T *get_or_null(const RID &p_rid, bool p_initialize = false) {
  171. if (p_rid == RID()) {
  172. return nullptr;
  173. }
  174. if constexpr (THREAD_SAFE) {
  175. SYNC_ACQUIRE;
  176. }
  177. uint64_t id = p_rid.get_id();
  178. uint32_t idx = uint32_t(id & 0xFFFFFFFF);
  179. uint32_t ma;
  180. if constexpr (THREAD_SAFE) { // Read atomically to avoid data race with the store in _allocate_rid().
  181. ma = ((std::atomic<uint32_t> *)&max_alloc)->load(std::memory_order_relaxed);
  182. } else {
  183. ma = max_alloc;
  184. }
  185. if (unlikely(idx >= ma)) {
  186. return nullptr;
  187. }
  188. uint32_t idx_chunk = idx / elements_in_chunk;
  189. uint32_t idx_element = idx % elements_in_chunk;
  190. uint32_t validator = uint32_t(id >> 32);
  191. if constexpr (THREAD_SAFE) {
  192. #ifdef TSAN_ENABLED
  193. __tsan_acquire(&chunks[idx_chunk]); // We know not a race in practice.
  194. __tsan_acquire(&chunks[idx_chunk][idx_element]); // We know not a race in practice.
  195. #endif
  196. }
  197. Chunk &c = chunks[idx_chunk][idx_element];
  198. if constexpr (THREAD_SAFE) {
  199. #ifdef TSAN_ENABLED
  200. __tsan_release(&chunks[idx_chunk]);
  201. __tsan_release(&chunks[idx_chunk][idx_element]);
  202. __tsan_acquire(&c.validator); // We know not a race in practice.
  203. #endif
  204. }
  205. if (unlikely(p_initialize)) {
  206. if (unlikely(!(c.validator & 0x80000000))) {
  207. ERR_FAIL_V_MSG(nullptr, "Initializing already initialized RID");
  208. }
  209. if (unlikely((c.validator & 0x7FFFFFFF) != validator)) {
  210. ERR_FAIL_V_MSG(nullptr, "Attempting to initialize the wrong RID");
  211. }
  212. c.validator &= 0x7FFFFFFF; //initialized
  213. } else if (unlikely(c.validator != validator)) {
  214. if ((c.validator & 0x80000000) && c.validator != 0xFFFFFFFF) {
  215. ERR_FAIL_V_MSG(nullptr, "Attempting to use an uninitialized RID");
  216. }
  217. return nullptr;
  218. }
  219. if constexpr (THREAD_SAFE) {
  220. #ifdef TSAN_ENABLED
  221. __tsan_release(&c.validator);
  222. #endif
  223. }
  224. T *ptr = &c.data;
  225. return ptr;
  226. }
  227. void initialize_rid(RID p_rid) {
  228. T *mem = get_or_null(p_rid, true);
  229. ERR_FAIL_NULL(mem);
  230. if constexpr (THREAD_SAFE) {
  231. #ifdef TSAN_ENABLED
  232. __tsan_acquire(mem); // We know not a race in practice.
  233. #endif
  234. }
  235. memnew_placement(mem, T);
  236. if constexpr (THREAD_SAFE) {
  237. #ifdef TSAN_ENABLED
  238. __tsan_release(mem);
  239. #endif
  240. SYNC_RELEASE;
  241. }
  242. }
  243. void initialize_rid(RID p_rid, const T &p_value) {
  244. T *mem = get_or_null(p_rid, true);
  245. ERR_FAIL_NULL(mem);
  246. if constexpr (THREAD_SAFE) {
  247. #ifdef TSAN_ENABLED
  248. __tsan_acquire(mem); // We know not a race in practice.
  249. #endif
  250. }
  251. memnew_placement(mem, T(p_value));
  252. if constexpr (THREAD_SAFE) {
  253. #ifdef TSAN_ENABLED
  254. __tsan_release(mem);
  255. #endif
  256. SYNC_RELEASE;
  257. }
  258. }
  259. _FORCE_INLINE_ bool owns(const RID &p_rid) const {
  260. if constexpr (THREAD_SAFE) {
  261. mutex.lock();
  262. }
  263. uint64_t id = p_rid.get_id();
  264. uint32_t idx = uint32_t(id & 0xFFFFFFFF);
  265. if (unlikely(idx >= max_alloc)) {
  266. if constexpr (THREAD_SAFE) {
  267. mutex.unlock();
  268. }
  269. return false;
  270. }
  271. uint32_t idx_chunk = idx / elements_in_chunk;
  272. uint32_t idx_element = idx % elements_in_chunk;
  273. uint32_t validator = uint32_t(id >> 32);
  274. bool owned = (chunks[idx_chunk][idx_element].validator & 0x7FFFFFFF) == validator;
  275. if constexpr (THREAD_SAFE) {
  276. mutex.unlock();
  277. }
  278. return owned;
  279. }
  280. _FORCE_INLINE_ void free(const RID &p_rid) {
  281. if constexpr (THREAD_SAFE) {
  282. mutex.lock();
  283. }
  284. uint64_t id = p_rid.get_id();
  285. uint32_t idx = uint32_t(id & 0xFFFFFFFF);
  286. if (unlikely(idx >= max_alloc)) {
  287. if constexpr (THREAD_SAFE) {
  288. mutex.unlock();
  289. }
  290. ERR_FAIL();
  291. }
  292. uint32_t idx_chunk = idx / elements_in_chunk;
  293. uint32_t idx_element = idx % elements_in_chunk;
  294. uint32_t validator = uint32_t(id >> 32);
  295. if (unlikely(chunks[idx_chunk][idx_element].validator & 0x80000000)) {
  296. if constexpr (THREAD_SAFE) {
  297. mutex.unlock();
  298. }
  299. ERR_FAIL_MSG("Attempted to free an uninitialized or invalid RID");
  300. } else if (unlikely(chunks[idx_chunk][idx_element].validator != validator)) {
  301. if constexpr (THREAD_SAFE) {
  302. mutex.unlock();
  303. }
  304. ERR_FAIL();
  305. }
  306. chunks[idx_chunk][idx_element].data.~T();
  307. chunks[idx_chunk][idx_element].validator = 0xFFFFFFFF; // go invalid
  308. alloc_count--;
  309. free_list_chunks[alloc_count / elements_in_chunk][alloc_count % elements_in_chunk] = idx;
  310. if constexpr (THREAD_SAFE) {
  311. mutex.unlock();
  312. }
  313. }
  314. _FORCE_INLINE_ uint32_t get_rid_count() const {
  315. return alloc_count;
  316. }
  317. LocalVector<RID> get_owned_list() const {
  318. LocalVector<RID> owned;
  319. if constexpr (THREAD_SAFE) {
  320. mutex.lock();
  321. }
  322. for (size_t i = 0; i < max_alloc; i++) {
  323. uint64_t validator = chunks[i / elements_in_chunk][i % elements_in_chunk].validator;
  324. if (validator != 0xFFFFFFFF) {
  325. owned.push_back(_make_from_id((validator << 32) | i));
  326. }
  327. }
  328. if constexpr (THREAD_SAFE) {
  329. mutex.unlock();
  330. }
  331. return owned;
  332. }
  333. //used for fast iteration in the elements or RIDs
  334. void fill_owned_buffer(RID *p_rid_buffer) const {
  335. if constexpr (THREAD_SAFE) {
  336. mutex.lock();
  337. }
  338. uint32_t idx = 0;
  339. for (size_t i = 0; i < max_alloc; i++) {
  340. uint64_t validator = chunks[i / elements_in_chunk][i % elements_in_chunk].validator;
  341. if (validator != 0xFFFFFFFF) {
  342. p_rid_buffer[idx] = _make_from_id((validator << 32) | i);
  343. idx++;
  344. }
  345. }
  346. if constexpr (THREAD_SAFE) {
  347. mutex.unlock();
  348. }
  349. }
  350. void set_description(const char *p_description) {
  351. description = p_description;
  352. }
  353. RID_Alloc(uint32_t p_target_chunk_byte_size = 65536, uint32_t p_maximum_number_of_elements = 262144) {
  354. elements_in_chunk = sizeof(T) > p_target_chunk_byte_size ? 1 : (p_target_chunk_byte_size / sizeof(T));
  355. if constexpr (THREAD_SAFE) {
  356. chunk_limit = (p_maximum_number_of_elements / elements_in_chunk) + 1;
  357. chunks = (Chunk **)memalloc(sizeof(Chunk *) * chunk_limit);
  358. free_list_chunks = (uint32_t **)memalloc(sizeof(uint32_t *) * chunk_limit);
  359. SYNC_RELEASE;
  360. }
  361. }
  362. ~RID_Alloc() {
  363. if constexpr (THREAD_SAFE) {
  364. SYNC_ACQUIRE;
  365. }
  366. if (alloc_count) {
  367. print_error(vformat("ERROR: %d RID allocations of type '%s' were leaked at exit.",
  368. alloc_count, description ? description : typeid(T).name()));
  369. for (size_t i = 0; i < max_alloc; i++) {
  370. uint32_t validator = chunks[i / elements_in_chunk][i % elements_in_chunk].validator;
  371. if (validator & 0x80000000) {
  372. continue; //uninitialized
  373. }
  374. if (validator != 0xFFFFFFFF) {
  375. chunks[i / elements_in_chunk][i % elements_in_chunk].data.~T();
  376. }
  377. }
  378. }
  379. uint32_t chunk_count = max_alloc / elements_in_chunk;
  380. for (uint32_t i = 0; i < chunk_count; i++) {
  381. memfree(chunks[i]);
  382. memfree(free_list_chunks[i]);
  383. }
  384. if (chunks) {
  385. memfree(chunks);
  386. memfree(free_list_chunks);
  387. }
  388. }
  389. };
  390. template <typename T, bool THREAD_SAFE = false>
  391. class RID_PtrOwner {
  392. RID_Alloc<T *, THREAD_SAFE> alloc;
  393. public:
  394. _FORCE_INLINE_ RID make_rid(T *p_ptr) {
  395. return alloc.make_rid(p_ptr);
  396. }
  397. _FORCE_INLINE_ RID allocate_rid() {
  398. return alloc.allocate_rid();
  399. }
  400. _FORCE_INLINE_ void initialize_rid(RID p_rid, T *p_ptr) {
  401. alloc.initialize_rid(p_rid, p_ptr);
  402. }
  403. _FORCE_INLINE_ T *get_or_null(const RID &p_rid) {
  404. T **ptr = alloc.get_or_null(p_rid);
  405. if (unlikely(!ptr)) {
  406. return nullptr;
  407. }
  408. return *ptr;
  409. }
  410. _FORCE_INLINE_ void replace(const RID &p_rid, T *p_new_ptr) {
  411. T **ptr = alloc.get_or_null(p_rid);
  412. ERR_FAIL_NULL(ptr);
  413. *ptr = p_new_ptr;
  414. }
  415. _FORCE_INLINE_ bool owns(const RID &p_rid) const {
  416. return alloc.owns(p_rid);
  417. }
  418. _FORCE_INLINE_ void free(const RID &p_rid) {
  419. alloc.free(p_rid);
  420. }
  421. _FORCE_INLINE_ uint32_t get_rid_count() const {
  422. return alloc.get_rid_count();
  423. }
  424. _FORCE_INLINE_ LocalVector<RID> get_owned_list() const {
  425. return alloc.get_owned_list();
  426. }
  427. void fill_owned_buffer(RID *p_rid_buffer) const {
  428. alloc.fill_owned_buffer(p_rid_buffer);
  429. }
  430. void set_description(const char *p_description) {
  431. alloc.set_description(p_description);
  432. }
  433. RID_PtrOwner(uint32_t p_target_chunk_byte_size = 65536, uint32_t p_maximum_number_of_elements = 262144) :
  434. alloc(p_target_chunk_byte_size, p_maximum_number_of_elements) {}
  435. };
  436. template <typename T, bool THREAD_SAFE = false>
  437. class RID_Owner {
  438. RID_Alloc<T, THREAD_SAFE> alloc;
  439. public:
  440. _FORCE_INLINE_ RID make_rid() {
  441. return alloc.make_rid();
  442. }
  443. _FORCE_INLINE_ RID make_rid(const T &p_ptr) {
  444. return alloc.make_rid(p_ptr);
  445. }
  446. _FORCE_INLINE_ RID allocate_rid() {
  447. return alloc.allocate_rid();
  448. }
  449. _FORCE_INLINE_ void initialize_rid(RID p_rid) {
  450. alloc.initialize_rid(p_rid);
  451. }
  452. _FORCE_INLINE_ void initialize_rid(RID p_rid, const T &p_ptr) {
  453. alloc.initialize_rid(p_rid, p_ptr);
  454. }
  455. _FORCE_INLINE_ T *get_or_null(const RID &p_rid) {
  456. return alloc.get_or_null(p_rid);
  457. }
  458. _FORCE_INLINE_ bool owns(const RID &p_rid) const {
  459. return alloc.owns(p_rid);
  460. }
  461. _FORCE_INLINE_ void free(const RID &p_rid) {
  462. alloc.free(p_rid);
  463. }
  464. _FORCE_INLINE_ uint32_t get_rid_count() const {
  465. return alloc.get_rid_count();
  466. }
  467. _FORCE_INLINE_ LocalVector<RID> get_owned_list() const {
  468. return alloc.get_owned_list();
  469. }
  470. void fill_owned_buffer(RID *p_rid_buffer) const {
  471. alloc.fill_owned_buffer(p_rid_buffer);
  472. }
  473. void set_description(const char *p_description) {
  474. alloc.set_description(p_description);
  475. }
  476. RID_Owner(uint32_t p_target_chunk_byte_size = 65536, uint32_t p_maximum_number_of_elements = 262144) :
  477. alloc(p_target_chunk_byte_size, p_maximum_number_of_elements) {}
  478. };