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 */
60 int callback_list_serial;
63 int depth; /**< number of recursive runs */
64 DBusList *need_dispatch;
82 DBusWatchFunction function;
85 DBusFreeFunction free_data_func;
86 /* last watch handle failed due to OOM */
87 unsigned int last_iteration_oom : 1;
94 unsigned long last_tv_sec;
95 unsigned long last_tv_usec;
98 #define WATCH_CALLBACK(callback) ((WatchCallback*)callback)
99 #define TIMEOUT_CALLBACK(callback) ((TimeoutCallback*)callback)
101 static WatchCallback*
102 watch_callback_new (DBusWatch *watch,
103 DBusWatchFunction function,
105 DBusFreeFunction free_data_func)
109 cb = dbus_new (WatchCallback, 1);
114 cb->function = function;
115 cb->last_iteration_oom = FALSE;
116 cb->callback.refcount = 1;
117 cb->callback.type = CALLBACK_WATCH;
119 cb->free_data_func = free_data_func;
124 static TimeoutCallback*
125 timeout_callback_new (DBusTimeout *timeout)
129 cb = dbus_new (TimeoutCallback, 1);
133 cb->timeout = timeout;
134 _dbus_get_current_time (&cb->last_tv_sec,
136 cb->callback.refcount = 1;
137 cb->callback.type = CALLBACK_TIMEOUT;
143 callback_ref (Callback *cb)
145 _dbus_assert (cb->refcount > 0);
153 callback_unref (Callback *cb)
155 _dbus_assert (cb->refcount > 0);
159 if (cb->refcount == 0)
161 if (cb->type == CALLBACK_WATCH && WATCH_CALLBACK (cb)->free_data_func)
162 (WATCH_CALLBACK (cb)->free_data_func) (WATCH_CALLBACK (cb)->data);
169 add_callback (DBusLoop *loop,
172 if (!_dbus_list_append (&loop->callbacks, cb))
175 loop->callback_list_serial += 1;
180 loop->watch_count += 1;
182 case CALLBACK_TIMEOUT:
183 loop->timeout_count += 1;
191 remove_callback (DBusLoop *loop,
194 Callback *cb = link->data;
199 loop->watch_count -= 1;
201 case CALLBACK_TIMEOUT:
202 loop->timeout_count -= 1;
207 _dbus_list_remove_link (&loop->callbacks, link);
208 loop->callback_list_serial += 1;
212 _dbus_loop_new (void)
216 loop = dbus_new0 (DBusLoop, 1);
226 _dbus_loop_ref (DBusLoop *loop)
228 _dbus_assert (loop != NULL);
229 _dbus_assert (loop->refcount > 0);
237 _dbus_loop_unref (DBusLoop *loop)
239 _dbus_assert (loop != NULL);
240 _dbus_assert (loop->refcount > 0);
243 if (loop->refcount == 0)
245 while (loop->need_dispatch)
247 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
249 dbus_connection_unref (connection);
257 _dbus_loop_add_watch (DBusLoop *loop,
259 DBusWatchFunction function,
261 DBusFreeFunction free_data_func)
265 wcb = watch_callback_new (watch, function, data, free_data_func);
269 if (!add_callback (loop, (Callback*) wcb))
271 wcb->free_data_func = NULL; /* don't want to have this side effect */
272 callback_unref ((Callback*) wcb);
280 _dbus_loop_remove_watch (DBusLoop *loop,
282 DBusWatchFunction function,
287 /* fd.o #33336: we want people to remove their watches before invalidating
289 _dbus_assert (dbus_watch_get_socket (watch) != -1);
291 link = _dbus_list_get_first_link (&loop->callbacks);
294 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
295 Callback *this = link->data;
297 if (this->type == CALLBACK_WATCH &&
298 WATCH_CALLBACK (this)->watch == watch &&
299 WATCH_CALLBACK (this)->data == data &&
300 WATCH_CALLBACK (this)->function == function)
302 remove_callback (loop, link);
310 _dbus_warn ("could not find watch %p function %p data %p to remove\n",
311 watch, (void *)function, data);
315 _dbus_loop_add_timeout (DBusLoop *loop,
316 DBusTimeout *timeout)
318 TimeoutCallback *tcb;
320 tcb = timeout_callback_new (timeout);
324 if (!add_callback (loop, (Callback*) tcb))
326 callback_unref ((Callback*) tcb);
334 _dbus_loop_remove_timeout (DBusLoop *loop,
335 DBusTimeout *timeout)
339 link = _dbus_list_get_first_link (&loop->callbacks);
342 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
343 Callback *this = link->data;
345 if (this->type == CALLBACK_TIMEOUT &&
346 TIMEOUT_CALLBACK (this)->timeout == timeout)
348 remove_callback (loop, link);
356 _dbus_warn ("could not find timeout %p to remove\n", timeout);
359 /* Convolutions from GLib, there really must be a better way
363 check_timeout (unsigned long tv_sec,
364 unsigned long tv_usec,
365 TimeoutCallback *tcb,
370 unsigned long expiration_tv_sec;
371 unsigned long expiration_tv_usec;
372 long interval_seconds;
373 long interval_milliseconds;
376 /* I'm pretty sure this function could suck (a lot) less */
378 interval = dbus_timeout_get_interval (tcb->timeout);
380 interval_seconds = interval / 1000L;
381 interval_milliseconds = interval % 1000L;
383 expiration_tv_sec = tcb->last_tv_sec + interval_seconds;
384 expiration_tv_usec = tcb->last_tv_usec + interval_milliseconds * 1000;
385 if (expiration_tv_usec >= 1000000)
387 expiration_tv_usec -= 1000000;
388 expiration_tv_sec += 1;
391 sec_remaining = expiration_tv_sec - tv_sec;
392 /* need to force this to be signed, as it is intended to sometimes
393 * produce a negative result
395 msec_remaining = ((long) expiration_tv_usec - (long) tv_usec) / 1000L;
398 _dbus_verbose ("Interval is %ld seconds %ld msecs\n",
400 interval_milliseconds);
401 _dbus_verbose ("Now is %lu seconds %lu usecs\n",
403 _dbus_verbose ("Last is %lu seconds %lu usecs\n",
404 tcb->last_tv_sec, tcb->last_tv_usec);
405 _dbus_verbose ("Exp is %lu seconds %lu usecs\n",
406 expiration_tv_sec, expiration_tv_usec);
407 _dbus_verbose ("Pre-correction, sec_remaining %ld msec_remaining %ld\n",
408 sec_remaining, msec_remaining);
411 /* We do the following in a rather convoluted fashion to deal with
412 * the fact that we don't have an integral type big enough to hold
413 * the difference of two timevals in milliseconds.
415 if (sec_remaining < 0 || (sec_remaining == 0 && msec_remaining < 0))
421 if (msec_remaining < 0)
423 msec_remaining += 1000;
427 if (sec_remaining > (_DBUS_INT_MAX / 1000) ||
428 msec_remaining > _DBUS_INT_MAX)
429 *timeout = _DBUS_INT_MAX;
431 *timeout = sec_remaining * 1000 + msec_remaining;
434 if (*timeout > interval)
436 /* This indicates that the system clock probably moved backward */
437 _dbus_verbose ("System clock set backward! Resetting timeout.\n");
439 tcb->last_tv_sec = tv_sec;
440 tcb->last_tv_usec = tv_usec;
446 _dbus_verbose (" timeout expires in %d milliseconds\n", *timeout);
449 return *timeout == 0;
453 _dbus_loop_dispatch (DBusLoop *loop)
457 _dbus_verbose (" %d connections to dispatch\n", _dbus_list_get_length (&loop->need_dispatch));
460 if (loop->need_dispatch == NULL)
464 while (loop->need_dispatch != NULL)
466 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
470 DBusDispatchStatus status;
472 status = dbus_connection_dispatch (connection);
474 if (status == DBUS_DISPATCH_COMPLETE)
476 dbus_connection_unref (connection);
481 if (status == DBUS_DISPATCH_NEED_MEMORY)
482 _dbus_wait_for_memory ();
491 _dbus_loop_queue_dispatch (DBusLoop *loop,
492 DBusConnection *connection)
494 if (_dbus_list_append (&loop->need_dispatch, connection))
496 dbus_connection_ref (connection);
503 /* Returns TRUE if we invoked any timeouts or have ready file
504 * descriptors, which is just used in test code as a debug hack
508 _dbus_loop_iterate (DBusLoop *loop,
511 #define N_STACK_DESCRIPTORS 64
514 DBusPollFD stack_fds[N_STACK_DESCRIPTORS];
516 WatchCallback **watches_for_fds;
517 WatchCallback *stack_watches_for_fds[N_STACK_DESCRIPTORS];
523 dbus_bool_t oom_watch_pending;
529 watches_for_fds = NULL;
531 oom_watch_pending = FALSE;
532 orig_depth = loop->depth;
535 _dbus_verbose ("Iteration block=%d depth=%d timeout_count=%d watch_count=%d\n",
536 block, loop->depth, loop->timeout_count, loop->watch_count);
539 if (loop->callbacks == NULL)
542 if (loop->watch_count > N_STACK_DESCRIPTORS)
544 fds = dbus_new0 (DBusPollFD, loop->watch_count);
548 _dbus_wait_for_memory ();
549 fds = dbus_new0 (DBusPollFD, loop->watch_count);
552 watches_for_fds = dbus_new (WatchCallback*, loop->watch_count);
553 while (watches_for_fds == NULL)
555 _dbus_wait_for_memory ();
556 watches_for_fds = dbus_new (WatchCallback*, loop->watch_count);
562 watches_for_fds = stack_watches_for_fds;
565 /* fill our array of fds and watches */
567 link = _dbus_list_get_first_link (&loop->callbacks);
570 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
571 Callback *cb = link->data;
572 if (cb->type == CALLBACK_WATCH)
575 WatchCallback *wcb = WATCH_CALLBACK (cb);
576 int fd = dbus_watch_get_socket (wcb->watch);
578 if (wcb->last_iteration_oom)
580 /* we skip this one this time, but reenable it next time,
581 * and have a timeout on this iteration
583 wcb->last_iteration_oom = FALSE;
584 oom_watch_pending = TRUE;
586 retval = TRUE; /* return TRUE here to keep the loop going,
587 * since we don't know the watch is inactive
591 _dbus_verbose (" skipping watch on fd %d as it was out of memory last time\n",
595 else if (_DBUS_UNLIKELY (fd == -1))
597 _dbus_warn ("watch %p was invalidated but not removed; "
598 "removing it now\n", wcb->watch);
599 _dbus_loop_remove_watch (loop, wcb->watch, wcb->function,
602 else if (dbus_watch_get_enabled (wcb->watch))
604 watches_for_fds[n_fds] = wcb;
608 flags = dbus_watch_get_flags (wcb->watch);
611 fds[n_fds].revents = 0;
612 fds[n_fds].events = 0;
613 if (flags & DBUS_WATCH_READABLE)
614 fds[n_fds].events |= _DBUS_POLLIN;
615 if (flags & DBUS_WATCH_WRITABLE)
616 fds[n_fds].events |= _DBUS_POLLOUT;
619 _dbus_verbose (" polling watch on fd %d %s\n",
620 fd, watch_flags_to_string (flags));
628 _dbus_verbose (" skipping disabled watch on fd %d %s\n",
630 watch_flags_to_string (dbus_watch_get_flags (wcb->watch)));
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->callbacks);
649 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
650 Callback *cb = link->data;
652 if (cb->type == CALLBACK_TIMEOUT &&
653 dbus_timeout_get_enabled (TIMEOUT_CALLBACK (cb)->timeout))
655 TimeoutCallback *tcb = TIMEOUT_CALLBACK (cb);
658 check_timeout (tv_sec, tv_usec, tcb, &msecs_remaining);
661 timeout = msecs_remaining;
663 timeout = MIN (msecs_remaining, timeout);
666 _dbus_verbose (" timeout added, %d remaining, aggregate timeout %ld\n",
667 msecs_remaining, timeout);
670 _dbus_assert (timeout >= 0);
673 break; /* it's not going to get shorter... */
676 else if (cb->type == CALLBACK_TIMEOUT)
678 _dbus_verbose (" skipping disabled timeout\n");
686 /* Never block if we have stuff to dispatch */
687 if (!block || loop->need_dispatch != NULL)
691 _dbus_verbose (" timeout is 0 as we aren't blocking\n");
695 /* if a watch is OOM, don't wait longer than the OOM
696 * wait to re-enable it
698 if (oom_watch_pending)
699 timeout = MIN (timeout, _dbus_get_oom_wait ());
702 _dbus_verbose (" polling on %d descriptors timeout %ld\n", n_fds, timeout);
705 n_ready = _dbus_poll (fds, n_fds, timeout);
707 initial_serial = loop->callback_list_serial;
709 if (loop->timeout_count > 0)
711 unsigned long tv_sec;
712 unsigned long tv_usec;
714 _dbus_get_current_time (&tv_sec, &tv_usec);
716 /* It'd be nice to avoid this O(n) thingy here */
717 link = _dbus_list_get_first_link (&loop->callbacks);
720 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
721 Callback *cb = link->data;
723 if (initial_serial != loop->callback_list_serial)
726 if (loop->depth != orig_depth)
729 if (cb->type == CALLBACK_TIMEOUT &&
730 dbus_timeout_get_enabled (TIMEOUT_CALLBACK (cb)->timeout))
732 TimeoutCallback *tcb = TIMEOUT_CALLBACK (cb);
735 if (check_timeout (tv_sec, tv_usec,
736 tcb, &msecs_remaining))
738 /* Save last callback time and fire this timeout */
739 tcb->last_tv_sec = tv_sec;
740 tcb->last_tv_usec = tv_usec;
743 _dbus_verbose (" invoking timeout\n");
746 /* can theoretically return FALSE on OOM, but we just
747 * let it fire again later - in practice that's what
748 * every wrapper callback in dbus-daemon used to do */
749 dbus_timeout_handle (tcb->timeout);
756 _dbus_verbose (" timeout has not expired\n");
761 else if (cb->type == CALLBACK_TIMEOUT)
763 _dbus_verbose (" skipping invocation of disabled timeout\n");
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 if (fds[i].revents != 0)
789 unsigned int condition;
791 wcb = watches_for_fds[i];
794 if (fds[i].revents & _DBUS_POLLIN)
795 condition |= DBUS_WATCH_READABLE;
796 if (fds[i].revents & _DBUS_POLLOUT)
797 condition |= DBUS_WATCH_WRITABLE;
798 if (fds[i].revents & _DBUS_POLLHUP)
799 condition |= DBUS_WATCH_HANGUP;
800 if (fds[i].revents & _DBUS_POLLERR)
801 condition |= DBUS_WATCH_ERROR;
803 /* condition may still be 0 if we got some
804 * weird POLLFOO thing like POLLWRBAND
807 if (condition != 0 &&
808 dbus_watch_get_enabled (wcb->watch))
810 if (!(* wcb->function) (wcb->watch, condition, wcb->data))
811 wcb->last_iteration_oom = TRUE;
814 _dbus_verbose (" Invoked watch, oom = %d\n",
815 wcb->last_iteration_oom);
821 if (_DBUS_UNLIKELY (fds[i].revents & _DBUS_POLLNVAL))
823 DBusWatch *watch = _dbus_watch_ref (wcb->watch);
825 _dbus_warn ("invalid request, socket fd %d not open\n",
827 _dbus_loop_remove_watch (loop, watch, wcb->function,
829 _dbus_watch_invalidate (watch);
830 _dbus_watch_unref (watch);
840 _dbus_verbose (" moving to next iteration\n");
843 if (fds && fds != stack_fds)
850 callback_unref (&watches_for_fds[i]->callback);
854 if (watches_for_fds != stack_watches_for_fds)
855 dbus_free (watches_for_fds);
858 if (_dbus_loop_dispatch (loop))
862 _dbus_verbose ("Returning %d\n", retval);
869 _dbus_loop_run (DBusLoop *loop)
873 _dbus_assert (loop->depth >= 0);
875 _dbus_loop_ref (loop);
877 our_exit_depth = loop->depth;
880 _dbus_verbose ("Running main loop, depth %d -> %d\n",
881 loop->depth - 1, loop->depth);
883 while (loop->depth != our_exit_depth)
884 _dbus_loop_iterate (loop, TRUE);
886 _dbus_loop_unref (loop);
890 _dbus_loop_quit (DBusLoop *loop)
892 _dbus_assert (loop->depth > 0);
896 _dbus_verbose ("Quit main loop, depth %d -> %d\n",
897 loop->depth + 1, loop->depth);
901 _dbus_get_oom_wait (void)
903 #ifdef DBUS_BUILD_TESTS
904 /* make tests go fast */
912 _dbus_wait_for_memory (void)
914 _dbus_verbose ("Waiting for more memory\n");
915 _dbus_sleep_milliseconds (_dbus_get_oom_wait ());
918 #endif /* !DOXYGEN_SHOULD_SKIP_THIS */