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 /** fd => 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;
57 unsigned long last_tv_sec;
58 unsigned long last_tv_usec;
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_INT, 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_int (loop->watches, fd);
180 watches = dbus_new0 (DBusList *, 1);
185 if (!_dbus_hash_table_insert_int (loop->watches, fd, watches))
196 cull_watches_for_invalid_fd (DBusLoop *loop,
202 _dbus_warn ("invalid request, socket fd %d not open\n", fd);
203 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
207 for (link = _dbus_list_get_first_link (watches);
209 link = _dbus_list_get_next_link (watches, link))
210 _dbus_watch_invalidate (link->data);
213 _dbus_hash_table_remove_int (loop->watches, fd);
217 gc_watch_table_entry (DBusLoop *loop,
221 /* If watches is already NULL we have nothing to do */
225 /* We can't GC hash table entries if they're non-empty lists */
226 if (*watches != NULL)
229 _dbus_hash_table_remove_int (loop->watches, fd);
234 refresh_watches_for_fd (DBusLoop *loop,
239 unsigned int flags = 0;
240 dbus_bool_t interested = FALSE;
242 _dbus_assert (fd != -1);
245 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
247 /* we allocated this in the first _dbus_loop_add_watch for the fd, and keep
248 * it until there are none left */
249 _dbus_assert (watches != NULL);
251 for (link = _dbus_list_get_first_link (watches);
253 link = _dbus_list_get_next_link (watches, link))
255 if (dbus_watch_get_enabled (link->data) &&
256 !_dbus_watch_get_oom_last_time (link->data))
258 flags |= dbus_watch_get_flags (link->data);
264 _dbus_socket_set_enable (loop->socket_set, fd, flags);
266 _dbus_socket_set_disable (loop->socket_set, fd);
270 _dbus_loop_add_watch (DBusLoop *loop,
276 fd = dbus_watch_get_socket (watch);
277 _dbus_assert (fd != -1);
279 watches = ensure_watch_table_entry (loop, fd);
284 if (!_dbus_list_append (watches, _dbus_watch_ref (watch)))
286 _dbus_watch_unref (watch);
287 gc_watch_table_entry (loop, watches, fd);
292 if (_dbus_list_length_is_one (watches))
294 if (!_dbus_socket_set_add (loop->socket_set, fd,
295 dbus_watch_get_flags (watch),
296 dbus_watch_get_enabled (watch)))
298 _dbus_hash_table_remove_int (loop->watches, fd);
304 /* we're modifying, not adding, which can't fail with OOM */
305 refresh_watches_for_fd (loop, watches, fd);
308 loop->callback_list_serial += 1;
309 loop->watch_count += 1;
314 _dbus_loop_toggle_watch (DBusLoop *loop,
317 refresh_watches_for_fd (loop, NULL, dbus_watch_get_socket (watch));
321 _dbus_loop_remove_watch (DBusLoop *loop,
328 /* This relies on people removing watches before they invalidate them,
329 * which has been safe since fd.o #33336 was fixed. Assert about it
330 * so we don't regress. */
331 fd = dbus_watch_get_socket (watch);
332 _dbus_assert (fd != -1);
334 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
338 link = _dbus_list_get_first_link (watches);
341 DBusList *next = _dbus_list_get_next_link (watches, link);
342 DBusWatch *this = link->data;
346 _dbus_list_remove_link (watches, link);
347 loop->callback_list_serial += 1;
348 loop->watch_count -= 1;
349 _dbus_watch_unref (this);
351 /* if that was the last watch for that fd, drop the hash table
352 * entry, and stop reserving space for it in the socket set */
353 if (gc_watch_table_entry (loop, watches, fd))
355 _dbus_socket_set_remove (loop->socket_set, fd);
365 _dbus_warn ("could not find watch %p to remove\n", watch);
369 _dbus_loop_add_timeout (DBusLoop *loop,
370 DBusTimeout *timeout)
372 TimeoutCallback *tcb;
374 tcb = timeout_callback_new (timeout);
378 if (_dbus_list_append (&loop->timeouts, tcb))
380 loop->callback_list_serial += 1;
381 loop->timeout_count += 1;
385 timeout_callback_free (tcb);
393 _dbus_loop_remove_timeout (DBusLoop *loop,
394 DBusTimeout *timeout)
398 link = _dbus_list_get_first_link (&loop->timeouts);
401 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
402 TimeoutCallback *this = link->data;
404 if (this->timeout == timeout)
406 _dbus_list_remove_link (&loop->timeouts, link);
407 loop->callback_list_serial += 1;
408 loop->timeout_count -= 1;
409 timeout_callback_free (this);
417 _dbus_warn ("could not find timeout %p to remove\n", timeout);
420 /* Convolutions from GLib, there really must be a better way
424 check_timeout (unsigned long tv_sec,
425 unsigned long tv_usec,
426 TimeoutCallback *tcb,
431 unsigned long expiration_tv_sec;
432 unsigned long expiration_tv_usec;
433 long interval_seconds;
434 long interval_milliseconds;
437 /* I'm pretty sure this function could suck (a lot) less */
439 interval = dbus_timeout_get_interval (tcb->timeout);
441 interval_seconds = interval / 1000L;
442 interval_milliseconds = interval % 1000L;
444 expiration_tv_sec = tcb->last_tv_sec + interval_seconds;
445 expiration_tv_usec = tcb->last_tv_usec + interval_milliseconds * 1000;
446 if (expiration_tv_usec >= 1000000)
448 expiration_tv_usec -= 1000000;
449 expiration_tv_sec += 1;
452 sec_remaining = expiration_tv_sec - tv_sec;
453 /* need to force this to be signed, as it is intended to sometimes
454 * produce a negative result
456 msec_remaining = ((long) expiration_tv_usec - (long) tv_usec) / 1000L;
459 _dbus_verbose ("Interval is %ld seconds %ld msecs\n",
461 interval_milliseconds);
462 _dbus_verbose ("Now is %lu seconds %lu usecs\n",
464 _dbus_verbose ("Last is %lu seconds %lu usecs\n",
465 tcb->last_tv_sec, tcb->last_tv_usec);
466 _dbus_verbose ("Exp is %lu seconds %lu usecs\n",
467 expiration_tv_sec, expiration_tv_usec);
468 _dbus_verbose ("Pre-correction, sec_remaining %ld msec_remaining %ld\n",
469 sec_remaining, msec_remaining);
472 /* We do the following in a rather convoluted fashion to deal with
473 * the fact that we don't have an integral type big enough to hold
474 * the difference of two timevals in milliseconds.
476 if (sec_remaining < 0 || (sec_remaining == 0 && msec_remaining < 0))
482 if (msec_remaining < 0)
484 msec_remaining += 1000;
488 if (sec_remaining > (_DBUS_INT_MAX / 1000) ||
489 msec_remaining > _DBUS_INT_MAX)
490 *timeout = _DBUS_INT_MAX;
492 *timeout = sec_remaining * 1000 + msec_remaining;
495 if (*timeout > interval)
497 /* This indicates that the system clock probably moved backward */
498 _dbus_verbose ("System clock set backward! Resetting timeout.\n");
500 tcb->last_tv_sec = tv_sec;
501 tcb->last_tv_usec = tv_usec;
507 _dbus_verbose (" timeout expires in %d milliseconds\n", *timeout);
510 return *timeout == 0;
514 _dbus_loop_dispatch (DBusLoop *loop)
518 _dbus_verbose (" %d connections to dispatch\n", _dbus_list_get_length (&loop->need_dispatch));
521 if (loop->need_dispatch == NULL)
525 while (loop->need_dispatch != NULL)
527 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
531 DBusDispatchStatus status;
533 status = dbus_connection_dispatch (connection);
535 if (status == DBUS_DISPATCH_COMPLETE)
537 dbus_connection_unref (connection);
542 if (status == DBUS_DISPATCH_NEED_MEMORY)
543 _dbus_wait_for_memory ();
552 _dbus_loop_queue_dispatch (DBusLoop *loop,
553 DBusConnection *connection)
555 if (_dbus_list_append (&loop->need_dispatch, connection))
557 dbus_connection_ref (connection);
564 /* Returns TRUE if we invoked any timeouts or have ready file
565 * descriptors, which is just used in test code as a debug hack
569 _dbus_loop_iterate (DBusLoop *loop,
572 #define N_STACK_DESCRIPTORS 64
574 DBusSocketEvent ready_fds[N_STACK_DESCRIPTORS];
584 orig_depth = loop->depth;
587 _dbus_verbose ("Iteration block=%d depth=%d timeout_count=%d watch_count=%d\n",
588 block, loop->depth, loop->timeout_count, loop->watch_count);
591 if (_dbus_hash_table_get_n_entries (loop->watches) == 0 &&
592 loop->timeouts == NULL)
596 if (loop->timeout_count > 0)
598 unsigned long tv_sec;
599 unsigned long tv_usec;
601 _dbus_get_monotonic_time (&tv_sec, &tv_usec);
603 link = _dbus_list_get_first_link (&loop->timeouts);
606 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
607 TimeoutCallback *tcb = link->data;
609 if (dbus_timeout_get_enabled (tcb->timeout))
613 check_timeout (tv_sec, tv_usec, tcb, &msecs_remaining);
616 timeout = msecs_remaining;
618 timeout = MIN (msecs_remaining, timeout);
621 _dbus_verbose (" timeout added, %d remaining, aggregate timeout %ld\n",
622 msecs_remaining, timeout);
625 _dbus_assert (timeout >= 0);
628 break; /* it's not going to get shorter... */
633 _dbus_verbose (" skipping disabled timeout\n");
641 /* Never block if we have stuff to dispatch */
642 if (!block || loop->need_dispatch != NULL)
646 _dbus_verbose (" timeout is 0 as we aren't blocking\n");
650 /* if a watch was OOM last time, don't wait longer than the OOM
651 * wait to re-enable it
653 if (loop->oom_watch_pending)
654 timeout = MIN (timeout, _dbus_get_oom_wait ());
657 _dbus_verbose (" polling on %d descriptors timeout %ld\n", n_fds, timeout);
660 n_ready = _dbus_socket_set_poll (loop->socket_set, ready_fds,
661 _DBUS_N_ELEMENTS (ready_fds), timeout);
663 /* re-enable any watches we skipped this time */
664 if (loop->oom_watch_pending)
666 DBusHashIter hash_iter;
668 loop->oom_watch_pending = FALSE;
670 _dbus_hash_iter_init (loop->watches, &hash_iter);
672 while (_dbus_hash_iter_next (&hash_iter))
679 fd = _dbus_hash_iter_get_int_key (&hash_iter);
680 watches = _dbus_hash_iter_get_value (&hash_iter);
682 for (link = _dbus_list_get_first_link (watches);
684 link = _dbus_list_get_next_link (watches, link))
686 DBusWatch *watch = link->data;
688 if (_dbus_watch_get_oom_last_time (watch))
690 _dbus_watch_set_oom_last_time (watch, FALSE);
696 refresh_watches_for_fd (loop, watches, fd);
699 retval = TRUE; /* return TRUE here to keep the loop going,
700 * since we don't know the watch was inactive */
703 initial_serial = loop->callback_list_serial;
705 if (loop->timeout_count > 0)
707 unsigned long tv_sec;
708 unsigned long tv_usec;
710 _dbus_get_monotonic_time (&tv_sec, &tv_usec);
712 /* It'd be nice to avoid this O(n) thingy here */
713 link = _dbus_list_get_first_link (&loop->timeouts);
716 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
717 TimeoutCallback *tcb = link->data;
719 if (initial_serial != loop->callback_list_serial)
722 if (loop->depth != orig_depth)
725 if (dbus_timeout_get_enabled (tcb->timeout))
729 if (check_timeout (tv_sec, tv_usec,
730 tcb, &msecs_remaining))
732 /* Save last callback time and fire this timeout */
733 tcb->last_tv_sec = tv_sec;
734 tcb->last_tv_usec = tv_usec;
737 _dbus_verbose (" invoking timeout\n");
740 /* can theoretically return FALSE on OOM, but we just
741 * let it fire again later - in practice that's what
742 * every wrapper callback in dbus-daemon used to do */
743 dbus_timeout_handle (tcb->timeout);
750 _dbus_verbose (" timeout has not expired\n");
757 _dbus_verbose (" skipping invocation of disabled timeout\n");
767 for (i = 0; i < n_ready; i++)
771 unsigned int condition;
774 /* FIXME I think this "restart if we change the watches"
775 * approach could result in starving watches
776 * toward the end of the list.
778 if (initial_serial != loop->callback_list_serial)
781 if (loop->depth != orig_depth)
784 _dbus_assert (ready_fds[i].flags != 0);
786 if (_DBUS_UNLIKELY (ready_fds[i].flags & _DBUS_WATCH_NVAL))
788 cull_watches_for_invalid_fd (loop, ready_fds[i].fd);
792 condition = ready_fds[i].flags;
793 _dbus_assert ((condition & _DBUS_WATCH_NVAL) == 0);
795 /* condition may still be 0 if we got some
796 * weird POLLFOO thing like POLLWRBAND
801 watches = _dbus_hash_table_lookup_int (loop->watches,
809 for (link = _dbus_list_get_first_link (watches);
813 DBusWatch *watch = link->data;
815 next = _dbus_list_get_next_link (watches, link);
817 if (dbus_watch_get_enabled (watch))
821 oom = !dbus_watch_handle (watch, condition);
825 _dbus_watch_set_oom_last_time (watch, TRUE);
826 loop->oom_watch_pending = TRUE;
831 _dbus_verbose (" Invoked watch, oom = %d\n", oom);
835 /* We re-check this every time, in case the callback
836 * added/removed watches, which might make our position in
837 * the linked list invalid. See the FIXME above. */
838 if (initial_serial != loop->callback_list_serial ||
839 loop->depth != orig_depth)
842 refresh_watches_for_fd (loop, NULL, ready_fds[i].fd);
850 refresh_watches_for_fd (loop, watches, ready_fds[i].fd);
856 _dbus_verbose (" moving to next iteration\n");
859 if (_dbus_loop_dispatch (loop))
863 _dbus_verbose ("Returning %d\n", retval);
870 _dbus_loop_run (DBusLoop *loop)
874 _dbus_assert (loop->depth >= 0);
876 _dbus_loop_ref (loop);
878 our_exit_depth = loop->depth;
881 _dbus_verbose ("Running main loop, depth %d -> %d\n",
882 loop->depth - 1, loop->depth);
884 while (loop->depth != our_exit_depth)
885 _dbus_loop_iterate (loop, TRUE);
887 _dbus_loop_unref (loop);
891 _dbus_loop_quit (DBusLoop *loop)
893 _dbus_assert (loop->depth > 0);
897 _dbus_verbose ("Quit main loop, depth %d -> %d\n",
898 loop->depth + 1, loop->depth);
902 _dbus_get_oom_wait (void)
904 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
905 /* make tests go fast */
913 _dbus_wait_for_memory (void)
915 _dbus_verbose ("Waiting for more memory\n");
916 _dbus_sleep_milliseconds (_dbus_get_oom_wait ());
919 #endif /* !DOXYGEN_SHOULD_SKIP_THIS */