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-watch.h>
35 #define MAINLOOP_SPEW 0
40 /** DBusPollable => dbus_malloc'd DBusList ** of references to DBusWatch */
41 DBusHashTable *watches;
42 DBusSocketSet *socket_set;
44 int callback_list_serial;
47 int depth; /**< number of recursive runs */
48 DBusList *need_dispatch;
49 /** TRUE if we will skip a watch next time because it was OOM; becomes
50 * FALSE between polling, and dealing with the results of the poll */
51 unsigned oom_watch_pending : 1;
61 #define TIMEOUT_CALLBACK(callback) ((TimeoutCallback*)callback)
63 static TimeoutCallback*
64 timeout_callback_new (DBusTimeout *timeout)
68 cb = dbus_new (TimeoutCallback, 1);
72 cb->timeout = timeout;
73 _dbus_get_monotonic_time (&cb->last_tv_sec,
79 timeout_callback_free (TimeoutCallback *cb)
85 free_watch_table_entry (void *data)
87 DBusList **watches = data;
90 /* DBusHashTable sometimes calls free_function(NULL) even if you never
91 * have NULL as a value */
95 for (watch = _dbus_list_pop_first (watches);
97 watch = _dbus_list_pop_first (watches))
99 _dbus_watch_unref (watch);
102 _dbus_assert (*watches == NULL);
107 _dbus_loop_new (void)
111 loop = dbus_new0 (DBusLoop, 1);
115 loop->watches = _dbus_hash_table_new (DBUS_HASH_POLLABLE, NULL,
116 free_watch_table_entry);
118 loop->socket_set = _dbus_socket_set_new (0);
120 if (loop->watches == NULL || loop->socket_set == NULL)
122 if (loop->watches != NULL)
123 _dbus_hash_table_unref (loop->watches);
125 if (loop->socket_set != NULL)
126 _dbus_socket_set_free (loop->socket_set);
138 _dbus_loop_ref (DBusLoop *loop)
140 _dbus_assert (loop != NULL);
141 _dbus_assert (loop->refcount > 0);
149 _dbus_loop_unref (DBusLoop *loop)
151 _dbus_assert (loop != NULL);
152 _dbus_assert (loop->refcount > 0);
155 if (loop->refcount == 0)
157 while (loop->need_dispatch)
159 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
161 dbus_connection_unref (connection);
164 _dbus_hash_table_unref (loop->watches);
165 _dbus_socket_set_free (loop->socket_set);
171 ensure_watch_table_entry (DBusLoop *loop,
176 watches = _dbus_hash_table_lookup_pollable (loop->watches, fd);
180 watches = dbus_new0 (DBusList *, 1);
185 if (!_dbus_hash_table_insert_pollable (loop->watches, fd, watches))
196 cull_watches_for_invalid_fd (DBusLoop *loop,
202 _dbus_warn ("invalid request, socket fd %" DBUS_POLLABLE_FORMAT " not open\n",
203 _dbus_pollable_printable (fd));
204 watches = _dbus_hash_table_lookup_pollable (loop->watches, fd);
208 for (link = _dbus_list_get_first_link (watches);
210 link = _dbus_list_get_next_link (watches, link))
211 _dbus_watch_invalidate (link->data);
214 _dbus_hash_table_remove_pollable (loop->watches, fd);
218 gc_watch_table_entry (DBusLoop *loop,
222 /* If watches is already NULL we have nothing to do */
226 /* We can't GC hash table entries if they're non-empty lists */
227 if (*watches != NULL)
230 _dbus_hash_table_remove_pollable (loop->watches, fd);
235 refresh_watches_for_fd (DBusLoop *loop,
240 unsigned int flags = 0;
241 dbus_bool_t interested = FALSE;
243 _dbus_assert (_dbus_pollable_is_valid (fd));
246 watches = _dbus_hash_table_lookup_pollable (loop->watches, fd);
248 /* we allocated this in the first _dbus_loop_add_watch for the fd, and keep
249 * it until there are none left */
250 _dbus_assert (watches != NULL);
252 for (link = _dbus_list_get_first_link (watches);
254 link = _dbus_list_get_next_link (watches, link))
256 if (dbus_watch_get_enabled (link->data) &&
257 !_dbus_watch_get_oom_last_time (link->data))
259 flags |= dbus_watch_get_flags (link->data);
265 _dbus_socket_set_enable (loop->socket_set, fd, flags);
267 _dbus_socket_set_disable (loop->socket_set, fd);
271 _dbus_loop_add_watch (DBusLoop *loop,
277 fd = _dbus_watch_get_pollable (watch);
278 _dbus_assert (_dbus_pollable_is_valid (fd));
280 watches = ensure_watch_table_entry (loop, fd);
285 if (!_dbus_list_append (watches, _dbus_watch_ref (watch)))
287 _dbus_watch_unref (watch);
288 gc_watch_table_entry (loop, watches, fd);
293 if (_dbus_list_length_is_one (watches))
295 if (!_dbus_socket_set_add (loop->socket_set, fd,
296 dbus_watch_get_flags (watch),
297 dbus_watch_get_enabled (watch)))
299 _dbus_hash_table_remove_pollable (loop->watches, fd);
305 /* we're modifying, not adding, which can't fail with OOM */
306 refresh_watches_for_fd (loop, watches, fd);
309 loop->callback_list_serial += 1;
310 loop->watch_count += 1;
315 _dbus_loop_toggle_watch (DBusLoop *loop,
318 refresh_watches_for_fd (loop, NULL, _dbus_watch_get_pollable (watch));
322 _dbus_loop_remove_watch (DBusLoop *loop,
329 /* This relies on people removing watches before they invalidate them,
330 * which has been safe since fd.o #33336 was fixed. Assert about it
331 * so we don't regress. */
332 fd = _dbus_watch_get_pollable (watch);
333 _dbus_assert (_dbus_pollable_is_valid (fd));
335 watches = _dbus_hash_table_lookup_pollable (loop->watches, fd);
339 link = _dbus_list_get_first_link (watches);
342 DBusList *next = _dbus_list_get_next_link (watches, link);
343 DBusWatch *this = link->data;
347 _dbus_list_remove_link (watches, link);
348 loop->callback_list_serial += 1;
349 loop->watch_count -= 1;
350 _dbus_watch_unref (this);
352 /* if that was the last watch for that fd, drop the hash table
353 * entry, and stop reserving space for it in the socket set */
354 if (gc_watch_table_entry (loop, watches, fd))
356 _dbus_socket_set_remove (loop->socket_set, fd);
366 _dbus_warn ("could not find watch %p to remove\n", watch);
370 _dbus_loop_add_timeout (DBusLoop *loop,
371 DBusTimeout *timeout)
373 TimeoutCallback *tcb;
375 tcb = timeout_callback_new (timeout);
379 if (_dbus_list_append (&loop->timeouts, tcb))
381 loop->callback_list_serial += 1;
382 loop->timeout_count += 1;
386 timeout_callback_free (tcb);
394 _dbus_loop_remove_timeout (DBusLoop *loop,
395 DBusTimeout *timeout)
399 link = _dbus_list_get_first_link (&loop->timeouts);
402 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
403 TimeoutCallback *this = link->data;
405 if (this->timeout == timeout)
407 _dbus_list_remove_link (&loop->timeouts, link);
408 loop->callback_list_serial += 1;
409 loop->timeout_count -= 1;
410 timeout_callback_free (this);
418 _dbus_warn ("could not find timeout %p to remove\n", timeout);
421 /* Convolutions from GLib, there really must be a better way
425 check_timeout (long tv_sec,
427 TimeoutCallback *tcb,
432 long expiration_tv_sec;
433 long expiration_tv_usec;
434 long interval_seconds;
435 long interval_milliseconds;
438 /* I'm pretty sure this function could suck (a lot) less */
440 interval = dbus_timeout_get_interval (tcb->timeout);
442 interval_seconds = interval / 1000L;
443 interval_milliseconds = interval % 1000L;
445 expiration_tv_sec = tcb->last_tv_sec + interval_seconds;
446 expiration_tv_usec = tcb->last_tv_usec + interval_milliseconds * 1000;
447 if (expiration_tv_usec >= 1000000)
449 expiration_tv_usec -= 1000000;
450 expiration_tv_sec += 1;
453 sec_remaining = expiration_tv_sec - tv_sec;
454 msec_remaining = (expiration_tv_usec - tv_usec) / 1000L;
457 _dbus_verbose ("Interval is %ld seconds %ld msecs\n",
459 interval_milliseconds);
460 _dbus_verbose ("Now is %lu seconds %lu usecs\n",
462 _dbus_verbose ("Last is %lu seconds %lu usecs\n",
463 tcb->last_tv_sec, tcb->last_tv_usec);
464 _dbus_verbose ("Exp is %lu seconds %lu usecs\n",
465 expiration_tv_sec, expiration_tv_usec);
466 _dbus_verbose ("Pre-correction, sec_remaining %ld msec_remaining %ld\n",
467 sec_remaining, msec_remaining);
470 /* We do the following in a rather convoluted fashion to deal with
471 * the fact that we don't have an integral type big enough to hold
472 * the difference of two timevals in milliseconds.
474 if (sec_remaining < 0 || (sec_remaining == 0 && msec_remaining < 0))
480 if (msec_remaining < 0)
482 msec_remaining += 1000;
486 if (sec_remaining > (_DBUS_INT_MAX / 1000) ||
487 msec_remaining > _DBUS_INT_MAX)
488 *timeout = _DBUS_INT_MAX;
490 *timeout = sec_remaining * 1000 + msec_remaining;
493 if (*timeout > interval)
495 /* This indicates that the system clock probably moved backward */
496 _dbus_verbose ("System clock set backward! Resetting timeout.\n");
498 tcb->last_tv_sec = tv_sec;
499 tcb->last_tv_usec = tv_usec;
505 _dbus_verbose (" timeout expires in %d milliseconds\n", *timeout);
508 return *timeout == 0;
512 _dbus_loop_dispatch (DBusLoop *loop)
516 _dbus_verbose (" %d connections to dispatch\n", _dbus_list_get_length (&loop->need_dispatch));
519 if (loop->need_dispatch == NULL)
523 while (loop->need_dispatch != NULL)
525 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
529 DBusDispatchStatus status;
531 status = dbus_connection_dispatch (connection);
533 if (status == DBUS_DISPATCH_COMPLETE)
535 dbus_connection_unref (connection);
540 if (status == DBUS_DISPATCH_NEED_MEMORY)
541 _dbus_wait_for_memory ();
550 _dbus_loop_queue_dispatch (DBusLoop *loop,
551 DBusConnection *connection)
553 if (_dbus_list_append (&loop->need_dispatch, connection))
555 dbus_connection_ref (connection);
562 /* Returns TRUE if we invoked any timeouts or have ready file
563 * descriptors, which is just used in test code as a debug hack
567 _dbus_loop_iterate (DBusLoop *loop,
570 #define N_STACK_DESCRIPTORS 64
572 DBusSocketEvent ready_fds[N_STACK_DESCRIPTORS];
582 orig_depth = loop->depth;
585 _dbus_verbose ("Iteration block=%d depth=%d timeout_count=%d watch_count=%d\n",
586 block, loop->depth, loop->timeout_count, loop->watch_count);
589 if (_dbus_hash_table_get_n_entries (loop->watches) == 0 &&
590 loop->timeouts == NULL)
594 if (loop->timeout_count > 0)
599 _dbus_get_monotonic_time (&tv_sec, &tv_usec);
601 link = _dbus_list_get_first_link (&loop->timeouts);
604 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
605 TimeoutCallback *tcb = link->data;
607 if (dbus_timeout_get_enabled (tcb->timeout))
611 check_timeout (tv_sec, tv_usec, tcb, &msecs_remaining);
614 timeout = msecs_remaining;
616 timeout = MIN (msecs_remaining, timeout);
619 _dbus_verbose (" timeout added, %d remaining, aggregate timeout %ld\n",
620 msecs_remaining, timeout);
623 _dbus_assert (timeout >= 0);
626 break; /* it's not going to get shorter... */
631 _dbus_verbose (" skipping disabled timeout\n");
639 /* Never block if we have stuff to dispatch */
640 if (!block || loop->need_dispatch != NULL)
644 _dbus_verbose (" timeout is 0 as we aren't blocking\n");
648 /* if a watch was OOM last time, don't wait longer than the OOM
649 * wait to re-enable it
651 if (loop->oom_watch_pending)
652 timeout = MIN (timeout, _dbus_get_oom_wait ());
655 _dbus_verbose (" polling on %d descriptors timeout %ld\n", _DBUS_N_ELEMENTS (ready_fds), timeout);
658 n_ready = _dbus_socket_set_poll (loop->socket_set, ready_fds,
659 _DBUS_N_ELEMENTS (ready_fds), timeout);
661 /* re-enable any watches we skipped this time */
662 if (loop->oom_watch_pending)
664 DBusHashIter hash_iter;
666 loop->oom_watch_pending = FALSE;
668 _dbus_hash_iter_init (loop->watches, &hash_iter);
670 while (_dbus_hash_iter_next (&hash_iter))
677 fd = _dbus_hash_iter_get_pollable_key (&hash_iter);
678 watches = _dbus_hash_iter_get_value (&hash_iter);
680 for (link = _dbus_list_get_first_link (watches);
682 link = _dbus_list_get_next_link (watches, link))
684 DBusWatch *watch = link->data;
686 if (_dbus_watch_get_oom_last_time (watch))
688 _dbus_watch_set_oom_last_time (watch, FALSE);
694 refresh_watches_for_fd (loop, watches, fd);
697 retval = TRUE; /* return TRUE here to keep the loop going,
698 * since we don't know the watch was inactive */
701 initial_serial = loop->callback_list_serial;
703 if (loop->timeout_count > 0)
708 _dbus_get_monotonic_time (&tv_sec, &tv_usec);
710 /* It'd be nice to avoid this O(n) thingy here */
711 link = _dbus_list_get_first_link (&loop->timeouts);
714 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
715 TimeoutCallback *tcb = link->data;
717 if (initial_serial != loop->callback_list_serial)
720 if (loop->depth != orig_depth)
723 if (dbus_timeout_get_enabled (tcb->timeout))
727 if (check_timeout (tv_sec, tv_usec,
728 tcb, &msecs_remaining))
730 /* Save last callback time and fire this timeout */
731 tcb->last_tv_sec = tv_sec;
732 tcb->last_tv_usec = tv_usec;
735 _dbus_verbose (" invoking timeout\n");
738 /* can theoretically return FALSE on OOM, but we just
739 * let it fire again later - in practice that's what
740 * every wrapper callback in dbus-daemon used to do */
741 dbus_timeout_handle (tcb->timeout);
748 _dbus_verbose (" timeout has not expired\n");
755 _dbus_verbose (" skipping invocation of disabled timeout\n");
765 for (i = 0; i < n_ready; i++)
769 unsigned int condition;
772 /* FIXME I think this "restart if we change the watches"
773 * approach could result in starving watches
774 * toward the end of the list.
776 if (initial_serial != loop->callback_list_serial)
779 if (loop->depth != orig_depth)
782 _dbus_assert (ready_fds[i].flags != 0);
784 if (_DBUS_UNLIKELY (ready_fds[i].flags & _DBUS_WATCH_NVAL))
786 cull_watches_for_invalid_fd (loop, ready_fds[i].fd);
790 condition = ready_fds[i].flags;
791 _dbus_assert ((condition & _DBUS_WATCH_NVAL) == 0);
793 /* condition may still be 0 if we got some
794 * weird POLLFOO thing like POLLWRBAND
799 watches = _dbus_hash_table_lookup_pollable (loop->watches,
807 for (link = _dbus_list_get_first_link (watches);
811 DBusWatch *watch = link->data;
813 next = _dbus_list_get_next_link (watches, link);
815 if (dbus_watch_get_enabled (watch))
819 oom = !dbus_watch_handle (watch, condition);
823 _dbus_watch_set_oom_last_time (watch, TRUE);
824 loop->oom_watch_pending = TRUE;
829 _dbus_verbose (" Invoked watch, oom = %d\n", oom);
833 /* We re-check this every time, in case the callback
834 * added/removed watches, which might make our position in
835 * the linked list invalid. See the FIXME above. */
836 if (initial_serial != loop->callback_list_serial ||
837 loop->depth != orig_depth)
840 refresh_watches_for_fd (loop, NULL, ready_fds[i].fd);
848 refresh_watches_for_fd (loop, watches, ready_fds[i].fd);
854 _dbus_verbose (" moving to next iteration\n");
857 if (_dbus_loop_dispatch (loop))
861 _dbus_verbose ("Returning %d\n", retval);
868 _dbus_loop_run (DBusLoop *loop)
872 _dbus_assert (loop->depth >= 0);
874 _dbus_loop_ref (loop);
876 our_exit_depth = loop->depth;
879 _dbus_verbose ("Running main loop, depth %d -> %d\n",
880 loop->depth - 1, loop->depth);
882 while (loop->depth != our_exit_depth)
883 _dbus_loop_iterate (loop, TRUE);
885 _dbus_loop_unref (loop);
889 _dbus_loop_quit (DBusLoop *loop)
891 _dbus_assert (loop->depth > 0);
895 _dbus_verbose ("Quit main loop, depth %d -> %d\n",
896 loop->depth + 1, loop->depth);
900 _dbus_get_oom_wait (void)
902 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
903 /* make tests go fast */
911 _dbus_wait_for_memory (void)
913 _dbus_verbose ("Waiting for more memory\n");
914 _dbus_sleep_milliseconds (_dbus_get_oom_wait ());
917 #endif /* !DOXYGEN_SHOULD_SKIP_THIS */