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);
135 callback_unref (Callback *cb)
137 _dbus_assert (cb->refcount > 0);
141 if (cb->refcount == 0)
143 if (cb->free_data_func)
144 (* cb->free_data_func) (cb->data);
151 add_callback (DBusLoop *loop,
154 if (!_dbus_list_append (&loop->callbacks, cb))
157 loop->callback_list_serial += 1;
162 loop->watch_count += 1;
164 case CALLBACK_TIMEOUT:
165 loop->timeout_count += 1;
173 remove_callback (DBusLoop *loop,
176 Callback *cb = link->data;
181 loop->watch_count -= 1;
183 case CALLBACK_TIMEOUT:
184 loop->timeout_count -= 1;
189 _dbus_list_remove_link (&loop->callbacks, link);
190 loop->callback_list_serial += 1;
194 _dbus_loop_new (void)
198 loop = dbus_new0 (DBusLoop, 1);
208 _dbus_loop_ref (DBusLoop *loop)
210 _dbus_assert (loop != NULL);
211 _dbus_assert (loop->refcount > 0);
217 _dbus_loop_unref (DBusLoop *loop)
219 _dbus_assert (loop != NULL);
220 _dbus_assert (loop->refcount > 0);
223 if (loop->refcount == 0)
225 while (loop->need_dispatch)
227 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
229 dbus_connection_unref (connection);
237 _dbus_loop_add_watch (DBusLoop *loop,
239 DBusWatchFunction function,
241 DBusFreeFunction free_data_func)
245 wcb = watch_callback_new (watch, function, data, free_data_func);
249 if (!add_callback (loop, (Callback*) wcb))
251 wcb->callback.free_data_func = NULL; /* don't want to have this side effect */
252 callback_unref ((Callback*) wcb);
260 _dbus_loop_remove_watch (DBusLoop *loop,
262 DBusWatchFunction function,
267 link = _dbus_list_get_first_link (&loop->callbacks);
270 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
271 Callback *this = link->data;
273 if (this->type == CALLBACK_WATCH &&
274 WATCH_CALLBACK (this)->watch == watch &&
275 this->data == data &&
276 WATCH_CALLBACK (this)->function == function)
278 remove_callback (loop, link);
286 _dbus_warn ("could not find watch %p function %p data %p to remove\n",
287 watch, (void *)function, data);
291 _dbus_loop_add_timeout (DBusLoop *loop,
292 DBusTimeout *timeout,
293 DBusTimeoutFunction function,
295 DBusFreeFunction free_data_func)
297 TimeoutCallback *tcb;
299 tcb = timeout_callback_new (timeout, function, data, free_data_func);
303 if (!add_callback (loop, (Callback*) tcb))
305 tcb->callback.free_data_func = NULL; /* don't want to have this side effect */
306 callback_unref ((Callback*) tcb);
314 _dbus_loop_remove_timeout (DBusLoop *loop,
315 DBusTimeout *timeout,
316 DBusTimeoutFunction function,
321 link = _dbus_list_get_first_link (&loop->callbacks);
324 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
325 Callback *this = link->data;
327 if (this->type == CALLBACK_TIMEOUT &&
328 TIMEOUT_CALLBACK (this)->timeout == timeout &&
329 this->data == data &&
330 TIMEOUT_CALLBACK (this)->function == function)
332 remove_callback (loop, link);
340 _dbus_warn ("could not find timeout %p function %p data %p to remove\n",
341 timeout, (void *)function, data);
344 /* Convolutions from GLib, there really must be a better way
348 check_timeout (unsigned long tv_sec,
349 unsigned long tv_usec,
350 TimeoutCallback *tcb,
355 unsigned long expiration_tv_sec;
356 unsigned long expiration_tv_usec;
357 long interval_seconds;
358 long interval_milliseconds;
361 /* I'm pretty sure this function could suck (a lot) less */
363 interval = dbus_timeout_get_interval (tcb->timeout);
365 interval_seconds = interval / 1000L;
366 interval_milliseconds = interval % 1000L;
368 expiration_tv_sec = tcb->last_tv_sec + interval_seconds;
369 expiration_tv_usec = tcb->last_tv_usec + interval_milliseconds * 1000;
370 if (expiration_tv_usec >= 1000000)
372 expiration_tv_usec -= 1000000;
373 expiration_tv_sec += 1;
376 sec_remaining = expiration_tv_sec - tv_sec;
377 /* need to force this to be signed, as it is intended to sometimes
378 * produce a negative result
380 msec_remaining = ((long) expiration_tv_usec - (long) tv_usec) / 1000L;
383 _dbus_verbose ("Interval is %ld seconds %ld msecs\n",
385 interval_milliseconds);
386 _dbus_verbose ("Now is %lu seconds %lu usecs\n",
388 _dbus_verbose ("Last is %lu seconds %lu usecs\n",
389 tcb->last_tv_sec, tcb->last_tv_usec);
390 _dbus_verbose ("Exp is %lu seconds %lu usecs\n",
391 expiration_tv_sec, expiration_tv_usec);
392 _dbus_verbose ("Pre-correction, sec_remaining %ld msec_remaining %ld\n",
393 sec_remaining, msec_remaining);
396 /* We do the following in a rather convoluted fashion to deal with
397 * the fact that we don't have an integral type big enough to hold
398 * the difference of two timevals in milliseconds.
400 if (sec_remaining < 0 || (sec_remaining == 0 && msec_remaining < 0))
406 if (msec_remaining < 0)
408 msec_remaining += 1000;
412 if (sec_remaining > (_DBUS_INT_MAX / 1000) ||
413 msec_remaining > _DBUS_INT_MAX)
414 *timeout = _DBUS_INT_MAX;
416 *timeout = sec_remaining * 1000 + msec_remaining;
419 if (*timeout > interval)
421 /* This indicates that the system clock probably moved backward */
422 _dbus_verbose ("System clock set backward! Resetting timeout.\n");
424 tcb->last_tv_sec = tv_sec;
425 tcb->last_tv_usec = tv_usec;
431 _dbus_verbose (" timeout expires in %d milliseconds\n", *timeout);
434 return *timeout == 0;
438 _dbus_loop_dispatch (DBusLoop *loop)
442 _dbus_verbose (" %d connections to dispatch\n", _dbus_list_get_length (&loop->need_dispatch));
445 if (loop->need_dispatch == NULL)
449 while (loop->need_dispatch != NULL)
451 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
455 DBusDispatchStatus status;
457 status = dbus_connection_dispatch (connection);
459 if (status == DBUS_DISPATCH_COMPLETE)
461 dbus_connection_unref (connection);
466 if (status == DBUS_DISPATCH_NEED_MEMORY)
467 _dbus_wait_for_memory ();
476 _dbus_loop_queue_dispatch (DBusLoop *loop,
477 DBusConnection *connection)
479 if (_dbus_list_append (&loop->need_dispatch, connection))
481 dbus_connection_ref (connection);
488 /* Returns TRUE if we invoked any timeouts or have ready file
489 * descriptors, which is just used in test code as a debug hack
493 _dbus_loop_iterate (DBusLoop *loop,
496 #define N_STACK_DESCRIPTORS 64
499 DBusPollFD stack_fds[N_STACK_DESCRIPTORS];
501 WatchCallback **watches_for_fds;
502 WatchCallback *stack_watches_for_fds[N_STACK_DESCRIPTORS];
508 dbus_bool_t oom_watch_pending;
514 watches_for_fds = NULL;
516 oom_watch_pending = FALSE;
517 orig_depth = loop->depth;
520 _dbus_verbose ("Iteration block=%d depth=%d timeout_count=%d watch_count=%d\n",
521 block, loop->depth, loop->timeout_count, loop->watch_count);
524 if (loop->callbacks == NULL)
527 if (loop->watch_count > N_STACK_DESCRIPTORS)
529 fds = dbus_new0 (DBusPollFD, loop->watch_count);
533 _dbus_wait_for_memory ();
534 fds = dbus_new0 (DBusPollFD, loop->watch_count);
537 watches_for_fds = dbus_new (WatchCallback*, loop->watch_count);
538 while (watches_for_fds == NULL)
540 _dbus_wait_for_memory ();
541 watches_for_fds = dbus_new (WatchCallback*, loop->watch_count);
547 watches_for_fds = stack_watches_for_fds;
550 /* fill our array of fds and watches */
552 link = _dbus_list_get_first_link (&loop->callbacks);
555 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
556 Callback *cb = link->data;
557 if (cb->type == CALLBACK_WATCH)
560 WatchCallback *wcb = WATCH_CALLBACK (cb);
562 if (wcb->last_iteration_oom)
564 /* we skip this one this time, but reenable it next time,
565 * and have a timeout on this iteration
567 wcb->last_iteration_oom = FALSE;
568 oom_watch_pending = TRUE;
570 retval = TRUE; /* return TRUE here to keep the loop going,
571 * since we don't know the watch is inactive
575 _dbus_verbose (" skipping watch on fd %d as it was out of memory last time\n",
576 dbus_watch_get_fd (wcb->watch));
579 else if (dbus_watch_get_enabled (wcb->watch))
581 watches_for_fds[n_fds] = wcb;
585 flags = dbus_watch_get_flags (wcb->watch);
587 fds[n_fds].fd = dbus_watch_get_fd (wcb->watch);
588 fds[n_fds].revents = 0;
589 fds[n_fds].events = 0;
590 if (flags & DBUS_WATCH_READABLE)
591 fds[n_fds].events |= _DBUS_POLLIN;
592 if (flags & DBUS_WATCH_WRITABLE)
593 fds[n_fds].events |= _DBUS_POLLOUT;
596 _dbus_verbose (" polling watch on fd %d\n", fds[n_fds].fd);
604 _dbus_verbose (" skipping disabled watch on fd %d\n",
605 dbus_watch_get_fd (wcb->watch));
614 if (loop->timeout_count > 0)
616 unsigned long tv_sec;
617 unsigned long tv_usec;
619 _dbus_get_current_time (&tv_sec, &tv_usec);
621 link = _dbus_list_get_first_link (&loop->callbacks);
624 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
625 Callback *cb = link->data;
627 if (cb->type == CALLBACK_TIMEOUT &&
628 dbus_timeout_get_enabled (TIMEOUT_CALLBACK (cb)->timeout))
630 TimeoutCallback *tcb = TIMEOUT_CALLBACK (cb);
633 check_timeout (tv_sec, tv_usec, tcb, &msecs_remaining);
636 timeout = msecs_remaining;
638 timeout = MIN (msecs_remaining, timeout);
641 _dbus_verbose (" timeout added, %d remaining, aggregate timeout %ld\n",
642 msecs_remaining, timeout);
645 _dbus_assert (timeout >= 0);
648 break; /* it's not going to get shorter... */
651 else if (cb->type == CALLBACK_TIMEOUT)
653 _dbus_verbose (" skipping disabled timeout\n");
661 /* Never block if we have stuff to dispatch */
662 if (!block || loop->need_dispatch != NULL)
666 _dbus_verbose (" timeout is 0 as we aren't blocking\n");
670 /* if a watch is OOM, don't wait longer than the OOM
671 * wait to re-enable it
673 if (oom_watch_pending)
674 timeout = MIN (timeout, _dbus_get_oom_wait ());
677 _dbus_verbose (" polling on %d descriptors timeout %ld\n", n_fds, timeout);
680 n_ready = _dbus_poll (fds, n_fds, timeout);
682 initial_serial = loop->callback_list_serial;
684 if (loop->timeout_count > 0)
686 unsigned long tv_sec;
687 unsigned long tv_usec;
689 _dbus_get_current_time (&tv_sec, &tv_usec);
691 /* It'd be nice to avoid this O(n) thingy here */
692 link = _dbus_list_get_first_link (&loop->callbacks);
695 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
696 Callback *cb = link->data;
698 if (initial_serial != loop->callback_list_serial)
701 if (loop->depth != orig_depth)
704 if (cb->type == CALLBACK_TIMEOUT &&
705 dbus_timeout_get_enabled (TIMEOUT_CALLBACK (cb)->timeout))
707 TimeoutCallback *tcb = TIMEOUT_CALLBACK (cb);
710 if (check_timeout (tv_sec, tv_usec,
711 tcb, &msecs_remaining))
713 /* Save last callback time and fire this timeout */
714 tcb->last_tv_sec = tv_sec;
715 tcb->last_tv_usec = tv_usec;
718 _dbus_verbose (" invoking timeout\n");
721 (* tcb->function) (tcb->timeout,
729 _dbus_verbose (" timeout has not expired\n");
734 else if (cb->type == CALLBACK_TIMEOUT)
736 _dbus_verbose (" skipping invocation of disabled timeout\n");
749 /* FIXME I think this "restart if we change the watches"
750 * approach could result in starving watches
751 * toward the end of the list.
753 if (initial_serial != loop->callback_list_serial)
756 if (loop->depth != orig_depth)
759 if (fds[i].revents != 0)
762 unsigned int condition;
764 wcb = watches_for_fds[i];
767 if (fds[i].revents & _DBUS_POLLIN)
768 condition |= DBUS_WATCH_READABLE;
769 if (fds[i].revents & _DBUS_POLLOUT)
770 condition |= DBUS_WATCH_WRITABLE;
771 if (fds[i].revents & _DBUS_POLLHUP)
772 condition |= DBUS_WATCH_HANGUP;
773 if (fds[i].revents & _DBUS_POLLERR)
774 condition |= DBUS_WATCH_ERROR;
776 /* condition may still be 0 if we got some
777 * weird POLLFOO thing like POLLWRBAND
780 if (condition != 0 &&
781 dbus_watch_get_enabled (wcb->watch))
783 if (!(* wcb->function) (wcb->watch,
785 ((Callback*)wcb)->data))
786 wcb->last_iteration_oom = TRUE;
789 _dbus_verbose (" Invoked watch, oom = %d\n",
790 wcb->last_iteration_oom);
803 _dbus_verbose (" moving to next iteration\n");
806 if (fds && fds != stack_fds)
813 callback_unref (&watches_for_fds[i]->callback);
817 if (watches_for_fds != stack_watches_for_fds)
818 dbus_free (watches_for_fds);
821 if (_dbus_loop_dispatch (loop))
825 _dbus_verbose ("Returning %d\n", retval);
832 _dbus_loop_run (DBusLoop *loop)
836 _dbus_assert (loop->depth >= 0);
838 _dbus_loop_ref (loop);
840 our_exit_depth = loop->depth;
843 _dbus_verbose ("Running main loop, depth %d -> %d\n",
844 loop->depth - 1, loop->depth);
846 while (loop->depth != our_exit_depth)
847 _dbus_loop_iterate (loop, TRUE);
849 _dbus_loop_unref (loop);
853 _dbus_loop_quit (DBusLoop *loop)
855 _dbus_assert (loop->depth > 0);
859 _dbus_verbose ("Quit main loop, depth %d -> %d\n",
860 loop->depth + 1, loop->depth);
864 _dbus_get_oom_wait (void)
866 #ifdef DBUS_BUILD_TESTS
867 /* make tests go fast */
875 _dbus_wait_for_memory (void)
877 _dbus_verbose ("Waiting for more memory\n");
878 _dbus_sleep_milliseconds (_dbus_get_oom_wait ());
881 #endif /* DOXYGEN_SHOULD_SKIP_THIS */