2004-09-22 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mono / io-layer / mutexes.c
index 085595b6d9901370119274ec37cafc59c595ac9e..ee10921578aea85b51a46f531f01034c8ec1fef6 100644 (file)
+/*
+ * mutexes.c:  Mutex handles
+ *
+ * Author:
+ *     Dick Porter (dick@ximian.com)
+ *
+ * (C) 2002 Ximian, Inc.
+ */
+
 #include <config.h>
 #include <glib.h>
 #include <pthread.h>
 #include <string.h>
+#include <unistd.h>
 
-#include "mono/io-layer/wapi.h"
-#include "wapi-private.h"
-#include "wait-private.h"
-#include "misc-private.h"
-#include "handles-private.h"
+#include <mono/io-layer/wapi.h>
+#include <mono/io-layer/wapi-private.h>
+#include <mono/io-layer/misc-private.h>
+#include <mono/io-layer/handles-private.h>
+#include <mono/io-layer/mono-mutex.h>
+#include <mono/io-layer/mutex-private.h>
 
-#define DEBUG
+#undef DEBUG
 
-struct _WapiHandle_mutex
-{
-       WapiHandle handle;
-       pthread_mutex_t mutex;
-       pthread_t tid;
-       guint32 recursion;
+/* This is used to serialise mutex creation when names are given
+ */
+static mono_mutex_t named_mutex_mutex;
+
+static void mutex_close_shared (gpointer handle);
+static void mutex_signal(gpointer handle);
+static void mutex_own (gpointer handle);
+static gboolean mutex_is_owned (gpointer handle);
+
+struct _WapiHandleOps _wapi_mutex_ops = {
+       mutex_close_shared,     /* close_shared */
+       NULL,                   /* close_private */
+       mutex_signal,           /* signal */
+       mutex_own,              /* own */
+       mutex_is_owned,         /* is_owned */
 };
 
-static void mutex_close(WapiHandle *handle);
-static gboolean mutex_wait(WapiHandle *handle, guint32 ms);
-static guint32 mutex_wait_multiple(gpointer data);
-
-static struct _WapiHandleOps mutex_ops = {
-       mutex_close,            /* close */
-       NULL,                   /* getfiletype */
-       NULL,                   /* readfile */
-       NULL,                   /* writefile */
-       NULL,                   /* seek */
-       NULL,                   /* setendoffile */
-       NULL,                   /* getfilesize */
-       mutex_wait,             /* wait */
-       mutex_wait_multiple,    /* wait_multiple */
-};
+static mono_once_t mutex_ops_once=MONO_ONCE_INIT;
 
-static void mutex_close(WapiHandle *handle)
+static void mutex_ops_init (void)
 {
-       struct _WapiHandle_mutex *mutex_handle=(struct _WapiHandle_mutex *)handle;
-       
-#ifdef DEBUG
-       g_message(G_GNUC_PRETTY_FUNCTION ": closing mutex handle %p",
-                 mutex_handle);
-#endif
-}
+       int thr_ret;
+#if defined(_POSIX_THREAD_PROCESS_SHARED) && _POSIX_THREAD_PROCESS_SHARED != -1
+       pthread_mutexattr_t mutex_shared_attr;
 
-static gboolean mutex_wait(WapiHandle *handle, guint32 ms)
-{
-       struct _WapiHandle_mutex *mutex_handle=(struct _WapiHandle_mutex *)handle;
-       pthread_t tid=pthread_self();
-       int ret;
-       
-#ifdef DEBUG
-       g_message(G_GNUC_PRETTY_FUNCTION ": waiting for mutex handle %p",
-                 mutex_handle);
-#endif
+       thr_ret = mono_mutexattr_init (&mutex_shared_attr);
+       g_assert (thr_ret == 0);
 
-       if(mutex_handle->tid==tid) {
-               /* We already own this mutex, so just increase the count and
-                * return TRUE
-                */
+       thr_ret = mono_mutexattr_setpshared (&mutex_shared_attr,
+                                            PTHREAD_PROCESS_SHARED);
+       g_assert (thr_ret == 0);
 
-               mutex_handle->recursion++;
-       
-#ifdef DEBUG
-               g_message(G_GNUC_PRETTY_FUNCTION
-                         ": Already own mutex handle %p (recursion %d)",
-                         mutex_handle, mutex_handle->recursion);
+       thr_ret = mono_mutex_init (&named_mutex_mutex, &mutex_shared_attr);
+       g_assert (thr_ret == 0);
+#else
+       thr_ret = mono_mutex_init (&named_mutex_mutex, NULL);
 #endif
 
-               return(TRUE);
-       }
+       _wapi_handle_register_capabilities (WAPI_HANDLE_MUTEX,
+                                           WAPI_HANDLE_CAP_WAIT |
+                                           WAPI_HANDLE_CAP_SIGNAL |
+                                           WAPI_HANDLE_CAP_OWN);
+}
+
+static void mutex_close_shared (gpointer handle)
+{
+       struct _WapiHandle_mutex *mutex_handle;
+       gboolean ok;
        
-       if(ms==INFINITE) {
-               ret=pthread_mutex_lock(&mutex_handle->mutex);
-       } else {
-               struct timespec timeout;
-               
-               _wapi_calc_timeout(&timeout, ms);
-               
-               ret=pthread_mutex_timedlock(&mutex_handle->mutex, &timeout);
+       ok=_wapi_lookup_handle (handle, WAPI_HANDLE_MUTEX,
+                               (gpointer *)&mutex_handle, NULL);
+       if(ok==FALSE) {
+               g_warning (G_GNUC_PRETTY_FUNCTION
+                          ": error looking up mutex handle %p", handle);
+               return;
        }
-
-       if(ret==0) {
-               /* Mutex locked */
        
 #ifdef DEBUG
-               g_message(G_GNUC_PRETTY_FUNCTION ": Locking mutex handle %p",
-                         mutex_handle);
+       g_message(G_GNUC_PRETTY_FUNCTION ": closing mutex handle %p", handle);
 #endif
 
-               mutex_handle->tid=tid;
-               mutex_handle->recursion=1;
-
-               return(TRUE);
-       } else {
-               /* ret might be ETIMEDOUT for timeout, or other for error */
-       
-#ifdef DEBUG
-               g_message(G_GNUC_PRETTY_FUNCTION
-                         ": Failed to lock mutex handle %p: %s", mutex_handle,
-                         strerror(ret));
-#endif
-               return(FALSE);
+       if(mutex_handle->sharedns.name!=0) {
+               _wapi_handle_scratch_delete (mutex_handle->sharedns.name);
+               mutex_handle->sharedns.name=0;
        }
 }
 
-static guint32 mutex_wait_multiple(gpointer data G_GNUC_UNUSED)
+static void mutex_signal(gpointer handle)
 {
-       WaitQueueItem *item=(WaitQueueItem *)data;
-       GPtrArray *needed;
-       int ret;
-       guint32 numhandles;
-       struct timespec timeout;
-       pthread_t tid=pthread_self();
-       guint32 i, iterations;
+       ReleaseMutex(handle);
+}
+
+static void mutex_own (gpointer handle)
+{
+       struct _WapiHandle_mutex *mutex_handle;
+       gboolean ok;
        
-       numhandles=item->handles[WAPI_HANDLE_MUTEX]->len;
+       ok=_wapi_lookup_handle (handle, WAPI_HANDLE_MUTEX,
+                               (gpointer *)&mutex_handle, NULL);
+       if(ok==FALSE) {
+               g_warning (G_GNUC_PRETTY_FUNCTION
+                          ": error looking up mutex handle %p", handle);
+               return;
+       }
        
 #ifdef DEBUG
-       g_message(G_GNUC_PRETTY_FUNCTION
-                 ": waiting on %d mutex handles for %d ms", numhandles,
-                 item->timeout);
+       g_message(G_GNUC_PRETTY_FUNCTION ": owning mutex handle %p", handle);
 #endif
 
-       /*
-        * See which ones we need to lock
-        */
-       needed=g_ptr_array_new();
-       for(i=0; i<numhandles; i++) {
-               struct _WapiHandle_mutex *mutex_handle;
-               
-               mutex_handle=g_ptr_array_index(
-                       item->handles[WAPI_HANDLE_MUTEX], i);
-               
-               if(mutex_handle->tid!=tid) {
-                       /* We don't have this one, so add it to the list */
-                       g_ptr_array_add(needed, mutex_handle);
-               }
-       }
+       _wapi_handle_set_signal_state (handle, FALSE, FALSE);
+       
+       mutex_handle->pid=getpid ();
+       mutex_handle->tid=pthread_self ();
+       mutex_handle->recursion++;
 
 #ifdef DEBUG
-       g_message(G_GNUC_PRETTY_FUNCTION ": need to lock %d mutex handles",
-                 needed->len);
+       g_message (G_GNUC_PRETTY_FUNCTION
+                  ": mutex handle %p locked %d times by %d:%ld", handle,
+                  mutex_handle->recursion, mutex_handle->pid,
+                  mutex_handle->tid);
 #endif
+}
+
+static gboolean mutex_is_owned (gpointer handle)
+{
+       struct _WapiHandle_mutex *mutex_handle;
+       gboolean ok;
        
-       iterations=0;
-       do {
-               iterations++;
-               
-               /* If the timeout isnt INFINITE but greater than 1s,
-                * split the timeout into 1s chunks
-                */
-               if((item->timeout!=INFINITE) &&
-                  (item->timeout < (iterations*1000))) {
-                       _wapi_calc_timeout(
-                               &timeout, item->timeout-((iterations-1)*1000));
-               } else {
-                       _wapi_calc_timeout(&timeout, 1000);
-               }
+       ok=_wapi_lookup_handle (handle, WAPI_HANDLE_MUTEX,
+                               (gpointer *)&mutex_handle, NULL);
+       if(ok==FALSE) {
+               g_warning (G_GNUC_PRETTY_FUNCTION
+                          ": error looking up mutex handle %p", handle);
+               return(FALSE);
+       }
        
-               /* Try and lock as many mutexes as we can until we run
-                * out of time, but to avoid deadlocks back off if we
-                * fail to lock one
-                */
-               for(i=0; i<needed->len; i++) {
-                       struct _WapiHandle_mutex *mutex_handle;
-
-                       mutex_handle=g_ptr_array_index(needed, i);
-               
 #ifdef DEBUG
-                       g_message(G_GNUC_PRETTY_FUNCTION
-                                 ": Locking %d mutex %p (owner %ld, me %ld)",
-                                 i, mutex_handle, mutex_handle->tid, tid);
-#endif
-
-                       ret=pthread_mutex_timedlock(&mutex_handle->mutex,
-                                                   &timeout);
-
-#ifdef DEBUG
-                       g_message(G_GNUC_PRETTY_FUNCTION ": timedlock ret %s",
-                                 strerror(ret));
+       g_message(G_GNUC_PRETTY_FUNCTION
+                 ": testing ownership mutex handle %p", handle);
 #endif
 
-                       if(ret!=0) {
-                               /* ETIMEDOUT is the most likely, but
-                                * fail on other error too
-                                */
-
+       if(mutex_handle->recursion>0 &&
+          mutex_handle->pid==getpid () &&
+          mutex_handle->tid==pthread_self ()) {
 #ifdef DEBUG
-                               g_message(G_GNUC_PRETTY_FUNCTION
-                                         ": Lock %d mutex failed: %s", i,
-                                         strerror(ret));
+               g_message (G_GNUC_PRETTY_FUNCTION
+                          ": mutex handle %p owned by %d:%ld", handle,
+                          getpid (), pthread_self ());
 #endif
 
-                               while(i--) {
+               return(TRUE);
+       } else {
 #ifdef DEBUG
-                                       g_message(G_GNUC_PRETTY_FUNCTION
-                                                 ": Releasing %d mutex", i);
+               g_message (G_GNUC_PRETTY_FUNCTION
+                          ": mutex handle %p not owned by %d:%ld, but locked %d times by %d:%ld", handle, getpid (), pthread_self (), mutex_handle->recursion, mutex_handle->pid, mutex_handle->tid);
 #endif
-                                       mutex_handle=g_ptr_array_index(needed,
-                                                                      i);
-                                       pthread_mutex_unlock(
-                                               &mutex_handle->mutex);
-                               }
 
-                               break;
-                       }
+               return(FALSE);
+       }
+}
 
-                       /* OK, got that one. Don't record it as ours
-                        * though until we get them all
-                        */
-               }
+struct mutex_check_data
+{
+       pid_t pid;
+       pthread_t tid;
+};
 
-               if(i==needed->len) {
-                       /* We've locked all the mutexes.  Update the
-                        * ones we already had, and record that the
-                        * new ones belong to us
-                        */
-                       for(i=0; i<numhandles; i++) {
-                               struct _WapiHandle_mutex *mutex_handle;
-                               guint32 idx;
+static gboolean mutex_check (gpointer handle, gpointer user_data)
+{
+       struct _WapiHandle_mutex *mutex_handle;
+       gboolean ok;
+       struct mutex_check_data *data = (struct mutex_check_data *)user_data;
+       int thr_ret;
+       
+       ok = _wapi_lookup_handle (handle, WAPI_HANDLE_MUTEX,
+                                 (gpointer *)&mutex_handle, NULL);
+       if (ok == FALSE) {
+               g_warning (G_GNUC_PRETTY_FUNCTION
+                          ": error looking up mutex handle %p", handle);
+               return(FALSE);
+       }
 
-                               mutex_handle=g_ptr_array_index(
-                                       item->handles[WAPI_HANDLE_MUTEX], i);
-               
-                               idx=g_array_index(
-                                       item->waitindex[WAPI_HANDLE_MUTEX],
-                                       guint32, i);
-                               _wapi_handle_set_lowest(item, idx);
-                               
+       pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
+                             handle);
+       thr_ret = _wapi_handle_lock_handle (handle);
+       g_assert (thr_ret == 0);
+       
+       if (mutex_handle->pid == data->pid &&
+           mutex_handle->tid == data->tid) {
 #ifdef DEBUG
-                               g_message(G_GNUC_PRETTY_FUNCTION
-                                         ": Updating mutex %p", mutex_handle);
+               g_message (G_GNUC_PRETTY_FUNCTION
+                          ": Mutex handle %p abandoned!", handle);
 #endif
-                               
-                               if(mutex_handle->tid==tid) {
-                                       /* We already own this mutex,
-                                        * so just increase the count
-                                        */
-                                       mutex_handle->recursion++;
-                               } else {
-                                       mutex_handle->tid=tid;
-                                       mutex_handle->recursion=1;
-                               }
-                       }
+
+               mutex_handle->recursion = 0;
+               mutex_handle->pid = 0;
+               mutex_handle->tid = 0;
                
-                       g_ptr_array_free(needed, FALSE);
+               _wapi_handle_set_signal_state (handle, TRUE, FALSE);
+       }
 
-                       item->waited[WAPI_HANDLE_MUTEX]=TRUE;
-                       item->waitcount[WAPI_HANDLE_MUTEX]=numhandles;
-                       
-                       return(numhandles);
-               }
-       } while((item->timeout==INFINITE) ||
-               (item->timeout > (iterations * 1000)));
+       thr_ret = _wapi_handle_unlock_handle (handle);
+       g_assert (thr_ret == 0);
+       pthread_cleanup_pop (0);
+       
+       /* Return false to keep searching */
+       return(FALSE);
+}
 
-       /* Didn't get all the locks, and timeout isn't INFINITE */
-               
-       g_ptr_array_free(needed, FALSE);
+/* When a thread exits, any mutexes it still holds need to be signalled */
+void _wapi_mutex_check_abandoned (pid_t pid, pthread_t tid)
+{
+       struct mutex_check_data data;
 
-       item->waited[WAPI_HANDLE_MUTEX]=TRUE;
-       item->waitcount[WAPI_HANDLE_MUTEX]=0;
+       data.pid = pid;
+       data.tid = tid;
        
-       return(0);
+       _wapi_search_handle (WAPI_HANDLE_MUTEX, mutex_check, &data, NULL,
+                            NULL);
 }
 
 /**
@@ -272,7 +229,7 @@ static guint32 mutex_wait_multiple(gpointer data G_GNUC_UNUSED)
  * @owned: If %TRUE, the mutex is created with the calling thread
  * already owning the mutex.
  * @name:Pointer to a string specifying the name of this mutex, or
- * %NULL.  Currently ignored.
+ * %NULL.
  *
  * Creates a new mutex handle.  A mutex is signalled when no thread
  * owns it.  A thread acquires ownership of the mutex by waiting for
@@ -285,27 +242,128 @@ static guint32 mutex_wait_multiple(gpointer data G_GNUC_UNUSED)
  *
  * Return value: A new handle, or %NULL on error.
  */
-WapiHandle *CreateMutex(WapiSecurityAttributes *security G_GNUC_UNUSED, gboolean owned G_GNUC_UNUSED,
-                       const guchar *name G_GNUC_UNUSED)
+gpointer CreateMutex(WapiSecurityAttributes *security G_GNUC_UNUSED, gboolean owned,
+                       const gunichar2 *name)
 {
        struct _WapiHandle_mutex *mutex_handle;
-       WapiHandle *handle;
+       gpointer handle;
+       gboolean ok;
+       gchar *utf8_name;
+       int thr_ret;
+       gpointer ret = NULL;
        
-       mutex_handle=(struct _WapiHandle_mutex *)g_new0(struct _WapiHandle_mutex, 1);
-       handle=(WapiHandle *)mutex_handle;
-       _WAPI_HANDLE_INIT(handle, WAPI_HANDLE_MUTEX, mutex_ops);
+       mono_once (&mutex_ops_once, mutex_ops_init);
 
-       pthread_mutex_init(&mutex_handle->mutex, NULL);
-       if(owned==TRUE) {
-               pthread_t tid=pthread_self();
-               
-               pthread_mutex_lock(&mutex_handle->mutex);
+       /* w32 seems to guarantee that opening named mutexes can't
+        * race each other
+        */
+       pthread_cleanup_push ((void(*)(void *))mono_mutex_unlock_in_cleanup,
+                             (void *)&named_mutex_mutex);
+       thr_ret = mono_mutex_lock (&named_mutex_mutex);
+       g_assert (thr_ret == 0);
+
+       /* Need to blow away any old errors here, because code tests
+        * for ERROR_ALREADY_EXISTS on success (!) to see if a mutex
+        * was freshly created
+        */
+       SetLastError (ERROR_SUCCESS);
+       
+       if(name!=NULL) {
+               utf8_name=g_utf16_to_utf8 (name, -1, NULL, NULL, NULL);
+       } else {
+               utf8_name=NULL;
+       }
+       
+#ifdef DEBUG
+       g_message (G_GNUC_PRETTY_FUNCTION ": Creating mutex (name [%s])",
+                  utf8_name==NULL?"<unnamed>":utf8_name);
+#endif
+       
+       if(name!=NULL) {
+               handle=_wapi_search_handle_namespace (
+                       WAPI_HANDLE_MUTEX, utf8_name,
+                       (gpointer *)&mutex_handle, NULL);
+               if(handle==_WAPI_HANDLE_INVALID) {
+                       /* The name has already been used for a different
+                        * object.
+                        */
+                       g_free (utf8_name);
+                       SetLastError (ERROR_INVALID_HANDLE);
+                       goto cleanup;
+               } else if (handle!=NULL) {
+                       g_free (utf8_name);
+                       _wapi_handle_ref (handle);
+                       ret = handle;
+
+                       /* Not an error, but this is how the caller is
+                        * informed that the mutex wasn't freshly
+                        * created
+                        */
+                       SetLastError (ERROR_ALREADY_EXISTS);
+                       goto cleanup;
+               }
+               /* Otherwise fall through to create the mutex. */
+       }
+       
+       handle=_wapi_handle_new (WAPI_HANDLE_MUTEX);
+       if(handle==_WAPI_HANDLE_INVALID) {
+               g_warning (G_GNUC_PRETTY_FUNCTION
+                          ": error creating mutex handle");
+               if(utf8_name!=NULL) {
+                       g_free (utf8_name);
+               }
+               goto cleanup;
+       }
+
+       pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
+                             handle);
+       thr_ret = _wapi_handle_lock_handle (handle);
+       g_assert (thr_ret == 0);
+       
+       ok=_wapi_lookup_handle (handle, WAPI_HANDLE_MUTEX,
+                               (gpointer *)&mutex_handle, NULL);
+       if(ok==FALSE) {
+               g_warning (G_GNUC_PRETTY_FUNCTION
+                          ": error looking up mutex handle %p", handle);
+               if(utf8_name!=NULL) {
+                       g_free (utf8_name);
+               }
                
-               mutex_handle->tid=tid;
-               mutex_handle->recursion=1;
+               goto handle_cleanup;
+       }
+       ret = handle;
+       
+       if(utf8_name!=NULL) {
+               mutex_handle->sharedns.name=_wapi_handle_scratch_store (
+                       utf8_name, strlen (utf8_name));
+       }
+       
+       if(owned==TRUE) {
+               mutex_own (handle);
+       } else {
+               _wapi_handle_set_signal_state (handle, TRUE, FALSE);
        }
        
-       return(handle);
+#ifdef DEBUG
+       g_message (G_GNUC_PRETTY_FUNCTION ": returning mutex handle %p",
+                  handle);
+#endif
+
+       if(utf8_name!=NULL) {
+               g_free (utf8_name);
+       }
+
+handle_cleanup:
+       thr_ret = _wapi_handle_unlock_handle (handle);
+       g_assert (thr_ret == 0);
+       pthread_cleanup_pop (0);
+       
+cleanup:
+       thr_ret = mono_mutex_unlock (&named_mutex_mutex);
+       g_assert (thr_ret == 0);
+       pthread_cleanup_pop (0);
+       
+       return(ret);
 }
 
 /**
@@ -317,36 +375,60 @@ WapiHandle *CreateMutex(WapiSecurityAttributes *security G_GNUC_UNUSED, gboolean
  * Return value: %TRUE on success, %FALSE otherwise.  This function
  * fails if the calling thread does not own the mutex @handle.
  */
-gboolean ReleaseMutex(WapiHandle *handle)
+gboolean ReleaseMutex(gpointer handle)
 {
-       struct _WapiHandle_mutex *mutex_handle=(struct _WapiHandle_mutex *)handle;
+       struct _WapiHandle_mutex *mutex_handle;
+       gboolean ok;
        pthread_t tid=pthread_self();
+       pid_t pid=getpid ();
+       int thr_ret;
+       gboolean ret = FALSE;
+       
+       ok=_wapi_lookup_handle (handle, WAPI_HANDLE_MUTEX,
+                               (gpointer *)&mutex_handle, NULL);
+       if(ok==FALSE) {
+               g_warning (G_GNUC_PRETTY_FUNCTION
+                          ": error looking up mutex handle %p", handle);
+               return(FALSE);
+       }
+
+       pthread_cleanup_push ((void(*)(void *))_wapi_handle_unlock_handle,
+                             handle);
+       thr_ret = _wapi_handle_lock_handle (handle);
+       g_assert (thr_ret == 0);
        
 #ifdef DEBUG
        g_message(G_GNUC_PRETTY_FUNCTION ": Releasing mutex handle %p",
-                 mutex_handle);
+                 handle);
 #endif
 
-       if(mutex_handle->tid!=tid) {
+       if(mutex_handle->tid!=tid || mutex_handle->pid!=pid) {
 #ifdef DEBUG
-               g_message(G_GNUC_PRETTY_FUNCTION ": We don't own mutex handle %p (owned by %ld, me %ld)", mutex_handle, mutex_handle->tid, tid);
+               g_message(G_GNUC_PRETTY_FUNCTION ": We don't own mutex handle %p (owned by %d:%ld, me %d:%ld)", handle, mutex_handle->pid, mutex_handle->tid, pid, tid);
 #endif
 
-               return(FALSE);
+               goto cleanup;
        }
-
+       ret = TRUE;
+       
        /* OK, we own this mutex */
        mutex_handle->recursion--;
        
        if(mutex_handle->recursion==0) {
 #ifdef DEBUG
                g_message(G_GNUC_PRETTY_FUNCTION ": Unlocking mutex handle %p",
-                         mutex_handle);
+                         handle);
 #endif
 
+               mutex_handle->pid=0;
                mutex_handle->tid=0;
-               pthread_mutex_unlock(&mutex_handle->mutex);
+               _wapi_handle_set_signal_state (handle, TRUE, FALSE);
        }
+
+cleanup:
+       thr_ret = _wapi_handle_unlock_handle (handle);
+       g_assert (thr_ret == 0);
+       pthread_cleanup_pop (0);
        
-       return(TRUE);
+       return(ret);
 }