+
+/************************** Thread-local Storage ****************************/
+
+#if (defined(SILC_THREADS) && defined(HAVE_PTHREAD_KEY_CREATE) && \
+ defined(HAVE_PTHREAD_ONCE))
+
+static SilcBool key_set = FALSE;
+static pthread_key_t key;
+static pthread_once_t key_once = PTHREAD_ONCE_INIT;
+
+static void silc_thread_tls_destructor(void *context)
+{
+ SilcTls tls = context;
+
+ if (tls->tls_variables)
+ silc_hash_table_free(tls->tls_variables);
+ tls->tls_variables = NULL;
+
+ silc_free(tls);
+}
+
+static void silc_thread_tls_alloc(void)
+{
+ if (pthread_key_create(&key, silc_thread_tls_destructor))
+ SILC_LOG_ERROR(("Error creating Thread-local storage"));
+ key_set = TRUE;
+}
+
+SilcTls silc_thread_tls_init(void)
+{
+ SilcTls tls;
+
+ pthread_once(&key_once, silc_thread_tls_alloc);
+
+ if (silc_thread_get_tls())
+ return silc_thread_get_tls();
+
+ /* Allocate Tls for the thread */
+ tls = silc_calloc(1, sizeof(*tls));
+ if (!tls) {
+ SILC_LOG_ERROR(("Error allocating Thread-local storage"));
+ return NULL;
+ }
+ pthread_setspecific(key, tls);
+
+ /* Allocate global lock */
+ silc_mutex_alloc(&tls->lock);
+
+ return tls;
+}
+
+static SilcTls silc_thread_tls_init_shared(SilcTls other)
+{
+ SilcTls tls;
+
+ pthread_once(&key_once, silc_thread_tls_alloc);
+
+ if (silc_thread_get_tls())
+ return silc_thread_get_tls();
+
+ /* Allocate Tls for the thread */
+ tls = silc_calloc(1, sizeof(*tls));
+ if (!tls) {
+ SILC_LOG_ERROR(("Error allocating Thread-local storage"));
+ return NULL;
+ }
+ pthread_setspecific(key, tls);
+
+ /* Take shared data */
+ tls->shared_data = 1;
+ tls->lock = other->lock;
+ tls->variables = other->variables;
+
+ return tls;
+}
+
+SilcTls silc_thread_get_tls(void)
+{
+ if (!key_set)
+ return NULL;
+ return pthread_getspecific(key);
+}
+
+void silc_thread_tls_uninit(void)
+{
+ SilcTls tls = silc_thread_get_tls();
+
+ if (!tls || tls->shared_data)
+ return;
+
+ /* Main thread cleanup */
+ if (tls->tls_variables)
+ silc_hash_table_free(tls->tls_variables);
+ if (tls->variables)
+ silc_hash_table_free(tls->variables);
+ if (tls->lock)
+ silc_mutex_free(tls->lock);
+ tls->variables = NULL;
+ tls->lock = NULL;
+ silc_free(tls);
+ pthread_setspecific(key, NULL);
+}
+
+#else
+
+SilcTlsStruct tls;
+SilcTls tls_ptr = NULL;
+
+SilcTls silc_thread_tls_init(void)
+{
+ if (silc_thread_get_tls())
+ return silc_thread_get_tls();
+
+ tls_ptr = &tls;
+ memset(tls_ptr, 0, sizeof(*tls_ptr));
+
+ atexit(silc_thread_tls_uninit);
+
+ return tls_ptr;
+}
+
+static SilcTls silc_thread_tls_init_shared(SilcTls other)
+{
+ return silc_thread_tls_init();
+}
+
+SilcTls silc_thread_get_tls(void)
+{
+ return tls_ptr;
+}
+
+void silc_thread_tls_uninit(void)
+{
+ if (tls.tls_variables)
+ silc_hash_table_free(tls.tls_variables);
+ if (tls.variables)
+ silc_hash_table_free(tls.variables);
+ if (tls.lock)
+ silc_mutex_free(tls.lock);
+}
+
+#endif