event.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. /* Copyright (c) 1993-2008 by Richard Kelsey and Jonathan Rees.
  2. See file COPYING. */
  3. #define _WIN32_WINNT 0x0400/* for SetWaitableTimer */
  4. #include <windows.h>
  5. #include <signal.h>
  6. #include <stdlib.h>
  7. #include <stdio.h>
  8. #include <errno.h> /* for errno, (ANSI) */
  9. #include "c-mods.h"
  10. #include "scheme48vm.h"
  11. #include "event.h"
  12. static void
  13. set_signal_catcher(int signum, void (*catcher)(int))
  14. {
  15. signal(signum, catcher);
  16. }
  17. static long keyboard_interrupt_count = 0;
  18. static VOID CALLBACK
  19. keyboard_interrupt_callback(DWORD dwParam)
  20. {
  21. keyboard_interrupt_count += 1;
  22. NOTE_EVENT;
  23. }
  24. HANDLE s48_main_thread;
  25. when_keyboard_interrupt(int ign)
  26. {
  27. if (!QueueUserAPC(keyboard_interrupt_callback,
  28. s48_main_thread,
  29. (DWORD) 0))
  30. {
  31. fprintf(stderr, "QueueUserAPC failed\n");
  32. exit(-1);
  33. }
  34. }
  35. static void
  36. start_control_c_interrupts()
  37. {
  38. set_signal_catcher(SIGINT, when_keyboard_interrupt);
  39. }
  40. /* ticks since last timer-interrupt request
  41. (except for some types, identical to Unix code) */
  42. long s48_current_time = 0;
  43. static long alarm_time = -1;
  44. static long poll_time = -1;
  45. static long poll_interval = 5;
  46. static void
  47. when_alarm_interrupt()
  48. {
  49. s48_current_time += 1;
  50. /* fprintf(stderr, "[tick %ld]", s48_current_time); */
  51. if ((alarm_time >= 0 && alarm_time <= s48_current_time) ||
  52. (poll_time >= 0 && poll_time <= s48_current_time))
  53. NOTE_EVENT;
  54. }
  55. #define USEC_PER_POLL (1000000 / POLLS_PER_SECOND)
  56. /* delta is in ticks, 0 cancels current alarm */
  57. long
  58. s48_schedule_alarm_interrupt(long delta)
  59. {
  60. long old;
  61. /* fprintf(stderr, "<scheduling alarm for %ld + %ld>\n", s48_current_time,
  62. delta/TICKS_PER_POLL); */
  63. /* get remaining time */
  64. if (alarm_time == -1)
  65. old = -1;
  66. else
  67. old = (alarm_time - s48_current_time) * TICKS_PER_POLL;
  68. /* decrement poll_time and reset current_time */
  69. if (poll_time != -1)
  70. poll_time -= s48_current_time;
  71. s48_current_time = 0;
  72. /* set alarm_time */
  73. if (delta == 0)
  74. {
  75. NOTE_EVENT;
  76. alarm_time = 0;
  77. }
  78. else
  79. alarm_time = delta / TICKS_PER_POLL;
  80. return old;
  81. }
  82. /* The next two procedures return times in seconds and ticks
  83. (also from Lars Bergstrom's version */
  84. static DWORD startup_real_time_ticks;
  85. long s48_real_time(long *ticks)
  86. {
  87. DWORD now;
  88. now = GetTickCount();
  89. *ticks = ((now - startup_real_time_ticks) % 1000) * (TICKS_PER_SECOND / 1000);
  90. return (now - startup_real_time_ticks) / 1000;
  91. }
  92. long s48_run_time(long *ticks)
  93. {
  94. FILETIME create, exit, user, kernel;
  95. SYSTEMTIME systime;
  96. HANDLE this_process;
  97. BOOL status;
  98. this_process = GetCurrentProcess();
  99. status = GetProcessTimes(this_process, &create, &exit, &user, &kernel);
  100. status = FileTimeToSystemTime(&user, &systime);
  101. /* go from 100ns to 1ms resolution */
  102. *ticks = systime.wMilliseconds * (TICKS_PER_SECOND / 1000);
  103. return systime.wSecond;
  104. }
  105. static HANDLE alarm_thread = NULL;
  106. DWORD
  107. alarm_thread_func(LPDWORD id)
  108. {
  109. for (;;)
  110. {
  111. Sleep(USEC_PER_POLL / 1000);
  112. when_alarm_interrupt();
  113. }
  114. return 0; /* shouldn't get here */
  115. }
  116. /*
  117. * If it's being called for the first time, create the thread
  118. * If it's being called again, that means that it's been suspended
  119. * and should be resumed.
  120. */
  121. void
  122. s48_start_alarm_interrupts(void)
  123. {
  124. if (alarm_thread == NULL)
  125. {
  126. DWORD alarm_thread_id;
  127. alarm_thread = CreateThread(NULL, /* no security attributes */
  128. 0, /* default stack size */
  129. (LPTHREAD_START_ROUTINE) alarm_thread_func,
  130. NULL, /* argument to thread -- ignored */
  131. 0, /* default creation flags */
  132. &alarm_thread_id);
  133. if (alarm_thread == NULL)
  134. {
  135. fprintf(stderr, "failure creating alarm timer thread\n");
  136. exit(-1);
  137. }
  138. }
  139. else
  140. ResumeThread(alarm_thread);
  141. }
  142. void
  143. s48_stop_alarm_interrupts(void)
  144. {
  145. if (alarm_thread != NULL)
  146. SuspendThread(alarm_thread);
  147. }
  148. /*
  149. * We keep two queues of ports: those that have a pending operation, and
  150. * those whose operation has completed. Periodically, we call select() on
  151. * the pending ports and move any that are ready onto the other queue and
  152. * signal an event.
  153. */
  154. #define FD_QUIESCENT 0 /* idle */
  155. #define FD_READY 1 /* I/O ready to be performed */
  156. #define FD_PENDING 2 /* waiting */
  157. typedef struct fd_struct {
  158. int fd, /* file descriptor */
  159. status; /* one of the FD_* constants */
  160. long os_status; /* characters processed or error code */
  161. psbool has_error;
  162. psbool is_input; /* iff input */
  163. struct fd_struct *next; /* next on same queue */
  164. } fd_struct;
  165. /*
  166. * A queue of fd_structs is empty iff the first field is NULL. In
  167. * that case, lastp points to first.
  168. */
  169. typedef struct fdque
  170. {
  171. fd_struct *first, **lastp;
  172. } fdque;
  173. static fd_struct *fds[FD_SETSIZE];
  174. static fdque ready = {
  175. NULL,
  176. &ready.first
  177. };
  178. /*
  179. * Given a pointer to the link of a fd_struct, and a pointer to
  180. * the queue it is on, remove the entry from the queue.
  181. * The entry removed is returned.
  182. */
  183. static fd_struct *
  184. rmque(fd_struct **link, fdque *que)
  185. {
  186. fd_struct *res;
  187. res = *link;
  188. *link = res->next;
  189. if (res->next == NULL)
  190. que->lastp = link;
  191. return (res);
  192. }
  193. /*
  194. * Find a fd_struct in a queue, and remove it.
  195. */
  196. static void
  197. findrm(fd_struct *entry, fdque *que)
  198. {
  199. fd_struct **fp,
  200. *f;
  201. for (fp = &que->first; (f = *fp) != entry; fp = &f->next)
  202. if (f == NULL) {
  203. fprintf(stderr, "ERROR: findrm fd %d, status %d not on queue.\n",
  204. entry->fd, entry->status);
  205. return;
  206. }
  207. rmque(fp, que);
  208. }
  209. /*
  210. * Add a fd_struct to a queue.
  211. */
  212. static void
  213. addque(fd_struct *entry, fdque *que)
  214. {
  215. *que->lastp = entry;
  216. entry->next = NULL;
  217. que->lastp = &entry->next;
  218. }
  219. static psbool
  220. there_are_ready_ports(void)
  221. {
  222. return (ready.first != NULL);
  223. }
  224. static int
  225. next_ready_port(long* os_status, psbool* has_error)
  226. {
  227. fd_struct *p;
  228. p = rmque(&ready.first, &ready);
  229. p->status = FD_QUIESCENT;
  230. *os_status = p->os_status;
  231. *has_error = p->has_error;
  232. return (p->fd);
  233. }
  234. /*
  235. * Put fd on to the queue of ports with ready operations.
  236. * Return PSTRUE if successful, and PSFALSE otherwise.
  237. */
  238. psbool
  239. s48_add_ready_fd(long fd, psbool is_input, psbool has_error, long os_status)
  240. {
  241. fd_struct* data = fds[fd]; /* we created this before */
  242. data->is_input = is_input;
  243. data->os_status = os_status;
  244. data->has_error = has_error;
  245. if (data->status == FD_READY)
  246. return (PSTRUE); /* fd is already ready */
  247. data->status = FD_READY;
  248. addque(data, &ready);
  249. return PSTRUE;
  250. }
  251. /*
  252. * Add a new fd_struct for fd.
  253. */
  254. static fd_struct *
  255. add_fd(long fd, psbool is_input)
  256. {
  257. struct fd_struct *new;
  258. new = (struct fd_struct *)malloc(sizeof(*new));
  259. if (new != NULL) {
  260. new->fd = fd;
  261. new->status = FD_QUIESCENT;
  262. new->is_input = is_input;
  263. new->next = NULL;
  264. fds[fd] = new;
  265. }
  266. return (new);
  267. }
  268. static fd_struct *
  269. get_or_create_fd_struct(long fd, psbool is_input)
  270. {
  271. if (fds[fd] == NULL)
  272. return add_fd(fd, is_input);
  273. else
  274. return fds[fd];
  275. }
  276. psbool
  277. s48_add_pending_fd(int fd, psbool is_input)
  278. {
  279. fd_struct* data = get_or_create_fd_struct(fd, is_input);
  280. if (data)
  281. {
  282. if (data->status != FD_PENDING)
  283. {
  284. data->status = FD_PENDING;
  285. if (poll_time == -1)
  286. poll_time = s48_current_time + poll_interval;
  287. }
  288. return PSTRUE;
  289. }
  290. else
  291. return PSFALSE;
  292. }
  293. psbool
  294. s48_is_pending(long fd)
  295. {
  296. return (fds[fd] != NULL) && (fds[fd]->status == FD_PENDING);
  297. }
  298. /*
  299. * Remove fd from any queues it is on. Returns true if the FD was on a queue
  300. * and false if it wasn't.
  301. */
  302. psbool
  303. s48_remove_fd(int fd)
  304. {
  305. struct fd_struct *data;
  306. if (! (0 <= fd && fd < FD_SETSIZE)) {
  307. fprintf(stderr, "ERROR: s48_remove_fd fd %d not in [0, %d)\n",
  308. fd,
  309. FD_SETSIZE);
  310. return PSFALSE;
  311. }
  312. data = fds[fd];
  313. if (data == NULL)
  314. return PSFALSE;
  315. if (data->status == FD_PENDING) {
  316. /* the callback will see this and no-op */
  317. data->status = FD_QUIESCENT;
  318. /*#### if (pending.first == NULL)
  319. poll_time = -1; */
  320. } else if (data->status == FD_READY)
  321. findrm(data, &ready);
  322. free((void *)data);
  323. fds[fd] = NULL;
  324. return TRUE;
  325. }
  326. HANDLE
  327. s48_create_mutex_semaphore()
  328. {
  329. HANDLE handle = CreateSemaphore(NULL, /* lpSemaphoreAttributes */
  330. 0, /* lInitialCount */
  331. 1, /* lMaximumCount */
  332. NULL); /* lpName */
  333. if (handle == NULL)
  334. {
  335. fprintf(stderr, "error in CreateSemaphore\n");
  336. exit(-1);
  337. }
  338. return handle;
  339. }
  340. static HANDLE external_event_mutex;
  341. #define LOCK_EXTERNAL_EVENTS WaitForSingleObject(external_event_mutex, INFINITE)
  342. #define UNLOCK_EXTERNAL_EVENTS ReleaseSemaphore(external_event_mutex, 1, NULL)
  343. long
  344. s48_dequeue_external_event(char* readyp)
  345. {
  346. long retval;
  347. LOCK_EXTERNAL_EVENTS;
  348. retval = s48_dequeue_external_eventBUunsafe(readyp);
  349. UNLOCK_EXTERNAL_EVENTS;
  350. return retval;
  351. }
  352. static char
  353. external_event_pending()
  354. {
  355. char retval;
  356. LOCK_EXTERNAL_EVENTS;
  357. retval = s48_external_event_pendingPUunsafe();
  358. UNLOCK_EXTERNAL_EVENTS;
  359. return retval;
  360. }
  361. /* no side effect */
  362. static char
  363. external_event_ready()
  364. {
  365. char retval;
  366. LOCK_EXTERNAL_EVENTS;
  367. retval = s48_external_event_readyPUunsafe();
  368. UNLOCK_EXTERNAL_EVENTS;
  369. return retval;
  370. }
  371. VOID CALLBACK
  372. s48_when_external_event_interrupt(DWORD dwParam)
  373. {
  374. /* do nothing, except possibly interrupt the running SleepEx */
  375. }
  376. void
  377. s48_note_external_event(long uid)
  378. {
  379. LOCK_EXTERNAL_EVENTS;
  380. s48_note_external_eventBUunsafe(uid);
  381. UNLOCK_EXTERNAL_EVENTS;
  382. NOTE_EVENT;
  383. if (!QueueUserAPC(s48_when_external_event_interrupt,
  384. s48_main_thread,
  385. (DWORD) 0))
  386. {
  387. fprintf(stderr, "QueueUserAPC failed\n");
  388. exit(-1);
  389. }
  390. }
  391. /*
  392. * ; Scheme version of the get-next-event procedure
  393. * ;
  394. * ; 1. If there has been a keyboard interrupt, return it.
  395. * ; 2. Check for ready ports if enough time has passed since the last check.
  396. * ; 3. If there is a ready port, return it.
  397. * ; 4. If an alarm is due, return it.
  398. * ; 5. If no events are pending, clear the event flags.
  399. * (define (get-next-event)
  400. * (cond ((> *keyboard-interrupt-count* 0)
  401. * (without-interrupts
  402. * (lambda ()
  403. * (set! *keyboard-interrupt-count*
  404. * (- *keyboard-interrupt-count* 1))))
  405. * (values (enum event-type keyboard-interrupt) #f #f))
  406. * (else
  407. * (cond ((>= *current_time* *poll-time*)
  408. * (queue-ready-ports)
  409. * (set! *poll-time* (+ *time* *poll-interval*))))
  410. * (cond ((not (queue-empty? ready-ports))
  411. * (values (enum event-type i/o-completion)
  412. * (dequeue! ready-ports)))
  413. * ((>= *current_time* *alarm-time*)
  414. * (set! *alarm-time* max-integer)
  415. * (values (enum event-type alarm-interrupt) #f))
  416. * (else
  417. * (without-interrupts
  418. * (lambda ()
  419. * (if (and (= *keyboard-interrupt-count* 0)
  420. * (> *alarm-time* *current_time*)
  421. * (> *poll-time* *current_time*))
  422. * (set! *pending-event?* #f))))
  423. * (values (enum event-type no-event) #f))))))
  424. */
  425. int
  426. s48_get_next_event(long *ready_fd, long *status)
  427. {
  428. /* extern int s48_os_signal_pending(void); */
  429. /*
  430. fprintf(stderr, "[poll at %d (waiting for %d)]\n", s48_current_time, alarm_time);
  431. */
  432. if (keyboard_interrupt_count > 0) {
  433. --keyboard_interrupt_count;
  434. /* fprintf(stderr, "[keyboard interrupt]\n"); */
  435. return (KEYBOARD_INTERRUPT_EVENT);
  436. }
  437. if (poll_time != -1 && s48_current_time >= poll_time) {
  438. SleepEx(0, TRUE);
  439. poll_time = s48_current_time + poll_interval;
  440. }
  441. if (there_are_ready_ports()) {
  442. psbool has_error;
  443. *ready_fd = next_ready_port(status, &has_error);
  444. if (has_error)
  445. {
  446. /* fprintf(stderr, "[i/o error on port %ld, status %ld]\n", *ready_fd, *status); */
  447. return (IO_ERROR_EVENT);
  448. }
  449. else
  450. {
  451. /* fprintf(stderr, "[i/o completion on port %ld, status %ld]\n", *ready_fd, *status); */
  452. return (IO_COMPLETION_EVENT);
  453. }
  454. }
  455. if (alarm_time != -1 && s48_current_time >= alarm_time) {
  456. alarm_time = -1;
  457. /* fprintf(stderr, "[alarm %ld]\n", s48_current_time); */
  458. return (ALARM_EVENT);
  459. }
  460. /*
  461. if (s48_os_signal_pending())
  462. return (OS_SIGNAL_EVENT);
  463. */
  464. if (external_event_pending())
  465. return (EXTERNAL_EVENT);
  466. if ((keyboard_interrupt_count == 0)
  467. && (alarm_time == -1 || s48_current_time < alarm_time)
  468. && (poll_time == -1 || s48_current_time < poll_time))
  469. s48_Spending_eventsPS = PSFALSE;
  470. return (NO_EVENT);
  471. }
  472. int
  473. s48_wait_for_event(long max_wait, psbool is_minutes)
  474. {
  475. /* fprintf(stderr, "[waiting]\n"); */
  476. DWORD dwMilliseconds;
  477. s48_stop_alarm_interrupts();
  478. if (max_wait == -1)
  479. dwMilliseconds = INFINITE;
  480. else if (is_minutes)
  481. dwMilliseconds = max_wait * 60 * 1000;
  482. else
  483. dwMilliseconds = max_wait * (1000 / TICKS_PER_SECOND);
  484. SleepEx(dwMilliseconds,
  485. TRUE);
  486. if (there_are_ready_ports()
  487. || external_event_ready())
  488. NOTE_EVENT;
  489. s48_start_alarm_interrupts();
  490. return NO_ERRORS;
  491. }
  492. void
  493. s48_sysdep_init(void)
  494. {
  495. startup_real_time_ticks = GetTickCount();
  496. /* Yes, this is the official hoopla to get at an absolute handle for
  497. the current thread. GetCurrentThread() returns a *constant*. */
  498. if (!DuplicateHandle(GetCurrentProcess(),
  499. GetCurrentThread(), GetCurrentProcess(),
  500. &s48_main_thread,
  501. THREAD_ALL_ACCESS, FALSE, 0))
  502. {
  503. fprintf(stderr, "DuplicateHandle failed\n");
  504. exit(-1);
  505. }
  506. external_event_mutex = s48_create_mutex_semaphore();
  507. UNLOCK_EXTERNAL_EVENTS;
  508. start_control_c_interrupts();
  509. s48_start_alarm_interrupts();
  510. {
  511. extern void s48_fd_io_init();
  512. s48_fd_io_init();
  513. }
  514. }