1 //******************************************************************
3 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22 //*********************************************************************
26 * This file provides APIs related to mutex and semaphores.
29 // Defining _POSIX_C_SOURCE macro with 199309L (or greater) as value
30 // causes header files to expose definitions
31 // corresponding to the POSIX.1b, Real-time extensions
32 // (IEEE Std 1003.1b-1993) specification
34 // For this specific file, see use of clock_gettime and PTHREAD_MUTEX_DEFAULT
35 #ifndef _POSIX_C_SOURCE
36 #define _POSIX_C_SOURCE 200809L
39 #include "iotivity_config.h"
53 #ifdef HAVE_SYS_TIME_H
59 #include <oic_malloc.h>
64 * Logging tag for module name
66 #define TAG PCF("OIC_UMUTEX")
70 * Android has pthread_condattr_setclock() only in version >= 5.0, older
71 * version do have a function called __pthread_cond_timedwait_relative()
72 * which waits *for* the given timespec, this function is not visible in
73 * android version >= 5.0 anymore. This is the same way as it is handled in
75 * http://code.qt.io/cgit/qt/qtbase.git/tree/src/corelib/thread/qwaitcondition_unix.cpp?h=v5.5.0#n54
77 static int camutex_condattr_setclock(pthread_condattr_t *, clockid_t)
78 __attribute__ ((weakref("pthread_condattr_setclock")));
80 static int camutex_cond_timedwait_relative(pthread_cond_t*, pthread_mutex_t*, const struct timespec*)
81 __attribute__ ((weakref("__pthread_cond_timedwait_relative")));
82 #endif /* __ANDROID__ */
84 static const uint64_t USECS_PER_SEC = 1000000;
85 static const uint64_t NANOSECS_PER_USECS = 1000;
86 static const uint64_t NANOSECS_PER_SEC = 1000000000L;
88 typedef struct _tagMutexInfo_t
90 pthread_mutex_t mutex;
93 * Catch some of the incorrect mutex usage, by tracking the mutex owner,
101 typedef struct _tagEventInfo_t
104 pthread_condattr_t condattr;
107 typedef struct _tagThreadInfo_t
110 pthread_attr_t threadattr;
111 } oc_thread_internal;
114 static pthread_t oc_get_current_thread_id()
116 pthread_t id = pthread_self();
117 assert(OC_INVALID_THREAD_ID != id);
122 OCThreadResult_t oc_thread_new(oc_thread *t, void *(*start_routine)(void *), void *arg)
124 OCThreadResult_t res = OC_THREAD_SUCCESS;
125 oc_thread_internal *threadInfo = (oc_thread_internal*)OICMalloc(sizeof(oc_thread_internal));
126 if (NULL != threadInfo)
128 int result = pthread_create(&threadInfo->thread, NULL, start_routine, arg);
131 res = OC_THREAD_CREATE_FAILURE;
134 OIC_LOG_V(ERROR, TAG, "%s: pthread_create failed", __func__);
138 *t = (oc_thread)threadInfo;
143 OIC_LOG_V(ERROR, TAG, "%s Failed to allocate thread!", __func__);
145 res = OC_THREAD_ALLOCATION_FAILURE;
150 OCThreadResult_t oc_thread_free(oc_thread t)
152 OCThreadResult_t res = OC_THREAD_SUCCESS;
153 oc_thread_internal *threadInfo = (oc_thread_internal*) t;
160 OIC_LOG_V(ERROR, TAG, "%s Invalid thread !", __func__);
161 res = OC_THREAD_INVALID;
166 OCThreadResult_t oc_thread_wait(oc_thread t)
168 OCThreadResult_t res = OC_THREAD_SUCCESS;
169 oc_thread_internal *threadInfo = (oc_thread_internal*) t;
170 int joinres = pthread_join(threadInfo->thread, NULL);
173 OIC_LOG_V(ERROR, TAG, "Failed to join thread with error %d", joinres);
174 res = OC_THREAD_WAIT_FAILURE;
180 oc_mutex oc_mutex_new(void)
182 oc_mutex retVal = NULL;
183 oc_mutex_internal *mutexInfo = (oc_mutex_internal*) OICMalloc(sizeof(oc_mutex_internal));
184 if (NULL != mutexInfo)
186 // create the mutex with the attributes set
187 int ret=pthread_mutex_init(&(mutexInfo->mutex), PTHREAD_MUTEX_DEFAULT);
191 mutexInfo->owner = OC_INVALID_THREAD_ID;
193 retVal = (oc_mutex) mutexInfo;
197 OIC_LOG_V(ERROR, TAG, "%s Failed to initialize mutex !", __func__);
203 OIC_LOG_V(ERROR, TAG, "%s Failed to allocate mutex!", __func__);
209 bool oc_mutex_free(oc_mutex mutex)
212 oc_mutex_internal *mutexInfo = (oc_mutex_internal*) mutex;
215 int ret = pthread_mutex_destroy(&mutexInfo->mutex);
223 OIC_LOG_V(ERROR, TAG, "%s Failed to free mutex !", __func__);
228 OIC_LOG_V(ERROR, TAG, "%s Invalid mutex !", __func__);
234 void oc_mutex_lock(oc_mutex mutex)
236 oc_mutex_internal *mutexInfo = (oc_mutex_internal*) mutex;
239 int ret = pthread_mutex_lock(&mutexInfo->mutex);
242 OIC_LOG_V(ERROR, TAG, "Pthread Mutex lock failed: %d", ret);
248 * Updating the owner field must be performed while owning the lock,
249 * to solve race conditions with other threads using the same lock.
251 mutexInfo->owner = oc_get_current_thread_id();
256 OIC_LOG_V(ERROR, TAG, "%s Invalid mutex !", __func__);
260 void oc_mutex_unlock(oc_mutex mutex)
262 oc_mutex_internal *mutexInfo = (oc_mutex_internal*) mutex;
267 * Updating the owner field must be performed while owning the lock,
268 * to solve race conditions with other threads using the same lock.
270 mutexInfo->owner = OC_INVALID_THREAD_ID;
273 int ret = pthread_mutex_unlock(&mutexInfo->mutex);
276 OIC_LOG_V(ERROR, TAG, "Pthread Mutex unlock failed: %d", ret);
283 OIC_LOG_V(ERROR, TAG, "%s: Invalid mutex !", __func__);
287 void oc_mutex_assert_owner(const oc_mutex mutex, bool currentThreadIsOwner)
291 (void)currentThreadIsOwner;
293 assert(NULL != mutex);
294 const oc_mutex_internal *mutexInfo = (const oc_mutex_internal*) mutex;
296 pthread_t currentThreadID = oc_get_current_thread_id();
297 if (currentThreadIsOwner)
299 assert(pthread_equal(mutexInfo->owner, currentThreadID));
303 assert(!pthread_equal(mutexInfo->owner, currentThreadID));
308 oc_cond oc_cond_new(void)
310 oc_cond retVal = NULL;
311 oc_cond_internal *eventInfo = (oc_cond_internal*) OICMalloc(sizeof(oc_cond_internal));
312 if (NULL != eventInfo)
314 int ret = pthread_condattr_init(&(eventInfo->condattr));
317 OIC_LOG_V(ERROR, TAG, "%s: Failed to initialize condition variable attribute %d!",
323 #if defined(__ANDROID__) || _POSIX_TIMERS > 0
325 if (camutex_condattr_setclock)
327 ret = camutex_condattr_setclock(&(eventInfo->condattr), CLOCK_MONOTONIC);
330 ret = pthread_condattr_setclock(&(eventInfo->condattr), CLOCK_MONOTONIC);
331 #endif /* __ANDROID__ */
334 OIC_LOG_V(ERROR, TAG, "%s: Failed to set condition variable clock %d!",
336 pthread_condattr_destroy(&(eventInfo->condattr));
341 #endif /* defined(__ANDROID__) || _POSIX_TIMERS > 0 */
342 ret = pthread_cond_init(&(eventInfo->cond), &(eventInfo->condattr));
345 retVal = (oc_cond) eventInfo;
349 OIC_LOG_V(ERROR, TAG, "%s: Failed to initialize condition variable %d!", __func__, ret);
350 pthread_condattr_destroy(&(eventInfo->condattr));
356 OIC_LOG_V(ERROR, TAG, "%s: Failed to allocate condition variable!", __func__);
362 void oc_cond_free(oc_cond cond)
364 oc_cond_internal *eventInfo = (oc_cond_internal*) cond;
365 if (eventInfo != NULL)
367 int ret = pthread_cond_destroy(&(eventInfo->cond));
368 int ret2 = pthread_condattr_destroy(&(eventInfo->condattr));
369 if (0 == ret && 0 == ret2)
375 OIC_LOG_V(ERROR, TAG, "%s: Failed to destroy condition variable %d, %d",
376 __func__, ret, ret2);
381 OIC_LOG_V(ERROR, TAG, "%s: Invalid parameter", __func__);
385 void oc_cond_signal(oc_cond cond)
387 oc_cond_internal *eventInfo = (oc_cond_internal*) cond;
388 if (eventInfo != NULL)
390 int ret = pthread_cond_signal(&(eventInfo->cond));
393 OIC_LOG_V(ERROR, TAG, "%s: Failed to signal condition variable", __func__);
398 OIC_LOG_V(ERROR, TAG, "%s: Invalid parameter", __func__);
402 void oc_cond_broadcast(oc_cond cond)
404 oc_cond_internal* eventInfo = (oc_cond_internal*) cond;
405 if (eventInfo != NULL)
407 int ret = pthread_cond_broadcast(&(eventInfo->cond));
410 OIC_LOG_V(ERROR, TAG, "%s: failed to signal condition variable", __func__);
415 OIC_LOG_V(ERROR, TAG, "%s: Invalid parameter", __func__);
419 void oc_cond_wait(oc_cond cond, oc_mutex mutex)
421 oc_cond_wait_for(cond, mutex, 0L);
424 #ifndef TIMEVAL_TO_TIMESPEC
425 #define TIMEVAL_TO_TIMESPEC(tv, ts) { \
426 (ts)->tv_sec = (tv)->tv_sec; \
427 (ts)->tv_nsec = (tv)->tv_usec * 1000; \
431 struct timespec oc_get_current_time()
433 #if defined(__ANDROID__) || _POSIX_TIMERS > 0
435 clock_gettime(CLOCK_MONOTONIC, &ts);
439 gettimeofday(&tv, NULL);
441 TIMEVAL_TO_TIMESPEC(&tv, &ts);
446 void oc_add_microseconds_to_timespec(struct timespec* ts, uint64_t microseconds)
448 time_t secPart = microseconds/USECS_PER_SEC;
449 uint64_t nsecPart = (microseconds % USECS_PER_SEC) * NANOSECS_PER_USECS;
450 uint64_t totalNs = ts->tv_nsec + nsecPart;
451 time_t secOfNs = totalNs/NANOSECS_PER_SEC;
453 ts->tv_nsec = (totalNs)% NANOSECS_PER_SEC;
454 ts->tv_sec += secPart + secOfNs;
457 OCWaitResult_t oc_cond_wait_for(oc_cond cond, oc_mutex mutex, uint64_t microseconds)
459 OCWaitResult_t retVal = OC_WAIT_INVAL;
461 oc_cond_internal *eventInfo = (oc_cond_internal*) cond;
462 oc_mutex_internal *mutexInfo = (oc_mutex_internal*) mutex;
464 if (NULL == mutexInfo)
466 OIC_LOG_V(ERROR, TAG, "%s: Invalid mutex", __func__);
467 return OC_WAIT_INVAL;
470 if (NULL == eventInfo)
472 OIC_LOG_V(ERROR, TAG, "%s: Invalid condition", __func__);
473 return OC_WAIT_INVAL;
476 if (microseconds > 0)
479 struct timespec abstime = { .tv_sec = 0 };
482 if (camutex_cond_timedwait_relative)
484 abstime.tv_sec = microseconds / USECS_PER_SEC;
485 abstime.tv_nsec = (microseconds % USECS_PER_SEC) * NANOSECS_PER_USECS;
486 //Wait for the given time
487 ret = camutex_cond_timedwait_relative(&(eventInfo->cond), &(mutexInfo->mutex), &abstime);
491 abstime = oc_get_current_time();
492 oc_add_microseconds_to_timespec(&abstime, microseconds);
494 //Wait for the given time
495 ret = pthread_cond_timedwait(&(eventInfo->cond), &(mutexInfo->mutex), &abstime);
502 retVal = OC_WAIT_SUCCESS;
505 retVal = OC_WAIT_TIMEDOUT;
508 OIC_LOG_V(ERROR, TAG, "%s: condition, mutex, or abstime is Invalid", __func__);
509 retVal = OC_WAIT_INVAL;
512 OIC_LOG_V(ERROR, TAG, "%s: pthread_cond_timedwait returned %d", __func__, retVal);
513 retVal = OC_WAIT_INVAL;
520 int ret = pthread_cond_wait(&eventInfo->cond, &mutexInfo->mutex);
521 retVal = ret == 0 ? OC_WAIT_SUCCESS : OC_WAIT_INVAL;