rid_owner.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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. #ifndef RID_OWNER_H
  31. #define RID_OWNER_H
  32. #include "core/os/memory.h"
  33. #include "core/os/mutex.h"
  34. #include "core/string/print_string.h"
  35. #include "core/templates/list.h"
  36. #include "core/templates/rid.h"
  37. #include "core/templates/safe_refcount.h"
  38. #include <stdio.h>
  39. #include <typeinfo>
  40. #ifdef SANITIZERS_ENABLED
  41. #ifdef __has_feature
  42. #if __has_feature(thread_sanitizer)
  43. #define TSAN_ENABLED
  44. #endif
  45. #elif defined(__SANITIZE_THREAD__)
  46. #define TSAN_ENABLED
  47. #endif
  48. #endif
  49. #ifdef TSAN_ENABLED
  50. #include <sanitizer/tsan_interface.h>
  51. #endif
  52. // The following macros would need to be implemented somehow
  53. // for purely weakly ordered architectures. There's a test case
  54. // ("[RID_Owner] Thread safety") with potential to catch issues
  55. // on such architectures if these primitives fail to be implemented.
  56. // For now, they will be just markers about needs that may arise.
  57. #define WEAK_MEMORY_ORDER 0
  58. #if WEAK_MEMORY_ORDER
  59. // Ideally, we'd have implementations that collaborate with the
  60. // sync mechanism used (e.g., the mutex) so instead of some full
  61. // memory barriers being issued, some acquire-release on the
  62. // primitive itself. However, these implementations will at least
  63. // provide correctness.
  64. #define SYNC_ACQUIRE std::atomic_thread_fence(std::memory_order_acquire);
  65. #define SYNC_RELEASE std::atomic_thread_fence(std::memory_order_release);
  66. #else
  67. // Compiler barriers are enough in this case.
  68. #define SYNC_ACQUIRE std::atomic_signal_fence(std::memory_order_acquire);
  69. #define SYNC_RELEASE std::atomic_signal_fence(std::memory_order_release);
  70. #endif
  71. class RID_AllocBase {
  72. static SafeNumeric<uint64_t> base_id;
  73. protected:
  74. static RID _make_from_id(uint64_t p_id) {
  75. RID rid;
  76. rid._id = p_id;
  77. return rid;
  78. }
  79. static RID _gen_rid() {
  80. return _make_from_id(_gen_id());
  81. }
  82. friend struct VariantUtilityFunctions;
  83. static uint64_t _gen_id() {
  84. return base_id.increment();
  85. }
  86. public:
  87. virtual ~RID_AllocBase() {}
  88. };
  89. template <typename T, bool THREAD_SAFE = false>
  90. class RID_Alloc : public RID_AllocBase {
  91. struct Chunk {
  92. T data;
  93. uint32_t validator;
  94. };
  95. Chunk **chunks = nullptr;
  96. uint32_t **free_list_chunks = nullptr;
  97. uint32_t elements_in_chunk;
  98. uint32_t max_alloc = 0;
  99. uint32_t alloc_count = 0;
  100. uint32_t chunk_limit = 0;
  101. const char *description = nullptr;
  102. mutable Mutex mutex;
  103. _FORCE_INLINE_ RID _allocate_rid() {
  104. if constexpr (THREAD_SAFE) {
  105. mutex.lock();
  106. }
  107. if (alloc_count == max_alloc) {
  108. //allocate a new chunk
  109. uint32_t chunk_count = alloc_count == 0 ? 0 : (max_alloc / elements_in_chunk);
  110. if (THREAD_SAFE && chunk_count == chunk_limit) {
  111. mutex.unlock();
  112. if (description != nullptr) {
  113. ERR_FAIL_V_MSG(RID(), vformat("Element limit for RID of type '%s' reached.", String(description)));
  114. } else {
  115. ERR_FAIL_V_MSG(RID(), "Element limit reached.");
  116. }
  117. }
  118. //grow chunks
  119. if constexpr (!THREAD_SAFE) {
  120. chunks = (Chunk **)memrealloc(chunks, sizeof(Chunk *) * (chunk_count + 1));
  121. }
  122. chunks[chunk_count] = (Chunk *)memalloc(sizeof(Chunk) * elements_in_chunk); //but don't initialize
  123. //grow free lists
  124. if constexpr (!THREAD_SAFE) {
  125. free_list_chunks = (uint32_t **)memrealloc(free_list_chunks, sizeof(uint32_t *) * (chunk_count + 1));
  126. }
  127. free_list_chunks[chunk_count] = (uint32_t *)memalloc(sizeof(uint32_t) * elements_in_chunk);
  128. //initialize
  129. for (uint32_t i = 0; i < elements_in_chunk; i++) {
  130. // Don't initialize chunk.
  131. chunks[chunk_count][i].validator = 0xFFFFFFFF;
  132. free_list_chunks[chunk_count][i] = alloc_count + i;
  133. }
  134. if constexpr (THREAD_SAFE) {
  135. // Store atomically to avoid data race with the load in get_or_null().
  136. ((std::atomic<uint32_t> *)&max_alloc)->store(max_alloc + elements_in_chunk, std::memory_order_relaxed);
  137. } else {
  138. max_alloc += elements_in_chunk;
  139. }
  140. }
  141. uint32_t free_index = free_list_chunks[alloc_count / elements_in_chunk][alloc_count % elements_in_chunk];
  142. uint32_t free_chunk = free_index / elements_in_chunk;
  143. uint32_t free_element = free_index % elements_in_chunk;
  144. uint32_t validator = (uint32_t)(_gen_id() & 0x7FFFFFFF);
  145. CRASH_COND_MSG(validator == 0x7FFFFFFF, "Overflow in RID validator");
  146. uint64_t id = validator;
  147. id <<= 32;
  148. id |= free_index;
  149. chunks[free_chunk][free_element].validator = validator;
  150. chunks[free_chunk][free_element].validator |= 0x80000000; //mark uninitialized bit
  151. alloc_count++;
  152. if constexpr (THREAD_SAFE) {
  153. mutex.unlock();
  154. }
  155. return _make_from_id(id);
  156. }
  157. public:
  158. RID make_rid() {
  159. RID rid = _allocate_rid();
  160. initialize_rid(rid);
  161. return rid;
  162. }
  163. RID make_rid(const T &p_value) {
  164. RID rid = _allocate_rid();
  165. initialize_rid(rid, p_value);
  166. return rid;
  167. }
  168. //allocate but don't initialize, use initialize_rid afterwards
  169. RID allocate_rid() {
  170. return _allocate_rid();
  171. }
  172. _FORCE_INLINE_ T *get_or_null(const RID &p_rid, bool p_initialize = false) {
  173. if (p_rid == RID()) {
  174. return nullptr;
  175. }
  176. if constexpr (THREAD_SAFE) {
  177. SYNC_ACQUIRE;
  178. }
  179. uint64_t id = p_rid.get_id();
  180. uint32_t idx = uint32_t(id & 0xFFFFFFFF);
  181. uint32_t ma;
  182. if constexpr (THREAD_SAFE) { // Read atomically to avoid data race with the store in _allocate_rid().
  183. ma = ((std::atomic<uint32_t> *)&max_alloc)->load(std::memory_order_relaxed);
  184. } else {
  185. ma = max_alloc;
  186. }
  187. if (unlikely(idx >= ma)) {
  188. return nullptr;
  189. }
  190. uint32_t idx_chunk = idx / elements_in_chunk;
  191. uint32_t idx_element = idx % elements_in_chunk;
  192. uint32_t validator = uint32_t(id >> 32);
  193. if constexpr (THREAD_SAFE) {
  194. #ifdef TSAN_ENABLED
  195. __tsan_acquire(&chunks[idx_chunk]); // We know not a race in practice.
  196. __tsan_acquire(&chunks[idx_chunk][idx_element]); // We know not a race in practice.
  197. #endif
  198. }
  199. Chunk &c = chunks[idx_chunk][idx_element];
  200. if constexpr (THREAD_SAFE) {
  201. #ifdef TSAN_ENABLED
  202. __tsan_release(&chunks[idx_chunk]);
  203. __tsan_release(&chunks[idx_chunk][idx_element]);
  204. __tsan_acquire(&c.validator); // We know not a race in practice.
  205. #endif
  206. }
  207. if (unlikely(p_initialize)) {
  208. if (unlikely(!(c.validator & 0x80000000))) {
  209. ERR_FAIL_V_MSG(nullptr, "Initializing already initialized RID");
  210. }
  211. if (unlikely((c.validator & 0x7FFFFFFF) != validator)) {
  212. ERR_FAIL_V_MSG(nullptr, "Attempting to initialize the wrong RID");
  213. }
  214. c.validator &= 0x7FFFFFFF; //initialized
  215. } else if (unlikely(c.validator != validator)) {
  216. if ((c.validator & 0x80000000) && c.validator != 0xFFFFFFFF) {
  217. ERR_FAIL_V_MSG(nullptr, "Attempting to use an uninitialized RID");
  218. }
  219. return nullptr;
  220. }
  221. if constexpr (THREAD_SAFE) {
  222. #ifdef TSAN_ENABLED
  223. __tsan_release(&c.validator);
  224. #endif
  225. }
  226. T *ptr = &c.data;
  227. return ptr;
  228. }
  229. void initialize_rid(RID p_rid) {
  230. T *mem = get_or_null(p_rid, true);
  231. ERR_FAIL_NULL(mem);
  232. if constexpr (THREAD_SAFE) {
  233. #ifdef TSAN_ENABLED
  234. __tsan_acquire(mem); // We know not a race in practice.
  235. #endif
  236. }
  237. memnew_placement(mem, T);
  238. if constexpr (THREAD_SAFE) {
  239. #ifdef TSAN_ENABLED
  240. __tsan_release(mem);
  241. #endif
  242. SYNC_RELEASE;
  243. }
  244. }
  245. void initialize_rid(RID p_rid, const T &p_value) {
  246. T *mem = get_or_null(p_rid, true);
  247. ERR_FAIL_NULL(mem);
  248. if constexpr (THREAD_SAFE) {
  249. #ifdef TSAN_ENABLED
  250. __tsan_acquire(mem); // We know not a race in practice.
  251. #endif
  252. }
  253. memnew_placement(mem, T(p_value));
  254. if constexpr (THREAD_SAFE) {
  255. #ifdef TSAN_ENABLED
  256. __tsan_release(mem);
  257. #endif
  258. SYNC_RELEASE;
  259. }
  260. }
  261. _FORCE_INLINE_ bool owns(const RID &p_rid) const {
  262. if constexpr (THREAD_SAFE) {
  263. mutex.lock();
  264. }
  265. uint64_t id = p_rid.get_id();
  266. uint32_t idx = uint32_t(id & 0xFFFFFFFF);
  267. if (unlikely(idx >= max_alloc)) {
  268. if constexpr (THREAD_SAFE) {
  269. mutex.unlock();
  270. }
  271. return false;
  272. }
  273. uint32_t idx_chunk = idx / elements_in_chunk;
  274. uint32_t idx_element = idx % elements_in_chunk;
  275. uint32_t validator = uint32_t(id >> 32);
  276. bool owned = (validator != 0x7FFFFFFF) && (chunks[idx_chunk][idx_element].validator & 0x7FFFFFFF) == validator;
  277. if constexpr (THREAD_SAFE) {
  278. mutex.unlock();
  279. }
  280. return owned;
  281. }
  282. _FORCE_INLINE_ void free(const RID &p_rid) {
  283. if constexpr (THREAD_SAFE) {
  284. mutex.lock();
  285. }
  286. uint64_t id = p_rid.get_id();
  287. uint32_t idx = uint32_t(id & 0xFFFFFFFF);
  288. if (unlikely(idx >= max_alloc)) {
  289. if constexpr (THREAD_SAFE) {
  290. mutex.unlock();
  291. }
  292. ERR_FAIL();
  293. }
  294. uint32_t idx_chunk = idx / elements_in_chunk;
  295. uint32_t idx_element = idx % elements_in_chunk;
  296. uint32_t validator = uint32_t(id >> 32);
  297. if (unlikely(chunks[idx_chunk][idx_element].validator & 0x80000000)) {
  298. if constexpr (THREAD_SAFE) {
  299. mutex.unlock();
  300. }
  301. ERR_FAIL_MSG("Attempted to free an uninitialized or invalid RID");
  302. } else if (unlikely(chunks[idx_chunk][idx_element].validator != validator)) {
  303. if constexpr (THREAD_SAFE) {
  304. mutex.unlock();
  305. }
  306. ERR_FAIL();
  307. }
  308. chunks[idx_chunk][idx_element].data.~T();
  309. chunks[idx_chunk][idx_element].validator = 0xFFFFFFFF; // go invalid
  310. alloc_count--;
  311. free_list_chunks[alloc_count / elements_in_chunk][alloc_count % elements_in_chunk] = idx;
  312. if constexpr (THREAD_SAFE) {
  313. mutex.unlock();
  314. }
  315. }
  316. _FORCE_INLINE_ uint32_t get_rid_count() const {
  317. return alloc_count;
  318. }
  319. void get_owned_list(List<RID> *p_owned) const {
  320. if constexpr (THREAD_SAFE) {
  321. mutex.lock();
  322. }
  323. for (size_t i = 0; i < max_alloc; i++) {
  324. uint64_t validator = chunks[i / elements_in_chunk][i % elements_in_chunk].validator;
  325. if (validator != 0xFFFFFFFF) {
  326. p_owned->push_back(_make_from_id((validator << 32) | i));
  327. }
  328. }
  329. if constexpr (THREAD_SAFE) {
  330. mutex.unlock();
  331. }
  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_ void get_owned_list(List<RID> *p_owned) const {
  425. return alloc.get_owned_list(p_owned);
  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_ void get_owned_list(List<RID> *p_owned) const {
  468. return alloc.get_owned_list(p_owned);
  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. };
  479. #endif // RID_OWNER_H