xref: /freebsd/sys/contrib/openzfs/lib/libspl/mutex.c (revision 8ac904ce090b1c2e355da8aa122ca2252183f4e1)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2012, 2018 by Delphix. All rights reserved.
25  * Copyright (c) 2016 Actifio, Inc. All rights reserved.
26  * Copyright (c) 2025, Klara, Inc.
27  */
28 
29 #include <assert.h>
30 #include <pthread.h>
31 #include <string.h>
32 #include <errno.h>
33 #include <sys/mutex.h>
34 
35 /*
36  * =========================================================================
37  * mutexes
38  * =========================================================================
39  */
40 
41 void
mutex_init(kmutex_t * mp,char * name,int type,void * cookie)42 mutex_init(kmutex_t *mp, char *name, int type, void *cookie)
43 {
44 	(void) name, (void) type, (void) cookie;
45 	VERIFY0(pthread_mutex_init(&mp->m_lock, NULL));
46 	memset(&mp->m_owner, 0, sizeof (pthread_t));
47 }
48 
49 void
mutex_destroy(kmutex_t * mp)50 mutex_destroy(kmutex_t *mp)
51 {
52 	VERIFY0(pthread_mutex_destroy(&mp->m_lock));
53 }
54 
55 void
mutex_enter(kmutex_t * mp)56 mutex_enter(kmutex_t *mp)
57 {
58 	VERIFY0(pthread_mutex_lock(&mp->m_lock));
59 	mp->m_owner = pthread_self();
60 }
61 
62 int
mutex_enter_check_return(kmutex_t * mp)63 mutex_enter_check_return(kmutex_t *mp)
64 {
65 	int error = pthread_mutex_lock(&mp->m_lock);
66 	if (error == 0)
67 		mp->m_owner = pthread_self();
68 	return (error);
69 }
70 
71 int
mutex_tryenter(kmutex_t * mp)72 mutex_tryenter(kmutex_t *mp)
73 {
74 	int error = pthread_mutex_trylock(&mp->m_lock);
75 	if (error == 0) {
76 		mp->m_owner = pthread_self();
77 		return (1);
78 	} else {
79 		VERIFY3S(error, ==, EBUSY);
80 		return (0);
81 	}
82 }
83 
84 void
mutex_exit(kmutex_t * mp)85 mutex_exit(kmutex_t *mp)
86 {
87 	memset(&mp->m_owner, 0, sizeof (pthread_t));
88 	VERIFY0(pthread_mutex_unlock(&mp->m_lock));
89 }
90