ua_nodestore_default.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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-2017 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  5. * Copyright 2017 (c) Julian Grothoff
  6. * Copyright 2017 (c) Stefan Profanter, fortiss GmbH
  7. */
  8. #include "ua_nodestore_default.h"
  9. /* container_of */
  10. #define container_of(ptr, type, member) \
  11. (type *)((uintptr_t)ptr - offsetof(type,member))
  12. #ifdef UA_ENABLE_MULTITHREADING
  13. #include <pthread.h>
  14. #define BEGIN_CRITSECT(NODEMAP) pthread_mutex_lock(&(NODEMAP)->mutex)
  15. #define END_CRITSECT(NODEMAP) pthread_mutex_unlock(&(NODEMAP)->mutex)
  16. #else
  17. #define BEGIN_CRITSECT(NODEMAP)
  18. #define END_CRITSECT(NODEMAP)
  19. #endif
  20. /* The default Nodestore is simply a hash-map from NodeIds to Nodes. To find an
  21. * entry, iterate over candidate positions according to the NodeId hash.
  22. *
  23. * - Tombstone or non-matching NodeId: continue searching
  24. * - Matching NodeId: Return the entry
  25. * - NULL: Abort the search
  26. *
  27. * The nodestore uses atomic operations to set entries of the hash-map. If
  28. * UA_ENABLE_IMMUTABLE_NODES is configured, the nodestore allows read-access
  29. * from an interrupt without seeing corrupted nodes. For true multi-threaded
  30. * access, a mutex is used.
  31. *
  32. * Multi-threading without a mutex could be realized with the Linux RCU mechanism.
  33. * But this is not done for this implementation of the nodestore. */
  34. typedef struct UA_NodeMapEntry {
  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. #ifdef UA_ENABLE_MULTITHREADING
  48. pthread_mutex_t mutex; /* 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 64 bit 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_deleteMembers(&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 64 bit 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. UA_NodeId_equal(&entry->node.nodeId, nodeid))
  206. return &ns->entries[(UA_UInt32)idx];
  207. idx += hash2;
  208. if(idx >= size)
  209. idx -= size;
  210. } while((UA_UInt32)idx != startIdx && entry);
  211. /* NULL is returned if there is no free slot (idx == startIdx)
  212. * and the node id is not found or if the end of the used slots (!entry)
  213. * is reached. */
  214. return NULL;
  215. }
  216. /***********************/
  217. /* Interface functions */
  218. /***********************/
  219. static UA_Node *
  220. UA_NodeMap_newNode(void *context, UA_NodeClass nodeClass) {
  221. UA_NodeMapEntry *entry = newEntry(nodeClass);
  222. if(!entry)
  223. return NULL;
  224. return &entry->node;
  225. }
  226. static void
  227. UA_NodeMap_deleteNode(void *context, UA_Node *node) {
  228. #ifdef UA_ENABLE_MULTITHREADING
  229. UA_NodeMap *ns = (UA_NodeMap*)context;
  230. #endif
  231. BEGIN_CRITSECT(ns);
  232. UA_NodeMapEntry *entry = container_of(node, UA_NodeMapEntry, node);
  233. UA_assert(&entry->node == node);
  234. deleteEntry(entry);
  235. END_CRITSECT(ns);
  236. }
  237. static const UA_Node *
  238. UA_NodeMap_getNode(void *context, const UA_NodeId *nodeid) {
  239. UA_NodeMap *ns = (UA_NodeMap*)context;
  240. BEGIN_CRITSECT(ns);
  241. UA_NodeMapEntry **entry = findOccupiedSlot(ns, nodeid);
  242. if(!entry) {
  243. END_CRITSECT(ns);
  244. return NULL;
  245. }
  246. ++(*entry)->refCount;
  247. END_CRITSECT(ns);
  248. return (const UA_Node*)&(*entry)->node;
  249. }
  250. static void
  251. UA_NodeMap_releaseNode(void *context, const UA_Node *node) {
  252. if (!node)
  253. return;
  254. #ifdef UA_ENABLE_MULTITHREADING
  255. UA_NodeMap *ns = (UA_NodeMap*)context;
  256. #endif
  257. BEGIN_CRITSECT(ns);
  258. UA_NodeMapEntry *entry = container_of(node, UA_NodeMapEntry, node);
  259. UA_assert(&entry->node == node);
  260. UA_assert(entry->refCount > 0);
  261. --entry->refCount;
  262. cleanupEntry(entry);
  263. END_CRITSECT(ns);
  264. }
  265. static UA_StatusCode
  266. UA_NodeMap_getNodeCopy(void *context, const UA_NodeId *nodeid,
  267. UA_Node **outNode) {
  268. UA_NodeMap *ns = (UA_NodeMap*)context;
  269. BEGIN_CRITSECT(ns);
  270. UA_NodeMapEntry **slot = findOccupiedSlot(ns, nodeid);
  271. if(!slot) {
  272. END_CRITSECT(ns);
  273. return UA_STATUSCODE_BADNODEIDUNKNOWN;
  274. }
  275. UA_NodeMapEntry *entry = *slot;
  276. UA_NodeMapEntry *newItem = newEntry(entry->node.nodeClass);
  277. if(!newItem) {
  278. END_CRITSECT(ns);
  279. return UA_STATUSCODE_BADOUTOFMEMORY;
  280. }
  281. UA_StatusCode retval = UA_Node_copy(&entry->node, &newItem->node);
  282. if(retval == UA_STATUSCODE_GOOD) {
  283. newItem->orig = entry; // store the pointer to the original
  284. *outNode = &newItem->node;
  285. } else {
  286. deleteEntry(newItem);
  287. }
  288. END_CRITSECT(ns);
  289. return retval;
  290. }
  291. static UA_StatusCode
  292. UA_NodeMap_removeNode(void *context, const UA_NodeId *nodeid) {
  293. UA_NodeMap *ns = (UA_NodeMap*)context;
  294. BEGIN_CRITSECT(ns);
  295. UA_NodeMapEntry **slot = findOccupiedSlot(ns, nodeid);
  296. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  297. if(slot)
  298. retval = clearSlot(ns, slot);
  299. else
  300. retval = UA_STATUSCODE_BADNODEIDUNKNOWN;
  301. END_CRITSECT(ns);
  302. return retval;
  303. }
  304. static UA_StatusCode
  305. UA_NodeMap_insertNode(void *context, UA_Node *node,
  306. UA_NodeId *addedNodeId) {
  307. UA_NodeMap *ns = (UA_NodeMap*)context;
  308. BEGIN_CRITSECT(ns);
  309. if(ns->size * 3 <= ns->count * 4) {
  310. if(expand(ns) != UA_STATUSCODE_GOOD) {
  311. END_CRITSECT(ns);
  312. return UA_STATUSCODE_BADINTERNALERROR;
  313. }
  314. }
  315. UA_NodeMapEntry **slot;
  316. if(node->nodeId.identifierType == UA_NODEIDTYPE_NUMERIC &&
  317. node->nodeId.identifier.numeric == 0) {
  318. /* create a random nodeid */
  319. /* start at least with 50,000 to make sure we don not conflict with nodes from the spec */
  320. /* if we find a conflict, we just try another identifier until we have tried all possible identifiers */
  321. /* since the size is prime and we don't change the increase val, we will reach the starting id again */
  322. /* E.g. adding a nodeset will create children while there are still other nodes which need to be created */
  323. /* Thus the node ids may collide */
  324. UA_UInt32 size = ns->size;
  325. UA_UInt64 identifier = mod(50000 + size+1, UA_UINT32_MAX); // start value, use 64 bit container to avoid overflow
  326. UA_UInt32 increase = mod2(ns->count+1, size);
  327. UA_UInt32 startId = (UA_UInt32)identifier; // mod ensures us that the id is a valid 32 bit
  328. do {
  329. node->nodeId.identifier.numeric = (UA_UInt32)identifier;
  330. slot = findFreeSlot(ns, &node->nodeId);
  331. if(slot)
  332. break;
  333. identifier += increase;
  334. if(identifier >= size)
  335. identifier -= size;
  336. } while((UA_UInt32)identifier != startId);
  337. } else {
  338. slot = findFreeSlot(ns, &node->nodeId);
  339. }
  340. if(!slot) {
  341. deleteEntry(container_of(node, UA_NodeMapEntry, node));
  342. END_CRITSECT(ns);
  343. return UA_STATUSCODE_BADNODEIDEXISTS;
  344. }
  345. /* Copy the NodeId */
  346. UA_StatusCode retval = UA_STATUSCODE_GOOD;
  347. if(addedNodeId) {
  348. retval = UA_NodeId_copy(&node->nodeId, addedNodeId);
  349. if(retval != UA_STATUSCODE_GOOD) {
  350. deleteEntry(container_of(node, UA_NodeMapEntry, node));
  351. END_CRITSECT(ns);
  352. return retval;
  353. }
  354. }
  355. /* Insert the node */
  356. UA_NodeMapEntry *oldEntryContainer = *slot;
  357. UA_NodeMapEntry *newEntryContainer = container_of(node, UA_NodeMapEntry, node);
  358. if(oldEntryContainer > UA_NODEMAP_TOMBSTONE ||
  359. UA_atomic_cmpxchg((void**)slot, oldEntryContainer,
  360. newEntryContainer) != oldEntryContainer) {
  361. deleteEntry(container_of(node, UA_NodeMapEntry, node));
  362. END_CRITSECT(ns);
  363. return UA_STATUSCODE_BADNODEIDEXISTS;
  364. }
  365. ++ns->count;
  366. END_CRITSECT(ns);
  367. return retval;
  368. }
  369. static UA_StatusCode
  370. UA_NodeMap_replaceNode(void *context, UA_Node *node) {
  371. UA_NodeMap *ns = (UA_NodeMap*)context;
  372. BEGIN_CRITSECT(ns);
  373. /* Find the node */
  374. UA_NodeMapEntry **slot = findOccupiedSlot(ns, &node->nodeId);
  375. if(!slot) {
  376. END_CRITSECT(ns);
  377. return UA_STATUSCODE_BADNODEIDUNKNOWN;
  378. }
  379. UA_NodeMapEntry *newEntryContainer = container_of(node, UA_NodeMapEntry, node);
  380. UA_NodeMapEntry *oldEntryContainer = *slot;
  381. /* The node was already updated since the copy was made? */
  382. if(oldEntryContainer != newEntryContainer->orig) {
  383. deleteEntry(newEntryContainer);
  384. END_CRITSECT(ns);
  385. return UA_STATUSCODE_BADINTERNALERROR;
  386. }
  387. /* Replace the entry with an atomic operation */
  388. if(UA_atomic_cmpxchg((void**)slot, oldEntryContainer,
  389. newEntryContainer) != oldEntryContainer) {
  390. deleteEntry(newEntryContainer);
  391. END_CRITSECT(ns);
  392. return UA_STATUSCODE_BADINTERNALERROR;
  393. }
  394. oldEntryContainer->deleted = true;
  395. cleanupEntry(oldEntryContainer);
  396. END_CRITSECT(ns);
  397. return UA_STATUSCODE_GOOD;
  398. }
  399. static void
  400. UA_NodeMap_iterate(void *context, void *visitorContext,
  401. UA_NodestoreVisitor visitor) {
  402. UA_NodeMap *ns = (UA_NodeMap*)context;
  403. BEGIN_CRITSECT(ns);
  404. for(UA_UInt32 i = 0; i < ns->size; ++i) {
  405. if(ns->entries[i] > UA_NODEMAP_TOMBSTONE) {
  406. END_CRITSECT(ns);
  407. UA_NodeMapEntry *entry = ns->entries[i];
  408. entry->refCount++;
  409. visitor(visitorContext, &entry->node);
  410. entry->refCount--;
  411. cleanupEntry(entry);
  412. BEGIN_CRITSECT(ns);
  413. }
  414. }
  415. END_CRITSECT(ns);
  416. }
  417. static void
  418. UA_NodeMap_delete(void *context) {
  419. UA_NodeMap *ns = (UA_NodeMap*)context;
  420. #ifdef UA_ENABLE_MULTITHREADING
  421. pthread_mutex_destroy(&ns->mutex);
  422. #endif
  423. UA_UInt32 size = ns->size;
  424. UA_NodeMapEntry **entries = ns->entries;
  425. for(UA_UInt32 i = 0; i < size; ++i) {
  426. if(entries[i] > UA_NODEMAP_TOMBSTONE) {
  427. /* On debugging builds, check that all nodes were release */
  428. UA_assert(entries[i]->refCount == 0);
  429. /* Delete the node */
  430. deleteEntry(entries[i]);
  431. }
  432. }
  433. UA_free(ns->entries);
  434. UA_free(ns);
  435. }
  436. UA_StatusCode
  437. UA_Nodestore_default_new(UA_Nodestore *ns) {
  438. /* Allocate and initialize the nodemap */
  439. UA_NodeMap *nodemap = (UA_NodeMap*)UA_malloc(sizeof(UA_NodeMap));
  440. if(!nodemap)
  441. return UA_STATUSCODE_BADOUTOFMEMORY;
  442. nodemap->sizePrimeIndex = higher_prime_index(UA_NODEMAP_MINSIZE);
  443. nodemap->size = primes[nodemap->sizePrimeIndex];
  444. nodemap->count = 0;
  445. nodemap->entries = (UA_NodeMapEntry**)
  446. UA_calloc(nodemap->size, sizeof(UA_NodeMapEntry*));
  447. if(!nodemap->entries) {
  448. UA_free(nodemap);
  449. return UA_STATUSCODE_BADOUTOFMEMORY;
  450. }
  451. #ifdef UA_ENABLE_MULTITHREADING
  452. pthread_mutex_init(&nodemap->mutex, NULL);
  453. #endif
  454. /* Populate the nodestore */
  455. ns->context = nodemap;
  456. ns->deleteNodestore = UA_NodeMap_delete;
  457. ns->inPlaceEditAllowed = true;
  458. ns->newNode = UA_NodeMap_newNode;
  459. ns->deleteNode = UA_NodeMap_deleteNode;
  460. ns->getNode = UA_NodeMap_getNode;
  461. ns->releaseNode = UA_NodeMap_releaseNode;
  462. ns->getNodeCopy = UA_NodeMap_getNodeCopy;
  463. ns->insertNode = UA_NodeMap_insertNode;
  464. ns->replaceNode = UA_NodeMap_replaceNode;
  465. ns->removeNode = UA_NodeMap_removeNode;
  466. ns->iterate = UA_NodeMap_iterate;
  467. return UA_STATUSCODE_GOOD;
  468. }