1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-mainloop.c Main loop utility
4 * Copyright (C) 2003, 2004 Red Hat, Inc.
6 * Licensed under the Academic Free License version 2.1
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include "dbus-mainloop.h"
26 #ifndef DOXYGEN_SHOULD_SKIP_THIS
28 #include <dbus/dbus-list.h>
29 #include <dbus/dbus-sysdeps.h>
31 #define MAINLOOP_SPEW 0
34 #ifdef DBUS_ENABLE_VERBOSE_MODE
36 watch_flags_to_string (int flags)
38 const char *watch_type;
40 if ((flags & DBUS_WATCH_READABLE) &&
41 (flags & DBUS_WATCH_WRITABLE))
42 watch_type = "readwrite";
43 else if (flags & DBUS_WATCH_READABLE)
45 else if (flags & DBUS_WATCH_WRITABLE)
48 watch_type = "not read or write";
51 #endif /* DBUS_ENABLE_VERBOSE_MODE */
52 #endif /* MAINLOOP_SPEW */
58 int callback_list_serial;
61 int depth; /**< number of recursive runs */
62 DBusList *need_dispatch;
76 DBusFreeFunction free_data_func;
82 DBusWatchFunction function;
84 /* last watch handle failed due to OOM */
85 unsigned int last_iteration_oom : 1;
92 DBusTimeoutFunction function;
93 unsigned long last_tv_sec;
94 unsigned long last_tv_usec;
97 #define WATCH_CALLBACK(callback) ((WatchCallback*)callback)
98 #define TIMEOUT_CALLBACK(callback) ((TimeoutCallback*)callback)
100 static WatchCallback*
101 watch_callback_new (DBusWatch *watch,
102 DBusWatchFunction function,
104 DBusFreeFunction free_data_func)
108 cb = dbus_new (WatchCallback, 1);
113 cb->function = function;
114 cb->last_iteration_oom = FALSE;
115 cb->callback.refcount = 1;
116 cb->callback.type = CALLBACK_WATCH;
117 cb->callback.data = data;
118 cb->callback.free_data_func = free_data_func;
123 static TimeoutCallback*
124 timeout_callback_new (DBusTimeout *timeout,
125 DBusTimeoutFunction function,
127 DBusFreeFunction free_data_func)
131 cb = dbus_new (TimeoutCallback, 1);
135 cb->timeout = timeout;
136 cb->function = function;
137 _dbus_get_current_time (&cb->last_tv_sec,
139 cb->callback.refcount = 1;
140 cb->callback.type = CALLBACK_TIMEOUT;
141 cb->callback.data = data;
142 cb->callback.free_data_func = free_data_func;
148 callback_ref (Callback *cb)
150 _dbus_assert (cb->refcount > 0);
158 callback_unref (Callback *cb)
160 _dbus_assert (cb->refcount > 0);
164 if (cb->refcount == 0)
166 if (cb->free_data_func)
167 (* cb->free_data_func) (cb->data);
174 add_callback (DBusLoop *loop,
177 if (!_dbus_list_append (&loop->callbacks, cb))
180 loop->callback_list_serial += 1;
185 loop->watch_count += 1;
187 case CALLBACK_TIMEOUT:
188 loop->timeout_count += 1;
196 remove_callback (DBusLoop *loop,
199 Callback *cb = link->data;
204 loop->watch_count -= 1;
206 case CALLBACK_TIMEOUT:
207 loop->timeout_count -= 1;
212 _dbus_list_remove_link (&loop->callbacks, link);
213 loop->callback_list_serial += 1;
217 _dbus_loop_new (void)
221 loop = dbus_new0 (DBusLoop, 1);
231 _dbus_loop_ref (DBusLoop *loop)
233 _dbus_assert (loop != NULL);
234 _dbus_assert (loop->refcount > 0);
242 _dbus_loop_unref (DBusLoop *loop)
244 _dbus_assert (loop != NULL);
245 _dbus_assert (loop->refcount > 0);
248 if (loop->refcount == 0)
250 while (loop->need_dispatch)
252 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
254 dbus_connection_unref (connection);
262 _dbus_loop_add_watch (DBusLoop *loop,
264 DBusWatchFunction function,
266 DBusFreeFunction free_data_func)
270 wcb = watch_callback_new (watch, function, data, free_data_func);
274 if (!add_callback (loop, (Callback*) wcb))
276 wcb->callback.free_data_func = NULL; /* don't want to have this side effect */
277 callback_unref ((Callback*) wcb);
285 _dbus_loop_remove_watch (DBusLoop *loop,
287 DBusWatchFunction function,
292 link = _dbus_list_get_first_link (&loop->callbacks);
295 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
296 Callback *this = link->data;
298 if (this->type == CALLBACK_WATCH &&
299 WATCH_CALLBACK (this)->watch == watch &&
300 this->data == data &&
301 WATCH_CALLBACK (this)->function == function)
303 remove_callback (loop, link);
311 _dbus_warn ("could not find watch %p function %p data %p to remove\n",
312 watch, (void *)function, data);
316 _dbus_loop_add_timeout (DBusLoop *loop,
317 DBusTimeout *timeout,
318 DBusTimeoutFunction function,
320 DBusFreeFunction free_data_func)
322 TimeoutCallback *tcb;
324 tcb = timeout_callback_new (timeout, function, data, free_data_func);
328 if (!add_callback (loop, (Callback*) tcb))
330 tcb->callback.free_data_func = NULL; /* don't want to have this side effect */
331 callback_unref ((Callback*) tcb);
339 _dbus_loop_remove_timeout (DBusLoop *loop,
340 DBusTimeout *timeout,
341 DBusTimeoutFunction function,
346 link = _dbus_list_get_first_link (&loop->callbacks);
349 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
350 Callback *this = link->data;
352 if (this->type == CALLBACK_TIMEOUT &&
353 TIMEOUT_CALLBACK (this)->timeout == timeout &&
354 this->data == data &&
355 TIMEOUT_CALLBACK (this)->function == function)
357 remove_callback (loop, link);
365 _dbus_warn ("could not find timeout %p function %p data %p to remove\n",
366 timeout, (void *)function, data);
369 /* Convolutions from GLib, there really must be a better way
373 check_timeout (unsigned long tv_sec,
374 unsigned long tv_usec,
375 TimeoutCallback *tcb,
380 unsigned long expiration_tv_sec;
381 unsigned long expiration_tv_usec;
382 long interval_seconds;
383 long interval_milliseconds;
386 /* I'm pretty sure this function could suck (a lot) less */
388 interval = dbus_timeout_get_interval (tcb->timeout);
390 interval_seconds = interval / 1000L;
391 interval_milliseconds = interval % 1000L;
393 expiration_tv_sec = tcb->last_tv_sec + interval_seconds;
394 expiration_tv_usec = tcb->last_tv_usec + interval_milliseconds * 1000;
395 if (expiration_tv_usec >= 1000000)
397 expiration_tv_usec -= 1000000;
398 expiration_tv_sec += 1;
401 sec_remaining = expiration_tv_sec - tv_sec;
402 /* need to force this to be signed, as it is intended to sometimes
403 * produce a negative result
405 msec_remaining = ((long) expiration_tv_usec - (long) tv_usec) / 1000L;
408 _dbus_verbose ("Interval is %ld seconds %ld msecs\n",
410 interval_milliseconds);
411 _dbus_verbose ("Now is %lu seconds %lu usecs\n",
413 _dbus_verbose ("Last is %lu seconds %lu usecs\n",
414 tcb->last_tv_sec, tcb->last_tv_usec);
415 _dbus_verbose ("Exp is %lu seconds %lu usecs\n",
416 expiration_tv_sec, expiration_tv_usec);
417 _dbus_verbose ("Pre-correction, sec_remaining %ld msec_remaining %ld\n",
418 sec_remaining, msec_remaining);
421 /* We do the following in a rather convoluted fashion to deal with
422 * the fact that we don't have an integral type big enough to hold
423 * the difference of two timevals in milliseconds.
425 if (sec_remaining < 0 || (sec_remaining == 0 && msec_remaining < 0))
431 if (msec_remaining < 0)
433 msec_remaining += 1000;
437 if (sec_remaining > (_DBUS_INT_MAX / 1000) ||
438 msec_remaining > _DBUS_INT_MAX)
439 *timeout = _DBUS_INT_MAX;
441 *timeout = sec_remaining * 1000 + msec_remaining;
444 if (*timeout > interval)
446 /* This indicates that the system clock probably moved backward */
447 _dbus_verbose ("System clock set backward! Resetting timeout.\n");
449 tcb->last_tv_sec = tv_sec;
450 tcb->last_tv_usec = tv_usec;
456 _dbus_verbose (" timeout expires in %d milliseconds\n", *timeout);
459 return *timeout == 0;
463 _dbus_loop_dispatch (DBusLoop *loop)
467 _dbus_verbose (" %d connections to dispatch\n", _dbus_list_get_length (&loop->need_dispatch));
470 if (loop->need_dispatch == NULL)
474 while (loop->need_dispatch != NULL)
476 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
480 DBusDispatchStatus status;
482 status = dbus_connection_dispatch (connection);
484 if (status == DBUS_DISPATCH_COMPLETE)
486 dbus_connection_unref (connection);
491 if (status == DBUS_DISPATCH_NEED_MEMORY)
492 _dbus_wait_for_memory ();
501 _dbus_loop_queue_dispatch (DBusLoop *loop,
502 DBusConnection *connection)
504 if (_dbus_list_append (&loop->need_dispatch, connection))
506 dbus_connection_ref (connection);
513 /* Returns TRUE if we invoked any timeouts or have ready file
514 * descriptors, which is just used in test code as a debug hack
518 _dbus_loop_iterate (DBusLoop *loop,
521 #define N_STACK_DESCRIPTORS 64
524 DBusPollFD stack_fds[N_STACK_DESCRIPTORS];
526 WatchCallback **watches_for_fds;
527 WatchCallback *stack_watches_for_fds[N_STACK_DESCRIPTORS];
533 dbus_bool_t oom_watch_pending;
539 watches_for_fds = NULL;
541 oom_watch_pending = FALSE;
542 orig_depth = loop->depth;
545 _dbus_verbose ("Iteration block=%d depth=%d timeout_count=%d watch_count=%d\n",
546 block, loop->depth, loop->timeout_count, loop->watch_count);
549 if (loop->callbacks == NULL)
552 if (loop->watch_count > N_STACK_DESCRIPTORS)
554 fds = dbus_new0 (DBusPollFD, loop->watch_count);
558 _dbus_wait_for_memory ();
559 fds = dbus_new0 (DBusPollFD, loop->watch_count);
562 watches_for_fds = dbus_new (WatchCallback*, loop->watch_count);
563 while (watches_for_fds == NULL)
565 _dbus_wait_for_memory ();
566 watches_for_fds = dbus_new (WatchCallback*, loop->watch_count);
572 watches_for_fds = stack_watches_for_fds;
575 /* fill our array of fds and watches */
577 link = _dbus_list_get_first_link (&loop->callbacks);
580 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
581 Callback *cb = link->data;
582 if (cb->type == CALLBACK_WATCH)
585 WatchCallback *wcb = WATCH_CALLBACK (cb);
587 if (wcb->last_iteration_oom)
589 /* we skip this one this time, but reenable it next time,
590 * and have a timeout on this iteration
592 wcb->last_iteration_oom = FALSE;
593 oom_watch_pending = TRUE;
595 retval = TRUE; /* return TRUE here to keep the loop going,
596 * since we don't know the watch is inactive
600 _dbus_verbose (" skipping watch on fd %d as it was out of memory last time\n",
601 dbus_watch_get_fd (wcb->watch));
604 else if (dbus_watch_get_enabled (wcb->watch))
606 watches_for_fds[n_fds] = wcb;
610 flags = dbus_watch_get_flags (wcb->watch);
612 fds[n_fds].fd = dbus_watch_get_fd (wcb->watch);
613 fds[n_fds].revents = 0;
614 fds[n_fds].events = 0;
615 if (flags & DBUS_WATCH_READABLE)
616 fds[n_fds].events |= _DBUS_POLLIN;
617 if (flags & DBUS_WATCH_WRITABLE)
618 fds[n_fds].events |= _DBUS_POLLOUT;
621 _dbus_verbose (" polling watch on fd %d %s\n",
622 fds[n_fds].fd, watch_flags_to_string (flags));
630 _dbus_verbose (" skipping disabled watch on fd %d %s\n",
631 dbus_watch_get_fd (wcb->watch),
632 watch_flags_to_string (dbus_watch_get_flags (wcb->watch)));
641 if (loop->timeout_count > 0)
643 unsigned long tv_sec;
644 unsigned long tv_usec;
646 _dbus_get_current_time (&tv_sec, &tv_usec);
648 link = _dbus_list_get_first_link (&loop->callbacks);
651 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
652 Callback *cb = link->data;
654 if (cb->type == CALLBACK_TIMEOUT &&
655 dbus_timeout_get_enabled (TIMEOUT_CALLBACK (cb)->timeout))
657 TimeoutCallback *tcb = TIMEOUT_CALLBACK (cb);
660 check_timeout (tv_sec, tv_usec, tcb, &msecs_remaining);
663 timeout = msecs_remaining;
665 timeout = MIN (msecs_remaining, timeout);
668 _dbus_verbose (" timeout added, %d remaining, aggregate timeout %ld\n",
669 msecs_remaining, timeout);
672 _dbus_assert (timeout >= 0);
675 break; /* it's not going to get shorter... */
678 else if (cb->type == CALLBACK_TIMEOUT)
680 _dbus_verbose (" skipping disabled timeout\n");
688 /* Never block if we have stuff to dispatch */
689 if (!block || loop->need_dispatch != NULL)
693 _dbus_verbose (" timeout is 0 as we aren't blocking\n");
697 /* if a watch is OOM, don't wait longer than the OOM
698 * wait to re-enable it
700 if (oom_watch_pending)
701 timeout = MIN (timeout, _dbus_get_oom_wait ());
704 _dbus_verbose (" polling on %d descriptors timeout %ld\n", n_fds, timeout);
707 n_ready = _dbus_poll (fds, n_fds, timeout);
709 initial_serial = loop->callback_list_serial;
711 if (loop->timeout_count > 0)
713 unsigned long tv_sec;
714 unsigned long tv_usec;
716 _dbus_get_current_time (&tv_sec, &tv_usec);
718 /* It'd be nice to avoid this O(n) thingy here */
719 link = _dbus_list_get_first_link (&loop->callbacks);
722 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
723 Callback *cb = link->data;
725 if (initial_serial != loop->callback_list_serial)
728 if (loop->depth != orig_depth)
731 if (cb->type == CALLBACK_TIMEOUT &&
732 dbus_timeout_get_enabled (TIMEOUT_CALLBACK (cb)->timeout))
734 TimeoutCallback *tcb = TIMEOUT_CALLBACK (cb);
737 if (check_timeout (tv_sec, tv_usec,
738 tcb, &msecs_remaining))
740 /* Save last callback time and fire this timeout */
741 tcb->last_tv_sec = tv_sec;
742 tcb->last_tv_usec = tv_usec;
745 _dbus_verbose (" invoking timeout\n");
748 (* tcb->function) (tcb->timeout,
756 _dbus_verbose (" timeout has not expired\n");
761 else if (cb->type == CALLBACK_TIMEOUT)
763 _dbus_verbose (" skipping invocation of disabled timeout\n");
776 /* FIXME I think this "restart if we change the watches"
777 * approach could result in starving watches
778 * toward the end of the list.
780 if (initial_serial != loop->callback_list_serial)
783 if (loop->depth != orig_depth)
786 if (fds[i].revents != 0)
789 unsigned int condition;
791 wcb = watches_for_fds[i];
794 if (fds[i].revents & _DBUS_POLLIN)
795 condition |= DBUS_WATCH_READABLE;
796 if (fds[i].revents & _DBUS_POLLOUT)
797 condition |= DBUS_WATCH_WRITABLE;
798 if (fds[i].revents & _DBUS_POLLHUP)
799 condition |= DBUS_WATCH_HANGUP;
800 if (fds[i].revents & _DBUS_POLLERR)
801 condition |= DBUS_WATCH_ERROR;
803 /* condition may still be 0 if we got some
804 * weird POLLFOO thing like POLLWRBAND
807 if (condition != 0 &&
808 dbus_watch_get_enabled (wcb->watch))
810 if (!(* wcb->function) (wcb->watch,
812 ((Callback*)wcb)->data))
813 wcb->last_iteration_oom = TRUE;
816 _dbus_verbose (" Invoked watch, oom = %d\n",
817 wcb->last_iteration_oom);
830 _dbus_verbose (" moving to next iteration\n");
833 if (fds && fds != stack_fds)
840 callback_unref (&watches_for_fds[i]->callback);
844 if (watches_for_fds != stack_watches_for_fds)
845 dbus_free (watches_for_fds);
848 if (_dbus_loop_dispatch (loop))
852 _dbus_verbose ("Returning %d\n", retval);
859 _dbus_loop_run (DBusLoop *loop)
863 _dbus_assert (loop->depth >= 0);
865 _dbus_loop_ref (loop);
867 our_exit_depth = loop->depth;
870 _dbus_verbose ("Running main loop, depth %d -> %d\n",
871 loop->depth - 1, loop->depth);
873 while (loop->depth != our_exit_depth)
874 _dbus_loop_iterate (loop, TRUE);
876 _dbus_loop_unref (loop);
880 _dbus_loop_quit (DBusLoop *loop)
882 _dbus_assert (loop->depth > 0);
886 _dbus_verbose ("Quit main loop, depth %d -> %d\n",
887 loop->depth + 1, loop->depth);
891 _dbus_get_oom_wait (void)
893 #ifdef DBUS_BUILD_TESTS
894 /* make tests go fast */
902 _dbus_wait_for_memory (void)
904 _dbus_verbose ("Waiting for more memory\n");
905 _dbus_sleep_milliseconds (_dbus_get_oom_wait ());
908 #endif /* DOXYGEN_SHOULD_SKIP_THIS */