1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-mainloop.c Main loop utility
4 * Copyright © 2003, 2004 Red Hat, Inc.
5 * Copyright © 2011 Nokia Corporation
7 * Licensed under the Academic Free License version 2.1
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include "dbus-mainloop.h"
28 #ifndef DOXYGEN_SHOULD_SKIP_THIS
30 #include <dbus/dbus-hash.h>
31 #include <dbus/dbus-list.h>
32 #include <dbus/dbus-socket-set.h>
33 #include <dbus/dbus-timeout.h>
34 #include <dbus/dbus-watch.h>
36 #define MAINLOOP_SPEW 0
41 /** DBusPollable => dbus_malloc'd DBusList ** of references to DBusWatch */
42 DBusHashTable *watches;
43 DBusSocketSet *socket_set;
45 int callback_list_serial;
48 int depth; /**< number of recursive runs */
49 DBusList *need_dispatch;
50 /** TRUE if we will skip a watch next time because it was OOM; becomes
51 * FALSE between polling, and dealing with the results of the poll */
52 unsigned oom_watch_pending : 1;
62 #define TIMEOUT_CALLBACK(callback) ((TimeoutCallback*)callback)
64 static TimeoutCallback*
65 timeout_callback_new (DBusTimeout *timeout)
69 cb = dbus_new (TimeoutCallback, 1);
73 cb->timeout = timeout;
74 _dbus_get_monotonic_time (&cb->last_tv_sec,
80 timeout_callback_free (TimeoutCallback *cb)
86 free_watch_table_entry (void *data)
88 DBusList **watches = data;
91 /* DBusHashTable sometimes calls free_function(NULL) even if you never
92 * have NULL as a value */
96 for (watch = _dbus_list_pop_first (watches);
98 watch = _dbus_list_pop_first (watches))
100 _dbus_watch_unref (watch);
103 _dbus_assert (*watches == NULL);
108 _dbus_loop_new (void)
112 loop = dbus_new0 (DBusLoop, 1);
116 loop->watches = _dbus_hash_table_new (DBUS_HASH_POLLABLE, NULL,
117 free_watch_table_entry);
119 loop->socket_set = _dbus_socket_set_new (0);
121 if (loop->watches == NULL || loop->socket_set == NULL)
123 if (loop->watches != NULL)
124 _dbus_hash_table_unref (loop->watches);
126 if (loop->socket_set != NULL)
127 _dbus_socket_set_free (loop->socket_set);
139 _dbus_loop_ref (DBusLoop *loop)
141 _dbus_assert (loop != NULL);
142 _dbus_assert (loop->refcount > 0);
150 _dbus_loop_unref (DBusLoop *loop)
152 _dbus_assert (loop != NULL);
153 _dbus_assert (loop->refcount > 0);
156 if (loop->refcount == 0)
158 while (loop->need_dispatch)
160 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
162 dbus_connection_unref (connection);
165 _dbus_hash_table_unref (loop->watches);
166 _dbus_socket_set_free (loop->socket_set);
172 ensure_watch_table_entry (DBusLoop *loop,
177 watches = _dbus_hash_table_lookup_pollable (loop->watches, fd);
181 watches = dbus_new0 (DBusList *, 1);
186 if (!_dbus_hash_table_insert_pollable (loop->watches, fd, watches))
197 cull_watches_for_invalid_fd (DBusLoop *loop,
203 _dbus_warn ("invalid request, socket fd %" DBUS_POLLABLE_FORMAT " not open",
204 _dbus_pollable_printable (fd));
205 watches = _dbus_hash_table_lookup_pollable (loop->watches, fd);
209 for (link = _dbus_list_get_first_link (watches);
211 link = _dbus_list_get_next_link (watches, link))
212 _dbus_watch_invalidate (link->data);
215 _dbus_hash_table_remove_pollable (loop->watches, fd);
219 gc_watch_table_entry (DBusLoop *loop,
223 /* If watches is already NULL we have nothing to do */
227 /* We can't GC hash table entries if they're non-empty lists */
228 if (*watches != NULL)
231 _dbus_hash_table_remove_pollable (loop->watches, fd);
236 refresh_watches_for_fd (DBusLoop *loop,
241 unsigned int flags = 0;
242 dbus_bool_t interested = FALSE;
244 _dbus_assert (_dbus_pollable_is_valid (fd));
247 watches = _dbus_hash_table_lookup_pollable (loop->watches, fd);
249 /* we allocated this in the first _dbus_loop_add_watch for the fd, and keep
250 * it until there are none left */
251 _dbus_assert (watches != NULL);
253 for (link = _dbus_list_get_first_link (watches);
255 link = _dbus_list_get_next_link (watches, link))
257 if (dbus_watch_get_enabled (link->data) &&
258 !_dbus_watch_get_oom_last_time (link->data))
260 flags |= dbus_watch_get_flags (link->data);
266 _dbus_socket_set_enable (loop->socket_set, fd, flags);
268 _dbus_socket_set_disable (loop->socket_set, fd);
272 _dbus_loop_add_watch (DBusLoop *loop,
278 fd = _dbus_watch_get_pollable (watch);
279 _dbus_assert (_dbus_pollable_is_valid (fd));
281 watches = ensure_watch_table_entry (loop, fd);
286 if (!_dbus_list_append (watches, _dbus_watch_ref (watch)))
288 _dbus_watch_unref (watch);
289 gc_watch_table_entry (loop, watches, fd);
294 if (_dbus_list_length_is_one (watches))
296 if (!_dbus_socket_set_add (loop->socket_set, fd,
297 dbus_watch_get_flags (watch),
298 dbus_watch_get_enabled (watch)))
300 _dbus_hash_table_remove_pollable (loop->watches, fd);
306 /* we're modifying, not adding, which can't fail with OOM */
307 refresh_watches_for_fd (loop, watches, fd);
310 loop->callback_list_serial += 1;
311 loop->watch_count += 1;
316 _dbus_loop_toggle_watch (DBusLoop *loop,
319 refresh_watches_for_fd (loop, NULL, _dbus_watch_get_pollable (watch));
323 _dbus_loop_remove_watch (DBusLoop *loop,
330 /* This relies on people removing watches before they invalidate them,
331 * which has been safe since fd.o #33336 was fixed. Assert about it
332 * so we don't regress. */
333 fd = _dbus_watch_get_pollable (watch);
334 _dbus_assert (_dbus_pollable_is_valid (fd));
336 watches = _dbus_hash_table_lookup_pollable (loop->watches, fd);
340 link = _dbus_list_get_first_link (watches);
343 DBusList *next = _dbus_list_get_next_link (watches, link);
344 DBusWatch *this = link->data;
348 _dbus_list_remove_link (watches, link);
349 loop->callback_list_serial += 1;
350 loop->watch_count -= 1;
351 _dbus_watch_unref (this);
353 /* if that was the last watch for that fd, drop the hash table
354 * entry, and stop reserving space for it in the socket set */
355 if (gc_watch_table_entry (loop, watches, fd))
357 _dbus_socket_set_remove (loop->socket_set, fd);
367 _dbus_warn ("could not find watch %p to remove", watch);
371 _dbus_loop_add_timeout (DBusLoop *loop,
372 DBusTimeout *timeout)
374 TimeoutCallback *tcb;
376 tcb = timeout_callback_new (timeout);
380 if (_dbus_list_append (&loop->timeouts, tcb))
382 loop->callback_list_serial += 1;
383 loop->timeout_count += 1;
387 timeout_callback_free (tcb);
395 _dbus_loop_remove_timeout (DBusLoop *loop,
396 DBusTimeout *timeout)
400 link = _dbus_list_get_first_link (&loop->timeouts);
403 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
404 TimeoutCallback *this = link->data;
406 if (this->timeout == timeout)
408 _dbus_list_remove_link (&loop->timeouts, link);
409 loop->callback_list_serial += 1;
410 loop->timeout_count -= 1;
411 timeout_callback_free (this);
419 _dbus_warn ("could not find timeout %p to remove", timeout);
422 /* Convolutions from GLib, there really must be a better way
426 check_timeout (long tv_sec,
428 TimeoutCallback *tcb,
433 long expiration_tv_sec;
434 long expiration_tv_usec;
435 long interval_seconds;
436 long interval_milliseconds;
439 /* I'm pretty sure this function could suck (a lot) less */
441 interval = dbus_timeout_get_interval (tcb->timeout);
443 interval_seconds = interval / 1000L;
444 interval_milliseconds = interval % 1000L;
446 expiration_tv_sec = tcb->last_tv_sec + interval_seconds;
447 expiration_tv_usec = tcb->last_tv_usec + interval_milliseconds * 1000;
448 if (expiration_tv_usec >= 1000000)
450 expiration_tv_usec -= 1000000;
451 expiration_tv_sec += 1;
454 sec_remaining = expiration_tv_sec - tv_sec;
455 msec_remaining = (expiration_tv_usec - tv_usec) / 1000L;
458 _dbus_verbose ("Interval is %ld seconds %ld msecs\n",
460 interval_milliseconds);
461 _dbus_verbose ("Now is %lu seconds %lu usecs\n",
463 _dbus_verbose ("Last is %lu seconds %lu usecs\n",
464 tcb->last_tv_sec, tcb->last_tv_usec);
465 _dbus_verbose ("Exp is %lu seconds %lu usecs\n",
466 expiration_tv_sec, expiration_tv_usec);
467 _dbus_verbose ("Pre-correction, sec_remaining %ld msec_remaining %ld\n",
468 sec_remaining, msec_remaining);
471 /* We do the following in a rather convoluted fashion to deal with
472 * the fact that we don't have an integral type big enough to hold
473 * the difference of two timevals in milliseconds.
475 if (sec_remaining < 0 || (sec_remaining == 0 && msec_remaining < 0))
481 if (msec_remaining < 0)
483 msec_remaining += 1000;
487 if (sec_remaining > (_DBUS_INT_MAX / 1000) ||
488 msec_remaining > _DBUS_INT_MAX)
489 *timeout = _DBUS_INT_MAX;
491 *timeout = sec_remaining * 1000 + msec_remaining;
494 if (*timeout > interval)
496 /* This indicates that the system clock probably moved backward */
497 _dbus_verbose ("System clock set backward! Resetting timeout.\n");
499 tcb->last_tv_sec = tv_sec;
500 tcb->last_tv_usec = tv_usec;
506 _dbus_verbose (" timeout expires in %d milliseconds\n", *timeout);
509 return *timeout == 0;
513 _dbus_loop_dispatch (DBusLoop *loop)
517 _dbus_verbose (" %d connections to dispatch\n", _dbus_list_get_length (&loop->need_dispatch));
520 if (loop->need_dispatch == NULL)
524 while (loop->need_dispatch != NULL)
526 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
530 DBusDispatchStatus status;
532 status = dbus_connection_dispatch (connection);
534 if (status == DBUS_DISPATCH_COMPLETE)
536 dbus_connection_unref (connection);
541 if (status == DBUS_DISPATCH_NEED_MEMORY)
542 _dbus_wait_for_memory ();
551 _dbus_loop_queue_dispatch (DBusLoop *loop,
552 DBusConnection *connection)
554 if (_dbus_list_append (&loop->need_dispatch, connection))
556 dbus_connection_ref (connection);
563 /* Returns TRUE if we invoked any timeouts or have ready file
564 * descriptors, which is just used in test code as a debug hack
568 _dbus_loop_iterate (DBusLoop *loop,
571 #define N_STACK_DESCRIPTORS 64
573 DBusSocketEvent ready_fds[N_STACK_DESCRIPTORS];
583 orig_depth = loop->depth;
586 _dbus_verbose ("Iteration block=%d depth=%d timeout_count=%d watch_count=%d\n",
587 block, loop->depth, loop->timeout_count, loop->watch_count);
590 if (_dbus_hash_table_get_n_entries (loop->watches) == 0 &&
591 loop->timeouts == NULL)
595 if (loop->timeout_count > 0)
600 _dbus_get_monotonic_time (&tv_sec, &tv_usec);
602 link = _dbus_list_get_first_link (&loop->timeouts);
605 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
606 TimeoutCallback *tcb = link->data;
608 if (dbus_timeout_get_enabled (tcb->timeout))
612 if (_dbus_timeout_needs_restart (tcb->timeout))
614 tcb->last_tv_sec = tv_sec;
615 tcb->last_tv_usec = tv_usec;
616 _dbus_timeout_restarted (tcb->timeout);
619 check_timeout (tv_sec, tv_usec, tcb, &msecs_remaining);
622 timeout = msecs_remaining;
624 timeout = MIN (msecs_remaining, timeout);
627 _dbus_verbose (" timeout added, %d remaining, aggregate timeout %ld\n",
628 msecs_remaining, timeout);
631 _dbus_assert (timeout >= 0);
636 _dbus_verbose (" skipping disabled timeout\n");
644 /* Never block if we have stuff to dispatch */
645 if (!block || loop->need_dispatch != NULL)
649 _dbus_verbose (" timeout is 0 as we aren't blocking\n");
653 /* if a watch was OOM last time, don't wait longer than the OOM
654 * wait to re-enable it
656 if (loop->oom_watch_pending)
657 timeout = MIN (timeout, _dbus_get_oom_wait ());
660 _dbus_verbose (" polling on %d descriptors timeout %ld\n", _DBUS_N_ELEMENTS (ready_fds), timeout);
663 n_ready = _dbus_socket_set_poll (loop->socket_set, ready_fds,
664 _DBUS_N_ELEMENTS (ready_fds), timeout);
666 /* re-enable any watches we skipped this time */
667 if (loop->oom_watch_pending)
669 DBusHashIter hash_iter;
671 loop->oom_watch_pending = FALSE;
673 _dbus_hash_iter_init (loop->watches, &hash_iter);
675 while (_dbus_hash_iter_next (&hash_iter))
682 fd = _dbus_hash_iter_get_pollable_key (&hash_iter);
683 watches = _dbus_hash_iter_get_value (&hash_iter);
685 for (link = _dbus_list_get_first_link (watches);
687 link = _dbus_list_get_next_link (watches, link))
689 DBusWatch *watch = link->data;
691 if (_dbus_watch_get_oom_last_time (watch))
693 _dbus_watch_set_oom_last_time (watch, FALSE);
699 refresh_watches_for_fd (loop, watches, fd);
702 retval = TRUE; /* return TRUE here to keep the loop going,
703 * since we don't know the watch was inactive */
706 initial_serial = loop->callback_list_serial;
708 if (loop->timeout_count > 0)
713 _dbus_get_monotonic_time (&tv_sec, &tv_usec);
715 /* It'd be nice to avoid this O(n) thingy here */
716 link = _dbus_list_get_first_link (&loop->timeouts);
719 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
720 TimeoutCallback *tcb = link->data;
722 if (initial_serial != loop->callback_list_serial)
725 if (loop->depth != orig_depth)
728 if (dbus_timeout_get_enabled (tcb->timeout))
732 if (check_timeout (tv_sec, tv_usec,
733 tcb, &msecs_remaining))
735 /* Save last callback time and fire this timeout */
736 tcb->last_tv_sec = tv_sec;
737 tcb->last_tv_usec = tv_usec;
740 _dbus_verbose (" invoking timeout\n");
743 /* can theoretically return FALSE on OOM, but we just
744 * let it fire again later - in practice that's what
745 * every wrapper callback in dbus-daemon used to do */
746 dbus_timeout_handle (tcb->timeout);
753 _dbus_verbose (" timeout has not expired\n");
760 _dbus_verbose (" skipping invocation of disabled timeout\n");
770 for (i = 0; i < n_ready; i++)
774 unsigned int condition;
777 /* FIXME I think this "restart if we change the watches"
778 * approach could result in starving watches
779 * toward the end of the list.
781 if (initial_serial != loop->callback_list_serial)
784 if (loop->depth != orig_depth)
787 _dbus_assert (ready_fds[i].flags != 0);
789 if (_DBUS_UNLIKELY (ready_fds[i].flags & _DBUS_WATCH_NVAL))
791 cull_watches_for_invalid_fd (loop, ready_fds[i].fd);
795 condition = ready_fds[i].flags;
796 _dbus_assert ((condition & _DBUS_WATCH_NVAL) == 0);
798 /* condition may still be 0 if we got some
799 * weird POLLFOO thing like POLLWRBAND
804 watches = _dbus_hash_table_lookup_pollable (loop->watches,
812 for (link = _dbus_list_get_first_link (watches);
816 DBusWatch *watch = link->data;
818 next = _dbus_list_get_next_link (watches, link);
820 if (dbus_watch_get_enabled (watch))
824 oom = !dbus_watch_handle (watch, condition);
828 _dbus_watch_set_oom_last_time (watch, TRUE);
829 loop->oom_watch_pending = TRUE;
834 _dbus_verbose (" Invoked watch, oom = %d\n", oom);
838 /* We re-check this every time, in case the callback
839 * added/removed watches, which might make our position in
840 * the linked list invalid. See the FIXME above. */
841 if (initial_serial != loop->callback_list_serial ||
842 loop->depth != orig_depth)
845 refresh_watches_for_fd (loop, NULL, ready_fds[i].fd);
853 refresh_watches_for_fd (loop, watches, ready_fds[i].fd);
859 _dbus_verbose (" moving to next iteration\n");
862 if (_dbus_loop_dispatch (loop))
866 _dbus_verbose ("Returning %d\n", retval);
873 _dbus_loop_run (DBusLoop *loop)
877 _dbus_assert (loop->depth >= 0);
879 _dbus_loop_ref (loop);
881 our_exit_depth = loop->depth;
884 _dbus_verbose ("Running main loop, depth %d -> %d\n",
885 loop->depth - 1, loop->depth);
887 while (loop->depth != our_exit_depth)
888 _dbus_loop_iterate (loop, TRUE);
890 _dbus_loop_unref (loop);
894 _dbus_loop_quit (DBusLoop *loop)
896 _dbus_assert (loop->depth > 0);
900 _dbus_verbose ("Quit main loop, depth %d -> %d\n",
901 loop->depth + 1, loop->depth);
905 _dbus_get_oom_wait (void)
907 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
908 /* make tests go fast */
916 _dbus_wait_for_memory (void)
918 _dbus_verbose ("Waiting for more memory\n");
919 _dbus_sleep_milliseconds (_dbus_get_oom_wait ());
922 #endif /* !DOXYGEN_SHOULD_SKIP_THIS */