ua_nodestore_hashmap.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. do {
  202. UA_NodeMapEntry *entry = ns->entries[(UA_UInt32)idx];
  203. /* Found a candidate */
  204. if(entry > UA_NODEMAP_TOMBSTONE) {
  205. if(entry->nodeIdHash == h &&
  206. UA_NodeId_equal(&entry->node.nodeId, nodeid))
  207. return &ns->entries[(UA_UInt32)idx];
  208. } else {
  209. /* No entry can be found afterwards */
  210. if(entry == NULL)
  211. return NULL;
  212. }
  213. idx += hash2;
  214. if(idx >= size)
  215. idx -= size;
  216. } while((UA_UInt32)idx != startIdx);
  217. return NULL;
  218. }
  219. /***********************/
  220. /* Interface functions */
  221. /***********************/
  222. static UA_Node *
  223. UA_NodeMap_newNode(void *context, UA_NodeClass nodeClass) {
  224. UA_NodeMapEntry *entry = newEntry(nodeClass);
  225. if(!entry)
  226. return NULL;
  227. return &entry->node;
  228. }
  229. static void
  230. UA_NodeMap_deleteNode(void *context, UA_Node *node) {
  231. #if UA_MULTITHREADING >= 100
  232. UA_NodeMap *ns = (UA_NodeMap*)context;
  233. #endif
  234. BEGIN_CRITSECT(ns);
  235. UA_NodeMapEntry *entry = container_of(node, UA_NodeMapEntry, node);
  236. UA_assert(&entry->node == node);
  237. deleteEntry(entry);
  238. END_CRITSECT(ns);
  239. }
  240. static const UA_Node *
  241. UA_NodeMap_getNode(void *context, const UA_NodeId *nodeid) {
  242. UA_NodeMap *ns = (UA_NodeMap*)context;
  243. BEGIN_CRITSECT(ns);
  244. UA_NodeMapEntry **entry = findOccupiedSlot(ns, nodeid);
  245. if(!entry) {
  246. END_CRITSECT(ns);
  247. return NULL;
  248. }
  249. ++(*entry)->refCount;
  250. END_CRITSECT(ns);
  251. return (const UA_Node*)&(*entry)->node;
  252. }
  253. static void
  254. UA_NodeMap_releaseNode(void *context, const UA_Node *node) {
  255. if (!node)
  256. return;
  257. #if UA_MULTITHREADING >= 100
  258. UA_NodeMap *ns = (UA_NodeMap*)context;
  259. #endif
  260. BEGIN_CRITSECT(ns);
  261. UA_NodeMapEntry *entry = container_of(node, UA_NodeMapEntry, node);
  262. UA_assert(&entry->node == node);
  263. UA_assert(entry->refCount > 0);
  264. --entry->refCount;
  265. cleanupEntry(entry);
  266. END_CRITSECT(ns);
  267. }
  268. static UA_StatusCode
  269. UA_NodeMap_getNodeCopy(void *context, const UA_NodeId *nodeid,
  270. UA_Node **outNode) {
  271. UA_NodeMap *ns = (UA_NodeMap*)context;
  272. BEGIN_CRITSECT(ns);
  273. UA_NodeMapEntry **slot = findOccupiedSlot(ns, nodeid);
  274. if(!slot) {
  275. END_CRITSECT(ns);
  276. return UA_STATUSCODE_BADNODEIDUNKNOWN;
  277. }
  278. UA_NodeMapEntry *entry = *slot;
  279. UA_NodeMapEntry *newItem = newEntry(entry->node.nodeClass);
  280. if(!newItem) {
  281. END_CRITSECT(ns);
  282. return UA_STATUSCODE_BADOUTOFMEMORY;
  283. }
  284. UA_StatusCode retval = UA_Node_copy(&entry->node, &newItem->node);
  285. if(retval == UA_STATUSCODE_GOOD) {
  286. newItem->orig = entry; /* Store the pointer to the original */
  287. *outNode = &newItem->node;
  288. } else {
  289. deleteEntry(newItem);
  290. }
  291. END_CRITSECT(ns);
  292. return retval;
  293. }
  294. static UA_StatusCode
  295. UA_NodeMap_removeNode(void *context, const UA_NodeId *nodeid) {
  296. UA_NodeMap *ns = (UA_NodeMap*)context;
  297. BEGIN_CRITSECT(ns);
  298. UA_NodeMapEntry **slot = findOccupiedSlot(ns, nodeid);
  299. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  300. if(slot)
  301. retval = clearSlot(ns, slot);
  302. else
  303. retval = UA_STATUSCODE_BADNODEIDUNKNOWN;
  304. END_CRITSECT(ns);
  305. return retval;
  306. }
  307. static UA_StatusCode
  308. UA_NodeMap_insertNode(void *context, UA_Node *node,
  309. UA_NodeId *addedNodeId) {
  310. UA_NodeMap *ns = (UA_NodeMap*)context;
  311. BEGIN_CRITSECT(ns);
  312. if(ns->size * 3 <= ns->count * 4) {
  313. if(expand(ns) != UA_STATUSCODE_GOOD) {
  314. END_CRITSECT(ns);
  315. return UA_STATUSCODE_BADINTERNALERROR;
  316. }
  317. }
  318. UA_NodeMapEntry **slot;
  319. if(node->nodeId.identifierType == UA_NODEIDTYPE_NUMERIC &&
  320. node->nodeId.identifier.numeric == 0) {
  321. /* Create a random nodeid: Start at least with 50,000 to make sure we
  322. * don not conflict with nodes from the spec. If we find a conflict, we
  323. * just try another identifier until we have tried all possible
  324. * identifiers. Since the size is prime and we don't change the increase
  325. * val, we will reach the starting id again. E.g. adding a nodeset will
  326. * create children while there are still other nodes which need to be
  327. * created. Thus the node ids may collide. */
  328. UA_UInt32 size = ns->size;
  329. UA_UInt64 identifier = mod(50000 + size+1, UA_UINT32_MAX); /* Use 64bit to
  330. * avoid overflow */
  331. UA_UInt32 increase = mod2(ns->count+1, size);
  332. UA_UInt32 startId = (UA_UInt32)identifier; /* mod ensures us that the id
  333. * is a valid 32 bit integer */
  334. do {
  335. node->nodeId.identifier.numeric = (UA_UInt32)identifier;
  336. slot = findFreeSlot(ns, &node->nodeId);
  337. if(slot)
  338. break;
  339. identifier += increase;
  340. if(identifier >= size)
  341. identifier -= size;
  342. } while((UA_UInt32)identifier != startId);
  343. } else {
  344. slot = findFreeSlot(ns, &node->nodeId);
  345. }
  346. if(!slot) {
  347. deleteEntry(container_of(node, UA_NodeMapEntry, node));
  348. END_CRITSECT(ns);
  349. return UA_STATUSCODE_BADNODEIDEXISTS;
  350. }
  351. /* Copy the NodeId */
  352. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  353. if(addedNodeId) {
  354. retval = UA_NodeId_copy(&node->nodeId, addedNodeId);
  355. if(retval != UA_STATUSCODE_GOOD) {
  356. deleteEntry(container_of(node, UA_NodeMapEntry, node));
  357. END_CRITSECT(ns);
  358. return retval;
  359. }
  360. }
  361. /* Store the hash */
  362. UA_NodeMapEntry *newEntry = container_of(node, UA_NodeMapEntry, node);
  363. newEntry->nodeIdHash = UA_NodeId_hash(&node->nodeId);
  364. /* Insert the node */
  365. UA_NodeMapEntry *oldEntry = *slot;
  366. if(UA_atomic_cmpxchg((void**)slot, oldEntry, newEntry) != oldEntry) {
  367. deleteEntry(container_of(node, UA_NodeMapEntry, node));
  368. END_CRITSECT(ns);
  369. return UA_STATUSCODE_BADNODEIDEXISTS;
  370. }
  371. ++ns->count;
  372. END_CRITSECT(ns);
  373. return retval;
  374. }
  375. static UA_StatusCode
  376. UA_NodeMap_replaceNode(void *context, UA_Node *node) {
  377. UA_NodeMap *ns = (UA_NodeMap*)context;
  378. UA_NodeMapEntry *newEntryContainer = container_of(node, UA_NodeMapEntry, node);
  379. BEGIN_CRITSECT(ns);
  380. /* Find the node */
  381. UA_NodeMapEntry **slot = findOccupiedSlot(ns, &node->nodeId);
  382. if(!slot) {
  383. deleteEntry(newEntryContainer);
  384. END_CRITSECT(ns);
  385. return UA_STATUSCODE_BADNODEIDUNKNOWN;
  386. }
  387. UA_NodeMapEntry *oldEntryContainer = *slot;
  388. /* The node was already updated since the copy was made? */
  389. if(oldEntryContainer != newEntryContainer->orig) {
  390. deleteEntry(newEntryContainer);
  391. END_CRITSECT(ns);
  392. return UA_STATUSCODE_BADINTERNALERROR;
  393. }
  394. /* Store the hash */
  395. newEntryContainer->nodeIdHash = oldEntryContainer->nodeIdHash;
  396. /* Replace the entry with an atomic operation */
  397. if(UA_atomic_cmpxchg((void**)slot, oldEntryContainer,
  398. newEntryContainer) != oldEntryContainer) {
  399. deleteEntry(newEntryContainer);
  400. END_CRITSECT(ns);
  401. return UA_STATUSCODE_BADINTERNALERROR;
  402. }
  403. oldEntryContainer->deleted = true;
  404. cleanupEntry(oldEntryContainer);
  405. END_CRITSECT(ns);
  406. return UA_STATUSCODE_GOOD;
  407. }
  408. static void
  409. UA_NodeMap_iterate(void *context, UA_NodestoreVisitor visitor,
  410. void *visitorContext) {
  411. UA_NodeMap *ns = (UA_NodeMap*)context;
  412. BEGIN_CRITSECT(ns);
  413. for(UA_UInt32 i = 0; i < ns->size; ++i) {
  414. if(ns->entries[i] > UA_NODEMAP_TOMBSTONE) {
  415. END_CRITSECT(ns);
  416. UA_NodeMapEntry *entry = ns->entries[i];
  417. entry->refCount++;
  418. visitor(visitorContext, &entry->node);
  419. entry->refCount--;
  420. cleanupEntry(entry);
  421. BEGIN_CRITSECT(ns);
  422. }
  423. }
  424. END_CRITSECT(ns);
  425. }
  426. static void
  427. UA_NodeMap_delete(void *context) {
  428. UA_NodeMap *ns = (UA_NodeMap*)context;
  429. #if UA_MULTITHREADING >= 100
  430. UA_LOCK_DESTROY(ns->lock);
  431. #endif
  432. UA_UInt32 size = ns->size;
  433. UA_NodeMapEntry **entries = ns->entries;
  434. for(UA_UInt32 i = 0; i < size; ++i) {
  435. if(entries[i] > UA_NODEMAP_TOMBSTONE) {
  436. /* On debugging builds, check that all nodes were release */
  437. UA_assert(entries[i]->refCount == 0);
  438. /* Delete the node */
  439. deleteEntry(entries[i]);
  440. }
  441. }
  442. UA_free(ns->entries);
  443. UA_free(ns);
  444. }
  445. UA_StatusCode
  446. UA_Nodestore_HashMap(UA_Nodestore *ns) {
  447. /* Allocate and initialize the nodemap */
  448. UA_NodeMap *nodemap = (UA_NodeMap*)UA_malloc(sizeof(UA_NodeMap));
  449. if(!nodemap)
  450. return UA_STATUSCODE_BADOUTOFMEMORY;
  451. nodemap->sizePrimeIndex = higher_prime_index(UA_NODEMAP_MINSIZE);
  452. nodemap->size = primes[nodemap->sizePrimeIndex];
  453. nodemap->count = 0;
  454. nodemap->entries = (UA_NodeMapEntry**)
  455. UA_calloc(nodemap->size, sizeof(UA_NodeMapEntry*));
  456. if(!nodemap->entries) {
  457. UA_free(nodemap);
  458. return UA_STATUSCODE_BADOUTOFMEMORY;
  459. }
  460. #if UA_MULTITHREADING >= 100
  461. UA_LOCK_INIT(nodemap->lock)
  462. #endif
  463. /* Populate the nodestore */
  464. ns->context = nodemap;
  465. ns->clear = UA_NodeMap_delete;
  466. ns->newNode = UA_NodeMap_newNode;
  467. ns->deleteNode = UA_NodeMap_deleteNode;
  468. ns->getNode = UA_NodeMap_getNode;
  469. ns->releaseNode = UA_NodeMap_releaseNode;
  470. ns->getNodeCopy = UA_NodeMap_getNodeCopy;
  471. ns->insertNode = UA_NodeMap_insertNode;
  472. ns->replaceNode = UA_NodeMap_replaceNode;
  473. ns->removeNode = UA_NodeMap_removeNode;
  474. ns->iterate = UA_NodeMap_iterate;
  475. return UA_STATUSCODE_GOOD;
  476. }