]> code.delx.au - gnu-emacs/blob - src/atimer.c
Update copyright year to 2015
[gnu-emacs] / src / atimer.c
1 /* Asynchronous timers.
2 Copyright (C) 2000-2015 Free Software Foundation, Inc.
3
4 This file is part of GNU Emacs.
5
6 GNU Emacs is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
18
19 #include <config.h>
20 #include <stdio.h>
21
22 #include "lisp.h"
23 #include "syssignal.h"
24 #include "systime.h"
25 #include "blockinput.h"
26 #include "atimer.h"
27 #include <unistd.h>
28
29 #ifdef HAVE_TIMERFD
30 #include <errno.h>
31 # include <sys/timerfd.h>
32 #endif
33
34 /* Free-list of atimer structures. */
35
36 static struct atimer *free_atimers;
37
38 /* List of currently not running timers due to a call to
39 lock_atimer. */
40
41 static struct atimer *stopped_atimers;
42
43 /* List of active atimers, sorted by expiration time. The timer that
44 will become ripe next is always at the front of this list. */
45
46 static struct atimer *atimers;
47
48 #ifdef HAVE_ITIMERSPEC
49 /* The alarm timer and whether it was properly initialized, if
50 POSIX timers are available. */
51 static timer_t alarm_timer;
52 static bool alarm_timer_ok;
53
54 # ifdef HAVE_TIMERFD
55 /* File descriptor for timer, or -1 if it could not be created. */
56 static int timerfd;
57 # else
58 enum { timerfd = -1 };
59 # endif
60 #endif
61
62 /* Block/unblock SIGALRM. */
63
64 static void
65 block_atimers (sigset_t *oldset)
66 {
67 sigset_t blocked;
68 sigemptyset (&blocked);
69 sigaddset (&blocked, SIGALRM);
70 sigaddset (&blocked, SIGINT);
71 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
72 }
73 static void
74 unblock_atimers (sigset_t const *oldset)
75 {
76 pthread_sigmask (SIG_SETMASK, oldset, 0);
77 }
78
79 /* Function prototypes. */
80
81 static void set_alarm (void);
82 static void schedule_atimer (struct atimer *);
83 static struct atimer *append_atimer_lists (struct atimer *,
84 struct atimer *);
85
86 /* Start a new atimer of type TYPE. TIMESTAMP specifies when the timer is
87 ripe. FN is the function to call when the timer fires.
88 CLIENT_DATA is stored in the client_data member of the atimer
89 structure returned and so made available to FN when it is called.
90
91 If TYPE is ATIMER_ABSOLUTE, TIMESTAMP is the absolute time at which the
92 timer fires.
93
94 If TYPE is ATIMER_RELATIVE, the timer is ripe TIMESTAMP seconds in the
95 future.
96
97 In both cases, the timer is automatically freed after it has fired.
98
99 If TYPE is ATIMER_CONTINUOUS, the timer fires every TIMESTAMP seconds.
100
101 Value is a pointer to the atimer started. It can be used in calls
102 to cancel_atimer; don't free it yourself. */
103
104 struct atimer *
105 start_atimer (enum atimer_type type, struct timespec timestamp,
106 atimer_callback fn, void *client_data)
107 {
108 struct atimer *t;
109 sigset_t oldset;
110
111 /* Round TIMESTAMP up to the next full second if we don't have itimers. */
112 #ifndef HAVE_SETITIMER
113 if (timestamp.tv_nsec != 0 && timestamp.tv_sec < TYPE_MAXIMUM (time_t))
114 timestamp = make_timespec (timestamp.tv_sec + 1, 0);
115 #endif /* not HAVE_SETITIMER */
116
117 /* Get an atimer structure from the free-list, or allocate
118 a new one. */
119 if (free_atimers)
120 {
121 t = free_atimers;
122 free_atimers = t->next;
123 }
124 else
125 t = xmalloc (sizeof *t);
126
127 /* Fill the atimer structure. */
128 memset (t, 0, sizeof *t);
129 t->type = type;
130 t->fn = fn;
131 t->client_data = client_data;
132
133 block_atimers (&oldset);
134
135 /* Compute the timer's expiration time. */
136 switch (type)
137 {
138 case ATIMER_ABSOLUTE:
139 t->expiration = timestamp;
140 break;
141
142 case ATIMER_RELATIVE:
143 t->expiration = timespec_add (current_timespec (), timestamp);
144 break;
145
146 case ATIMER_CONTINUOUS:
147 t->expiration = timespec_add (current_timespec (), timestamp);
148 t->interval = timestamp;
149 break;
150 }
151
152 /* Insert the timer in the list of active atimers. */
153 schedule_atimer (t);
154 unblock_atimers (&oldset);
155
156 /* Arrange for a SIGALRM at the time the next atimer is ripe. */
157 set_alarm ();
158
159 return t;
160 }
161
162
163 /* Cancel and free atimer TIMER. */
164
165 void
166 cancel_atimer (struct atimer *timer)
167 {
168 int i;
169 sigset_t oldset;
170
171 block_atimers (&oldset);
172
173 for (i = 0; i < 2; ++i)
174 {
175 struct atimer *t, *prev;
176 struct atimer **list = i ? &stopped_atimers : &atimers;
177
178 /* See if TIMER is active or stopped. */
179 for (t = *list, prev = NULL; t && t != timer; prev = t, t = t->next)
180 ;
181
182 /* If it is, take it off its list, and put in on the free-list.
183 We don't bother to arrange for setting a different alarm time,
184 since a too early one doesn't hurt. */
185 if (t)
186 {
187 if (prev)
188 prev->next = t->next;
189 else
190 *list = t->next;
191
192 t->next = free_atimers;
193 free_atimers = t;
194 break;
195 }
196 }
197
198 unblock_atimers (&oldset);
199 }
200
201
202 /* Append two lists of atimers LIST_1 and LIST_2 and return the
203 result list. */
204
205 static struct atimer *
206 append_atimer_lists (struct atimer *list_1, struct atimer *list_2)
207 {
208 if (list_1 == NULL)
209 return list_2;
210 else if (list_2 == NULL)
211 return list_1;
212 else
213 {
214 struct atimer *p;
215
216 for (p = list_1; p->next; p = p->next)
217 ;
218 p->next = list_2;
219 return list_1;
220 }
221 }
222
223
224 /* Stop all timers except timer T. T null means stop all timers. */
225
226 void
227 stop_other_atimers (struct atimer *t)
228 {
229 sigset_t oldset;
230 block_atimers (&oldset);
231
232 if (t)
233 {
234 struct atimer *p, *prev;
235
236 /* See if T is active. */
237 for (p = atimers, prev = NULL; p && p != t; prev = p, p = p->next)
238 ;
239
240 if (p == t)
241 {
242 if (prev)
243 prev->next = t->next;
244 else
245 atimers = t->next;
246 t->next = NULL;
247 }
248 else
249 /* T is not active. Let's handle this like T == 0. */
250 t = NULL;
251 }
252
253 stopped_atimers = append_atimer_lists (atimers, stopped_atimers);
254 atimers = t;
255 unblock_atimers (&oldset);
256 }
257
258
259 /* Run all timers again, if some have been stopped with a call to
260 stop_other_atimers. */
261
262 void
263 run_all_atimers (void)
264 {
265 if (stopped_atimers)
266 {
267 struct atimer *t = atimers;
268 struct atimer *next;
269 sigset_t oldset;
270
271 block_atimers (&oldset);
272 atimers = stopped_atimers;
273 stopped_atimers = NULL;
274
275 while (t)
276 {
277 next = t->next;
278 schedule_atimer (t);
279 t = next;
280 }
281
282 unblock_atimers (&oldset);
283 }
284 }
285
286
287 /* Arrange for a SIGALRM to arrive when the next timer is ripe. */
288
289 static void
290 set_alarm (void)
291 {
292 if (atimers)
293 {
294 #ifdef HAVE_SETITIMER
295 struct itimerval it;
296 #endif
297 struct timespec now, interval;
298
299 #ifdef HAVE_ITIMERSPEC
300 if (0 <= timerfd || alarm_timer_ok)
301 {
302 struct itimerspec ispec;
303 ispec.it_value = atimers->expiration;
304 ispec.it_interval.tv_sec = ispec.it_interval.tv_nsec = 0;
305 # ifdef HAVE_TIMERFD
306 if (timerfd_settime (timerfd, TFD_TIMER_ABSTIME, &ispec, 0) == 0)
307 {
308 add_timer_wait_descriptor (timerfd);
309 return;
310 }
311 # endif
312 if (alarm_timer_ok
313 && timer_settime (alarm_timer, TIMER_ABSTIME, &ispec, 0) == 0)
314 return;
315 }
316 #endif
317
318 /* Determine interval till the next timer is ripe.
319 Don't set the interval to 0; this disables the timer. */
320 now = current_timespec ();
321 interval = (timespec_cmp (atimers->expiration, now) <= 0
322 ? make_timespec (0, 1000 * 1000)
323 : timespec_sub (atimers->expiration, now));
324
325 #ifdef HAVE_SETITIMER
326
327 memset (&it, 0, sizeof it);
328 it.it_value = make_timeval (interval);
329 setitimer (ITIMER_REAL, &it, 0);
330 #else /* not HAVE_SETITIMER */
331 alarm (max (interval.tv_sec, 1));
332 #endif /* not HAVE_SETITIMER */
333 }
334 }
335
336
337 /* Insert timer T into the list of active atimers `atimers', keeping
338 the list sorted by expiration time. T must not be in this list
339 already. */
340
341 static void
342 schedule_atimer (struct atimer *t)
343 {
344 struct atimer *a = atimers, *prev = NULL;
345
346 /* Look for the first atimer that is ripe after T. */
347 while (a && timespec_cmp (a->expiration, t->expiration) < 0)
348 prev = a, a = a->next;
349
350 /* Insert T in front of the atimer found, if any. */
351 if (prev)
352 prev->next = t;
353 else
354 atimers = t;
355
356 t->next = a;
357 }
358
359 static void
360 run_timers (void)
361 {
362 struct timespec now = current_timespec ();
363
364 while (atimers && timespec_cmp (atimers->expiration, now) <= 0)
365 {
366 struct atimer *t = atimers;
367 atimers = atimers->next;
368 t->fn (t);
369
370 if (t->type == ATIMER_CONTINUOUS)
371 {
372 t->expiration = timespec_add (now, t->interval);
373 schedule_atimer (t);
374 }
375 else
376 {
377 t->next = free_atimers;
378 free_atimers = t;
379 }
380 }
381
382 set_alarm ();
383 }
384
385
386 /* Signal handler for SIGALRM. SIGNO is the signal number, i.e.
387 SIGALRM. */
388
389 static void
390 handle_alarm_signal (int sig)
391 {
392 pending_signals = 1;
393 }
394
395 #ifdef HAVE_TIMERFD
396
397 /* Called from wait_reading_process_output when FD, which
398 should be equal to TIMERFD, is available for reading. */
399
400 void
401 timerfd_callback (int fd, void *arg)
402 {
403 ptrdiff_t nbytes;
404 uint64_t expirations;
405
406 eassert (fd == timerfd);
407 nbytes = emacs_read (fd, &expirations, sizeof (expirations));
408
409 if (nbytes == sizeof (expirations))
410 {
411 /* Timer should expire just once. */
412 eassert (expirations == 1);
413 do_pending_atimers ();
414 }
415 else if (nbytes < 0)
416 /* For some not yet known reason, we may get weird event and no
417 data on timer descriptor. This can break Gnus at least, see:
418 http://lists.gnu.org/archive/html/emacs-devel/2014-07/msg00503.html. */
419 eassert (errno == EAGAIN);
420 else
421 /* I don't know what else can happen with this descriptor. */
422 emacs_abort ();
423 }
424
425 #endif /* HAVE_TIMERFD */
426
427 /* Do pending timers. */
428
429 void
430 do_pending_atimers (void)
431 {
432 if (atimers)
433 {
434 sigset_t oldset;
435 block_atimers (&oldset);
436 run_timers ();
437 unblock_atimers (&oldset);
438 }
439 }
440
441
442 /* Turn alarms on/off. This seems to be temporarily necessary on
443 some systems like HPUX (see process.c). */
444
445 void
446 turn_on_atimers (bool on)
447 {
448 if (on)
449 set_alarm ();
450 else
451 {
452 #ifdef HAVE_ITIMERSPEC
453 struct itimerspec ispec;
454 memset (&ispec, 0, sizeof ispec);
455 if (alarm_timer_ok)
456 timer_settime (alarm_timer, TIMER_ABSTIME, &ispec, 0);
457 # ifdef HAVE_TIMERFD
458 timerfd_settime (timerfd, TFD_TIMER_ABSTIME, &ispec, 0);
459 # endif
460 #endif
461 alarm (0);
462 }
463 }
464
465 /* This is intended to use from automated tests. */
466
467 #ifdef ENABLE_CHECKING
468
469 #define MAXTIMERS 10
470
471 struct atimer_result
472 {
473 /* Time when we expect this timer to trigger. */
474 struct timespec expected;
475
476 /* Timer status: -1 if not triggered, 0 if triggered
477 too early or too late, 1 if triggered timely. */
478 int intime;
479 };
480
481 static void
482 debug_timer_callback (struct atimer *t)
483 {
484 struct timespec now = current_timespec ();
485 struct atimer_result *r = (struct atimer_result *) t->client_data;
486 int result = timespec_cmp (now, r->expected);
487
488 if (result < 0)
489 /* Too early. */
490 r->intime = 0;
491 else if (result >= 0)
492 {
493 #ifdef HAVE_SETITIMER
494 struct timespec delta = timespec_sub (now, r->expected);
495 /* Too late if later than expected + 0.01s. FIXME:
496 this should depend from system clock resolution. */
497 if (timespec_cmp (delta, make_timespec (0, 10000000)) > 0)
498 r->intime = 0;
499 else
500 #endif /* HAVE_SETITIMER */
501 r->intime = 1;
502 }
503 }
504
505 DEFUN ("debug-timer-check", Fdebug_timer_check, Sdebug_timer_check, 0, 0, 0,
506 doc: /* Run internal self-tests to check timers subsystem.
507 Return t if all self-tests are passed, nil otherwise. */)
508 (void)
509 {
510 int i, ok;
511 struct atimer *timer;
512 struct atimer_result *results[MAXTIMERS];
513 struct timespec t = make_timespec (0, 0);
514
515 /* Arm MAXTIMERS relative timers to trigger with 0.1s intervals. */
516 for (i = 0; i < MAXTIMERS; i++)
517 {
518 results[i] = xmalloc (sizeof (struct atimer_result));
519 t = timespec_add (t, make_timespec (0, 100000000));
520 results[i]->expected = timespec_add (current_timespec (), t);
521 results[i]->intime = -1;
522 timer = start_atimer (ATIMER_RELATIVE, t,
523 debug_timer_callback, results[i]);
524 }
525
526 /* Wait for 1s but process timers. */
527 wait_reading_process_output (1, 0, 0, false, Qnil, NULL, 0);
528 /* Shut up the compiler by "using" this variable. */
529 (void) timer;
530
531 for (i = 0, ok = 0; i < MAXTIMERS; i++)
532 ok += results[i]->intime, xfree (results[i]);
533
534 return ok == MAXTIMERS ? Qt : Qnil;
535 }
536
537 #endif /* ENABLE_CHECKING */
538
539 void
540 init_atimer (void)
541 {
542 #ifdef HAVE_ITIMERSPEC
543 # ifdef HAVE_TIMERFD
544 /* Until this feature is considered stable, you can ask to not use it. */
545 timerfd = (egetenv ("EMACS_IGNORE_TIMERFD") ? -1 :
546 timerfd_create (CLOCK_REALTIME, TFD_NONBLOCK | TFD_CLOEXEC));
547 # endif
548 if (timerfd < 0)
549 {
550 struct sigevent sigev;
551 sigev.sigev_notify = SIGEV_SIGNAL;
552 sigev.sigev_signo = SIGALRM;
553 sigev.sigev_value.sival_ptr = &alarm_timer;
554 alarm_timer_ok
555 = timer_create (CLOCK_REALTIME, &sigev, &alarm_timer) == 0;
556 }
557 #endif
558 free_atimers = stopped_atimers = atimers = NULL;
559
560 /* pending_signals is initialized in init_keyboard. */
561 struct sigaction action;
562 emacs_sigaction_init (&action, handle_alarm_signal);
563 sigaction (SIGALRM, &action, 0);
564
565 #ifdef ENABLE_CHECKING
566 defsubr (&Sdebug_timer_check);
567 #endif
568 }