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