1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "dbus-mainloop.h"
27 #ifndef DOXYGEN_SHOULD_SKIP_THIS
29 #include <dbus/dbus-list.h>
30 #include <dbus/dbus-sysdeps.h>
31 #include <dbus/dbus-watch.h>
33 #define MAINLOOP_SPEW 0
36 #ifdef DBUS_ENABLE_VERBOSE_MODE
38 watch_flags_to_string (int flags)
40 const char *watch_type;
42 if ((flags & DBUS_WATCH_READABLE) &&
43 (flags & DBUS_WATCH_WRITABLE))
44 watch_type = "readwrite";
45 else if (flags & DBUS_WATCH_READABLE)
47 else if (flags & DBUS_WATCH_WRITABLE)
50 watch_type = "not read or write";
53 #endif /* DBUS_ENABLE_VERBOSE_MODE */
54 #endif /* MAINLOOP_SPEW */
60 int callback_list_serial;
63 int depth; /**< number of recursive runs */
64 DBusList *need_dispatch;
78 DBusFreeFunction free_data_func;
84 DBusWatchFunction function;
86 /* last watch handle failed due to OOM */
87 unsigned int last_iteration_oom : 1;
94 DBusTimeoutFunction function;
95 unsigned long last_tv_sec;
96 unsigned long last_tv_usec;
99 #define WATCH_CALLBACK(callback) ((WatchCallback*)callback)
100 #define TIMEOUT_CALLBACK(callback) ((TimeoutCallback*)callback)
102 static WatchCallback*
103 watch_callback_new (DBusWatch *watch,
104 DBusWatchFunction function,
106 DBusFreeFunction free_data_func)
110 cb = dbus_new (WatchCallback, 1);
115 cb->function = function;
116 cb->last_iteration_oom = FALSE;
117 cb->callback.refcount = 1;
118 cb->callback.type = CALLBACK_WATCH;
119 cb->callback.data = data;
120 cb->callback.free_data_func = free_data_func;
125 static TimeoutCallback*
126 timeout_callback_new (DBusTimeout *timeout,
127 DBusTimeoutFunction function,
129 DBusFreeFunction free_data_func)
133 cb = dbus_new (TimeoutCallback, 1);
137 cb->timeout = timeout;
138 cb->function = function;
139 _dbus_get_current_time (&cb->last_tv_sec,
141 cb->callback.refcount = 1;
142 cb->callback.type = CALLBACK_TIMEOUT;
143 cb->callback.data = data;
144 cb->callback.free_data_func = free_data_func;
150 callback_ref (Callback *cb)
152 _dbus_assert (cb->refcount > 0);
160 callback_unref (Callback *cb)
162 _dbus_assert (cb->refcount > 0);
166 if (cb->refcount == 0)
168 if (cb->free_data_func)
169 (* cb->free_data_func) (cb->data);
176 add_callback (DBusLoop *loop,
179 if (!_dbus_list_append (&loop->callbacks, cb))
182 loop->callback_list_serial += 1;
187 loop->watch_count += 1;
189 case CALLBACK_TIMEOUT:
190 loop->timeout_count += 1;
198 remove_callback (DBusLoop *loop,
201 Callback *cb = link->data;
206 loop->watch_count -= 1;
208 case CALLBACK_TIMEOUT:
209 loop->timeout_count -= 1;
214 _dbus_list_remove_link (&loop->callbacks, link);
215 loop->callback_list_serial += 1;
219 _dbus_loop_new (void)
223 loop = dbus_new0 (DBusLoop, 1);
233 _dbus_loop_ref (DBusLoop *loop)
235 _dbus_assert (loop != NULL);
236 _dbus_assert (loop->refcount > 0);
244 _dbus_loop_unref (DBusLoop *loop)
246 _dbus_assert (loop != NULL);
247 _dbus_assert (loop->refcount > 0);
250 if (loop->refcount == 0)
252 while (loop->need_dispatch)
254 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
256 dbus_connection_unref (connection);
264 _dbus_loop_add_watch (DBusLoop *loop,
266 DBusWatchFunction function,
268 DBusFreeFunction free_data_func)
272 wcb = watch_callback_new (watch, function, data, free_data_func);
276 if (!add_callback (loop, (Callback*) wcb))
278 wcb->callback.free_data_func = NULL; /* don't want to have this side effect */
279 callback_unref ((Callback*) wcb);
287 _dbus_loop_remove_watch (DBusLoop *loop,
289 DBusWatchFunction function,
294 link = _dbus_list_get_first_link (&loop->callbacks);
297 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
298 Callback *this = link->data;
300 if (this->type == CALLBACK_WATCH &&
301 WATCH_CALLBACK (this)->watch == watch &&
302 this->data == data &&
303 WATCH_CALLBACK (this)->function == function)
305 remove_callback (loop, link);
313 _dbus_warn ("could not find watch %p function %p data %p to remove\n",
314 watch, (void *)function, data);
318 _dbus_loop_add_timeout (DBusLoop *loop,
319 DBusTimeout *timeout,
320 DBusTimeoutFunction function,
322 DBusFreeFunction free_data_func)
324 TimeoutCallback *tcb;
326 tcb = timeout_callback_new (timeout, function, data, free_data_func);
330 if (!add_callback (loop, (Callback*) tcb))
332 tcb->callback.free_data_func = NULL; /* don't want to have this side effect */
333 callback_unref ((Callback*) tcb);
341 _dbus_loop_remove_timeout (DBusLoop *loop,
342 DBusTimeout *timeout,
343 DBusTimeoutFunction function,
348 link = _dbus_list_get_first_link (&loop->callbacks);
351 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
352 Callback *this = link->data;
354 if (this->type == CALLBACK_TIMEOUT &&
355 TIMEOUT_CALLBACK (this)->timeout == timeout &&
356 this->data == data &&
357 TIMEOUT_CALLBACK (this)->function == function)
359 remove_callback (loop, link);
367 _dbus_warn ("could not find timeout %p function %p data %p to remove\n",
368 timeout, (void *)function, data);
371 /* Convolutions from GLib, there really must be a better way
375 check_timeout (unsigned long tv_sec,
376 unsigned long tv_usec,
377 TimeoutCallback *tcb,
382 unsigned long expiration_tv_sec;
383 unsigned long expiration_tv_usec;
384 long interval_seconds;
385 long interval_milliseconds;
388 /* I'm pretty sure this function could suck (a lot) less */
390 interval = dbus_timeout_get_interval (tcb->timeout);
392 interval_seconds = interval / 1000L;
393 interval_milliseconds = interval % 1000L;
395 expiration_tv_sec = tcb->last_tv_sec + interval_seconds;
396 expiration_tv_usec = tcb->last_tv_usec + interval_milliseconds * 1000;
397 if (expiration_tv_usec >= 1000000)
399 expiration_tv_usec -= 1000000;
400 expiration_tv_sec += 1;
403 sec_remaining = expiration_tv_sec - tv_sec;
404 /* need to force this to be signed, as it is intended to sometimes
405 * produce a negative result
407 msec_remaining = ((long) expiration_tv_usec - (long) tv_usec) / 1000L;
410 _dbus_verbose ("Interval is %ld seconds %ld msecs\n",
412 interval_milliseconds);
413 _dbus_verbose ("Now is %lu seconds %lu usecs\n",
415 _dbus_verbose ("Last is %lu seconds %lu usecs\n",
416 tcb->last_tv_sec, tcb->last_tv_usec);
417 _dbus_verbose ("Exp is %lu seconds %lu usecs\n",
418 expiration_tv_sec, expiration_tv_usec);
419 _dbus_verbose ("Pre-correction, sec_remaining %ld msec_remaining %ld\n",
420 sec_remaining, msec_remaining);
423 /* We do the following in a rather convoluted fashion to deal with
424 * the fact that we don't have an integral type big enough to hold
425 * the difference of two timevals in milliseconds.
427 if (sec_remaining < 0 || (sec_remaining == 0 && msec_remaining < 0))
433 if (msec_remaining < 0)
435 msec_remaining += 1000;
439 if (sec_remaining > (_DBUS_INT_MAX / 1000) ||
440 msec_remaining > _DBUS_INT_MAX)
441 *timeout = _DBUS_INT_MAX;
443 *timeout = sec_remaining * 1000 + msec_remaining;
446 if (*timeout > interval)
448 /* This indicates that the system clock probably moved backward */
449 _dbus_verbose ("System clock set backward! Resetting timeout.\n");
451 tcb->last_tv_sec = tv_sec;
452 tcb->last_tv_usec = tv_usec;
458 _dbus_verbose (" timeout expires in %d milliseconds\n", *timeout);
461 return *timeout == 0;
465 _dbus_loop_dispatch (DBusLoop *loop)
469 _dbus_verbose (" %d connections to dispatch\n", _dbus_list_get_length (&loop->need_dispatch));
472 if (loop->need_dispatch == NULL)
476 while (loop->need_dispatch != NULL)
478 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
482 DBusDispatchStatus status;
484 status = dbus_connection_dispatch (connection);
486 if (status == DBUS_DISPATCH_COMPLETE)
488 dbus_connection_unref (connection);
493 if (status == DBUS_DISPATCH_NEED_MEMORY)
494 _dbus_wait_for_memory ();
503 _dbus_loop_queue_dispatch (DBusLoop *loop,
504 DBusConnection *connection)
506 if (_dbus_list_append (&loop->need_dispatch, connection))
508 dbus_connection_ref (connection);
515 /* Returns TRUE if we invoked any timeouts or have ready file
516 * descriptors, which is just used in test code as a debug hack
520 _dbus_loop_iterate (DBusLoop *loop,
523 #define N_STACK_DESCRIPTORS 64
526 DBusPollFD stack_fds[N_STACK_DESCRIPTORS];
528 WatchCallback **watches_for_fds;
529 WatchCallback *stack_watches_for_fds[N_STACK_DESCRIPTORS];
535 dbus_bool_t oom_watch_pending;
541 watches_for_fds = NULL;
543 oom_watch_pending = FALSE;
544 orig_depth = loop->depth;
547 _dbus_verbose ("Iteration block=%d depth=%d timeout_count=%d watch_count=%d\n",
548 block, loop->depth, loop->timeout_count, loop->watch_count);
551 if (loop->callbacks == NULL)
554 if (loop->watch_count > N_STACK_DESCRIPTORS)
556 fds = dbus_new0 (DBusPollFD, loop->watch_count);
560 _dbus_wait_for_memory ();
561 fds = dbus_new0 (DBusPollFD, loop->watch_count);
564 watches_for_fds = dbus_new (WatchCallback*, loop->watch_count);
565 while (watches_for_fds == NULL)
567 _dbus_wait_for_memory ();
568 watches_for_fds = dbus_new (WatchCallback*, loop->watch_count);
574 watches_for_fds = stack_watches_for_fds;
577 /* fill our array of fds and watches */
579 link = _dbus_list_get_first_link (&loop->callbacks);
582 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
583 Callback *cb = link->data;
584 if (cb->type == CALLBACK_WATCH)
587 WatchCallback *wcb = WATCH_CALLBACK (cb);
588 int fd = dbus_watch_get_socket (wcb->watch);
590 if (wcb->last_iteration_oom)
592 /* we skip this one this time, but reenable it next time,
593 * and have a timeout on this iteration
595 wcb->last_iteration_oom = FALSE;
596 oom_watch_pending = TRUE;
598 retval = TRUE; /* return TRUE here to keep the loop going,
599 * since we don't know the watch is inactive
603 _dbus_verbose (" skipping watch on fd %d as it was out of memory last time\n",
607 else if (_DBUS_UNLIKELY (fd == -1))
609 _dbus_warn ("watch %p was invalidated but not removed; "
610 "removing it now\n", wcb->watch);
611 _dbus_loop_remove_watch (loop, wcb->watch, wcb->function,
612 ((Callback *)wcb)->data);
614 else if (dbus_watch_get_enabled (wcb->watch))
616 watches_for_fds[n_fds] = wcb;
620 flags = dbus_watch_get_flags (wcb->watch);
623 fds[n_fds].revents = 0;
624 fds[n_fds].events = 0;
625 if (flags & DBUS_WATCH_READABLE)
626 fds[n_fds].events |= _DBUS_POLLIN;
627 if (flags & DBUS_WATCH_WRITABLE)
628 fds[n_fds].events |= _DBUS_POLLOUT;
631 _dbus_verbose (" polling watch on fd %d %s\n",
632 fd, watch_flags_to_string (flags));
640 _dbus_verbose (" skipping disabled watch on fd %d %s\n",
642 watch_flags_to_string (dbus_watch_get_flags (wcb->watch)));
651 if (loop->timeout_count > 0)
653 unsigned long tv_sec;
654 unsigned long tv_usec;
656 _dbus_get_current_time (&tv_sec, &tv_usec);
658 link = _dbus_list_get_first_link (&loop->callbacks);
661 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
662 Callback *cb = link->data;
664 if (cb->type == CALLBACK_TIMEOUT &&
665 dbus_timeout_get_enabled (TIMEOUT_CALLBACK (cb)->timeout))
667 TimeoutCallback *tcb = TIMEOUT_CALLBACK (cb);
670 check_timeout (tv_sec, tv_usec, tcb, &msecs_remaining);
673 timeout = msecs_remaining;
675 timeout = MIN (msecs_remaining, timeout);
678 _dbus_verbose (" timeout added, %d remaining, aggregate timeout %ld\n",
679 msecs_remaining, timeout);
682 _dbus_assert (timeout >= 0);
685 break; /* it's not going to get shorter... */
688 else if (cb->type == CALLBACK_TIMEOUT)
690 _dbus_verbose (" skipping disabled timeout\n");
698 /* Never block if we have stuff to dispatch */
699 if (!block || loop->need_dispatch != NULL)
703 _dbus_verbose (" timeout is 0 as we aren't blocking\n");
707 /* if a watch is OOM, don't wait longer than the OOM
708 * wait to re-enable it
710 if (oom_watch_pending)
711 timeout = MIN (timeout, _dbus_get_oom_wait ());
714 _dbus_verbose (" polling on %d descriptors timeout %ld\n", n_fds, timeout);
717 n_ready = _dbus_poll (fds, n_fds, timeout);
719 initial_serial = loop->callback_list_serial;
721 if (loop->timeout_count > 0)
723 unsigned long tv_sec;
724 unsigned long tv_usec;
726 _dbus_get_current_time (&tv_sec, &tv_usec);
728 /* It'd be nice to avoid this O(n) thingy here */
729 link = _dbus_list_get_first_link (&loop->callbacks);
732 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
733 Callback *cb = link->data;
735 if (initial_serial != loop->callback_list_serial)
738 if (loop->depth != orig_depth)
741 if (cb->type == CALLBACK_TIMEOUT &&
742 dbus_timeout_get_enabled (TIMEOUT_CALLBACK (cb)->timeout))
744 TimeoutCallback *tcb = TIMEOUT_CALLBACK (cb);
747 if (check_timeout (tv_sec, tv_usec,
748 tcb, &msecs_remaining))
750 /* Save last callback time and fire this timeout */
751 tcb->last_tv_sec = tv_sec;
752 tcb->last_tv_usec = tv_usec;
755 _dbus_verbose (" invoking timeout\n");
758 (* tcb->function) (tcb->timeout,
766 _dbus_verbose (" timeout has not expired\n");
771 else if (cb->type == CALLBACK_TIMEOUT)
773 _dbus_verbose (" skipping invocation of disabled timeout\n");
786 /* FIXME I think this "restart if we change the watches"
787 * approach could result in starving watches
788 * toward the end of the list.
790 if (initial_serial != loop->callback_list_serial)
793 if (loop->depth != orig_depth)
796 if (fds[i].revents != 0)
799 unsigned int condition;
801 wcb = watches_for_fds[i];
804 if (fds[i].revents & _DBUS_POLLIN)
805 condition |= DBUS_WATCH_READABLE;
806 if (fds[i].revents & _DBUS_POLLOUT)
807 condition |= DBUS_WATCH_WRITABLE;
808 if (fds[i].revents & _DBUS_POLLHUP)
809 condition |= DBUS_WATCH_HANGUP;
810 if (fds[i].revents & _DBUS_POLLERR)
811 condition |= DBUS_WATCH_ERROR;
813 /* condition may still be 0 if we got some
814 * weird POLLFOO thing like POLLWRBAND
817 if (condition != 0 &&
818 dbus_watch_get_enabled (wcb->watch))
820 if (!(* wcb->function) (wcb->watch,
822 ((Callback*)wcb)->data))
823 wcb->last_iteration_oom = TRUE;
826 _dbus_verbose (" Invoked watch, oom = %d\n",
827 wcb->last_iteration_oom);
833 if (_DBUS_UNLIKELY (fds[i].revents & _DBUS_POLLNVAL))
835 _dbus_warn ("invalid request, socket fd %d not open\n",
837 _dbus_watch_invalidate (wcb->watch);
838 _dbus_loop_remove_watch (loop, wcb->watch, wcb->function,
839 ((Callback *)wcb)->data);
849 _dbus_verbose (" moving to next iteration\n");
852 if (fds && fds != stack_fds)
859 callback_unref (&watches_for_fds[i]->callback);
863 if (watches_for_fds != stack_watches_for_fds)
864 dbus_free (watches_for_fds);
867 if (_dbus_loop_dispatch (loop))
871 _dbus_verbose ("Returning %d\n", retval);
878 _dbus_loop_run (DBusLoop *loop)
882 _dbus_assert (loop->depth >= 0);
884 _dbus_loop_ref (loop);
886 our_exit_depth = loop->depth;
889 _dbus_verbose ("Running main loop, depth %d -> %d\n",
890 loop->depth - 1, loop->depth);
892 while (loop->depth != our_exit_depth)
893 _dbus_loop_iterate (loop, TRUE);
895 _dbus_loop_unref (loop);
899 _dbus_loop_quit (DBusLoop *loop)
901 _dbus_assert (loop->depth > 0);
905 _dbus_verbose ("Quit main loop, depth %d -> %d\n",
906 loop->depth + 1, loop->depth);
910 _dbus_get_oom_wait (void)
912 #ifdef DBUS_BUILD_TESTS
913 /* make tests go fast */
921 _dbus_wait_for_memory (void)
923 _dbus_verbose ("Waiting for more memory\n");
924 _dbus_sleep_milliseconds (_dbus_get_oom_wait ());
927 #endif /* !DOXYGEN_SHOULD_SKIP_THIS */