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
38 #ifdef DBUS_ENABLE_VERBOSE_MODE
40 watch_flags_to_string (int flags)
42 const char *watch_type;
44 if ((flags & DBUS_WATCH_READABLE) &&
45 (flags & DBUS_WATCH_WRITABLE))
46 watch_type = "readwrite";
47 else if (flags & DBUS_WATCH_READABLE)
49 else if (flags & DBUS_WATCH_WRITABLE)
52 watch_type = "not read or write";
55 #endif /* DBUS_ENABLE_VERBOSE_MODE */
56 #endif /* MAINLOOP_SPEW */
61 /** fd => dbus_malloc'd DBusList ** of references to DBusWatch */
62 DBusHashTable *watches;
63 DBusSocketSet *socket_set;
65 int callback_list_serial;
68 int depth; /**< number of recursive runs */
69 DBusList *need_dispatch;
70 /** TRUE if we will skip a watch next time because it was OOM; becomes
71 * FALSE between polling, and dealing with the results of the poll */
72 unsigned oom_watch_pending : 1;
78 unsigned long last_tv_sec;
79 unsigned long last_tv_usec;
82 #define TIMEOUT_CALLBACK(callback) ((TimeoutCallback*)callback)
84 static TimeoutCallback*
85 timeout_callback_new (DBusTimeout *timeout)
89 cb = dbus_new (TimeoutCallback, 1);
93 cb->timeout = timeout;
94 _dbus_get_monotonic_time (&cb->last_tv_sec,
100 timeout_callback_free (TimeoutCallback *cb)
106 free_watch_table_entry (void *data)
108 DBusList **watches = data;
111 /* DBusHashTable sometimes calls free_function(NULL) even if you never
112 * have NULL as a value */
116 for (watch = _dbus_list_pop_first (watches);
118 watch = _dbus_list_pop_first (watches))
120 _dbus_watch_unref (watch);
123 _dbus_assert (*watches == NULL);
128 _dbus_loop_new (void)
132 loop = dbus_new0 (DBusLoop, 1);
136 loop->watches = _dbus_hash_table_new (DBUS_HASH_INT, NULL,
137 free_watch_table_entry);
139 loop->socket_set = _dbus_socket_set_new (0);
141 if (loop->watches == NULL || loop->socket_set == NULL)
143 if (loop->watches != NULL)
144 _dbus_hash_table_unref (loop->watches);
146 if (loop->socket_set != NULL)
147 _dbus_socket_set_free (loop->socket_set);
159 _dbus_loop_ref (DBusLoop *loop)
161 _dbus_assert (loop != NULL);
162 _dbus_assert (loop->refcount > 0);
170 _dbus_loop_unref (DBusLoop *loop)
172 _dbus_assert (loop != NULL);
173 _dbus_assert (loop->refcount > 0);
176 if (loop->refcount == 0)
178 while (loop->need_dispatch)
180 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
182 dbus_connection_unref (connection);
185 _dbus_hash_table_unref (loop->watches);
186 _dbus_socket_set_free (loop->socket_set);
192 ensure_watch_table_entry (DBusLoop *loop,
197 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
201 watches = dbus_new0 (DBusList *, 1);
206 if (!_dbus_hash_table_insert_int (loop->watches, fd, watches))
217 cull_watches_for_invalid_fd (DBusLoop *loop,
223 _dbus_warn ("invalid request, socket fd %d not open\n", fd);
224 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
228 for (link = _dbus_list_get_first_link (watches);
230 link = _dbus_list_get_next_link (watches, link))
231 _dbus_watch_invalidate (link->data);
234 _dbus_hash_table_remove_int (loop->watches, fd);
238 gc_watch_table_entry (DBusLoop *loop,
242 /* If watches is already NULL we have nothing to do */
246 /* We can't GC hash table entries if they're non-empty lists */
247 if (*watches != NULL)
250 _dbus_hash_table_remove_int (loop->watches, fd);
255 refresh_watches_for_fd (DBusLoop *loop,
260 unsigned int flags = 0;
261 dbus_bool_t interested = FALSE;
263 _dbus_assert (fd != -1);
266 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
268 /* we allocated this in the first _dbus_loop_add_watch for the fd, and keep
269 * it until there are none left */
270 _dbus_assert (watches != NULL);
272 for (link = _dbus_list_get_first_link (watches);
274 link = _dbus_list_get_next_link (watches, link))
276 if (dbus_watch_get_enabled (link->data) &&
277 !_dbus_watch_get_oom_last_time (link->data))
279 flags |= dbus_watch_get_flags (link->data);
285 _dbus_socket_set_enable (loop->socket_set, fd, flags);
287 _dbus_socket_set_disable (loop->socket_set, fd);
291 _dbus_loop_add_watch (DBusLoop *loop,
297 fd = dbus_watch_get_socket (watch);
298 _dbus_assert (fd != -1);
300 watches = ensure_watch_table_entry (loop, fd);
305 if (!_dbus_list_append (watches, _dbus_watch_ref (watch)))
307 _dbus_watch_unref (watch);
308 gc_watch_table_entry (loop, watches, fd);
313 if (_dbus_list_length_is_one (watches))
315 if (!_dbus_socket_set_add (loop->socket_set, fd,
316 dbus_watch_get_flags (watch),
317 dbus_watch_get_enabled (watch)))
319 _dbus_hash_table_remove_int (loop->watches, fd);
325 /* we're modifying, not adding, which can't fail with OOM */
326 refresh_watches_for_fd (loop, watches, fd);
329 loop->callback_list_serial += 1;
330 loop->watch_count += 1;
335 _dbus_loop_toggle_watch (DBusLoop *loop,
338 refresh_watches_for_fd (loop, NULL, dbus_watch_get_socket (watch));
342 _dbus_loop_remove_watch (DBusLoop *loop,
349 /* This relies on people removing watches before they invalidate them,
350 * which has been safe since fd.o #33336 was fixed. Assert about it
351 * so we don't regress. */
352 fd = dbus_watch_get_socket (watch);
353 _dbus_assert (fd != -1);
355 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
359 link = _dbus_list_get_first_link (watches);
362 DBusList *next = _dbus_list_get_next_link (watches, link);
363 DBusWatch *this = link->data;
367 _dbus_list_remove_link (watches, link);
368 loop->callback_list_serial += 1;
369 loop->watch_count -= 1;
370 _dbus_watch_unref (this);
372 /* if that was the last watch for that fd, drop the hash table
373 * entry, and stop reserving space for it in the socket set */
374 if (gc_watch_table_entry (loop, watches, fd))
376 _dbus_socket_set_remove (loop->socket_set, fd);
386 _dbus_warn ("could not find watch %p to remove\n", watch);
390 _dbus_loop_add_timeout (DBusLoop *loop,
391 DBusTimeout *timeout)
393 TimeoutCallback *tcb;
395 tcb = timeout_callback_new (timeout);
399 if (_dbus_list_append (&loop->timeouts, tcb))
401 loop->callback_list_serial += 1;
402 loop->timeout_count += 1;
406 timeout_callback_free (tcb);
414 _dbus_loop_remove_timeout (DBusLoop *loop,
415 DBusTimeout *timeout)
419 link = _dbus_list_get_first_link (&loop->timeouts);
422 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
423 TimeoutCallback *this = link->data;
425 if (this->timeout == timeout)
427 _dbus_list_remove_link (&loop->timeouts, link);
428 loop->callback_list_serial += 1;
429 loop->timeout_count -= 1;
430 timeout_callback_free (this);
438 _dbus_warn ("could not find timeout %p to remove\n", timeout);
441 /* Convolutions from GLib, there really must be a better way
445 check_timeout (unsigned long tv_sec,
446 unsigned long tv_usec,
447 TimeoutCallback *tcb,
452 unsigned long expiration_tv_sec;
453 unsigned long expiration_tv_usec;
454 long interval_seconds;
455 long interval_milliseconds;
458 /* I'm pretty sure this function could suck (a lot) less */
460 interval = dbus_timeout_get_interval (tcb->timeout);
462 interval_seconds = interval / 1000L;
463 interval_milliseconds = interval % 1000L;
465 expiration_tv_sec = tcb->last_tv_sec + interval_seconds;
466 expiration_tv_usec = tcb->last_tv_usec + interval_milliseconds * 1000;
467 if (expiration_tv_usec >= 1000000)
469 expiration_tv_usec -= 1000000;
470 expiration_tv_sec += 1;
473 sec_remaining = expiration_tv_sec - tv_sec;
474 /* need to force this to be signed, as it is intended to sometimes
475 * produce a negative result
477 msec_remaining = ((long) expiration_tv_usec - (long) tv_usec) / 1000L;
480 _dbus_verbose ("Interval is %ld seconds %ld msecs\n",
482 interval_milliseconds);
483 _dbus_verbose ("Now is %lu seconds %lu usecs\n",
485 _dbus_verbose ("Last is %lu seconds %lu usecs\n",
486 tcb->last_tv_sec, tcb->last_tv_usec);
487 _dbus_verbose ("Exp is %lu seconds %lu usecs\n",
488 expiration_tv_sec, expiration_tv_usec);
489 _dbus_verbose ("Pre-correction, sec_remaining %ld msec_remaining %ld\n",
490 sec_remaining, msec_remaining);
493 /* We do the following in a rather convoluted fashion to deal with
494 * the fact that we don't have an integral type big enough to hold
495 * the difference of two timevals in milliseconds.
497 if (sec_remaining < 0 || (sec_remaining == 0 && msec_remaining < 0))
503 if (msec_remaining < 0)
505 msec_remaining += 1000;
509 if (sec_remaining > (_DBUS_INT_MAX / 1000) ||
510 msec_remaining > _DBUS_INT_MAX)
511 *timeout = _DBUS_INT_MAX;
513 *timeout = sec_remaining * 1000 + msec_remaining;
516 if (*timeout > interval)
518 /* This indicates that the system clock probably moved backward */
519 _dbus_verbose ("System clock set backward! Resetting timeout.\n");
521 tcb->last_tv_sec = tv_sec;
522 tcb->last_tv_usec = tv_usec;
528 _dbus_verbose (" timeout expires in %d milliseconds\n", *timeout);
531 return *timeout == 0;
535 _dbus_loop_dispatch (DBusLoop *loop)
539 _dbus_verbose (" %d connections to dispatch\n", _dbus_list_get_length (&loop->need_dispatch));
542 if (loop->need_dispatch == NULL)
546 while (loop->need_dispatch != NULL)
548 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
552 DBusDispatchStatus status;
554 status = dbus_connection_dispatch (connection);
556 if (status == DBUS_DISPATCH_COMPLETE)
558 dbus_connection_unref (connection);
563 if (status == DBUS_DISPATCH_NEED_MEMORY)
564 _dbus_wait_for_memory ();
573 _dbus_loop_queue_dispatch (DBusLoop *loop,
574 DBusConnection *connection)
576 if (_dbus_list_append (&loop->need_dispatch, connection))
578 dbus_connection_ref (connection);
585 /* Returns TRUE if we invoked any timeouts or have ready file
586 * descriptors, which is just used in test code as a debug hack
590 _dbus_loop_iterate (DBusLoop *loop,
593 #define N_STACK_DESCRIPTORS 64
595 DBusSocketEvent ready_fds[N_STACK_DESCRIPTORS];
605 orig_depth = loop->depth;
608 _dbus_verbose ("Iteration block=%d depth=%d timeout_count=%d watch_count=%d\n",
609 block, loop->depth, loop->timeout_count, loop->watch_count);
612 if (_dbus_hash_table_get_n_entries (loop->watches) == 0 &&
613 loop->timeouts == NULL)
617 if (loop->timeout_count > 0)
619 unsigned long tv_sec;
620 unsigned long tv_usec;
622 _dbus_get_monotonic_time (&tv_sec, &tv_usec);
624 link = _dbus_list_get_first_link (&loop->timeouts);
627 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
628 TimeoutCallback *tcb = link->data;
630 if (dbus_timeout_get_enabled (tcb->timeout))
634 check_timeout (tv_sec, tv_usec, tcb, &msecs_remaining);
637 timeout = msecs_remaining;
639 timeout = MIN (msecs_remaining, timeout);
642 _dbus_verbose (" timeout added, %d remaining, aggregate timeout %ld\n",
643 msecs_remaining, timeout);
646 _dbus_assert (timeout >= 0);
649 break; /* it's not going to get shorter... */
654 _dbus_verbose (" skipping disabled timeout\n");
662 /* Never block if we have stuff to dispatch */
663 if (!block || loop->need_dispatch != NULL)
667 _dbus_verbose (" timeout is 0 as we aren't blocking\n");
671 /* if a watch was OOM last time, don't wait longer than the OOM
672 * wait to re-enable it
674 if (loop->oom_watch_pending)
675 timeout = MIN (timeout, _dbus_get_oom_wait ());
678 _dbus_verbose (" polling on %d descriptors timeout %ld\n", n_fds, timeout);
681 n_ready = _dbus_socket_set_poll (loop->socket_set, ready_fds,
682 _DBUS_N_ELEMENTS (ready_fds), timeout);
684 /* re-enable any watches we skipped this time */
685 if (loop->oom_watch_pending)
687 DBusHashIter hash_iter;
689 loop->oom_watch_pending = FALSE;
691 _dbus_hash_iter_init (loop->watches, &hash_iter);
693 while (_dbus_hash_iter_next (&hash_iter))
700 fd = _dbus_hash_iter_get_int_key (&hash_iter);
701 watches = _dbus_hash_iter_get_value (&hash_iter);
703 for (link = _dbus_list_get_first_link (watches);
705 link = _dbus_list_get_next_link (watches, link))
707 DBusWatch *watch = link->data;
709 if (_dbus_watch_get_oom_last_time (watch))
711 _dbus_watch_set_oom_last_time (watch, FALSE);
717 refresh_watches_for_fd (loop, watches, fd);
720 retval = TRUE; /* return TRUE here to keep the loop going,
721 * since we don't know the watch was inactive */
724 initial_serial = loop->callback_list_serial;
726 if (loop->timeout_count > 0)
728 unsigned long tv_sec;
729 unsigned long tv_usec;
731 _dbus_get_monotonic_time (&tv_sec, &tv_usec);
733 /* It'd be nice to avoid this O(n) thingy here */
734 link = _dbus_list_get_first_link (&loop->timeouts);
737 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
738 TimeoutCallback *tcb = link->data;
740 if (initial_serial != loop->callback_list_serial)
743 if (loop->depth != orig_depth)
746 if (dbus_timeout_get_enabled (tcb->timeout))
750 if (check_timeout (tv_sec, tv_usec,
751 tcb, &msecs_remaining))
753 /* Save last callback time and fire this timeout */
754 tcb->last_tv_sec = tv_sec;
755 tcb->last_tv_usec = tv_usec;
758 _dbus_verbose (" invoking timeout\n");
761 /* can theoretically return FALSE on OOM, but we just
762 * let it fire again later - in practice that's what
763 * every wrapper callback in dbus-daemon used to do */
764 dbus_timeout_handle (tcb->timeout);
771 _dbus_verbose (" timeout has not expired\n");
778 _dbus_verbose (" skipping invocation of disabled timeout\n");
788 for (i = 0; i < n_ready; i++)
792 unsigned int condition;
795 /* FIXME I think this "restart if we change the watches"
796 * approach could result in starving watches
797 * toward the end of the list.
799 if (initial_serial != loop->callback_list_serial)
802 if (loop->depth != orig_depth)
805 _dbus_assert (ready_fds[i].flags != 0);
807 if (_DBUS_UNLIKELY (ready_fds[i].flags & _DBUS_WATCH_NVAL))
809 cull_watches_for_invalid_fd (loop, ready_fds[i].fd);
813 condition = ready_fds[i].flags;
814 _dbus_assert ((condition & _DBUS_WATCH_NVAL) == 0);
816 /* condition may still be 0 if we got some
817 * weird POLLFOO thing like POLLWRBAND
822 watches = _dbus_hash_table_lookup_int (loop->watches,
830 for (link = _dbus_list_get_first_link (watches);
834 DBusWatch *watch = link->data;
836 next = _dbus_list_get_next_link (watches, link);
838 if (dbus_watch_get_enabled (watch))
842 oom = !dbus_watch_handle (watch, condition);
846 _dbus_watch_set_oom_last_time (watch, TRUE);
847 loop->oom_watch_pending = TRUE;
852 _dbus_verbose (" Invoked watch, oom = %d\n", oom);
856 /* We re-check this every time, in case the callback
857 * added/removed watches, which might make our position in
858 * the linked list invalid. See the FIXME above. */
859 if (initial_serial != loop->callback_list_serial ||
860 loop->depth != orig_depth)
863 refresh_watches_for_fd (loop, NULL, ready_fds[i].fd);
871 refresh_watches_for_fd (loop, watches, ready_fds[i].fd);
877 _dbus_verbose (" moving to next iteration\n");
880 if (_dbus_loop_dispatch (loop))
884 _dbus_verbose ("Returning %d\n", retval);
891 _dbus_loop_run (DBusLoop *loop)
895 _dbus_assert (loop->depth >= 0);
897 _dbus_loop_ref (loop);
899 our_exit_depth = loop->depth;
902 _dbus_verbose ("Running main loop, depth %d -> %d\n",
903 loop->depth - 1, loop->depth);
905 while (loop->depth != our_exit_depth)
906 _dbus_loop_iterate (loop, TRUE);
908 _dbus_loop_unref (loop);
912 _dbus_loop_quit (DBusLoop *loop)
914 _dbus_assert (loop->depth > 0);
918 _dbus_verbose ("Quit main loop, depth %d -> %d\n",
919 loop->depth + 1, loop->depth);
923 _dbus_get_oom_wait (void)
925 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
926 /* make tests go fast */
934 _dbus_wait_for_memory (void)
936 _dbus_verbose ("Waiting for more memory\n");
937 _dbus_sleep_milliseconds (_dbus_get_oom_wait ());
940 #endif /* !DOXYGEN_SHOULD_SKIP_THIS */