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;
64 int callback_list_serial;
67 int depth; /**< number of recursive runs */
68 DBusList *need_dispatch;
75 unsigned long last_tv_sec;
76 unsigned long last_tv_usec;
79 #define TIMEOUT_CALLBACK(callback) ((TimeoutCallback*)callback)
81 static TimeoutCallback*
82 timeout_callback_new (DBusTimeout *timeout)
86 cb = dbus_new (TimeoutCallback, 1);
90 cb->timeout = timeout;
91 _dbus_get_current_time (&cb->last_tv_sec,
97 static TimeoutCallback *
98 timeout_callback_ref (TimeoutCallback *cb)
100 _dbus_assert (cb->refcount > 0);
108 timeout_callback_unref (TimeoutCallback *cb)
110 _dbus_assert (cb->refcount > 0);
114 if (cb->refcount == 0)
121 free_watch_table_entry (void *data)
123 DBusList **watches = data;
126 /* DBusHashTable sometimes calls free_function(NULL) even if you never
127 * have NULL as a value */
131 for (watch = _dbus_list_pop_first (watches);
133 watch = _dbus_list_pop_first (watches))
135 _dbus_watch_unref (watch);
138 _dbus_assert (*watches == NULL);
143 _dbus_loop_new (void)
147 loop = dbus_new0 (DBusLoop, 1);
151 loop->watches = _dbus_hash_table_new (DBUS_HASH_INT, NULL,
152 free_watch_table_entry);
154 if (loop->watches == NULL)
166 _dbus_loop_ref (DBusLoop *loop)
168 _dbus_assert (loop != NULL);
169 _dbus_assert (loop->refcount > 0);
177 _dbus_loop_unref (DBusLoop *loop)
179 _dbus_assert (loop != NULL);
180 _dbus_assert (loop->refcount > 0);
183 if (loop->refcount == 0)
185 while (loop->need_dispatch)
187 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
189 dbus_connection_unref (connection);
192 _dbus_hash_table_unref (loop->watches);
198 ensure_watch_table_entry (DBusLoop *loop,
203 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
207 watches = dbus_new0 (DBusList *, 1);
212 if (!_dbus_hash_table_insert_int (loop->watches, fd, watches))
223 cull_watches_for_invalid_fd (DBusLoop *loop,
230 _dbus_warn ("invalid request, socket fd %d not open\n", fd);
231 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
235 for (link = _dbus_list_get_first_link (watches);
237 link = _dbus_list_get_next_link (watches, link))
238 _dbus_watch_invalidate (link->data);
241 _dbus_hash_table_remove_int (loop->watches, fd);
245 gc_watch_table_entry (DBusLoop *loop,
249 /* If watches is already NULL we have nothing to do */
253 /* We can't GC hash table entries if they're non-empty lists */
254 if (*watches != NULL)
257 _dbus_hash_table_remove_int (loop->watches, fd);
261 _dbus_loop_add_watch (DBusLoop *loop,
267 fd = dbus_watch_get_socket (watch);
268 _dbus_assert (fd != -1);
270 watches = ensure_watch_table_entry (loop, fd);
275 if (_dbus_list_append (watches, _dbus_watch_ref (watch)))
277 loop->callback_list_serial += 1;
278 loop->watch_count += 1;
282 _dbus_watch_unref (watch);
283 gc_watch_table_entry (loop, watches, fd);
292 _dbus_loop_remove_watch (DBusLoop *loop,
299 /* This relies on people removing watches before they invalidate them,
300 * which has been safe since fd.o #33336 was fixed. Assert about it
301 * so we don't regress. */
302 fd = dbus_watch_get_socket (watch);
303 _dbus_assert (fd != -1);
305 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
309 link = _dbus_list_get_first_link (watches);
312 DBusList *next = _dbus_list_get_next_link (watches, link);
313 DBusWatch *this = link->data;
317 _dbus_list_remove_link (watches, link);
318 loop->callback_list_serial += 1;
319 loop->watch_count -= 1;
320 _dbus_watch_unref (this);
322 /* if that was the last watch for that fd, drop the hash table
324 gc_watch_table_entry (loop, watches, fd);
333 _dbus_warn ("could not find watch %p to remove\n", watch);
337 _dbus_loop_add_timeout (DBusLoop *loop,
338 DBusTimeout *timeout)
340 TimeoutCallback *tcb;
342 tcb = timeout_callback_new (timeout);
346 if (_dbus_list_append (&loop->timeouts, tcb))
348 loop->callback_list_serial += 1;
349 loop->timeout_count += 1;
353 timeout_callback_unref (tcb);
361 _dbus_loop_remove_timeout (DBusLoop *loop,
362 DBusTimeout *timeout)
366 link = _dbus_list_get_first_link (&loop->timeouts);
369 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
370 TimeoutCallback *this = link->data;
372 if (this->timeout == timeout)
374 _dbus_list_remove_link (&loop->timeouts, link);
375 loop->callback_list_serial += 1;
376 loop->timeout_count -= 1;
377 timeout_callback_unref (this);
385 _dbus_warn ("could not find timeout %p to remove\n", timeout);
388 /* Convolutions from GLib, there really must be a better way
392 check_timeout (unsigned long tv_sec,
393 unsigned long tv_usec,
394 TimeoutCallback *tcb,
399 unsigned long expiration_tv_sec;
400 unsigned long expiration_tv_usec;
401 long interval_seconds;
402 long interval_milliseconds;
405 /* I'm pretty sure this function could suck (a lot) less */
407 interval = dbus_timeout_get_interval (tcb->timeout);
409 interval_seconds = interval / 1000L;
410 interval_milliseconds = interval % 1000L;
412 expiration_tv_sec = tcb->last_tv_sec + interval_seconds;
413 expiration_tv_usec = tcb->last_tv_usec + interval_milliseconds * 1000;
414 if (expiration_tv_usec >= 1000000)
416 expiration_tv_usec -= 1000000;
417 expiration_tv_sec += 1;
420 sec_remaining = expiration_tv_sec - tv_sec;
421 /* need to force this to be signed, as it is intended to sometimes
422 * produce a negative result
424 msec_remaining = ((long) expiration_tv_usec - (long) tv_usec) / 1000L;
427 _dbus_verbose ("Interval is %ld seconds %ld msecs\n",
429 interval_milliseconds);
430 _dbus_verbose ("Now is %lu seconds %lu usecs\n",
432 _dbus_verbose ("Last is %lu seconds %lu usecs\n",
433 tcb->last_tv_sec, tcb->last_tv_usec);
434 _dbus_verbose ("Exp is %lu seconds %lu usecs\n",
435 expiration_tv_sec, expiration_tv_usec);
436 _dbus_verbose ("Pre-correction, sec_remaining %ld msec_remaining %ld\n",
437 sec_remaining, msec_remaining);
440 /* We do the following in a rather convoluted fashion to deal with
441 * the fact that we don't have an integral type big enough to hold
442 * the difference of two timevals in milliseconds.
444 if (sec_remaining < 0 || (sec_remaining == 0 && msec_remaining < 0))
450 if (msec_remaining < 0)
452 msec_remaining += 1000;
456 if (sec_remaining > (_DBUS_INT_MAX / 1000) ||
457 msec_remaining > _DBUS_INT_MAX)
458 *timeout = _DBUS_INT_MAX;
460 *timeout = sec_remaining * 1000 + msec_remaining;
463 if (*timeout > interval)
465 /* This indicates that the system clock probably moved backward */
466 _dbus_verbose ("System clock set backward! Resetting timeout.\n");
468 tcb->last_tv_sec = tv_sec;
469 tcb->last_tv_usec = tv_usec;
475 _dbus_verbose (" timeout expires in %d milliseconds\n", *timeout);
478 return *timeout == 0;
482 _dbus_loop_dispatch (DBusLoop *loop)
486 _dbus_verbose (" %d connections to dispatch\n", _dbus_list_get_length (&loop->need_dispatch));
489 if (loop->need_dispatch == NULL)
493 while (loop->need_dispatch != NULL)
495 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
499 DBusDispatchStatus status;
501 status = dbus_connection_dispatch (connection);
503 if (status == DBUS_DISPATCH_COMPLETE)
505 dbus_connection_unref (connection);
510 if (status == DBUS_DISPATCH_NEED_MEMORY)
511 _dbus_wait_for_memory ();
520 _dbus_loop_queue_dispatch (DBusLoop *loop,
521 DBusConnection *connection)
523 if (_dbus_list_append (&loop->need_dispatch, connection))
525 dbus_connection_ref (connection);
532 /* Returns TRUE if we invoked any timeouts or have ready file
533 * descriptors, which is just used in test code as a debug hack
537 _dbus_loop_iterate (DBusLoop *loop,
540 #define N_STACK_DESCRIPTORS 64
542 DBusSocketSet *socket_set = NULL;
543 DBusSocketEvent ready_fds[N_STACK_DESCRIPTORS];
549 dbus_bool_t oom_watch_pending;
551 DBusHashIter hash_iter;
555 oom_watch_pending = FALSE;
556 orig_depth = loop->depth;
559 _dbus_verbose ("Iteration block=%d depth=%d timeout_count=%d watch_count=%d\n",
560 block, loop->depth, loop->timeout_count, loop->watch_count);
563 if (_dbus_hash_table_get_n_entries (loop->watches) == 0 &&
564 loop->timeouts == NULL)
567 socket_set = _dbus_socket_set_new (loop->watch_count);
569 while (socket_set == NULL)
571 _dbus_wait_for_memory ();
572 socket_set = _dbus_socket_set_new (loop->watch_count);
575 /* fill our array of fds and watches */
576 _dbus_hash_iter_init (loop->watches, &hash_iter);
578 while (_dbus_hash_iter_next (&hash_iter))
585 fd = _dbus_hash_iter_get_int_key (&hash_iter);
586 watches = _dbus_hash_iter_get_value (&hash_iter);
590 for (link = _dbus_list_get_first_link (watches);
592 link = _dbus_list_get_next_link (watches, link))
594 DBusWatch *watch = link->data;
596 if (_dbus_watch_get_oom_last_time (watch))
598 /* we skip this one this time, but reenable it next time,
599 * and have a timeout on this iteration
601 _dbus_watch_set_oom_last_time (watch, FALSE);
602 oom_watch_pending = TRUE;
604 retval = TRUE; /* return TRUE here to keep the loop going,
605 * since we don't know the watch is inactive
609 _dbus_verbose (" skipping watch on fd %d as it was out of memory last time\n",
613 else if (dbus_watch_get_enabled (watch))
615 flags |= dbus_watch_get_flags (watch);
622 _dbus_socket_set_add (socket_set, fd, flags, TRUE);
625 _dbus_verbose (" polling watch on fd %d %s\n",
626 fd, watch_flags_to_string (flags));
632 _dbus_verbose (" skipping disabled watch on fd %d %s\n",
633 fd, watch_flags_to_string (flags));
639 if (loop->timeout_count > 0)
641 unsigned long tv_sec;
642 unsigned long tv_usec;
644 _dbus_get_current_time (&tv_sec, &tv_usec);
646 link = _dbus_list_get_first_link (&loop->timeouts);
649 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
650 TimeoutCallback *tcb = link->data;
652 if (dbus_timeout_get_enabled (tcb->timeout))
656 check_timeout (tv_sec, tv_usec, tcb, &msecs_remaining);
659 timeout = msecs_remaining;
661 timeout = MIN (msecs_remaining, timeout);
664 _dbus_verbose (" timeout added, %d remaining, aggregate timeout %ld\n",
665 msecs_remaining, timeout);
668 _dbus_assert (timeout >= 0);
671 break; /* it's not going to get shorter... */
676 _dbus_verbose (" skipping disabled timeout\n");
684 /* Never block if we have stuff to dispatch */
685 if (!block || loop->need_dispatch != NULL)
689 _dbus_verbose (" timeout is 0 as we aren't blocking\n");
693 /* if a watch is OOM, don't wait longer than the OOM
694 * wait to re-enable it
696 if (oom_watch_pending)
697 timeout = MIN (timeout, _dbus_get_oom_wait ());
700 _dbus_verbose (" polling on %d descriptors timeout %ld\n", n_fds, timeout);
703 n_ready = _dbus_socket_set_poll (socket_set, ready_fds,
704 _DBUS_N_ELEMENTS (ready_fds), timeout);
706 initial_serial = loop->callback_list_serial;
708 if (loop->timeout_count > 0)
710 unsigned long tv_sec;
711 unsigned long tv_usec;
713 _dbus_get_current_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;
776 /* FIXME I think this "restart if we change the watches"
777 * approach could result in starving watches
778 * toward the end of the list.
780 if (initial_serial != loop->callback_list_serial)
783 if (loop->depth != orig_depth)
786 _dbus_assert (ready_fds[i].flags != 0);
788 if (_DBUS_UNLIKELY (ready_fds[i].flags & _DBUS_WATCH_NVAL))
790 cull_watches_for_invalid_fd (loop, ready_fds[i].fd);
794 condition = ready_fds[i].flags;
795 _dbus_assert ((condition & _DBUS_WATCH_NVAL) == 0);
797 /* condition may still be 0 if we got some
798 * weird POLLFOO thing like POLLWRBAND
803 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);
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)
839 if (loop->depth != orig_depth)
848 _dbus_verbose (" moving to next iteration\n");
852 _dbus_socket_set_free (socket_set);
854 if (_dbus_loop_dispatch (loop))
858 _dbus_verbose ("Returning %d\n", retval);
865 _dbus_loop_run (DBusLoop *loop)
869 _dbus_assert (loop->depth >= 0);
871 _dbus_loop_ref (loop);
873 our_exit_depth = loop->depth;
876 _dbus_verbose ("Running main loop, depth %d -> %d\n",
877 loop->depth - 1, loop->depth);
879 while (loop->depth != our_exit_depth)
880 _dbus_loop_iterate (loop, TRUE);
882 _dbus_loop_unref (loop);
886 _dbus_loop_quit (DBusLoop *loop)
888 _dbus_assert (loop->depth > 0);
892 _dbus_verbose ("Quit main loop, depth %d -> %d\n",
893 loop->depth + 1, loop->depth);
897 _dbus_get_oom_wait (void)
899 #ifdef DBUS_BUILD_TESTS
900 /* make tests go fast */
908 _dbus_wait_for_memory (void)
910 _dbus_verbose ("Waiting for more memory\n");
911 _dbus_sleep_milliseconds (_dbus_get_oom_wait ());
914 #endif /* !DOXYGEN_SHOULD_SKIP_THIS */