1 /* $OpenBSD: kern_synch.c,v 1.217 2025/01/22 13:30:41 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 67 extern void proc_stop(struct proc *p, int); 68 69 /* 70 * We're only looking at 7 bits of the address; everything is 71 * aligned to 4, lots of things are aligned to greater powers 72 * of 2. Shift right by 8, i.e. drop the bottom 256 worth. 73 */ 74 #define TABLESIZE 128 75 #define LOOKUP(x) (((long)(x) >> 8) & (TABLESIZE - 1)) 76 TAILQ_HEAD(slpque,proc) slpque[TABLESIZE]; 77 78 void 79 sleep_queue_init(void) 80 { 81 int i; 82 83 for (i = 0; i < TABLESIZE; i++) 84 TAILQ_INIT(&slpque[i]); 85 } 86 87 /* 88 * Global sleep channel for threads that do not want to 89 * receive wakeup(9) broadcasts. 90 */ 91 int nowake; 92 93 /* 94 * During autoconfiguration or after a panic, a sleep will simply 95 * lower the priority briefly to allow interrupts, then return. 96 * The priority to be used (safepri) is machine-dependent, thus this 97 * value is initialized and maintained in the machine-dependent layers. 98 * This priority will typically be 0, or the lowest priority 99 * that is safe for use on the interrupt stack; it can be made 100 * higher to block network software interrupts after panics. 101 */ 102 extern int safepri; 103 104 /* 105 * General sleep call. Suspends the current process until a wakeup is 106 * performed on the specified identifier. The process will then be made 107 * runnable with the specified priority. Sleeps at most timo/hz seconds 108 * (0 means no timeout). If pri includes PCATCH flag, signals are checked 109 * before and after sleeping, else signals are not checked. Returns 0 if 110 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a 111 * signal needs to be delivered, ERESTART is returned if the current system 112 * call should be restarted if possible, and EINTR is returned if the system 113 * call should be interrupted by the signal (return EINTR). 114 */ 115 int 116 tsleep(const volatile void *ident, int priority, const char *wmesg, int timo) 117 { 118 #ifdef MULTIPROCESSOR 119 int hold_count; 120 #endif 121 122 KASSERT((priority & ~(PRIMASK | PCATCH)) == 0); 123 KASSERT(ident != &nowake || ISSET(priority, PCATCH) || timo != 0); 124 125 #ifdef MULTIPROCESSOR 126 KASSERT(ident == &nowake || timo || _kernel_lock_held()); 127 #endif 128 129 #ifdef DDB 130 if (cold == 2) 131 db_stack_dump(); 132 #endif 133 if (cold || panicstr) { 134 int s; 135 /* 136 * After a panic, or during autoconfiguration, 137 * just give interrupts a chance, then just return; 138 * don't run any other procs or panic below, 139 * in case this is the idle process and already asleep. 140 */ 141 s = splhigh(); 142 splx(safepri); 143 #ifdef MULTIPROCESSOR 144 if (_kernel_lock_held()) { 145 hold_count = __mp_release_all(&kernel_lock); 146 __mp_acquire_count(&kernel_lock, hold_count); 147 } 148 #endif 149 splx(s); 150 return (0); 151 } 152 153 sleep_setup(ident, priority, wmesg); 154 return sleep_finish(timo, 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 int error, spl; 209 #ifdef MULTIPROCESSOR 210 int hold_count; 211 #endif 212 213 KASSERT((priority & ~(PRIMASK | PCATCH | PNORELOCK)) == 0); 214 KASSERT(ident != &nowake || ISSET(priority, PCATCH) || timo != 0); 215 KASSERT(mtx != NULL); 216 217 #ifdef DDB 218 if (cold == 2) 219 db_stack_dump(); 220 #endif 221 if (cold || panicstr) { 222 /* 223 * After a panic, or during autoconfiguration, 224 * just give interrupts a chance, then just return; 225 * don't run any other procs or panic below, 226 * in case this is the idle process and already asleep. 227 */ 228 spl = MUTEX_OLDIPL(mtx); 229 MUTEX_OLDIPL(mtx) = safepri; 230 mtx_leave(mtx); 231 #ifdef MULTIPROCESSOR 232 if (_kernel_lock_held()) { 233 hold_count = __mp_release_all(&kernel_lock); 234 __mp_acquire_count(&kernel_lock, hold_count); 235 } 236 #endif 237 if ((priority & PNORELOCK) == 0) { 238 mtx_enter(mtx); 239 MUTEX_OLDIPL(mtx) = spl; 240 } else 241 splx(spl); 242 return (0); 243 } 244 245 sleep_setup(ident, priority, wmesg); 246 247 mtx_leave(mtx); 248 /* signal may stop the process, release mutex before that */ 249 error = sleep_finish(timo, 1); 250 251 if ((priority & PNORELOCK) == 0) 252 mtx_enter(mtx); 253 254 return error; 255 } 256 257 int 258 msleep_nsec(const volatile void *ident, struct mutex *mtx, int priority, 259 const char *wmesg, uint64_t nsecs) 260 { 261 uint64_t to_ticks; 262 263 if (nsecs == INFSLP) 264 return msleep(ident, mtx, priority, wmesg, 0); 265 #ifdef DIAGNOSTIC 266 if (nsecs == 0) { 267 log(LOG_WARNING, 268 "%s: %s[%d]: %s: trying to sleep zero nanoseconds\n", 269 __func__, curproc->p_p->ps_comm, curproc->p_p->ps_pid, 270 wmesg); 271 } 272 #endif 273 nsecs = MIN(nsecs, UINT64_MAX - tick_nsec); 274 to_ticks = (nsecs + tick_nsec - 1) / (tick_nsec + 1) + 1; 275 if (to_ticks > INT_MAX) 276 to_ticks = INT_MAX; 277 return msleep(ident, mtx, priority, wmesg, (int)to_ticks); 278 } 279 280 /* 281 * Same as tsleep, but if we have a rwlock provided, then once we've 282 * entered the sleep queue we drop the it. After sleeping we re-lock. 283 */ 284 int 285 rwsleep(const volatile void *ident, struct rwlock *rwl, int priority, 286 const char *wmesg, int timo) 287 { 288 int error, status; 289 290 KASSERT((priority & ~(PRIMASK | PCATCH | PNORELOCK)) == 0); 291 KASSERT(ident != &nowake || ISSET(priority, PCATCH) || timo != 0); 292 KASSERT(ident != rwl); 293 rw_assert_anylock(rwl); 294 status = rw_status(rwl); 295 296 sleep_setup(ident, priority, wmesg); 297 298 rw_exit(rwl); 299 /* signal may stop the process, release rwlock before that */ 300 error = sleep_finish(timo, 1); 301 302 if ((priority & PNORELOCK) == 0) 303 rw_enter(rwl, status); 304 305 return error; 306 } 307 308 int 309 rwsleep_nsec(const volatile void *ident, struct rwlock *rwl, int priority, 310 const char *wmesg, uint64_t nsecs) 311 { 312 uint64_t to_ticks; 313 314 if (nsecs == INFSLP) 315 return rwsleep(ident, rwl, priority, wmesg, 0); 316 #ifdef DIAGNOSTIC 317 if (nsecs == 0) { 318 log(LOG_WARNING, 319 "%s: %s[%d]: %s: trying to sleep zero nanoseconds\n", 320 __func__, curproc->p_p->ps_comm, curproc->p_p->ps_pid, 321 wmesg); 322 } 323 #endif 324 nsecs = MIN(nsecs, UINT64_MAX - tick_nsec); 325 to_ticks = (nsecs + tick_nsec - 1) / (tick_nsec + 1) + 1; 326 if (to_ticks > INT_MAX) 327 to_ticks = INT_MAX; 328 return rwsleep(ident, rwl, priority, wmesg, (int)to_ticks); 329 } 330 331 void 332 sleep_setup(const volatile void *ident, int prio, const char *wmesg) 333 { 334 struct proc *p = curproc; 335 336 #ifdef DIAGNOSTIC 337 if (p->p_flag & P_CANTSLEEP) 338 panic("sleep: %s failed insomnia", p->p_p->ps_comm); 339 if (ident == NULL) 340 panic("sleep: no ident"); 341 if (p->p_stat != SONPROC) 342 panic("sleep: not SONPROC but %d", p->p_stat); 343 #endif 344 /* exiting processes are not allowed to catch signals */ 345 if (p->p_flag & P_WEXIT) 346 CLR(prio, PCATCH); 347 348 SCHED_LOCK(); 349 350 TRACEPOINT(sched, sleep, NULL); 351 352 p->p_wchan = ident; 353 p->p_wmesg = wmesg; 354 p->p_slptime = 0; 355 p->p_slppri = prio & PRIMASK; 356 atomic_setbits_int(&p->p_flag, P_WSLEEP); 357 TAILQ_INSERT_TAIL(&slpque[LOOKUP(ident)], p, p_runq); 358 if (prio & PCATCH) 359 atomic_setbits_int(&p->p_flag, P_SINTR); 360 p->p_stat = SSLEEP; 361 362 SCHED_UNLOCK(); 363 } 364 365 int 366 sleep_finish(int timo, int do_sleep) 367 { 368 struct proc *p = curproc; 369 int catch, error = 0, error1 = 0; 370 371 catch = p->p_flag & P_SINTR; 372 373 if (timo != 0) { 374 KASSERT((p->p_flag & P_TIMEOUT) == 0); 375 timeout_add(&p->p_sleep_to, timo); 376 } 377 378 if (catch != 0) { 379 /* 380 * We put ourselves on the sleep queue and start our 381 * timeout before calling sleep_signal_check(), as we could 382 * stop there, and a wakeup or a SIGCONT (or both) could 383 * occur while we were stopped. A SIGCONT would cause 384 * us to be marked as SSLEEP without resuming us, thus 385 * we must be ready for sleep when sleep_signal_check() is 386 * called. 387 */ 388 if ((error = sleep_signal_check(p, 0)) != 0) { 389 catch = 0; 390 do_sleep = 0; 391 } 392 } 393 394 SCHED_LOCK(); 395 /* 396 * A few checks need to happen before going to sleep: 397 * - If the wakeup happens while going to sleep, p->p_wchan 398 * will be NULL. In that case unwind immediately but still 399 * check for possible signals and timeouts. 400 * - If the sleep is aborted call unsleep and take us of the 401 * sleep queue. 402 * - If requested to stop force a switch even if the sleep 403 * condition got cleared. 404 */ 405 if (p->p_wchan == NULL) 406 do_sleep = 0; 407 if (do_sleep == 0) 408 unsleep(p); 409 if (p->p_stat == SSTOP) 410 do_sleep = 1; 411 atomic_clearbits_int(&p->p_flag, P_WSLEEP); 412 413 if (do_sleep) { 414 KASSERT(p->p_stat == SSLEEP || p->p_stat == SSTOP); 415 p->p_ru.ru_nvcsw++; 416 mi_switch(); 417 } else { 418 KASSERT(p->p_stat == SONPROC || p->p_stat == SSLEEP); 419 p->p_stat = SONPROC; 420 } 421 422 #ifdef DIAGNOSTIC 423 if (p->p_stat != SONPROC) 424 panic("sleep_finish !SONPROC"); 425 #endif 426 427 p->p_cpu->ci_schedstate.spc_curpriority = p->p_usrpri; 428 SCHED_UNLOCK(); 429 430 /* 431 * Even though this belongs to the signal handling part of sleep, 432 * we need to clear it before the ktrace. 433 */ 434 atomic_clearbits_int(&p->p_flag, P_SINTR); 435 436 if (timo != 0) { 437 if (p->p_flag & P_TIMEOUT) { 438 error1 = EWOULDBLOCK; 439 } else { 440 /* This can sleep. It must not use timeouts. */ 441 timeout_del_barrier(&p->p_sleep_to); 442 } 443 atomic_clearbits_int(&p->p_flag, P_TIMEOUT); 444 } 445 446 /* 447 * Check if thread was woken up because of a unwind or signal 448 * but ignore any pending stop condition. 449 */ 450 if (catch != 0) 451 error = sleep_signal_check(p, 1); 452 453 /* Signal errors are higher priority than timeouts. */ 454 if (error == 0 && error1 != 0) 455 error = error1; 456 457 return error; 458 } 459 460 /* 461 * Check and handle signals and suspensions around a sleep cycle. 462 * The 2nd call in sleep_finish() sets nostop = 1 and then stop 463 * signals can be ignored since the sleep is over and the process 464 * will stop in userret. 465 */ 466 int 467 sleep_signal_check(struct proc *p, int nostop) 468 { 469 struct sigctx ctx; 470 int err, sig; 471 472 if ((err = single_thread_check(p, 1)) != 0) { 473 if (err != EWOULDBLOCK) 474 return err; 475 476 /* requested to stop */ 477 if (!nostop) { 478 mtx_enter(&p->p_p->ps_mtx); 479 if (--p->p_p->ps_singlecnt == 0) 480 wakeup(&p->p_p->ps_singlecnt); 481 mtx_leave(&p->p_p->ps_mtx); 482 483 SCHED_LOCK(); 484 p->p_stat = SSTOP; 485 SCHED_UNLOCK(); 486 } 487 } 488 489 if ((sig = cursig(p, &ctx, 1)) != 0) { 490 if (ctx.sig_stop) { 491 if (!nostop) { 492 p->p_p->ps_xsig = sig; 493 SCHED_LOCK(); 494 proc_stop(p, 0); 495 SCHED_UNLOCK(); 496 } 497 } else if (ctx.sig_intr && !ctx.sig_ignore) 498 return EINTR; 499 else 500 return ERESTART; 501 } 502 503 return 0; 504 } 505 506 int 507 wakeup_proc(struct proc *p, int flags) 508 { 509 int awakened = 0; 510 511 SCHED_ASSERT_LOCKED(); 512 513 if (p->p_wchan != NULL) { 514 awakened = 1; 515 if (flags) 516 atomic_setbits_int(&p->p_flag, flags); 517 #ifdef DIAGNOSTIC 518 if (p->p_stat != SSLEEP && p->p_stat != SSTOP) 519 panic("thread %d p_stat is %d", p->p_tid, p->p_stat); 520 #endif 521 unsleep(p); 522 if (p->p_stat == SSLEEP) 523 setrunnable(p); 524 } 525 526 return awakened; 527 } 528 529 530 /* 531 * Implement timeout for tsleep. 532 * If process hasn't been awakened (wchan non-zero), 533 * set timeout flag and undo the sleep. If proc 534 * is stopped, just unsleep so it will remain stopped. 535 */ 536 void 537 endtsleep(void *arg) 538 { 539 struct proc *p = arg; 540 541 SCHED_LOCK(); 542 wakeup_proc(p, P_TIMEOUT); 543 SCHED_UNLOCK(); 544 } 545 546 /* 547 * Remove a process from its wait queue 548 */ 549 void 550 unsleep(struct proc *p) 551 { 552 SCHED_ASSERT_LOCKED(); 553 554 if (p->p_wchan != NULL) { 555 TAILQ_REMOVE(&slpque[LOOKUP(p->p_wchan)], p, p_runq); 556 p->p_wchan = NULL; 557 p->p_wmesg = NULL; 558 TRACEPOINT(sched, unsleep, p->p_tid + THREAD_PID_OFFSET, 559 p->p_p->ps_pid); 560 } 561 } 562 563 /* 564 * Make a number of processes sleeping on the specified identifier runnable. 565 */ 566 void 567 wakeup_n(const volatile void *ident, int n) 568 { 569 struct slpque *qp, wakeq; 570 struct proc *p; 571 struct proc *pnext; 572 573 TAILQ_INIT(&wakeq); 574 575 SCHED_LOCK(); 576 qp = &slpque[LOOKUP(ident)]; 577 for (p = TAILQ_FIRST(qp); p != NULL && n != 0; p = pnext) { 578 pnext = TAILQ_NEXT(p, p_runq); 579 #ifdef DIAGNOSTIC 580 if (p->p_stat != SSLEEP && p->p_stat != SSTOP) 581 panic("thread %d p_stat is %d", p->p_tid, p->p_stat); 582 #endif 583 KASSERT(p->p_wchan != NULL); 584 if (p->p_wchan == ident) { 585 TAILQ_REMOVE(qp, p, p_runq); 586 p->p_wchan = NULL; 587 p->p_wmesg = NULL; 588 TAILQ_INSERT_TAIL(&wakeq, p, p_runq); 589 --n; 590 } 591 } 592 while ((p = TAILQ_FIRST(&wakeq))) { 593 TAILQ_REMOVE(&wakeq, p, p_runq); 594 TRACEPOINT(sched, unsleep, p->p_tid + THREAD_PID_OFFSET, 595 p->p_p->ps_pid); 596 if (p->p_stat == SSLEEP) 597 setrunnable(p); 598 } 599 SCHED_UNLOCK(); 600 } 601 602 /* 603 * Make all processes sleeping on the specified identifier runnable. 604 */ 605 void 606 wakeup(const volatile void *chan) 607 { 608 wakeup_n(chan, -1); 609 } 610 611 int 612 sys_sched_yield(struct proc *p, void *v, register_t *retval) 613 { 614 struct proc *q; 615 uint8_t newprio; 616 617 /* 618 * If one of the threads of a multi-threaded process called 619 * sched_yield(2), drop its priority to ensure its siblings 620 * can make some progress. 621 */ 622 mtx_enter(&p->p_p->ps_mtx); 623 newprio = p->p_usrpri; 624 TAILQ_FOREACH(q, &p->p_p->ps_threads, p_thr_link) 625 newprio = max(newprio, q->p_runpri); 626 mtx_leave(&p->p_p->ps_mtx); 627 628 SCHED_LOCK(); 629 setrunqueue(p->p_cpu, p, newprio); 630 p->p_ru.ru_nvcsw++; 631 mi_switch(); 632 SCHED_UNLOCK(); 633 634 return (0); 635 } 636 637 static inline int 638 thrsleep_unlock(_atomic_lock_t *atomiclock) 639 { 640 static _atomic_lock_t unlocked = _ATOMIC_LOCK_UNLOCKED; 641 642 if (atomiclock == NULL) 643 return 0; 644 645 return copyout(&unlocked, atomiclock, sizeof(unlocked)); 646 } 647 648 struct tslpentry { 649 TAILQ_ENTRY(tslpentry) tslp_link; 650 struct process *tslp_ps; 651 long tslp_ident; 652 struct proc *volatile tslp_p; 653 }; 654 655 struct tslp_bucket { 656 struct tslpqueue tsb_list; 657 struct mutex tsb_lock; 658 } __aligned(64); 659 660 /* thrsleep queue shared between processes */ 661 static struct tslp_bucket tsb_shared; 662 663 #define TSLP_BUCKET_BITS 6 664 #define TSLP_BUCKET_SIZE (1UL << TSLP_BUCKET_BITS) 665 #define TSLP_BUCKET_MASK (TSLP_BUCKET_SIZE - 1) 666 667 static struct tslp_bucket tsb_buckets[TSLP_BUCKET_SIZE]; 668 669 void 670 tslp_init(void) 671 { 672 struct tslp_bucket *tsb; 673 size_t i; 674 675 TAILQ_INIT(&tsb_shared.tsb_list); 676 mtx_init(&tsb_shared.tsb_lock, IPL_MPFLOOR); 677 678 for (i = 0; i < nitems(tsb_buckets); i++) { 679 tsb = &tsb_buckets[i]; 680 681 TAILQ_INIT(&tsb->tsb_list); 682 mtx_init(&tsb->tsb_lock, IPL_MPFLOOR); 683 } 684 } 685 686 static struct tslp_bucket * 687 thrsleep_bucket(long ident) 688 { 689 ident >>= 3; 690 ident ^= ident >> TSLP_BUCKET_BITS; 691 ident &= TSLP_BUCKET_MASK; 692 693 return &tsb_buckets[ident]; 694 } 695 696 static int 697 thrsleep(struct proc *p, struct sys___thrsleep_args *v) 698 { 699 struct sys___thrsleep_args /* { 700 syscallarg(const volatile void *) ident; 701 syscallarg(clockid_t) clock_id; 702 syscallarg(const struct timespec *) tp; 703 syscallarg(void *) lock; 704 syscallarg(const int *) abort; 705 } */ *uap = v; 706 long ident = (long)SCARG(uap, ident); 707 struct tslpentry entry; 708 struct tslp_bucket *tsb; 709 struct timespec *tsp = (struct timespec *)SCARG(uap, tp); 710 void *lock = SCARG(uap, lock); 711 const uint32_t *abortp = SCARG(uap, abort); 712 clockid_t clock_id = SCARG(uap, clock_id); 713 uint64_t to_ticks = 0; 714 int error = 0; 715 716 if (ident == 0) 717 return (EINVAL); 718 if (tsp != NULL) { 719 struct timespec now; 720 uint64_t nsecs; 721 722 if ((error = clock_gettime(p, clock_id, &now))) 723 return (error); 724 #ifdef KTRACE 725 if (KTRPOINT(p, KTR_STRUCT)) 726 ktrabstimespec(p, tsp); 727 #endif 728 729 if (timespeccmp(tsp, &now, <=)) { 730 /* already passed: still do the unlock */ 731 if ((error = thrsleep_unlock(lock))) 732 return (error); 733 return (EWOULDBLOCK); 734 } 735 736 timespecsub(tsp, &now, tsp); 737 nsecs = MIN(TIMESPEC_TO_NSEC(tsp), MAXTSLP); 738 to_ticks = (nsecs + tick_nsec - 1) / (tick_nsec + 1) + 1; 739 if (to_ticks > INT_MAX) 740 to_ticks = INT_MAX; 741 } 742 743 tsb = (ident == -1) ? &tsb_shared : thrsleep_bucket(ident); 744 745 /* Interlock with wakeup. */ 746 entry.tslp_ps = p->p_p; 747 entry.tslp_ident = ident; 748 entry.tslp_p = p; 749 750 mtx_enter(&tsb->tsb_lock); 751 TAILQ_INSERT_TAIL(&tsb->tsb_list, &entry, tslp_link); 752 mtx_leave(&tsb->tsb_lock); 753 754 error = thrsleep_unlock(lock); 755 if (error != 0) 756 goto leave; 757 758 if (abortp != NULL) { 759 uint32_t abort; 760 error = copyin32(abortp, &abort); 761 if (error != 0) 762 goto leave; 763 if (abort) { 764 error = EINTR; 765 goto leave; 766 } 767 } 768 769 sleep_setup(&entry, PWAIT|PCATCH, "thrsleep"); 770 error = sleep_finish(to_ticks, entry.tslp_p != NULL); 771 if (error != 0 || entry.tslp_p != NULL) { 772 mtx_enter(&tsb->tsb_lock); 773 if (entry.tslp_p != NULL) 774 TAILQ_REMOVE(&tsb->tsb_list, &entry, tslp_link); 775 else 776 error = 0; 777 mtx_leave(&tsb->tsb_lock); 778 779 if (error == ERESTART) 780 error = ECANCELED; 781 } 782 783 return (error); 784 785 leave: 786 if (entry.tslp_p != NULL) { 787 mtx_enter(&tsb->tsb_lock); 788 if (entry.tslp_p != NULL) 789 TAILQ_REMOVE(&tsb->tsb_list, &entry, tslp_link); 790 mtx_leave(&tsb->tsb_lock); 791 } 792 793 return (error); 794 } 795 796 int 797 sys___thrsleep(struct proc *p, void *v, register_t *retval) 798 { 799 struct sys___thrsleep_args /* { 800 syscallarg(const volatile void *) ident; 801 syscallarg(clockid_t) clock_id; 802 syscallarg(struct timespec *) tp; 803 syscallarg(void *) lock; 804 syscallarg(const int *) abort; 805 } */ *uap = v; 806 struct timespec ts; 807 int error; 808 809 if (SCARG(uap, tp) != NULL) { 810 if ((error = copyin(SCARG(uap, tp), &ts, sizeof(ts)))) { 811 *retval = error; 812 return 0; 813 } 814 if (!timespecisvalid(&ts)) { 815 *retval = EINVAL; 816 return 0; 817 } 818 SCARG(uap, tp) = &ts; 819 } 820 821 *retval = thrsleep(p, uap); 822 return 0; 823 } 824 825 static void 826 tslp_wakeups(struct tslpqueue *tslpq) 827 { 828 struct tslpentry *entry, *nentry; 829 struct proc *p; 830 831 SCHED_LOCK(); 832 TAILQ_FOREACH_SAFE(entry, tslpq, tslp_link, nentry) { 833 p = entry->tslp_p; 834 entry->tslp_p = NULL; 835 wakeup_proc(p, 0); 836 } 837 SCHED_UNLOCK(); 838 } 839 840 int 841 sys___thrwakeup(struct proc *p, void *v, register_t *retval) 842 { 843 struct sys___thrwakeup_args /* { 844 syscallarg(const volatile void *) ident; 845 syscallarg(int) n; 846 } */ *uap = v; 847 struct tslpentry *entry, *nentry; 848 struct tslp_bucket *tsb; 849 long ident = (long)SCARG(uap, ident); 850 int n = SCARG(uap, n); 851 int found = 0; 852 struct tslpqueue wq = TAILQ_HEAD_INITIALIZER(wq); 853 854 if (ident == 0) { 855 *retval = EINVAL; 856 return (0); 857 } 858 859 if (ident == -1) { 860 /* 861 * Wake up all waiters with ident -1. This is needed 862 * because ident -1 can be shared by multiple userspace 863 * lock state machines concurrently. The implementation 864 * has no way to direct the wakeup to a particular 865 * state machine. 866 */ 867 mtx_enter(&tsb_shared.tsb_lock); 868 tslp_wakeups(&tsb_shared.tsb_list); 869 TAILQ_INIT(&tsb_shared.tsb_list); 870 mtx_leave(&tsb_shared.tsb_lock); 871 872 *retval = 0; 873 return (0); 874 } 875 876 tsb = thrsleep_bucket(ident); 877 878 mtx_enter(&tsb->tsb_lock); 879 TAILQ_FOREACH_SAFE(entry, &tsb->tsb_list, tslp_link, nentry) { 880 if (entry->tslp_ident == ident && entry->tslp_ps == p->p_p) { 881 TAILQ_REMOVE(&tsb->tsb_list, entry, tslp_link); 882 TAILQ_INSERT_TAIL(&wq, entry, tslp_link); 883 884 if (++found == n) 885 break; 886 } 887 } 888 889 if (found) 890 tslp_wakeups(&wq); 891 mtx_leave(&tsb->tsb_lock); 892 893 *retval = found ? 0 : ESRCH; 894 return (0); 895 } 896 897 void 898 refcnt_init(struct refcnt *r) 899 { 900 refcnt_init_trace(r, 0); 901 } 902 903 void 904 refcnt_init_trace(struct refcnt *r, int idx) 905 { 906 r->r_traceidx = idx; 907 atomic_store_int(&r->r_refs, 1); 908 TRACEINDEX(refcnt, r->r_traceidx, r, 0, +1); 909 } 910 911 void 912 refcnt_take(struct refcnt *r) 913 { 914 u_int refs; 915 916 refs = atomic_inc_int_nv(&r->r_refs); 917 KASSERT(refs != 0); 918 TRACEINDEX(refcnt, r->r_traceidx, r, refs - 1, +1); 919 (void)refs; 920 } 921 922 int 923 refcnt_rele(struct refcnt *r) 924 { 925 u_int refs; 926 927 membar_exit_before_atomic(); 928 refs = atomic_dec_int_nv(&r->r_refs); 929 KASSERT(refs != ~0); 930 TRACEINDEX(refcnt, r->r_traceidx, r, refs + 1, -1); 931 if (refs == 0) { 932 membar_enter_after_atomic(); 933 return (1); 934 } 935 return (0); 936 } 937 938 void 939 refcnt_rele_wake(struct refcnt *r) 940 { 941 if (refcnt_rele(r)) 942 wakeup_one(r); 943 } 944 945 void 946 refcnt_finalize(struct refcnt *r, const char *wmesg) 947 { 948 u_int refs; 949 950 membar_exit_before_atomic(); 951 refs = atomic_dec_int_nv(&r->r_refs); 952 KASSERT(refs != ~0); 953 TRACEINDEX(refcnt, r->r_traceidx, r, refs + 1, -1); 954 while (refs) { 955 sleep_setup(r, PWAIT, wmesg); 956 refs = atomic_load_int(&r->r_refs); 957 sleep_finish(0, refs); 958 } 959 TRACEINDEX(refcnt, r->r_traceidx, r, refs, 0); 960 /* Order subsequent loads and stores after refs == 0 load. */ 961 membar_sync(); 962 } 963 964 int 965 refcnt_shared(struct refcnt *r) 966 { 967 u_int refs; 968 969 refs = atomic_load_int(&r->r_refs); 970 TRACEINDEX(refcnt, r->r_traceidx, r, refs, 0); 971 return (refs > 1); 972 } 973 974 unsigned int 975 refcnt_read(struct refcnt *r) 976 { 977 u_int refs; 978 979 refs = atomic_load_int(&r->r_refs); 980 TRACEINDEX(refcnt, r->r_traceidx, r, refs, 0); 981 return (refs); 982 } 983 984 void 985 cond_init(struct cond *c) 986 { 987 atomic_store_int(&c->c_wait, 1); 988 } 989 990 void 991 cond_signal(struct cond *c) 992 { 993 atomic_store_int(&c->c_wait, 0); 994 995 wakeup_one(c); 996 } 997 998 void 999 cond_wait(struct cond *c, const char *wmesg) 1000 { 1001 unsigned int wait; 1002 1003 wait = atomic_load_int(&c->c_wait); 1004 while (wait) { 1005 sleep_setup(c, PWAIT, wmesg); 1006 wait = atomic_load_int(&c->c_wait); 1007 sleep_finish(0, wait); 1008 } 1009 } 1010