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-hash.h>
30 #include <dbus/dbus-list.h>
31 #include <dbus/dbus-sysdeps.h>
32 #include <dbus/dbus-watch.h>
34 #define MAINLOOP_SPEW 0
37 #ifdef DBUS_ENABLE_VERBOSE_MODE
39 watch_flags_to_string (int flags)
41 const char *watch_type;
43 if ((flags & DBUS_WATCH_READABLE) &&
44 (flags & DBUS_WATCH_WRITABLE))
45 watch_type = "readwrite";
46 else if (flags & DBUS_WATCH_READABLE)
48 else if (flags & DBUS_WATCH_WRITABLE)
51 watch_type = "not read or write";
54 #endif /* DBUS_ENABLE_VERBOSE_MODE */
55 #endif /* MAINLOOP_SPEW */
60 /** fd => dbus_malloc'd DBusList ** of references to DBusWatch */
61 DBusHashTable *watches;
63 int callback_list_serial;
66 int depth; /**< number of recursive runs */
67 DBusList *need_dispatch;
71 watch_flags_to_poll_events (unsigned int flags)
75 if (flags & DBUS_WATCH_READABLE)
76 events |= _DBUS_POLLIN;
77 if (flags & DBUS_WATCH_WRITABLE)
78 events |= _DBUS_POLLOUT;
84 watch_flags_from_poll_revents (short revents)
86 unsigned int condition = 0;
88 if (revents & _DBUS_POLLIN)
89 condition |= DBUS_WATCH_READABLE;
90 if (revents & _DBUS_POLLOUT)
91 condition |= DBUS_WATCH_WRITABLE;
92 if (revents & _DBUS_POLLHUP)
93 condition |= DBUS_WATCH_HANGUP;
94 if (revents & _DBUS_POLLERR)
95 condition |= DBUS_WATCH_ERROR;
103 DBusTimeout *timeout;
104 unsigned long last_tv_sec;
105 unsigned long last_tv_usec;
108 #define TIMEOUT_CALLBACK(callback) ((TimeoutCallback*)callback)
110 static TimeoutCallback*
111 timeout_callback_new (DBusTimeout *timeout)
115 cb = dbus_new (TimeoutCallback, 1);
119 cb->timeout = timeout;
120 _dbus_get_current_time (&cb->last_tv_sec,
126 static TimeoutCallback *
127 timeout_callback_ref (TimeoutCallback *cb)
129 _dbus_assert (cb->refcount > 0);
137 timeout_callback_unref (TimeoutCallback *cb)
139 _dbus_assert (cb->refcount > 0);
143 if (cb->refcount == 0)
150 free_watch_table_entry (void *data)
152 DBusList **watches = data;
155 /* DBusHashTable sometimes calls free_function(NULL) even if you never
156 * have NULL as a value */
160 for (watch = _dbus_list_pop_first (watches);
162 watch = _dbus_list_pop_first (watches))
164 _dbus_watch_unref (watch);
167 _dbus_assert (*watches == NULL);
172 _dbus_loop_new (void)
176 loop = dbus_new0 (DBusLoop, 1);
180 loop->watches = _dbus_hash_table_new (DBUS_HASH_INT, NULL,
181 free_watch_table_entry);
183 if (loop->watches == NULL)
195 _dbus_loop_ref (DBusLoop *loop)
197 _dbus_assert (loop != NULL);
198 _dbus_assert (loop->refcount > 0);
206 _dbus_loop_unref (DBusLoop *loop)
208 _dbus_assert (loop != NULL);
209 _dbus_assert (loop->refcount > 0);
212 if (loop->refcount == 0)
214 while (loop->need_dispatch)
216 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
218 dbus_connection_unref (connection);
221 _dbus_hash_table_unref (loop->watches);
227 ensure_watch_table_entry (DBusLoop *loop,
232 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
236 watches = dbus_new0 (DBusList *, 1);
241 if (!_dbus_hash_table_insert_int (loop->watches, fd, watches))
252 cull_watches_for_invalid_fd (DBusLoop *loop,
259 _dbus_warn ("invalid request, socket fd %d not open\n", fd);
260 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
264 for (link = _dbus_list_get_first_link (watches);
266 link = _dbus_list_get_next_link (watches, link))
267 _dbus_watch_invalidate (link->data);
270 _dbus_hash_table_remove_int (loop->watches, fd);
274 gc_watch_table_entry (DBusLoop *loop,
278 /* If watches is already NULL we have nothing to do */
282 /* We can't GC hash table entries if they're non-empty lists */
283 if (*watches != NULL)
286 _dbus_hash_table_remove_int (loop->watches, fd);
290 _dbus_loop_add_watch (DBusLoop *loop,
296 fd = dbus_watch_get_socket (watch);
297 _dbus_assert (fd != -1);
299 watches = ensure_watch_table_entry (loop, fd);
304 if (_dbus_list_append (watches, _dbus_watch_ref (watch)))
306 loop->callback_list_serial += 1;
307 loop->watch_count += 1;
311 _dbus_watch_unref (watch);
312 gc_watch_table_entry (loop, watches, fd);
321 _dbus_loop_remove_watch (DBusLoop *loop,
328 /* This relies on people removing watches before they invalidate them,
329 * which has been safe since fd.o #33336 was fixed. Assert about it
330 * so we don't regress. */
331 fd = dbus_watch_get_socket (watch);
332 _dbus_assert (fd != -1);
334 watches = _dbus_hash_table_lookup_int (loop->watches, fd);
338 link = _dbus_list_get_first_link (watches);
341 DBusList *next = _dbus_list_get_next_link (watches, link);
342 DBusWatch *this = link->data;
346 _dbus_list_remove_link (watches, link);
347 loop->callback_list_serial += 1;
348 loop->watch_count -= 1;
349 _dbus_watch_unref (this);
351 /* if that was the last watch for that fd, drop the hash table
353 gc_watch_table_entry (loop, watches, fd);
362 _dbus_warn ("could not find watch %p to remove\n", watch);
366 _dbus_loop_add_timeout (DBusLoop *loop,
367 DBusTimeout *timeout)
369 TimeoutCallback *tcb;
371 tcb = timeout_callback_new (timeout);
375 if (_dbus_list_append (&loop->timeouts, tcb))
377 loop->callback_list_serial += 1;
378 loop->timeout_count += 1;
382 timeout_callback_unref (tcb);
390 _dbus_loop_remove_timeout (DBusLoop *loop,
391 DBusTimeout *timeout)
395 link = _dbus_list_get_first_link (&loop->timeouts);
398 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
399 TimeoutCallback *this = link->data;
401 if (this->timeout == timeout)
403 _dbus_list_remove_link (&loop->timeouts, link);
404 loop->callback_list_serial += 1;
405 loop->timeout_count -= 1;
406 timeout_callback_unref (this);
414 _dbus_warn ("could not find timeout %p to remove\n", timeout);
417 /* Convolutions from GLib, there really must be a better way
421 check_timeout (unsigned long tv_sec,
422 unsigned long tv_usec,
423 TimeoutCallback *tcb,
428 unsigned long expiration_tv_sec;
429 unsigned long expiration_tv_usec;
430 long interval_seconds;
431 long interval_milliseconds;
434 /* I'm pretty sure this function could suck (a lot) less */
436 interval = dbus_timeout_get_interval (tcb->timeout);
438 interval_seconds = interval / 1000L;
439 interval_milliseconds = interval % 1000L;
441 expiration_tv_sec = tcb->last_tv_sec + interval_seconds;
442 expiration_tv_usec = tcb->last_tv_usec + interval_milliseconds * 1000;
443 if (expiration_tv_usec >= 1000000)
445 expiration_tv_usec -= 1000000;
446 expiration_tv_sec += 1;
449 sec_remaining = expiration_tv_sec - tv_sec;
450 /* need to force this to be signed, as it is intended to sometimes
451 * produce a negative result
453 msec_remaining = ((long) expiration_tv_usec - (long) tv_usec) / 1000L;
456 _dbus_verbose ("Interval is %ld seconds %ld msecs\n",
458 interval_milliseconds);
459 _dbus_verbose ("Now is %lu seconds %lu usecs\n",
461 _dbus_verbose ("Last is %lu seconds %lu usecs\n",
462 tcb->last_tv_sec, tcb->last_tv_usec);
463 _dbus_verbose ("Exp is %lu seconds %lu usecs\n",
464 expiration_tv_sec, expiration_tv_usec);
465 _dbus_verbose ("Pre-correction, sec_remaining %ld msec_remaining %ld\n",
466 sec_remaining, msec_remaining);
469 /* We do the following in a rather convoluted fashion to deal with
470 * the fact that we don't have an integral type big enough to hold
471 * the difference of two timevals in milliseconds.
473 if (sec_remaining < 0 || (sec_remaining == 0 && msec_remaining < 0))
479 if (msec_remaining < 0)
481 msec_remaining += 1000;
485 if (sec_remaining > (_DBUS_INT_MAX / 1000) ||
486 msec_remaining > _DBUS_INT_MAX)
487 *timeout = _DBUS_INT_MAX;
489 *timeout = sec_remaining * 1000 + msec_remaining;
492 if (*timeout > interval)
494 /* This indicates that the system clock probably moved backward */
495 _dbus_verbose ("System clock set backward! Resetting timeout.\n");
497 tcb->last_tv_sec = tv_sec;
498 tcb->last_tv_usec = tv_usec;
504 _dbus_verbose (" timeout expires in %d milliseconds\n", *timeout);
507 return *timeout == 0;
511 _dbus_loop_dispatch (DBusLoop *loop)
515 _dbus_verbose (" %d connections to dispatch\n", _dbus_list_get_length (&loop->need_dispatch));
518 if (loop->need_dispatch == NULL)
522 while (loop->need_dispatch != NULL)
524 DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
528 DBusDispatchStatus status;
530 status = dbus_connection_dispatch (connection);
532 if (status == DBUS_DISPATCH_COMPLETE)
534 dbus_connection_unref (connection);
539 if (status == DBUS_DISPATCH_NEED_MEMORY)
540 _dbus_wait_for_memory ();
549 _dbus_loop_queue_dispatch (DBusLoop *loop,
550 DBusConnection *connection)
552 if (_dbus_list_append (&loop->need_dispatch, connection))
554 dbus_connection_ref (connection);
561 /* Returns TRUE if we invoked any timeouts or have ready file
562 * descriptors, which is just used in test code as a debug hack
566 _dbus_loop_iterate (DBusLoop *loop,
569 #define N_STACK_DESCRIPTORS 64
572 DBusPollFD stack_fds[N_STACK_DESCRIPTORS];
579 dbus_bool_t oom_watch_pending;
581 DBusHashIter hash_iter;
587 oom_watch_pending = FALSE;
588 orig_depth = loop->depth;
591 _dbus_verbose ("Iteration block=%d depth=%d timeout_count=%d watch_count=%d\n",
592 block, loop->depth, loop->timeout_count, loop->watch_count);
595 if (_dbus_hash_table_get_n_entries (loop->watches) == 0 &&
596 loop->timeouts == NULL)
599 if (loop->watch_count > N_STACK_DESCRIPTORS)
601 fds = dbus_new0 (DBusPollFD, loop->watch_count);
605 _dbus_wait_for_memory ();
606 fds = dbus_new0 (DBusPollFD, loop->watch_count);
614 /* fill our array of fds and watches */
616 _dbus_hash_iter_init (loop->watches, &hash_iter);
618 while (_dbus_hash_iter_next (&hash_iter))
624 fd = _dbus_hash_iter_get_int_key (&hash_iter);
625 watches = _dbus_hash_iter_get_value (&hash_iter);
628 for (link = _dbus_list_get_first_link (watches);
630 link = _dbus_list_get_next_link (watches, link))
632 DBusWatch *watch = link->data;
634 if (_dbus_watch_get_oom_last_time (watch))
636 /* we skip this one this time, but reenable it next time,
637 * and have a timeout on this iteration
639 _dbus_watch_set_oom_last_time (watch, FALSE);
640 oom_watch_pending = TRUE;
642 retval = TRUE; /* return TRUE here to keep the loop going,
643 * since we don't know the watch is inactive
647 _dbus_verbose (" skipping watch on fd %d as it was out of memory last time\n",
651 else if (dbus_watch_get_enabled (watch))
653 flags |= dbus_watch_get_flags (watch);
660 fds[n_fds].revents = 0;
661 fds[n_fds].events = watch_flags_to_poll_events (flags);
664 _dbus_verbose (" polling watch on fd %d %s\n",
665 loop->fds[loop->n_fds].fd, watch_flags_to_string (flags));
673 _dbus_verbose (" skipping disabled watch on fd %d %s\n",
675 watch_flags_to_string (dbus_watch_get_flags (watch)));
681 if (loop->timeout_count > 0)
683 unsigned long tv_sec;
684 unsigned long tv_usec;
686 _dbus_get_current_time (&tv_sec, &tv_usec);
688 link = _dbus_list_get_first_link (&loop->timeouts);
691 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
692 TimeoutCallback *tcb = link->data;
694 if (dbus_timeout_get_enabled (tcb->timeout))
698 check_timeout (tv_sec, tv_usec, tcb, &msecs_remaining);
701 timeout = msecs_remaining;
703 timeout = MIN (msecs_remaining, timeout);
706 _dbus_verbose (" timeout added, %d remaining, aggregate timeout %ld\n",
707 msecs_remaining, timeout);
710 _dbus_assert (timeout >= 0);
713 break; /* it's not going to get shorter... */
718 _dbus_verbose (" skipping disabled timeout\n");
726 /* Never block if we have stuff to dispatch */
727 if (!block || loop->need_dispatch != NULL)
731 _dbus_verbose (" timeout is 0 as we aren't blocking\n");
735 /* if a watch is OOM, don't wait longer than the OOM
736 * wait to re-enable it
738 if (oom_watch_pending)
739 timeout = MIN (timeout, _dbus_get_oom_wait ());
742 _dbus_verbose (" polling on %d descriptors timeout %ld\n", n_fds, timeout);
745 n_ready = _dbus_poll (fds, n_fds, timeout);
747 initial_serial = loop->callback_list_serial;
749 if (loop->timeout_count > 0)
751 unsigned long tv_sec;
752 unsigned long tv_usec;
754 _dbus_get_current_time (&tv_sec, &tv_usec);
756 /* It'd be nice to avoid this O(n) thingy here */
757 link = _dbus_list_get_first_link (&loop->timeouts);
760 DBusList *next = _dbus_list_get_next_link (&loop->timeouts, link);
761 TimeoutCallback *tcb = link->data;
763 if (initial_serial != loop->callback_list_serial)
766 if (loop->depth != orig_depth)
769 if (dbus_timeout_get_enabled (tcb->timeout))
773 if (check_timeout (tv_sec, tv_usec,
774 tcb, &msecs_remaining))
776 /* Save last callback time and fire this timeout */
777 tcb->last_tv_sec = tv_sec;
778 tcb->last_tv_usec = tv_usec;
781 _dbus_verbose (" invoking timeout\n");
784 /* can theoretically return FALSE on OOM, but we just
785 * let it fire again later - in practice that's what
786 * every wrapper callback in dbus-daemon used to do */
787 dbus_timeout_handle (tcb->timeout);
794 _dbus_verbose (" timeout has not expired\n");
801 _dbus_verbose (" skipping invocation of disabled timeout\n");
811 for (i = 0; i < n_fds; i++)
815 unsigned int condition;
817 /* FIXME I think this "restart if we change the watches"
818 * approach could result in starving watches
819 * toward the end of the list.
821 if (initial_serial != loop->callback_list_serial)
824 if (loop->depth != orig_depth)
827 if (fds[i].revents == 0)
830 if (_DBUS_UNLIKELY (fds[i].revents & _DBUS_POLLNVAL))
832 cull_watches_for_invalid_fd (loop, fds[i].fd);
836 condition = watch_flags_from_poll_revents (fds[i].revents);
838 /* condition may still be 0 if we got some
839 * weird POLLFOO thing like POLLWRBAND
844 watches = _dbus_hash_table_lookup_int (loop->watches, fds[i].fd);
849 for (link = _dbus_list_get_first_link (watches);
853 DBusWatch *watch = link->data;
855 next = _dbus_list_get_next_link (watches, link);
857 if (dbus_watch_get_enabled (watch))
861 oom = !dbus_watch_handle (watch, condition);
865 _dbus_watch_set_oom_last_time (watch, TRUE);
869 _dbus_verbose (" Invoked watch, oom = %d\n", oom);
873 /* We re-check this every time, in case the callback
874 * added/removed watches, which might make our position in
875 * the linked list invalid. See the FIXME above. */
876 if (initial_serial != loop->callback_list_serial)
879 if (loop->depth != orig_depth)
888 _dbus_verbose (" moving to next iteration\n");
891 if (fds && fds != stack_fds)
894 if (_dbus_loop_dispatch (loop))
898 _dbus_verbose ("Returning %d\n", retval);
905 _dbus_loop_run (DBusLoop *loop)
909 _dbus_assert (loop->depth >= 0);
911 _dbus_loop_ref (loop);
913 our_exit_depth = loop->depth;
916 _dbus_verbose ("Running main loop, depth %d -> %d\n",
917 loop->depth - 1, loop->depth);
919 while (loop->depth != our_exit_depth)
920 _dbus_loop_iterate (loop, TRUE);
922 _dbus_loop_unref (loop);
926 _dbus_loop_quit (DBusLoop *loop)
928 _dbus_assert (loop->depth > 0);
932 _dbus_verbose ("Quit main loop, depth %d -> %d\n",
933 loop->depth + 1, loop->depth);
937 _dbus_get_oom_wait (void)
939 #ifdef DBUS_BUILD_TESTS
940 /* make tests go fast */
948 _dbus_wait_for_memory (void)
950 _dbus_verbose ("Waiting for more memory\n");
951 _dbus_sleep_milliseconds (_dbus_get_oom_wait ());
954 #endif /* !DOXYGEN_SHOULD_SKIP_THIS */