kern_sx.c revision 189846
1/*-
2 * Copyright (c) 2007 Attilio Rao <attilio@freebsd.org>
3 * Copyright (c) 2001 Jason Evans <jasone@freebsd.org>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice(s), this list of conditions and the following disclaimer as
11 *    the first lines of this file unmodified other than the possible
12 *    addition of one or more copyright notices.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice(s), this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 * DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
21 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
27 * DAMAGE.
28 */
29
30/*
31 * Shared/exclusive locks.  This implementation attempts to ensure
32 * deterministic lock granting behavior, so that slocks and xlocks are
33 * interleaved.
34 *
35 * Priority propagation will not generally raise the priority of lock holders,
36 * so should not be relied upon in combination with sx locks.
37 */
38
39#include "opt_adaptive_sx.h"
40#include "opt_ddb.h"
41
42#include <sys/cdefs.h>
43__FBSDID("$FreeBSD: head/sys/kern/kern_sx.c 189846 2009-03-15 08:03:54Z jeff $");
44
45#include <sys/param.h>
46#include <sys/ktr.h>
47#include <sys/lock.h>
48#include <sys/mutex.h>
49#include <sys/proc.h>
50#include <sys/sleepqueue.h>
51#include <sys/sx.h>
52#include <sys/systm.h>
53
54#ifdef ADAPTIVE_SX
55#include <machine/cpu.h>
56#endif
57
58#ifdef DDB
59#include <ddb/ddb.h>
60#endif
61
62#if !defined(SMP) && defined(ADAPTIVE_SX)
63#error "You must have SMP to enable the ADAPTIVE_SX option"
64#endif
65
66CTASSERT(((SX_ADAPTIVESPIN | SX_RECURSE) & LO_CLASSFLAGS) ==
67    (SX_ADAPTIVESPIN | SX_RECURSE));
68
69/* Handy macros for sleep queues. */
70#define	SQ_EXCLUSIVE_QUEUE	0
71#define	SQ_SHARED_QUEUE		1
72
73/*
74 * Variations on DROP_GIANT()/PICKUP_GIANT() for use in this file.  We
75 * drop Giant anytime we have to sleep or if we adaptively spin.
76 */
77#define	GIANT_DECLARE							\
78	int _giantcnt = 0;						\
79	WITNESS_SAVE_DECL(Giant)					\
80
81#define	GIANT_SAVE() do {						\
82	if (mtx_owned(&Giant)) {					\
83		WITNESS_SAVE(&Giant.lock_object, Giant);		\
84		while (mtx_owned(&Giant)) {				\
85			_giantcnt++;					\
86			mtx_unlock(&Giant);				\
87		}							\
88	}								\
89} while (0)
90
91#define GIANT_RESTORE() do {						\
92	if (_giantcnt > 0) {						\
93		mtx_assert(&Giant, MA_NOTOWNED);			\
94		while (_giantcnt--)					\
95			mtx_lock(&Giant);				\
96		WITNESS_RESTORE(&Giant.lock_object, Giant);		\
97	}								\
98} while (0)
99
100/*
101 * Returns true if an exclusive lock is recursed.  It assumes
102 * curthread currently has an exclusive lock.
103 */
104#define	sx_recurse		lock_object.lo_data
105#define	sx_recursed(sx)		((sx)->sx_recurse != 0)
106
107static void	assert_sx(struct lock_object *lock, int what);
108#ifdef DDB
109static void	db_show_sx(struct lock_object *lock);
110#endif
111static void	lock_sx(struct lock_object *lock, int how);
112static int	unlock_sx(struct lock_object *lock);
113
114struct lock_class lock_class_sx = {
115	.lc_name = "sx",
116	.lc_flags = LC_SLEEPLOCK | LC_SLEEPABLE | LC_RECURSABLE | LC_UPGRADABLE,
117	.lc_assert = assert_sx,
118#ifdef DDB
119	.lc_ddb_show = db_show_sx,
120#endif
121	.lc_lock = lock_sx,
122	.lc_unlock = unlock_sx,
123};
124
125#ifndef INVARIANTS
126#define	_sx_assert(sx, what, file, line)
127#endif
128
129void
130assert_sx(struct lock_object *lock, int what)
131{
132
133	sx_assert((struct sx *)lock, what);
134}
135
136void
137lock_sx(struct lock_object *lock, int how)
138{
139	struct sx *sx;
140
141	sx = (struct sx *)lock;
142	if (how)
143		sx_xlock(sx);
144	else
145		sx_slock(sx);
146}
147
148int
149unlock_sx(struct lock_object *lock)
150{
151	struct sx *sx;
152
153	sx = (struct sx *)lock;
154	sx_assert(sx, SA_LOCKED | SA_NOTRECURSED);
155	if (sx_xlocked(sx)) {
156		sx_xunlock(sx);
157		return (1);
158	} else {
159		sx_sunlock(sx);
160		return (0);
161	}
162}
163
164void
165sx_sysinit(void *arg)
166{
167	struct sx_args *sargs = arg;
168
169	sx_init(sargs->sa_sx, sargs->sa_desc);
170}
171
172void
173sx_init_flags(struct sx *sx, const char *description, int opts)
174{
175	int flags;
176
177	MPASS((opts & ~(SX_QUIET | SX_RECURSE | SX_NOWITNESS | SX_DUPOK |
178	    SX_NOPROFILE | SX_ADAPTIVESPIN)) == 0);
179
180	flags = LO_RECURSABLE | LO_SLEEPABLE | LO_UPGRADABLE;
181	if (opts & SX_DUPOK)
182		flags |= LO_DUPOK;
183	if (opts & SX_NOPROFILE)
184		flags |= LO_NOPROFILE;
185	if (!(opts & SX_NOWITNESS))
186		flags |= LO_WITNESS;
187	if (opts & SX_QUIET)
188		flags |= LO_QUIET;
189
190	flags |= opts & (SX_ADAPTIVESPIN | SX_RECURSE);
191	sx->sx_lock = SX_LOCK_UNLOCKED;
192	sx->sx_recurse = 0;
193	lock_init(&sx->lock_object, &lock_class_sx, description, NULL, flags);
194}
195
196void
197sx_destroy(struct sx *sx)
198{
199
200	KASSERT(sx->sx_lock == SX_LOCK_UNLOCKED, ("sx lock still held"));
201	KASSERT(sx->sx_recurse == 0, ("sx lock still recursed"));
202	sx->sx_lock = SX_LOCK_DESTROYED;
203	lock_destroy(&sx->lock_object);
204}
205
206int
207_sx_slock(struct sx *sx, int opts, const char *file, int line)
208{
209	int error = 0;
210
211	MPASS(curthread != NULL);
212	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
213	    ("sx_slock() of destroyed sx @ %s:%d", file, line));
214	WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER, file, line, NULL);
215	error = __sx_slock(sx, opts, file, line);
216	if (!error) {
217		LOCK_LOG_LOCK("SLOCK", &sx->lock_object, 0, 0, file, line);
218		WITNESS_LOCK(&sx->lock_object, 0, file, line);
219		curthread->td_locks++;
220	}
221
222	return (error);
223}
224
225int
226_sx_try_slock(struct sx *sx, const char *file, int line)
227{
228	uintptr_t x;
229
230	for (;;) {
231		x = sx->sx_lock;
232		KASSERT(x != SX_LOCK_DESTROYED,
233		    ("sx_try_slock() of destroyed sx @ %s:%d", file, line));
234		if (!(x & SX_LOCK_SHARED))
235			break;
236		if (atomic_cmpset_acq_ptr(&sx->sx_lock, x, x + SX_ONE_SHARER)) {
237			LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 1, file, line);
238			WITNESS_LOCK(&sx->lock_object, LOP_TRYLOCK, file, line);
239			curthread->td_locks++;
240			return (1);
241		}
242	}
243
244	LOCK_LOG_TRY("SLOCK", &sx->lock_object, 0, 0, file, line);
245	return (0);
246}
247
248int
249_sx_xlock(struct sx *sx, int opts, const char *file, int line)
250{
251	int error = 0;
252
253	MPASS(curthread != NULL);
254	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
255	    ("sx_xlock() of destroyed sx @ %s:%d", file, line));
256	WITNESS_CHECKORDER(&sx->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file,
257	    line, NULL);
258	error = __sx_xlock(sx, curthread, opts, file, line);
259	if (!error) {
260		LOCK_LOG_LOCK("XLOCK", &sx->lock_object, 0, sx->sx_recurse,
261		    file, line);
262		WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
263		curthread->td_locks++;
264	}
265
266	return (error);
267}
268
269int
270_sx_try_xlock(struct sx *sx, const char *file, int line)
271{
272	int rval;
273
274	MPASS(curthread != NULL);
275	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
276	    ("sx_try_xlock() of destroyed sx @ %s:%d", file, line));
277
278	if (sx_xlocked(sx) && (sx->lock_object.lo_flags & SX_RECURSE) != 0) {
279		sx->sx_recurse++;
280		atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
281		rval = 1;
282	} else
283		rval = atomic_cmpset_acq_ptr(&sx->sx_lock, SX_LOCK_UNLOCKED,
284		    (uintptr_t)curthread);
285	LOCK_LOG_TRY("XLOCK", &sx->lock_object, 0, rval, file, line);
286	if (rval) {
287		WITNESS_LOCK(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
288		    file, line);
289		curthread->td_locks++;
290	}
291
292	return (rval);
293}
294
295void
296_sx_sunlock(struct sx *sx, const char *file, int line)
297{
298
299	MPASS(curthread != NULL);
300	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
301	    ("sx_sunlock() of destroyed sx @ %s:%d", file, line));
302	_sx_assert(sx, SA_SLOCKED, file, line);
303	curthread->td_locks--;
304	WITNESS_UNLOCK(&sx->lock_object, 0, file, line);
305	LOCK_LOG_LOCK("SUNLOCK", &sx->lock_object, 0, 0, file, line);
306	__sx_sunlock(sx, file, line);
307	lock_profile_release_lock(&sx->lock_object);
308}
309
310void
311_sx_xunlock(struct sx *sx, const char *file, int line)
312{
313
314	MPASS(curthread != NULL);
315	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
316	    ("sx_xunlock() of destroyed sx @ %s:%d", file, line));
317	_sx_assert(sx, SA_XLOCKED, file, line);
318	curthread->td_locks--;
319	WITNESS_UNLOCK(&sx->lock_object, LOP_EXCLUSIVE, file, line);
320	LOCK_LOG_LOCK("XUNLOCK", &sx->lock_object, 0, sx->sx_recurse, file,
321	    line);
322	if (!sx_recursed(sx))
323		lock_profile_release_lock(&sx->lock_object);
324	__sx_xunlock(sx, curthread, file, line);
325}
326
327/*
328 * Try to do a non-blocking upgrade from a shared lock to an exclusive lock.
329 * This will only succeed if this thread holds a single shared lock.
330 * Return 1 if if the upgrade succeed, 0 otherwise.
331 */
332int
333_sx_try_upgrade(struct sx *sx, const char *file, int line)
334{
335	uintptr_t x;
336	int success;
337
338	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
339	    ("sx_try_upgrade() of destroyed sx @ %s:%d", file, line));
340	_sx_assert(sx, SA_SLOCKED, file, line);
341
342	/*
343	 * Try to switch from one shared lock to an exclusive lock.  We need
344	 * to maintain the SX_LOCK_EXCLUSIVE_WAITERS flag if set so that
345	 * we will wake up the exclusive waiters when we drop the lock.
346	 */
347	x = sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS;
348	success = atomic_cmpset_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) | x,
349	    (uintptr_t)curthread | x);
350	LOCK_LOG_TRY("XUPGRADE", &sx->lock_object, 0, success, file, line);
351	if (success)
352		WITNESS_UPGRADE(&sx->lock_object, LOP_EXCLUSIVE | LOP_TRYLOCK,
353		    file, line);
354	return (success);
355}
356
357/*
358 * Downgrade an unrecursed exclusive lock into a single shared lock.
359 */
360void
361_sx_downgrade(struct sx *sx, const char *file, int line)
362{
363	uintptr_t x;
364	int wakeup_swapper;
365
366	KASSERT(sx->sx_lock != SX_LOCK_DESTROYED,
367	    ("sx_downgrade() of destroyed sx @ %s:%d", file, line));
368	_sx_assert(sx, SA_XLOCKED | SA_NOTRECURSED, file, line);
369#ifndef INVARIANTS
370	if (sx_recursed(sx))
371		panic("downgrade of a recursed lock");
372#endif
373
374	WITNESS_DOWNGRADE(&sx->lock_object, 0, file, line);
375
376	/*
377	 * Try to switch from an exclusive lock with no shared waiters
378	 * to one sharer with no shared waiters.  If there are
379	 * exclusive waiters, we don't need to lock the sleep queue so
380	 * long as we preserve the flag.  We do one quick try and if
381	 * that fails we grab the sleepq lock to keep the flags from
382	 * changing and do it the slow way.
383	 *
384	 * We have to lock the sleep queue if there are shared waiters
385	 * so we can wake them up.
386	 */
387	x = sx->sx_lock;
388	if (!(x & SX_LOCK_SHARED_WAITERS) &&
389	    atomic_cmpset_rel_ptr(&sx->sx_lock, x, SX_SHARERS_LOCK(1) |
390	    (x & SX_LOCK_EXCLUSIVE_WAITERS))) {
391		LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
392		return;
393	}
394
395	/*
396	 * Lock the sleep queue so we can read the waiters bits
397	 * without any races and wakeup any shared waiters.
398	 */
399	sleepq_lock(&sx->lock_object);
400
401	/*
402	 * Preserve SX_LOCK_EXCLUSIVE_WAITERS while downgraded to a single
403	 * shared lock.  If there are any shared waiters, wake them up.
404	 */
405	wakeup_swapper = 0;
406	x = sx->sx_lock;
407	atomic_store_rel_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1) |
408	    (x & SX_LOCK_EXCLUSIVE_WAITERS));
409	if (x & SX_LOCK_SHARED_WAITERS)
410		wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
411		    0, SQ_SHARED_QUEUE);
412	sleepq_release(&sx->lock_object);
413
414	LOCK_LOG_LOCK("XDOWNGRADE", &sx->lock_object, 0, 0, file, line);
415
416	if (wakeup_swapper)
417		kick_proc0();
418}
419
420/*
421 * This function represents the so-called 'hard case' for sx_xlock
422 * operation.  All 'easy case' failures are redirected to this.  Note
423 * that ideally this would be a static function, but it needs to be
424 * accessible from at least sx.h.
425 */
426int
427_sx_xlock_hard(struct sx *sx, uintptr_t tid, int opts, const char *file,
428    int line)
429{
430	GIANT_DECLARE;
431#ifdef ADAPTIVE_SX
432	volatile struct thread *owner;
433#endif
434	uintptr_t x;
435#ifdef LOCK_PROFILING
436	uint64_t waittime = 0;
437	int contested = 0;
438#endif
439	int error = 0;
440
441	/* If we already hold an exclusive lock, then recurse. */
442	if (sx_xlocked(sx)) {
443		KASSERT((sx->lock_object.lo_flags & SX_RECURSE) != 0,
444	    ("_sx_xlock_hard: recursed on non-recursive sx %s @ %s:%d\n",
445		    sx->lock_object.lo_name, file, line));
446		sx->sx_recurse++;
447		atomic_set_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
448		if (LOCK_LOG_TEST(&sx->lock_object, 0))
449			CTR2(KTR_LOCK, "%s: %p recursing", __func__, sx);
450		return (0);
451	}
452
453	if (LOCK_LOG_TEST(&sx->lock_object, 0))
454		CTR5(KTR_LOCK, "%s: %s contested (lock=%p) at %s:%d", __func__,
455		    sx->lock_object.lo_name, (void *)sx->sx_lock, file, line);
456
457	while (!atomic_cmpset_acq_ptr(&sx->sx_lock, SX_LOCK_UNLOCKED, tid)) {
458		lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
459		    &waittime);
460#ifdef ADAPTIVE_SX
461		/*
462		 * If the lock is write locked and the owner is
463		 * running on another CPU, spin until the owner stops
464		 * running or the state of the lock changes.
465		 */
466		x = sx->sx_lock;
467		if (!(x & SX_LOCK_SHARED) &&
468		    (sx->lock_object.lo_flags & SX_ADAPTIVESPIN)) {
469			x = SX_OWNER(x);
470			owner = (struct thread *)x;
471			if (TD_IS_RUNNING(owner)) {
472				if (LOCK_LOG_TEST(&sx->lock_object, 0))
473					CTR3(KTR_LOCK,
474					    "%s: spinning on %p held by %p",
475					    __func__, sx, owner);
476				GIANT_SAVE();
477				while (SX_OWNER(sx->sx_lock) == x &&
478				    TD_IS_RUNNING(owner))
479					cpu_spinwait();
480				continue;
481			}
482		}
483#endif
484
485		sleepq_lock(&sx->lock_object);
486		x = sx->sx_lock;
487
488		/*
489		 * If the lock was released while spinning on the
490		 * sleep queue chain lock, try again.
491		 */
492		if (x == SX_LOCK_UNLOCKED) {
493			sleepq_release(&sx->lock_object);
494			continue;
495		}
496
497#ifdef ADAPTIVE_SX
498		/*
499		 * The current lock owner might have started executing
500		 * on another CPU (or the lock could have changed
501		 * owners) while we were waiting on the sleep queue
502		 * chain lock.  If so, drop the sleep queue lock and try
503		 * again.
504		 */
505		if (!(x & SX_LOCK_SHARED) &&
506		    (sx->lock_object.lo_flags & SX_ADAPTIVESPIN)) {
507			owner = (struct thread *)SX_OWNER(x);
508			if (TD_IS_RUNNING(owner)) {
509				sleepq_release(&sx->lock_object);
510				continue;
511			}
512		}
513#endif
514
515		/*
516		 * If an exclusive lock was released with both shared
517		 * and exclusive waiters and a shared waiter hasn't
518		 * woken up and acquired the lock yet, sx_lock will be
519		 * set to SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS.
520		 * If we see that value, try to acquire it once.  Note
521		 * that we have to preserve SX_LOCK_EXCLUSIVE_WAITERS
522		 * as there are other exclusive waiters still.  If we
523		 * fail, restart the loop.
524		 */
525		if (x == (SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS)) {
526			if (atomic_cmpset_acq_ptr(&sx->sx_lock,
527			    SX_LOCK_UNLOCKED | SX_LOCK_EXCLUSIVE_WAITERS,
528			    tid | SX_LOCK_EXCLUSIVE_WAITERS)) {
529				sleepq_release(&sx->lock_object);
530				CTR2(KTR_LOCK, "%s: %p claimed by new writer",
531				    __func__, sx);
532				break;
533			}
534			sleepq_release(&sx->lock_object);
535			continue;
536		}
537
538		/*
539		 * Try to set the SX_LOCK_EXCLUSIVE_WAITERS.  If we fail,
540		 * than loop back and retry.
541		 */
542		if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
543			if (!atomic_cmpset_ptr(&sx->sx_lock, x,
544			    x | SX_LOCK_EXCLUSIVE_WAITERS)) {
545				sleepq_release(&sx->lock_object);
546				continue;
547			}
548			if (LOCK_LOG_TEST(&sx->lock_object, 0))
549				CTR2(KTR_LOCK, "%s: %p set excl waiters flag",
550				    __func__, sx);
551		}
552
553		/*
554		 * Since we have been unable to acquire the exclusive
555		 * lock and the exclusive waiters flag is set, we have
556		 * to sleep.
557		 */
558		if (LOCK_LOG_TEST(&sx->lock_object, 0))
559			CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
560			    __func__, sx);
561
562		GIANT_SAVE();
563		sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
564		    SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
565		    SLEEPQ_INTERRUPTIBLE : 0), SQ_EXCLUSIVE_QUEUE);
566		if (!(opts & SX_INTERRUPTIBLE))
567			sleepq_wait(&sx->lock_object, 0);
568		else
569			error = sleepq_wait_sig(&sx->lock_object, 0);
570
571		if (error) {
572			if (LOCK_LOG_TEST(&sx->lock_object, 0))
573				CTR2(KTR_LOCK,
574			"%s: interruptible sleep by %p suspended by signal",
575				    __func__, sx);
576			break;
577		}
578		if (LOCK_LOG_TEST(&sx->lock_object, 0))
579			CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
580			    __func__, sx);
581	}
582
583	GIANT_RESTORE();
584	if (!error)
585		lock_profile_obtain_lock_success(&sx->lock_object, contested,
586		    waittime, file, line);
587	return (error);
588}
589
590/*
591 * This function represents the so-called 'hard case' for sx_xunlock
592 * operation.  All 'easy case' failures are redirected to this.  Note
593 * that ideally this would be a static function, but it needs to be
594 * accessible from at least sx.h.
595 */
596void
597_sx_xunlock_hard(struct sx *sx, uintptr_t tid, const char *file, int line)
598{
599	uintptr_t x;
600	int queue, wakeup_swapper;
601
602	MPASS(!(sx->sx_lock & SX_LOCK_SHARED));
603
604	/* If the lock is recursed, then unrecurse one level. */
605	if (sx_xlocked(sx) && sx_recursed(sx)) {
606		if ((--sx->sx_recurse) == 0)
607			atomic_clear_ptr(&sx->sx_lock, SX_LOCK_RECURSED);
608		if (LOCK_LOG_TEST(&sx->lock_object, 0))
609			CTR2(KTR_LOCK, "%s: %p unrecursing", __func__, sx);
610		return;
611	}
612	MPASS(sx->sx_lock & (SX_LOCK_SHARED_WAITERS |
613	    SX_LOCK_EXCLUSIVE_WAITERS));
614	if (LOCK_LOG_TEST(&sx->lock_object, 0))
615		CTR2(KTR_LOCK, "%s: %p contested", __func__, sx);
616
617	sleepq_lock(&sx->lock_object);
618	x = SX_LOCK_UNLOCKED;
619
620	/*
621	 * The wake up algorithm here is quite simple and probably not
622	 * ideal.  It gives precedence to shared waiters if they are
623	 * present.  For this condition, we have to preserve the
624	 * state of the exclusive waiters flag.
625	 */
626	if (sx->sx_lock & SX_LOCK_SHARED_WAITERS) {
627		queue = SQ_SHARED_QUEUE;
628		x |= (sx->sx_lock & SX_LOCK_EXCLUSIVE_WAITERS);
629	} else
630		queue = SQ_EXCLUSIVE_QUEUE;
631
632	/* Wake up all the waiters for the specific queue. */
633	if (LOCK_LOG_TEST(&sx->lock_object, 0))
634		CTR3(KTR_LOCK, "%s: %p waking up all threads on %s queue",
635		    __func__, sx, queue == SQ_SHARED_QUEUE ? "shared" :
636		    "exclusive");
637	atomic_store_rel_ptr(&sx->sx_lock, x);
638	wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX, 0,
639	    queue);
640	sleepq_release(&sx->lock_object);
641	if (wakeup_swapper)
642		kick_proc0();
643}
644
645/*
646 * This function represents the so-called 'hard case' for sx_slock
647 * operation.  All 'easy case' failures are redirected to this.  Note
648 * that ideally this would be a static function, but it needs to be
649 * accessible from at least sx.h.
650 */
651int
652_sx_slock_hard(struct sx *sx, int opts, const char *file, int line)
653{
654	GIANT_DECLARE;
655#ifdef ADAPTIVE_SX
656	volatile struct thread *owner;
657#endif
658#ifdef LOCK_PROFILING
659	uint64_t waittime = 0;
660	int contested = 0;
661#endif
662	uintptr_t x;
663	int error = 0;
664
665	/*
666	 * As with rwlocks, we don't make any attempt to try to block
667	 * shared locks once there is an exclusive waiter.
668	 */
669	for (;;) {
670		x = sx->sx_lock;
671
672		/*
673		 * If no other thread has an exclusive lock then try to bump up
674		 * the count of sharers.  Since we have to preserve the state
675		 * of SX_LOCK_EXCLUSIVE_WAITERS, if we fail to acquire the
676		 * shared lock loop back and retry.
677		 */
678		if (x & SX_LOCK_SHARED) {
679			MPASS(!(x & SX_LOCK_SHARED_WAITERS));
680			if (atomic_cmpset_acq_ptr(&sx->sx_lock, x,
681			    x + SX_ONE_SHARER)) {
682				if (LOCK_LOG_TEST(&sx->lock_object, 0))
683					CTR4(KTR_LOCK,
684					    "%s: %p succeed %p -> %p", __func__,
685					    sx, (void *)x,
686					    (void *)(x + SX_ONE_SHARER));
687				break;
688			}
689			continue;
690		}
691		lock_profile_obtain_lock_failed(&sx->lock_object, &contested,
692		    &waittime);
693
694#ifdef ADAPTIVE_SX
695		/*
696		 * If the owner is running on another CPU, spin until
697		 * the owner stops running or the state of the lock
698		 * changes.
699		 */
700		if (sx->lock_object.lo_flags & SX_ADAPTIVESPIN) {
701			x = SX_OWNER(x);
702			owner = (struct thread *)x;
703			if (TD_IS_RUNNING(owner)) {
704				if (LOCK_LOG_TEST(&sx->lock_object, 0))
705					CTR3(KTR_LOCK,
706					    "%s: spinning on %p held by %p",
707					    __func__, sx, owner);
708				GIANT_SAVE();
709				while (SX_OWNER(sx->sx_lock) == x &&
710				    TD_IS_RUNNING(owner))
711					cpu_spinwait();
712				continue;
713			}
714		}
715#endif
716
717		/*
718		 * Some other thread already has an exclusive lock, so
719		 * start the process of blocking.
720		 */
721		sleepq_lock(&sx->lock_object);
722		x = sx->sx_lock;
723
724		/*
725		 * The lock could have been released while we spun.
726		 * In this case loop back and retry.
727		 */
728		if (x & SX_LOCK_SHARED) {
729			sleepq_release(&sx->lock_object);
730			continue;
731		}
732
733#ifdef ADAPTIVE_SX
734		/*
735		 * If the owner is running on another CPU, spin until
736		 * the owner stops running or the state of the lock
737		 * changes.
738		 */
739		if (!(x & SX_LOCK_SHARED) &&
740		    (sx->lock_object.lo_flags & SX_ADAPTIVESPIN)) {
741			owner = (struct thread *)SX_OWNER(x);
742			if (TD_IS_RUNNING(owner)) {
743				sleepq_release(&sx->lock_object);
744				continue;
745			}
746		}
747#endif
748
749		/*
750		 * Try to set the SX_LOCK_SHARED_WAITERS flag.  If we
751		 * fail to set it drop the sleep queue lock and loop
752		 * back.
753		 */
754		if (!(x & SX_LOCK_SHARED_WAITERS)) {
755			if (!atomic_cmpset_ptr(&sx->sx_lock, x,
756			    x | SX_LOCK_SHARED_WAITERS)) {
757				sleepq_release(&sx->lock_object);
758				continue;
759			}
760			if (LOCK_LOG_TEST(&sx->lock_object, 0))
761				CTR2(KTR_LOCK, "%s: %p set shared waiters flag",
762				    __func__, sx);
763		}
764
765		/*
766		 * Since we have been unable to acquire the shared lock,
767		 * we have to sleep.
768		 */
769		if (LOCK_LOG_TEST(&sx->lock_object, 0))
770			CTR2(KTR_LOCK, "%s: %p blocking on sleep queue",
771			    __func__, sx);
772
773		GIANT_SAVE();
774		sleepq_add(&sx->lock_object, NULL, sx->lock_object.lo_name,
775		    SLEEPQ_SX | ((opts & SX_INTERRUPTIBLE) ?
776		    SLEEPQ_INTERRUPTIBLE : 0), SQ_SHARED_QUEUE);
777		if (!(opts & SX_INTERRUPTIBLE))
778			sleepq_wait(&sx->lock_object, 0);
779		else
780			error = sleepq_wait_sig(&sx->lock_object, 0);
781
782		if (error) {
783			if (LOCK_LOG_TEST(&sx->lock_object, 0))
784				CTR2(KTR_LOCK,
785			"%s: interruptible sleep by %p suspended by signal",
786				    __func__, sx);
787			break;
788		}
789		if (LOCK_LOG_TEST(&sx->lock_object, 0))
790			CTR2(KTR_LOCK, "%s: %p resuming from sleep queue",
791			    __func__, sx);
792	}
793	if (error == 0)
794		lock_profile_obtain_lock_success(&sx->lock_object, contested,
795		    waittime, file, line);
796
797	GIANT_RESTORE();
798	return (error);
799}
800
801/*
802 * This function represents the so-called 'hard case' for sx_sunlock
803 * operation.  All 'easy case' failures are redirected to this.  Note
804 * that ideally this would be a static function, but it needs to be
805 * accessible from at least sx.h.
806 */
807void
808_sx_sunlock_hard(struct sx *sx, const char *file, int line)
809{
810	uintptr_t x;
811	int wakeup_swapper;
812
813	for (;;) {
814		x = sx->sx_lock;
815
816		/*
817		 * We should never have sharers while at least one thread
818		 * holds a shared lock.
819		 */
820		KASSERT(!(x & SX_LOCK_SHARED_WAITERS),
821		    ("%s: waiting sharers", __func__));
822
823		/*
824		 * See if there is more than one shared lock held.  If
825		 * so, just drop one and return.
826		 */
827		if (SX_SHARERS(x) > 1) {
828			if (atomic_cmpset_ptr(&sx->sx_lock, x,
829			    x - SX_ONE_SHARER)) {
830				if (LOCK_LOG_TEST(&sx->lock_object, 0))
831					CTR4(KTR_LOCK,
832					    "%s: %p succeeded %p -> %p",
833					    __func__, sx, (void *)x,
834					    (void *)(x - SX_ONE_SHARER));
835				break;
836			}
837			continue;
838		}
839
840		/*
841		 * If there aren't any waiters for an exclusive lock,
842		 * then try to drop it quickly.
843		 */
844		if (!(x & SX_LOCK_EXCLUSIVE_WAITERS)) {
845			MPASS(x == SX_SHARERS_LOCK(1));
846			if (atomic_cmpset_ptr(&sx->sx_lock, SX_SHARERS_LOCK(1),
847			    SX_LOCK_UNLOCKED)) {
848				if (LOCK_LOG_TEST(&sx->lock_object, 0))
849					CTR2(KTR_LOCK, "%s: %p last succeeded",
850					    __func__, sx);
851				break;
852			}
853			continue;
854		}
855
856		/*
857		 * At this point, there should just be one sharer with
858		 * exclusive waiters.
859		 */
860		MPASS(x == (SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS));
861
862		sleepq_lock(&sx->lock_object);
863
864		/*
865		 * Wake up semantic here is quite simple:
866		 * Just wake up all the exclusive waiters.
867		 * Note that the state of the lock could have changed,
868		 * so if it fails loop back and retry.
869		 */
870		if (!atomic_cmpset_ptr(&sx->sx_lock,
871		    SX_SHARERS_LOCK(1) | SX_LOCK_EXCLUSIVE_WAITERS,
872		    SX_LOCK_UNLOCKED)) {
873			sleepq_release(&sx->lock_object);
874			continue;
875		}
876		if (LOCK_LOG_TEST(&sx->lock_object, 0))
877			CTR2(KTR_LOCK, "%s: %p waking up all thread on"
878			    "exclusive queue", __func__, sx);
879		wakeup_swapper = sleepq_broadcast(&sx->lock_object, SLEEPQ_SX,
880		    0, SQ_EXCLUSIVE_QUEUE);
881		sleepq_release(&sx->lock_object);
882		if (wakeup_swapper)
883			kick_proc0();
884		break;
885	}
886}
887
888#ifdef INVARIANT_SUPPORT
889#ifndef INVARIANTS
890#undef	_sx_assert
891#endif
892
893/*
894 * In the non-WITNESS case, sx_assert() can only detect that at least
895 * *some* thread owns an slock, but it cannot guarantee that *this*
896 * thread owns an slock.
897 */
898void
899_sx_assert(struct sx *sx, int what, const char *file, int line)
900{
901#ifndef WITNESS
902	int slocked = 0;
903#endif
904
905	if (panicstr != NULL)
906		return;
907	switch (what) {
908	case SA_SLOCKED:
909	case SA_SLOCKED | SA_NOTRECURSED:
910	case SA_SLOCKED | SA_RECURSED:
911#ifndef WITNESS
912		slocked = 1;
913		/* FALLTHROUGH */
914#endif
915	case SA_LOCKED:
916	case SA_LOCKED | SA_NOTRECURSED:
917	case SA_LOCKED | SA_RECURSED:
918#ifdef WITNESS
919		witness_assert(&sx->lock_object, what, file, line);
920#else
921		/*
922		 * If some other thread has an exclusive lock or we
923		 * have one and are asserting a shared lock, fail.
924		 * Also, if no one has a lock at all, fail.
925		 */
926		if (sx->sx_lock == SX_LOCK_UNLOCKED ||
927		    (!(sx->sx_lock & SX_LOCK_SHARED) && (slocked ||
928		    sx_xholder(sx) != curthread)))
929			panic("Lock %s not %slocked @ %s:%d\n",
930			    sx->lock_object.lo_name, slocked ? "share " : "",
931			    file, line);
932
933		if (!(sx->sx_lock & SX_LOCK_SHARED)) {
934			if (sx_recursed(sx)) {
935				if (what & SA_NOTRECURSED)
936					panic("Lock %s recursed @ %s:%d\n",
937					    sx->lock_object.lo_name, file,
938					    line);
939			} else if (what & SA_RECURSED)
940				panic("Lock %s not recursed @ %s:%d\n",
941				    sx->lock_object.lo_name, file, line);
942		}
943#endif
944		break;
945	case SA_XLOCKED:
946	case SA_XLOCKED | SA_NOTRECURSED:
947	case SA_XLOCKED | SA_RECURSED:
948		if (sx_xholder(sx) != curthread)
949			panic("Lock %s not exclusively locked @ %s:%d\n",
950			    sx->lock_object.lo_name, file, line);
951		if (sx_recursed(sx)) {
952			if (what & SA_NOTRECURSED)
953				panic("Lock %s recursed @ %s:%d\n",
954				    sx->lock_object.lo_name, file, line);
955		} else if (what & SA_RECURSED)
956			panic("Lock %s not recursed @ %s:%d\n",
957			    sx->lock_object.lo_name, file, line);
958		break;
959	case SA_UNLOCKED:
960#ifdef WITNESS
961		witness_assert(&sx->lock_object, what, file, line);
962#else
963		/*
964		 * If we hold an exclusve lock fail.  We can't
965		 * reliably check to see if we hold a shared lock or
966		 * not.
967		 */
968		if (sx_xholder(sx) == curthread)
969			panic("Lock %s exclusively locked @ %s:%d\n",
970			    sx->lock_object.lo_name, file, line);
971#endif
972		break;
973	default:
974		panic("Unknown sx lock assertion: %d @ %s:%d", what, file,
975		    line);
976	}
977}
978#endif	/* INVARIANT_SUPPORT */
979
980#ifdef DDB
981static void
982db_show_sx(struct lock_object *lock)
983{
984	struct thread *td;
985	struct sx *sx;
986
987	sx = (struct sx *)lock;
988
989	db_printf(" state: ");
990	if (sx->sx_lock == SX_LOCK_UNLOCKED)
991		db_printf("UNLOCKED\n");
992	else if (sx->sx_lock == SX_LOCK_DESTROYED) {
993		db_printf("DESTROYED\n");
994		return;
995	} else if (sx->sx_lock & SX_LOCK_SHARED)
996		db_printf("SLOCK: %ju\n", (uintmax_t)SX_SHARERS(sx->sx_lock));
997	else {
998		td = sx_xholder(sx);
999		db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td,
1000		    td->td_tid, td->td_proc->p_pid, td->td_name);
1001		if (sx_recursed(sx))
1002			db_printf(" recursed: %d\n", sx->sx_recurse);
1003	}
1004
1005	db_printf(" waiters: ");
1006	switch(sx->sx_lock &
1007	    (SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS)) {
1008	case SX_LOCK_SHARED_WAITERS:
1009		db_printf("shared\n");
1010		break;
1011	case SX_LOCK_EXCLUSIVE_WAITERS:
1012		db_printf("exclusive\n");
1013		break;
1014	case SX_LOCK_SHARED_WAITERS | SX_LOCK_EXCLUSIVE_WAITERS:
1015		db_printf("exclusive and shared\n");
1016		break;
1017	default:
1018		db_printf("none\n");
1019	}
1020}
1021
1022/*
1023 * Check to see if a thread that is blocked on a sleep queue is actually
1024 * blocked on an sx lock.  If so, output some details and return true.
1025 * If the lock has an exclusive owner, return that in *ownerp.
1026 */
1027int
1028sx_chain(struct thread *td, struct thread **ownerp)
1029{
1030	struct sx *sx;
1031
1032	/*
1033	 * Check to see if this thread is blocked on an sx lock.
1034	 * First, we check the lock class.  If that is ok, then we
1035	 * compare the lock name against the wait message.
1036	 */
1037	sx = td->td_wchan;
1038	if (LOCK_CLASS(&sx->lock_object) != &lock_class_sx ||
1039	    sx->lock_object.lo_name != td->td_wmesg)
1040		return (0);
1041
1042	/* We think we have an sx lock, so output some details. */
1043	db_printf("blocked on sx \"%s\" ", td->td_wmesg);
1044	*ownerp = sx_xholder(sx);
1045	if (sx->sx_lock & SX_LOCK_SHARED)
1046		db_printf("SLOCK (count %ju)\n",
1047		    (uintmax_t)SX_SHARERS(sx->sx_lock));
1048	else
1049		db_printf("XLOCK\n");
1050	return (1);
1051}
1052#endif
1053