ua_nodestore_hashmap.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  2. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information.
  3. *
  4. * Copyright 2014-2019 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  5. * Copyright 2017 (c) Julian Grothoff
  6. * Copyright 2017 (c) Stefan Profanter, fortiss GmbH
  7. */
  8. #include <open62541/plugin/nodestore_default.h>
  9. #if UA_MULTITHREADING >= 100
  10. #define BEGIN_CRITSECT(NODEMAP) UA_LOCK(NODEMAP->lock)
  11. #define END_CRITSECT(NODEMAP) UA_UNLOCK(NODEMAP->lock)
  12. #else
  13. #define BEGIN_CRITSECT(NODEMAP) do {} while(0)
  14. #define END_CRITSECT(NODEMAP) do {} while(0)
  15. #endif
  16. /* container_of */
  17. #define container_of(ptr, type, member) \
  18. (type *)((uintptr_t)ptr - offsetof(type,member))
  19. /* The default Nodestore is simply a hash-map from NodeIds to Nodes. To find an
  20. * entry, iterate over candidate positions according to the NodeId hash.
  21. *
  22. * - Tombstone or non-matching NodeId: continue searching
  23. * - Matching NodeId: Return the entry
  24. * - NULL: Abort the search
  25. *
  26. * The nodestore uses atomic operations to set entries of the hash-map. If
  27. * UA_ENABLE_IMMUTABLE_NODES is configured, the nodestore allows read-access
  28. * from an interrupt without seeing corrupted nodes. For true multi-threaded
  29. * access, a mutex is used.
  30. *
  31. * Multi-threading without a mutex could be realized with the Linux RCU mechanism.
  32. * But this is not done for this implementation of the nodestore. */
  33. typedef struct UA_NodeMapEntry {
  34. UA_UInt32 nodeIdHash;
  35. struct UA_NodeMapEntry *orig; /* the version this is a copy from (or NULL) */
  36. UA_UInt16 refCount; /* How many consumers have a reference to the node? */
  37. UA_Boolean deleted; /* Node was marked as deleted and can be deleted when refCount == 0 */
  38. UA_Node node;
  39. } UA_NodeMapEntry;
  40. #define UA_NODEMAP_MINSIZE 64
  41. #define UA_NODEMAP_TOMBSTONE ((UA_NodeMapEntry*)0x01)
  42. typedef struct {
  43. UA_NodeMapEntry **entries;
  44. UA_UInt32 size;
  45. UA_UInt32 count;
  46. UA_UInt32 sizePrimeIndex;
  47. #if UA_MULTITHREADING >= 100
  48. UA_LOCK_TYPE(lock) /* Protect access */
  49. #endif
  50. } UA_NodeMap;
  51. /*********************/
  52. /* HashMap Utilities */
  53. /*********************/
  54. /* The size of the hash-map is always a prime number. They are chosen to be
  55. * close to the next power of 2. So the size ca. doubles with each prime. */
  56. static UA_UInt32 const primes[] = {
  57. 7, 13, 31, 61, 127, 251,
  58. 509, 1021, 2039, 4093, 8191, 16381,
  59. 32749, 65521, 131071, 262139, 524287, 1048573,
  60. 2097143, 4194301, 8388593, 16777213, 33554393, 67108859,
  61. 134217689, 268435399, 536870909, 1073741789, 2147483647, 4294967291
  62. };
  63. static UA_UInt32 mod(UA_UInt32 h, UA_UInt32 size) { return h % size; }
  64. static UA_UInt32 mod2(UA_UInt32 h, UA_UInt32 size) { return 1 + (h % (size - 2)); }
  65. static UA_UInt16
  66. higher_prime_index(UA_UInt32 n) {
  67. UA_UInt16 low = 0;
  68. UA_UInt16 high = (UA_UInt16)(sizeof(primes) / sizeof(UA_UInt32));
  69. while(low != high) {
  70. UA_UInt16 mid = (UA_UInt16)(low + ((high - low) / 2));
  71. if(n > primes[mid])
  72. low = (UA_UInt16)(mid + 1);
  73. else
  74. high = mid;
  75. }
  76. return low;
  77. }
  78. /* Returns an empty slot or null if the nodeid exists or if no empty slot is found. */
  79. static UA_NodeMapEntry **
  80. findFreeSlot(const UA_NodeMap *ns, const UA_NodeId *nodeid) {
  81. UA_NodeMapEntry **retval = NULL;
  82. UA_UInt32 h = UA_NodeId_hash(nodeid);
  83. UA_UInt32 size = ns->size;
  84. UA_UInt64 idx = mod(h, size); /* Use 64bit container to avoid overflow */
  85. UA_UInt32 startIdx = (UA_UInt32)idx;
  86. UA_UInt32 hash2 = mod2(h, size);
  87. UA_NodeMapEntry *entry = NULL;
  88. do {
  89. entry = ns->entries[(UA_UInt32)idx];
  90. if(entry > UA_NODEMAP_TOMBSTONE &&
  91. UA_NodeId_equal(&entry->node.nodeId, nodeid))
  92. return NULL;
  93. if(!retval && entry <= UA_NODEMAP_TOMBSTONE)
  94. retval = &ns->entries[(UA_UInt32)idx];
  95. idx += hash2;
  96. if(idx >= size)
  97. idx -= size;
  98. } while((UA_UInt32)idx != startIdx && entry);
  99. /* NULL is returned if there is no free slot (idx == startIdx).
  100. * Otherwise the first free slot is returned after we are sure,
  101. * that the node id cannot be found in the used hashmap (!entry). */
  102. return retval;
  103. }
  104. /* The occupancy of the table after the call will be about 50% */
  105. static UA_StatusCode
  106. expand(UA_NodeMap *ns) {
  107. UA_UInt32 osize = ns->size;
  108. UA_UInt32 count = ns->count;
  109. /* Resize only when table after removal of unused elements is either too
  110. full or too empty */
  111. if(count * 2 < osize && (count * 8 > osize || osize <= UA_NODEMAP_MINSIZE))
  112. return UA_STATUSCODE_GOOD;
  113. UA_NodeMapEntry **oentries = ns->entries;
  114. UA_UInt32 nindex = higher_prime_index(count * 2);
  115. UA_UInt32 nsize = primes[nindex];
  116. UA_NodeMapEntry **nentries = (UA_NodeMapEntry **)UA_calloc(nsize, sizeof(UA_NodeMapEntry*));
  117. if(!nentries)
  118. return UA_STATUSCODE_BADOUTOFMEMORY;
  119. ns->entries = nentries;
  120. ns->size = nsize;
  121. ns->sizePrimeIndex = nindex;
  122. /* recompute the position of every entry and insert the pointer */
  123. for(size_t i = 0, j = 0; i < osize && j < count; ++i) {
  124. if(oentries[i] <= UA_NODEMAP_TOMBSTONE)
  125. continue;
  126. UA_NodeMapEntry **e = findFreeSlot(ns, &oentries[i]->node.nodeId);
  127. UA_assert(e);
  128. *e = oentries[i];
  129. ++j;
  130. }
  131. UA_free(oentries);
  132. return UA_STATUSCODE_GOOD;
  133. }
  134. static UA_NodeMapEntry *
  135. newEntry(UA_NodeClass nodeClass) {
  136. size_t size = sizeof(UA_NodeMapEntry) - sizeof(UA_Node);
  137. switch(nodeClass) {
  138. case UA_NODECLASS_OBJECT:
  139. size += sizeof(UA_ObjectNode);
  140. break;
  141. case UA_NODECLASS_VARIABLE:
  142. size += sizeof(UA_VariableNode);
  143. break;
  144. case UA_NODECLASS_METHOD:
  145. size += sizeof(UA_MethodNode);
  146. break;
  147. case UA_NODECLASS_OBJECTTYPE:
  148. size += sizeof(UA_ObjectTypeNode);
  149. break;
  150. case UA_NODECLASS_VARIABLETYPE:
  151. size += sizeof(UA_VariableTypeNode);
  152. break;
  153. case UA_NODECLASS_REFERENCETYPE:
  154. size += sizeof(UA_ReferenceTypeNode);
  155. break;
  156. case UA_NODECLASS_DATATYPE:
  157. size += sizeof(UA_DataTypeNode);
  158. break;
  159. case UA_NODECLASS_VIEW:
  160. size += sizeof(UA_ViewNode);
  161. break;
  162. default:
  163. return NULL;
  164. }
  165. UA_NodeMapEntry *entry = (UA_NodeMapEntry*)UA_calloc(1, size);
  166. if(!entry)
  167. return NULL;
  168. entry->node.nodeClass = nodeClass;
  169. return entry;
  170. }
  171. static void
  172. deleteEntry(UA_NodeMapEntry *entry) {
  173. UA_Node_clear(&entry->node);
  174. UA_free(entry);
  175. }
  176. static void
  177. cleanupEntry(UA_NodeMapEntry *entry) {
  178. if(entry->deleted && entry->refCount == 0)
  179. deleteEntry(entry);
  180. }
  181. static UA_StatusCode
  182. clearSlot(UA_NodeMap *ns, UA_NodeMapEntry **slot) {
  183. UA_NodeMapEntry *entry = *slot;
  184. if(UA_atomic_cmpxchg((void**)slot, entry, UA_NODEMAP_TOMBSTONE) != entry)
  185. return UA_STATUSCODE_BADINTERNALERROR;
  186. entry->deleted = true;
  187. cleanupEntry(entry);
  188. --ns->count;
  189. /* Downsize the hashmap if it is very empty */
  190. if(ns->count * 8 < ns->size && ns->size > 32)
  191. expand(ns); /* Can fail. Just continue with the bigger hashmap. */
  192. return UA_STATUSCODE_GOOD;
  193. }
  194. static UA_NodeMapEntry **
  195. findOccupiedSlot(const UA_NodeMap *ns, const UA_NodeId *nodeid) {
  196. UA_UInt32 h = UA_NodeId_hash(nodeid);
  197. UA_UInt32 size = ns->size;
  198. UA_UInt64 idx = mod(h, size); /* Use 64bit container to avoid overflow */
  199. UA_UInt32 hash2 = mod2(h, size);
  200. UA_UInt32 startIdx = (UA_UInt32)idx;
  201. UA_NodeMapEntry *entry = NULL;
  202. do {
  203. entry = ns->entries[(UA_UInt32)idx];
  204. if(entry > UA_NODEMAP_TOMBSTONE &&
  205. entry->nodeIdHash == h &&
  206. UA_NodeId_equal(&entry->node.nodeId, nodeid))
  207. return &ns->entries[(UA_UInt32)idx];
  208. idx += hash2;
  209. if(idx >= size)
  210. idx -= size;
  211. } while((UA_UInt32)idx != startIdx && entry);
  212. /* NULL is returned if there is no free slot (idx == startIdx)
  213. * and the node id is not found or if the end of the used slots (!entry)
  214. * is reached. */
  215. return NULL;
  216. }
  217. /***********************/
  218. /* Interface functions */
  219. /***********************/
  220. static UA_Node *
  221. UA_NodeMap_newNode(void *context, UA_NodeClass nodeClass) {
  222. UA_NodeMapEntry *entry = newEntry(nodeClass);
  223. if(!entry)
  224. return NULL;
  225. return &entry->node;
  226. }
  227. static void
  228. UA_NodeMap_deleteNode(void *context, UA_Node *node) {
  229. #if UA_MULTITHREADING >= 100
  230. UA_NodeMap *ns = (UA_NodeMap*)context;
  231. #endif
  232. BEGIN_CRITSECT(ns);
  233. UA_NodeMapEntry *entry = container_of(node, UA_NodeMapEntry, node);
  234. UA_assert(&entry->node == node);
  235. deleteEntry(entry);
  236. END_CRITSECT(ns);
  237. }
  238. static const UA_Node *
  239. UA_NodeMap_getNode(void *context, const UA_NodeId *nodeid) {
  240. UA_NodeMap *ns = (UA_NodeMap*)context;
  241. BEGIN_CRITSECT(ns);
  242. UA_NodeMapEntry **entry = findOccupiedSlot(ns, nodeid);
  243. if(!entry) {
  244. END_CRITSECT(ns);
  245. return NULL;
  246. }
  247. ++(*entry)->refCount;
  248. END_CRITSECT(ns);
  249. return (const UA_Node*)&(*entry)->node;
  250. }
  251. static void
  252. UA_NodeMap_releaseNode(void *context, const UA_Node *node) {
  253. if (!node)
  254. return;
  255. #if UA_MULTITHREADING >= 100
  256. UA_NodeMap *ns = (UA_NodeMap*)context;
  257. #endif
  258. BEGIN_CRITSECT(ns);
  259. UA_NodeMapEntry *entry = container_of(node, UA_NodeMapEntry, node);
  260. UA_assert(&entry->node == node);
  261. UA_assert(entry->refCount > 0);
  262. --entry->refCount;
  263. cleanupEntry(entry);
  264. END_CRITSECT(ns);
  265. }
  266. static UA_StatusCode
  267. UA_NodeMap_getNodeCopy(void *context, const UA_NodeId *nodeid,
  268. UA_Node **outNode) {
  269. UA_NodeMap *ns = (UA_NodeMap*)context;
  270. BEGIN_CRITSECT(ns);
  271. UA_NodeMapEntry **slot = findOccupiedSlot(ns, nodeid);
  272. if(!slot) {
  273. END_CRITSECT(ns);
  274. return UA_STATUSCODE_BADNODEIDUNKNOWN;
  275. }
  276. UA_NodeMapEntry *entry = *slot;
  277. UA_NodeMapEntry *newItem = newEntry(entry->node.nodeClass);
  278. if(!newItem) {
  279. END_CRITSECT(ns);
  280. return UA_STATUSCODE_BADOUTOFMEMORY;
  281. }
  282. UA_StatusCode retval = UA_Node_copy(&entry->node, &newItem->node);
  283. if(retval == UA_STATUSCODE_GOOD) {
  284. newItem->orig = entry; /* Store the pointer to the original */
  285. *outNode = &newItem->node;
  286. } else {
  287. deleteEntry(newItem);
  288. }
  289. END_CRITSECT(ns);
  290. return retval;
  291. }
  292. static UA_StatusCode
  293. UA_NodeMap_removeNode(void *context, const UA_NodeId *nodeid) {
  294. UA_NodeMap *ns = (UA_NodeMap*)context;
  295. BEGIN_CRITSECT(ns);
  296. UA_NodeMapEntry **slot = findOccupiedSlot(ns, nodeid);
  297. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  298. if(slot)
  299. retval = clearSlot(ns, slot);
  300. else
  301. retval = UA_STATUSCODE_BADNODEIDUNKNOWN;
  302. END_CRITSECT(ns);
  303. return retval;
  304. }
  305. static UA_StatusCode
  306. UA_NodeMap_insertNode(void *context, UA_Node *node,
  307. UA_NodeId *addedNodeId) {
  308. UA_NodeMap *ns = (UA_NodeMap*)context;
  309. BEGIN_CRITSECT(ns);
  310. if(ns->size * 3 <= ns->count * 4) {
  311. if(expand(ns) != UA_STATUSCODE_GOOD) {
  312. END_CRITSECT(ns);
  313. return UA_STATUSCODE_BADINTERNALERROR;
  314. }
  315. }
  316. UA_NodeMapEntry **slot;
  317. if(node->nodeId.identifierType == UA_NODEIDTYPE_NUMERIC &&
  318. node->nodeId.identifier.numeric == 0) {
  319. /* Create a random nodeid: Start at least with 50,000 to make sure we
  320. * don not conflict with nodes from the spec. If we find a conflict, we
  321. * just try another identifier until we have tried all possible
  322. * identifiers. Since the size is prime and we don't change the increase
  323. * val, we will reach the starting id again. E.g. adding a nodeset will
  324. * create children while there are still other nodes which need to be
  325. * created. Thus the node ids may collide. */
  326. UA_UInt32 size = ns->size;
  327. UA_UInt64 identifier = mod(50000 + size+1, UA_UINT32_MAX); /* Use 64bit to
  328. * avoid overflow */
  329. UA_UInt32 increase = mod2(ns->count+1, size);
  330. UA_UInt32 startId = (UA_UInt32)identifier; /* mod ensures us that the id
  331. * is a valid 32 bit integer */
  332. do {
  333. node->nodeId.identifier.numeric = (UA_UInt32)identifier;
  334. slot = findFreeSlot(ns, &node->nodeId);
  335. if(slot)
  336. break;
  337. identifier += increase;
  338. if(identifier >= size)
  339. identifier -= size;
  340. } while((UA_UInt32)identifier != startId);
  341. } else {
  342. slot = findFreeSlot(ns, &node->nodeId);
  343. }
  344. if(!slot) {
  345. deleteEntry(container_of(node, UA_NodeMapEntry, node));
  346. END_CRITSECT(ns);
  347. return UA_STATUSCODE_BADNODEIDEXISTS;
  348. }
  349. /* Copy the NodeId */
  350. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  351. if(addedNodeId) {
  352. retval = UA_NodeId_copy(&node->nodeId, addedNodeId);
  353. if(retval != UA_STATUSCODE_GOOD) {
  354. deleteEntry(container_of(node, UA_NodeMapEntry, node));
  355. END_CRITSECT(ns);
  356. return retval;
  357. }
  358. }
  359. /* Store the hash */
  360. UA_NodeMapEntry *newEntry = container_of(node, UA_NodeMapEntry, node);
  361. newEntry->nodeIdHash = UA_NodeId_hash(&node->nodeId);
  362. /* Insert the node */
  363. UA_NodeMapEntry *oldEntry = *slot;
  364. if(UA_atomic_cmpxchg((void**)slot, oldEntry, newEntry) != oldEntry) {
  365. deleteEntry(container_of(node, UA_NodeMapEntry, node));
  366. END_CRITSECT(ns);
  367. return UA_STATUSCODE_BADNODEIDEXISTS;
  368. }
  369. ++ns->count;
  370. END_CRITSECT(ns);
  371. return retval;
  372. }
  373. static UA_StatusCode
  374. UA_NodeMap_replaceNode(void *context, UA_Node *node) {
  375. UA_NodeMap *ns = (UA_NodeMap*)context;
  376. UA_NodeMapEntry *newEntryContainer = container_of(node, UA_NodeMapEntry, node);
  377. BEGIN_CRITSECT(ns);
  378. /* Find the node */
  379. UA_NodeMapEntry **slot = findOccupiedSlot(ns, &node->nodeId);
  380. if(!slot) {
  381. deleteEntry(newEntryContainer);
  382. END_CRITSECT(ns);
  383. return UA_STATUSCODE_BADNODEIDUNKNOWN;
  384. }
  385. UA_NodeMapEntry *oldEntryContainer = *slot;
  386. /* The node was already updated since the copy was made? */
  387. if(oldEntryContainer != newEntryContainer->orig) {
  388. deleteEntry(newEntryContainer);
  389. END_CRITSECT(ns);
  390. return UA_STATUSCODE_BADINTERNALERROR;
  391. }
  392. /* Store the hash */
  393. newEntryContainer->nodeIdHash = oldEntryContainer->nodeIdHash;
  394. /* Replace the entry with an atomic operation */
  395. if(UA_atomic_cmpxchg((void**)slot, oldEntryContainer,
  396. newEntryContainer) != oldEntryContainer) {
  397. deleteEntry(newEntryContainer);
  398. END_CRITSECT(ns);
  399. return UA_STATUSCODE_BADINTERNALERROR;
  400. }
  401. oldEntryContainer->deleted = true;
  402. cleanupEntry(oldEntryContainer);
  403. END_CRITSECT(ns);
  404. return UA_STATUSCODE_GOOD;
  405. }
  406. static void
  407. UA_NodeMap_iterate(void *context, UA_NodestoreVisitor visitor,
  408. void *visitorContext) {
  409. UA_NodeMap *ns = (UA_NodeMap*)context;
  410. BEGIN_CRITSECT(ns);
  411. for(UA_UInt32 i = 0; i < ns->size; ++i) {
  412. if(ns->entries[i] > UA_NODEMAP_TOMBSTONE) {
  413. END_CRITSECT(ns);
  414. UA_NodeMapEntry *entry = ns->entries[i];
  415. entry->refCount++;
  416. visitor(visitorContext, &entry->node);
  417. entry->refCount--;
  418. cleanupEntry(entry);
  419. BEGIN_CRITSECT(ns);
  420. }
  421. }
  422. END_CRITSECT(ns);
  423. }
  424. static void
  425. UA_NodeMap_delete(void *context) {
  426. UA_NodeMap *ns = (UA_NodeMap*)context;
  427. #if UA_MULTITHREADING >= 100
  428. UA_LOCK_DESTROY(ns->lock);
  429. #endif
  430. UA_UInt32 size = ns->size;
  431. UA_NodeMapEntry **entries = ns->entries;
  432. for(UA_UInt32 i = 0; i < size; ++i) {
  433. if(entries[i] > UA_NODEMAP_TOMBSTONE) {
  434. /* On debugging builds, check that all nodes were release */
  435. UA_assert(entries[i]->refCount == 0);
  436. /* Delete the node */
  437. deleteEntry(entries[i]);
  438. }
  439. }
  440. UA_free(ns->entries);
  441. UA_free(ns);
  442. }
  443. UA_StatusCode
  444. UA_Nodestore_HashMap(UA_Nodestore *ns) {
  445. /* Allocate and initialize the nodemap */
  446. UA_NodeMap *nodemap = (UA_NodeMap*)UA_malloc(sizeof(UA_NodeMap));
  447. if(!nodemap)
  448. return UA_STATUSCODE_BADOUTOFMEMORY;
  449. nodemap->sizePrimeIndex = higher_prime_index(UA_NODEMAP_MINSIZE);
  450. nodemap->size = primes[nodemap->sizePrimeIndex];
  451. nodemap->count = 0;
  452. nodemap->entries = (UA_NodeMapEntry**)
  453. UA_calloc(nodemap->size, sizeof(UA_NodeMapEntry*));
  454. if(!nodemap->entries) {
  455. UA_free(nodemap);
  456. return UA_STATUSCODE_BADOUTOFMEMORY;
  457. }
  458. #if UA_MULTITHREADING >= 100
  459. UA_LOCK_INIT(nodemap->lock)
  460. #endif
  461. /* Populate the nodestore */
  462. ns->context = nodemap;
  463. ns->clear = UA_NodeMap_delete;
  464. ns->newNode = UA_NodeMap_newNode;
  465. ns->deleteNode = UA_NodeMap_deleteNode;
  466. ns->getNode = UA_NodeMap_getNode;
  467. ns->releaseNode = UA_NodeMap_releaseNode;
  468. ns->getNodeCopy = UA_NodeMap_getNodeCopy;
  469. ns->insertNode = UA_NodeMap_insertNode;
  470. ns->replaceNode = UA_NodeMap_replaceNode;
  471. ns->removeNode = UA_NodeMap_removeNode;
  472. ns->iterate = UA_NodeMap_iterate;
  473. return UA_STATUSCODE_GOOD;
  474. }