ua_server_worker.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. #include "ua_util.h"
  2. #include "ua_server_internal.h"
  3. #if defined(__APPLE__) || defined(__MACH__)
  4. #include <mach/clock.h>
  5. #include <mach/mach.h>
  6. #endif
  7. /**
  8. * There are four types of job execution:
  9. *
  10. * 1. Normal jobs (dispatched to worker threads if multithreading is activated)
  11. *
  12. * 2. Repeated jobs with a repetition interval (dispatched to worker threads)
  13. *
  14. * 3. Mainloop jobs are executed (once) from the mainloop and not in the worker threads. The server
  15. * contains a stack structure where all threads can add mainloop jobs for the next mainloop
  16. * iteration. This is used e.g. to trigger adding and removing repeated jobs without blocking the
  17. * mainloop.
  18. *
  19. * 4. Delayed jobs are executed once in a worker thread. But only when all normal jobs that were
  20. * dispatched earlier have been executed. This is achieved by a counter in the worker threads. We
  21. * compute from the counter if all previous jobs have finished. The delay can be very long, since we
  22. * try to not interfere too much with normal execution. A use case is to eventually free obsolete
  23. * structures that _could_ still be accessed from concurrent threads.
  24. *
  25. * - Remove the entry from the list
  26. * - mark it as "dead" with an atomic operation
  27. * - add a delayed job that frees the memory when all concurrent operations have completed
  28. *
  29. * This approach to concurrently accessible memory is known as epoch based reclamation [1]. According to
  30. * [2], it performs competitively well on many-core systems. Our version of EBR does however not require
  31. * a global epoch. Instead, every worker thread has its own epoch counter that we observe for changes.
  32. *
  33. * [1] Fraser, K. 2003. Practical lock freedom. Ph.D. thesis. Computer Laboratory, University of Cambridge.
  34. * [2] Hart, T. E., McKenney, P. E., Brown, A. D., & Walpole, J. (2007). Performance of memory reclamation
  35. * for lockless synchronization. Journal of Parallel and Distributed Computing, 67(12), 1270-1285.
  36. *
  37. *
  38. */
  39. #define MAXTIMEOUT 50000 // max timeout in microsec until the next main loop iteration
  40. #define BATCHSIZE 20 // max number of jobs that are dispatched at once to workers
  41. /**
  42. * server: UA server context
  43. * jobs: pointer to array of jobs or NULL if jobsSize == -1
  44. * jobsSize: nr. of valid jobs or -1
  45. */
  46. static void processJobs(UA_Server *server, UA_Job *jobs, UA_Int32 jobsSize) {
  47. for (UA_Int32 i = 0; i < jobsSize; i++) {
  48. UA_Job *job = &jobs[i];
  49. switch(job->type) {
  50. case UA_JOBTYPE_NOTHING:
  51. break;
  52. case UA_JOBTYPE_DETACHCONNECTION:
  53. UA_Connection_detachSecureChannel(job->job.closeConnection);
  54. break;
  55. case UA_JOBTYPE_BINARYMESSAGE_NETWORKLAYER:
  56. UA_Server_processBinaryMessage(server, job->job.binaryMessage.connection,
  57. &job->job.binaryMessage.message);
  58. UA_Connection *connection = job->job.binaryMessage.connection;
  59. connection->releaseRecvBuffer(connection, &job->job.binaryMessage.message);
  60. break;
  61. case UA_JOBTYPE_BINARYMESSAGE_ALLOCATED:
  62. UA_Server_processBinaryMessage(server, job->job.binaryMessage.connection,
  63. &job->job.binaryMessage.message);
  64. UA_ByteString_deleteMembers(&job->job.binaryMessage.message);
  65. break;
  66. case UA_JOBTYPE_METHODCALL:
  67. case UA_JOBTYPE_METHODCALL_DELAYED:
  68. job->job.methodCall.method(server, job->job.methodCall.data);
  69. break;
  70. default:
  71. UA_LOG_WARNING(server->logger, UA_LOGCATEGORY_SERVER, "Trying to execute a job of unknown type");
  72. break;
  73. }
  74. }
  75. }
  76. /*******************************/
  77. /* Worker Threads and Dispatch */
  78. /*******************************/
  79. #ifdef UA_MULTITHREADING
  80. struct MainLoopJob {
  81. struct cds_lfs_node node;
  82. UA_Job job;
  83. };
  84. /** Entry in the dispatch queue */
  85. struct DispatchJobsList {
  86. struct cds_wfcq_node node; // node for the queue
  87. size_t jobsSize;
  88. UA_Job *jobs;
  89. };
  90. /** Dispatch jobs to workers. Slices the job array up if it contains more than BATCHSIZE items. The jobs
  91. array is freed in the worker threads. */
  92. static void dispatchJobs(UA_Server *server, UA_Job *jobs, size_t jobsSize) {
  93. size_t startIndex = jobsSize; // start at the end
  94. while(jobsSize > 0) {
  95. size_t size = BATCHSIZE;
  96. if(size > jobsSize)
  97. size = jobsSize;
  98. startIndex = startIndex - size;
  99. struct DispatchJobsList *wln = UA_malloc(sizeof(struct DispatchJobsList));
  100. if(startIndex > 0) {
  101. wln->jobs = UA_malloc(size * sizeof(UA_Job));
  102. UA_memcpy(wln->jobs, &jobs[startIndex], size * sizeof(UA_Job));
  103. wln->jobsSize = size;
  104. } else {
  105. /* forward the original array */
  106. wln->jobsSize = size;
  107. wln->jobs = jobs;
  108. }
  109. cds_wfcq_node_init(&wln->node);
  110. cds_wfcq_enqueue(&server->dispatchQueue_head, &server->dispatchQueue_tail, &wln->node);
  111. jobsSize -= size;
  112. }
  113. }
  114. // throwaway struct to bring data into the worker threads
  115. struct workerStartData {
  116. UA_Server *server;
  117. UA_UInt32 **workerCounter;
  118. };
  119. /** Waits until jobs arrive in the dispatch queue and processes them. */
  120. static void * workerLoop(struct workerStartData *startInfo) {
  121. /* Initialized the (thread local) random seed */
  122. UA_random_seed((uintptr_t)startInfo);
  123. rcu_register_thread();
  124. UA_UInt32 *c = UA_malloc(sizeof(UA_UInt32));
  125. uatomic_set(c, 0);
  126. *startInfo->workerCounter = c;
  127. UA_Server *server = startInfo->server;
  128. UA_free(startInfo);
  129. pthread_mutex_t mutex; // required for the condition variable
  130. pthread_mutex_init(&mutex,0);
  131. pthread_mutex_lock(&mutex);
  132. struct timespec to;
  133. while(*server->running) {
  134. struct DispatchJobsList *wln = (struct DispatchJobsList*)
  135. cds_wfcq_dequeue_blocking(&server->dispatchQueue_head, &server->dispatchQueue_tail);
  136. if(wln) {
  137. processJobs(server, wln->jobs, wln->jobsSize);
  138. UA_free(wln->jobs);
  139. UA_free(wln);
  140. } else {
  141. /* sleep until a work arrives (and wakes up all worker threads) */
  142. #if defined(__APPLE__) || defined(__MACH__) // OS X does not have clock_gettime, use clock_get_time
  143. clock_serv_t cclock;
  144. mach_timespec_t mts;
  145. host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
  146. clock_get_time(cclock, &mts);
  147. mach_port_deallocate(mach_task_self(), cclock);
  148. to.tv_sec = mts.tv_sec;
  149. to.tv_nsec = mts.tv_nsec;
  150. #else
  151. clock_gettime(CLOCK_REALTIME, &to);
  152. #endif
  153. to.tv_sec += 2;
  154. pthread_cond_timedwait(&server->dispatchQueue_condition, &mutex, &to);
  155. }
  156. uatomic_inc(c); // increase the workerCounter;
  157. }
  158. pthread_mutex_unlock(&mutex);
  159. pthread_mutex_destroy(&mutex);
  160. rcu_barrier(); // wait for all scheduled call_rcu work to complete
  161. rcu_unregister_thread();
  162. /* we need to return _something_ for pthreads */
  163. return UA_NULL;
  164. }
  165. static void emptyDispatchQueue(UA_Server *server) {
  166. while(!cds_wfcq_empty(&server->dispatchQueue_head, &server->dispatchQueue_tail)) {
  167. struct DispatchJobsList *wln = (struct DispatchJobsList*)
  168. cds_wfcq_dequeue_blocking(&server->dispatchQueue_head, &server->dispatchQueue_tail);
  169. processJobs(server, wln->jobs, wln->jobsSize);
  170. UA_free(wln->jobs);
  171. UA_free(wln);
  172. }
  173. }
  174. #endif
  175. /*****************/
  176. /* Repeated Jobs */
  177. /*****************/
  178. struct IdentifiedJob {
  179. UA_Job job;
  180. UA_Guid id;
  181. };
  182. /**
  183. * The RepeatedJobs structure contains an array of jobs that are either executed with the same
  184. * repetition interval. The linked list is sorted, so we can stop traversing when the first element
  185. * has nextTime > now.
  186. */
  187. struct RepeatedJobs {
  188. LIST_ENTRY(RepeatedJobs) pointers; ///> Links to the next list of repeated jobs (with a different) interval
  189. UA_DateTime nextTime; ///> The next time when the jobs are to be executed
  190. UA_UInt32 interval; ///> Interval in 100ns resolution
  191. size_t jobsSize; ///> Number of jobs contained
  192. struct IdentifiedJob jobs[]; ///> The jobs. This is not a pointer, instead the struct is variable sized.
  193. };
  194. /* throwaway struct for the mainloop callback */
  195. struct AddRepeatedJob {
  196. struct IdentifiedJob job;
  197. UA_UInt32 interval;
  198. };
  199. /* internal. call only from the main loop. */
  200. static UA_StatusCode addRepeatedJob(UA_Server *server, struct AddRepeatedJob * UA_RESTRICT arw) {
  201. struct RepeatedJobs *matchingTw = UA_NULL; // add the item here
  202. struct RepeatedJobs *lastTw = UA_NULL; // if there is no repeated job, add a new one this entry
  203. struct RepeatedJobs *tempTw;
  204. /* search for matching entry */
  205. UA_DateTime firstTime = UA_DateTime_now() + arw->interval;
  206. tempTw = LIST_FIRST(&server->repeatedJobs);
  207. while(tempTw) {
  208. if(arw->interval == tempTw->interval) {
  209. matchingTw = tempTw;
  210. break;
  211. }
  212. if(tempTw->nextTime > firstTime)
  213. break;
  214. lastTw = tempTw;
  215. tempTw = LIST_NEXT(lastTw, pointers);
  216. }
  217. if(matchingTw) {
  218. /* append to matching entry */
  219. matchingTw = UA_realloc(matchingTw, sizeof(struct RepeatedJobs) +
  220. (sizeof(struct IdentifiedJob) * (matchingTw->jobsSize + 1)));
  221. if(!matchingTw) {
  222. #ifdef UA_MULTITHREADING
  223. UA_free(arw);
  224. #endif
  225. return UA_STATUSCODE_BADOUTOFMEMORY;
  226. }
  227. /* point the realloced struct */
  228. if(matchingTw->pointers.le_next)
  229. matchingTw->pointers.le_next->pointers.le_prev = &matchingTw->pointers.le_next;
  230. if(matchingTw->pointers.le_prev)
  231. *matchingTw->pointers.le_prev = matchingTw;
  232. } else {
  233. /* create a new entry */
  234. matchingTw = UA_malloc(sizeof(struct RepeatedJobs) + sizeof(struct IdentifiedJob));
  235. if(!matchingTw) {
  236. #ifdef UA_MULTITHREADING
  237. UA_free(arw);
  238. #endif
  239. return UA_STATUSCODE_BADOUTOFMEMORY;
  240. }
  241. matchingTw->jobsSize = 0;
  242. matchingTw->nextTime = firstTime;
  243. matchingTw->interval = arw->interval;
  244. if(lastTw)
  245. LIST_INSERT_AFTER(lastTw, matchingTw, pointers);
  246. else
  247. LIST_INSERT_HEAD(&server->repeatedJobs, matchingTw, pointers);
  248. }
  249. matchingTw->jobs[matchingTw->jobsSize] = arw->job;
  250. matchingTw->jobsSize++;
  251. #ifdef UA_MULTITHREADING
  252. UA_free(arw);
  253. #endif
  254. return UA_STATUSCODE_GOOD;
  255. }
  256. UA_StatusCode UA_Server_addRepeatedJob(UA_Server *server, UA_Job job, UA_UInt32 interval, UA_Guid *jobId) {
  257. /* the interval needs to be at least 5ms */
  258. if(interval < 5)
  259. return UA_STATUSCODE_BADINTERNALERROR;
  260. interval *= 10000; // from ms to 100ns resolution
  261. #ifdef UA_MULTITHREADING
  262. struct AddRepeatedJob *arw = UA_malloc(sizeof(struct AddRepeatedJob));
  263. if(!arw)
  264. return UA_STATUSCODE_BADOUTOFMEMORY;
  265. arw->interval = interval;
  266. arw->job.job = job;
  267. if(jobId) {
  268. arw->job.id = UA_Guid_random(&server->random_seed);
  269. *jobId = arw->job.id;
  270. } else
  271. UA_Guid_init(&arw->job.id);
  272. struct MainLoopJob *mlw = UA_malloc(sizeof(struct MainLoopJob));
  273. if(!mlw) {
  274. UA_free(arw);
  275. return UA_STATUSCODE_BADOUTOFMEMORY;
  276. }
  277. mlw->job = (UA_Job) {
  278. .type = UA_JOBTYPE_METHODCALL,
  279. .job.methodCall = {.data = arw, .method = (void (*)(UA_Server*, void*))addRepeatedJob}};
  280. cds_lfs_push(&server->mainLoopJobs, &mlw->node);
  281. #else
  282. struct AddRepeatedJob arw;
  283. arw.interval = interval;
  284. arw.job.job = job;
  285. if(jobId) {
  286. arw.job.id = UA_Guid_random(&server->random_seed);
  287. *jobId = arw.job.id;
  288. } else
  289. UA_Guid_init(&arw.job.id);
  290. addRepeatedJob(server, &arw);
  291. #endif
  292. return UA_STATUSCODE_GOOD;
  293. }
  294. /* Returns the timeout until the next repeated job in ms */
  295. static UA_UInt16 processRepeatedJobs(UA_Server *server) {
  296. UA_DateTime current = UA_DateTime_now();
  297. struct RepeatedJobs *next = LIST_FIRST(&server->repeatedJobs);
  298. struct RepeatedJobs *tw = UA_NULL;
  299. while(next) {
  300. tw = next;
  301. if(tw->nextTime > current)
  302. break;
  303. next = LIST_NEXT(tw, pointers);
  304. #ifdef UA_MULTITHREADING
  305. // copy the entry and insert at the new location
  306. UA_Job *jobsCopy = UA_malloc(sizeof(UA_Job) * tw->jobsSize);
  307. if(!jobsCopy) {
  308. UA_LOG_ERROR(server->logger, UA_LOGCATEGORY_SERVER, "Not enough memory to dispatch delayed jobs");
  309. break;
  310. }
  311. for(size_t i=0;i<tw->jobsSize;i++)
  312. jobsCopy[i] = tw->jobs[i].job;
  313. dispatchJobs(server, jobsCopy, tw->jobsSize); // frees the job pointer
  314. #else
  315. for(size_t i=0;i<tw->jobsSize;i++)
  316. processJobs(server, &tw->jobs[i].job, 1); // does not free the job ptr
  317. #endif
  318. tw->nextTime += tw->interval;
  319. struct RepeatedJobs *prevTw = tw; // after which tw do we insert?
  320. while(UA_TRUE) {
  321. struct RepeatedJobs *n = LIST_NEXT(prevTw, pointers);
  322. if(!n || n->nextTime > tw->nextTime)
  323. break;
  324. prevTw = n;
  325. }
  326. if(prevTw != tw) {
  327. LIST_REMOVE(tw, pointers);
  328. LIST_INSERT_AFTER(prevTw, tw, pointers);
  329. }
  330. }
  331. // check if the next repeated job is sooner than the usual timeout
  332. // calc in 32 bit must be ok
  333. struct RepeatedJobs *first = LIST_FIRST(&server->repeatedJobs);
  334. UA_UInt32 timeout = MAXTIMEOUT;
  335. if(first) {
  336. timeout = (UA_UInt32)((first->nextTime - current) / 10);
  337. if(timeout > MAXTIMEOUT)
  338. return MAXTIMEOUT;
  339. }
  340. return timeout;
  341. }
  342. /* Call this function only from the main loop! */
  343. static void removeRepeatedJob(UA_Server *server, UA_Guid *jobId) {
  344. struct RepeatedJobs *tw;
  345. LIST_FOREACH(tw, &server->repeatedJobs, pointers) {
  346. for(size_t i = 0; i < tw->jobsSize; i++) {
  347. if(!UA_Guid_equal(jobId, &tw->jobs[i].id))
  348. continue;
  349. if(tw->jobsSize == 1) {
  350. LIST_REMOVE(tw, pointers);
  351. UA_free(tw);
  352. } else {
  353. tw->jobsSize--;
  354. tw->jobs[i] = tw->jobs[tw->jobsSize]; // move the last entry to overwrite
  355. }
  356. goto finish; // ugly break
  357. }
  358. }
  359. finish:
  360. #ifdef UA_MULTITHREADING
  361. UA_free(jobId);
  362. #endif
  363. return;
  364. }
  365. UA_StatusCode UA_Server_removeRepeatedJob(UA_Server *server, UA_Guid jobId) {
  366. #ifdef UA_MULTITHREADING
  367. UA_Guid *idptr = UA_malloc(sizeof(UA_Guid));
  368. if(!idptr)
  369. return UA_STATUSCODE_BADOUTOFMEMORY;
  370. *idptr = jobId;
  371. // dispatch to the mainloopjobs stack
  372. struct MainLoopJob *mlw = UA_malloc(sizeof(struct MainLoopJob));
  373. mlw->job = (UA_Job) {
  374. .type = UA_JOBTYPE_METHODCALL,
  375. .job.methodCall = {.data = idptr, .method = (void (*)(UA_Server*, void*))removeRepeatedJob}};
  376. cds_lfs_push(&server->mainLoopJobs, &mlw->node);
  377. #else
  378. removeRepeatedJob(server, &jobId);
  379. #endif
  380. return UA_STATUSCODE_GOOD;
  381. }
  382. void UA_Server_deleteAllRepeatedJobs(UA_Server *server) {
  383. struct RepeatedJobs *current;
  384. while((current = LIST_FIRST(&server->repeatedJobs))) {
  385. LIST_REMOVE(current, pointers);
  386. UA_free(current);
  387. }
  388. }
  389. /****************/
  390. /* Delayed Jobs */
  391. /****************/
  392. #ifdef UA_MULTITHREADING
  393. #define DELAYEDJOBSSIZE 100 // Collect delayed jobs until we have DELAYEDWORKSIZE items
  394. struct DelayedJobs {
  395. struct DelayedJobs *next;
  396. UA_UInt32 *workerCounters; // initially UA_NULL until the counter are set
  397. UA_UInt32 jobsCount; // the size of the array is DELAYEDJOBSSIZE, the count may be less
  398. UA_Job jobs[DELAYEDJOBSSIZE]; // when it runs full, a new delayedJobs entry is created
  399. };
  400. /* Dispatched as an ordinary job when the DelayedJobs list is full */
  401. static void getCounters(UA_Server *server, struct DelayedJobs *delayed) {
  402. UA_UInt32 *counters = UA_malloc(server->nThreads * sizeof(UA_UInt32));
  403. for(UA_UInt16 i = 0;i<server->nThreads;i++)
  404. counters[i] = *server->workerCounters[i];
  405. delayed->workerCounters = counters;
  406. }
  407. // Call from the main thread only. This is the only function that modifies
  408. // server->delayedWork. processDelayedWorkQueue modifies the "next" (after the
  409. // head).
  410. static void addDelayedJob(UA_Server *server, UA_Job *job) {
  411. struct DelayedJobs *dj = server->delayedJobs;
  412. if(!dj || dj->jobsCount >= DELAYEDJOBSSIZE) {
  413. /* create a new DelayedJobs and add it to the linked list */
  414. dj = UA_malloc(sizeof(struct DelayedJobs));
  415. if(!dj) {
  416. UA_LOG_ERROR(server->logger, UA_LOGCATEGORY_SERVER, "Not enough memory to add a delayed job");
  417. return;
  418. }
  419. dj->jobsCount = 0;
  420. dj->workerCounters = UA_NULL;
  421. dj->next = server->delayedJobs;
  422. server->delayedJobs = dj;
  423. /* dispatch a method that sets the counter for the full list that comes afterwards */
  424. if(dj->next) {
  425. UA_Job *setCounter = UA_malloc(sizeof(UA_Job));
  426. *setCounter = (UA_Job) {.type = UA_JOBTYPE_METHODCALL, .job.methodCall =
  427. {.method = (void (*)(UA_Server*, void*))getCounters, .data = dj->next}};
  428. dispatchJobs(server, setCounter, 1);
  429. }
  430. }
  431. dj->jobs[dj->jobsCount] = *job;
  432. dj->jobsCount++;
  433. }
  434. static void addDelayedJobAsync(UA_Server *server, UA_Job *job) {
  435. addDelayedJob(server, job);
  436. UA_free(job);
  437. }
  438. UA_StatusCode UA_Server_addDelayedJob(UA_Server *server, UA_Job job) {
  439. UA_Job *j = UA_malloc(sizeof(UA_Job));
  440. if(!j)
  441. return UA_STATUSCODE_BADOUTOFMEMORY;
  442. *j = job;
  443. struct MainLoopJob *mlw = UA_malloc(sizeof(struct MainLoopJob));
  444. mlw->job = (UA_Job) {.type = UA_JOBTYPE_METHODCALL, .job.methodCall =
  445. {.data = j, .method = (void (*)(UA_Server*, void*))addDelayedJobAsync}};
  446. cds_lfs_push(&server->mainLoopJobs, &mlw->node);
  447. return UA_STATUSCODE_GOOD;
  448. }
  449. /* Find out which delayed jobs can be executed now */
  450. static void dispatchDelayedJobs(UA_Server *server, void *data /* not used, but needed for the signature*/) {
  451. /* start at the second */
  452. struct DelayedJobs *dw = server->delayedJobs, *beforedw = dw;
  453. if(dw)
  454. dw = dw->next;
  455. /* find the first delayedwork where the counters have been set and have moved */
  456. while(dw) {
  457. if(!dw->workerCounters) {
  458. beforedw = dw;
  459. dw = dw->next;
  460. continue;
  461. }
  462. UA_Boolean allMoved = UA_TRUE;
  463. for(UA_UInt16 i=0;i<server->nThreads;i++) {
  464. if(dw->workerCounters[i] == *server->workerCounters[i]) {
  465. allMoved = UA_FALSE;
  466. break;
  467. }
  468. }
  469. if(allMoved)
  470. break;
  471. beforedw = dw;
  472. dw = dw->next;
  473. }
  474. /* process and free all delayed jobs from here on */
  475. while(dw) {
  476. processJobs(server, dw->jobs, dw->jobsCount);
  477. struct DelayedJobs *next = uatomic_xchg(&beforedw->next, UA_NULL);
  478. UA_free(dw);
  479. UA_free(dw->workerCounters);
  480. dw = next;
  481. }
  482. }
  483. #endif
  484. /********************/
  485. /* Main Server Loop */
  486. /********************/
  487. #ifdef UA_MULTITHREADING
  488. static void processMainLoopJobs(UA_Server *server) {
  489. /* no synchronization required if we only use push and pop_all */
  490. struct cds_lfs_head *head = __cds_lfs_pop_all(&server->mainLoopJobs);
  491. if(!head)
  492. return;
  493. struct MainLoopJob *mlw = (struct MainLoopJob*)&head->node;
  494. struct MainLoopJob *next;
  495. do {
  496. processJobs(server, &mlw->job, 1);
  497. next = (struct MainLoopJob*)mlw->node.next;
  498. UA_free(mlw);
  499. } while((mlw = next));
  500. //UA_free(head);
  501. }
  502. #endif
  503. UA_StatusCode UA_Server_run_startup(UA_Server *server, UA_UInt16 nThreads, UA_Boolean *running) {
  504. UA_StatusCode result = UA_STATUSCODE_GOOD;
  505. #ifdef UA_MULTITHREADING
  506. /* Prepare the worker threads */
  507. server->running = running; // the threads need to access the variable
  508. server->nThreads = nThreads;
  509. pthread_cond_init(&server->dispatchQueue_condition, 0);
  510. server->thr = UA_malloc(nThreads * sizeof(pthread_t));
  511. server->workerCounters = UA_malloc(nThreads * sizeof(UA_UInt32 *));
  512. for(UA_UInt32 i=0;i<nThreads;i++) {
  513. struct workerStartData *startData = UA_malloc(sizeof(struct workerStartData));
  514. startData->server = server;
  515. startData->workerCounter = &server->workerCounters[i];
  516. pthread_create(&server->thr[i], UA_NULL, (void* (*)(void*))workerLoop, startData);
  517. }
  518. /* try to execute the delayed callbacks every 10 sec */
  519. UA_Job processDelayed = {.type = UA_JOBTYPE_METHODCALL,
  520. .job.methodCall = {.method = dispatchDelayedJobs, .data = UA_NULL} };
  521. UA_Server_addRepeatedJob(server, processDelayed, 10000, UA_NULL);
  522. #endif
  523. /* Start the networklayers */
  524. for(size_t i = 0; i < server->networkLayersSize; i++)
  525. result |= server->networkLayers[i]->start(server->networkLayers[i], server->logger);
  526. return result;
  527. }
  528. UA_StatusCode UA_Server_run_mainloop(UA_Server *server, UA_Boolean *running) {
  529. #ifdef UA_MULTITHREADING
  530. /* Run Work in the main loop */
  531. processMainLoopJobs(server);
  532. #endif
  533. /* Process repeated work */
  534. UA_UInt16 timeout = processRepeatedJobs(server);
  535. /* Get work from the networklayer */
  536. for(size_t i = 0; i < server->networkLayersSize; i++) {
  537. UA_ServerNetworkLayer *nl = server->networkLayers[i];
  538. UA_Job *jobs;
  539. UA_Int32 jobsSize;
  540. if(*running) {
  541. if(i == server->networkLayersSize-1)
  542. jobsSize = nl->getJobs(nl, &jobs, timeout);
  543. else
  544. jobsSize = nl->getJobs(nl, &jobs, 0);
  545. } else
  546. jobsSize = server->networkLayers[i]->stop(nl, &jobs);
  547. #ifdef UA_MULTITHREADING
  548. /* Filter out delayed work */
  549. for(UA_Int32 k=0;k<jobsSize;k++) {
  550. if(jobs[k].type != UA_JOBTYPE_METHODCALL_DELAYED)
  551. continue;
  552. addDelayedJob(server, &jobs[k]);
  553. jobs[k].type = UA_JOBTYPE_NOTHING;
  554. }
  555. /* Dispatch work to the worker threads */
  556. dispatchJobs(server, jobs, jobsSize);
  557. /* Trigger sleeping worker threads */
  558. if(jobsSize > 0)
  559. pthread_cond_broadcast(&server->dispatchQueue_condition);
  560. #else
  561. processJobs(server, jobs, jobsSize);
  562. if(jobsSize > 0)
  563. UA_free(jobs);
  564. #endif
  565. }
  566. return UA_STATUSCODE_GOOD;
  567. }
  568. UA_StatusCode UA_Server_run_shutdown(UA_Server *server, UA_UInt16 nThreads){
  569. #ifdef UA_MULTITHREADING
  570. /* Wait for all worker threads to finish */
  571. for(UA_UInt32 i=0;i<nThreads;i++) {
  572. pthread_join(server->thr[i], UA_NULL);
  573. UA_free(server->workerCounters[i]);
  574. }
  575. UA_free(server->workerCounters);
  576. UA_free(server->thr);
  577. /* Manually finish the work still enqueued */
  578. emptyDispatchQueue(server);
  579. /* Process the remaining delayed work */
  580. struct DelayedJobs *dw = server->delayedJobs;
  581. while(dw) {
  582. processJobs(server, dw->jobs, dw->jobsCount);
  583. struct DelayedJobs *next = dw->next;
  584. UA_free(dw->workerCounters);
  585. UA_free(dw);
  586. dw = next;
  587. }
  588. #endif
  589. return UA_STATUSCODE_GOOD;
  590. }
  591. UA_StatusCode UA_Server_run(UA_Server *server, UA_UInt16 nThreads, UA_Boolean *running) {
  592. if(UA_STATUSCODE_GOOD == UA_Server_run_startup(server, nThreads, running)){
  593. while(*running) {
  594. UA_Server_run_mainloop(server, running);
  595. }
  596. }
  597. UA_Server_run_shutdown(server, nThreads);
  598. return UA_STATUSCODE_GOOD;
  599. }