xref: /nrf52832-nimble/packages/NimBLE-latest/porting/npl/linux/src/os_mutex.c (revision 042d53a763ad75cb1465103098bb88c245d95138)
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements.  See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership.  The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License.  You may obtain a copy of the License at
9  *
10  *  http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied.  See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 
20 #include <assert.h>
21 #include <stdint.h>
22 #include <string.h>
23 #include "os/os.h"
24 #include "nimble/nimble_npl.h"
25 
26 #include <pthread.h>
27 
28 ble_npl_error_t
ble_npl_mutex_init(struct ble_npl_mutex * mu)29 ble_npl_mutex_init(struct ble_npl_mutex *mu)
30 {
31     pthread_mutexattr_t mu_attr;
32 
33     if (!mu) {
34         return BLE_NPL_INVALID_PARAM;
35     }
36 
37     pthread_mutexattr_settype(&mu_attr, PTHREAD_MUTEX_RECURSIVE_NP);
38     pthread_mutex_init(&mu->lock, &mu_attr);
39 
40     return BLE_NPL_OK;
41 }
42 
43 ble_npl_error_t
ble_npl_mutex_release(struct ble_npl_mutex * mu)44 ble_npl_mutex_release(struct ble_npl_mutex *mu)
45 {
46     if (!mu) {
47         return BLE_NPL_INVALID_PARAM;
48     }
49 
50     if (pthread_mutex_unlock(&mu->lock)) {
51         return BLE_NPL_BAD_MUTEX;
52     }
53 
54     return BLE_NPL_OK;
55 }
56 
57 ble_npl_error_t
ble_npl_mutex_pend(struct ble_npl_mutex * mu,uint32_t timeout)58 ble_npl_mutex_pend(struct ble_npl_mutex *mu, uint32_t timeout)
59 {
60     struct timespec wait;
61 
62     if (!mu) {
63         return BLE_NPL_INVALID_PARAM;
64     }
65 
66     assert(&mu->lock);
67 
68     wait.tv_sec  = timeout / 1000;
69     wait.tv_nsec = (timeout % 1000) * 1000000;
70     wait.tv_nsec %= 1000000000;
71 
72     if (pthread_mutex_timedlock(&mu->lock, &wait)) {
73         return BLE_NPL_TIMEOUT;
74     }
75 
76     return BLE_NPL_OK;
77 }
78