Commit Graph

103 Commits

Author SHA1 Message Date
Konstantin Belousov
ec5fed758c Ensure that threading library is initialized in pthread_mutex_init().
We need at least thr_malloc ready.  The situation is possible e.g. in case
of libthr being listed in DT_NEEDED before some of its consumers.

Reported and tested by:	lev
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2020-11-30 17:00:36 +00:00
Konstantin Belousov
f9bf9282c9 Fix destruction of the robust mutexes.
If robust mutex' owner terminated, causing kernel-assisted state
recovery, and then pthread_mutex_destroy() is executed as the next
action, assert is triggered about mutex still being on the list.
Ignore the mutex linkage in pthread_mutex_destroy() for shared robust
mutexes with dead owner, same as for enqueue_mutex().

Reported by:	avg
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2019-09-23 13:24:31 +00:00
Konstantin Belousov
0ab1bfc7b2 Avoid conflicts with libc symbols in libthr jump table.
In some corner cases of static linking and unexpected libraries order
on the linker command line, libc symbol might preempt the same libthr
symbol, in which case libthr jump table points back to libc causing
either infinite recursion or loop.  Handle all of such symbols by
using private libthr names for them, ensuring that the right pointers
are installed into the table.

In collaboration with: arichardson
PR:	239475
Tested by:	pho
MFC after:	2 weeks
Sponsored by:	The FreeBSD Foundation
Differential revision:	https://reviews.freebsd.org/D21088
2019-07-31 19:27:20 +00:00
Konstantin Belousov
b8f75b175c Do not access mutex memory after unlock.
PR:	237195
Reported by:	freebsd@hurrikhan.eu
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2019-04-12 17:27:19 +00:00
Konstantin Belousov
e4314da2e4 Fixes for very early use of the pthread_mutex_* and libthr malloc.
When libthr is statically linked into the binary, order of the
constructors execution is not deterministic.  It is possible for the
application constructor to use pthread_mutex_* functions before the
libthr initialization was done.

Handle it by:
- making thr_malloc.c locking functions operational when curthread is not
  yet set;
- making __thr_malloc_init() idempotent, allowing more than one call to it;
- unconditionally calling __thr_malloc_init() before initializing
  a process-private mutex.

Reported and tested by:	mmel
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2019-02-04 21:16:15 +00:00
Konstantin Belousov
381c2d2e9a Untangle jemalloc and mutexes initialization.
The need to use libc malloc(3) from some places in libthr always
caused issues.  For instance, per-thread key allocation was switched to
use plain mmap(2) to get storage, because some third party mallocs
used keys for implementation of calloc(3).

Even more important, libthr calls calloc(3) during initialization of
pthread mutexes, and jemalloc uses pthread mutexes.  Jemalloc provides
some way to both postpone the initialization, and to make
initialization to use specialized allocator, but this is very fragile
and often breaks.  See the referenced PR for another example.

Add the small malloc implementation used by rtld, to libthr. Use it in
thr_spec.c and for mutexes initialization. This avoids the issues with
mutual dependencies between malloc and libthr in principle.  The
drawback is that some more allocations are not interceptable for
alternate malloc implementations.  There should be not too much memory
use from this allocator, and the alternative, direct use of mmap(2) is
obviously worse.

PR:	235211
MFC after:	2 weeks
Sponsored by:	The FreeBSD Foundation
Differential revision:	https://reviews.freebsd.org/D18988
2019-01-29 22:46:44 +00:00
Pedro F. Giffuni
b6413b6db8 POSIX compliance improvements in the pthread(3) functions.
This basically adds makes use of the C99 restrict keyword, and also
adds some 'const's to four threading functions: pthread_mutexattr_gettype(),
pthread_mutexattr_getprioceiling(), pthread_mutexattr_getprotocol(), and
pthread_mutex_getprioceiling. The changes are in accordance to POSIX/SUSv4-2018.

Hinted by:	DragonFlyBSD

Relnotes:	yes
MFC after:	1 month
Differential Revision:	D16722
2018-08-18 01:05:38 +00:00
Pedro F. Giffuni
df57947f08 spdx: initial adoption of licensing ID tags.
The Software Package Data Exchange (SPDX) group provides a specification
to make it easier for automated tools to detect and summarize well known
opensource licenses. We are gradually adopting the specification, noting
that the tags are considered only advisory and do not, in any way,
superceed or replace the license texts.

Special thanks to Wind River for providing access to "The Duke of
Highlander" tool: an older (2014) run over FreeBSD tree was useful as a
starting point.

Initially, only tag files that use BSD 4-Clause "Original" license.

RelNotes:	yes
Differential Revision:	https://reviews.freebsd.org/D13133
2017-11-18 14:26:50 +00:00
Eric van Gyzen
5a6d7b723f libthr: fix warnings from GCC when WARNS=6
Fix warnings about:
- redundant declarations
- a local variable shadowing a global function (dlinfo)
- an old-style function definition (with an empty parameter list)
- a variable that is possibly used uninitialized

"make tinderbox" passes this time, except for a few unrelated
kernel failures.

Reviewed by:	kib
MFC after:	3 days
Sponsored by:	Dell EMC
Differential Revision:	https://reviews.freebsd.org/D10870
2017-05-23 16:12:50 +00:00
Jason Evans
c45e7190ab Fix __pthread_mutex_trylock() to call THR_CRITICAL_LEAVE() on failure rather
than on success.  This regression was introduced by r300043 (Add implementation
of robust mutexes...).

MFC after:	1 day
2017-05-13 17:49:53 +00:00
Konstantin Belousov
4edfc1e3bf Revert r302194, there are issues with some applications after changing
the return value, in particular console-kit-daemon.

Reported by:	Ivan Klymenko <fidaj@ukr.net>
Sponsored by:	The FreeBSD Foundation
MFC after:	2 weeks
Approved by:	re (gjb)
2016-06-25 20:20:24 +00:00
Konstantin Belousov
a068480247 For pthread_mutex_trylock() call on owned error-check or non-portable
adaptive mutex, return EDEADLK as required by POSIX.  The
pthread_mutex_lock() is already compliant.

Tested by:	Guy Yur <guyyur@gmail.com>
Sponsored by:	The FreeBSD Foundation
MFC after:	2 weeks
Approved by:	re (gjb)
2016-06-25 11:30:40 +00:00
Conrad Meyer
c72ef5eab3 libthr: Use formatted PANIC()
No functional change, although _thread_printf() may be slightly less functional
or render some values differently from libc snprintf(3).  No ABI change.

Reviewed by:	kib
Sponsored by:	EMC / Isilon Storage Division
Differential Revision:	https://reviews.freebsd.org/D6672
2016-06-01 16:12:26 +00:00
Konstantin Belousov
2a339d9e3d Add implementation of robust mutexes, hopefully close enough to the
intention of the POSIX IEEE Std 1003.1TM-2008/Cor 1-2013.

A robust mutex is guaranteed to be cleared by the system upon either
thread or process owner termination while the mutex is held.  The next
mutex locker is then notified about inconsistent mutex state and can
execute (or abandon) corrective actions.

The patch mostly consists of small changes here and there, adding
neccessary checks for the inconsistent and abandoned conditions into
existing paths.  Additionally, the thread exit handler was extended to
iterate over the userspace-maintained list of owned robust mutexes,
unlocking and marking as terminated each of them.

The list of owned robust mutexes cannot be maintained atomically
synchronous with the mutex lock state (it is possible in kernel, but
is too expensive).  Instead, for the duration of lock or unlock
operation, the current mutex is remembered in a special slot that is
also checked by the kernel at thread termination.

Kernel must be aware about the per-thread location of the heads of
robust mutex lists and the current active mutex slot.  When a thread
touches a robust mutex for the first time, a new umtx op syscall is
issued which informs about location of lists heads.

The umtx sleep queues for PP and PI mutexes are split between
non-robust and robust.

Somewhat unrelated changes in the patch:
1. Style.
2. The fix for proper tdfind() call use in umtxq_sleep_pi() for shared
   pi mutexes.
3. Removal of the userspace struct pthread_mutex m_owner field.
4. The sysctl kern.ipc.umtx_vnode_persistent is added, which controls
   the lifetime of the shared mutex associated with a vnode' page.

Reviewed by:	jilles (previous version, supposedly the objection was fixed)
Discussed with:	brooks, Martin Simmons <martin@lispworks.com> (some aspects)
Tested by:	pho
Sponsored by:	The FreeBSD Foundation
2016-05-17 09:56:22 +00:00
Konstantin Belousov
fe60c14631 If off-page lookup failed, there is no memory to perform
shared_mutex_init() upon.

Sponsored by:	The FreeBSD Foundation
2016-04-12 10:25:44 +00:00
Konstantin Belousov
3279301186 Use __FBSDID() for .c files from lib/libthr/thread.
Sponsored by:	The FreeBSD Foundation
2016-04-08 11:15:26 +00:00
Konstantin Belousov
9e821f2796 Assert that the lock objects put into the off-page, fit into the page.
Sponsored by:	The FreeBSD Foundation
2016-04-08 10:21:43 +00:00
Konstantin Belousov
6044c03a37 Apparently there are some popular programs around which assume that it
is safe to call pthread_mutex_init() on the same shared mutex several
times.  POSIX claims that the behaviour in this case is undefined.

Make this working by only allowing one caller to initialize the mutex.
Other callers either see already completed initialization and do
nothing, or busy-loop yielding while designated initializer finishes.
Also make the API requirements loose by initializing mutexes on other
pthread_mutex*() calls if they see uninitialized shared mutex.

Only mutexes provide the hack for now, but it could be also
implemented for other process shared primitives from libthr.

Reported and tested by:	"Oleg V. Nauman" <oleg@opentransfer.com>
Sponsored by:	The FreeBSD Foundation
2016-03-22 10:51:42 +00:00
Konstantin Belousov
07f22a288d Provide more information on failing checks in mutex_assert_is_owned()
and mutex_assert_not_owned().  snprintf() use in this context should
be safe.

Sponsored by:	The FreeBSD Foundation
2016-03-21 06:48:11 +00:00
Konstantin Belousov
1bdbd70599 Implement process-shared locks support for libthr.so.3, without
breaking the ABI.  Special value is stored in the lock pointer to
indicate shared lock, and offline page in the shared memory is
allocated to store the actual lock.

Reviewed by:	vangyzen (previous version)
Discussed with:	deischen, emaste, jhb, rwatson,
	Martin Simmons <martin@lispworks.com>
Tested by:	pho
Sponsored by:	The FreeBSD Foundation
2016-02-28 17:52:33 +00:00
Konstantin Belousov
3e6d2e9b4e Propagate errors from _thr_umutex_unlock2 through mutex_unlock_common.
Errors from _thr_umutex_unlock2 should "never happen" in normal
circumstances.  If they do, however, return them to the application
so it can fail early and loudly.  Hiding the errors will only delay
the inevitable failure, making it harder to find and diagnose.

Submitted by:	Eric van Gyzen <eric_van_gyzen@dell.com>
Obtained from:	Dell Inc.
PR:	198914
MFC after:	1 week
2015-02-25 16:18:26 +00:00
David Xu
e220a13ab9 MFp4:
Further decreases unexpected context switches by defering mutex wakeup
until internal sleep queue lock is released.
2012-08-11 23:17:02 +00:00
David Xu
e3b090f037 Return EBUSY for PTHREAD_MUTEX_ADAPTIVE_NP too when the mutex could not
be acquired.

PR:	168317
MFC after:	3 days
2012-05-27 01:24:51 +00:00
David Xu
ebc8e8fd7f Return 0 instead of garbage value.
Found by:	clang static analyzer
2011-01-06 08:13:30 +00:00
David Xu
e29ba4c2db Always clear flag PMUTEX_FLAG_DEFERED when unlocking, as it is only
significant for lock owner.
2010-12-24 07:41:39 +00:00
David Xu
d1078b0b03 MFp4:
- Add flags CVWAIT_ABSTIME and CVWAIT_CLOCKID for umtx kernel based
  condition variable, this should eliminate an extra system call to get
  current time.

- Add sub-function UMTX_OP_NWAKE_PRIVATE to wake up N channels in single
  system call. Create userland sleep queue for condition variable, in most
  cases, thread will wait in the queue, the pthread_cond_signal will defer
  thread wakeup until the mutex is unlocked, it tries to avoid an extra
  system call and a extra context switch in time window of pthread_cond_signal
  and pthread_mutex_unlock.

The changes are part of process-shared mutex project.
2010-12-22 05:01:52 +00:00
David Xu
e96b4de80e Remove locking and unlock in pthread_mutex_destroy, because
it can not fix race condition in application code, as a result,
the problem described in PR threads/151767 is avoided.
2010-10-27 04:19:07 +00:00
David Xu
ec92603cf9 Check invalid mutex in _mutex_cv_unlock. 2010-09-29 06:06:58 +00:00
David Xu
bbb64c2143 In current code, statically initialized and destroyed object have
same null value, the code can not distinguish between them, to
fix the problem, now a destroyed object is assigned to a non-null
value, and it will be rejected by some pthread functions.
PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP is changed to number 1, so that
adaptive mutex can be statically initialized correctly.
2010-09-28 04:57:56 +00:00
David Xu
ada33a6e36 Change atfork lock from mutex to rwlock, also make mutexes used by malloc()
module private type, when private type mutex is locked/unlocked, thread
critical region is entered or leaved. These changes makes fork()
async-signal safe which required by POSIX. Note that user's atfork handler
still needs to be async-signal safe, but it is not problem of libthr, it
is user's responsiblity.
2010-09-01 03:11:21 +00:00
David Xu
7de1ecef2d Add two commands to _umtx_op system call to allow a simple mutex to be
locked and unlocked completely in userland. by locking and unlocking mutex
in userland, it reduces the total time a mutex is locked by a thread,
in some application code, a mutex only protects a small piece of code, the
code's execution time is less than a simple system call, if a lock contention
happens, however in current implemenation, the lock holder has to extend its
locking time and enter kernel to unlock it, the change avoids this disadvantage,
it first sets mutex to free state and then enters kernel and wake one waiter
up. This improves performance dramatically in some sysbench mutex tests.

Tested by: kris
Sounds great: jeff
2008-06-24 07:32:12 +00:00
David Xu
850f4d66cb - Reduce function call overhead for uncontended case.
- Remove unused flags MUTEX_FLAGS_* and their code.
- Check validity of the timeout parameter in mutex_self_lock().
2008-05-29 07:57:33 +00:00
Kris Kennaway
dd77f9f7f2 Increase the default MUTEX_ADAPTIVE_SPINS to 2000, after further
testing it turns out 200 was too short to give good adaptive
performance.

Reviewed by:   jeff
MFC after:     1 week
2008-04-26 13:19:07 +00:00
Ruslan Ermilov
7e0e78248e Fixed mis-implementation of pthread_mutex_get{spin,yield}loops_np().
Reviewed by:	davidxu
2008-03-25 09:48:10 +00:00
Dag-Erling Smørgrav
096ba44775 _pthread_mutex_isowned_np(): use a more reliable method; the current code
will work in simple cases, but may fail in more complicated ones.

Reviewed by:	davidxu
2008-02-14 12:37:58 +00:00
Dag-Erling Smørgrav
d29b081fee Remove unnecessary prototype. 2008-02-06 20:43:19 +00:00
Dag-Erling Smørgrav
1cbdac2668 Per discussion on -threads, rename _islocked_np() to _isowned_np(). 2008-02-06 19:34:31 +00:00
Dag-Erling Smørgrav
fcd61d9141 After careful consideration (and a brief discussion with attilio@), change
the semantics of pthread_mutex_islocked_np() to return true if and only if
the mutex is held by the current thread.

Obviously, change the regression test to match.

MFC after:	2 weeks
2008-02-04 12:35:23 +00:00
Dag-Erling Smørgrav
5fd410a787 Add pthread_mutex_islocked_np(), a cheap way to verify that a mutex is
locked.  This is intended primarily to support the userland equivalent
of the various *_ASSERT_LOCKED() macros we have in the kernel.

MFC after:	2 weeks
2008-02-03 22:38:10 +00:00
David Xu
c5f411515c Add function prototypes. 2007-12-17 02:53:11 +00:00
David Xu
093fcf1694 1. Add function pthread_mutex_setspinloops_np to turn a mutex's spin
loop count.
2. Add function pthread_mutex_setyieldloops_np to turn a mutex's yield
   loop count.
3. Make environment variables PTHREAD_SPINLOOPS and PTHREAD_YIELDLOOPS
   to be only used for turnning PTHREAD_MUTEX_ADAPTIVE_NP mutex.
2007-12-14 06:25:57 +00:00
David Xu
6a663207e7 Enclose all code for macro ENQUEUE_MUTEX in do while statement, and
add missing brackets.

MFC: after 1 day
2007-12-11 08:00:58 +00:00
Jason Evans
b6b7fd3e2a Fix pointer dereferencing problems in _pthread_mutex_init_calloc_cb() that
were obscured by pseudo-opaque pthreads API pointer casting.
2007-11-28 00:16:24 +00:00
Jason Evans
e1636e1f97 Add _pthread_mutex_init_calloc_cb() to libthr and libkse, so that malloc(3)
(part of libc) can use pthreads mutexes without causing infinite recursion
during initialization.
2007-11-27 03:16:44 +00:00
David Xu
9e1ddd5fa0 Convert ceiling type to unsigned integer before comparing, fix compiler
warnings.
2007-11-21 05:25:27 +00:00
David Xu
56b45d9067 Avoid doing adaptive spinning for priority protected mutex, current
implementation always does lock in kernel.
2007-10-31 01:50:48 +00:00
David Xu
55f18e070f Don't do adaptive spinning if it is running on UP kernel. 2007-10-31 01:44:50 +00:00
David Xu
e8ef3c283b Restore revision 1.55, the kris's adaptive mutex type. 2007-10-31 01:37:13 +00:00
Kris Kennaway
83941f797f Adaptive mutexes should have the same deadlock detection properties that
default (errorcheck) mutexes do.

Noticed by:          davidxu
2007-10-30 09:24:23 +00:00
David Xu
7416cdabcd Add my recent work of adaptive spin mutex code. Use two environments variable
to tune pthread mutex performance:
1. LIBPTHREAD_SPINLOOPS
	If a pthread mutex is being locked by another thread, this environment
	variable sets total number of spin loops before the current thread
	sleeps in kernel, this saves a syscall overhead if the mutex will be
	unlocked very soon (well written application code).
2. LIBPTHREAD_YIELDLOOPS
	If a pthread mutex is being locked by other threads, this environment
	variable sets total number of sched_yield() loops before the currrent
	thread sleeps in kernel. if a pthread mutex is locked, the current thread
	gives up cpu, but will not sleep in kernel, this means, current thread
	does not set contention bit in mutex, but let lock owner to run again
	if the owner is on kernel's run queue, and when lock owner unlocks the
	mutex, it does not need to enter kernel and do lots of work to resume
	mutex waiters, in some cases, this saves lots of syscall overheads for
	mutex owner.

In my practice, sometimes LIBPTHREAD_YIELDLOOPS can massively improve performance
than LIBPTHREAD_SPINLOOPS, this depends on application. These two environments
are global to all pthread mutex, there is no interface to set them for each
pthread mutex, the default values are zero, this means spinning is turned off
by default.
2007-10-30 05:57:37 +00:00