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;
79 unsigned long last_tv_sec;
80 unsigned long last_tv_usec;
83 #define TIMEOUT_CALLBACK(callback) ((TimeoutCallback*)callback)
85 static TimeoutCallback*
86 timeout_callback_new (DBusTimeout *timeout)
90 cb = dbus_new (TimeoutCallback, 1);
94 cb->timeout = timeout;
95 _dbus_get_current_time (&cb->last_tv_sec,
101 static TimeoutCallback *
102 timeout_callback_ref (TimeoutCallback *cb)
104 _dbus_assert (cb->refcount > 0);
112 timeout_callback_unref (TimeoutCallback *cb)
114 _dbus_assert (cb->refcount > 0);
118 if (cb->refcount == 0)
125 free_watch_table_entry (void *data)
127 DBusList **watches = data;
130 /* DBusHashTable sometimes calls free_function(NULL) even if you never
131 * have NULL as a value */
135 for (watch = _dbus_list_pop_first (watches);
137 watch = _dbus_list_pop_first (watches))
139 _dbus_watch_unref (watch);
142 _dbus_assert (*watches == NULL);
147 _dbus_loop_new (void)
151 loop = dbus_new0 (DBusLoop, 1);
155 loop->watches = _dbus_hash_table_new (DBUS_HASH_INT, NULL,
156 free_watch_table_entry);
158 loop->socket_set = _dbus_socket_set_new (0);
160 if (loop->watches == NULL || loop->socket_set == NULL)
162 if (loop->watches != NULL)
163 _dbus_hash_table_unref (loop->watches);
165 if (loop->socket_set != NULL)
166 _dbus_socket_set_free (loop->socket_set);
178 _dbus_loop_ref (DBusLoop *loop)
180 _dbus_assert (loop != NULL);
181 _dbus_assert (loop->refcount > 0);
189 _dbus_loop_unref (DBusLoop *loop)
191 _dbus_assert (loop != NULL);
192 _dbus_assert (loop->refcount > 0);
195 if (loop->refcount == 0)
197 while (loop->need_dispatch)
199 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
201 dbus_connection_unref (connection);
204 _dbus_hash_table_unref (loop->watches);
205 _dbus_socket_set_free (loop->socket_set);
211 ensure_watch_table_entry (DBusLoop *loop,
216 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
220 watches = dbus_new0 (DBusList *, 1);
225 if (!_dbus_hash_table_insert_int (loop->watches, fd, watches))
236 cull_watches_for_invalid_fd (DBusLoop *loop,
243 _dbus_warn ("invalid request, socket fd %d not open\n", fd);
244 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
248 for (link = _dbus_list_get_first_link (watches);
250 link = _dbus_list_get_next_link (watches, link))
251 _dbus_watch_invalidate (link->data);
254 _dbus_hash_table_remove_int (loop->watches, fd);
258 gc_watch_table_entry (DBusLoop *loop,
262 /* If watches is already NULL we have nothing to do */
266 /* We can't GC hash table entries if they're non-empty lists */
267 if (*watches != NULL)
270 _dbus_hash_table_remove_int (loop->watches, fd);
275 refresh_watches_for_fd (DBusLoop *loop,
280 unsigned int flags = 0;
281 dbus_bool_t interested;
283 _dbus_assert (fd != -1);
286 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
288 /* we allocated this in the first _dbus_loop_add_watch for the fd, and keep
289 * it until there are none left */
290 _dbus_assert (watches != NULL);
292 for (link = _dbus_list_get_first_link (watches);
294 link = _dbus_list_get_next_link (watches, link))
296 if (dbus_watch_get_enabled (link->data) &&
297 !_dbus_watch_get_oom_last_time (link->data))
299 flags |= dbus_watch_get_flags (link->data);
305 _dbus_socket_set_enable (loop->socket_set, fd, flags);
307 _dbus_socket_set_disable (loop->socket_set, fd);
311 _dbus_loop_add_watch (DBusLoop *loop,
317 fd = dbus_watch_get_socket (watch);
318 _dbus_assert (fd != -1);
320 watches = ensure_watch_table_entry (loop, fd);
325 if (!_dbus_list_append (watches, _dbus_watch_ref (watch)))
327 _dbus_watch_unref (watch);
328 gc_watch_table_entry (loop, watches, fd);
333 if (_dbus_list_length_is_one (watches))
335 if (!_dbus_socket_set_add (loop->socket_set, fd,
336 dbus_watch_get_flags (watch),
337 dbus_watch_get_enabled (watch)))
339 _dbus_hash_table_remove_int (loop->watches, fd);
345 /* we're modifying, not adding, which can't fail with OOM */
346 refresh_watches_for_fd (loop, watches, fd);
349 loop->callback_list_serial += 1;
350 loop->watch_count += 1;
355 _dbus_loop_toggle_watch (DBusLoop *loop,
358 refresh_watches_for_fd (loop, NULL, dbus_watch_get_socket (watch));
362 _dbus_loop_remove_watch (DBusLoop *loop,
369 /* This relies on people removing watches before they invalidate them,
370 * which has been safe since fd.o #33336 was fixed. Assert about it
371 * so we don't regress. */
372 fd = dbus_watch_get_socket (watch);
373 _dbus_assert (fd != -1);
375 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
379 link = _dbus_list_get_first_link (watches);
382 DBusList *next = _dbus_list_get_next_link (watches, link);
383 DBusWatch *this = link->data;
387 _dbus_list_remove_link (watches, link);
388 loop->callback_list_serial += 1;
389 loop->watch_count -= 1;
390 _dbus_watch_unref (this);
392 /* if that was the last watch for that fd, drop the hash table
393 * entry, and stop reserving space for it in the socket set */
394 if (gc_watch_table_entry (loop, watches, fd))
396 _dbus_socket_set_remove (loop->socket_set, fd);
406 _dbus_warn ("could not find watch %p to remove\n", watch);
410 _dbus_loop_add_timeout (DBusLoop *loop,
411 DBusTimeout *timeout)
413 TimeoutCallback *tcb;
415 tcb = timeout_callback_new (timeout);
419 if (_dbus_list_append (&loop->timeouts, tcb))
421 loop->callback_list_serial += 1;
422 loop->timeout_count += 1;
426 timeout_callback_unref (tcb);
434 _dbus_loop_remove_timeout (DBusLoop *loop,
435 DBusTimeout *timeout)
439 link = _dbus_list_get_first_link (&loop->timeouts);
442 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
443 TimeoutCallback *this = link->data;
445 if (this->timeout == timeout)
447 _dbus_list_remove_link (&loop->timeouts, link);
448 loop->callback_list_serial += 1;
449 loop->timeout_count -= 1;
450 timeout_callback_unref (this);
458 _dbus_warn ("could not find timeout %p to remove\n", timeout);
461 /* Convolutions from GLib, there really must be a better way
465 check_timeout (unsigned long tv_sec,
466 unsigned long tv_usec,
467 TimeoutCallback *tcb,
472 unsigned long expiration_tv_sec;
473 unsigned long expiration_tv_usec;
474 long interval_seconds;
475 long interval_milliseconds;
478 /* I'm pretty sure this function could suck (a lot) less */
480 interval = dbus_timeout_get_interval (tcb->timeout);
482 interval_seconds = interval / 1000L;
483 interval_milliseconds = interval % 1000L;
485 expiration_tv_sec = tcb->last_tv_sec + interval_seconds;
486 expiration_tv_usec = tcb->last_tv_usec + interval_milliseconds * 1000;
487 if (expiration_tv_usec >= 1000000)
489 expiration_tv_usec -= 1000000;
490 expiration_tv_sec += 1;
493 sec_remaining = expiration_tv_sec - tv_sec;
494 /* need to force this to be signed, as it is intended to sometimes
495 * produce a negative result
497 msec_remaining = ((long) expiration_tv_usec - (long) tv_usec) / 1000L;
500 _dbus_verbose ("Interval is %ld seconds %ld msecs\n",
502 interval_milliseconds);
503 _dbus_verbose ("Now is %lu seconds %lu usecs\n",
505 _dbus_verbose ("Last is %lu seconds %lu usecs\n",
506 tcb->last_tv_sec, tcb->last_tv_usec);
507 _dbus_verbose ("Exp is %lu seconds %lu usecs\n",
508 expiration_tv_sec, expiration_tv_usec);
509 _dbus_verbose ("Pre-correction, sec_remaining %ld msec_remaining %ld\n",
510 sec_remaining, msec_remaining);
513 /* We do the following in a rather convoluted fashion to deal with
514 * the fact that we don't have an integral type big enough to hold
515 * the difference of two timevals in milliseconds.
517 if (sec_remaining < 0 || (sec_remaining == 0 && msec_remaining < 0))
523 if (msec_remaining < 0)
525 msec_remaining += 1000;
529 if (sec_remaining > (_DBUS_INT_MAX / 1000) ||
530 msec_remaining > _DBUS_INT_MAX)
531 *timeout = _DBUS_INT_MAX;
533 *timeout = sec_remaining * 1000 + msec_remaining;
536 if (*timeout > interval)
538 /* This indicates that the system clock probably moved backward */
539 _dbus_verbose ("System clock set backward! Resetting timeout.\n");
541 tcb->last_tv_sec = tv_sec;
542 tcb->last_tv_usec = tv_usec;
548 _dbus_verbose (" timeout expires in %d milliseconds\n", *timeout);
551 return *timeout == 0;
555 _dbus_loop_dispatch (DBusLoop *loop)
559 _dbus_verbose (" %d connections to dispatch\n", _dbus_list_get_length (&loop->need_dispatch));
562 if (loop->need_dispatch == NULL)
566 while (loop->need_dispatch != NULL)
568 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
572 DBusDispatchStatus status;
574 status = dbus_connection_dispatch (connection);
576 if (status == DBUS_DISPATCH_COMPLETE)
578 dbus_connection_unref (connection);
583 if (status == DBUS_DISPATCH_NEED_MEMORY)
584 _dbus_wait_for_memory ();
593 _dbus_loop_queue_dispatch (DBusLoop *loop,
594 DBusConnection *connection)
596 if (_dbus_list_append (&loop->need_dispatch, connection))
598 dbus_connection_ref (connection);
605 /* Returns TRUE if we invoked any timeouts or have ready file
606 * descriptors, which is just used in test code as a debug hack
610 _dbus_loop_iterate (DBusLoop *loop,
613 #define N_STACK_DESCRIPTORS 64
615 DBusSocketEvent ready_fds[N_STACK_DESCRIPTORS];
625 orig_depth = loop->depth;
628 _dbus_verbose ("Iteration block=%d depth=%d timeout_count=%d watch_count=%d\n",
629 block, loop->depth, loop->timeout_count, loop->watch_count);
632 if (_dbus_hash_table_get_n_entries (loop->watches) == 0 &&
633 loop->timeouts == NULL)
637 if (loop->timeout_count > 0)
639 unsigned long tv_sec;
640 unsigned long tv_usec;
642 _dbus_get_current_time (&tv_sec, &tv_usec);
644 link = _dbus_list_get_first_link (&loop->timeouts);
647 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
648 TimeoutCallback *tcb = link->data;
650 if (dbus_timeout_get_enabled (tcb->timeout))
654 check_timeout (tv_sec, tv_usec, tcb, &msecs_remaining);
657 timeout = msecs_remaining;
659 timeout = MIN (msecs_remaining, timeout);
662 _dbus_verbose (" timeout added, %d remaining, aggregate timeout %ld\n",
663 msecs_remaining, timeout);
666 _dbus_assert (timeout >= 0);
669 break; /* it's not going to get shorter... */
674 _dbus_verbose (" skipping disabled timeout\n");
682 /* Never block if we have stuff to dispatch */
683 if (!block || loop->need_dispatch != NULL)
687 _dbus_verbose (" timeout is 0 as we aren't blocking\n");
691 /* if a watch was OOM last time, don't wait longer than the OOM
692 * wait to re-enable it
694 if (loop->oom_watch_pending)
695 timeout = MIN (timeout, _dbus_get_oom_wait ());
698 _dbus_verbose (" polling on %d descriptors timeout %ld\n", n_fds, timeout);
701 n_ready = _dbus_socket_set_poll (loop->socket_set, ready_fds,
702 _DBUS_N_ELEMENTS (ready_fds), timeout);
704 /* re-enable any watches we skipped this time */
705 if (loop->oom_watch_pending)
707 DBusHashIter hash_iter;
709 loop->oom_watch_pending = FALSE;
711 _dbus_hash_iter_init (loop->watches, &hash_iter);
713 while (_dbus_hash_iter_next (&hash_iter))
720 fd = _dbus_hash_iter_get_int_key (&hash_iter);
721 watches = _dbus_hash_iter_get_value (&hash_iter);
723 for (link = _dbus_list_get_first_link (watches);
725 link = _dbus_list_get_next_link (watches, link))
727 DBusWatch *watch = link->data;
729 if (_dbus_watch_get_oom_last_time (watch))
731 _dbus_watch_set_oom_last_time (watch, FALSE);
737 refresh_watches_for_fd (loop, watches, fd);
740 retval = TRUE; /* return TRUE here to keep the loop going,
741 * since we don't know the watch was inactive */
744 initial_serial = loop->callback_list_serial;
746 if (loop->timeout_count > 0)
748 unsigned long tv_sec;
749 unsigned long tv_usec;
751 _dbus_get_current_time (&tv_sec, &tv_usec);
753 /* It'd be nice to avoid this O(n) thingy here */
754 link = _dbus_list_get_first_link (&loop->timeouts);
757 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
758 TimeoutCallback *tcb = link->data;
760 if (initial_serial != loop->callback_list_serial)
763 if (loop->depth != orig_depth)
766 if (dbus_timeout_get_enabled (tcb->timeout))
770 if (check_timeout (tv_sec, tv_usec,
771 tcb, &msecs_remaining))
773 /* Save last callback time and fire this timeout */
774 tcb->last_tv_sec = tv_sec;
775 tcb->last_tv_usec = tv_usec;
778 _dbus_verbose (" invoking timeout\n");
781 /* can theoretically return FALSE on OOM, but we just
782 * let it fire again later - in practice that's what
783 * every wrapper callback in dbus-daemon used to do */
784 dbus_timeout_handle (tcb->timeout);
791 _dbus_verbose (" timeout has not expired\n");
798 _dbus_verbose (" skipping invocation of disabled timeout\n");
808 for (i = 0; i < n_ready; i++)
812 unsigned int condition;
815 /* FIXME I think this "restart if we change the watches"
816 * approach could result in starving watches
817 * toward the end of the list.
819 if (initial_serial != loop->callback_list_serial)
822 if (loop->depth != orig_depth)
825 _dbus_assert (ready_fds[i].flags != 0);
827 if (_DBUS_UNLIKELY (ready_fds[i].flags & _DBUS_WATCH_NVAL))
829 cull_watches_for_invalid_fd (loop, ready_fds[i].fd);
833 condition = ready_fds[i].flags;
834 _dbus_assert ((condition & _DBUS_WATCH_NVAL) == 0);
836 /* condition may still be 0 if we got some
837 * weird POLLFOO thing like POLLWRBAND
842 watches = _dbus_hash_table_lookup_int (loop->watches,
850 for (link = _dbus_list_get_first_link (watches);
854 DBusWatch *watch = link->data;
856 next = _dbus_list_get_next_link (watches, link);
858 if (dbus_watch_get_enabled (watch))
862 oom = !dbus_watch_handle (watch, condition);
866 _dbus_watch_set_oom_last_time (watch, TRUE);
867 loop->oom_watch_pending = TRUE;
872 _dbus_verbose (" Invoked watch, oom = %d\n", oom);
876 /* We re-check this every time, in case the callback
877 * added/removed watches, which might make our position in
878 * the linked list invalid. See the FIXME above. */
879 if (initial_serial != loop->callback_list_serial ||
880 loop->depth != orig_depth)
883 refresh_watches_for_fd (loop, NULL, ready_fds[i].fd);
891 refresh_watches_for_fd (loop, watches, ready_fds[i].fd);
897 _dbus_verbose (" moving to next iteration\n");
900 if (_dbus_loop_dispatch (loop))
904 _dbus_verbose ("Returning %d\n", retval);
911 _dbus_loop_run (DBusLoop *loop)
915 _dbus_assert (loop->depth >= 0);
917 _dbus_loop_ref (loop);
919 our_exit_depth = loop->depth;
922 _dbus_verbose ("Running main loop, depth %d -> %d\n",
923 loop->depth - 1, loop->depth);
925 while (loop->depth != our_exit_depth)
926 _dbus_loop_iterate (loop, TRUE);
928 _dbus_loop_unref (loop);
932 _dbus_loop_quit (DBusLoop *loop)
934 _dbus_assert (loop->depth > 0);
938 _dbus_verbose ("Quit main loop, depth %d -> %d\n",
939 loop->depth + 1, loop->depth);
943 _dbus_get_oom_wait (void)
945 #ifdef DBUS_BUILD_TESTS
946 /* make tests go fast */
954 _dbus_wait_for_memory (void)
956 _dbus_verbose ("Waiting for more memory\n");
957 _dbus_sleep_milliseconds (_dbus_get_oom_wait ());
960 #endif /* !DOXYGEN_SHOULD_SKIP_THIS */