GDBusConnection: make the closed flag atomic (but still lock to write)
[platform/upstream/glib.git] / gio / gdbusconnection.c
index 0b80020..1b01624 100644 (file)
@@ -329,7 +329,9 @@ _g_strv_has_string (const gchar* const *haystack,
 
 /* Flags in connection->atomic_flags */
 enum {
-    FLAG_INITIALIZED = 1 << 0
+    FLAG_INITIALIZED = 1 << 0,
+    FLAG_EXIT_ON_CLOSE = 1 << 1,
+    FLAG_CLOSED = 1 << 2
 };
 
 /**
@@ -349,16 +351,18 @@ struct _GDBusConnection
   /* -- General object state ------------------------------------------------ */
   /* ------------------------------------------------------------------------ */
 
-  /* object-wide lock */
+  /* General-purpose lock for most fields */
   GMutex lock;
 
   /* A lock used in the init() method of the GInitable interface - see comments
-   * in initable_init() for why a separate lock is needed
+   * in initable_init() for why a separate lock is needed.
+   *
+   * If you need both @lock and @init_lock, you must take @init_lock first.
    */
   GMutex init_lock;
 
   /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
-   * someone calls org.freedesktop.DBus.GetMachineId()
+   * someone calls org.freedesktop.DBus.GetMachineId(). Protected by @lock.
    */
   gchar *machine_id;
 
@@ -374,10 +378,7 @@ struct _GDBusConnection
    */
   GDBusAuth *auth;
 
-  /* Set to TRUE if the connection has been closed */
-  gboolean closed;
-
-  /* Last serial used */
+  /* Last serial used. Protected by @lock. */
   guint32 last_serial;
 
   /* The object used to send/receive messages.
@@ -402,6 +403,11 @@ struct _GDBusConnection
 
   /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
    * Inspect @initialization_error to see whether it succeeded or failed.
+   *
+   * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
+   *
+   * FLAG_CLOSED is the closed property. It may be read at any time, but
+   * may only be written while holding @lock.
    */
   volatile gint atomic_flags;
 
@@ -415,39 +421,41 @@ struct _GDBusConnection
   /* The result of g_main_context_ref_thread_default() when the object
    * was created (the GObject _init() function) - this is used for delivery
    * of the :closed GObject signal.
+   *
+   * Only set in the GObject init function, so no locks are needed.
    */
   GMainContext *main_context_at_construction;
 
-  /* construct properties */
+  /* Read-only construct properties, no locks needed */
   gchar *address;
   GDBusConnectionFlags flags;
 
-  /* Map used for managing method replies */
+  /* Map used for managing method replies, protected by @lock */
   GHashTable *map_method_serial_to_send_message_data;  /* guint32 -> SendMessageData* */
 
-  /* Maps used for managing signal subscription */
+  /* Maps used for managing signal subscription, protected by @lock */
   GHashTable *map_rule_to_signal_data;                      /* match rule (gchar*)    -> SignalData */
   GHashTable *map_id_to_signal_data;                        /* id (guint)             -> SignalData */
   GHashTable *map_sender_unique_name_to_signal_data_array;  /* unique sender (gchar*) -> GPtrArray* of SignalData */
 
-  /* Maps used for managing exported objects and subtrees */
+  /* Maps used for managing exported objects and subtrees,
+   * protected by @lock
+   */
   GHashTable *map_object_path_to_eo;  /* gchar* -> ExportedObject* */
   GHashTable *map_id_to_ei;           /* guint  -> ExportedInterface* */
   GHashTable *map_object_path_to_es;  /* gchar* -> ExportedSubtree* */
   GHashTable *map_id_to_es;           /* guint  -> ExportedSubtree* */
 
-  /* Structure used for message filters */
+  /* Structure used for message filters, protected by @lock */
   GPtrArray *filters;
 
-  /* Whether to exit on close */
-  gboolean exit_on_close;
-
   /* Capabilities negotiated during authentication
    * Read-only after initable_init(), so it may be read without holding a
    * lock, if you check for initialization first.
    */
   GDBusCapabilityFlags capabilities;
 
+  /* Protected by @init_lock */
   GDBusAuthObserver *authentication_observer;
 
   /* Read-only after initable_init(), so it may be read if you either
@@ -550,6 +558,48 @@ check_initialized (GDBusConnection *connection)
   return TRUE;
 }
 
+typedef enum {
+    MAY_BE_UNINITIALIZED = (1<<1)
+} CheckUnclosedFlags;
+
+/*
+ * Check the same thing as check_initialized(), and also that the
+ * connection is not closed. If the connection is uninitialized,
+ * raise a critical warning (it's programmer error); if it's closed,
+ * raise a recoverable GError (it's a runtime error).
+ *
+ * This function is a memory barrier.
+ *
+ * Returns: %TRUE if initialized and not closed
+ */
+static gboolean
+check_unclosed (GDBusConnection     *connection,
+                CheckUnclosedFlags   check,
+                GError             **error)
+{
+  /* check_initialized() is effectively inlined, so we don't waste time
+   * doing two memory barriers
+   */
+  gint flags = g_atomic_int_get (&connection->atomic_flags);
+
+  if (!(check & MAY_BE_UNINITIALIZED))
+    {
+      g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
+      g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
+    }
+
+  if (flags & FLAG_CLOSED)
+    {
+      g_set_error_literal (error,
+                           G_IO_ERROR,
+                           G_IO_ERROR_CLOSED,
+                           _("The connection is closed"));
+      return FALSE;
+    }
+
+  return TRUE;
+}
+
 static GHashTable *alive_connections = NULL;
 
 static void
@@ -642,6 +692,7 @@ g_dbus_connection_finalize (GObject *object)
   G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
 }
 
+/* called in any user thread, with the connection's lock not held */
 static void
 g_dbus_connection_get_property (GObject    *object,
                                 guint       prop_id,
@@ -682,6 +733,7 @@ g_dbus_connection_get_property (GObject    *object,
     }
 }
 
+/* called in any user thread, with the connection's lock not held */
 static void
 g_dbus_connection_set_property (GObject      *object,
                                 guint         prop_id,
@@ -722,6 +774,11 @@ g_dbus_connection_set_property (GObject      *object,
     }
 }
 
+/* Base-class implementation of GDBusConnection::closed.
+ *
+ * Called in a user thread, by the main context that was thread-default when
+ * the object was constructed.
+ */
 static void
 g_dbus_connection_real_closed (GDBusConnection *connection,
                                gboolean         remote_peer_vanished,
@@ -732,7 +789,8 @@ g_dbus_connection_real_closed (GDBusConnection *connection,
   /* Because atomic int access is a memory barrier, we can safely read
    * initialization_error without a lock, as long as we do it afterwards.
    */
-  if (remote_peer_vanished && connection->exit_on_close &&
+  if (remote_peer_vanished &&
+      (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
       (flags & FLAG_INITIALIZED) != 0 &&
       connection->initialization_error == NULL)
     {
@@ -1107,8 +1165,13 @@ g_dbus_connection_start_message_processing (GDBusConnection *connection)
 gboolean
 g_dbus_connection_is_closed (GDBusConnection *connection)
 {
+  gint flags;
+
   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
-  return connection->closed;
+
+  flags = g_atomic_int_get (&connection->atomic_flags);
+
+  return (flags & FLAG_CLOSED) ? TRUE : FALSE;
 }
 
 /**
@@ -1135,6 +1198,7 @@ g_dbus_connection_get_capabilities (GDBusConnection *connection)
 
 /* ---------------------------------------------------------------------------------------------------- */
 
+/* Called in a temporary thread without holding locks. */
 static void
 flush_in_thread_func (GSimpleAsyncResult *res,
                       GObject            *object,
@@ -1260,21 +1324,18 @@ g_dbus_connection_flush_sync (GDBusConnection  *connection,
 
   ret = FALSE;
 
-  /* do not use g_return_val_if_fail(), we want the memory barrier */
-  if (!check_initialized (connection))
+  /* This is only a best-effort attempt to see whether the connection is
+   * closed, so it doesn't need the lock. If the connection closes just
+   * after this check, but before scheduling the flush operation, the
+   * result will be more or less the same as if the connection closed while
+   * the flush operation was pending - it'll fail with either CLOSED or
+   * CANCELLED.
+   */
+  if (!check_unclosed (connection, 0, error))
     goto out;
 
   g_assert (connection->worker != NULL);
 
-  if (connection->closed)
-    {
-      g_set_error_literal (error,
-                           G_IO_ERROR,
-                           G_IO_ERROR_CLOSED,
-                           _("The connection is closed"));
-      goto out;
-    }
-
   ret = _g_dbus_worker_flush_sync (connection->worker,
                                    cancellable,
                                    error);
@@ -1301,6 +1362,9 @@ emit_closed_data_free (EmitClosedData *data)
   g_free (data);
 }
 
+/* Called in a user thread that has acquired the main context that was
+ * thread-default when the object was constructed
+ */
 static gboolean
 emit_closed_in_idle (gpointer user_data)
 {
@@ -1317,21 +1381,19 @@ emit_closed_in_idle (gpointer user_data)
   return FALSE;
 }
 
-/* Can be called from any thread, must hold lock */
+/* Can be called from any thread, must hold lock.
+ * FLAG_CLOSED must already have been set.
+ */
 static void
-set_closed_unlocked (GDBusConnection *connection,
-                     gboolean         remote_peer_vanished,
-                     GError          *error)
+schedule_closed_unlocked (GDBusConnection *connection,
+                          gboolean         remote_peer_vanished,
+                          GError          *error)
 {
   GSource *idle_source;
   EmitClosedData *data;
 
   CONNECTION_ENSURE_LOCK (connection);
 
-  g_assert (!connection->closed);
-
-  connection->closed = TRUE;
-
   data = g_new0 (EmitClosedData, 1);
   data->connection = g_object_ref (connection);
   data->remote_peer_vanished = remote_peer_vanished;
@@ -1450,6 +1512,7 @@ typedef struct {
     GAsyncResult *result;
 } SyncCloseData;
 
+/* Can be called by any thread, without the connection lock */
 static void
 sync_close_cb (GObject *source_object,
                GAsyncResult *res,
@@ -1488,8 +1551,7 @@ g_dbus_connection_close_sync (GDBusConnection     *connection,
 
   ret = FALSE;
 
-  CONNECTION_LOCK (connection);
-  if (!connection->closed)
+  if (check_unclosed (connection, 0, error))
     {
       GMainContext *context;
       SyncCloseData data;
@@ -1499,31 +1561,22 @@ g_dbus_connection_close_sync (GDBusConnection     *connection,
       data.loop = g_main_loop_new (context, TRUE);
       data.result = NULL;
 
-      CONNECTION_UNLOCK (connection);
       g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
       g_main_loop_run (data.loop);
       ret = g_dbus_connection_close_finish (connection, data.result, error);
-      CONNECTION_LOCK (connection);
 
       g_object_unref (data.result);
       g_main_loop_unref (data.loop);
       g_main_context_pop_thread_default (context);
       g_main_context_unref (context);
     }
-  else
-    {
-      g_set_error_literal (error,
-                           G_IO_ERROR,
-                           G_IO_ERROR_CLOSED,
-                           _("The connection is closed"));
-    }
-  CONNECTION_UNLOCK (connection);
 
   return ret;
 }
 
 /* ---------------------------------------------------------------------------------------------------- */
 
+/* Can be called by any thread, with the connection lock held */
 static gboolean
 g_dbus_connection_send_message_unlocked (GDBusConnection   *connection,
                                          GDBusMessage      *message,
@@ -1553,23 +1606,12 @@ g_dbus_connection_send_message_unlocked (GDBusConnection   *connection,
    * chicken-and-egg problems. initable_init() is responsible for setting up
    * our prerequisites (mainly connection->worker), and only calling us
    * from its own thread (so no memory barrier is needed).
-   *
-   * In the case where we're not initializing, do not use
-   * g_return_val_if_fail() - we want the memory barrier.
    */
-  if ((flags & SEND_MESSAGE_FLAGS_INITIALIZING) == 0 &&
-      !check_initialized (connection))
+  if (!check_unclosed (connection,
+                       (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
+                       error))
     goto out;
 
-  if (connection->closed)
-    {
-      g_set_error_literal (error,
-                           G_IO_ERROR,
-                           G_IO_ERROR_CLOSED,
-                           _("The connection is closed"));
-      goto out;
-    }
-
   blob = g_dbus_message_to_blob (message,
                                  &blob_size,
                                  connection->capabilities,
@@ -1700,6 +1742,7 @@ typedef struct
   gboolean delivered;
 } SendMessageData;
 
+/* Can be called from any thread with or without lock held */
 static SendMessageData *
 send_message_data_ref (SendMessageData *data)
 {
@@ -1707,6 +1750,7 @@ send_message_data_ref (SendMessageData *data)
   return data;
 }
 
+/* Can be called from any thread with or without lock held */
 static void
 send_message_data_unref (SendMessageData *data)
 {
@@ -1761,7 +1805,7 @@ send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
 
 /* ---------------------------------------------------------------------------------------------------- */
 
-/* must hold lock */
+/* Can be called from any thread with lock held */
 static void
 send_message_data_deliver_reply_unlocked (SendMessageData *data,
                                           GDBusMessage    *reply)
@@ -1781,6 +1825,7 @@ send_message_data_deliver_reply_unlocked (SendMessageData *data,
 
 /* ---------------------------------------------------------------------------------------------------- */
 
+/* Called from a user thread, lock is not held */
 static gboolean
 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
 {
@@ -1825,6 +1870,7 @@ send_message_with_reply_cancelled_cb (GCancellable *cancellable,
 
 /* ---------------------------------------------------------------------------------------------------- */
 
+/* Called from a user thread, lock is not held */
 static gboolean
 send_message_with_reply_timeout_cb (gpointer user_data)
 {
@@ -1849,6 +1895,7 @@ send_message_with_reply_timeout_cb (gpointer user_data)
 
 /* ---------------------------------------------------------------------------------------------------- */
 
+/* Called from a user thread, connection's lock is held */
 static void
 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection     *connection,
                                                     GDBusMessage        *message,
@@ -1888,17 +1935,6 @@ g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection     *connect
       goto out;
     }
 
-  if (connection->closed)
-    {
-      g_simple_async_result_set_error (simple,
-                                       G_IO_ERROR,
-                                       G_IO_ERROR_CLOSED,
-                                       _("The connection is closed"));
-      g_simple_async_result_complete_in_idle (simple);
-      g_object_unref (simple);
-      goto out;
-    }
-
   error = NULL;
   if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
     {
@@ -2082,6 +2118,7 @@ typedef struct
   GMainLoop *loop;
 } SendMessageSyncData;
 
+/* Called from a user thread, lock is not held */
 static void
 send_message_with_reply_sync_cb (GDBusConnection *connection,
                                  GAsyncResult    *res,
@@ -2200,7 +2237,7 @@ typedef struct
   GDestroyNotify              user_data_free_func;
 } FilterData;
 
-/* Called in worker's thread - we must not block */
+/* Called in GDBusWorker's thread - we must not block - with no lock held */
 static void
 on_worker_message_received (GDBusWorker  *worker,
                             GDBusMessage *message,
@@ -2302,7 +2339,7 @@ on_worker_message_received (GDBusWorker  *worker,
   g_free (filters);
 }
 
-/* Called in worker's thread */
+/* Called in GDBusWorker's thread, lock is not held */
 static GDBusMessage *
 on_worker_message_about_to_be_sent (GDBusWorker  *worker,
                                     GDBusMessage *message,
@@ -2357,7 +2394,7 @@ on_worker_message_about_to_be_sent (GDBusWorker  *worker,
   return message;
 }
 
-/* called with connection lock held */
+/* called with connection lock held, in GDBusWorker thread */
 static gboolean
 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
 {
@@ -2379,7 +2416,7 @@ cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
   return TRUE;
 }
 
-/* Called in worker's thread - we must not block */
+/* Called in GDBusWorker's thread - we must not block - without lock held */
 static void
 on_worker_closed (GDBusWorker *worker,
                   gboolean     remote_peer_vanished,
@@ -2388,6 +2425,7 @@ on_worker_closed (GDBusWorker *worker,
 {
   GDBusConnection *connection;
   gboolean alive;
+  guint old_atomic_flags;
 
   G_LOCK (message_bus_lock);
   alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
@@ -2403,10 +2441,16 @@ on_worker_closed (GDBusWorker *worker,
   //g_debug ("in on_worker_closed: %s", error->message);
 
   CONNECTION_LOCK (connection);
-  if (!connection->closed)
+  /* Even though this is atomic, we do it inside the lock to avoid breaking
+   * assumptions in remove_match_rule(). We'd need the lock in a moment
+   * anyway, so, no loss.
+   */
+  old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
+
+  if (!(old_atomic_flags & FLAG_CLOSED))
     {
       g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
-      set_closed_unlocked (connection, remote_peer_vanished, error);
+      schedule_closed_unlocked (connection, remote_peer_vanished, error);
     }
   CONNECTION_UNLOCK (connection);
 
@@ -2415,7 +2459,11 @@ on_worker_closed (GDBusWorker *worker,
 
 /* ---------------------------------------------------------------------------------------------------- */
 
-/* Determines the biggest set of capabilities we can support on this connection */
+/* Determines the biggest set of capabilities we can support on this
+ * connection.
+ *
+ * Called with the init_lock held.
+ */
 static GDBusCapabilityFlags
 get_offered_capabilities_max (GDBusConnection *connection)
 {
@@ -2428,6 +2476,7 @@ get_offered_capabilities_max (GDBusConnection *connection)
       return ret;
 }
 
+/* Called in a user thread, lock is not held */
 static gboolean
 initable_init (GInitable     *initable,
                GCancellable  *cancellable,
@@ -2924,7 +2973,12 @@ g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
                                      gboolean         exit_on_close)
 {
   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
-  connection->exit_on_close = exit_on_close;
+
+  if (exit_on_close)
+    g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
+  else
+    g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
+
 }
 
 /**
@@ -2944,7 +2998,11 @@ gboolean
 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
 {
   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
-  return connection->exit_on_close;
+
+  if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
+    return TRUE;
+  else
+    return FALSE;
 }
 
 /**
@@ -3071,6 +3129,7 @@ g_dbus_connection_add_filter (GDBusConnection            *connection,
 
   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
   g_return_val_if_fail (filter_function != NULL, 0);
+  g_return_val_if_fail (check_initialized (connection), 0);
 
   CONNECTION_LOCK (connection);
   data = g_new0 (FilterData, 1);
@@ -3115,6 +3174,7 @@ g_dbus_connection_remove_filter (GDBusConnection *connection,
   FilterData *to_destroy;
 
   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
+  g_return_if_fail (check_initialized (connection));
 
   CONNECTION_LOCK (connection);
   to_destroy = NULL;
@@ -3213,7 +3273,7 @@ static guint _global_subtree_registration_id = 1;
 
 /* ---------------------------------------------------------------------------------------------------- */
 
-/* must hold lock when calling */
+/* Called in a user thread, lock is held */
 static void
 add_match_rule (GDBusConnection *connection,
                 const gchar     *match_rule)
@@ -3244,7 +3304,7 @@ add_match_rule (GDBusConnection *connection,
 
 /* ---------------------------------------------------------------------------------------------------- */
 
-/* must hold lock when calling */
+/* Called in a user thread, lock is held */
 static void
 remove_match_rule (GDBusConnection *connection,
                    const gchar     *match_rule)
@@ -3268,6 +3328,10 @@ remove_match_rule (GDBusConnection *connection,
                                                 NULL,
                                                 &error))
     {
+      /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
+       * critical; but we're holding the lock, and our caller checked whether
+       * we were already closed, so we can't get that error.
+       */
       g_critical ("Error while sending RemoveMatch() message: %s", error->message);
       g_error_free (error);
     }
@@ -3359,6 +3423,7 @@ g_dbus_connection_signal_subscribe (GDBusConnection     *connection,
   g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
   g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
   g_return_val_if_fail (callback != NULL, 0);
+  g_return_val_if_fail (check_initialized (connection), 0);
 
   CONNECTION_LOCK (connection);
 
@@ -3442,6 +3507,7 @@ g_dbus_connection_signal_subscribe (GDBusConnection     *connection,
 
 /* ---------------------------------------------------------------------------------------------------- */
 
+/* called in any thread */
 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
 static void
 unsubscribe_id_internal (GDBusConnection *connection,
@@ -3489,12 +3555,20 @@ unsubscribe_id_internal (GDBusConnection *connection,
             }
 
           /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
-          if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
+          if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
+              !is_signal_data_for_name_lost_or_acquired (signal_data) &&
+              !g_dbus_connection_is_closed (connection) &&
+              !connection->finalizing)
             {
-              if (!is_signal_data_for_name_lost_or_acquired (signal_data))
-                if (!connection->closed && !connection->finalizing)
-                  remove_match_rule (connection, signal_data->rule);
+              /* The check for g_dbus_connection_is_closed() means that
+               * sending the RemoveMatch message can't fail with
+               * G_IO_ERROR_CLOSED, because we're holding the lock,
+               * so on_worker_closed() can't happen between the check we just
+               * did, and releasing the lock later.
+               */
+              remove_match_rule (connection, signal_data->rule);
             }
+
           signal_data_free (signal_data);
         }
 
@@ -3524,6 +3598,7 @@ g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
   guint n;
 
   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
+  g_return_if_fail (check_initialized (connection));
 
   subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
 
@@ -3626,7 +3701,7 @@ signal_instance_free (SignalInstance *signal_instance)
   g_free (signal_instance);
 }
 
-/* called in message handler thread WITH lock held */
+/* called in GDBusWorker thread WITH lock held */
 static void
 schedule_callbacks (GDBusConnection *connection,
                     GPtrArray       *signal_data_array,
@@ -3713,7 +3788,7 @@ schedule_callbacks (GDBusConnection *connection,
     }
 }
 
-/* called in message handler thread with lock held */
+/* called in GDBusWorker thread with lock held */
 static void
 distribute_signals (GDBusConnection *connection,
                     GDBusMessage    *message)
@@ -3888,7 +3963,7 @@ exported_interface_free (ExportedInterface *ei)
  * @subtree_registration_id (if not zero) has been unregistered. If
  * so, returns %TRUE.
  *
- * Caller must *not* hold lock.
+ * May be called by any thread. Caller must *not* hold lock.
  */
 static gboolean
 has_object_been_unregistered (GDBusConnection  *connection,
@@ -4065,7 +4140,7 @@ invoke_set_property_in_idle_cb (gpointer _data)
   return FALSE;
 }
 
-/* called with lock held */
+/* called in any thread with connection's lock held */
 static gboolean
 validate_and_maybe_schedule_property_getset (GDBusConnection            *connection,
                                              GDBusMessage               *message,
@@ -4179,7 +4254,7 @@ validate_and_maybe_schedule_property_getset (GDBusConnection            *connect
   return handled;
 }
 
-/* called with lock held */
+/* called in GDBusWorker thread with connection's lock held */
 static gboolean
 handle_getset_property (GDBusConnection *connection,
                         ExportedObject  *eo,
@@ -4323,7 +4398,7 @@ invoke_get_all_properties_in_idle_cb (gpointer _data)
   return FALSE;
 }
 
-/* called with lock held */
+/* called in any thread with connection's lock held */
 static gboolean
 validate_and_maybe_schedule_property_get_all (GDBusConnection            *connection,
                                               GDBusMessage               *message,
@@ -4373,7 +4448,7 @@ validate_and_maybe_schedule_property_get_all (GDBusConnection            *connec
   return handled;
 }
 
-/* called with lock held */
+/* called in GDBusWorker thread with connection's lock held */
 static gboolean
 handle_get_all_properties (GDBusConnection *connection,
                            ExportedObject  *eo,
@@ -4495,6 +4570,7 @@ maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHa
 }
 
 /* TODO: we want a nicer public interface for this */
+/* called in any thread with connection's lock held */
 static gchar **
 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
                                             const gchar     *path)
@@ -4536,6 +4612,7 @@ g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
   return ret;
 }
 
+/* called in any thread with connection's lock not held */
 static gchar **
 g_dbus_connection_list_registered (GDBusConnection *connection,
                                    const gchar     *path)
@@ -4547,7 +4624,7 @@ g_dbus_connection_list_registered (GDBusConnection *connection,
   return ret;
 }
 
-/* called in message handler thread with lock held */
+/* called in GDBusWorker thread with connection's lock held */
 static gboolean
 handle_introspect (GDBusConnection *connection,
                    ExportedObject  *eo,
@@ -4638,7 +4715,7 @@ call_in_idle_cb (gpointer user_data)
   return FALSE;
 }
 
-/* called in message handler thread with lock held */
+/* called in GDBusWorker thread with connection's lock held */
 static gboolean
 validate_and_maybe_schedule_method_call (GDBusConnection            *connection,
                                          GDBusMessage               *message,
@@ -4748,7 +4825,7 @@ validate_and_maybe_schedule_method_call (GDBusConnection            *connection,
 
 /* ---------------------------------------------------------------------------------------------------- */
 
-/* called in message handler thread with lock held */
+/* called in GDBusWorker thread with connection's lock held */
 static gboolean
 obj_message_func (GDBusConnection *connection,
                   ExportedObject  *eo,
@@ -4895,6 +4972,7 @@ g_dbus_connection_register_object (GDBusConnection            *connection,
   g_return_val_if_fail (interface_info != NULL, 0);
   g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
   g_return_val_if_fail (error == NULL || *error == NULL, 0);
+  g_return_val_if_fail (check_initialized (connection), 0);
 
   ret = 0;
 
@@ -4971,6 +5049,7 @@ g_dbus_connection_unregister_object (GDBusConnection *connection,
   gboolean ret;
 
   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
+  g_return_val_if_fail (check_initialized (connection), FALSE);
 
   ret = FALSE;
 
@@ -5043,6 +5122,7 @@ g_dbus_connection_emit_signal (GDBusConnection  *connection,
   g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
   g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
   g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
+  g_return_val_if_fail (check_initialized (connection), FALSE);
 
   if (G_UNLIKELY (_g_dbus_debug_emission ()))
     {
@@ -5173,6 +5253,7 @@ call_state_free (CallState *state)
   g_slice_free (CallState, state);
 }
 
+/* called in any thread, with the connection's lock not held */
 static void
 g_dbus_connection_call_done (GObject      *source,
                              GAsyncResult *result,
@@ -5229,6 +5310,7 @@ g_dbus_connection_call_done (GObject      *source,
   g_object_unref (simple);
 }
 
+/* called in any thread, with the connection's lock not held */
 static void
 g_dbus_connection_call_internal (GDBusConnection        *connection,
                                  const gchar            *bus_name,
@@ -5254,6 +5336,7 @@ g_dbus_connection_call_internal (GDBusConnection        *connection,
   g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
   g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
   g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
+  g_return_if_fail (check_initialized (connection));
 #ifdef G_OS_UNIX
   g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
 #else
@@ -5313,6 +5396,7 @@ g_dbus_connection_call_internal (GDBusConnection        *connection,
     g_object_unref (message);
 }
 
+/* called in any thread, with the connection's lock not held */
 static GVariant *
 g_dbus_connection_call_finish_internal (GDBusConnection  *connection,
                                         GUnixFDList     **out_fd_list,
@@ -5338,6 +5422,7 @@ g_dbus_connection_call_finish_internal (GDBusConnection  *connection,
   return g_variant_ref (state->value);
 }
 
+/* called in any user thread, with the connection's lock not held */
 static GVariant *
 g_dbus_connection_call_sync_internal (GDBusConnection         *connection,
                                       const gchar             *bus_name,
@@ -5377,6 +5462,9 @@ g_dbus_connection_call_sync_internal (GDBusConnection         *connection,
 #endif
   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
 
+  if (!(flags & CALL_FLAGS_INITIALIZING))
+    g_return_val_if_fail (check_initialized (connection), FALSE);
+
   if (reply_type == NULL)
     reply_type = G_VARIANT_TYPE_ANY;
 
@@ -5789,7 +5877,9 @@ exported_subtree_free (ExportedSubtree *es)
   g_free (es);
 }
 
-/* called without lock held */
+/* called without lock held in the thread where the caller registered
+ * the subtree
+ */
 static gboolean
 handle_subtree_introspect (GDBusConnection *connection,
                            ExportedSubtree *es,
@@ -5898,7 +5988,9 @@ handle_subtree_introspect (GDBusConnection *connection,
   return handled;
 }
 
-/* called without lock held */
+/* called without lock held in the thread where the caller registered
+ * the subtree
+ */
 static gboolean
 handle_subtree_method_invocation (GDBusConnection *connection,
                                   ExportedSubtree *es,
@@ -6165,7 +6257,7 @@ process_subtree_vtable_message_in_idle_cb (gpointer _data)
   return FALSE;
 }
 
-/* called in message handler thread with lock held */
+/* called in GDBusWorker thread with connection's lock held */
 static gboolean
 subtree_message_func (GDBusConnection *connection,
                       ExportedSubtree *es,
@@ -6261,6 +6353,7 @@ g_dbus_connection_register_subtree (GDBusConnection           *connection,
   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
   g_return_val_if_fail (vtable != NULL, 0);
   g_return_val_if_fail (error == NULL || *error == NULL, 0);
+  g_return_val_if_fail (check_initialized (connection), 0);
 
   ret = 0;
 
@@ -6322,6 +6415,7 @@ g_dbus_connection_unregister_subtree (GDBusConnection *connection,
   gboolean ret;
 
   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
+  g_return_val_if_fail (check_initialized (connection), FALSE);
 
   ret = FALSE;
 
@@ -6345,7 +6439,7 @@ g_dbus_connection_unregister_subtree (GDBusConnection *connection,
 
 /* ---------------------------------------------------------------------------------------------------- */
 
-/* must be called with lock held */
+/* may be called in any thread, with connection's lock held */
 static void
 handle_generic_ping_unlocked (GDBusConnection *connection,
                               const gchar     *object_path,
@@ -6357,7 +6451,7 @@ handle_generic_ping_unlocked (GDBusConnection *connection,
   g_object_unref (reply);
 }
 
-/* must be called with lock held */
+/* may be called in any thread, with connection's lock held */
 static void
 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
                                         const gchar     *object_path,
@@ -6390,7 +6484,7 @@ handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
   g_object_unref (reply);
 }
 
-/* must be called with lock held */
+/* may be called in any thread, with connection's lock held */
 static void
 handle_generic_introspect_unlocked (GDBusConnection *connection,
                                     const gchar     *object_path,
@@ -6418,7 +6512,7 @@ handle_generic_introspect_unlocked (GDBusConnection *connection,
   g_string_free (s, TRUE);
 }
 
-/* must be called with lock held */
+/* may be called in any thread, with connection's lock held */
 static gboolean
 handle_generic_unlocked (GDBusConnection *connection,
                          GDBusMessage    *message)
@@ -6465,7 +6559,7 @@ handle_generic_unlocked (GDBusConnection *connection,
 
 /* ---------------------------------------------------------------------------------------------------- */
 
-/* called in message handler thread with lock held */
+/* called in GDBusWorker thread with connection's lock held */
 static void
 distribute_method_call (GDBusConnection *connection,
                         GDBusMessage    *message)
@@ -6559,6 +6653,7 @@ distribute_method_call (GDBusConnection *connection,
 
 /* ---------------------------------------------------------------------------------------------------- */
 
+/* Called in any user thread, with the message_bus_lock held. */
 static GDBusConnection **
 message_bus_get_singleton (GBusType   bus_type,
                            GError   **error)
@@ -6621,6 +6716,7 @@ message_bus_get_singleton (GBusType   bus_type,
   return ret;
 }
 
+/* Called in any user thread, without holding locks. */
 static GDBusConnection *
 get_uninitialized_connection (GBusType       bus_type,
                               GCancellable  *cancellable,