xref: /openbsd-src/sys/kern/kern_synch.c (revision a12463492a3c241ca884dc82eb3a89b0ce7c9ee3)
1 /*	$OpenBSD: kern_synch.c,v 1.212 2024/11/07 13:34:16 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 *, int);
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("sleep: no ident");
343 	if (p->p_stat != SONPROC)
344 		panic("sleep: not SONPROC but %d", p->p_stat);
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)) != 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 	/*
449 	 * Check if thread was woken up because of a unwind or signal
450 	 * but ignore any pending stop condition.
451 	 */
452 	if (catch != 0)
453 		error = sleep_signal_check(p, 1);
454 
455 	/* Signal errors are higher priority than timeouts. */
456 	if (error == 0 && error1 != 0)
457 		error = error1;
458 
459 	return error;
460 }
461 
462 /*
463  * Check and handle signals and suspensions around a sleep cycle.
464  */
465 int
466 sleep_signal_check(struct proc *p, int nostop)
467 {
468 	struct sigctx ctx;
469 	int err, sig;
470 
471 	if ((err = single_thread_check(p, 1)) != 0)
472 		return err;
473 	if ((sig = cursig(p, &ctx, 1)) != 0) {
474 		if (!nostop && ctx.sig_stop) {
475 			p->p_p->ps_xsig = sig;
476 			SCHED_LOCK();
477 			proc_stop(p, 0);
478 			SCHED_UNLOCK();
479 		} else if (ctx.sig_intr)
480 			return EINTR;
481 		else
482 			return ERESTART;
483 	}
484 	return 0;
485 }
486 
487 int
488 wakeup_proc(struct proc *p, int flags)
489 {
490 	int awakened = 0;
491 
492 	SCHED_ASSERT_LOCKED();
493 
494 	if (p->p_wchan != NULL) {
495 		awakened = 1;
496 		if (flags)
497 			atomic_setbits_int(&p->p_flag, flags);
498 #ifdef DIAGNOSTIC
499 		if (p->p_stat != SSLEEP && p->p_stat != SSTOP)
500 			panic("thread %d p_stat is %d", p->p_tid, p->p_stat);
501 #endif
502 		unsleep(p);
503 		if (p->p_stat == SSLEEP)
504 			setrunnable(p);
505 	}
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 
522 	SCHED_LOCK();
523 	wakeup_proc(p, P_TIMEOUT);
524 	SCHED_UNLOCK();
525 }
526 
527 /*
528  * Remove a process from its wait queue
529  */
530 void
531 unsleep(struct proc *p)
532 {
533 	SCHED_ASSERT_LOCKED();
534 
535 	if (p->p_wchan != NULL) {
536 		TAILQ_REMOVE(&slpque[LOOKUP(p->p_wchan)], p, p_runq);
537 		p->p_wchan = NULL;
538 		p->p_wmesg = NULL;
539 		TRACEPOINT(sched, unsleep, p->p_tid + THREAD_PID_OFFSET,
540 		    p->p_p->ps_pid);
541 	}
542 }
543 
544 /*
545  * Make a number of processes sleeping on the specified identifier runnable.
546  */
547 void
548 wakeup_n(const volatile void *ident, int n)
549 {
550 	struct slpque *qp, wakeq;
551 	struct proc *p;
552 	struct proc *pnext;
553 
554 	TAILQ_INIT(&wakeq);
555 
556 	SCHED_LOCK();
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 #ifdef DIAGNOSTIC
561 		if (p->p_stat != SSLEEP && p->p_stat != SSTOP)
562 			panic("thread %d p_stat is %d", p->p_tid, p->p_stat);
563 #endif
564 		KASSERT(p->p_wchan != NULL);
565 		if (p->p_wchan == ident) {
566 			TAILQ_REMOVE(qp, p, p_runq);
567 			p->p_wchan = NULL;
568 			p->p_wmesg = NULL;
569 			TAILQ_INSERT_TAIL(&wakeq, p, p_runq);
570 			--n;
571 		}
572 	}
573 	while ((p = TAILQ_FIRST(&wakeq))) {
574 		TAILQ_REMOVE(&wakeq, p, p_runq);
575 		TRACEPOINT(sched, unsleep, p->p_tid + THREAD_PID_OFFSET,
576 		    p->p_p->ps_pid);
577 		if (p->p_stat == SSLEEP)
578 			setrunnable(p);
579 	}
580 	SCHED_UNLOCK();
581 }
582 
583 /*
584  * Make all processes sleeping on the specified identifier runnable.
585  */
586 void
587 wakeup(const volatile void *chan)
588 {
589 	wakeup_n(chan, -1);
590 }
591 
592 int
593 sys_sched_yield(struct proc *p, void *v, register_t *retval)
594 {
595 	struct proc *q;
596 	uint8_t newprio;
597 
598 	/*
599 	 * If one of the threads of a multi-threaded process called
600 	 * sched_yield(2), drop its priority to ensure its siblings
601 	 * can make some progress.
602 	 */
603 	mtx_enter(&p->p_p->ps_mtx);
604 	newprio = p->p_usrpri;
605 	TAILQ_FOREACH(q, &p->p_p->ps_threads, p_thr_link)
606 		newprio = max(newprio, q->p_runpri);
607 	mtx_leave(&p->p_p->ps_mtx);
608 
609 	SCHED_LOCK();
610 	setrunqueue(p->p_cpu, p, newprio);
611 	p->p_ru.ru_nvcsw++;
612 	mi_switch();
613 	SCHED_UNLOCK();
614 
615 	return (0);
616 }
617 
618 int
619 thrsleep_unlock(void *lock)
620 {
621 	static _atomic_lock_t unlocked = _ATOMIC_LOCK_UNLOCKED;
622 	_atomic_lock_t *atomiclock = lock;
623 
624 	if (!lock)
625 		return 0;
626 
627 	return copyout(&unlocked, atomiclock, sizeof(unlocked));
628 }
629 
630 struct tslpentry {
631 	TAILQ_ENTRY(tslpentry)	tslp_link;
632 	long			tslp_ident;
633 };
634 
635 /* thrsleep queue shared between processes */
636 static struct tslpqueue thrsleep_queue = TAILQ_HEAD_INITIALIZER(thrsleep_queue);
637 static struct rwlock thrsleep_lock = RWLOCK_INITIALIZER("thrsleeplk");
638 
639 int
640 thrsleep(struct proc *p, struct sys___thrsleep_args *v)
641 {
642 	struct sys___thrsleep_args /* {
643 		syscallarg(const volatile void *) ident;
644 		syscallarg(clockid_t) clock_id;
645 		syscallarg(const struct timespec *) tp;
646 		syscallarg(void *) lock;
647 		syscallarg(const int *) abort;
648 	} */ *uap = v;
649 	long ident = (long)SCARG(uap, ident);
650 	struct tslpentry entry;
651 	struct tslpqueue *queue;
652 	struct rwlock *qlock;
653 	struct timespec *tsp = (struct timespec *)SCARG(uap, tp);
654 	void *lock = SCARG(uap, lock);
655 	uint64_t nsecs = INFSLP;
656 	int abort = 0, error;
657 	clockid_t clock_id = SCARG(uap, clock_id);
658 
659 	if (ident == 0)
660 		return (EINVAL);
661 	if (tsp != NULL) {
662 		struct timespec now;
663 
664 		if ((error = clock_gettime(p, clock_id, &now)))
665 			return (error);
666 #ifdef KTRACE
667 		if (KTRPOINT(p, KTR_STRUCT))
668 			ktrabstimespec(p, tsp);
669 #endif
670 
671 		if (timespeccmp(tsp, &now, <=)) {
672 			/* already passed: still do the unlock */
673 			if ((error = thrsleep_unlock(lock)))
674 				return (error);
675 			return (EWOULDBLOCK);
676 		}
677 
678 		timespecsub(tsp, &now, tsp);
679 		nsecs = MIN(TIMESPEC_TO_NSEC(tsp), MAXTSLP);
680 	}
681 
682 	if (ident == -1) {
683 		queue = &thrsleep_queue;
684 		qlock = &thrsleep_lock;
685 	} else {
686 		queue = &p->p_p->ps_tslpqueue;
687 		qlock = &p->p_p->ps_lock;
688 	}
689 
690 	/* Interlock with wakeup. */
691 	entry.tslp_ident = ident;
692 	rw_enter_write(qlock);
693 	TAILQ_INSERT_TAIL(queue, &entry, tslp_link);
694 	rw_exit_write(qlock);
695 
696 	error = thrsleep_unlock(lock);
697 
698 	if (error == 0 && SCARG(uap, abort) != NULL)
699 		error = copyin(SCARG(uap, abort), &abort, sizeof(abort));
700 
701 	rw_enter_write(qlock);
702 	if (error != 0)
703 		goto out;
704 	if (abort != 0) {
705 		error = EINTR;
706 		goto out;
707 	}
708 	if (entry.tslp_ident != 0) {
709 		error = rwsleep_nsec(&entry, qlock, PWAIT|PCATCH, "thrsleep",
710 		    nsecs);
711 	}
712 
713 out:
714 	if (entry.tslp_ident != 0)
715 		TAILQ_REMOVE(queue, &entry, tslp_link);
716 	rw_exit_write(qlock);
717 
718 	if (error == ERESTART)
719 		error = ECANCELED;
720 
721 	return (error);
722 
723 }
724 
725 int
726 sys___thrsleep(struct proc *p, void *v, register_t *retval)
727 {
728 	struct sys___thrsleep_args /* {
729 		syscallarg(const volatile void *) ident;
730 		syscallarg(clockid_t) clock_id;
731 		syscallarg(struct timespec *) tp;
732 		syscallarg(void *) lock;
733 		syscallarg(const int *) abort;
734 	} */ *uap = v;
735 	struct timespec ts;
736 	int error;
737 
738 	if (SCARG(uap, tp) != NULL) {
739 		if ((error = copyin(SCARG(uap, tp), &ts, sizeof(ts)))) {
740 			*retval = error;
741 			return 0;
742 		}
743 		if (!timespecisvalid(&ts)) {
744 			*retval = EINVAL;
745 			return 0;
746 		}
747 		SCARG(uap, tp) = &ts;
748 	}
749 
750 	*retval = thrsleep(p, uap);
751 	return 0;
752 }
753 
754 int
755 sys___thrwakeup(struct proc *p, void *v, register_t *retval)
756 {
757 	struct sys___thrwakeup_args /* {
758 		syscallarg(const volatile void *) ident;
759 		syscallarg(int) n;
760 	} */ *uap = v;
761 	struct tslpentry *entry, *tmp;
762 	struct tslpqueue *queue;
763 	struct rwlock *qlock;
764 	long ident = (long)SCARG(uap, ident);
765 	int n = SCARG(uap, n);
766 	int found = 0;
767 
768 	if (ident == 0)
769 		*retval = EINVAL;
770 	else {
771 		if (ident == -1) {
772 			queue = &thrsleep_queue;
773 			qlock = &thrsleep_lock;
774 			/*
775 			 * Wake up all waiters with ident -1. This is needed
776 			 * because ident -1 can be shared by multiple userspace
777 			 * lock state machines concurrently. The implementation
778 			 * has no way to direct the wakeup to a particular
779 			 * state machine.
780 			 */
781 			n = 0;
782 		} else {
783 			queue = &p->p_p->ps_tslpqueue;
784 			qlock = &p->p_p->ps_lock;
785 		}
786 
787 		rw_enter_write(qlock);
788 		TAILQ_FOREACH_SAFE(entry, queue, tslp_link, tmp) {
789 			if (entry->tslp_ident == ident) {
790 				TAILQ_REMOVE(queue, entry, tslp_link);
791 				entry->tslp_ident = 0;
792 				wakeup_one(entry);
793 				if (++found == n)
794 					break;
795 			}
796 		}
797 		rw_exit_write(qlock);
798 
799 		if (ident == -1)
800 			*retval = 0;
801 		else
802 			*retval = found ? 0 : ESRCH;
803 	}
804 
805 	return (0);
806 }
807 
808 void
809 refcnt_init(struct refcnt *r)
810 {
811 	refcnt_init_trace(r, 0);
812 }
813 
814 void
815 refcnt_init_trace(struct refcnt *r, int idx)
816 {
817 	r->r_traceidx = idx;
818 	atomic_store_int(&r->r_refs, 1);
819 	TRACEINDEX(refcnt, r->r_traceidx, r, 0, +1);
820 }
821 
822 void
823 refcnt_take(struct refcnt *r)
824 {
825 	u_int refs;
826 
827 	refs = atomic_inc_int_nv(&r->r_refs);
828 	KASSERT(refs != 0);
829 	TRACEINDEX(refcnt, r->r_traceidx, r, refs - 1, +1);
830 	(void)refs;
831 }
832 
833 int
834 refcnt_rele(struct refcnt *r)
835 {
836 	u_int refs;
837 
838 	membar_exit_before_atomic();
839 	refs = atomic_dec_int_nv(&r->r_refs);
840 	KASSERT(refs != ~0);
841 	TRACEINDEX(refcnt, r->r_traceidx, r, refs + 1, -1);
842 	if (refs == 0) {
843 		membar_enter_after_atomic();
844 		return (1);
845 	}
846 	return (0);
847 }
848 
849 void
850 refcnt_rele_wake(struct refcnt *r)
851 {
852 	if (refcnt_rele(r))
853 		wakeup_one(r);
854 }
855 
856 void
857 refcnt_finalize(struct refcnt *r, const char *wmesg)
858 {
859 	u_int refs;
860 
861 	membar_exit_before_atomic();
862 	refs = atomic_dec_int_nv(&r->r_refs);
863 	KASSERT(refs != ~0);
864 	TRACEINDEX(refcnt, r->r_traceidx, r, refs + 1, -1);
865 	while (refs) {
866 		sleep_setup(r, PWAIT, wmesg);
867 		refs = atomic_load_int(&r->r_refs);
868 		sleep_finish(0, refs);
869 	}
870 	TRACEINDEX(refcnt, r->r_traceidx, r, refs, 0);
871 	/* Order subsequent loads and stores after refs == 0 load. */
872 	membar_sync();
873 }
874 
875 int
876 refcnt_shared(struct refcnt *r)
877 {
878 	u_int refs;
879 
880 	refs = atomic_load_int(&r->r_refs);
881 	TRACEINDEX(refcnt, r->r_traceidx, r, refs, 0);
882 	return (refs > 1);
883 }
884 
885 unsigned int
886 refcnt_read(struct refcnt *r)
887 {
888 	u_int refs;
889 
890 	refs = atomic_load_int(&r->r_refs);
891 	TRACEINDEX(refcnt, r->r_traceidx, r, refs, 0);
892 	return (refs);
893 }
894 
895 void
896 cond_init(struct cond *c)
897 {
898 	atomic_store_int(&c->c_wait, 1);
899 }
900 
901 void
902 cond_signal(struct cond *c)
903 {
904 	atomic_store_int(&c->c_wait, 0);
905 
906 	wakeup_one(c);
907 }
908 
909 void
910 cond_wait(struct cond *c, const char *wmesg)
911 {
912 	unsigned int wait;
913 
914 	wait = atomic_load_int(&c->c_wait);
915 	while (wait) {
916 		sleep_setup(c, PWAIT, wmesg);
917 		wait = atomic_load_int(&c->c_wait);
918 		sleep_finish(0, wait);
919 	}
920 }
921