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