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-list.h>
30 #include <dbus/dbus-sysdeps.h>
31 #include <dbus/dbus-watch.h>
33 #define MAINLOOP_SPEW 0
36 #ifdef DBUS_ENABLE_VERBOSE_MODE
38 watch_flags_to_string (int flags)
40 const char *watch_type;
42 if ((flags & DBUS_WATCH_READABLE) &&
43 (flags & DBUS_WATCH_WRITABLE))
44 watch_type = "readwrite";
45 else if (flags & DBUS_WATCH_READABLE)
47 else if (flags & DBUS_WATCH_WRITABLE)
50 watch_type = "not read or write";
53 #endif /* DBUS_ENABLE_VERBOSE_MODE */
54 #endif /* MAINLOOP_SPEW */
61 int callback_list_serial;
64 int depth; /**< number of recursive runs */
65 DBusList *need_dispatch;
69 watch_flags_to_poll_events (unsigned int flags)
73 if (flags & DBUS_WATCH_READABLE)
74 events |= _DBUS_POLLIN;
75 if (flags & DBUS_WATCH_WRITABLE)
76 events |= _DBUS_POLLOUT;
82 watch_flags_from_poll_revents (short revents)
84 unsigned int condition = 0;
86 if (revents & _DBUS_POLLIN)
87 condition |= DBUS_WATCH_READABLE;
88 if (revents & _DBUS_POLLOUT)
89 condition |= DBUS_WATCH_WRITABLE;
90 if (revents & _DBUS_POLLHUP)
91 condition |= DBUS_WATCH_HANGUP;
92 if (revents & _DBUS_POLLERR)
93 condition |= DBUS_WATCH_ERROR;
119 DBusTimeout *timeout;
120 unsigned long last_tv_sec;
121 unsigned long last_tv_usec;
124 #define WATCH_CALLBACK(callback) ((WatchCallback*)callback)
125 #define TIMEOUT_CALLBACK(callback) ((TimeoutCallback*)callback)
127 static WatchCallback*
128 watch_callback_new (DBusWatch *watch)
132 cb = dbus_new (WatchCallback, 1);
137 cb->callback.refcount = 1;
138 cb->callback.type = CALLBACK_WATCH;
143 static TimeoutCallback*
144 timeout_callback_new (DBusTimeout *timeout)
148 cb = dbus_new (TimeoutCallback, 1);
152 cb->timeout = timeout;
153 _dbus_get_current_time (&cb->last_tv_sec,
155 cb->callback.refcount = 1;
156 cb->callback.type = CALLBACK_TIMEOUT;
162 callback_ref (Callback *cb)
164 _dbus_assert (cb->refcount > 0);
172 callback_unref (Callback *cb)
174 _dbus_assert (cb->refcount > 0);
178 if (cb->refcount == 0)
185 add_callback (DBusLoop *loop,
190 if (!_dbus_list_append (list, cb))
193 loop->callback_list_serial += 1;
198 loop->watch_count += 1;
200 case CALLBACK_TIMEOUT:
201 loop->timeout_count += 1;
209 remove_callback (DBusLoop *loop,
213 Callback *cb = link->data;
218 loop->watch_count -= 1;
220 case CALLBACK_TIMEOUT:
221 loop->timeout_count -= 1;
226 _dbus_list_remove_link (list, link);
227 loop->callback_list_serial += 1;
231 _dbus_loop_new (void)
235 loop = dbus_new0 (DBusLoop, 1);
245 _dbus_loop_ref (DBusLoop *loop)
247 _dbus_assert (loop != NULL);
248 _dbus_assert (loop->refcount > 0);
256 _dbus_loop_unref (DBusLoop *loop)
258 _dbus_assert (loop != NULL);
259 _dbus_assert (loop->refcount > 0);
262 if (loop->refcount == 0)
264 while (loop->need_dispatch)
266 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
268 dbus_connection_unref (connection);
276 _dbus_loop_add_watch (DBusLoop *loop,
281 wcb = watch_callback_new (watch);
285 if (!add_callback (loop, &loop->watches, (Callback*) wcb))
287 callback_unref ((Callback*) wcb);
295 _dbus_loop_remove_watch (DBusLoop *loop,
300 /* fd.o #33336: we want people to remove their watches before invalidating
302 _dbus_assert (dbus_watch_get_socket (watch) != -1);
304 link = _dbus_list_get_first_link (&loop->watches);
307 DBusList *next = _dbus_list_get_next_link (&loop->watches, link);
308 WatchCallback *this = link->data;
310 _dbus_assert (this->callback.type == CALLBACK_WATCH);
312 if (this->watch == watch)
314 remove_callback (loop, &loop->watches, link);
322 _dbus_warn ("could not find watch %p to remove\n", watch);
326 _dbus_loop_add_timeout (DBusLoop *loop,
327 DBusTimeout *timeout)
329 TimeoutCallback *tcb;
331 tcb = timeout_callback_new (timeout);
335 if (!add_callback (loop, &loop->timeouts, (Callback*) tcb))
337 callback_unref ((Callback*) tcb);
345 _dbus_loop_remove_timeout (DBusLoop *loop,
346 DBusTimeout *timeout)
350 link = _dbus_list_get_first_link (&loop->timeouts);
353 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
354 TimeoutCallback *this = link->data;
356 _dbus_assert (this->callback.type == CALLBACK_TIMEOUT);
358 if (this->timeout == timeout)
360 remove_callback (loop, &loop->timeouts, link);
368 _dbus_warn ("could not find timeout %p to remove\n", timeout);
371 /* Convolutions from GLib, there really must be a better way
375 check_timeout (unsigned long tv_sec,
376 unsigned long tv_usec,
377 TimeoutCallback *tcb,
382 unsigned long expiration_tv_sec;
383 unsigned long expiration_tv_usec;
384 long interval_seconds;
385 long interval_milliseconds;
388 /* I'm pretty sure this function could suck (a lot) less */
390 interval = dbus_timeout_get_interval (tcb->timeout);
392 interval_seconds = interval / 1000L;
393 interval_milliseconds = interval % 1000L;
395 expiration_tv_sec = tcb->last_tv_sec + interval_seconds;
396 expiration_tv_usec = tcb->last_tv_usec + interval_milliseconds * 1000;
397 if (expiration_tv_usec >= 1000000)
399 expiration_tv_usec -= 1000000;
400 expiration_tv_sec += 1;
403 sec_remaining = expiration_tv_sec - tv_sec;
404 /* need to force this to be signed, as it is intended to sometimes
405 * produce a negative result
407 msec_remaining = ((long) expiration_tv_usec - (long) tv_usec) / 1000L;
410 _dbus_verbose ("Interval is %ld seconds %ld msecs\n",
412 interval_milliseconds);
413 _dbus_verbose ("Now is %lu seconds %lu usecs\n",
415 _dbus_verbose ("Last is %lu seconds %lu usecs\n",
416 tcb->last_tv_sec, tcb->last_tv_usec);
417 _dbus_verbose ("Exp is %lu seconds %lu usecs\n",
418 expiration_tv_sec, expiration_tv_usec);
419 _dbus_verbose ("Pre-correction, sec_remaining %ld msec_remaining %ld\n",
420 sec_remaining, msec_remaining);
423 /* We do the following in a rather convoluted fashion to deal with
424 * the fact that we don't have an integral type big enough to hold
425 * the difference of two timevals in milliseconds.
427 if (sec_remaining < 0 || (sec_remaining == 0 && msec_remaining < 0))
433 if (msec_remaining < 0)
435 msec_remaining += 1000;
439 if (sec_remaining > (_DBUS_INT_MAX / 1000) ||
440 msec_remaining > _DBUS_INT_MAX)
441 *timeout = _DBUS_INT_MAX;
443 *timeout = sec_remaining * 1000 + msec_remaining;
446 if (*timeout > interval)
448 /* This indicates that the system clock probably moved backward */
449 _dbus_verbose ("System clock set backward! Resetting timeout.\n");
451 tcb->last_tv_sec = tv_sec;
452 tcb->last_tv_usec = tv_usec;
458 _dbus_verbose (" timeout expires in %d milliseconds\n", *timeout);
461 return *timeout == 0;
465 _dbus_loop_dispatch (DBusLoop *loop)
469 _dbus_verbose (" %d connections to dispatch\n", _dbus_list_get_length (&loop->need_dispatch));
472 if (loop->need_dispatch == NULL)
476 while (loop->need_dispatch != NULL)
478 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
482 DBusDispatchStatus status;
484 status = dbus_connection_dispatch (connection);
486 if (status == DBUS_DISPATCH_COMPLETE)
488 dbus_connection_unref (connection);
493 if (status == DBUS_DISPATCH_NEED_MEMORY)
494 _dbus_wait_for_memory ();
503 _dbus_loop_queue_dispatch (DBusLoop *loop,
504 DBusConnection *connection)
506 if (_dbus_list_append (&loop->need_dispatch, connection))
508 dbus_connection_ref (connection);
515 /* Returns TRUE if we invoked any timeouts or have ready file
516 * descriptors, which is just used in test code as a debug hack
520 _dbus_loop_iterate (DBusLoop *loop,
523 #define N_STACK_DESCRIPTORS 64
526 DBusPollFD stack_fds[N_STACK_DESCRIPTORS];
528 WatchCallback **watches_for_fds;
529 WatchCallback *stack_watches_for_fds[N_STACK_DESCRIPTORS];
535 dbus_bool_t oom_watch_pending;
541 watches_for_fds = NULL;
543 oom_watch_pending = FALSE;
544 orig_depth = loop->depth;
547 _dbus_verbose ("Iteration block=%d depth=%d timeout_count=%d watch_count=%d\n",
548 block, loop->depth, loop->timeout_count, loop->watch_count);
551 if (loop->watches == NULL && loop->timeouts == NULL)
554 if (loop->watch_count > N_STACK_DESCRIPTORS)
556 fds = dbus_new0 (DBusPollFD, loop->watch_count);
560 _dbus_wait_for_memory ();
561 fds = dbus_new0 (DBusPollFD, loop->watch_count);
564 watches_for_fds = dbus_new (WatchCallback*, loop->watch_count);
565 while (watches_for_fds == NULL)
567 _dbus_wait_for_memory ();
568 watches_for_fds = dbus_new (WatchCallback*, loop->watch_count);
574 watches_for_fds = stack_watches_for_fds;
577 /* fill our array of fds and watches */
579 link = _dbus_list_get_first_link (&loop->watches);
582 DBusList *next = _dbus_list_get_next_link (&loop->watches, link);
583 Callback *cb = link->data;
588 _dbus_assert (cb->type == CALLBACK_WATCH);
590 wcb = WATCH_CALLBACK (cb);
591 fd = dbus_watch_get_socket (wcb->watch);
593 if (_dbus_watch_get_oom_last_time (wcb->watch))
595 /* we skip this one this time, but reenable it next time,
596 * and have a timeout on this iteration
598 _dbus_watch_set_oom_last_time (wcb->watch, FALSE);
599 oom_watch_pending = TRUE;
601 retval = TRUE; /* return TRUE here to keep the loop going,
602 * since we don't know the watch is inactive
606 _dbus_verbose (" skipping watch on fd %d as it was out of memory last time\n",
610 else if (_DBUS_UNLIKELY (fd == -1))
612 _dbus_warn ("watch %p was invalidated but not removed; "
613 "removing it now\n", wcb->watch);
614 _dbus_loop_remove_watch (loop, wcb->watch);
616 else if (dbus_watch_get_enabled (wcb->watch))
618 watches_for_fds[n_fds] = wcb;
622 flags = dbus_watch_get_flags (wcb->watch);
625 fds[n_fds].revents = 0;
626 fds[n_fds].events = watch_flags_to_poll_events (flags);
629 _dbus_verbose (" polling watch on fd %d %s\n",
630 loop->fds[loop->n_fds].fd, watch_flags_to_string (flags));
638 _dbus_verbose (" skipping disabled watch on fd %d %s\n",
640 watch_flags_to_string (dbus_watch_get_flags (wcb->watch)));
648 if (loop->timeout_count > 0)
650 unsigned long tv_sec;
651 unsigned long tv_usec;
653 _dbus_get_current_time (&tv_sec, &tv_usec);
655 link = _dbus_list_get_first_link (&loop->timeouts);
658 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
659 Callback *cb = link->data;
661 _dbus_assert (cb->type == CALLBACK_TIMEOUT);
663 if (dbus_timeout_get_enabled (TIMEOUT_CALLBACK (cb)->timeout))
665 TimeoutCallback *tcb = TIMEOUT_CALLBACK (cb);
668 check_timeout (tv_sec, tv_usec, tcb, &msecs_remaining);
671 timeout = msecs_remaining;
673 timeout = MIN (msecs_remaining, timeout);
676 _dbus_verbose (" timeout added, %d remaining, aggregate timeout %ld\n",
677 msecs_remaining, timeout);
680 _dbus_assert (timeout >= 0);
683 break; /* it's not going to get shorter... */
688 _dbus_verbose (" skipping disabled timeout\n");
696 /* Never block if we have stuff to dispatch */
697 if (!block || loop->need_dispatch != NULL)
701 _dbus_verbose (" timeout is 0 as we aren't blocking\n");
705 /* if a watch is OOM, don't wait longer than the OOM
706 * wait to re-enable it
708 if (oom_watch_pending)
709 timeout = MIN (timeout, _dbus_get_oom_wait ());
712 _dbus_verbose (" polling on %d descriptors timeout %ld\n", n_fds, timeout);
715 n_ready = _dbus_poll (fds, n_fds, timeout);
717 initial_serial = loop->callback_list_serial;
719 if (loop->timeout_count > 0)
721 unsigned long tv_sec;
722 unsigned long tv_usec;
724 _dbus_get_current_time (&tv_sec, &tv_usec);
726 /* It'd be nice to avoid this O(n) thingy here */
727 link = _dbus_list_get_first_link (&loop->timeouts);
730 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
731 Callback *cb = link->data;
733 if (initial_serial != loop->callback_list_serial)
736 if (loop->depth != orig_depth)
739 _dbus_assert (cb->type == CALLBACK_TIMEOUT);
741 if (dbus_timeout_get_enabled (TIMEOUT_CALLBACK (cb)->timeout))
743 TimeoutCallback *tcb = TIMEOUT_CALLBACK (cb);
746 if (check_timeout (tv_sec, tv_usec,
747 tcb, &msecs_remaining))
749 /* Save last callback time and fire this timeout */
750 tcb->last_tv_sec = tv_sec;
751 tcb->last_tv_usec = tv_usec;
754 _dbus_verbose (" invoking timeout\n");
757 /* can theoretically return FALSE on OOM, but we just
758 * let it fire again later - in practice that's what
759 * every wrapper callback in dbus-daemon used to do */
760 dbus_timeout_handle (tcb->timeout);
767 _dbus_verbose (" timeout has not expired\n");
774 _dbus_verbose (" skipping invocation of disabled timeout\n");
787 /* FIXME I think this "restart if we change the watches"
788 * approach could result in starving watches
789 * toward the end of the list.
791 if (initial_serial != loop->callback_list_serial)
794 if (loop->depth != orig_depth)
797 if (fds[i].revents != 0)
800 unsigned int condition;
802 wcb = watches_for_fds[i];
803 condition = watch_flags_from_poll_revents (fds[i].revents);
805 /* condition may still be 0 if we got some
806 * weird POLLFOO thing like POLLWRBAND
809 if (condition != 0 &&
810 dbus_watch_get_enabled (wcb->watch))
814 oom = !dbus_watch_handle (wcb->watch, condition);
818 _dbus_watch_set_oom_last_time (wcb->watch, TRUE);
822 _dbus_verbose (" Invoked watch, oom = %d\n", oom);
828 if (_DBUS_UNLIKELY (fds[i].revents & _DBUS_POLLNVAL))
830 DBusWatch *watch = _dbus_watch_ref (wcb->watch);
832 _dbus_warn ("invalid request, socket fd %d not open\n",
834 _dbus_loop_remove_watch (loop, watch);
835 _dbus_watch_invalidate (watch);
836 _dbus_watch_unref (watch);
846 _dbus_verbose (" moving to next iteration\n");
849 if (fds && fds != stack_fds)
856 callback_unref (&watches_for_fds[i]->callback);
860 if (watches_for_fds != stack_watches_for_fds)
861 dbus_free (watches_for_fds);
864 if (_dbus_loop_dispatch (loop))
868 _dbus_verbose ("Returning %d\n", retval);
875 _dbus_loop_run (DBusLoop *loop)
879 _dbus_assert (loop->depth >= 0);
881 _dbus_loop_ref (loop);
883 our_exit_depth = loop->depth;
886 _dbus_verbose ("Running main loop, depth %d -> %d\n",
887 loop->depth - 1, loop->depth);
889 while (loop->depth != our_exit_depth)
890 _dbus_loop_iterate (loop, TRUE);
892 _dbus_loop_unref (loop);
896 _dbus_loop_quit (DBusLoop *loop)
898 _dbus_assert (loop->depth > 0);
902 _dbus_verbose ("Quit main loop, depth %d -> %d\n",
903 loop->depth + 1, loop->depth);
907 _dbus_get_oom_wait (void)
909 #ifdef DBUS_BUILD_TESTS
910 /* make tests go fast */
918 _dbus_wait_for_memory (void)
920 _dbus_verbose ("Waiting for more memory\n");
921 _dbus_sleep_milliseconds (_dbus_get_oom_wait ());
924 #endif /* !DOXYGEN_SHOULD_SKIP_THIS */