1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-mainloop.c Main loop utility
4 * Copyright (C) 2003 Red Hat, Inc.
6 * Licensed under the Academic Free License version 1.2
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include "dbus-mainloop.h"
26 #ifndef DOXYGEN_SHOULD_SKIP_THIS
28 #include <dbus/dbus-list.h>
29 #include <dbus/dbus-sysdeps.h>
31 #define MAINLOOP_SPEW 0
37 int callback_list_serial;
40 int depth; /**< number of recursive runs */
41 DBusList *need_dispatch;
55 DBusFreeFunction free_data_func;
61 DBusWatchFunction function;
63 /* last watch handle failed due to OOM */
64 unsigned int last_iteration_oom : 1;
71 DBusTimeoutFunction function;
72 unsigned long last_tv_sec;
73 unsigned long last_tv_usec;
76 #define WATCH_CALLBACK(callback) ((WatchCallback*)callback)
77 #define TIMEOUT_CALLBACK(callback) ((TimeoutCallback*)callback)
80 watch_callback_new (DBusWatch *watch,
81 DBusWatchFunction function,
83 DBusFreeFunction free_data_func)
87 cb = dbus_new (WatchCallback, 1);
92 cb->function = function;
93 cb->last_iteration_oom = FALSE;
94 cb->callback.refcount = 1;
95 cb->callback.type = CALLBACK_WATCH;
96 cb->callback.data = data;
97 cb->callback.free_data_func = free_data_func;
102 static TimeoutCallback*
103 timeout_callback_new (DBusTimeout *timeout,
104 DBusTimeoutFunction function,
106 DBusFreeFunction free_data_func)
110 cb = dbus_new (TimeoutCallback, 1);
114 cb->timeout = timeout;
115 cb->function = function;
116 _dbus_get_current_time (&cb->last_tv_sec,
118 cb->callback.refcount = 1;
119 cb->callback.type = CALLBACK_TIMEOUT;
120 cb->callback.data = data;
121 cb->callback.free_data_func = free_data_func;
127 callback_ref (Callback *cb)
129 _dbus_assert (cb->refcount > 0);
137 callback_unref (Callback *cb)
139 _dbus_assert (cb->refcount > 0);
143 if (cb->refcount == 0)
145 if (cb->free_data_func)
146 (* cb->free_data_func) (cb->data);
153 add_callback (DBusLoop *loop,
156 if (!_dbus_list_append (&loop->callbacks, cb))
159 loop->callback_list_serial += 1;
164 loop->watch_count += 1;
166 case CALLBACK_TIMEOUT:
167 loop->timeout_count += 1;
175 remove_callback (DBusLoop *loop,
178 Callback *cb = link->data;
183 loop->watch_count -= 1;
185 case CALLBACK_TIMEOUT:
186 loop->timeout_count -= 1;
191 _dbus_list_remove_link (&loop->callbacks, link);
192 loop->callback_list_serial += 1;
196 _dbus_loop_new (void)
200 loop = dbus_new0 (DBusLoop, 1);
210 _dbus_loop_ref (DBusLoop *loop)
212 _dbus_assert (loop != NULL);
213 _dbus_assert (loop->refcount > 0);
221 _dbus_loop_unref (DBusLoop *loop)
223 _dbus_assert (loop != NULL);
224 _dbus_assert (loop->refcount > 0);
227 if (loop->refcount == 0)
229 while (loop->need_dispatch)
231 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
233 dbus_connection_unref (connection);
241 _dbus_loop_add_watch (DBusLoop *loop,
243 DBusWatchFunction function,
245 DBusFreeFunction free_data_func)
249 wcb = watch_callback_new (watch, function, data, free_data_func);
253 if (!add_callback (loop, (Callback*) wcb))
255 wcb->callback.free_data_func = NULL; /* don't want to have this side effect */
256 callback_unref ((Callback*) wcb);
264 _dbus_loop_remove_watch (DBusLoop *loop,
266 DBusWatchFunction function,
271 link = _dbus_list_get_first_link (&loop->callbacks);
274 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
275 Callback *this = link->data;
277 if (this->type == CALLBACK_WATCH &&
278 WATCH_CALLBACK (this)->watch == watch &&
279 this->data == data &&
280 WATCH_CALLBACK (this)->function == function)
282 remove_callback (loop, link);
290 _dbus_warn ("could not find watch %p function %p data %p to remove\n",
291 watch, (void *)function, data);
295 _dbus_loop_add_timeout (DBusLoop *loop,
296 DBusTimeout *timeout,
297 DBusTimeoutFunction function,
299 DBusFreeFunction free_data_func)
301 TimeoutCallback *tcb;
303 tcb = timeout_callback_new (timeout, function, data, free_data_func);
307 if (!add_callback (loop, (Callback*) tcb))
309 tcb->callback.free_data_func = NULL; /* don't want to have this side effect */
310 callback_unref ((Callback*) tcb);
318 _dbus_loop_remove_timeout (DBusLoop *loop,
319 DBusTimeout *timeout,
320 DBusTimeoutFunction function,
325 link = _dbus_list_get_first_link (&loop->callbacks);
328 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
329 Callback *this = link->data;
331 if (this->type == CALLBACK_TIMEOUT &&
332 TIMEOUT_CALLBACK (this)->timeout == timeout &&
333 this->data == data &&
334 TIMEOUT_CALLBACK (this)->function == function)
336 remove_callback (loop, link);
344 _dbus_warn ("could not find timeout %p function %p data %p to remove\n",
345 timeout, (void *)function, data);
348 /* Convolutions from GLib, there really must be a better way
352 check_timeout (unsigned long tv_sec,
353 unsigned long tv_usec,
354 TimeoutCallback *tcb,
359 unsigned long expiration_tv_sec;
360 unsigned long expiration_tv_usec;
361 long interval_seconds;
362 long interval_milliseconds;
365 /* I'm pretty sure this function could suck (a lot) less */
367 interval = dbus_timeout_get_interval (tcb->timeout);
369 interval_seconds = interval / 1000L;
370 interval_milliseconds = interval % 1000L;
372 expiration_tv_sec = tcb->last_tv_sec + interval_seconds;
373 expiration_tv_usec = tcb->last_tv_usec + interval_milliseconds * 1000;
374 if (expiration_tv_usec >= 1000000)
376 expiration_tv_usec -= 1000000;
377 expiration_tv_sec += 1;
380 sec_remaining = expiration_tv_sec - tv_sec;
381 /* need to force this to be signed, as it is intended to sometimes
382 * produce a negative result
384 msec_remaining = ((long) expiration_tv_usec - (long) tv_usec) / 1000L;
387 _dbus_verbose ("Interval is %ld seconds %ld msecs\n",
389 interval_milliseconds);
390 _dbus_verbose ("Now is %lu seconds %lu usecs\n",
392 _dbus_verbose ("Last is %lu seconds %lu usecs\n",
393 tcb->last_tv_sec, tcb->last_tv_usec);
394 _dbus_verbose ("Exp is %lu seconds %lu usecs\n",
395 expiration_tv_sec, expiration_tv_usec);
396 _dbus_verbose ("Pre-correction, sec_remaining %ld msec_remaining %ld\n",
397 sec_remaining, msec_remaining);
400 /* We do the following in a rather convoluted fashion to deal with
401 * the fact that we don't have an integral type big enough to hold
402 * the difference of two timevals in milliseconds.
404 if (sec_remaining < 0 || (sec_remaining == 0 && msec_remaining < 0))
410 if (msec_remaining < 0)
412 msec_remaining += 1000;
416 if (sec_remaining > (_DBUS_INT_MAX / 1000) ||
417 msec_remaining > _DBUS_INT_MAX)
418 *timeout = _DBUS_INT_MAX;
420 *timeout = sec_remaining * 1000 + msec_remaining;
423 if (*timeout > interval)
425 /* This indicates that the system clock probably moved backward */
426 _dbus_verbose ("System clock set backward! Resetting timeout.\n");
428 tcb->last_tv_sec = tv_sec;
429 tcb->last_tv_usec = tv_usec;
435 _dbus_verbose (" timeout expires in %d milliseconds\n", *timeout);
438 return *timeout == 0;
442 _dbus_loop_dispatch (DBusLoop *loop)
446 _dbus_verbose (" %d connections to dispatch\n", _dbus_list_get_length (&loop->need_dispatch));
449 if (loop->need_dispatch == NULL)
453 while (loop->need_dispatch != NULL)
455 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
459 DBusDispatchStatus status;
461 status = dbus_connection_dispatch (connection);
463 if (status == DBUS_DISPATCH_COMPLETE)
465 dbus_connection_unref (connection);
470 if (status == DBUS_DISPATCH_NEED_MEMORY)
471 _dbus_wait_for_memory ();
480 _dbus_loop_queue_dispatch (DBusLoop *loop,
481 DBusConnection *connection)
483 if (_dbus_list_append (&loop->need_dispatch, connection))
485 dbus_connection_ref (connection);
492 /* Returns TRUE if we invoked any timeouts or have ready file
493 * descriptors, which is just used in test code as a debug hack
497 _dbus_loop_iterate (DBusLoop *loop,
500 #define N_STACK_DESCRIPTORS 64
503 DBusPollFD stack_fds[N_STACK_DESCRIPTORS];
505 WatchCallback **watches_for_fds;
506 WatchCallback *stack_watches_for_fds[N_STACK_DESCRIPTORS];
512 dbus_bool_t oom_watch_pending;
518 watches_for_fds = NULL;
520 oom_watch_pending = FALSE;
521 orig_depth = loop->depth;
524 _dbus_verbose ("Iteration block=%d depth=%d timeout_count=%d watch_count=%d\n",
525 block, loop->depth, loop->timeout_count, loop->watch_count);
528 if (loop->callbacks == NULL)
531 if (loop->watch_count > N_STACK_DESCRIPTORS)
533 fds = dbus_new0 (DBusPollFD, loop->watch_count);
537 _dbus_wait_for_memory ();
538 fds = dbus_new0 (DBusPollFD, loop->watch_count);
541 watches_for_fds = dbus_new (WatchCallback*, loop->watch_count);
542 while (watches_for_fds == NULL)
544 _dbus_wait_for_memory ();
545 watches_for_fds = dbus_new (WatchCallback*, loop->watch_count);
551 watches_for_fds = stack_watches_for_fds;
554 /* fill our array of fds and watches */
556 link = _dbus_list_get_first_link (&loop->callbacks);
559 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
560 Callback *cb = link->data;
561 if (cb->type == CALLBACK_WATCH)
564 WatchCallback *wcb = WATCH_CALLBACK (cb);
566 if (wcb->last_iteration_oom)
568 /* we skip this one this time, but reenable it next time,
569 * and have a timeout on this iteration
571 wcb->last_iteration_oom = FALSE;
572 oom_watch_pending = TRUE;
574 retval = TRUE; /* return TRUE here to keep the loop going,
575 * since we don't know the watch is inactive
579 _dbus_verbose (" skipping watch on fd %d as it was out of memory last time\n",
580 dbus_watch_get_fd (wcb->watch));
583 else if (dbus_watch_get_enabled (wcb->watch))
585 watches_for_fds[n_fds] = wcb;
589 flags = dbus_watch_get_flags (wcb->watch);
591 fds[n_fds].fd = dbus_watch_get_fd (wcb->watch);
592 fds[n_fds].revents = 0;
593 fds[n_fds].events = 0;
594 if (flags & DBUS_WATCH_READABLE)
595 fds[n_fds].events |= _DBUS_POLLIN;
596 if (flags & DBUS_WATCH_WRITABLE)
597 fds[n_fds].events |= _DBUS_POLLOUT;
600 _dbus_verbose (" polling watch on fd %d\n", fds[n_fds].fd);
608 _dbus_verbose (" skipping disabled watch on fd %d\n",
609 dbus_watch_get_fd (wcb->watch));
618 if (loop->timeout_count > 0)
620 unsigned long tv_sec;
621 unsigned long tv_usec;
623 _dbus_get_current_time (&tv_sec, &tv_usec);
625 link = _dbus_list_get_first_link (&loop->callbacks);
628 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
629 Callback *cb = link->data;
631 if (cb->type == CALLBACK_TIMEOUT &&
632 dbus_timeout_get_enabled (TIMEOUT_CALLBACK (cb)->timeout))
634 TimeoutCallback *tcb = TIMEOUT_CALLBACK (cb);
637 check_timeout (tv_sec, tv_usec, tcb, &msecs_remaining);
640 timeout = msecs_remaining;
642 timeout = MIN (msecs_remaining, timeout);
645 _dbus_verbose (" timeout added, %d remaining, aggregate timeout %ld\n",
646 msecs_remaining, timeout);
649 _dbus_assert (timeout >= 0);
652 break; /* it's not going to get shorter... */
655 else if (cb->type == CALLBACK_TIMEOUT)
657 _dbus_verbose (" skipping disabled timeout\n");
665 /* Never block if we have stuff to dispatch */
666 if (!block || loop->need_dispatch != NULL)
670 _dbus_verbose (" timeout is 0 as we aren't blocking\n");
674 /* if a watch is OOM, don't wait longer than the OOM
675 * wait to re-enable it
677 if (oom_watch_pending)
678 timeout = MIN (timeout, _dbus_get_oom_wait ());
681 _dbus_verbose (" polling on %d descriptors timeout %ld\n", n_fds, timeout);
684 n_ready = _dbus_poll (fds, n_fds, timeout);
686 initial_serial = loop->callback_list_serial;
688 if (loop->timeout_count > 0)
690 unsigned long tv_sec;
691 unsigned long tv_usec;
693 _dbus_get_current_time (&tv_sec, &tv_usec);
695 /* It'd be nice to avoid this O(n) thingy here */
696 link = _dbus_list_get_first_link (&loop->callbacks);
699 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
700 Callback *cb = link->data;
702 if (initial_serial != loop->callback_list_serial)
705 if (loop->depth != orig_depth)
708 if (cb->type == CALLBACK_TIMEOUT &&
709 dbus_timeout_get_enabled (TIMEOUT_CALLBACK (cb)->timeout))
711 TimeoutCallback *tcb = TIMEOUT_CALLBACK (cb);
714 if (check_timeout (tv_sec, tv_usec,
715 tcb, &msecs_remaining))
717 /* Save last callback time and fire this timeout */
718 tcb->last_tv_sec = tv_sec;
719 tcb->last_tv_usec = tv_usec;
722 _dbus_verbose (" invoking timeout\n");
725 (* tcb->function) (tcb->timeout,
733 _dbus_verbose (" timeout has not expired\n");
738 else if (cb->type == CALLBACK_TIMEOUT)
740 _dbus_verbose (" skipping invocation of disabled timeout\n");
753 /* FIXME I think this "restart if we change the watches"
754 * approach could result in starving watches
755 * toward the end of the list.
757 if (initial_serial != loop->callback_list_serial)
760 if (loop->depth != orig_depth)
763 if (fds[i].revents != 0)
766 unsigned int condition;
768 wcb = watches_for_fds[i];
771 if (fds[i].revents & _DBUS_POLLIN)
772 condition |= DBUS_WATCH_READABLE;
773 if (fds[i].revents & _DBUS_POLLOUT)
774 condition |= DBUS_WATCH_WRITABLE;
775 if (fds[i].revents & _DBUS_POLLHUP)
776 condition |= DBUS_WATCH_HANGUP;
777 if (fds[i].revents & _DBUS_POLLERR)
778 condition |= DBUS_WATCH_ERROR;
780 /* condition may still be 0 if we got some
781 * weird POLLFOO thing like POLLWRBAND
784 if (condition != 0 &&
785 dbus_watch_get_enabled (wcb->watch))
787 if (!(* wcb->function) (wcb->watch,
789 ((Callback*)wcb)->data))
790 wcb->last_iteration_oom = TRUE;
793 _dbus_verbose (" Invoked watch, oom = %d\n",
794 wcb->last_iteration_oom);
807 _dbus_verbose (" moving to next iteration\n");
810 if (fds && fds != stack_fds)
817 callback_unref (&watches_for_fds[i]->callback);
821 if (watches_for_fds != stack_watches_for_fds)
822 dbus_free (watches_for_fds);
825 if (_dbus_loop_dispatch (loop))
829 _dbus_verbose ("Returning %d\n", retval);
836 _dbus_loop_run (DBusLoop *loop)
840 _dbus_assert (loop->depth >= 0);
842 _dbus_loop_ref (loop);
844 our_exit_depth = loop->depth;
847 _dbus_verbose ("Running main loop, depth %d -> %d\n",
848 loop->depth - 1, loop->depth);
850 while (loop->depth != our_exit_depth)
851 _dbus_loop_iterate (loop, TRUE);
853 _dbus_loop_unref (loop);
857 _dbus_loop_quit (DBusLoop *loop)
859 _dbus_assert (loop->depth > 0);
863 _dbus_verbose ("Quit main loop, depth %d -> %d\n",
864 loop->depth + 1, loop->depth);
868 _dbus_get_oom_wait (void)
870 #ifdef DBUS_BUILD_TESTS
871 /* make tests go fast */
879 _dbus_wait_for_memory (void)
881 _dbus_verbose ("Waiting for more memory\n");
882 _dbus_sleep_milliseconds (_dbus_get_oom_wait ());
885 #endif /* DOXYGEN_SHOULD_SKIP_THIS */