Update copyright year to 2015
[emacs.git] / src / atimer.c
blob8ff9bb89757251fcdbc0056ebde388f7ae6b4e92
1 /* Asynchronous timers.
2 Copyright (C) 2000-2015 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
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.
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.
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/>. */
19 #include <config.h>
20 #include <stdio.h>
22 #include "lisp.h"
23 #include "syssignal.h"
24 #include "systime.h"
25 #include "blockinput.h"
26 #include "atimer.h"
27 #include <unistd.h>
29 #ifdef HAVE_TIMERFD
30 #include <errno.h>
31 # include <sys/timerfd.h>
32 #endif
34 /* Free-list of atimer structures. */
36 static struct atimer *free_atimers;
38 /* List of currently not running timers due to a call to
39 lock_atimer. */
41 static struct atimer *stopped_atimers;
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. */
46 static struct atimer *atimers;
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;
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
62 /* Block/unblock SIGALRM. */
64 static void
65 block_atimers (sigset_t *oldset)
67 sigset_t blocked;
68 sigemptyset (&blocked);
69 sigaddset (&blocked, SIGALRM);
70 sigaddset (&blocked, SIGINT);
71 pthread_sigmask (SIG_BLOCK, &blocked, oldset);
73 static void
74 unblock_atimers (sigset_t const *oldset)
76 pthread_sigmask (SIG_SETMASK, oldset, 0);
79 /* Function prototypes. */
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 *);
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.
91 If TYPE is ATIMER_ABSOLUTE, TIMESTAMP is the absolute time at which the
92 timer fires.
94 If TYPE is ATIMER_RELATIVE, the timer is ripe TIMESTAMP seconds in the
95 future.
97 In both cases, the timer is automatically freed after it has fired.
99 If TYPE is ATIMER_CONTINUOUS, the timer fires every TIMESTAMP seconds.
101 Value is a pointer to the atimer started. It can be used in calls
102 to cancel_atimer; don't free it yourself. */
104 struct atimer *
105 start_atimer (enum atimer_type type, struct timespec timestamp,
106 atimer_callback fn, void *client_data)
108 struct atimer *t;
109 sigset_t oldset;
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 */
117 /* Get an atimer structure from the free-list, or allocate
118 a new one. */
119 if (free_atimers)
121 t = free_atimers;
122 free_atimers = t->next;
124 else
125 t = xmalloc (sizeof *t);
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;
133 block_atimers (&oldset);
135 /* Compute the timer's expiration time. */
136 switch (type)
138 case ATIMER_ABSOLUTE:
139 t->expiration = timestamp;
140 break;
142 case ATIMER_RELATIVE:
143 t->expiration = timespec_add (current_timespec (), timestamp);
144 break;
146 case ATIMER_CONTINUOUS:
147 t->expiration = timespec_add (current_timespec (), timestamp);
148 t->interval = timestamp;
149 break;
152 /* Insert the timer in the list of active atimers. */
153 schedule_atimer (t);
154 unblock_atimers (&oldset);
156 /* Arrange for a SIGALRM at the time the next atimer is ripe. */
157 set_alarm ();
159 return t;
163 /* Cancel and free atimer TIMER. */
165 void
166 cancel_atimer (struct atimer *timer)
168 int i;
169 sigset_t oldset;
171 block_atimers (&oldset);
173 for (i = 0; i < 2; ++i)
175 struct atimer *t, *prev;
176 struct atimer **list = i ? &stopped_atimers : &atimers;
178 /* See if TIMER is active or stopped. */
179 for (t = *list, prev = NULL; t && t != timer; prev = t, t = t->next)
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)
187 if (prev)
188 prev->next = t->next;
189 else
190 *list = t->next;
192 t->next = free_atimers;
193 free_atimers = t;
194 break;
198 unblock_atimers (&oldset);
202 /* Append two lists of atimers LIST_1 and LIST_2 and return the
203 result list. */
205 static struct atimer *
206 append_atimer_lists (struct atimer *list_1, struct atimer *list_2)
208 if (list_1 == NULL)
209 return list_2;
210 else if (list_2 == NULL)
211 return list_1;
212 else
214 struct atimer *p;
216 for (p = list_1; p->next; p = p->next)
218 p->next = list_2;
219 return list_1;
224 /* Stop all timers except timer T. T null means stop all timers. */
226 void
227 stop_other_atimers (struct atimer *t)
229 sigset_t oldset;
230 block_atimers (&oldset);
232 if (t)
234 struct atimer *p, *prev;
236 /* See if T is active. */
237 for (p = atimers, prev = NULL; p && p != t; prev = p, p = p->next)
240 if (p == t)
242 if (prev)
243 prev->next = t->next;
244 else
245 atimers = t->next;
246 t->next = NULL;
248 else
249 /* T is not active. Let's handle this like T == 0. */
250 t = NULL;
253 stopped_atimers = append_atimer_lists (atimers, stopped_atimers);
254 atimers = t;
255 unblock_atimers (&oldset);
259 /* Run all timers again, if some have been stopped with a call to
260 stop_other_atimers. */
262 void
263 run_all_atimers (void)
265 if (stopped_atimers)
267 struct atimer *t = atimers;
268 struct atimer *next;
269 sigset_t oldset;
271 block_atimers (&oldset);
272 atimers = stopped_atimers;
273 stopped_atimers = NULL;
275 while (t)
277 next = t->next;
278 schedule_atimer (t);
279 t = next;
282 unblock_atimers (&oldset);
287 /* Arrange for a SIGALRM to arrive when the next timer is ripe. */
289 static void
290 set_alarm (void)
292 if (atimers)
294 #ifdef HAVE_SETITIMER
295 struct itimerval it;
296 #endif
297 struct timespec now, interval;
299 #ifdef HAVE_ITIMERSPEC
300 if (0 <= timerfd || alarm_timer_ok)
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)
308 add_timer_wait_descriptor (timerfd);
309 return;
311 # endif
312 if (alarm_timer_ok
313 && timer_settime (alarm_timer, TIMER_ABSTIME, &ispec, 0) == 0)
314 return;
316 #endif
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));
325 #ifdef HAVE_SETITIMER
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 */
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. */
341 static void
342 schedule_atimer (struct atimer *t)
344 struct atimer *a = atimers, *prev = NULL;
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;
350 /* Insert T in front of the atimer found, if any. */
351 if (prev)
352 prev->next = t;
353 else
354 atimers = t;
356 t->next = a;
359 static void
360 run_timers (void)
362 struct timespec now = current_timespec ();
364 while (atimers && timespec_cmp (atimers->expiration, now) <= 0)
366 struct atimer *t = atimers;
367 atimers = atimers->next;
368 t->fn (t);
370 if (t->type == ATIMER_CONTINUOUS)
372 t->expiration = timespec_add (now, t->interval);
373 schedule_atimer (t);
375 else
377 t->next = free_atimers;
378 free_atimers = t;
382 set_alarm ();
386 /* Signal handler for SIGALRM. SIGNO is the signal number, i.e.
387 SIGALRM. */
389 static void
390 handle_alarm_signal (int sig)
392 pending_signals = 1;
395 #ifdef HAVE_TIMERFD
397 /* Called from wait_reading_process_output when FD, which
398 should be equal to TIMERFD, is available for reading. */
400 void
401 timerfd_callback (int fd, void *arg)
403 ptrdiff_t nbytes;
404 uint64_t expirations;
406 eassert (fd == timerfd);
407 nbytes = emacs_read (fd, &expirations, sizeof (expirations));
409 if (nbytes == sizeof (expirations))
411 /* Timer should expire just once. */
412 eassert (expirations == 1);
413 do_pending_atimers ();
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 ();
425 #endif /* HAVE_TIMERFD */
427 /* Do pending timers. */
429 void
430 do_pending_atimers (void)
432 if (atimers)
434 sigset_t oldset;
435 block_atimers (&oldset);
436 run_timers ();
437 unblock_atimers (&oldset);
442 /* Turn alarms on/off. This seems to be temporarily necessary on
443 some systems like HPUX (see process.c). */
445 void
446 turn_on_atimers (bool on)
448 if (on)
449 set_alarm ();
450 else
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);
465 /* This is intended to use from automated tests. */
467 #ifdef ENABLE_CHECKING
469 #define MAXTIMERS 10
471 struct atimer_result
473 /* Time when we expect this timer to trigger. */
474 struct timespec expected;
476 /* Timer status: -1 if not triggered, 0 if triggered
477 too early or too late, 1 if triggered timely. */
478 int intime;
481 static void
482 debug_timer_callback (struct atimer *t)
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);
488 if (result < 0)
489 /* Too early. */
490 r->intime = 0;
491 else if (result >= 0)
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;
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)
510 int i, ok;
511 struct atimer *timer;
512 struct atimer_result *results[MAXTIMERS];
513 struct timespec t = make_timespec (0, 0);
515 /* Arm MAXTIMERS relative timers to trigger with 0.1s intervals. */
516 for (i = 0; i < MAXTIMERS; i++)
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]);
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;
531 for (i = 0, ok = 0; i < MAXTIMERS; i++)
532 ok += results[i]->intime, xfree (results[i]);
534 return ok == MAXTIMERS ? Qt : Qnil;
537 #endif /* ENABLE_CHECKING */
539 void
540 init_atimer (void)
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)
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;
557 #endif
558 free_atimers = stopped_atimers = atimers = NULL;
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);
565 #ifdef ENABLE_CHECKING
566 defsubr (&Sdebug_timer_check);
567 #endif