xref: /openbsd-src/sys/kern/kern_synch.c (revision aa563902a9fb835e591cb776b8d405d10f098e06)
1 /*	$OpenBSD: kern_synch.c,v 1.194 2023/07/11 07:02:43 claudio Exp $	*/
2 /*	$NetBSD: kern_synch.c,v 1.37 1996/04/22 01:38:37 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1990, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  * (c) UNIX System Laboratories, Inc.
8  * All or some portions of this file are derived from material licensed
9  * to the University of California by American Telephone and Telegraph
10  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11  * the permission of UNIX System Laboratories, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	@(#)kern_synch.c	8.6 (Berkeley) 1/21/94
38  */
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/proc.h>
43 #include <sys/kernel.h>
44 #include <sys/signalvar.h>
45 #include <sys/sched.h>
46 #include <sys/timeout.h>
47 #include <sys/mount.h>
48 #include <sys/syscallargs.h>
49 #include <sys/refcnt.h>
50 #include <sys/atomic.h>
51 #include <sys/tracepoint.h>
52 
53 #include <ddb/db_output.h>
54 
55 #include <machine/spinlock.h>
56 
57 #ifdef DIAGNOSTIC
58 #include <sys/syslog.h>
59 #endif
60 
61 #ifdef KTRACE
62 #include <sys/ktrace.h>
63 #endif
64 
65 int	sleep_signal_check(void);
66 int	thrsleep(struct proc *, struct sys___thrsleep_args *);
67 int	thrsleep_unlock(void *);
68 
69 /*
70  * We're only looking at 7 bits of the address; everything is
71  * aligned to 4, lots of things are aligned to greater powers
72  * of 2.  Shift right by 8, i.e. drop the bottom 256 worth.
73  */
74 #define TABLESIZE	128
75 #define LOOKUP(x)	(((long)(x) >> 8) & (TABLESIZE - 1))
76 TAILQ_HEAD(slpque,proc) slpque[TABLESIZE];
77 
78 void
79 sleep_queue_init(void)
80 {
81 	int i;
82 
83 	for (i = 0; i < TABLESIZE; i++)
84 		TAILQ_INIT(&slpque[i]);
85 }
86 
87 /*
88  * Global sleep channel for threads that do not want to
89  * receive wakeup(9) broadcasts.
90  */
91 int nowake;
92 
93 /*
94  * During autoconfiguration or after a panic, a sleep will simply
95  * lower the priority briefly to allow interrupts, then return.
96  * The priority to be used (safepri) is machine-dependent, thus this
97  * value is initialized and maintained in the machine-dependent layers.
98  * This priority will typically be 0, or the lowest priority
99  * that is safe for use on the interrupt stack; it can be made
100  * higher to block network software interrupts after panics.
101  */
102 extern int safepri;
103 
104 /*
105  * General sleep call.  Suspends the current process until a wakeup is
106  * performed on the specified identifier.  The process will then be made
107  * runnable with the specified priority.  Sleeps at most timo/hz seconds
108  * (0 means no timeout).  If pri includes PCATCH flag, signals are checked
109  * before and after sleeping, else signals are not checked.  Returns 0 if
110  * awakened, EWOULDBLOCK if the timeout expires.  If PCATCH is set and a
111  * signal needs to be delivered, ERESTART is returned if the current system
112  * call should be restarted if possible, and EINTR is returned if the system
113  * call should be interrupted by the signal (return EINTR).
114  */
115 int
116 tsleep(const volatile void *ident, int priority, const char *wmesg, int timo)
117 {
118 	struct sleep_state sls;
119 #ifdef MULTIPROCESSOR
120 	int hold_count;
121 #endif
122 
123 	KASSERT((priority & ~(PRIMASK | PCATCH)) == 0);
124 	KASSERT(ident != &nowake || ISSET(priority, PCATCH) || timo != 0);
125 
126 #ifdef MULTIPROCESSOR
127 	KASSERT(ident == &nowake || timo || _kernel_lock_held());
128 #endif
129 
130 #ifdef DDB
131 	if (cold == 2)
132 		db_stack_dump();
133 #endif
134 	if (cold || panicstr) {
135 		int s;
136 		/*
137 		 * After a panic, or during autoconfiguration,
138 		 * just give interrupts a chance, then just return;
139 		 * don't run any other procs or panic below,
140 		 * in case this is the idle process and already asleep.
141 		 */
142 		s = splhigh();
143 		splx(safepri);
144 #ifdef MULTIPROCESSOR
145 		if (_kernel_lock_held()) {
146 			hold_count = __mp_release_all(&kernel_lock);
147 			__mp_acquire_count(&kernel_lock, hold_count);
148 		}
149 #endif
150 		splx(s);
151 		return (0);
152 	}
153 
154 	sleep_setup(&sls, ident, priority, wmesg);
155 	return sleep_finish(&sls, priority, timo, 1);
156 }
157 
158 int
159 tsleep_nsec(const volatile void *ident, int priority, const char *wmesg,
160     uint64_t nsecs)
161 {
162 	uint64_t to_ticks;
163 
164 	if (nsecs == INFSLP)
165 		return tsleep(ident, priority, wmesg, 0);
166 #ifdef DIAGNOSTIC
167 	if (nsecs == 0) {
168 		log(LOG_WARNING,
169 		    "%s: %s[%d]: %s: trying to sleep zero nanoseconds\n",
170 		    __func__, curproc->p_p->ps_comm, curproc->p_p->ps_pid,
171 		    wmesg);
172 	}
173 #endif
174 	/*
175 	 * We want to sleep at least nsecs nanoseconds worth of ticks.
176 	 *
177 	 *  - Clamp nsecs to prevent arithmetic overflow.
178 	 *
179 	 *  - Round nsecs up to account for any nanoseconds that do not
180 	 *    divide evenly into tick_nsec, otherwise we'll lose them to
181 	 *    integer division in the next step.  We add (tick_nsec - 1)
182 	 *    to keep from introducing a spurious tick if there are no
183 	 *    such nanoseconds, i.e. nsecs % tick_nsec == 0.
184 	 *
185 	 *  - Divide the rounded value to a count of ticks.  We divide
186 	 *    by (tick_nsec + 1) to discard the extra tick introduced if,
187 	 *    before rounding, nsecs % tick_nsec == 1.
188 	 *
189 	 *  - Finally, add a tick to the result.  We need to wait out
190 	 *    the current tick before we can begin counting our interval,
191 	 *    as we do not know how much time has elapsed since the
192 	 *    current tick began.
193 	 */
194 	nsecs = MIN(nsecs, UINT64_MAX - tick_nsec);
195 	to_ticks = (nsecs + tick_nsec - 1) / (tick_nsec + 1) + 1;
196 	if (to_ticks > INT_MAX)
197 		to_ticks = INT_MAX;
198 	return tsleep(ident, priority, wmesg, (int)to_ticks);
199 }
200 
201 /*
202  * Same as tsleep, but if we have a mutex provided, then once we've
203  * entered the sleep queue we drop the mutex. After sleeping we re-lock.
204  */
205 int
206 msleep(const volatile void *ident, struct mutex *mtx, int priority,
207     const char *wmesg, int timo)
208 {
209 	struct sleep_state sls;
210 	int error, spl;
211 #ifdef MULTIPROCESSOR
212 	int hold_count;
213 #endif
214 
215 	KASSERT((priority & ~(PRIMASK | PCATCH | PNORELOCK)) == 0);
216 	KASSERT(ident != &nowake || ISSET(priority, PCATCH) || timo != 0);
217 	KASSERT(mtx != NULL);
218 
219 #ifdef DDB
220 	if (cold == 2)
221 		db_stack_dump();
222 #endif
223 	if (cold || panicstr) {
224 		/*
225 		 * After a panic, or during autoconfiguration,
226 		 * just give interrupts a chance, then just return;
227 		 * don't run any other procs or panic below,
228 		 * in case this is the idle process and already asleep.
229 		 */
230 		spl = MUTEX_OLDIPL(mtx);
231 		MUTEX_OLDIPL(mtx) = safepri;
232 		mtx_leave(mtx);
233 #ifdef MULTIPROCESSOR
234 		if (_kernel_lock_held()) {
235 			hold_count = __mp_release_all(&kernel_lock);
236 			__mp_acquire_count(&kernel_lock, hold_count);
237 		}
238 #endif
239 		if ((priority & PNORELOCK) == 0) {
240 			mtx_enter(mtx);
241 			MUTEX_OLDIPL(mtx) = spl;
242 		} else
243 			splx(spl);
244 		return (0);
245 	}
246 
247 	sleep_setup(&sls, ident, priority, wmesg);
248 
249 	mtx_leave(mtx);
250 	/* signal may stop the process, release mutex before that */
251 	error = sleep_finish(&sls, priority, timo, 1);
252 
253 	if ((priority & PNORELOCK) == 0)
254 		mtx_enter(mtx);
255 
256 	return error;
257 }
258 
259 int
260 msleep_nsec(const volatile void *ident, struct mutex *mtx, int priority,
261     const char *wmesg, uint64_t nsecs)
262 {
263 	uint64_t to_ticks;
264 
265 	if (nsecs == INFSLP)
266 		return msleep(ident, mtx, priority, wmesg, 0);
267 #ifdef DIAGNOSTIC
268 	if (nsecs == 0) {
269 		log(LOG_WARNING,
270 		    "%s: %s[%d]: %s: trying to sleep zero nanoseconds\n",
271 		    __func__, curproc->p_p->ps_comm, curproc->p_p->ps_pid,
272 		    wmesg);
273 	}
274 #endif
275 	nsecs = MIN(nsecs, UINT64_MAX - tick_nsec);
276 	to_ticks = (nsecs + tick_nsec - 1) / (tick_nsec + 1) + 1;
277 	if (to_ticks > INT_MAX)
278 		to_ticks = INT_MAX;
279 	return msleep(ident, mtx, priority, wmesg, (int)to_ticks);
280 }
281 
282 /*
283  * Same as tsleep, but if we have a rwlock provided, then once we've
284  * entered the sleep queue we drop the it. After sleeping we re-lock.
285  */
286 int
287 rwsleep(const volatile void *ident, struct rwlock *rwl, int priority,
288     const char *wmesg, int timo)
289 {
290 	struct sleep_state sls;
291 	int error, status;
292 
293 	KASSERT((priority & ~(PRIMASK | PCATCH | PNORELOCK)) == 0);
294 	KASSERT(ident != &nowake || ISSET(priority, PCATCH) || timo != 0);
295 	KASSERT(ident != rwl);
296 	rw_assert_anylock(rwl);
297 	status = rw_status(rwl);
298 
299 	sleep_setup(&sls, ident, priority, wmesg);
300 
301 	rw_exit(rwl);
302 	/* signal may stop the process, release rwlock before that */
303 	error = sleep_finish(&sls, priority, timo, 1);
304 
305 	if ((priority & PNORELOCK) == 0)
306 		rw_enter(rwl, status);
307 
308 	return error;
309 }
310 
311 int
312 rwsleep_nsec(const volatile void *ident, struct rwlock *rwl, int priority,
313     const char *wmesg, uint64_t nsecs)
314 {
315 	uint64_t to_ticks;
316 
317 	if (nsecs == INFSLP)
318 		return rwsleep(ident, rwl, priority, wmesg, 0);
319 #ifdef DIAGNOSTIC
320 	if (nsecs == 0) {
321 		log(LOG_WARNING,
322 		    "%s: %s[%d]: %s: trying to sleep zero nanoseconds\n",
323 		    __func__, curproc->p_p->ps_comm, curproc->p_p->ps_pid,
324 		    wmesg);
325 	}
326 #endif
327 	nsecs = MIN(nsecs, UINT64_MAX - tick_nsec);
328 	to_ticks = (nsecs + tick_nsec - 1) / (tick_nsec + 1) + 1;
329 	if (to_ticks > INT_MAX)
330 		to_ticks = INT_MAX;
331 	return 	rwsleep(ident, rwl, priority, wmesg, (int)to_ticks);
332 }
333 
334 void
335 sleep_setup(struct sleep_state *sls, const volatile void *ident, int prio,
336     const char *wmesg)
337 {
338 	struct proc *p = curproc;
339 	int s;
340 
341 #ifdef DIAGNOSTIC
342 	if (p->p_flag & P_CANTSLEEP)
343 		panic("sleep: %s failed insomnia", p->p_p->ps_comm);
344 	if (ident == NULL)
345 		panic("tsleep: no ident");
346 	if (p->p_stat != SONPROC)
347 		panic("tsleep: not SONPROC");
348 #endif
349 
350 	SCHED_LOCK(s);
351 
352 	TRACEPOINT(sched, sleep, NULL);
353 
354 	p->p_wchan = ident;
355 	p->p_wmesg = wmesg;
356 	p->p_slptime = 0;
357 	p->p_slppri = prio & PRIMASK;
358 	atomic_setbits_int(&p->p_flag, P_WSLEEP);
359 	TAILQ_INSERT_TAIL(&slpque[LOOKUP(ident)], p, p_runq);
360 	if (prio & PCATCH)
361 		atomic_setbits_int(&p->p_flag, P_SINTR);
362 	p->p_stat = SSLEEP;
363 
364 	SCHED_UNLOCK(s);
365 }
366 
367 int
368 sleep_finish(struct sleep_state *sls, int prio, int timo, int do_sleep)
369 {
370 	struct proc *p = curproc;
371 	int s, catch, error = 0, error1 = 0;
372 
373 	catch = prio & PCATCH;
374 
375 	if (timo != 0) {
376 		KASSERT((p->p_flag & P_TIMEOUT) == 0);
377 		timeout_add(&p->p_sleep_to, timo);
378 	}
379 
380 	SCHED_LOCK(s);
381 	if (catch != 0) {
382 		/*
383 		 * We put ourselves on the sleep queue and start our
384 		 * timeout before calling sleep_signal_check(), as we could
385 		 * stop there, and a wakeup or a SIGCONT (or both) could
386 		 * occur while we were stopped.  A SIGCONT would cause
387 		 * us to be marked as SSLEEP without resuming us, thus
388 		 * we must be ready for sleep when sleep_signal_check() is
389 		 * called.
390 		 */
391 		if ((error = sleep_signal_check()) != 0) {
392 			catch = 0;
393 			do_sleep = 0;
394 		}
395 	}
396 
397 	/*
398 	 * If the wakeup happens while going to sleep, p->p_wchan
399 	 * will be NULL. In that case unwind immediately but still
400 	 * check for possible signals and timeouts.
401 	 */
402 	if (p->p_wchan == NULL)
403 		do_sleep = 0;
404 
405 	atomic_clearbits_int(&p->p_flag, P_WSLEEP);
406 	if (do_sleep) {
407 		p->p_ru.ru_nvcsw++;
408 		mi_switch();
409 	} else {
410 		unsleep(p);
411 		p->p_stat = SONPROC;
412 	}
413 
414 #ifdef DIAGNOSTIC
415 	if (p->p_stat != SONPROC)
416 		panic("sleep_finish !SONPROC");
417 #endif
418 
419 	p->p_cpu->ci_schedstate.spc_curpriority = p->p_usrpri;
420 	SCHED_UNLOCK(s);
421 
422 	/*
423 	 * Even though this belongs to the signal handling part of sleep,
424 	 * we need to clear it before the ktrace.
425 	 */
426 	atomic_clearbits_int(&p->p_flag, P_SINTR);
427 
428 	if (timo != 0) {
429 		if (p->p_flag & P_TIMEOUT) {
430 			error1 = EWOULDBLOCK;
431 		} else {
432 			/* This can sleep. It must not use timeouts. */
433 			timeout_del_barrier(&p->p_sleep_to);
434 		}
435 		atomic_clearbits_int(&p->p_flag, P_TIMEOUT);
436 	}
437 
438 	/* Check if thread was woken up because of a unwind or signal */
439 	if (catch != 0)
440 		error = sleep_signal_check();
441 
442 	/* Signal errors are higher priority than timeouts. */
443 	if (error == 0 && error1 != 0)
444 		error = error1;
445 
446 	return error;
447 }
448 
449 /*
450  * Check and handle signals and suspensions around a sleep cycle.
451  */
452 int
453 sleep_signal_check(void)
454 {
455 	struct proc *p = curproc;
456 	struct sigctx ctx;
457 	int err, sig;
458 
459 	if ((err = single_thread_check(p, 1)) != 0)
460 		return err;
461 	if ((sig = cursig(p, &ctx)) != 0) {
462 		if (ctx.sig_intr)
463 			return EINTR;
464 		else
465 			return ERESTART;
466 	}
467 	return 0;
468 }
469 
470 int
471 wakeup_proc(struct proc *p, const volatile void *chan, int flags)
472 {
473 	int awakened = 0;
474 
475 	SCHED_ASSERT_LOCKED();
476 
477 	if (p->p_wchan != NULL &&
478 	   ((chan == NULL) || (p->p_wchan == chan))) {
479 		awakened = 1;
480 		if (flags)
481 			atomic_setbits_int(&p->p_flag, flags);
482 		if (p->p_stat == SSLEEP)
483 			setrunnable(p);
484 		else if (p->p_stat == SSTOP)
485 			unsleep(p);
486 #ifdef DIAGNOSTIC
487 		else
488 			panic("wakeup: p_stat is %d", (int)p->p_stat);
489 #endif
490 	}
491 
492 	return awakened;
493 }
494 
495 
496 /*
497  * Implement timeout for tsleep.
498  * If process hasn't been awakened (wchan non-zero),
499  * set timeout flag and undo the sleep.  If proc
500  * is stopped, just unsleep so it will remain stopped.
501  */
502 void
503 endtsleep(void *arg)
504 {
505 	struct proc *p = arg;
506 	int s;
507 
508 	SCHED_LOCK(s);
509 	wakeup_proc(p, NULL, P_TIMEOUT);
510 	SCHED_UNLOCK(s);
511 }
512 
513 /*
514  * Remove a process from its wait queue
515  */
516 void
517 unsleep(struct proc *p)
518 {
519 	SCHED_ASSERT_LOCKED();
520 
521 	if (p->p_wchan != NULL) {
522 		TAILQ_REMOVE(&slpque[LOOKUP(p->p_wchan)], p, p_runq);
523 		p->p_wchan = NULL;
524 		TRACEPOINT(sched, wakeup, p->p_tid + THREAD_PID_OFFSET,
525 		    p->p_p->ps_pid);
526 	}
527 }
528 
529 /*
530  * Make a number of processes sleeping on the specified identifier runnable.
531  */
532 void
533 wakeup_n(const volatile void *ident, int n)
534 {
535 	struct slpque *qp;
536 	struct proc *p;
537 	struct proc *pnext;
538 	int s;
539 
540 	SCHED_LOCK(s);
541 	qp = &slpque[LOOKUP(ident)];
542 	for (p = TAILQ_FIRST(qp); p != NULL && n != 0; p = pnext) {
543 		pnext = TAILQ_NEXT(p, p_runq);
544 #ifdef DIAGNOSTIC
545 		if (p->p_stat != SSLEEP && p->p_stat != SSTOP)
546 			panic("wakeup: p_stat is %d", (int)p->p_stat);
547 #endif
548 		if (wakeup_proc(p, ident, 0))
549 			--n;
550 	}
551 	SCHED_UNLOCK(s);
552 }
553 
554 /*
555  * Make all processes sleeping on the specified identifier runnable.
556  */
557 void
558 wakeup(const volatile void *chan)
559 {
560 	wakeup_n(chan, -1);
561 }
562 
563 int
564 sys_sched_yield(struct proc *p, void *v, register_t *retval)
565 {
566 	struct proc *q;
567 	uint8_t newprio;
568 	int s;
569 
570 	SCHED_LOCK(s);
571 	/*
572 	 * If one of the threads of a multi-threaded process called
573 	 * sched_yield(2), drop its priority to ensure its siblings
574 	 * can make some progress.
575 	 */
576 	newprio = p->p_usrpri;
577 	TAILQ_FOREACH(q, &p->p_p->ps_threads, p_thr_link)
578 		newprio = max(newprio, q->p_runpri);
579 	setrunqueue(p->p_cpu, p, newprio);
580 	p->p_ru.ru_nvcsw++;
581 	mi_switch();
582 	SCHED_UNLOCK(s);
583 
584 	return (0);
585 }
586 
587 int
588 thrsleep_unlock(void *lock)
589 {
590 	static _atomic_lock_t unlocked = _ATOMIC_LOCK_UNLOCKED;
591 	_atomic_lock_t *atomiclock = lock;
592 
593 	if (!lock)
594 		return 0;
595 
596 	return copyout(&unlocked, atomiclock, sizeof(unlocked));
597 }
598 
599 struct tslpentry {
600 	TAILQ_ENTRY(tslpentry)	tslp_link;
601 	long			tslp_ident;
602 };
603 
604 /* thrsleep queue shared between processes */
605 static struct tslpqueue thrsleep_queue = TAILQ_HEAD_INITIALIZER(thrsleep_queue);
606 static struct rwlock thrsleep_lock = RWLOCK_INITIALIZER("thrsleeplk");
607 
608 int
609 thrsleep(struct proc *p, struct sys___thrsleep_args *v)
610 {
611 	struct sys___thrsleep_args /* {
612 		syscallarg(const volatile void *) ident;
613 		syscallarg(clockid_t) clock_id;
614 		syscallarg(const struct timespec *) tp;
615 		syscallarg(void *) lock;
616 		syscallarg(const int *) abort;
617 	} */ *uap = v;
618 	long ident = (long)SCARG(uap, ident);
619 	struct tslpentry entry;
620 	struct tslpqueue *queue;
621 	struct rwlock *qlock;
622 	struct timespec *tsp = (struct timespec *)SCARG(uap, tp);
623 	void *lock = SCARG(uap, lock);
624 	uint64_t nsecs = INFSLP;
625 	int abort = 0, error;
626 	clockid_t clock_id = SCARG(uap, clock_id);
627 
628 	if (ident == 0)
629 		return (EINVAL);
630 	if (tsp != NULL) {
631 		struct timespec now;
632 
633 		if ((error = clock_gettime(p, clock_id, &now)))
634 			return (error);
635 #ifdef KTRACE
636 		if (KTRPOINT(p, KTR_STRUCT))
637 			ktrabstimespec(p, tsp);
638 #endif
639 
640 		if (timespeccmp(tsp, &now, <=)) {
641 			/* already passed: still do the unlock */
642 			if ((error = thrsleep_unlock(lock)))
643 				return (error);
644 			return (EWOULDBLOCK);
645 		}
646 
647 		timespecsub(tsp, &now, tsp);
648 		nsecs = MIN(TIMESPEC_TO_NSEC(tsp), MAXTSLP);
649 	}
650 
651 	if (ident == -1) {
652 		queue = &thrsleep_queue;
653 		qlock = &thrsleep_lock;
654 	} else {
655 		queue = &p->p_p->ps_tslpqueue;
656 		qlock = &p->p_p->ps_lock;
657 	}
658 
659 	/* Interlock with wakeup. */
660 	entry.tslp_ident = ident;
661 	rw_enter_write(qlock);
662 	TAILQ_INSERT_TAIL(queue, &entry, tslp_link);
663 	rw_exit_write(qlock);
664 
665 	error = thrsleep_unlock(lock);
666 
667 	if (error == 0 && SCARG(uap, abort) != NULL)
668 		error = copyin(SCARG(uap, abort), &abort, sizeof(abort));
669 
670 	rw_enter_write(qlock);
671 	if (error != 0)
672 		goto out;
673 	if (abort != 0) {
674 		error = EINTR;
675 		goto out;
676 	}
677 	if (entry.tslp_ident != 0) {
678 		error = rwsleep_nsec(&entry, qlock, PWAIT|PCATCH, "thrsleep",
679 		    nsecs);
680 	}
681 
682 out:
683 	if (entry.tslp_ident != 0)
684 		TAILQ_REMOVE(queue, &entry, tslp_link);
685 	rw_exit_write(qlock);
686 
687 	if (error == ERESTART)
688 		error = ECANCELED;
689 
690 	return (error);
691 
692 }
693 
694 int
695 sys___thrsleep(struct proc *p, void *v, register_t *retval)
696 {
697 	struct sys___thrsleep_args /* {
698 		syscallarg(const volatile void *) ident;
699 		syscallarg(clockid_t) clock_id;
700 		syscallarg(struct timespec *) tp;
701 		syscallarg(void *) lock;
702 		syscallarg(const int *) abort;
703 	} */ *uap = v;
704 	struct timespec ts;
705 	int error;
706 
707 	if (SCARG(uap, tp) != NULL) {
708 		if ((error = copyin(SCARG(uap, tp), &ts, sizeof(ts)))) {
709 			*retval = error;
710 			return 0;
711 		}
712 		if (!timespecisvalid(&ts)) {
713 			*retval = EINVAL;
714 			return 0;
715 		}
716 		SCARG(uap, tp) = &ts;
717 	}
718 
719 	*retval = thrsleep(p, uap);
720 	return 0;
721 }
722 
723 int
724 sys___thrwakeup(struct proc *p, void *v, register_t *retval)
725 {
726 	struct sys___thrwakeup_args /* {
727 		syscallarg(const volatile void *) ident;
728 		syscallarg(int) n;
729 	} */ *uap = v;
730 	struct tslpentry *entry, *tmp;
731 	struct tslpqueue *queue;
732 	struct rwlock *qlock;
733 	long ident = (long)SCARG(uap, ident);
734 	int n = SCARG(uap, n);
735 	int found = 0;
736 
737 	if (ident == 0)
738 		*retval = EINVAL;
739 	else {
740 		if (ident == -1) {
741 			queue = &thrsleep_queue;
742 			qlock = &thrsleep_lock;
743 			/*
744 			 * Wake up all waiters with ident -1. This is needed
745 			 * because ident -1 can be shared by multiple userspace
746 			 * lock state machines concurrently. The implementation
747 			 * has no way to direct the wakeup to a particular
748 			 * state machine.
749 			 */
750 			n = 0;
751 		} else {
752 			queue = &p->p_p->ps_tslpqueue;
753 			qlock = &p->p_p->ps_lock;
754 		}
755 
756 		rw_enter_write(qlock);
757 		TAILQ_FOREACH_SAFE(entry, queue, tslp_link, tmp) {
758 			if (entry->tslp_ident == ident) {
759 				TAILQ_REMOVE(queue, entry, tslp_link);
760 				entry->tslp_ident = 0;
761 				wakeup_one(entry);
762 				if (++found == n)
763 					break;
764 			}
765 		}
766 		rw_exit_write(qlock);
767 
768 		if (ident == -1)
769 			*retval = 0;
770 		else
771 			*retval = found ? 0 : ESRCH;
772 	}
773 
774 	return (0);
775 }
776 
777 void
778 refcnt_init(struct refcnt *r)
779 {
780 	refcnt_init_trace(r, 0);
781 }
782 
783 void
784 refcnt_init_trace(struct refcnt *r, int idx)
785 {
786 	r->r_traceidx = idx;
787 	atomic_store_int(&r->r_refs, 1);
788 	TRACEINDEX(refcnt, r->r_traceidx, r, 0, +1);
789 }
790 
791 void
792 refcnt_take(struct refcnt *r)
793 {
794 	u_int refs;
795 
796 	refs = atomic_inc_int_nv(&r->r_refs);
797 	KASSERT(refs != 0);
798 	TRACEINDEX(refcnt, r->r_traceidx, r, refs - 1, +1);
799 	(void)refs;
800 }
801 
802 int
803 refcnt_rele(struct refcnt *r)
804 {
805 	u_int refs;
806 
807 	membar_exit_before_atomic();
808 	refs = atomic_dec_int_nv(&r->r_refs);
809 	KASSERT(refs != ~0);
810 	TRACEINDEX(refcnt, r->r_traceidx, r, refs + 1, -1);
811 	if (refs == 0) {
812 		membar_enter_after_atomic();
813 		return (1);
814 	}
815 	return (0);
816 }
817 
818 void
819 refcnt_rele_wake(struct refcnt *r)
820 {
821 	if (refcnt_rele(r))
822 		wakeup_one(r);
823 }
824 
825 void
826 refcnt_finalize(struct refcnt *r, const char *wmesg)
827 {
828 	struct sleep_state sls;
829 	u_int refs;
830 
831 	membar_exit_before_atomic();
832 	refs = atomic_dec_int_nv(&r->r_refs);
833 	KASSERT(refs != ~0);
834 	TRACEINDEX(refcnt, r->r_traceidx, r, refs + 1, -1);
835 	while (refs) {
836 		sleep_setup(&sls, r, PWAIT, wmesg);
837 		refs = atomic_load_int(&r->r_refs);
838 		sleep_finish(&sls, PWAIT, 0, refs);
839 	}
840 	TRACEINDEX(refcnt, r->r_traceidx, r, refs, 0);
841 	/* Order subsequent loads and stores after refs == 0 load. */
842 	membar_sync();
843 }
844 
845 int
846 refcnt_shared(struct refcnt *r)
847 {
848 	u_int refs;
849 
850 	refs = atomic_load_int(&r->r_refs);
851 	TRACEINDEX(refcnt, r->r_traceidx, r, refs, 0);
852 	return (refs > 1);
853 }
854 
855 unsigned int
856 refcnt_read(struct refcnt *r)
857 {
858 	u_int refs;
859 
860 	refs = atomic_load_int(&r->r_refs);
861 	TRACEINDEX(refcnt, r->r_traceidx, r, refs, 0);
862 	return (refs);
863 }
864 
865 void
866 cond_init(struct cond *c)
867 {
868 	atomic_store_int(&c->c_wait, 1);
869 }
870 
871 void
872 cond_signal(struct cond *c)
873 {
874 	atomic_store_int(&c->c_wait, 0);
875 
876 	wakeup_one(c);
877 }
878 
879 void
880 cond_wait(struct cond *c, const char *wmesg)
881 {
882 	struct sleep_state sls;
883 	unsigned int wait;
884 
885 	wait = atomic_load_int(&c->c_wait);
886 	while (wait) {
887 		sleep_setup(&sls, c, PWAIT, wmesg);
888 		wait = atomic_load_int(&c->c_wait);
889 		sleep_finish(&sls, PWAIT, 0, wait);
890 	}
891 }
892