1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-mainloop.c Main loop utility
4 * Copyright (C) 2003, 2004 Red Hat, Inc.
6 * Licensed under the Academic Free License version 2.1
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "dbus-mainloop.h"
27 #ifndef DOXYGEN_SHOULD_SKIP_THIS
29 #include <dbus/dbus-hash.h>
30 #include <dbus/dbus-list.h>
31 #include <dbus/dbus-sysdeps.h>
32 #include <dbus/dbus-watch.h>
34 #define MAINLOOP_SPEW 0
37 #ifdef DBUS_ENABLE_VERBOSE_MODE
39 watch_flags_to_string (int flags)
41 const char *watch_type;
43 if ((flags & DBUS_WATCH_READABLE) &&
44 (flags & DBUS_WATCH_WRITABLE))
45 watch_type = "readwrite";
46 else if (flags & DBUS_WATCH_READABLE)
48 else if (flags & DBUS_WATCH_WRITABLE)
51 watch_type = "not read or write";
54 #endif /* DBUS_ENABLE_VERBOSE_MODE */
55 #endif /* MAINLOOP_SPEW */
60 /** fd => dbus_malloc'd DBusList ** of references to DBusWatch */
61 DBusHashTable *watches;
63 int callback_list_serial;
66 int depth; /**< number of recursive runs */
67 DBusList *need_dispatch;
71 watch_flags_to_poll_events (unsigned int flags)
75 if (flags & DBUS_WATCH_READABLE)
76 events |= _DBUS_POLLIN;
77 if (flags & DBUS_WATCH_WRITABLE)
78 events |= _DBUS_POLLOUT;
84 watch_flags_from_poll_revents (short revents)
86 unsigned int condition = 0;
88 if (revents & _DBUS_POLLIN)
89 condition |= DBUS_WATCH_READABLE;
90 if (revents & _DBUS_POLLOUT)
91 condition |= DBUS_WATCH_WRITABLE;
92 if (revents & _DBUS_POLLHUP)
93 condition |= DBUS_WATCH_HANGUP;
94 if (revents & _DBUS_POLLERR)
95 condition |= DBUS_WATCH_ERROR;
102 DBusTimeout *timeout;
103 unsigned long last_tv_sec;
104 unsigned long last_tv_usec;
107 #define TIMEOUT_CALLBACK(callback) ((TimeoutCallback*)callback)
109 static TimeoutCallback*
110 timeout_callback_new (DBusTimeout *timeout)
114 cb = dbus_new (TimeoutCallback, 1);
118 cb->timeout = timeout;
119 _dbus_get_current_time (&cb->last_tv_sec,
125 timeout_callback_free (TimeoutCallback *cb)
131 free_watch_table_entry (void *data)
133 DBusList **watches = data;
136 /* DBusHashTable sometimes calls free_function(NULL) even if you never
137 * have NULL as a value */
141 for (watch = _dbus_list_pop_first (watches);
143 watch = _dbus_list_pop_first (watches))
145 _dbus_watch_unref (watch);
148 _dbus_assert (*watches == NULL);
153 _dbus_loop_new (void)
157 loop = dbus_new0 (DBusLoop, 1);
161 loop->watches = _dbus_hash_table_new (DBUS_HASH_INT, NULL,
162 free_watch_table_entry);
164 if (loop->watches == NULL)
176 _dbus_loop_ref (DBusLoop *loop)
178 _dbus_assert (loop != NULL);
179 _dbus_assert (loop->refcount > 0);
187 _dbus_loop_unref (DBusLoop *loop)
189 _dbus_assert (loop != NULL);
190 _dbus_assert (loop->refcount > 0);
193 if (loop->refcount == 0)
195 while (loop->need_dispatch)
197 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
199 dbus_connection_unref (connection);
202 _dbus_hash_table_unref (loop->watches);
208 ensure_watch_table_entry (DBusLoop *loop,
213 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
217 watches = dbus_new0 (DBusList *, 1);
222 if (!_dbus_hash_table_insert_int (loop->watches, fd, watches))
233 cull_watches_for_invalid_fd (DBusLoop *loop,
239 _dbus_warn ("invalid request, socket fd %d not open\n", fd);
240 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
244 for (link = _dbus_list_get_first_link (watches);
246 link = _dbus_list_get_next_link (watches, link))
247 _dbus_watch_invalidate (link->data);
250 _dbus_hash_table_remove_int (loop->watches, fd);
254 gc_watch_table_entry (DBusLoop *loop,
258 /* If watches is already NULL we have nothing to do */
262 /* We can't GC hash table entries if they're non-empty lists */
263 if (*watches != NULL)
266 _dbus_hash_table_remove_int (loop->watches, 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 loop->callback_list_serial += 1;
287 loop->watch_count += 1;
291 _dbus_watch_unref (watch);
292 gc_watch_table_entry (loop, watches, fd);
301 _dbus_loop_remove_watch (DBusLoop *loop,
308 /* This relies on people removing watches before they invalidate them,
309 * which has been safe since fd.o #33336 was fixed. Assert about it
310 * so we don't regress. */
311 fd = dbus_watch_get_socket (watch);
312 _dbus_assert (fd != -1);
314 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
318 link = _dbus_list_get_first_link (watches);
321 DBusList *next = _dbus_list_get_next_link (watches, link);
322 DBusWatch *this = link->data;
326 _dbus_list_remove_link (watches, link);
327 loop->callback_list_serial += 1;
328 loop->watch_count -= 1;
329 _dbus_watch_unref (this);
331 /* if that was the last watch for that fd, drop the hash table
333 gc_watch_table_entry (loop, watches, fd);
342 _dbus_warn ("could not find watch %p to remove\n", watch);
346 _dbus_loop_add_timeout (DBusLoop *loop,
347 DBusTimeout *timeout)
349 TimeoutCallback *tcb;
351 tcb = timeout_callback_new (timeout);
355 if (_dbus_list_append (&loop->timeouts, tcb))
357 loop->callback_list_serial += 1;
358 loop->timeout_count += 1;
362 timeout_callback_free (tcb);
370 _dbus_loop_remove_timeout (DBusLoop *loop,
371 DBusTimeout *timeout)
375 link = _dbus_list_get_first_link (&loop->timeouts);
378 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
379 TimeoutCallback *this = link->data;
381 if (this->timeout == timeout)
383 _dbus_list_remove_link (&loop->timeouts, link);
384 loop->callback_list_serial += 1;
385 loop->timeout_count -= 1;
386 timeout_callback_free (this);
394 _dbus_warn ("could not find timeout %p to remove\n", timeout);
397 /* Convolutions from GLib, there really must be a better way
401 check_timeout (unsigned long tv_sec,
402 unsigned long tv_usec,
403 TimeoutCallback *tcb,
408 unsigned long expiration_tv_sec;
409 unsigned long expiration_tv_usec;
410 long interval_seconds;
411 long interval_milliseconds;
414 /* I'm pretty sure this function could suck (a lot) less */
416 interval = dbus_timeout_get_interval (tcb->timeout);
418 interval_seconds = interval / 1000L;
419 interval_milliseconds = interval % 1000L;
421 expiration_tv_sec = tcb->last_tv_sec + interval_seconds;
422 expiration_tv_usec = tcb->last_tv_usec + interval_milliseconds * 1000;
423 if (expiration_tv_usec >= 1000000)
425 expiration_tv_usec -= 1000000;
426 expiration_tv_sec += 1;
429 sec_remaining = expiration_tv_sec - tv_sec;
430 /* need to force this to be signed, as it is intended to sometimes
431 * produce a negative result
433 msec_remaining = ((long) expiration_tv_usec - (long) tv_usec) / 1000L;
436 _dbus_verbose ("Interval is %ld seconds %ld msecs\n",
438 interval_milliseconds);
439 _dbus_verbose ("Now is %lu seconds %lu usecs\n",
441 _dbus_verbose ("Last is %lu seconds %lu usecs\n",
442 tcb->last_tv_sec, tcb->last_tv_usec);
443 _dbus_verbose ("Exp is %lu seconds %lu usecs\n",
444 expiration_tv_sec, expiration_tv_usec);
445 _dbus_verbose ("Pre-correction, sec_remaining %ld msec_remaining %ld\n",
446 sec_remaining, msec_remaining);
449 /* We do the following in a rather convoluted fashion to deal with
450 * the fact that we don't have an integral type big enough to hold
451 * the difference of two timevals in milliseconds.
453 if (sec_remaining < 0 || (sec_remaining == 0 && msec_remaining < 0))
459 if (msec_remaining < 0)
461 msec_remaining += 1000;
465 if (sec_remaining > (_DBUS_INT_MAX / 1000) ||
466 msec_remaining > _DBUS_INT_MAX)
467 *timeout = _DBUS_INT_MAX;
469 *timeout = sec_remaining * 1000 + msec_remaining;
472 if (*timeout > interval)
474 /* This indicates that the system clock probably moved backward */
475 _dbus_verbose ("System clock set backward! Resetting timeout.\n");
477 tcb->last_tv_sec = tv_sec;
478 tcb->last_tv_usec = tv_usec;
484 _dbus_verbose (" timeout expires in %d milliseconds\n", *timeout);
487 return *timeout == 0;
491 _dbus_loop_dispatch (DBusLoop *loop)
495 _dbus_verbose (" %d connections to dispatch\n", _dbus_list_get_length (&loop->need_dispatch));
498 if (loop->need_dispatch == NULL)
502 while (loop->need_dispatch != NULL)
504 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
508 DBusDispatchStatus status;
510 status = dbus_connection_dispatch (connection);
512 if (status == DBUS_DISPATCH_COMPLETE)
514 dbus_connection_unref (connection);
519 if (status == DBUS_DISPATCH_NEED_MEMORY)
520 _dbus_wait_for_memory ();
529 _dbus_loop_queue_dispatch (DBusLoop *loop,
530 DBusConnection *connection)
532 if (_dbus_list_append (&loop->need_dispatch, connection))
534 dbus_connection_ref (connection);
541 /* Returns TRUE if we invoked any timeouts or have ready file
542 * descriptors, which is just used in test code as a debug hack
546 _dbus_loop_iterate (DBusLoop *loop,
549 #define N_STACK_DESCRIPTORS 64
552 DBusPollFD stack_fds[N_STACK_DESCRIPTORS];
559 dbus_bool_t oom_watch_pending;
561 DBusHashIter hash_iter;
567 oom_watch_pending = FALSE;
568 orig_depth = loop->depth;
571 _dbus_verbose ("Iteration block=%d depth=%d timeout_count=%d watch_count=%d\n",
572 block, loop->depth, loop->timeout_count, loop->watch_count);
575 if (_dbus_hash_table_get_n_entries (loop->watches) == 0 &&
576 loop->timeouts == NULL)
579 if (loop->watch_count > N_STACK_DESCRIPTORS)
581 fds = dbus_new0 (DBusPollFD, loop->watch_count);
585 _dbus_wait_for_memory ();
586 fds = dbus_new0 (DBusPollFD, loop->watch_count);
594 /* fill our array of fds and watches */
596 _dbus_hash_iter_init (loop->watches, &hash_iter);
598 while (_dbus_hash_iter_next (&hash_iter))
604 fd = _dbus_hash_iter_get_int_key (&hash_iter);
605 watches = _dbus_hash_iter_get_value (&hash_iter);
608 for (link = _dbus_list_get_first_link (watches);
610 link = _dbus_list_get_next_link (watches, link))
612 DBusWatch *watch = link->data;
614 if (_dbus_watch_get_oom_last_time (watch))
616 /* we skip this one this time, but reenable it next time,
617 * and have a timeout on this iteration
619 _dbus_watch_set_oom_last_time (watch, FALSE);
620 oom_watch_pending = TRUE;
622 retval = TRUE; /* return TRUE here to keep the loop going,
623 * since we don't know the watch is inactive
627 _dbus_verbose (" skipping watch on fd %d as it was out of memory last time\n",
631 else if (dbus_watch_get_enabled (watch))
633 flags |= dbus_watch_get_flags (watch);
640 fds[n_fds].revents = 0;
641 fds[n_fds].events = watch_flags_to_poll_events (flags);
644 _dbus_verbose (" polling watch on fd %d %s\n",
645 loop->fds[loop->n_fds].fd, watch_flags_to_string (flags));
653 _dbus_verbose (" skipping disabled watch on fd %d %s\n",
655 watch_flags_to_string (dbus_watch_get_flags (watch)));
661 if (loop->timeout_count > 0)
663 unsigned long tv_sec;
664 unsigned long tv_usec;
666 _dbus_get_current_time (&tv_sec, &tv_usec);
668 link = _dbus_list_get_first_link (&loop->timeouts);
671 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
672 TimeoutCallback *tcb = link->data;
674 if (dbus_timeout_get_enabled (tcb->timeout))
678 check_timeout (tv_sec, tv_usec, tcb, &msecs_remaining);
681 timeout = msecs_remaining;
683 timeout = MIN (msecs_remaining, timeout);
686 _dbus_verbose (" timeout added, %d remaining, aggregate timeout %ld\n",
687 msecs_remaining, timeout);
690 _dbus_assert (timeout >= 0);
693 break; /* it's not going to get shorter... */
698 _dbus_verbose (" skipping disabled timeout\n");
706 /* Never block if we have stuff to dispatch */
707 if (!block || loop->need_dispatch != NULL)
711 _dbus_verbose (" timeout is 0 as we aren't blocking\n");
715 /* if a watch is OOM, don't wait longer than the OOM
716 * wait to re-enable it
718 if (oom_watch_pending)
719 timeout = MIN (timeout, _dbus_get_oom_wait ());
722 _dbus_verbose (" polling on %d descriptors timeout %ld\n", n_fds, timeout);
725 n_ready = _dbus_poll (fds, n_fds, timeout);
727 initial_serial = loop->callback_list_serial;
729 if (loop->timeout_count > 0)
731 unsigned long tv_sec;
732 unsigned long tv_usec;
734 _dbus_get_current_time (&tv_sec, &tv_usec);
736 /* It'd be nice to avoid this O(n) thingy here */
737 link = _dbus_list_get_first_link (&loop->timeouts);
740 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
741 TimeoutCallback *tcb = link->data;
743 if (initial_serial != loop->callback_list_serial)
746 if (loop->depth != orig_depth)
749 if (dbus_timeout_get_enabled (tcb->timeout))
753 if (check_timeout (tv_sec, tv_usec,
754 tcb, &msecs_remaining))
756 /* Save last callback time and fire this timeout */
757 tcb->last_tv_sec = tv_sec;
758 tcb->last_tv_usec = tv_usec;
761 _dbus_verbose (" invoking timeout\n");
764 /* can theoretically return FALSE on OOM, but we just
765 * let it fire again later - in practice that's what
766 * every wrapper callback in dbus-daemon used to do */
767 dbus_timeout_handle (tcb->timeout);
774 _dbus_verbose (" timeout has not expired\n");
781 _dbus_verbose (" skipping invocation of disabled timeout\n");
791 for (i = 0; i < n_fds; i++)
795 unsigned int condition;
797 /* FIXME I think this "restart if we change the watches"
798 * approach could result in starving watches
799 * toward the end of the list.
801 if (initial_serial != loop->callback_list_serial)
804 if (loop->depth != orig_depth)
807 if (fds[i].revents == 0)
810 if (_DBUS_UNLIKELY (fds[i].revents & _DBUS_POLLNVAL))
812 cull_watches_for_invalid_fd (loop, fds[i].fd);
816 condition = watch_flags_from_poll_revents (fds[i].revents);
818 /* condition may still be 0 if we got some
819 * weird POLLFOO thing like POLLWRBAND
824 watches = _dbus_hash_table_lookup_int (loop->watches, fds[i].fd);
829 for (link = _dbus_list_get_first_link (watches);
833 DBusWatch *watch = link->data;
835 next = _dbus_list_get_next_link (watches, link);
837 if (dbus_watch_get_enabled (watch))
841 oom = !dbus_watch_handle (watch, condition);
845 _dbus_watch_set_oom_last_time (watch, TRUE);
849 _dbus_verbose (" Invoked watch, oom = %d\n", oom);
853 /* We re-check this every time, in case the callback
854 * added/removed watches, which might make our position in
855 * the linked list invalid. See the FIXME above. */
856 if (initial_serial != loop->callback_list_serial)
859 if (loop->depth != orig_depth)
868 _dbus_verbose (" moving to next iteration\n");
871 if (fds && fds != stack_fds)
874 if (_dbus_loop_dispatch (loop))
878 _dbus_verbose ("Returning %d\n", retval);
885 _dbus_loop_run (DBusLoop *loop)
889 _dbus_assert (loop->depth >= 0);
891 _dbus_loop_ref (loop);
893 our_exit_depth = loop->depth;
896 _dbus_verbose ("Running main loop, depth %d -> %d\n",
897 loop->depth - 1, loop->depth);
899 while (loop->depth != our_exit_depth)
900 _dbus_loop_iterate (loop, TRUE);
902 _dbus_loop_unref (loop);
906 _dbus_loop_quit (DBusLoop *loop)
908 _dbus_assert (loop->depth > 0);
912 _dbus_verbose ("Quit main loop, depth %d -> %d\n",
913 loop->depth + 1, loop->depth);
917 _dbus_get_oom_wait (void)
919 #ifdef DBUS_BUILD_TESTS
920 /* make tests go fast */
928 _dbus_wait_for_memory (void)
930 _dbus_verbose ("Waiting for more memory\n");
931 _dbus_sleep_milliseconds (_dbus_get_oom_wait ());
934 #endif /* !DOXYGEN_SHOULD_SKIP_THIS */