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>
32 #define MAINLOOP_SPEW 0
35 #ifdef DBUS_ENABLE_VERBOSE_MODE
37 watch_flags_to_string (int flags)
39 const char *watch_type;
41 if ((flags & DBUS_WATCH_READABLE) &&
42 (flags & DBUS_WATCH_WRITABLE))
43 watch_type = "readwrite";
44 else if (flags & DBUS_WATCH_READABLE)
46 else if (flags & DBUS_WATCH_WRITABLE)
49 watch_type = "not read or write";
52 #endif /* DBUS_ENABLE_VERBOSE_MODE */
53 #endif /* MAINLOOP_SPEW */
59 int callback_list_serial;
62 int depth; /**< number of recursive runs */
63 DBusList *need_dispatch;
77 DBusFreeFunction free_data_func;
83 DBusWatchFunction function;
85 /* last watch handle failed due to OOM */
86 unsigned int last_iteration_oom : 1;
93 DBusTimeoutFunction function;
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;
118 cb->callback.data = data;
119 cb->callback.free_data_func = free_data_func;
124 static TimeoutCallback*
125 timeout_callback_new (DBusTimeout *timeout,
126 DBusTimeoutFunction function,
128 DBusFreeFunction free_data_func)
132 cb = dbus_new (TimeoutCallback, 1);
136 cb->timeout = timeout;
137 cb->function = function;
138 _dbus_get_current_time (&cb->last_tv_sec,
140 cb->callback.refcount = 1;
141 cb->callback.type = CALLBACK_TIMEOUT;
142 cb->callback.data = data;
143 cb->callback.free_data_func = free_data_func;
149 callback_ref (Callback *cb)
151 _dbus_assert (cb->refcount > 0);
159 callback_unref (Callback *cb)
161 _dbus_assert (cb->refcount > 0);
165 if (cb->refcount == 0)
167 if (cb->free_data_func)
168 (* cb->free_data_func) (cb->data);
175 add_callback (DBusLoop *loop,
178 if (!_dbus_list_append (&loop->callbacks, cb))
181 loop->callback_list_serial += 1;
186 loop->watch_count += 1;
188 case CALLBACK_TIMEOUT:
189 loop->timeout_count += 1;
197 remove_callback (DBusLoop *loop,
200 Callback *cb = link->data;
205 loop->watch_count -= 1;
207 case CALLBACK_TIMEOUT:
208 loop->timeout_count -= 1;
213 _dbus_list_remove_link (&loop->callbacks, link);
214 loop->callback_list_serial += 1;
218 _dbus_loop_new (void)
222 loop = dbus_new0 (DBusLoop, 1);
232 _dbus_loop_ref (DBusLoop *loop)
234 _dbus_assert (loop != NULL);
235 _dbus_assert (loop->refcount > 0);
243 _dbus_loop_unref (DBusLoop *loop)
245 _dbus_assert (loop != NULL);
246 _dbus_assert (loop->refcount > 0);
249 if (loop->refcount == 0)
251 while (loop->need_dispatch)
253 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
255 dbus_connection_unref (connection);
263 _dbus_loop_add_watch (DBusLoop *loop,
265 DBusWatchFunction function,
267 DBusFreeFunction free_data_func)
271 wcb = watch_callback_new (watch, function, data, free_data_func);
275 if (!add_callback (loop, (Callback*) wcb))
277 wcb->callback.free_data_func = NULL; /* don't want to have this side effect */
278 callback_unref ((Callback*) wcb);
286 _dbus_loop_remove_watch (DBusLoop *loop,
288 DBusWatchFunction function,
293 link = _dbus_list_get_first_link (&loop->callbacks);
296 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
297 Callback *this = link->data;
299 if (this->type == CALLBACK_WATCH &&
300 WATCH_CALLBACK (this)->watch == watch &&
301 this->data == data &&
302 WATCH_CALLBACK (this)->function == function)
304 remove_callback (loop, link);
312 _dbus_warn ("could not find watch %p function %p data %p to remove\n",
313 watch, (void *)function, data);
317 _dbus_loop_add_timeout (DBusLoop *loop,
318 DBusTimeout *timeout,
319 DBusTimeoutFunction function,
321 DBusFreeFunction free_data_func)
323 TimeoutCallback *tcb;
325 tcb = timeout_callback_new (timeout, function, data, free_data_func);
329 if (!add_callback (loop, (Callback*) tcb))
331 tcb->callback.free_data_func = NULL; /* don't want to have this side effect */
332 callback_unref ((Callback*) tcb);
340 _dbus_loop_remove_timeout (DBusLoop *loop,
341 DBusTimeout *timeout,
342 DBusTimeoutFunction function,
347 link = _dbus_list_get_first_link (&loop->callbacks);
350 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
351 Callback *this = link->data;
353 if (this->type == CALLBACK_TIMEOUT &&
354 TIMEOUT_CALLBACK (this)->timeout == timeout &&
355 this->data == data &&
356 TIMEOUT_CALLBACK (this)->function == function)
358 remove_callback (loop, link);
366 _dbus_warn ("could not find timeout %p function %p data %p to remove\n",
367 timeout, (void *)function, data);
370 /* Convolutions from GLib, there really must be a better way
374 check_timeout (unsigned long tv_sec,
375 unsigned long tv_usec,
376 TimeoutCallback *tcb,
381 unsigned long expiration_tv_sec;
382 unsigned long expiration_tv_usec;
383 long interval_seconds;
384 long interval_milliseconds;
387 /* I'm pretty sure this function could suck (a lot) less */
389 interval = dbus_timeout_get_interval (tcb->timeout);
391 interval_seconds = interval / 1000L;
392 interval_milliseconds = interval % 1000L;
394 expiration_tv_sec = tcb->last_tv_sec + interval_seconds;
395 expiration_tv_usec = tcb->last_tv_usec + interval_milliseconds * 1000;
396 if (expiration_tv_usec >= 1000000)
398 expiration_tv_usec -= 1000000;
399 expiration_tv_sec += 1;
402 sec_remaining = expiration_tv_sec - tv_sec;
403 /* need to force this to be signed, as it is intended to sometimes
404 * produce a negative result
406 msec_remaining = ((long) expiration_tv_usec - (long) tv_usec) / 1000L;
409 _dbus_verbose ("Interval is %ld seconds %ld msecs\n",
411 interval_milliseconds);
412 _dbus_verbose ("Now is %lu seconds %lu usecs\n",
414 _dbus_verbose ("Last is %lu seconds %lu usecs\n",
415 tcb->last_tv_sec, tcb->last_tv_usec);
416 _dbus_verbose ("Exp is %lu seconds %lu usecs\n",
417 expiration_tv_sec, expiration_tv_usec);
418 _dbus_verbose ("Pre-correction, sec_remaining %ld msec_remaining %ld\n",
419 sec_remaining, msec_remaining);
422 /* We do the following in a rather convoluted fashion to deal with
423 * the fact that we don't have an integral type big enough to hold
424 * the difference of two timevals in milliseconds.
426 if (sec_remaining < 0 || (sec_remaining == 0 && msec_remaining < 0))
432 if (msec_remaining < 0)
434 msec_remaining += 1000;
438 if (sec_remaining > (_DBUS_INT_MAX / 1000) ||
439 msec_remaining > _DBUS_INT_MAX)
440 *timeout = _DBUS_INT_MAX;
442 *timeout = sec_remaining * 1000 + msec_remaining;
445 if (*timeout > interval)
447 /* This indicates that the system clock probably moved backward */
448 _dbus_verbose ("System clock set backward! Resetting timeout.\n");
450 tcb->last_tv_sec = tv_sec;
451 tcb->last_tv_usec = tv_usec;
457 _dbus_verbose (" timeout expires in %d milliseconds\n", *timeout);
460 return *timeout == 0;
464 _dbus_loop_dispatch (DBusLoop *loop)
468 _dbus_verbose (" %d connections to dispatch\n", _dbus_list_get_length (&loop->need_dispatch));
471 if (loop->need_dispatch == NULL)
475 while (loop->need_dispatch != NULL)
477 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
481 DBusDispatchStatus status;
483 status = dbus_connection_dispatch (connection);
485 if (status == DBUS_DISPATCH_COMPLETE)
487 dbus_connection_unref (connection);
492 if (status == DBUS_DISPATCH_NEED_MEMORY)
493 _dbus_wait_for_memory ();
502 _dbus_loop_queue_dispatch (DBusLoop *loop,
503 DBusConnection *connection)
505 if (_dbus_list_append (&loop->need_dispatch, connection))
507 dbus_connection_ref (connection);
514 /* Returns TRUE if we invoked any timeouts or have ready file
515 * descriptors, which is just used in test code as a debug hack
519 _dbus_loop_iterate (DBusLoop *loop,
522 #define N_STACK_DESCRIPTORS 64
525 DBusPollFD stack_fds[N_STACK_DESCRIPTORS];
527 WatchCallback **watches_for_fds;
528 WatchCallback *stack_watches_for_fds[N_STACK_DESCRIPTORS];
534 dbus_bool_t oom_watch_pending;
540 watches_for_fds = NULL;
542 oom_watch_pending = FALSE;
543 orig_depth = loop->depth;
546 _dbus_verbose ("Iteration block=%d depth=%d timeout_count=%d watch_count=%d\n",
547 block, loop->depth, loop->timeout_count, loop->watch_count);
550 if (loop->callbacks == NULL)
553 if (loop->watch_count > N_STACK_DESCRIPTORS)
555 fds = dbus_new0 (DBusPollFD, loop->watch_count);
559 _dbus_wait_for_memory ();
560 fds = dbus_new0 (DBusPollFD, loop->watch_count);
563 watches_for_fds = dbus_new (WatchCallback*, loop->watch_count);
564 while (watches_for_fds == NULL)
566 _dbus_wait_for_memory ();
567 watches_for_fds = dbus_new (WatchCallback*, loop->watch_count);
573 watches_for_fds = stack_watches_for_fds;
576 /* fill our array of fds and watches */
578 link = _dbus_list_get_first_link (&loop->callbacks);
581 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
582 Callback *cb = link->data;
583 if (cb->type == CALLBACK_WATCH)
586 WatchCallback *wcb = WATCH_CALLBACK (cb);
588 if (wcb->last_iteration_oom)
590 /* we skip this one this time, but reenable it next time,
591 * and have a timeout on this iteration
593 wcb->last_iteration_oom = FALSE;
594 oom_watch_pending = TRUE;
596 retval = TRUE; /* return TRUE here to keep the loop going,
597 * since we don't know the watch is inactive
601 _dbus_verbose (" skipping watch on fd %d as it was out of memory last time\n",
602 dbus_watch_get_socket (wcb->watch));
605 else if (dbus_watch_get_enabled (wcb->watch))
607 watches_for_fds[n_fds] = wcb;
611 flags = dbus_watch_get_flags (wcb->watch);
613 fds[n_fds].fd = dbus_watch_get_socket (wcb->watch);
614 fds[n_fds].revents = 0;
615 fds[n_fds].events = 0;
616 if (flags & DBUS_WATCH_READABLE)
617 fds[n_fds].events |= _DBUS_POLLIN;
618 if (flags & DBUS_WATCH_WRITABLE)
619 fds[n_fds].events |= _DBUS_POLLOUT;
622 _dbus_verbose (" polling watch on fd %d %s\n",
623 fds[n_fds].fd, watch_flags_to_string (flags));
631 _dbus_verbose (" skipping disabled watch on fd %d %s\n",
632 dbus_watch_get_socket (wcb->watch),
633 watch_flags_to_string (dbus_watch_get_flags (wcb->watch)));
642 if (loop->timeout_count > 0)
644 unsigned long tv_sec;
645 unsigned long tv_usec;
647 _dbus_get_current_time (&tv_sec, &tv_usec);
649 link = _dbus_list_get_first_link (&loop->callbacks);
652 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
653 Callback *cb = link->data;
655 if (cb->type == CALLBACK_TIMEOUT &&
656 dbus_timeout_get_enabled (TIMEOUT_CALLBACK (cb)->timeout))
658 TimeoutCallback *tcb = TIMEOUT_CALLBACK (cb);
661 check_timeout (tv_sec, tv_usec, tcb, &msecs_remaining);
664 timeout = msecs_remaining;
666 timeout = MIN (msecs_remaining, timeout);
669 _dbus_verbose (" timeout added, %d remaining, aggregate timeout %ld\n",
670 msecs_remaining, timeout);
673 _dbus_assert (timeout >= 0);
676 break; /* it's not going to get shorter... */
679 else if (cb->type == CALLBACK_TIMEOUT)
681 _dbus_verbose (" skipping disabled timeout\n");
689 /* Never block if we have stuff to dispatch */
690 if (!block || loop->need_dispatch != NULL)
694 _dbus_verbose (" timeout is 0 as we aren't blocking\n");
698 /* if a watch is OOM, don't wait longer than the OOM
699 * wait to re-enable it
701 if (oom_watch_pending)
702 timeout = MIN (timeout, _dbus_get_oom_wait ());
705 _dbus_verbose (" polling on %d descriptors timeout %ld\n", n_fds, timeout);
708 n_ready = _dbus_poll (fds, n_fds, timeout);
710 initial_serial = loop->callback_list_serial;
712 if (loop->timeout_count > 0)
714 unsigned long tv_sec;
715 unsigned long tv_usec;
717 _dbus_get_current_time (&tv_sec, &tv_usec);
719 /* It'd be nice to avoid this O(n) thingy here */
720 link = _dbus_list_get_first_link (&loop->callbacks);
723 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
724 Callback *cb = link->data;
726 if (initial_serial != loop->callback_list_serial)
729 if (loop->depth != orig_depth)
732 if (cb->type == CALLBACK_TIMEOUT &&
733 dbus_timeout_get_enabled (TIMEOUT_CALLBACK (cb)->timeout))
735 TimeoutCallback *tcb = TIMEOUT_CALLBACK (cb);
738 if (check_timeout (tv_sec, tv_usec,
739 tcb, &msecs_remaining))
741 /* Save last callback time and fire this timeout */
742 tcb->last_tv_sec = tv_sec;
743 tcb->last_tv_usec = tv_usec;
746 _dbus_verbose (" invoking timeout\n");
749 (* tcb->function) (tcb->timeout,
757 _dbus_verbose (" timeout has not expired\n");
762 else if (cb->type == CALLBACK_TIMEOUT)
764 _dbus_verbose (" skipping invocation of disabled timeout\n");
777 /* FIXME I think this "restart if we change the watches"
778 * approach could result in starving watches
779 * toward the end of the list.
781 if (initial_serial != loop->callback_list_serial)
784 if (loop->depth != orig_depth)
787 if (fds[i].revents != 0)
790 unsigned int condition;
792 wcb = watches_for_fds[i];
795 if (fds[i].revents & _DBUS_POLLIN)
796 condition |= DBUS_WATCH_READABLE;
797 if (fds[i].revents & _DBUS_POLLOUT)
798 condition |= DBUS_WATCH_WRITABLE;
799 if (fds[i].revents & _DBUS_POLLHUP)
800 condition |= DBUS_WATCH_HANGUP;
801 if (fds[i].revents & _DBUS_POLLERR)
802 condition |= DBUS_WATCH_ERROR;
804 /* condition may still be 0 if we got some
805 * weird POLLFOO thing like POLLWRBAND
808 if (condition != 0 &&
809 dbus_watch_get_enabled (wcb->watch))
811 if (!(* wcb->function) (wcb->watch,
813 ((Callback*)wcb)->data))
814 wcb->last_iteration_oom = TRUE;
817 _dbus_verbose (" Invoked watch, oom = %d\n",
818 wcb->last_iteration_oom);
831 _dbus_verbose (" moving to next iteration\n");
834 if (fds && fds != stack_fds)
841 callback_unref (&watches_for_fds[i]->callback);
845 if (watches_for_fds != stack_watches_for_fds)
846 dbus_free (watches_for_fds);
849 if (_dbus_loop_dispatch (loop))
853 _dbus_verbose ("Returning %d\n", retval);
860 _dbus_loop_run (DBusLoop *loop)
864 _dbus_assert (loop->depth >= 0);
866 _dbus_loop_ref (loop);
868 our_exit_depth = loop->depth;
871 _dbus_verbose ("Running main loop, depth %d -> %d\n",
872 loop->depth - 1, loop->depth);
874 while (loop->depth != our_exit_depth)
875 _dbus_loop_iterate (loop, TRUE);
877 _dbus_loop_unref (loop);
881 _dbus_loop_quit (DBusLoop *loop)
883 _dbus_assert (loop->depth > 0);
887 _dbus_verbose ("Quit main loop, depth %d -> %d\n",
888 loop->depth + 1, loop->depth);
892 _dbus_get_oom_wait (void)
894 #ifdef DBUS_BUILD_TESTS
895 /* make tests go fast */
903 _dbus_wait_for_memory (void)
905 _dbus_verbose ("Waiting for more memory\n");
906 _dbus_sleep_milliseconds (_dbus_get_oom_wait ());
909 #endif /* !DOXYGEN_SHOULD_SKIP_THIS */