rid_owner.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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/list.h"
  35. #include "core/templates/rid.h"
  36. #include "core/templates/safe_refcount.h"
  37. #include <stdio.h>
  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 = (uint32_t)(_gen_id() & 0x7FFFFFFF);
  144. CRASH_COND_MSG(validator == 0x7FFFFFFF, "Overflow in RID validator");
  145. uint64_t id = validator;
  146. id <<= 32;
  147. id |= free_index;
  148. chunks[free_chunk][free_element].validator = validator;
  149. chunks[free_chunk][free_element].validator |= 0x80000000; //mark uninitialized bit
  150. alloc_count++;
  151. if constexpr (THREAD_SAFE) {
  152. mutex.unlock();
  153. }
  154. return _make_from_id(id);
  155. }
  156. public:
  157. RID make_rid() {
  158. RID rid = _allocate_rid();
  159. initialize_rid(rid);
  160. return rid;
  161. }
  162. RID make_rid(const T &p_value) {
  163. RID rid = _allocate_rid();
  164. initialize_rid(rid, p_value);
  165. return rid;
  166. }
  167. //allocate but don't initialize, use initialize_rid afterwards
  168. RID allocate_rid() {
  169. return _allocate_rid();
  170. }
  171. _FORCE_INLINE_ T *get_or_null(const RID &p_rid, bool p_initialize = false) {
  172. if (p_rid == RID()) {
  173. return nullptr;
  174. }
  175. if constexpr (THREAD_SAFE) {
  176. SYNC_ACQUIRE;
  177. }
  178. uint64_t id = p_rid.get_id();
  179. uint32_t idx = uint32_t(id & 0xFFFFFFFF);
  180. uint32_t ma;
  181. if constexpr (THREAD_SAFE) { // Read atomically to avoid data race with the store in _allocate_rid().
  182. ma = ((std::atomic<uint32_t> *)&max_alloc)->load(std::memory_order_relaxed);
  183. } else {
  184. ma = max_alloc;
  185. }
  186. if (unlikely(idx >= ma)) {
  187. return nullptr;
  188. }
  189. uint32_t idx_chunk = idx / elements_in_chunk;
  190. uint32_t idx_element = idx % elements_in_chunk;
  191. uint32_t validator = uint32_t(id >> 32);
  192. if constexpr (THREAD_SAFE) {
  193. #ifdef TSAN_ENABLED
  194. __tsan_acquire(&chunks[idx_chunk]); // We know not a race in practice.
  195. __tsan_acquire(&chunks[idx_chunk][idx_element]); // We know not a race in practice.
  196. #endif
  197. }
  198. Chunk &c = chunks[idx_chunk][idx_element];
  199. if constexpr (THREAD_SAFE) {
  200. #ifdef TSAN_ENABLED
  201. __tsan_release(&chunks[idx_chunk]);
  202. __tsan_release(&chunks[idx_chunk][idx_element]);
  203. __tsan_acquire(&c.validator); // We know not a race in practice.
  204. #endif
  205. }
  206. if (unlikely(p_initialize)) {
  207. if (unlikely(!(c.validator & 0x80000000))) {
  208. ERR_FAIL_V_MSG(nullptr, "Initializing already initialized RID");
  209. }
  210. if (unlikely((c.validator & 0x7FFFFFFF) != validator)) {
  211. ERR_FAIL_V_MSG(nullptr, "Attempting to initialize the wrong RID");
  212. }
  213. c.validator &= 0x7FFFFFFF; //initialized
  214. } else if (unlikely(c.validator != validator)) {
  215. if ((c.validator & 0x80000000) && c.validator != 0xFFFFFFFF) {
  216. ERR_FAIL_V_MSG(nullptr, "Attempting to use an uninitialized RID");
  217. }
  218. return nullptr;
  219. }
  220. if constexpr (THREAD_SAFE) {
  221. #ifdef TSAN_ENABLED
  222. __tsan_release(&c.validator);
  223. #endif
  224. }
  225. T *ptr = &c.data;
  226. return ptr;
  227. }
  228. void initialize_rid(RID p_rid) {
  229. T *mem = get_or_null(p_rid, true);
  230. ERR_FAIL_NULL(mem);
  231. if constexpr (THREAD_SAFE) {
  232. #ifdef TSAN_ENABLED
  233. __tsan_acquire(mem); // We know not a race in practice.
  234. #endif
  235. }
  236. memnew_placement(mem, T);
  237. if constexpr (THREAD_SAFE) {
  238. #ifdef TSAN_ENABLED
  239. __tsan_release(mem);
  240. #endif
  241. SYNC_RELEASE;
  242. }
  243. }
  244. void initialize_rid(RID p_rid, const T &p_value) {
  245. T *mem = get_or_null(p_rid, true);
  246. ERR_FAIL_NULL(mem);
  247. if constexpr (THREAD_SAFE) {
  248. #ifdef TSAN_ENABLED
  249. __tsan_acquire(mem); // We know not a race in practice.
  250. #endif
  251. }
  252. memnew_placement(mem, T(p_value));
  253. if constexpr (THREAD_SAFE) {
  254. #ifdef TSAN_ENABLED
  255. __tsan_release(mem);
  256. #endif
  257. SYNC_RELEASE;
  258. }
  259. }
  260. _FORCE_INLINE_ bool owns(const RID &p_rid) const {
  261. if constexpr (THREAD_SAFE) {
  262. mutex.lock();
  263. }
  264. uint64_t id = p_rid.get_id();
  265. uint32_t idx = uint32_t(id & 0xFFFFFFFF);
  266. if (unlikely(idx >= max_alloc)) {
  267. if constexpr (THREAD_SAFE) {
  268. mutex.unlock();
  269. }
  270. return false;
  271. }
  272. uint32_t idx_chunk = idx / elements_in_chunk;
  273. uint32_t idx_element = idx % elements_in_chunk;
  274. uint32_t validator = uint32_t(id >> 32);
  275. bool owned = (validator != 0x7FFFFFFF) && (chunks[idx_chunk][idx_element].validator & 0x7FFFFFFF) == validator;
  276. if constexpr (THREAD_SAFE) {
  277. mutex.unlock();
  278. }
  279. return owned;
  280. }
  281. _FORCE_INLINE_ void free(const RID &p_rid) {
  282. if constexpr (THREAD_SAFE) {
  283. mutex.lock();
  284. }
  285. uint64_t id = p_rid.get_id();
  286. uint32_t idx = uint32_t(id & 0xFFFFFFFF);
  287. if (unlikely(idx >= max_alloc)) {
  288. if constexpr (THREAD_SAFE) {
  289. mutex.unlock();
  290. }
  291. ERR_FAIL();
  292. }
  293. uint32_t idx_chunk = idx / elements_in_chunk;
  294. uint32_t idx_element = idx % elements_in_chunk;
  295. uint32_t validator = uint32_t(id >> 32);
  296. if (unlikely(chunks[idx_chunk][idx_element].validator & 0x80000000)) {
  297. if constexpr (THREAD_SAFE) {
  298. mutex.unlock();
  299. }
  300. ERR_FAIL_MSG("Attempted to free an uninitialized or invalid RID");
  301. } else if (unlikely(chunks[idx_chunk][idx_element].validator != validator)) {
  302. if constexpr (THREAD_SAFE) {
  303. mutex.unlock();
  304. }
  305. ERR_FAIL();
  306. }
  307. chunks[idx_chunk][idx_element].data.~T();
  308. chunks[idx_chunk][idx_element].validator = 0xFFFFFFFF; // go invalid
  309. alloc_count--;
  310. free_list_chunks[alloc_count / elements_in_chunk][alloc_count % elements_in_chunk] = idx;
  311. if constexpr (THREAD_SAFE) {
  312. mutex.unlock();
  313. }
  314. }
  315. _FORCE_INLINE_ uint32_t get_rid_count() const {
  316. return alloc_count;
  317. }
  318. void get_owned_list(List<RID> *p_owned) const {
  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. p_owned->push_back(_make_from_id((validator << 32) | i));
  326. }
  327. }
  328. if constexpr (THREAD_SAFE) {
  329. mutex.unlock();
  330. }
  331. }
  332. //used for fast iteration in the elements or RIDs
  333. void fill_owned_buffer(RID *p_rid_buffer) const {
  334. if constexpr (THREAD_SAFE) {
  335. mutex.lock();
  336. }
  337. uint32_t idx = 0;
  338. for (size_t i = 0; i < max_alloc; i++) {
  339. uint64_t validator = chunks[i / elements_in_chunk][i % elements_in_chunk].validator;
  340. if (validator != 0xFFFFFFFF) {
  341. p_rid_buffer[idx] = _make_from_id((validator << 32) | i);
  342. idx++;
  343. }
  344. }
  345. if constexpr (THREAD_SAFE) {
  346. mutex.unlock();
  347. }
  348. }
  349. void set_description(const char *p_description) {
  350. description = p_description;
  351. }
  352. RID_Alloc(uint32_t p_target_chunk_byte_size = 65536, uint32_t p_maximum_number_of_elements = 262144) {
  353. elements_in_chunk = sizeof(T) > p_target_chunk_byte_size ? 1 : (p_target_chunk_byte_size / sizeof(T));
  354. if constexpr (THREAD_SAFE) {
  355. chunk_limit = (p_maximum_number_of_elements / elements_in_chunk) + 1;
  356. chunks = (Chunk **)memalloc(sizeof(Chunk *) * chunk_limit);
  357. free_list_chunks = (uint32_t **)memalloc(sizeof(uint32_t *) * chunk_limit);
  358. SYNC_RELEASE;
  359. }
  360. }
  361. ~RID_Alloc() {
  362. if constexpr (THREAD_SAFE) {
  363. SYNC_ACQUIRE;
  364. }
  365. if (alloc_count) {
  366. print_error(vformat("ERROR: %d RID allocations of type '%s' were leaked at exit.",
  367. alloc_count, description ? description : typeid(T).name()));
  368. for (size_t i = 0; i < max_alloc; i++) {
  369. uint32_t validator = chunks[i / elements_in_chunk][i % elements_in_chunk].validator;
  370. if (validator & 0x80000000) {
  371. continue; //uninitialized
  372. }
  373. if (validator != 0xFFFFFFFF) {
  374. chunks[i / elements_in_chunk][i % elements_in_chunk].data.~T();
  375. }
  376. }
  377. }
  378. uint32_t chunk_count = max_alloc / elements_in_chunk;
  379. for (uint32_t i = 0; i < chunk_count; i++) {
  380. memfree(chunks[i]);
  381. memfree(free_list_chunks[i]);
  382. }
  383. if (chunks) {
  384. memfree(chunks);
  385. memfree(free_list_chunks);
  386. }
  387. }
  388. };
  389. template <typename T, bool THREAD_SAFE = false>
  390. class RID_PtrOwner {
  391. RID_Alloc<T *, THREAD_SAFE> alloc;
  392. public:
  393. _FORCE_INLINE_ RID make_rid(T *p_ptr) {
  394. return alloc.make_rid(p_ptr);
  395. }
  396. _FORCE_INLINE_ RID allocate_rid() {
  397. return alloc.allocate_rid();
  398. }
  399. _FORCE_INLINE_ void initialize_rid(RID p_rid, T *p_ptr) {
  400. alloc.initialize_rid(p_rid, p_ptr);
  401. }
  402. _FORCE_INLINE_ T *get_or_null(const RID &p_rid) {
  403. T **ptr = alloc.get_or_null(p_rid);
  404. if (unlikely(!ptr)) {
  405. return nullptr;
  406. }
  407. return *ptr;
  408. }
  409. _FORCE_INLINE_ void replace(const RID &p_rid, T *p_new_ptr) {
  410. T **ptr = alloc.get_or_null(p_rid);
  411. ERR_FAIL_NULL(ptr);
  412. *ptr = p_new_ptr;
  413. }
  414. _FORCE_INLINE_ bool owns(const RID &p_rid) const {
  415. return alloc.owns(p_rid);
  416. }
  417. _FORCE_INLINE_ void free(const RID &p_rid) {
  418. alloc.free(p_rid);
  419. }
  420. _FORCE_INLINE_ uint32_t get_rid_count() const {
  421. return alloc.get_rid_count();
  422. }
  423. _FORCE_INLINE_ void get_owned_list(List<RID> *p_owned) const {
  424. return alloc.get_owned_list(p_owned);
  425. }
  426. void fill_owned_buffer(RID *p_rid_buffer) const {
  427. alloc.fill_owned_buffer(p_rid_buffer);
  428. }
  429. void set_description(const char *p_description) {
  430. alloc.set_description(p_description);
  431. }
  432. RID_PtrOwner(uint32_t p_target_chunk_byte_size = 65536, uint32_t p_maximum_number_of_elements = 262144) :
  433. alloc(p_target_chunk_byte_size, p_maximum_number_of_elements) {}
  434. };
  435. template <typename T, bool THREAD_SAFE = false>
  436. class RID_Owner {
  437. RID_Alloc<T, THREAD_SAFE> alloc;
  438. public:
  439. _FORCE_INLINE_ RID make_rid() {
  440. return alloc.make_rid();
  441. }
  442. _FORCE_INLINE_ RID make_rid(const T &p_ptr) {
  443. return alloc.make_rid(p_ptr);
  444. }
  445. _FORCE_INLINE_ RID allocate_rid() {
  446. return alloc.allocate_rid();
  447. }
  448. _FORCE_INLINE_ void initialize_rid(RID p_rid) {
  449. alloc.initialize_rid(p_rid);
  450. }
  451. _FORCE_INLINE_ void initialize_rid(RID p_rid, const T &p_ptr) {
  452. alloc.initialize_rid(p_rid, p_ptr);
  453. }
  454. _FORCE_INLINE_ T *get_or_null(const RID &p_rid) {
  455. return alloc.get_or_null(p_rid);
  456. }
  457. _FORCE_INLINE_ bool owns(const RID &p_rid) const {
  458. return alloc.owns(p_rid);
  459. }
  460. _FORCE_INLINE_ void free(const RID &p_rid) {
  461. alloc.free(p_rid);
  462. }
  463. _FORCE_INLINE_ uint32_t get_rid_count() const {
  464. return alloc.get_rid_count();
  465. }
  466. _FORCE_INLINE_ void get_owned_list(List<RID> *p_owned) const {
  467. return alloc.get_owned_list(p_owned);
  468. }
  469. void fill_owned_buffer(RID *p_rid_buffer) const {
  470. alloc.fill_owned_buffer(p_rid_buffer);
  471. }
  472. void set_description(const char *p_description) {
  473. alloc.set_description(p_description);
  474. }
  475. RID_Owner(uint32_t p_target_chunk_byte_size = 65536, uint32_t p_maximum_number_of_elements = 262144) :
  476. alloc(p_target_chunk_byte_size, p_maximum_number_of_elements) {}
  477. };