ua_server_worker.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  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 *tw = UA_NULL;
  298. while((tw = LIST_FIRST(&server->repeatedJobs)) != UA_NULL) {
  299. if(tw->nextTime > current)
  300. break;
  301. #ifdef UA_MULTITHREADING
  302. // copy the entry and insert at the new location
  303. UA_Job *jobsCopy = UA_malloc(sizeof(UA_Job) * tw->jobsSize);
  304. if(!jobsCopy) {
  305. UA_LOG_ERROR(server->logger, UA_LOGCATEGORY_SERVER, "Not enough memory to dispatch delayed jobs");
  306. break;
  307. }
  308. for(size_t i=0;i<tw->jobsSize;i++)
  309. jobsCopy[i] = tw->jobs[i].job;
  310. dispatchJobs(server, jobsCopy, tw->jobsSize); // frees the job pointer
  311. #else
  312. for(size_t i=0;i<tw->jobsSize;i++)
  313. //processJobs may sort the list but dont delete entries
  314. processJobs(server, &tw->jobs[i].job, 1); // does not free the job ptr
  315. #endif
  316. tw->nextTime += tw->interval;
  317. //start iterating the list from the beginning
  318. struct RepeatedJobs *prevTw = LIST_FIRST(&server->repeatedJobs); // after which tw do we insert?
  319. while(UA_TRUE) {
  320. struct RepeatedJobs *n = LIST_NEXT(prevTw, pointers);
  321. if(!n || n->nextTime > tw->nextTime)
  322. break;
  323. prevTw = n;
  324. }
  325. if(prevTw != tw) {
  326. LIST_REMOVE(tw, pointers);
  327. LIST_INSERT_AFTER(prevTw, tw, pointers);
  328. }
  329. }
  330. // check if the next repeated job is sooner than the usual timeout
  331. // calc in 32 bit must be ok
  332. struct RepeatedJobs *first = LIST_FIRST(&server->repeatedJobs);
  333. UA_UInt32 timeout = MAXTIMEOUT;
  334. if(first) {
  335. timeout = (UA_UInt32)((first->nextTime - current) / 10);
  336. if(timeout > MAXTIMEOUT)
  337. return MAXTIMEOUT;
  338. }
  339. return timeout;
  340. }
  341. /* Call this function only from the main loop! */
  342. static void removeRepeatedJob(UA_Server *server, UA_Guid *jobId) {
  343. struct RepeatedJobs *tw;
  344. LIST_FOREACH(tw, &server->repeatedJobs, pointers) {
  345. for(size_t i = 0; i < tw->jobsSize; i++) {
  346. if(!UA_Guid_equal(jobId, &tw->jobs[i].id))
  347. continue;
  348. if(tw->jobsSize == 1) {
  349. LIST_REMOVE(tw, pointers);
  350. UA_free(tw);
  351. } else {
  352. tw->jobsSize--;
  353. tw->jobs[i] = tw->jobs[tw->jobsSize]; // move the last entry to overwrite
  354. }
  355. goto finish; // ugly break
  356. }
  357. }
  358. finish:
  359. #ifdef UA_MULTITHREADING
  360. UA_free(jobId);
  361. #endif
  362. return;
  363. }
  364. UA_StatusCode UA_Server_removeRepeatedJob(UA_Server *server, UA_Guid jobId) {
  365. #ifdef UA_MULTITHREADING
  366. UA_Guid *idptr = UA_malloc(sizeof(UA_Guid));
  367. if(!idptr)
  368. return UA_STATUSCODE_BADOUTOFMEMORY;
  369. *idptr = jobId;
  370. // dispatch to the mainloopjobs stack
  371. struct MainLoopJob *mlw = UA_malloc(sizeof(struct MainLoopJob));
  372. mlw->job = (UA_Job) {
  373. .type = UA_JOBTYPE_METHODCALL,
  374. .job.methodCall = {.data = idptr, .method = (void (*)(UA_Server*, void*))removeRepeatedJob}};
  375. cds_lfs_push(&server->mainLoopJobs, &mlw->node);
  376. #else
  377. removeRepeatedJob(server, &jobId);
  378. #endif
  379. return UA_STATUSCODE_GOOD;
  380. }
  381. void UA_Server_deleteAllRepeatedJobs(UA_Server *server) {
  382. struct RepeatedJobs *current;
  383. while((current = LIST_FIRST(&server->repeatedJobs))) {
  384. LIST_REMOVE(current, pointers);
  385. UA_free(current);
  386. }
  387. }
  388. /****************/
  389. /* Delayed Jobs */
  390. /****************/
  391. #ifdef UA_MULTITHREADING
  392. #define DELAYEDJOBSSIZE 100 // Collect delayed jobs until we have DELAYEDWORKSIZE items
  393. struct DelayedJobs {
  394. struct DelayedJobs *next;
  395. UA_UInt32 *workerCounters; // initially UA_NULL until the counter are set
  396. UA_UInt32 jobsCount; // the size of the array is DELAYEDJOBSSIZE, the count may be less
  397. UA_Job jobs[DELAYEDJOBSSIZE]; // when it runs full, a new delayedJobs entry is created
  398. };
  399. /* Dispatched as an ordinary job when the DelayedJobs list is full */
  400. static void getCounters(UA_Server *server, struct DelayedJobs *delayed) {
  401. UA_UInt32 *counters = UA_malloc(server->nThreads * sizeof(UA_UInt32));
  402. for(UA_UInt16 i = 0;i<server->nThreads;i++)
  403. counters[i] = *server->workerCounters[i];
  404. delayed->workerCounters = counters;
  405. }
  406. // Call from the main thread only. This is the only function that modifies
  407. // server->delayedWork. processDelayedWorkQueue modifies the "next" (after the
  408. // head).
  409. static void addDelayedJob(UA_Server *server, UA_Job *job) {
  410. struct DelayedJobs *dj = server->delayedJobs;
  411. if(!dj || dj->jobsCount >= DELAYEDJOBSSIZE) {
  412. /* create a new DelayedJobs and add it to the linked list */
  413. dj = UA_malloc(sizeof(struct DelayedJobs));
  414. if(!dj) {
  415. UA_LOG_ERROR(server->logger, UA_LOGCATEGORY_SERVER, "Not enough memory to add a delayed job");
  416. return;
  417. }
  418. dj->jobsCount = 0;
  419. dj->workerCounters = UA_NULL;
  420. dj->next = server->delayedJobs;
  421. server->delayedJobs = dj;
  422. /* dispatch a method that sets the counter for the full list that comes afterwards */
  423. if(dj->next) {
  424. UA_Job *setCounter = UA_malloc(sizeof(UA_Job));
  425. *setCounter = (UA_Job) {.type = UA_JOBTYPE_METHODCALL, .job.methodCall =
  426. {.method = (void (*)(UA_Server*, void*))getCounters, .data = dj->next}};
  427. dispatchJobs(server, setCounter, 1);
  428. }
  429. }
  430. dj->jobs[dj->jobsCount] = *job;
  431. dj->jobsCount++;
  432. }
  433. static void addDelayedJobAsync(UA_Server *server, UA_Job *job) {
  434. addDelayedJob(server, job);
  435. UA_free(job);
  436. }
  437. UA_StatusCode UA_Server_addDelayedJob(UA_Server *server, UA_Job job) {
  438. UA_Job *j = UA_malloc(sizeof(UA_Job));
  439. if(!j)
  440. return UA_STATUSCODE_BADOUTOFMEMORY;
  441. *j = job;
  442. struct MainLoopJob *mlw = UA_malloc(sizeof(struct MainLoopJob));
  443. mlw->job = (UA_Job) {.type = UA_JOBTYPE_METHODCALL, .job.methodCall =
  444. {.data = j, .method = (void (*)(UA_Server*, void*))addDelayedJobAsync}};
  445. cds_lfs_push(&server->mainLoopJobs, &mlw->node);
  446. return UA_STATUSCODE_GOOD;
  447. }
  448. /* Find out which delayed jobs can be executed now */
  449. static void dispatchDelayedJobs(UA_Server *server, void *data /* not used, but needed for the signature*/) {
  450. /* start at the second */
  451. struct DelayedJobs *dw = server->delayedJobs, *beforedw = dw;
  452. if(dw)
  453. dw = dw->next;
  454. /* find the first delayedwork where the counters have been set and have moved */
  455. while(dw) {
  456. if(!dw->workerCounters) {
  457. beforedw = dw;
  458. dw = dw->next;
  459. continue;
  460. }
  461. UA_Boolean allMoved = UA_TRUE;
  462. for(UA_UInt16 i=0;i<server->nThreads;i++) {
  463. if(dw->workerCounters[i] == *server->workerCounters[i]) {
  464. allMoved = UA_FALSE;
  465. break;
  466. }
  467. }
  468. if(allMoved)
  469. break;
  470. beforedw = dw;
  471. dw = dw->next;
  472. }
  473. /* process and free all delayed jobs from here on */
  474. while(dw) {
  475. processJobs(server, dw->jobs, dw->jobsCount);
  476. struct DelayedJobs *next = uatomic_xchg(&beforedw->next, UA_NULL);
  477. UA_free(dw);
  478. UA_free(dw->workerCounters);
  479. dw = next;
  480. }
  481. }
  482. #endif
  483. /********************/
  484. /* Main Server Loop */
  485. /********************/
  486. #ifdef UA_MULTITHREADING
  487. static void processMainLoopJobs(UA_Server *server) {
  488. /* no synchronization required if we only use push and pop_all */
  489. struct cds_lfs_head *head = __cds_lfs_pop_all(&server->mainLoopJobs);
  490. if(!head)
  491. return;
  492. struct MainLoopJob *mlw = (struct MainLoopJob*)&head->node;
  493. struct MainLoopJob *next;
  494. do {
  495. processJobs(server, &mlw->job, 1);
  496. next = (struct MainLoopJob*)mlw->node.next;
  497. UA_free(mlw);
  498. } while((mlw = next));
  499. //UA_free(head);
  500. }
  501. #endif
  502. UA_StatusCode UA_Server_run_startup(UA_Server *server, UA_UInt16 nThreads, UA_Boolean *running) {
  503. UA_StatusCode result = UA_STATUSCODE_GOOD;
  504. #ifdef UA_MULTITHREADING
  505. /* Prepare the worker threads */
  506. server->running = running; // the threads need to access the variable
  507. server->nThreads = nThreads;
  508. pthread_cond_init(&server->dispatchQueue_condition, 0);
  509. server->thr = UA_malloc(nThreads * sizeof(pthread_t));
  510. server->workerCounters = UA_malloc(nThreads * sizeof(UA_UInt32 *));
  511. for(UA_UInt32 i=0;i<nThreads;i++) {
  512. struct workerStartData *startData = UA_malloc(sizeof(struct workerStartData));
  513. startData->server = server;
  514. startData->workerCounter = &server->workerCounters[i];
  515. pthread_create(&server->thr[i], UA_NULL, (void* (*)(void*))workerLoop, startData);
  516. }
  517. /* try to execute the delayed callbacks every 10 sec */
  518. UA_Job processDelayed = {.type = UA_JOBTYPE_METHODCALL,
  519. .job.methodCall = {.method = dispatchDelayedJobs, .data = UA_NULL} };
  520. UA_Server_addRepeatedJob(server, processDelayed, 10000, UA_NULL);
  521. #endif
  522. /* Start the networklayers */
  523. for(size_t i = 0; i < server->networkLayersSize; i++)
  524. result |= server->networkLayers[i]->start(server->networkLayers[i], server->logger);
  525. return result;
  526. }
  527. UA_StatusCode UA_Server_run_mainloop(UA_Server *server, UA_Boolean *running) {
  528. #ifdef UA_MULTITHREADING
  529. /* Run Work in the main loop */
  530. processMainLoopJobs(server);
  531. #endif
  532. /* Process repeated work */
  533. UA_UInt16 timeout = processRepeatedJobs(server);
  534. /* Get work from the networklayer */
  535. for(size_t i = 0; i < server->networkLayersSize; i++) {
  536. UA_ServerNetworkLayer *nl = server->networkLayers[i];
  537. UA_Job *jobs;
  538. UA_Int32 jobsSize;
  539. if(*running) {
  540. if(i == server->networkLayersSize-1)
  541. jobsSize = nl->getJobs(nl, &jobs, timeout);
  542. else
  543. jobsSize = nl->getJobs(nl, &jobs, 0);
  544. } else
  545. jobsSize = server->networkLayers[i]->stop(nl, &jobs);
  546. #ifdef UA_MULTITHREADING
  547. /* Filter out delayed work */
  548. for(UA_Int32 k=0;k<jobsSize;k++) {
  549. if(jobs[k].type != UA_JOBTYPE_METHODCALL_DELAYED)
  550. continue;
  551. addDelayedJob(server, &jobs[k]);
  552. jobs[k].type = UA_JOBTYPE_NOTHING;
  553. }
  554. /* Dispatch work to the worker threads */
  555. dispatchJobs(server, jobs, jobsSize);
  556. /* Trigger sleeping worker threads */
  557. if(jobsSize > 0)
  558. pthread_cond_broadcast(&server->dispatchQueue_condition);
  559. #else
  560. processJobs(server, jobs, jobsSize);
  561. if(jobsSize > 0)
  562. UA_free(jobs);
  563. #endif
  564. }
  565. return UA_STATUSCODE_GOOD;
  566. }
  567. UA_StatusCode UA_Server_run_shutdown(UA_Server *server, UA_UInt16 nThreads){
  568. UA_Job *stopJobs;
  569. for(size_t i = 0; i < server->networkLayersSize; i++) {
  570. size_t stopJobsSize = server->networkLayers[i]->stop(server->networkLayers[i], &stopJobs);
  571. processJobs(server, stopJobs, stopJobsSize);
  572. UA_free(stopJobs);
  573. }
  574. #ifdef UA_MULTITHREADING
  575. /* Wait for all worker threads to finish */
  576. for(UA_UInt32 i=0;i<nThreads;i++) {
  577. pthread_join(server->thr[i], UA_NULL);
  578. UA_free(server->workerCounters[i]);
  579. }
  580. UA_free(server->workerCounters);
  581. UA_free(server->thr);
  582. /* Manually finish the work still enqueued */
  583. emptyDispatchQueue(server);
  584. /* Process the remaining delayed work */
  585. struct DelayedJobs *dw = server->delayedJobs;
  586. while(dw) {
  587. processJobs(server, dw->jobs, dw->jobsCount);
  588. struct DelayedJobs *next = dw->next;
  589. UA_free(dw->workerCounters);
  590. UA_free(dw);
  591. dw = next;
  592. }
  593. #endif
  594. return UA_STATUSCODE_GOOD;
  595. }
  596. UA_StatusCode UA_Server_run(UA_Server *server, UA_UInt16 nThreads, UA_Boolean *running) {
  597. if(UA_STATUSCODE_GOOD == UA_Server_run_startup(server, nThreads, running)){
  598. while(*running) {
  599. UA_Server_run_mainloop(server, running);
  600. }
  601. }
  602. UA_Server_run_shutdown(server, nThreads);
  603. return UA_STATUSCODE_GOOD;
  604. }