timer.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  1. /**
  2. * WinPR: Windows Portable Runtime
  3. * Synchronization Functions
  4. *
  5. * Copyright 2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. */
  19. #ifdef HAVE_CONFIG_H
  20. #include "config.h"
  21. #endif
  22. #include <winpr/crt.h>
  23. #include <winpr/file.h>
  24. #include <winpr/sysinfo.h>
  25. #include <winpr/synch.h>
  26. #ifndef _WIN32
  27. #include <unistd.h>
  28. #include <errno.h>
  29. #include <sys/time.h>
  30. #include <signal.h>
  31. #endif
  32. #include "synch.h"
  33. #ifndef _WIN32
  34. #include "../handle/handle.h"
  35. #include "../log.h"
  36. #define TAG WINPR_TAG("synch.timer")
  37. static BOOL TimerCloseHandle(HANDLE handle);
  38. static BOOL TimerIsHandled(HANDLE handle)
  39. {
  40. WINPR_TIMER* pTimer = (WINPR_TIMER*)handle;
  41. if (!pTimer || (pTimer->Type != HANDLE_TYPE_TIMER))
  42. {
  43. SetLastError(ERROR_INVALID_HANDLE);
  44. return FALSE;
  45. }
  46. return TRUE;
  47. }
  48. static int TimerGetFd(HANDLE handle)
  49. {
  50. WINPR_TIMER* timer = (WINPR_TIMER*)handle;
  51. if (!TimerIsHandled(handle))
  52. return -1;
  53. return timer->fd;
  54. }
  55. static DWORD TimerCleanupHandle(HANDLE handle)
  56. {
  57. int length;
  58. UINT64 expirations;
  59. WINPR_TIMER* timer = (WINPR_TIMER*)handle;
  60. if (!TimerIsHandled(handle))
  61. return WAIT_FAILED;
  62. if (timer->bManualReset)
  63. return WAIT_OBJECT_0;
  64. length = read(timer->fd, (void*)&expirations, sizeof(UINT64));
  65. if (length != 8)
  66. {
  67. if (length == -1)
  68. {
  69. switch (errno)
  70. {
  71. case ETIMEDOUT:
  72. case EAGAIN:
  73. return WAIT_TIMEOUT;
  74. default:
  75. break;
  76. }
  77. WLog_ERR(TAG, "timer read() failure [%d] %s", errno, strerror(errno));
  78. }
  79. else
  80. {
  81. WLog_ERR(TAG, "timer read() failure - incorrect number of bytes read");
  82. }
  83. return WAIT_FAILED;
  84. }
  85. return WAIT_OBJECT_0;
  86. }
  87. BOOL TimerCloseHandle(HANDLE handle)
  88. {
  89. WINPR_TIMER* timer;
  90. timer = (WINPR_TIMER*)handle;
  91. if (!TimerIsHandled(handle))
  92. return FALSE;
  93. if (!timer->lpArgToCompletionRoutine)
  94. {
  95. #ifdef HAVE_SYS_TIMERFD_H
  96. if (timer->fd != -1)
  97. close(timer->fd);
  98. #endif
  99. }
  100. else
  101. {
  102. #ifdef WITH_POSIX_TIMER
  103. timer_delete(timer->tid);
  104. #endif
  105. }
  106. #if defined(__APPLE__)
  107. dispatch_release(timer->queue);
  108. dispatch_release(timer->source);
  109. if (timer->pipe[0] != -1)
  110. close(timer->pipe[0]);
  111. if (timer->pipe[1] != -1)
  112. close(timer->pipe[1]);
  113. #endif
  114. free(timer->name);
  115. free(timer);
  116. return TRUE;
  117. }
  118. #ifdef WITH_POSIX_TIMER
  119. static BOOL g_WaitableTimerSignalHandlerInstalled = FALSE;
  120. static void WaitableTimerHandler(void* arg)
  121. {
  122. WINPR_TIMER* timer = (WINPR_TIMER*)arg;
  123. if (!timer)
  124. return;
  125. if (timer->pfnCompletionRoutine)
  126. {
  127. timer->pfnCompletionRoutine(timer->lpArgToCompletionRoutine, 0, 0);
  128. if (timer->lPeriod)
  129. {
  130. timer->timeout.it_interval.tv_sec = (timer->lPeriod / 1000); /* seconds */
  131. timer->timeout.it_interval.tv_nsec =
  132. ((timer->lPeriod % 1000) * 1000000); /* nanoseconds */
  133. if ((timer_settime(timer->tid, 0, &(timer->timeout), NULL)) != 0)
  134. {
  135. WLog_ERR(TAG, "timer_settime");
  136. }
  137. }
  138. }
  139. }
  140. static void WaitableTimerSignalHandler(int signum, siginfo_t* siginfo, void* arg)
  141. {
  142. WINPR_TIMER* timer = siginfo->si_value.sival_ptr;
  143. WINPR_UNUSED(arg);
  144. if (!timer || (signum != SIGALRM))
  145. return;
  146. WaitableTimerHandler(timer);
  147. }
  148. static int InstallWaitableTimerSignalHandler(void)
  149. {
  150. if (!g_WaitableTimerSignalHandlerInstalled)
  151. {
  152. struct sigaction action;
  153. sigemptyset(&action.sa_mask);
  154. sigaddset(&action.sa_mask, SIGALRM);
  155. action.sa_flags = SA_RESTART | SA_SIGINFO;
  156. action.sa_sigaction = WaitableTimerSignalHandler;
  157. sigaction(SIGALRM, &action, NULL);
  158. g_WaitableTimerSignalHandlerInstalled = TRUE;
  159. }
  160. return 0;
  161. }
  162. #endif
  163. #if defined(__APPLE__)
  164. static void WaitableTimerHandler(void* arg)
  165. {
  166. UINT64 data = 1;
  167. WINPR_TIMER* timer = (WINPR_TIMER*)arg;
  168. if (!timer)
  169. return;
  170. if (timer->pfnCompletionRoutine)
  171. timer->pfnCompletionRoutine(timer->lpArgToCompletionRoutine, 0, 0);
  172. if (write(timer->pipe[1], &data, sizeof(data)) != sizeof(data))
  173. WLog_ERR(TAG, "failed to write to pipe");
  174. if (timer->lPeriod == 0)
  175. {
  176. if (timer->running)
  177. dispatch_suspend(timer->source);
  178. timer->running = FALSE;
  179. }
  180. }
  181. #endif
  182. static int InitializeWaitableTimer(WINPR_TIMER* timer)
  183. {
  184. int result = 0;
  185. if (!timer->lpArgToCompletionRoutine)
  186. {
  187. #ifdef HAVE_SYS_TIMERFD_H
  188. timer->fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
  189. if (timer->fd <= 0)
  190. return -1;
  191. #elif defined(__APPLE__)
  192. #else
  193. WLog_ERR(TAG, "%s: os specific implementation is missing", __FUNCTION__);
  194. result = -1;
  195. #endif
  196. }
  197. else
  198. {
  199. #ifdef WITH_POSIX_TIMER
  200. struct sigevent sigev;
  201. InstallWaitableTimerSignalHandler();
  202. ZeroMemory(&sigev, sizeof(struct sigevent));
  203. sigev.sigev_notify = SIGEV_SIGNAL;
  204. sigev.sigev_signo = SIGALRM;
  205. sigev.sigev_value.sival_ptr = (void*)timer;
  206. if ((timer_create(CLOCK_MONOTONIC, &sigev, &(timer->tid))) != 0)
  207. {
  208. WLog_ERR(TAG, "timer_create");
  209. return -1;
  210. }
  211. #elif defined(__APPLE__)
  212. #else
  213. WLog_ERR(TAG, "%s: os specific implementation is missing", __FUNCTION__);
  214. result = -1;
  215. #endif
  216. }
  217. timer->bInit = TRUE;
  218. return result;
  219. }
  220. static HANDLE_OPS ops = { TimerIsHandled, TimerCloseHandle,
  221. TimerGetFd, TimerCleanupHandle,
  222. NULL, NULL,
  223. NULL, NULL,
  224. NULL, NULL,
  225. NULL, NULL,
  226. NULL, NULL,
  227. NULL, NULL,
  228. NULL, NULL,
  229. NULL, NULL };
  230. /**
  231. * Waitable Timer
  232. */
  233. HANDLE CreateWaitableTimerA(LPSECURITY_ATTRIBUTES lpTimerAttributes, BOOL bManualReset,
  234. LPCSTR lpTimerName)
  235. {
  236. HANDLE handle = NULL;
  237. WINPR_TIMER* timer;
  238. if (lpTimerAttributes)
  239. WLog_WARN(TAG, "%s [%s] does not support lpTimerAttributes", __FUNCTION__, lpTimerName);
  240. timer = (WINPR_TIMER*)calloc(1, sizeof(WINPR_TIMER));
  241. if (timer)
  242. {
  243. WINPR_HANDLE_SET_TYPE_AND_MODE(timer, HANDLE_TYPE_TIMER, WINPR_FD_READ);
  244. handle = (HANDLE)timer;
  245. timer->fd = -1;
  246. timer->lPeriod = 0;
  247. timer->bManualReset = bManualReset;
  248. timer->pfnCompletionRoutine = NULL;
  249. timer->lpArgToCompletionRoutine = NULL;
  250. timer->bInit = FALSE;
  251. if (lpTimerName)
  252. timer->name = strdup(lpTimerName);
  253. timer->ops = &ops;
  254. #if defined(__APPLE__)
  255. if (pipe(timer->pipe) != 0)
  256. goto fail;
  257. timer->queue = dispatch_queue_create(TAG, DISPATCH_QUEUE_SERIAL);
  258. if (!timer->queue)
  259. goto fail;
  260. timer->source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, timer->queue);
  261. if (!timer->source)
  262. goto fail;
  263. dispatch_set_context(timer->source, timer);
  264. dispatch_source_set_event_handler_f(timer->source, WaitableTimerHandler);
  265. timer->fd = timer->pipe[0];
  266. if (fcntl(timer->fd, F_SETFL, O_NONBLOCK) < 0)
  267. goto fail;
  268. #endif
  269. }
  270. return handle;
  271. #if defined(__APPLE__)
  272. fail:
  273. TimerCloseHandle(handle);
  274. return NULL;
  275. #endif
  276. }
  277. HANDLE CreateWaitableTimerW(LPSECURITY_ATTRIBUTES lpTimerAttributes, BOOL bManualReset,
  278. LPCWSTR lpTimerName)
  279. {
  280. int rc;
  281. HANDLE handle;
  282. LPSTR name = NULL;
  283. rc = ConvertFromUnicode(CP_UTF8, 0, lpTimerName, -1, &name, 0, NULL, NULL);
  284. if (rc < 0)
  285. return NULL;
  286. handle = CreateWaitableTimerA(lpTimerAttributes, bManualReset, name);
  287. free(name);
  288. return handle;
  289. }
  290. HANDLE CreateWaitableTimerExA(LPSECURITY_ATTRIBUTES lpTimerAttributes, LPCSTR lpTimerName,
  291. DWORD dwFlags, DWORD dwDesiredAccess)
  292. {
  293. BOOL bManualReset = (dwFlags & CREATE_WAITABLE_TIMER_MANUAL_RESET) ? TRUE : FALSE;
  294. if (dwDesiredAccess != 0)
  295. WLog_WARN(TAG, "%s [%s] does not support dwDesiredAccess 0x%08" PRIx32, __FUNCTION__,
  296. lpTimerName, dwDesiredAccess);
  297. return CreateWaitableTimerA(lpTimerAttributes, bManualReset, lpTimerName);
  298. }
  299. HANDLE CreateWaitableTimerExW(LPSECURITY_ATTRIBUTES lpTimerAttributes, LPCWSTR lpTimerName,
  300. DWORD dwFlags, DWORD dwDesiredAccess)
  301. {
  302. int rc;
  303. HANDLE handle;
  304. LPSTR name = NULL;
  305. rc = ConvertFromUnicode(CP_UTF8, 0, lpTimerName, -1, &name, 0, NULL, NULL);
  306. if (rc < 0)
  307. return NULL;
  308. handle = CreateWaitableTimerExA(lpTimerAttributes, name, dwFlags, dwDesiredAccess);
  309. free(name);
  310. return handle;
  311. }
  312. BOOL SetWaitableTimer(HANDLE hTimer, const LARGE_INTEGER* lpDueTime, LONG lPeriod,
  313. PTIMERAPCROUTINE pfnCompletionRoutine, LPVOID lpArgToCompletionRoutine,
  314. BOOL fResume)
  315. {
  316. ULONG Type;
  317. WINPR_HANDLE* Object;
  318. WINPR_TIMER* timer;
  319. #if defined(WITH_POSIX_TIMER) || defined(__APPLE__)
  320. LONGLONG seconds = 0;
  321. LONGLONG nanoseconds = 0;
  322. #ifdef HAVE_SYS_TIMERFD_H
  323. int status = 0;
  324. #endif /* HAVE_SYS_TIMERFD_H */
  325. #endif /* WITH_POSIX_TIMER */
  326. if (!winpr_Handle_GetInfo(hTimer, &Type, &Object))
  327. return FALSE;
  328. if (Type != HANDLE_TYPE_TIMER)
  329. return FALSE;
  330. if (!lpDueTime)
  331. return FALSE;
  332. if (lPeriod < 0)
  333. return FALSE;
  334. if (fResume)
  335. {
  336. WLog_ERR(TAG, "%s does not support fResume", __FUNCTION__);
  337. return FALSE;
  338. }
  339. timer = (WINPR_TIMER*)Object;
  340. timer->lPeriod = lPeriod; /* milliseconds */
  341. timer->pfnCompletionRoutine = pfnCompletionRoutine;
  342. timer->lpArgToCompletionRoutine = lpArgToCompletionRoutine;
  343. if (!timer->bInit)
  344. {
  345. if (InitializeWaitableTimer(timer) < 0)
  346. return FALSE;
  347. }
  348. #ifdef WITH_POSIX_TIMER
  349. ZeroMemory(&(timer->timeout), sizeof(struct itimerspec));
  350. if (lpDueTime->QuadPart < 0)
  351. {
  352. LONGLONG due = lpDueTime->QuadPart * (-1);
  353. /* due time is in 100 nanosecond intervals */
  354. seconds = (due / 10000000);
  355. nanoseconds = ((due % 10000000) * 100);
  356. }
  357. else if (lpDueTime->QuadPart == 0)
  358. {
  359. seconds = nanoseconds = 0;
  360. }
  361. else
  362. {
  363. WLog_ERR(TAG, "absolute time not implemented");
  364. return FALSE;
  365. }
  366. if (lPeriod > 0)
  367. {
  368. timer->timeout.it_interval.tv_sec = (lPeriod / 1000); /* seconds */
  369. timer->timeout.it_interval.tv_nsec = ((lPeriod % 1000) * 1000000); /* nanoseconds */
  370. }
  371. if (lpDueTime->QuadPart != 0)
  372. {
  373. timer->timeout.it_value.tv_sec = seconds; /* seconds */
  374. timer->timeout.it_value.tv_nsec = nanoseconds; /* nanoseconds */
  375. }
  376. else
  377. {
  378. timer->timeout.it_value.tv_sec = timer->timeout.it_interval.tv_sec; /* seconds */
  379. timer->timeout.it_value.tv_nsec = timer->timeout.it_interval.tv_nsec; /* nanoseconds */
  380. }
  381. if (!timer->pfnCompletionRoutine)
  382. {
  383. #ifdef HAVE_SYS_TIMERFD_H
  384. status = timerfd_settime(timer->fd, 0, &(timer->timeout), NULL);
  385. if (status)
  386. {
  387. WLog_ERR(TAG, "timerfd_settime failure: %d", status);
  388. return FALSE;
  389. }
  390. #endif
  391. }
  392. else
  393. {
  394. if ((timer_settime(timer->tid, 0, &(timer->timeout), NULL)) != 0)
  395. {
  396. WLog_ERR(TAG, "timer_settime");
  397. return FALSE;
  398. }
  399. }
  400. #elif defined(__APPLE__)
  401. if (lpDueTime->QuadPart < 0)
  402. {
  403. LONGLONG due = lpDueTime->QuadPart * (-1);
  404. /* due time is in 100 nanosecond intervals */
  405. seconds = (due / 10000000);
  406. nanoseconds = due * 100;
  407. }
  408. else if (lpDueTime->QuadPart == 0)
  409. {
  410. seconds = nanoseconds = 0;
  411. }
  412. else
  413. {
  414. WLog_ERR(TAG, "absolute time not implemented");
  415. return FALSE;
  416. }
  417. {
  418. /* Clean out old data from FD */
  419. BYTE buffer[32];
  420. while (read(timer->fd, buffer, sizeof(buffer)) > 0)
  421. ;
  422. }
  423. {
  424. if (timer->running)
  425. dispatch_suspend(timer->source);
  426. dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, nanoseconds);
  427. uint64_t interval = DISPATCH_TIME_FOREVER;
  428. if (lPeriod > 0)
  429. interval = lPeriod * 1000000;
  430. dispatch_source_set_timer(timer->source, start, interval, 0);
  431. dispatch_resume(timer->source);
  432. timer->running = TRUE;
  433. }
  434. #endif
  435. return TRUE;
  436. }
  437. BOOL SetWaitableTimerEx(HANDLE hTimer, const LARGE_INTEGER* lpDueTime, LONG lPeriod,
  438. PTIMERAPCROUTINE pfnCompletionRoutine, LPVOID lpArgToCompletionRoutine,
  439. PREASON_CONTEXT WakeContext, ULONG TolerableDelay)
  440. {
  441. return SetWaitableTimer(hTimer, lpDueTime, lPeriod, pfnCompletionRoutine,
  442. lpArgToCompletionRoutine, FALSE);
  443. }
  444. HANDLE OpenWaitableTimerA(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpTimerName)
  445. {
  446. /* TODO: Implement */
  447. WLog_ERR(TAG, "%s not implemented", __FUNCTION__);
  448. return NULL;
  449. }
  450. HANDLE OpenWaitableTimerW(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCWSTR lpTimerName)
  451. {
  452. /* TODO: Implement */
  453. WLog_ERR(TAG, "%s not implemented", __FUNCTION__);
  454. return NULL;
  455. }
  456. BOOL CancelWaitableTimer(HANDLE hTimer)
  457. {
  458. ULONG Type;
  459. WINPR_HANDLE* Object;
  460. WINPR_TIMER* timer;
  461. if (!winpr_Handle_GetInfo(hTimer, &Type, &Object))
  462. return FALSE;
  463. if (Type != HANDLE_TYPE_TIMER)
  464. return FALSE;
  465. timer = (WINPR_TIMER*)Object;
  466. #if defined(__APPLE__)
  467. if (timer->running)
  468. dispatch_suspend(timer->source);
  469. timer->running = FALSE;
  470. #endif
  471. return TRUE;
  472. }
  473. /**
  474. * Timer-Queue Timer
  475. */
  476. /**
  477. * Design, Performance, and Optimization of Timer Strategies for Real-time ORBs:
  478. * http://www.cs.wustl.edu/~schmidt/Timer_Queue.html
  479. */
  480. static void timespec_add_ms(struct timespec* tspec, UINT32 ms)
  481. {
  482. UINT64 ns = tspec->tv_nsec + (ms * 1000000);
  483. tspec->tv_sec += (ns / 1000000000);
  484. tspec->tv_nsec = (ns % 1000000000);
  485. }
  486. static UINT64 timespec_to_ms(struct timespec* tspec)
  487. {
  488. UINT64 ms;
  489. ms = tspec->tv_sec * 1000;
  490. ms += tspec->tv_nsec / 1000000;
  491. return ms;
  492. }
  493. static void timespec_gettimeofday(struct timespec* tspec)
  494. {
  495. struct timeval tval;
  496. gettimeofday(&tval, NULL);
  497. tspec->tv_sec = tval.tv_sec;
  498. tspec->tv_nsec = tval.tv_usec * 1000;
  499. }
  500. static int timespec_compare(const struct timespec* tspec1, const struct timespec* tspec2)
  501. {
  502. if (tspec1->tv_sec == tspec2->tv_sec)
  503. return (tspec1->tv_nsec - tspec2->tv_nsec);
  504. else
  505. return (tspec1->tv_sec - tspec2->tv_sec);
  506. }
  507. static void timespec_copy(struct timespec* dst, struct timespec* src)
  508. {
  509. dst->tv_sec = src->tv_sec;
  510. dst->tv_nsec = src->tv_nsec;
  511. }
  512. static void InsertTimerQueueTimer(WINPR_TIMER_QUEUE_TIMER** pHead, WINPR_TIMER_QUEUE_TIMER* timer)
  513. {
  514. WINPR_TIMER_QUEUE_TIMER* node;
  515. if (!(*pHead))
  516. {
  517. *pHead = timer;
  518. timer->next = NULL;
  519. return;
  520. }
  521. node = *pHead;
  522. while (node->next)
  523. {
  524. if (timespec_compare(&(timer->ExpirationTime), &(node->ExpirationTime)) > 0)
  525. {
  526. if (timespec_compare(&(timer->ExpirationTime), &(node->next->ExpirationTime)) < 0)
  527. break;
  528. }
  529. node = node->next;
  530. }
  531. if (node->next)
  532. {
  533. timer->next = node->next->next;
  534. node->next = timer;
  535. }
  536. else
  537. {
  538. node->next = timer;
  539. timer->next = NULL;
  540. }
  541. }
  542. static void RemoveTimerQueueTimer(WINPR_TIMER_QUEUE_TIMER** pHead, WINPR_TIMER_QUEUE_TIMER* timer)
  543. {
  544. BOOL found = FALSE;
  545. WINPR_TIMER_QUEUE_TIMER* node;
  546. WINPR_TIMER_QUEUE_TIMER* prevNode;
  547. if (timer == *pHead)
  548. {
  549. *pHead = timer->next;
  550. timer->next = NULL;
  551. return;
  552. }
  553. node = *pHead;
  554. prevNode = NULL;
  555. while (node)
  556. {
  557. if (node == timer)
  558. {
  559. found = TRUE;
  560. break;
  561. }
  562. prevNode = node;
  563. node = node->next;
  564. }
  565. if (found)
  566. {
  567. if (prevNode)
  568. {
  569. prevNode->next = timer->next;
  570. }
  571. timer->next = NULL;
  572. }
  573. }
  574. static int FireExpiredTimerQueueTimers(WINPR_TIMER_QUEUE* timerQueue)
  575. {
  576. struct timespec CurrentTime;
  577. WINPR_TIMER_QUEUE_TIMER* node;
  578. if (!timerQueue->activeHead)
  579. return 0;
  580. timespec_gettimeofday(&CurrentTime);
  581. node = timerQueue->activeHead;
  582. while (node)
  583. {
  584. if (timespec_compare(&CurrentTime, &(node->ExpirationTime)) >= 0)
  585. {
  586. node->Callback(node->Parameter, TRUE);
  587. node->FireCount++;
  588. timerQueue->activeHead = node->next;
  589. node->next = NULL;
  590. if (node->Period)
  591. {
  592. timespec_add_ms(&(node->ExpirationTime), node->Period);
  593. InsertTimerQueueTimer(&(timerQueue->activeHead), node);
  594. }
  595. else
  596. {
  597. InsertTimerQueueTimer(&(timerQueue->inactiveHead), node);
  598. }
  599. node = timerQueue->activeHead;
  600. }
  601. else
  602. {
  603. break;
  604. }
  605. }
  606. return 0;
  607. }
  608. static void* TimerQueueThread(void* arg)
  609. {
  610. int status;
  611. struct timespec timeout;
  612. WINPR_TIMER_QUEUE* timerQueue = (WINPR_TIMER_QUEUE*)arg;
  613. while (1)
  614. {
  615. pthread_mutex_lock(&(timerQueue->cond_mutex));
  616. timespec_gettimeofday(&timeout);
  617. if (!timerQueue->activeHead)
  618. {
  619. timespec_add_ms(&timeout, 50);
  620. }
  621. else
  622. {
  623. if (timespec_compare(&timeout, &(timerQueue->activeHead->ExpirationTime)) < 0)
  624. {
  625. timespec_copy(&timeout, &(timerQueue->activeHead->ExpirationTime));
  626. }
  627. }
  628. status = pthread_cond_timedwait(&(timerQueue->cond), &(timerQueue->cond_mutex), &timeout);
  629. FireExpiredTimerQueueTimers(timerQueue);
  630. pthread_mutex_unlock(&(timerQueue->cond_mutex));
  631. if ((status != ETIMEDOUT) && (status != 0))
  632. break;
  633. if (timerQueue->bCancelled)
  634. break;
  635. }
  636. return NULL;
  637. }
  638. static int StartTimerQueueThread(WINPR_TIMER_QUEUE* timerQueue)
  639. {
  640. pthread_cond_init(&(timerQueue->cond), NULL);
  641. pthread_mutex_init(&(timerQueue->cond_mutex), NULL);
  642. pthread_mutex_init(&(timerQueue->mutex), NULL);
  643. pthread_attr_init(&(timerQueue->attr));
  644. timerQueue->param.sched_priority = sched_get_priority_max(SCHED_FIFO);
  645. pthread_attr_setschedparam(&(timerQueue->attr), &(timerQueue->param));
  646. pthread_attr_setschedpolicy(&(timerQueue->attr), SCHED_FIFO);
  647. pthread_create(&(timerQueue->thread), &(timerQueue->attr), TimerQueueThread, timerQueue);
  648. return 0;
  649. }
  650. HANDLE CreateTimerQueue(void)
  651. {
  652. HANDLE handle = NULL;
  653. WINPR_TIMER_QUEUE* timerQueue;
  654. timerQueue = (WINPR_TIMER_QUEUE*)calloc(1, sizeof(WINPR_TIMER_QUEUE));
  655. if (timerQueue)
  656. {
  657. WINPR_HANDLE_SET_TYPE_AND_MODE(timerQueue, HANDLE_TYPE_TIMER_QUEUE, WINPR_FD_READ);
  658. handle = (HANDLE)timerQueue;
  659. timerQueue->activeHead = NULL;
  660. timerQueue->inactiveHead = NULL;
  661. timerQueue->bCancelled = FALSE;
  662. StartTimerQueueThread(timerQueue);
  663. }
  664. return handle;
  665. }
  666. BOOL DeleteTimerQueueEx(HANDLE TimerQueue, HANDLE CompletionEvent)
  667. {
  668. void* rvalue;
  669. WINPR_TIMER_QUEUE* timerQueue;
  670. WINPR_TIMER_QUEUE_TIMER* node;
  671. WINPR_TIMER_QUEUE_TIMER* nextNode;
  672. if (!TimerQueue)
  673. return FALSE;
  674. timerQueue = (WINPR_TIMER_QUEUE*)TimerQueue;
  675. /* Cancel and delete timer queue timers */
  676. pthread_mutex_lock(&(timerQueue->cond_mutex));
  677. timerQueue->bCancelled = TRUE;
  678. pthread_cond_signal(&(timerQueue->cond));
  679. pthread_mutex_unlock(&(timerQueue->cond_mutex));
  680. pthread_join(timerQueue->thread, &rvalue);
  681. /**
  682. * Quote from MSDN regarding CompletionEvent:
  683. * If this parameter is INVALID_HANDLE_VALUE, the function waits for
  684. * all callback functions to complete before returning.
  685. * If this parameter is NULL, the function marks the timer for
  686. * deletion and returns immediately.
  687. *
  688. * Note: The current WinPR implementation implicitly waits for any
  689. * callback functions to complete (see pthread_join above)
  690. */
  691. {
  692. /* Move all active timers to the inactive timer list */
  693. node = timerQueue->activeHead;
  694. while (node)
  695. {
  696. InsertTimerQueueTimer(&(timerQueue->inactiveHead), node);
  697. node = node->next;
  698. }
  699. timerQueue->activeHead = NULL;
  700. /* Once all timers are inactive, free them */
  701. node = timerQueue->inactiveHead;
  702. while (node)
  703. {
  704. nextNode = node->next;
  705. free(node);
  706. node = nextNode;
  707. }
  708. timerQueue->inactiveHead = NULL;
  709. }
  710. /* Delete timer queue */
  711. pthread_cond_destroy(&(timerQueue->cond));
  712. pthread_mutex_destroy(&(timerQueue->cond_mutex));
  713. pthread_mutex_destroy(&(timerQueue->mutex));
  714. pthread_attr_destroy(&(timerQueue->attr));
  715. free(timerQueue);
  716. if (CompletionEvent && (CompletionEvent != INVALID_HANDLE_VALUE))
  717. SetEvent(CompletionEvent);
  718. return TRUE;
  719. }
  720. BOOL DeleteTimerQueue(HANDLE TimerQueue)
  721. {
  722. return DeleteTimerQueueEx(TimerQueue, NULL);
  723. }
  724. BOOL CreateTimerQueueTimer(PHANDLE phNewTimer, HANDLE TimerQueue, WAITORTIMERCALLBACK Callback,
  725. PVOID Parameter, DWORD DueTime, DWORD Period, ULONG Flags)
  726. {
  727. struct timespec CurrentTime;
  728. WINPR_TIMER_QUEUE* timerQueue;
  729. WINPR_TIMER_QUEUE_TIMER* timer;
  730. if (!TimerQueue)
  731. return FALSE;
  732. timespec_gettimeofday(&CurrentTime);
  733. timerQueue = (WINPR_TIMER_QUEUE*)TimerQueue;
  734. timer = (WINPR_TIMER_QUEUE_TIMER*)malloc(sizeof(WINPR_TIMER_QUEUE_TIMER));
  735. if (!timer)
  736. return FALSE;
  737. WINPR_HANDLE_SET_TYPE_AND_MODE(timer, HANDLE_TYPE_TIMER_QUEUE_TIMER, WINPR_FD_READ);
  738. *((UINT_PTR*)phNewTimer) = (UINT_PTR)(HANDLE)timer;
  739. timespec_copy(&(timer->StartTime), &CurrentTime);
  740. timespec_add_ms(&(timer->StartTime), DueTime);
  741. timespec_copy(&(timer->ExpirationTime), &(timer->StartTime));
  742. timer->Flags = Flags;
  743. timer->DueTime = DueTime;
  744. timer->Period = Period;
  745. timer->Callback = Callback;
  746. timer->Parameter = Parameter;
  747. timer->timerQueue = (WINPR_TIMER_QUEUE*)TimerQueue;
  748. timer->FireCount = 0;
  749. timer->next = NULL;
  750. pthread_mutex_lock(&(timerQueue->cond_mutex));
  751. InsertTimerQueueTimer(&(timerQueue->activeHead), timer);
  752. pthread_cond_signal(&(timerQueue->cond));
  753. pthread_mutex_unlock(&(timerQueue->cond_mutex));
  754. return TRUE;
  755. }
  756. BOOL ChangeTimerQueueTimer(HANDLE TimerQueue, HANDLE Timer, ULONG DueTime, ULONG Period)
  757. {
  758. struct timespec CurrentTime;
  759. WINPR_TIMER_QUEUE* timerQueue;
  760. WINPR_TIMER_QUEUE_TIMER* timer;
  761. if (!TimerQueue || !Timer)
  762. return FALSE;
  763. timespec_gettimeofday(&CurrentTime);
  764. timerQueue = (WINPR_TIMER_QUEUE*)TimerQueue;
  765. timer = (WINPR_TIMER_QUEUE_TIMER*)Timer;
  766. pthread_mutex_lock(&(timerQueue->cond_mutex));
  767. RemoveTimerQueueTimer(&(timerQueue->activeHead), timer);
  768. RemoveTimerQueueTimer(&(timerQueue->inactiveHead), timer);
  769. timer->DueTime = DueTime;
  770. timer->Period = Period;
  771. timer->next = NULL;
  772. timespec_copy(&(timer->StartTime), &CurrentTime);
  773. timespec_add_ms(&(timer->StartTime), DueTime);
  774. timespec_copy(&(timer->ExpirationTime), &(timer->StartTime));
  775. InsertTimerQueueTimer(&(timerQueue->activeHead), timer);
  776. pthread_cond_signal(&(timerQueue->cond));
  777. pthread_mutex_unlock(&(timerQueue->cond_mutex));
  778. return TRUE;
  779. }
  780. BOOL DeleteTimerQueueTimer(HANDLE TimerQueue, HANDLE Timer, HANDLE CompletionEvent)
  781. {
  782. WINPR_TIMER_QUEUE* timerQueue;
  783. WINPR_TIMER_QUEUE_TIMER* timer;
  784. if (!TimerQueue || !Timer)
  785. return FALSE;
  786. timerQueue = (WINPR_TIMER_QUEUE*)TimerQueue;
  787. timer = (WINPR_TIMER_QUEUE_TIMER*)Timer;
  788. pthread_mutex_lock(&(timerQueue->cond_mutex));
  789. /**
  790. * Quote from MSDN regarding CompletionEvent:
  791. * If this parameter is INVALID_HANDLE_VALUE, the function waits for
  792. * all callback functions to complete before returning.
  793. * If this parameter is NULL, the function marks the timer for
  794. * deletion and returns immediately.
  795. *
  796. * Note: The current WinPR implementation implicitly waits for any
  797. * callback functions to complete (see cond_mutex usage)
  798. */
  799. RemoveTimerQueueTimer(&(timerQueue->activeHead), timer);
  800. pthread_cond_signal(&(timerQueue->cond));
  801. pthread_mutex_unlock(&(timerQueue->cond_mutex));
  802. free(timer);
  803. if (CompletionEvent && (CompletionEvent != INVALID_HANDLE_VALUE))
  804. SetEvent(CompletionEvent);
  805. return TRUE;
  806. }
  807. #endif