2003-04-25 Havoc Pennington <hp@redhat.com>
[platform/upstream/dbus.git] / dbus / dbus-mainloop.c
index 721eedf..6019188 100644 (file)
@@ -26,6 +26,8 @@
 #include <dbus/dbus-list.h>
 #include <dbus/dbus-sysdeps.h>
 
+#define MAINLOOP_SPEW 1
+
 struct DBusLoop
 {
   int refcount;
@@ -45,6 +47,7 @@ typedef enum
 
 typedef struct
 {
+  int refcount;
   CallbackType type;
   void *data;
   DBusFreeFunction free_data_func;
@@ -72,10 +75,10 @@ typedef struct
 #define TIMEOUT_CALLBACK(callback) ((TimeoutCallback*)callback)
 
 static WatchCallback*
-watch_callback_new (DBusWatch        *watch,
+watch_callback_new (DBusWatch         *watch,
                     DBusWatchFunction  function,
-                    void             *data,
-                    DBusFreeFunction  free_data_func)
+                    void              *data,
+                    DBusFreeFunction   free_data_func)
 {
   WatchCallback *cb;
 
@@ -86,18 +89,19 @@ watch_callback_new (DBusWatch        *watch,
   cb->watch = watch;
   cb->function = function;
   cb->last_iteration_oom = FALSE;
+  cb->callback.refcount = 1;
   cb->callback.type = CALLBACK_WATCH;
   cb->callback.data = data;
   cb->callback.free_data_func = free_data_func;
-
+  
   return cb;
 }
 
 static TimeoutCallback*
-timeout_callback_new (DBusTimeout        *timeout,
+timeout_callback_new (DBusTimeout         *timeout,
                       DBusTimeoutFunction  function,
-                      void               *data,
-                      DBusFreeFunction    free_data_func)
+                      void                *data,
+                      DBusFreeFunction     free_data_func)
 {
   TimeoutCallback *cb;
 
@@ -109,6 +113,7 @@ timeout_callback_new (DBusTimeout        *timeout,
   cb->function = function;
   _dbus_get_current_time (&cb->last_tv_sec,
                           &cb->last_tv_usec);
+  cb->callback.refcount = 1;    
   cb->callback.type = CALLBACK_TIMEOUT;
   cb->callback.data = data;
   cb->callback.free_data_func = free_data_func;
@@ -117,12 +122,27 @@ timeout_callback_new (DBusTimeout        *timeout,
 }
 
 static void
-callback_free (Callback *cb)
+callback_ref (Callback *cb)
+{
+  _dbus_assert (cb->refcount > 0);
+  
+  cb->refcount += 1;
+}
+
+static void
+callback_unref (Callback *cb)
 {
-  if (cb->free_data_func)
-    (* cb->free_data_func) (cb->data);
+  _dbus_assert (cb->refcount > 0);
 
-  dbus_free (cb);
+  cb->refcount -= 1;
+
+  if (cb->refcount == 0)
+    {
+      if (cb->free_data_func)
+        (* cb->free_data_func) (cb->data);
+      
+      dbus_free (cb);
+    }
 }
 
 static dbus_bool_t
@@ -163,7 +183,7 @@ remove_callback (DBusLoop  *loop,
       break;
     }
   
-  callback_free (cb);
+  callback_unref (cb);
   _dbus_list_remove_link (&loop->callbacks, link);
   loop->callback_list_serial += 1;
 }
@@ -227,7 +247,7 @@ _dbus_loop_add_watch (DBusLoop          *loop,
   if (!add_callback (loop, (Callback*) wcb))
     {
       wcb->callback.free_data_func = NULL; /* don't want to have this side effect */
-      callback_free ((Callback*) wcb);
+      callback_unref ((Callback*) wcb);
       return FALSE;
     }
   
@@ -281,7 +301,7 @@ _dbus_loop_add_timeout (DBusLoop            *loop,
   if (!add_callback (loop, (Callback*) tcb))
     {
       tcb->callback.free_data_func = NULL; /* don't want to have this side effect */
-      callback_free ((Callback*) tcb);
+      callback_unref ((Callback*) tcb);
       return FALSE;
     }
   
@@ -336,10 +356,12 @@ check_timeout (unsigned long    tv_sec,
   long interval_milliseconds;
   int interval;
 
+  /* I'm pretty sure this function could suck (a lot) less */
+  
   interval = dbus_timeout_get_interval (tcb->timeout);
   
-  interval_seconds = interval / 1000;
-  interval_milliseconds = interval - interval_seconds * 1000;
+  interval_seconds = interval / 1000L;
+  interval_milliseconds = interval % 1000L;
   
   expiration_tv_sec = tcb->last_tv_sec + interval_seconds;
   expiration_tv_usec = tcb->last_tv_usec + interval_milliseconds * 1000;
@@ -348,44 +370,35 @@ check_timeout (unsigned long    tv_sec,
       expiration_tv_usec -= 1000000;
       expiration_tv_sec += 1;
     }
-
-  if (expiration_tv_sec < tv_sec ||
-      (expiration_tv_sec == tv_sec && expiration_tv_usec < tv_usec))
-    {
-      _dbus_verbose ("System clock went backward interval_seconds %ld interval_msecs %ld last_tv_sec %lu last_tv_usec %lu tv_sec %lu tv_usec %lu\n",
-                     interval_seconds, interval_milliseconds,
-                     tcb->last_tv_sec, tcb->last_tv_usec, tv_sec, tv_usec);
-          
-      /* The system time has been set backwards, reset the timeout to "interval" in the future */  
-      
-      tcb->last_tv_sec = tv_sec;
-      tcb->last_tv_usec = tv_usec;
-
-      *timeout = interval;
-
-      return FALSE;
-    }
   
   sec_remaining = expiration_tv_sec - tv_sec;
-  msec_remaining = (expiration_tv_usec - tv_usec) / 1000;
-
-#if 0
-  printf ("Interval is %ld seconds %ld msecs\n",
-          interval_seconds,
-          interval_milliseconds);
-  printf ("Now is %lu seconds %lu usecs\n",
-          tv_sec, tv_usec);
-  printf ("Exp is %lu seconds %lu usecs\n",
-          expiration_tv_sec, expiration_tv_usec);
-  printf ("Pre-correction, remaining sec_remaining %ld msec_remaining %ld\n", sec_remaining, msec_remaining);
+  /* need to force this to be signed, as it is intended to sometimes
+   * produce a negative result
+   */
+  msec_remaining = ((long) expiration_tv_usec - (long) tv_usec) / 1000L;
+
+#if MAINLOOP_SPEW
+  _dbus_verbose ("Interval is %ld seconds %ld msecs\n",
+                 interval_seconds,
+                 interval_milliseconds);
+  _dbus_verbose ("Now is  %lu seconds %lu usecs\n",
+                 tv_sec, tv_usec);
+  _dbus_verbose ("Last is %lu seconds %lu usecs\n",
+                 tcb->last_tv_sec, tcb->last_tv_usec);
+  _dbus_verbose ("Exp is  %lu seconds %lu usecs\n",
+                 expiration_tv_sec, expiration_tv_usec);
+  _dbus_verbose ("Pre-correction, sec_remaining %ld msec_remaining %ld\n",
+                 sec_remaining, msec_remaining);
 #endif
   
   /* We do the following in a rather convoluted fashion to deal with
    * the fact that we don't have an integral type big enough to hold
-   * the difference of two timevals in millseconds.
+   * the difference of two timevals in milliseconds.
    */
   if (sec_remaining < 0 || (sec_remaining == 0 && msec_remaining < 0))
-    msec_remaining = 0;
+    {
+      *timeout = 0;
+    }
   else
     {
       if (msec_remaining < 0)
@@ -394,30 +407,47 @@ check_timeout (unsigned long    tv_sec,
          sec_remaining -= 1;
        }
 
-      if (msec_remaining > _DBUS_INT_MAX)
-        {
-          /* Not going to fit in a 32-bit integer */
-          msec_remaining = _DBUS_INT_MAX;
-        }
+      if (sec_remaining > (_DBUS_INT_MAX / 1000) ||
+          msec_remaining > _DBUS_INT_MAX)
+        *timeout = _DBUS_INT_MAX;
+      else
+        *timeout = sec_remaining * 1000 + msec_remaining;        
     }
 
-  *timeout = msec_remaining;
+  if (*timeout > interval)
+    {
+      /* This indicates that the system clock probably moved backward */
+      _dbus_verbose ("System clock set backward! Resetting timeout.\n");
+      
+      tcb->last_tv_sec = tv_sec;
+      tcb->last_tv_usec = tv_usec;
 
-#if 0
-  printf ("Timeout expires in %d milliseconds\n", *timeout);
+      *timeout = interval;
+    }
+  
+#if MAINLOOP_SPEW
+  _dbus_verbose ("  timeout expires in %d milliseconds\n", *timeout);
 #endif
   
-  return msec_remaining == 0;
+  return *timeout == 0;
 }
 
-static void
+dbus_bool_t
 _dbus_loop_dispatch (DBusLoop *loop)
 {
+
+#if MAINLOOP_SPEW
+  _dbus_verbose ("  %d connections to dispatch\n", _dbus_list_get_length (&loop->need_dispatch));
+#endif
+  
+  if (loop->need_dispatch == NULL)
+    return FALSE;
+  
  next:
   while (loop->need_dispatch != NULL)
     {
       DBusConnection *connection = _dbus_list_pop_first (&loop->need_dispatch);
-
+      
       while (TRUE)
         {
           DBusDispatchStatus status;
@@ -436,13 +466,14 @@ _dbus_loop_dispatch (DBusLoop *loop)
             }
         }
     }
+
+  return TRUE;
 }
 
 dbus_bool_t
 _dbus_loop_queue_dispatch (DBusLoop       *loop,
                            DBusConnection *connection)
 {
-  
   if (_dbus_list_append (&loop->need_dispatch, connection))
     {
       dbus_connection_ref (connection);
@@ -459,11 +490,14 @@ _dbus_loop_queue_dispatch (DBusLoop       *loop,
 dbus_bool_t
 _dbus_loop_iterate (DBusLoop     *loop,
                     dbus_bool_t   block)
-{
+{  
+#define N_STACK_DESCRIPTORS 64
   dbus_bool_t retval;
   DBusPollFD *fds;
+  DBusPollFD stack_fds[N_STACK_DESCRIPTORS];
   int n_fds;
   WatchCallback **watches_for_fds;
+  WatchCallback *stack_watches_for_fds[N_STACK_DESCRIPTORS];
   int i;
   DBusList *link;
   int n_ready;
@@ -472,25 +506,46 @@ _dbus_loop_iterate (DBusLoop     *loop,
   dbus_bool_t oom_watch_pending;
   int orig_depth;
   
-  retval = FALSE;
-      
+  retval = FALSE;      
+
   fds = NULL;
   watches_for_fds = NULL;
+  n_fds = 0;
   oom_watch_pending = FALSE;
   orig_depth = loop->depth;
   
-#if 0
-  _dbus_verbose (" iterate %d timeouts %d watches\n",
-                 loop->timeout_count, loop->watch_count);
+#if MAINLOOP_SPEW
+  _dbus_verbose ("Iteration block=%d depth=%d timeout_count=%d watch_count=%d\n",
+                 block, loop->depth, loop->timeout_count, loop->watch_count);
 #endif
   
   if (loop->callbacks == NULL)
+    goto next_iteration;
+
+  if (loop->watch_count > N_STACK_DESCRIPTORS)
     {
-      _dbus_loop_quit (loop);
-      goto next_iteration;
+      fds = dbus_new0 (DBusPollFD, loop->watch_count);
+      
+      while (fds == NULL)
+        {
+          _dbus_wait_for_memory ();
+          fds = dbus_new0 (DBusPollFD, loop->watch_count);
+        }
+      
+      watches_for_fds = dbus_new (WatchCallback*, loop->watch_count);
+      while (watches_for_fds == NULL)
+        {
+          _dbus_wait_for_memory ();
+          watches_for_fds = dbus_new (WatchCallback*, loop->watch_count);
+        }
+    }
+  else
+    {      
+      fds = stack_fds;
+      watches_for_fds = stack_watches_for_fds;
     }
 
-  /* count enabled watches */
+  /* fill our array of fds and watches */
   n_fds = 0;
   link = _dbus_list_get_first_link (&loop->callbacks);
   while (link != NULL)
@@ -499,81 +554,65 @@ _dbus_loop_iterate (DBusLoop     *loop,
       Callback *cb = link->data;
       if (cb->type == CALLBACK_WATCH)
         {
+          unsigned int flags;
           WatchCallback *wcb = WATCH_CALLBACK (cb);
 
-          if (!wcb->last_iteration_oom &&
-              dbus_watch_get_enabled (wcb->watch))
-            ++n_fds;
-        }
-      
-      link = next;
-    }
+          if (wcb->last_iteration_oom)
+            {
+              /* we skip this one this time, but reenable it next time,
+               * and have a timeout on this iteration
+               */
+              wcb->last_iteration_oom = FALSE;
+              oom_watch_pending = TRUE;
+              
+              retval = TRUE; /* return TRUE here to keep the loop going,
+                              * since we don't know the watch is inactive
+                              */
 
-  /* fill our array of fds and watches */
-  if (n_fds > 0)
-    {
-      fds = dbus_new0 (DBusPollFD, n_fds);
-      while (fds == NULL)
-        {
-          _dbus_wait_for_memory ();
-          fds = dbus_new0 (DBusPollFD, n_fds);
-        }
-          
-      watches_for_fds = dbus_new (WatchCallback*, n_fds);
-      while (watches_for_fds == NULL)
-        {
-          _dbus_wait_for_memory ();
-          watches_for_fds = dbus_new (WatchCallback*, n_fds);
-        }
-      
-      i = 0;
-      link = _dbus_list_get_first_link (&loop->callbacks);
-      while (link != NULL)
-        {
-          DBusList *next = _dbus_list_get_next_link (&loop->callbacks, link);
-          Callback *cb = link->data;
-          if (cb->type == CALLBACK_WATCH)
+#if MAINLOOP_SPEW
+              _dbus_verbose ("  skipping watch on fd %d as it was out of memory last time\n",
+                             dbus_watch_get_fd (wcb->watch));
+#endif
+            }
+          else if (dbus_watch_get_enabled (wcb->watch))
             {
-              unsigned int flags;
-              WatchCallback *wcb = WATCH_CALLBACK (cb);
+              watches_for_fds[n_fds] = wcb;
 
-              if (wcb->last_iteration_oom)
-                {
-                  /* we skip this one this time, but reenable it next time,
-                   * and have a timeout on this iteration
-                   */
-                  wcb->last_iteration_oom = FALSE;
-                  oom_watch_pending = TRUE;
-                }
-              else if (dbus_watch_get_enabled (wcb->watch))
-                {
-                  watches_for_fds[i] = wcb;
+              callback_ref (cb);
                   
-                  flags = dbus_watch_get_flags (wcb->watch);
+              flags = dbus_watch_get_flags (wcb->watch);
                   
-                  fds[i].fd = dbus_watch_get_fd (wcb->watch);
-                  if (flags & DBUS_WATCH_READABLE)
-                    fds[i].events |= _DBUS_POLLIN;
-                  if (flags & DBUS_WATCH_WRITABLE)
-                    fds[i].events |= _DBUS_POLLOUT;
+              fds[n_fds].fd = dbus_watch_get_fd (wcb->watch);
+              fds[n_fds].revents = 0;
+              fds[n_fds].events = 0;
+              if (flags & DBUS_WATCH_READABLE)
+                fds[n_fds].events |= _DBUS_POLLIN;
+              if (flags & DBUS_WATCH_WRITABLE)
+                fds[n_fds].events |= _DBUS_POLLOUT;
+
+#if MAINLOOP_SPEW
+              _dbus_verbose ("  polling watch on fd %d\n", fds[n_fds].fd);
+#endif
 
-                  ++i;
-                }
+              n_fds += 1;
+            }
+          else
+            {
+#if MAINLOOP_SPEW
+              _dbus_verbose ("  skipping disabled watch on fd %d\n",
+                             dbus_watch_get_fd (wcb->watch));
+#endif
             }
-              
-          link = next;
         }
-
-      _dbus_assert (i == n_fds);
+              
+      link = next;
     }
-
+  
   timeout = -1;
   if (loop->timeout_count > 0)
     {
       unsigned long tv_sec;
       unsigned long tv_usec;
-
-      retval = TRUE;
       
       _dbus_get_current_time (&tv_sec, &tv_usec);
           
@@ -610,8 +649,8 @@ _dbus_loop_iterate (DBusLoop     *loop,
   if (!block || loop->need_dispatch != NULL)
     {
       timeout = 0;
-#if 0
-      printf ("timeout is 0 as we aren't blocking\n");
+#if MAINLOOP_SPEW
+      _dbus_verbose ("  timeout is 0 as we aren't blocking\n");
 #endif
     }
 
@@ -620,6 +659,10 @@ _dbus_loop_iterate (DBusLoop     *loop,
    */
   if (oom_watch_pending)
     timeout = MIN (timeout, _dbus_get_oom_wait ());
+
+#if MAINLOOP_SPEW
+  _dbus_verbose ("  polling on %d descriptors timeout %ld\n", n_fds, timeout);
+#endif
   
   n_ready = _dbus_poll (fds, n_fds, timeout);
 
@@ -658,12 +701,20 @@ _dbus_loop_iterate (DBusLoop     *loop,
                   tcb->last_tv_sec = tv_sec;
                   tcb->last_tv_usec = tv_usec;
 
-#if 0
-                  printf ("  invoking timeout\n");
+#if MAINLOOP_SPEW
+                  _dbus_verbose ("  invoking timeout\n");
 #endif
                   
                   (* tcb->function) (tcb->timeout,
                                      cb->data);
+
+                  retval = TRUE;
+                }
+              else
+                {
+#if MAINLOOP_SPEW
+                  _dbus_verbose ("  timeout has not expired\n");
+#endif
                 }
             }
 
@@ -692,7 +743,7 @@ _dbus_loop_iterate (DBusLoop     *loop,
               unsigned int condition;
                   
               wcb = watches_for_fds[i];
-                  
+              
               condition = 0;
               if (fds[i].revents & _DBUS_POLLIN)
                 condition |= DBUS_WATCH_READABLE;
@@ -715,6 +766,11 @@ _dbus_loop_iterate (DBusLoop     *loop,
                                           ((Callback*)wcb)->data))
                     wcb->last_iteration_oom = TRUE;
 
+#if MAINLOOP_SPEW
+                  _dbus_verbose ("  Invoked watch, oom = %d\n",
+                                 wcb->last_iteration_oom);
+#endif
+                  
                   retval = TRUE;
                 }
             }
@@ -724,15 +780,28 @@ _dbus_loop_iterate (DBusLoop     *loop,
     }
       
  next_iteration:
-  dbus_free (fds);
-  dbus_free (watches_for_fds);
-
-  if (loop->need_dispatch != NULL)
+  if (fds && fds != stack_fds)
+    dbus_free (fds);
+  if (watches_for_fds)
     {
-      retval = TRUE;
-      _dbus_loop_dispatch (loop);
+      i = 0;
+      while (i < n_fds)
+        {
+          callback_unref (&watches_for_fds[i]->callback);
+          ++i;
+        }
+      
+      if (watches_for_fds != stack_watches_for_fds)
+        dbus_free (watches_for_fds);
     }
   
+  if (_dbus_loop_dispatch (loop))
+    retval = TRUE;
+  
+#if MAINLOOP_SPEW
+  _dbus_verbose ("Returning %d\n", retval);
+#endif
+  
   return retval;
 }
 
@@ -741,10 +810,15 @@ _dbus_loop_run (DBusLoop *loop)
 {
   int our_exit_depth;
 
+  _dbus_assert (loop->depth >= 0);
+  
   _dbus_loop_ref (loop);
   
   our_exit_depth = loop->depth;
   loop->depth += 1;
+
+  _dbus_verbose ("Running main loop, depth %d -> %d\n",
+                 loop->depth - 1, loop->depth);
   
   while (loop->depth != our_exit_depth)
     _dbus_loop_iterate (loop, TRUE);
@@ -755,9 +829,12 @@ _dbus_loop_run (DBusLoop *loop)
 void
 _dbus_loop_quit (DBusLoop *loop)
 {
-  _dbus_assert (loop->depth > 0);
+  _dbus_assert (loop->depth > 0);  
   
   loop->depth -= 1;
+
+  _dbus_verbose ("Quit main loop, depth %d -> %d\n",
+                 loop->depth + 1, loop->depth);
 }
 
 int
@@ -774,6 +851,7 @@ _dbus_get_oom_wait (void)
 void
 _dbus_wait_for_memory (void)
 {
+  _dbus_verbose ("Waiting for more memory\n");
   _dbus_sleep_milliseconds (_dbus_get_oom_wait ());
 }