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