summaryrefslogtreecommitdiff
path: root/usr/src/lib/libfakekernel/common/mutex.c
blob: 0dff58c55338b6a37b1b779e3e0e84fda83bd3ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright 2018 Nexenta Systems, Inc.  All rights reserved.
 * Copyright 2017 RackTop Systems.
 */

/*
 * mutex(9f)
 */

/* This is the API we're emulating */
#include <sys/mutex.h>

#include <sys/errno.h>
#include <sys/debug.h>
#include <sys/thread.h>

int	_lwp_mutex_lock(lwp_mutex_t *);
int	_lwp_mutex_unlock(lwp_mutex_t *);
int	_lwp_mutex_trylock(lwp_mutex_t *);

extern clock_t ddi_get_lbolt(void);

/* See: head/synch.h ERRORCHECKMUTEX */
static const lwp_mutex_t default_mutex =
	{{0, 0, 0, {USYNC_THREAD|LOCK_ERRORCHECK}, _MUTEX_MAGIC},
	{{{0, 0, 0, 0, 0, 0, 0, 0}}}, 0};

/* ARGSUSED */
void
kmutex_init(kmutex_t *mp, char *name, kmutex_type_t typ, void *arg)
{
	mp->m_lock = default_mutex;
	mp->m_owner = _KTHREAD_INVALID;
}

/* ARGSUSED */
void
kmutex_destroy(kmutex_t *mp)
{
	mp->m_owner = _KTHREAD_INVALID;
}

void
kmutex_enter(kmutex_t *mp)
{
	kthread_t *t = _curthread();

	VERIFY(mp->m_owner != t);
	VERIFY(0 == _lwp_mutex_lock(&mp->m_lock));
	mp->m_owner = t;
}

int
mutex_tryenter(kmutex_t *mp)
{
	int rc;

	rc = _lwp_mutex_trylock(&mp->m_lock);
	if (rc == 0) {
		mp->m_owner = _curthread();
		return (1);
	}
	return (0);
}

void
kmutex_exit(kmutex_t *mp)
{
	ASSERT(mp->m_owner == _curthread());
	mp->m_owner = _KTHREAD_INVALID;
	(void) _lwp_mutex_unlock(&mp->m_lock);
}

/*
 * Returns the kthread_t * of the owner.
 */
void *
mutex_owner(const kmutex_t *mp)
{
	return (mp->m_owner);
}

int
mutex_owned(const kmutex_t *mp)
{
	void *t = _curthread();
	return (t == mp->m_owner);
}