1 /*
2  * Copyright (c) 2020-2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "fsm_common.h"
17 
18 #include <ctime>
19 #include <cstdio>
20 #include <climits>
21 #include <unistd.h>
22 
23 const uint32_t SEC2USEC = 1000000;
24 const uint16_t USEC2NSEC = 1000;
25 const uint32_t SEC2NSEC = 1000000000;
26 
FsmGetCurTimeUs()27 uint64_t FsmGetCurTimeUs()
28 {
29     struct timespec ts = { 0, 0 };
30 
31     (void)clock_gettime(CLOCK_MONOTONIC, &ts);
32 
33     uint64_t curT = (((uint64_t)ts.tv_sec) * SEC2USEC) + (((uint64_t)ts.tv_nsec) / USEC2NSEC);
34 
35     return (uint64_t)curT;
36 }
37 
FsmCondInitRelative(pthread_cond_t & cond)38 void FsmCondInitRelative(pthread_cond_t &cond)
39 {
40 #if (!defined(__LITE__))
41     pthread_condattr_t condAttr;
42     (void)pthread_condattr_init(&condAttr);
43 
44     (void)pthread_condattr_setclock(&condAttr, CLOCK_MONOTONIC);
45     (void)pthread_cond_init(&cond, &condAttr);
46 #else
47     (void)pthread_cond_init(&cond, nullptr);
48 #endif
49 }
50 
FsmCondTimewait(pthread_cond_t & cond,pthread_mutex_t & mutex,uint32_t delayUs)51 int32_t FsmCondTimewait(pthread_cond_t &cond, pthread_mutex_t &mutex, uint32_t delayUs)
52 {
53     struct timespec ts = { 0, 0 };
54 
55 #if (!defined(__LITE__))
56     (void)clock_gettime(CLOCK_MONOTONIC, &ts);
57 #else
58     ts.tv_sec = 0;
59     ts.tv_nsec = 0;
60 #endif
61     if (delayUs >= UINT_MAX / USEC2NSEC) {
62         return HI_FAILURE;
63     }
64     uint64_t delayNs = delayUs * USEC2NSEC;
65     ts.tv_sec += (delayNs / SEC2NSEC);
66     delayNs = delayNs % SEC2NSEC;
67 
68     if (ts.tv_nsec + delayNs > SEC2NSEC) {
69         ts.tv_sec++;
70         ts.tv_nsec = (ts.tv_nsec + delayNs) - SEC2NSEC;
71     } else {
72         ts.tv_nsec += delayNs;
73     }
74 
75     return pthread_cond_timedwait(&cond, &mutex, &ts);
76 }
77