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 #include <dbus/dbus-list.h>
27 #include <dbus/dbus-sysdeps.h>
29 #define MAINLOOP_SPEW 1
35 int callback_list_serial;
38 int depth; /**< number of recursive runs */
39 DBusList *need_dispatch;
53 DBusFreeFunction free_data_func;
59 DBusWatchFunction function;
61 /* last watch handle failed due to OOM */
62 unsigned int last_iteration_oom : 1;
69 DBusTimeoutFunction function;
70 unsigned long last_tv_sec;
71 unsigned long last_tv_usec;
74 #define WATCH_CALLBACK(callback) ((WatchCallback*)callback)
75 #define TIMEOUT_CALLBACK(callback) ((TimeoutCallback*)callback)
78 watch_callback_new (DBusWatch *watch,
79 DBusWatchFunction function,
81 DBusFreeFunction free_data_func)
85 cb = dbus_new (WatchCallback, 1);
90 cb->function = function;
91 cb->last_iteration_oom = FALSE;
92 cb->callback.refcount = 1;
93 cb->callback.type = CALLBACK_WATCH;
94 cb->callback.data = data;
95 cb->callback.free_data_func = free_data_func;
100 static TimeoutCallback*
101 timeout_callback_new (DBusTimeout *timeout,
102 DBusTimeoutFunction function,
104 DBusFreeFunction free_data_func)
108 cb = dbus_new (TimeoutCallback, 1);
112 cb->timeout = timeout;
113 cb->function = function;
114 _dbus_get_current_time (&cb->last_tv_sec,
116 cb->callback.refcount = 1;
117 cb->callback.type = CALLBACK_TIMEOUT;
118 cb->callback.data = data;
119 cb->callback.free_data_func = free_data_func;
125 callback_ref (Callback *cb)
127 _dbus_assert (cb->refcount > 0);
133 callback_unref (Callback *cb)
135 _dbus_assert (cb->refcount > 0);
139 if (cb->refcount == 0)
141 if (cb->free_data_func)
142 (* cb->free_data_func) (cb->data);
149 add_callback (DBusLoop *loop,
152 if (!_dbus_list_append (&loop->callbacks, cb))
155 loop->callback_list_serial += 1;
160 loop->watch_count += 1;
162 case CALLBACK_TIMEOUT:
163 loop->timeout_count += 1;
171 remove_callback (DBusLoop *loop,
174 Callback *cb = link->data;
179 loop->watch_count -= 1;
181 case CALLBACK_TIMEOUT:
182 loop->timeout_count -= 1;
187 _dbus_list_remove_link (&loop->callbacks, link);
188 loop->callback_list_serial += 1;
192 _dbus_loop_new (void)
196 loop = dbus_new0 (DBusLoop, 1);
206 _dbus_loop_ref (DBusLoop *loop)
208 _dbus_assert (loop != NULL);
209 _dbus_assert (loop->refcount > 0);
215 _dbus_loop_unref (DBusLoop *loop)
217 _dbus_assert (loop != NULL);
218 _dbus_assert (loop->refcount > 0);
221 if (loop->refcount == 0)
223 while (loop->need_dispatch)
225 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
227 dbus_connection_unref (connection);
235 _dbus_loop_add_watch (DBusLoop *loop,
237 DBusWatchFunction function,
239 DBusFreeFunction free_data_func)
243 wcb = watch_callback_new (watch, function, data, free_data_func);
247 if (!add_callback (loop, (Callback*) wcb))
249 wcb->callback.free_data_func = NULL; /* don't want to have this side effect */
250 callback_unref ((Callback*) wcb);
258 _dbus_loop_remove_watch (DBusLoop *loop,
260 DBusWatchFunction function,
265 link = _dbus_list_get_first_link (&loop->callbacks);
268 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
269 Callback *this = link->data;
271 if (this->type == CALLBACK_WATCH &&
272 WATCH_CALLBACK (this)->watch == watch &&
273 this->data == data &&
274 WATCH_CALLBACK (this)->function == function)
276 remove_callback (loop, link);
284 _dbus_warn ("could not find watch %p function %p data %p to remove\n",
285 watch, function, data);
289 _dbus_loop_add_timeout (DBusLoop *loop,
290 DBusTimeout *timeout,
291 DBusTimeoutFunction function,
293 DBusFreeFunction free_data_func)
295 TimeoutCallback *tcb;
297 tcb = timeout_callback_new (timeout, function, data, free_data_func);
301 if (!add_callback (loop, (Callback*) tcb))
303 tcb->callback.free_data_func = NULL; /* don't want to have this side effect */
304 callback_unref ((Callback*) tcb);
312 _dbus_loop_remove_timeout (DBusLoop *loop,
313 DBusTimeout *timeout,
314 DBusTimeoutFunction function,
319 link = _dbus_list_get_first_link (&loop->callbacks);
322 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
323 Callback *this = link->data;
325 if (this->type == CALLBACK_TIMEOUT &&
326 TIMEOUT_CALLBACK (this)->timeout == timeout &&
327 this->data == data &&
328 TIMEOUT_CALLBACK (this)->function == function)
330 remove_callback (loop, link);
338 _dbus_warn ("could not find timeout %p function %p data %p to remove\n",
339 timeout, function, data);
342 /* Convolutions from GLib, there really must be a better way
346 check_timeout (unsigned long tv_sec,
347 unsigned long tv_usec,
348 TimeoutCallback *tcb,
353 unsigned long expiration_tv_sec;
354 unsigned long expiration_tv_usec;
355 long interval_seconds;
356 long interval_milliseconds;
359 /* I'm pretty sure this function could suck (a lot) less */
361 interval = dbus_timeout_get_interval (tcb->timeout);
363 interval_seconds = interval / 1000L;
364 interval_milliseconds = interval % 1000L;
366 expiration_tv_sec = tcb->last_tv_sec + interval_seconds;
367 expiration_tv_usec = tcb->last_tv_usec + interval_milliseconds * 1000;
368 if (expiration_tv_usec >= 1000000)
370 expiration_tv_usec -= 1000000;
371 expiration_tv_sec += 1;
374 sec_remaining = expiration_tv_sec - tv_sec;
375 /* need to force this to be signed, as it is intended to sometimes
376 * produce a negative result
378 msec_remaining = ((long) expiration_tv_usec - (long) tv_usec) / 1000L;
381 _dbus_verbose ("Interval is %ld seconds %ld msecs\n",
383 interval_milliseconds);
384 _dbus_verbose ("Now is %lu seconds %lu usecs\n",
386 _dbus_verbose ("Last is %lu seconds %lu usecs\n",
387 tcb->last_tv_sec, tcb->last_tv_usec);
388 _dbus_verbose ("Exp is %lu seconds %lu usecs\n",
389 expiration_tv_sec, expiration_tv_usec);
390 _dbus_verbose ("Pre-correction, sec_remaining %ld msec_remaining %ld\n",
391 sec_remaining, msec_remaining);
394 /* We do the following in a rather convoluted fashion to deal with
395 * the fact that we don't have an integral type big enough to hold
396 * the difference of two timevals in milliseconds.
398 if (sec_remaining < 0 || (sec_remaining == 0 && msec_remaining < 0))
404 if (msec_remaining < 0)
406 msec_remaining += 1000;
410 if (sec_remaining > (_DBUS_INT_MAX / 1000) ||
411 msec_remaining > _DBUS_INT_MAX)
412 *timeout = _DBUS_INT_MAX;
414 *timeout = sec_remaining * 1000 + msec_remaining;
417 if (*timeout > interval)
419 /* This indicates that the system clock probably moved backward */
420 _dbus_verbose ("System clock set backward! Resetting timeout.\n");
422 tcb->last_tv_sec = tv_sec;
423 tcb->last_tv_usec = tv_usec;
429 _dbus_verbose (" timeout expires in %d milliseconds\n", *timeout);
432 return *timeout == 0;
436 _dbus_loop_dispatch (DBusLoop *loop)
440 _dbus_verbose (" %d connections to dispatch\n", _dbus_list_get_length (&loop->need_dispatch));
443 if (loop->need_dispatch == NULL)
447 while (loop->need_dispatch != NULL)
449 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
453 DBusDispatchStatus status;
455 status = dbus_connection_dispatch (connection);
457 if (status == DBUS_DISPATCH_COMPLETE)
459 dbus_connection_unref (connection);
464 if (status == DBUS_DISPATCH_NEED_MEMORY)
465 _dbus_wait_for_memory ();
474 _dbus_loop_queue_dispatch (DBusLoop *loop,
475 DBusConnection *connection)
477 if (_dbus_list_append (&loop->need_dispatch, connection))
479 dbus_connection_ref (connection);
486 /* Returns TRUE if we invoked any timeouts or have ready file
487 * descriptors, which is just used in test code as a debug hack
491 _dbus_loop_iterate (DBusLoop *loop,
494 #define N_STACK_DESCRIPTORS 64
497 DBusPollFD stack_fds[N_STACK_DESCRIPTORS];
499 WatchCallback **watches_for_fds;
500 WatchCallback *stack_watches_for_fds[N_STACK_DESCRIPTORS];
506 dbus_bool_t oom_watch_pending;
512 watches_for_fds = NULL;
514 oom_watch_pending = FALSE;
515 orig_depth = loop->depth;
518 _dbus_verbose ("Iteration block=%d depth=%d timeout_count=%d watch_count=%d\n",
519 block, loop->depth, loop->timeout_count, loop->watch_count);
522 if (loop->callbacks == NULL)
525 if (loop->watch_count > N_STACK_DESCRIPTORS)
527 fds = dbus_new0 (DBusPollFD, loop->watch_count);
531 _dbus_wait_for_memory ();
532 fds = dbus_new0 (DBusPollFD, loop->watch_count);
535 watches_for_fds = dbus_new (WatchCallback*, loop->watch_count);
536 while (watches_for_fds == NULL)
538 _dbus_wait_for_memory ();
539 watches_for_fds = dbus_new (WatchCallback*, loop->watch_count);
545 watches_for_fds = stack_watches_for_fds;
548 /* fill our array of fds and watches */
550 link = _dbus_list_get_first_link (&loop->callbacks);
553 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
554 Callback *cb = link->data;
555 if (cb->type == CALLBACK_WATCH)
558 WatchCallback *wcb = WATCH_CALLBACK (cb);
560 if (wcb->last_iteration_oom)
562 /* we skip this one this time, but reenable it next time,
563 * and have a timeout on this iteration
565 wcb->last_iteration_oom = FALSE;
566 oom_watch_pending = TRUE;
568 retval = TRUE; /* return TRUE here to keep the loop going,
569 * since we don't know the watch is inactive
573 _dbus_verbose (" skipping watch on fd %d as it was out of memory last time\n",
574 dbus_watch_get_fd (wcb->watch));
577 else if (dbus_watch_get_enabled (wcb->watch))
579 watches_for_fds[n_fds] = wcb;
583 flags = dbus_watch_get_flags (wcb->watch);
585 fds[n_fds].fd = dbus_watch_get_fd (wcb->watch);
586 fds[n_fds].revents = 0;
587 fds[n_fds].events = 0;
588 if (flags & DBUS_WATCH_READABLE)
589 fds[n_fds].events |= _DBUS_POLLIN;
590 if (flags & DBUS_WATCH_WRITABLE)
591 fds[n_fds].events |= _DBUS_POLLOUT;
594 _dbus_verbose (" polling watch on fd %d\n", fds[n_fds].fd);
602 _dbus_verbose (" skipping disabled watch on fd %d\n",
603 dbus_watch_get_fd (wcb->watch));
612 if (loop->timeout_count > 0)
614 unsigned long tv_sec;
615 unsigned long tv_usec;
617 _dbus_get_current_time (&tv_sec, &tv_usec);
619 link = _dbus_list_get_first_link (&loop->callbacks);
622 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
623 Callback *cb = link->data;
625 if (cb->type == CALLBACK_TIMEOUT &&
626 dbus_timeout_get_enabled (TIMEOUT_CALLBACK (cb)->timeout))
628 TimeoutCallback *tcb = TIMEOUT_CALLBACK (cb);
631 check_timeout (tv_sec, tv_usec, tcb, &msecs_remaining);
634 timeout = msecs_remaining;
636 timeout = MIN (msecs_remaining, timeout);
639 _dbus_verbose (" timeout added, %d remaining, aggregate timeout %d\n",
640 msecs_remaining, timeout);
643 _dbus_assert (timeout >= 0);
646 break; /* it's not going to get shorter... */
649 else if (cb->type == CALLBACK_TIMEOUT)
651 _dbus_verbose (" skipping disabled timeout\n");
659 /* Never block if we have stuff to dispatch */
660 if (!block || loop->need_dispatch != NULL)
664 _dbus_verbose (" timeout is 0 as we aren't blocking\n");
668 /* if a watch is OOM, don't wait longer than the OOM
669 * wait to re-enable it
671 if (oom_watch_pending)
672 timeout = MIN (timeout, _dbus_get_oom_wait ());
675 _dbus_verbose (" polling on %d descriptors timeout %ld\n", n_fds, timeout);
678 n_ready = _dbus_poll (fds, n_fds, timeout);
680 initial_serial = loop->callback_list_serial;
682 if (loop->timeout_count > 0)
684 unsigned long tv_sec;
685 unsigned long tv_usec;
687 _dbus_get_current_time (&tv_sec, &tv_usec);
689 /* It'd be nice to avoid this O(n) thingy here */
690 link = _dbus_list_get_first_link (&loop->callbacks);
693 DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
694 Callback *cb = link->data;
696 if (initial_serial != loop->callback_list_serial)
699 if (loop->depth != orig_depth)
702 if (cb->type == CALLBACK_TIMEOUT &&
703 dbus_timeout_get_enabled (TIMEOUT_CALLBACK (cb)->timeout))
705 TimeoutCallback *tcb = TIMEOUT_CALLBACK (cb);
708 if (check_timeout (tv_sec, tv_usec,
709 tcb, &msecs_remaining))
711 /* Save last callback time and fire this timeout */
712 tcb->last_tv_sec = tv_sec;
713 tcb->last_tv_usec = tv_usec;
716 _dbus_verbose (" invoking timeout\n");
719 (* tcb->function) (tcb->timeout,
727 _dbus_verbose (" timeout has not expired\n");
732 else if (cb->type == CALLBACK_TIMEOUT)
734 _dbus_verbose (" skipping invocation of disabled timeout\n");
747 /* FIXME I think this "restart if we change the watches"
748 * approach could result in starving watches
749 * toward the end of the list.
751 if (initial_serial != loop->callback_list_serial)
754 if (loop->depth != orig_depth)
757 if (fds[i].revents != 0)
760 unsigned int condition;
762 wcb = watches_for_fds[i];
765 if (fds[i].revents & _DBUS_POLLIN)
766 condition |= DBUS_WATCH_READABLE;
767 if (fds[i].revents & _DBUS_POLLOUT)
768 condition |= DBUS_WATCH_WRITABLE;
769 if (fds[i].revents & _DBUS_POLLHUP)
770 condition |= DBUS_WATCH_HANGUP;
771 if (fds[i].revents & _DBUS_POLLERR)
772 condition |= DBUS_WATCH_ERROR;
774 /* condition may still be 0 if we got some
775 * weird POLLFOO thing like POLLWRBAND
778 if (condition != 0 &&
779 dbus_watch_get_enabled (wcb->watch))
781 if (!(* wcb->function) (wcb->watch,
783 ((Callback*)wcb)->data))
784 wcb->last_iteration_oom = TRUE;
787 _dbus_verbose (" Invoked watch, oom = %d\n",
788 wcb->last_iteration_oom);
801 _dbus_verbose (" moving to next iteration\n");
804 if (fds && fds != stack_fds)
811 callback_unref (&watches_for_fds[i]->callback);
815 if (watches_for_fds != stack_watches_for_fds)
816 dbus_free (watches_for_fds);
819 if (_dbus_loop_dispatch (loop))
823 _dbus_verbose ("Returning %d\n", retval);
830 _dbus_loop_run (DBusLoop *loop)
834 _dbus_assert (loop->depth >= 0);
836 _dbus_loop_ref (loop);
838 our_exit_depth = loop->depth;
841 _dbus_verbose ("Running main loop, depth %d -> %d\n",
842 loop->depth - 1, loop->depth);
844 while (loop->depth != our_exit_depth)
845 _dbus_loop_iterate (loop, TRUE);
847 _dbus_loop_unref (loop);
851 _dbus_loop_quit (DBusLoop *loop)
853 _dbus_assert (loop->depth > 0);
857 _dbus_verbose ("Quit main loop, depth %d -> %d\n",
858 loop->depth + 1, loop->depth);
862 _dbus_get_oom_wait (void)
864 #ifdef DBUS_BUILD_TESTS
865 /* make tests go fast */
873 _dbus_wait_for_memory (void)
875 _dbus_verbose ("Waiting for more memory\n");
876 _dbus_sleep_milliseconds (_dbus_get_oom_wait ());