1 /*- 2 * Copyright (c) 2004 John Baldwin <jhb@FreeBSD.org> 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. Neither the name of the author nor the names of any co-contributors 14 * may be used to endorse or promote products derived from this software 15 * without specific prior written permission. 16 * 17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 27 * SUCH DAMAGE. 28 */ 29 30 /* 31 * Implementation of sleep queues used to hold queue of threads blocked on 32 * a wait channel. Sleep queues different from turnstiles in that wait 33 * channels are not owned by anyone, so there is no priority propagation. 34 * Sleep queues can also provide a timeout and can also be interrupted by 35 * signals. That said, there are several similarities between the turnstile 36 * and sleep queue implementations. (Note: turnstiles were implemented 37 * first.) For example, both use a hash table of the same size where each 38 * bucket is referred to as a "chain" that contains both a spin lock and 39 * a linked list of queues. An individual queue is located by using a hash 40 * to pick a chain, locking the chain, and then walking the chain searching 41 * for the queue. This means that a wait channel object does not need to 42 * embed it's queue head just as locks do not embed their turnstile queue 43 * head. Threads also carry around a sleep queue that they lend to the 44 * wait channel when blocking. Just as in turnstiles, the queue includes 45 * a free list of the sleep queues of other threads blocked on the same 46 * wait channel in the case of multiple waiters. 47 * 48 * Some additional functionality provided by sleep queues include the 49 * ability to set a timeout. The timeout is managed using a per-thread 50 * callout that resumes a thread if it is asleep. A thread may also 51 * catch signals while it is asleep (aka an interruptible sleep). The 52 * signal code uses sleepq_abort() to interrupt a sleeping thread. Finally, 53 * sleep queues also provide some extra assertions. One is not allowed to 54 * mix the sleep/wakeup and cv APIs for a given wait channel. Also, one 55 * must consistently use the same lock to synchronize with a wait channel, 56 * though this check is currently only a warning for sleep/wakeup due to 57 * pre-existing abuse of that API. The same lock must also be held when 58 * awakening threads, though that is currently only enforced for condition 59 * variables. 60 */ 61 62 #include <sys/cdefs.h> 63 __FBSDID("$FreeBSD$"); 64 65 #include "opt_sleepqueue_profiling.h" 66 #include "opt_ddb.h" 67 #include "opt_sched.h" 68 69 #include <sys/param.h> 70 #include <sys/systm.h> 71 #include <sys/lock.h> 72 #include <sys/kernel.h> 73 #include <sys/ktr.h> 74 #include <sys/mutex.h> 75 #include <sys/proc.h> 76 #include <sys/sbuf.h> 77 #include <sys/sched.h> 78 #include <sys/sdt.h> 79 #include <sys/signalvar.h> 80 #include <sys/sleepqueue.h> 81 #include <sys/sysctl.h> 82 83 #include <vm/uma.h> 84 85 #ifdef DDB 86 #include <ddb/ddb.h> 87 #endif 88 89 /* 90 * Constants for the hash table of sleep queue chains. 91 * SC_TABLESIZE must be a power of two for SC_MASK to work properly. 92 */ 93 #define SC_TABLESIZE 256 /* Must be power of 2. */ 94 #define SC_MASK (SC_TABLESIZE - 1) 95 #define SC_SHIFT 8 96 #define SC_HASH(wc) ((((uintptr_t)(wc) >> SC_SHIFT) ^ (uintptr_t)(wc)) & \ 97 SC_MASK) 98 #define SC_LOOKUP(wc) &sleepq_chains[SC_HASH(wc)] 99 #define NR_SLEEPQS 2 100 /* 101 * There two different lists of sleep queues. Both lists are connected 102 * via the sq_hash entries. The first list is the sleep queue chain list 103 * that a sleep queue is on when it is attached to a wait channel. The 104 * second list is the free list hung off of a sleep queue that is attached 105 * to a wait channel. 106 * 107 * Each sleep queue also contains the wait channel it is attached to, the 108 * list of threads blocked on that wait channel, flags specific to the 109 * wait channel, and the lock used to synchronize with a wait channel. 110 * The flags are used to catch mismatches between the various consumers 111 * of the sleep queue API (e.g. sleep/wakeup and condition variables). 112 * The lock pointer is only used when invariants are enabled for various 113 * debugging checks. 114 * 115 * Locking key: 116 * c - sleep queue chain lock 117 */ 118 struct sleepqueue { 119 TAILQ_HEAD(, thread) sq_blocked[NR_SLEEPQS]; /* (c) Blocked threads. */ 120 u_int sq_blockedcnt[NR_SLEEPQS]; /* (c) N. of blocked threads. */ 121 LIST_ENTRY(sleepqueue) sq_hash; /* (c) Chain and free list. */ 122 LIST_HEAD(, sleepqueue) sq_free; /* (c) Free queues. */ 123 void *sq_wchan; /* (c) Wait channel. */ 124 int sq_type; /* (c) Queue type. */ 125 #ifdef INVARIANTS 126 struct lock_object *sq_lock; /* (c) Associated lock. */ 127 #endif 128 }; 129 130 struct sleepqueue_chain { 131 LIST_HEAD(, sleepqueue) sc_queues; /* List of sleep queues. */ 132 struct mtx sc_lock; /* Spin lock for this chain. */ 133 #ifdef SLEEPQUEUE_PROFILING 134 u_int sc_depth; /* Length of sc_queues. */ 135 u_int sc_max_depth; /* Max length of sc_queues. */ 136 #endif 137 }; 138 139 #ifdef SLEEPQUEUE_PROFILING 140 u_int sleepq_max_depth; 141 static SYSCTL_NODE(_debug, OID_AUTO, sleepq, CTLFLAG_RD, 0, "sleepq profiling"); 142 static SYSCTL_NODE(_debug_sleepq, OID_AUTO, chains, CTLFLAG_RD, 0, 143 "sleepq chain stats"); 144 SYSCTL_UINT(_debug_sleepq, OID_AUTO, max_depth, CTLFLAG_RD, &sleepq_max_depth, 145 0, "maxmimum depth achieved of a single chain"); 146 147 static void sleepq_profile(const char *wmesg); 148 static int prof_enabled; 149 #endif 150 static struct sleepqueue_chain sleepq_chains[SC_TABLESIZE]; 151 static uma_zone_t sleepq_zone; 152 153 /* 154 * Prototypes for non-exported routines. 155 */ 156 static int sleepq_catch_signals(void *wchan, int pri); 157 static int sleepq_check_signals(void); 158 static int sleepq_check_timeout(void); 159 #ifdef INVARIANTS 160 static void sleepq_dtor(void *mem, int size, void *arg); 161 #endif 162 static int sleepq_init(void *mem, int size, int flags); 163 static int sleepq_resume_thread(struct sleepqueue *sq, struct thread *td, 164 int pri); 165 static void sleepq_switch(void *wchan, int pri); 166 static void sleepq_timeout(void *arg); 167 168 SDT_PROBE_DECLARE(sched, , , sleep); 169 SDT_PROBE_DECLARE(sched, , , wakeup); 170 171 /* 172 * Early initialization of sleep queues that is called from the sleepinit() 173 * SYSINIT. 174 */ 175 void 176 init_sleepqueues(void) 177 { 178 #ifdef SLEEPQUEUE_PROFILING 179 struct sysctl_oid *chain_oid; 180 char chain_name[10]; 181 #endif 182 int i; 183 184 for (i = 0; i < SC_TABLESIZE; i++) { 185 LIST_INIT(&sleepq_chains[i].sc_queues); 186 mtx_init(&sleepq_chains[i].sc_lock, "sleepq chain", NULL, 187 MTX_SPIN | MTX_RECURSE); 188 #ifdef SLEEPQUEUE_PROFILING 189 snprintf(chain_name, sizeof(chain_name), "%d", i); 190 chain_oid = SYSCTL_ADD_NODE(NULL, 191 SYSCTL_STATIC_CHILDREN(_debug_sleepq_chains), OID_AUTO, 192 chain_name, CTLFLAG_RD, NULL, "sleepq chain stats"); 193 SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(chain_oid), OID_AUTO, 194 "depth", CTLFLAG_RD, &sleepq_chains[i].sc_depth, 0, NULL); 195 SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(chain_oid), OID_AUTO, 196 "max_depth", CTLFLAG_RD, &sleepq_chains[i].sc_max_depth, 0, 197 NULL); 198 #endif 199 } 200 sleepq_zone = uma_zcreate("SLEEPQUEUE", sizeof(struct sleepqueue), 201 #ifdef INVARIANTS 202 NULL, sleepq_dtor, sleepq_init, NULL, UMA_ALIGN_CACHE, 0); 203 #else 204 NULL, NULL, sleepq_init, NULL, UMA_ALIGN_CACHE, 0); 205 #endif 206 207 thread0.td_sleepqueue = sleepq_alloc(); 208 } 209 210 /* 211 * Get a sleep queue for a new thread. 212 */ 213 struct sleepqueue * 214 sleepq_alloc(void) 215 { 216 217 return (uma_zalloc(sleepq_zone, M_WAITOK)); 218 } 219 220 /* 221 * Free a sleep queue when a thread is destroyed. 222 */ 223 void 224 sleepq_free(struct sleepqueue *sq) 225 { 226 227 uma_zfree(sleepq_zone, sq); 228 } 229 230 /* 231 * Lock the sleep queue chain associated with the specified wait channel. 232 */ 233 void 234 sleepq_lock(void *wchan) 235 { 236 struct sleepqueue_chain *sc; 237 238 sc = SC_LOOKUP(wchan); 239 mtx_lock_spin(&sc->sc_lock); 240 } 241 242 /* 243 * Look up the sleep queue associated with a given wait channel in the hash 244 * table locking the associated sleep queue chain. If no queue is found in 245 * the table, NULL is returned. 246 */ 247 struct sleepqueue * 248 sleepq_lookup(void *wchan) 249 { 250 struct sleepqueue_chain *sc; 251 struct sleepqueue *sq; 252 253 KASSERT(wchan != NULL, ("%s: invalid NULL wait channel", __func__)); 254 sc = SC_LOOKUP(wchan); 255 mtx_assert(&sc->sc_lock, MA_OWNED); 256 LIST_FOREACH(sq, &sc->sc_queues, sq_hash) 257 if (sq->sq_wchan == wchan) 258 return (sq); 259 return (NULL); 260 } 261 262 /* 263 * Unlock the sleep queue chain associated with a given wait channel. 264 */ 265 void 266 sleepq_release(void *wchan) 267 { 268 struct sleepqueue_chain *sc; 269 270 sc = SC_LOOKUP(wchan); 271 mtx_unlock_spin(&sc->sc_lock); 272 } 273 274 /* 275 * Places the current thread on the sleep queue for the specified wait 276 * channel. If INVARIANTS is enabled, then it associates the passed in 277 * lock with the sleepq to make sure it is held when that sleep queue is 278 * woken up. 279 */ 280 void 281 sleepq_add(void *wchan, struct lock_object *lock, const char *wmesg, int flags, 282 int queue) 283 { 284 struct sleepqueue_chain *sc; 285 struct sleepqueue *sq; 286 struct thread *td; 287 288 td = curthread; 289 sc = SC_LOOKUP(wchan); 290 mtx_assert(&sc->sc_lock, MA_OWNED); 291 MPASS(td->td_sleepqueue != NULL); 292 MPASS(wchan != NULL); 293 MPASS((queue >= 0) && (queue < NR_SLEEPQS)); 294 295 /* If this thread is not allowed to sleep, die a horrible death. */ 296 KASSERT(td->td_no_sleeping == 0, 297 ("%s: td %p to sleep on wchan %p with sleeping prohibited", 298 __func__, td, wchan)); 299 300 /* Look up the sleep queue associated with the wait channel 'wchan'. */ 301 sq = sleepq_lookup(wchan); 302 303 /* 304 * If the wait channel does not already have a sleep queue, use 305 * this thread's sleep queue. Otherwise, insert the current thread 306 * into the sleep queue already in use by this wait channel. 307 */ 308 if (sq == NULL) { 309 #ifdef INVARIANTS 310 int i; 311 312 sq = td->td_sleepqueue; 313 for (i = 0; i < NR_SLEEPQS; i++) { 314 KASSERT(TAILQ_EMPTY(&sq->sq_blocked[i]), 315 ("thread's sleep queue %d is not empty", i)); 316 KASSERT(sq->sq_blockedcnt[i] == 0, 317 ("thread's sleep queue %d count mismatches", i)); 318 } 319 KASSERT(LIST_EMPTY(&sq->sq_free), 320 ("thread's sleep queue has a non-empty free list")); 321 KASSERT(sq->sq_wchan == NULL, ("stale sq_wchan pointer")); 322 sq->sq_lock = lock; 323 #endif 324 #ifdef SLEEPQUEUE_PROFILING 325 sc->sc_depth++; 326 if (sc->sc_depth > sc->sc_max_depth) { 327 sc->sc_max_depth = sc->sc_depth; 328 if (sc->sc_max_depth > sleepq_max_depth) 329 sleepq_max_depth = sc->sc_max_depth; 330 } 331 #endif 332 sq = td->td_sleepqueue; 333 LIST_INSERT_HEAD(&sc->sc_queues, sq, sq_hash); 334 sq->sq_wchan = wchan; 335 sq->sq_type = flags & SLEEPQ_TYPE; 336 } else { 337 MPASS(wchan == sq->sq_wchan); 338 MPASS(lock == sq->sq_lock); 339 MPASS((flags & SLEEPQ_TYPE) == sq->sq_type); 340 LIST_INSERT_HEAD(&sq->sq_free, td->td_sleepqueue, sq_hash); 341 } 342 thread_lock(td); 343 TAILQ_INSERT_TAIL(&sq->sq_blocked[queue], td, td_slpq); 344 sq->sq_blockedcnt[queue]++; 345 td->td_sleepqueue = NULL; 346 td->td_sqqueue = queue; 347 td->td_wchan = wchan; 348 td->td_wmesg = wmesg; 349 if (flags & SLEEPQ_INTERRUPTIBLE) { 350 td->td_flags |= TDF_SINTR; 351 td->td_flags &= ~TDF_SLEEPABORT; 352 } 353 thread_unlock(td); 354 } 355 356 /* 357 * Sets a timeout that will remove the current thread from the specified 358 * sleep queue after timo ticks if the thread has not already been awakened. 359 */ 360 void 361 sleepq_set_timeout_sbt(void *wchan, sbintime_t sbt, sbintime_t pr, 362 int flags) 363 { 364 struct sleepqueue_chain *sc; 365 struct thread *td; 366 367 td = curthread; 368 sc = SC_LOOKUP(wchan); 369 mtx_assert(&sc->sc_lock, MA_OWNED); 370 MPASS(TD_ON_SLEEPQ(td)); 371 MPASS(td->td_sleepqueue == NULL); 372 MPASS(wchan != NULL); 373 callout_reset_sbt_on(&td->td_slpcallout, sbt, pr, 374 sleepq_timeout, td, PCPU_GET(cpuid), flags | C_DIRECT_EXEC); 375 } 376 377 /* 378 * Return the number of actual sleepers for the specified queue. 379 */ 380 u_int 381 sleepq_sleepcnt(void *wchan, int queue) 382 { 383 struct sleepqueue *sq; 384 385 KASSERT(wchan != NULL, ("%s: invalid NULL wait channel", __func__)); 386 MPASS((queue >= 0) && (queue < NR_SLEEPQS)); 387 sq = sleepq_lookup(wchan); 388 if (sq == NULL) 389 return (0); 390 return (sq->sq_blockedcnt[queue]); 391 } 392 393 /* 394 * Marks the pending sleep of the current thread as interruptible and 395 * makes an initial check for pending signals before putting a thread 396 * to sleep. Enters and exits with the thread lock held. Thread lock 397 * may have transitioned from the sleepq lock to a run lock. 398 */ 399 static int 400 sleepq_catch_signals(void *wchan, int pri) 401 { 402 struct sleepqueue_chain *sc; 403 struct sleepqueue *sq; 404 struct thread *td; 405 struct proc *p; 406 struct sigacts *ps; 407 int sig, ret; 408 409 td = curthread; 410 p = curproc; 411 sc = SC_LOOKUP(wchan); 412 mtx_assert(&sc->sc_lock, MA_OWNED); 413 MPASS(wchan != NULL); 414 if ((td->td_pflags & TDP_WAKEUP) != 0) { 415 td->td_pflags &= ~TDP_WAKEUP; 416 ret = EINTR; 417 thread_lock(td); 418 goto out; 419 } 420 421 /* 422 * See if there are any pending signals for this thread. If not 423 * we can switch immediately. Otherwise do the signal processing 424 * directly. 425 */ 426 thread_lock(td); 427 if ((td->td_flags & (TDF_NEEDSIGCHK | TDF_NEEDSUSPCHK)) == 0) { 428 sleepq_switch(wchan, pri); 429 return (0); 430 } 431 thread_unlock(td); 432 mtx_unlock_spin(&sc->sc_lock); 433 CTR3(KTR_PROC, "sleepq catching signals: thread %p (pid %ld, %s)", 434 (void *)td, (long)p->p_pid, td->td_name); 435 PROC_LOCK(p); 436 ps = p->p_sigacts; 437 mtx_lock(&ps->ps_mtx); 438 sig = cursig(td); 439 if (sig == 0) { 440 mtx_unlock(&ps->ps_mtx); 441 ret = thread_suspend_check(1); 442 MPASS(ret == 0 || ret == EINTR || ret == ERESTART); 443 } else { 444 if (SIGISMEMBER(ps->ps_sigintr, sig)) 445 ret = EINTR; 446 else 447 ret = ERESTART; 448 mtx_unlock(&ps->ps_mtx); 449 } 450 /* 451 * Lock the per-process spinlock prior to dropping the PROC_LOCK 452 * to avoid a signal delivery race. PROC_LOCK, PROC_SLOCK, and 453 * thread_lock() are currently held in tdsendsignal(). 454 */ 455 PROC_SLOCK(p); 456 mtx_lock_spin(&sc->sc_lock); 457 PROC_UNLOCK(p); 458 thread_lock(td); 459 PROC_SUNLOCK(p); 460 if (ret == 0) { 461 sleepq_switch(wchan, pri); 462 return (0); 463 } 464 out: 465 /* 466 * There were pending signals and this thread is still 467 * on the sleep queue, remove it from the sleep queue. 468 */ 469 if (TD_ON_SLEEPQ(td)) { 470 sq = sleepq_lookup(wchan); 471 if (sleepq_resume_thread(sq, td, 0)) { 472 #ifdef INVARIANTS 473 /* 474 * This thread hasn't gone to sleep yet, so it 475 * should not be swapped out. 476 */ 477 panic("not waking up swapper"); 478 #endif 479 } 480 } 481 mtx_unlock_spin(&sc->sc_lock); 482 MPASS(td->td_lock != &sc->sc_lock); 483 return (ret); 484 } 485 486 /* 487 * Switches to another thread if we are still asleep on a sleep queue. 488 * Returns with thread lock. 489 */ 490 static void 491 sleepq_switch(void *wchan, int pri) 492 { 493 struct sleepqueue_chain *sc; 494 struct sleepqueue *sq; 495 struct thread *td; 496 497 td = curthread; 498 sc = SC_LOOKUP(wchan); 499 mtx_assert(&sc->sc_lock, MA_OWNED); 500 THREAD_LOCK_ASSERT(td, MA_OWNED); 501 502 /* 503 * If we have a sleep queue, then we've already been woken up, so 504 * just return. 505 */ 506 if (td->td_sleepqueue != NULL) { 507 mtx_unlock_spin(&sc->sc_lock); 508 return; 509 } 510 511 /* 512 * If TDF_TIMEOUT is set, then our sleep has been timed out 513 * already but we are still on the sleep queue, so dequeue the 514 * thread and return. 515 */ 516 if (td->td_flags & TDF_TIMEOUT) { 517 MPASS(TD_ON_SLEEPQ(td)); 518 sq = sleepq_lookup(wchan); 519 if (sleepq_resume_thread(sq, td, 0)) { 520 #ifdef INVARIANTS 521 /* 522 * This thread hasn't gone to sleep yet, so it 523 * should not be swapped out. 524 */ 525 panic("not waking up swapper"); 526 #endif 527 } 528 mtx_unlock_spin(&sc->sc_lock); 529 return; 530 } 531 #ifdef SLEEPQUEUE_PROFILING 532 if (prof_enabled) 533 sleepq_profile(td->td_wmesg); 534 #endif 535 MPASS(td->td_sleepqueue == NULL); 536 sched_sleep(td, pri); 537 thread_lock_set(td, &sc->sc_lock); 538 SDT_PROBE0(sched, , , sleep); 539 TD_SET_SLEEPING(td); 540 mi_switch(SW_VOL | SWT_SLEEPQ, NULL); 541 KASSERT(TD_IS_RUNNING(td), ("running but not TDS_RUNNING")); 542 CTR3(KTR_PROC, "sleepq resume: thread %p (pid %ld, %s)", 543 (void *)td, (long)td->td_proc->p_pid, (void *)td->td_name); 544 } 545 546 /* 547 * Check to see if we timed out. 548 */ 549 static int 550 sleepq_check_timeout(void) 551 { 552 struct thread *td; 553 554 td = curthread; 555 THREAD_LOCK_ASSERT(td, MA_OWNED); 556 557 /* 558 * If TDF_TIMEOUT is set, we timed out. 559 */ 560 if (td->td_flags & TDF_TIMEOUT) { 561 td->td_flags &= ~TDF_TIMEOUT; 562 return (EWOULDBLOCK); 563 } 564 565 /* 566 * If TDF_TIMOFAIL is set, the timeout ran after we had 567 * already been woken up. 568 */ 569 if (td->td_flags & TDF_TIMOFAIL) 570 td->td_flags &= ~TDF_TIMOFAIL; 571 572 /* 573 * If callout_stop() fails, then the timeout is running on 574 * another CPU, so synchronize with it to avoid having it 575 * accidentally wake up a subsequent sleep. 576 */ 577 else if (callout_stop(&td->td_slpcallout) == 0) { 578 td->td_flags |= TDF_TIMEOUT; 579 TD_SET_SLEEPING(td); 580 mi_switch(SW_INVOL | SWT_SLEEPQTIMO, NULL); 581 } 582 return (0); 583 } 584 585 /* 586 * Check to see if we were awoken by a signal. 587 */ 588 static int 589 sleepq_check_signals(void) 590 { 591 struct thread *td; 592 593 td = curthread; 594 THREAD_LOCK_ASSERT(td, MA_OWNED); 595 596 /* We are no longer in an interruptible sleep. */ 597 if (td->td_flags & TDF_SINTR) 598 td->td_flags &= ~TDF_SINTR; 599 600 if (td->td_flags & TDF_SLEEPABORT) { 601 td->td_flags &= ~TDF_SLEEPABORT; 602 return (td->td_intrval); 603 } 604 605 return (0); 606 } 607 608 /* 609 * Block the current thread until it is awakened from its sleep queue. 610 */ 611 void 612 sleepq_wait(void *wchan, int pri) 613 { 614 struct thread *td; 615 616 td = curthread; 617 MPASS(!(td->td_flags & TDF_SINTR)); 618 thread_lock(td); 619 sleepq_switch(wchan, pri); 620 thread_unlock(td); 621 } 622 623 /* 624 * Block the current thread until it is awakened from its sleep queue 625 * or it is interrupted by a signal. 626 */ 627 int 628 sleepq_wait_sig(void *wchan, int pri) 629 { 630 int rcatch; 631 int rval; 632 633 rcatch = sleepq_catch_signals(wchan, pri); 634 rval = sleepq_check_signals(); 635 thread_unlock(curthread); 636 if (rcatch) 637 return (rcatch); 638 return (rval); 639 } 640 641 /* 642 * Block the current thread until it is awakened from its sleep queue 643 * or it times out while waiting. 644 */ 645 int 646 sleepq_timedwait(void *wchan, int pri) 647 { 648 struct thread *td; 649 int rval; 650 651 td = curthread; 652 MPASS(!(td->td_flags & TDF_SINTR)); 653 thread_lock(td); 654 sleepq_switch(wchan, pri); 655 rval = sleepq_check_timeout(); 656 thread_unlock(td); 657 658 return (rval); 659 } 660 661 /* 662 * Block the current thread until it is awakened from its sleep queue, 663 * it is interrupted by a signal, or it times out waiting to be awakened. 664 */ 665 int 666 sleepq_timedwait_sig(void *wchan, int pri) 667 { 668 int rcatch, rvalt, rvals; 669 670 rcatch = sleepq_catch_signals(wchan, pri); 671 rvalt = sleepq_check_timeout(); 672 rvals = sleepq_check_signals(); 673 thread_unlock(curthread); 674 if (rcatch) 675 return (rcatch); 676 if (rvals) 677 return (rvals); 678 return (rvalt); 679 } 680 681 /* 682 * Returns the type of sleepqueue given a waitchannel. 683 */ 684 int 685 sleepq_type(void *wchan) 686 { 687 struct sleepqueue *sq; 688 int type; 689 690 MPASS(wchan != NULL); 691 692 sleepq_lock(wchan); 693 sq = sleepq_lookup(wchan); 694 if (sq == NULL) { 695 sleepq_release(wchan); 696 return (-1); 697 } 698 type = sq->sq_type; 699 sleepq_release(wchan); 700 return (type); 701 } 702 703 /* 704 * Removes a thread from a sleep queue and makes it 705 * runnable. 706 */ 707 static int 708 sleepq_resume_thread(struct sleepqueue *sq, struct thread *td, int pri) 709 { 710 struct sleepqueue_chain *sc; 711 712 MPASS(td != NULL); 713 MPASS(sq->sq_wchan != NULL); 714 MPASS(td->td_wchan == sq->sq_wchan); 715 MPASS(td->td_sqqueue < NR_SLEEPQS && td->td_sqqueue >= 0); 716 THREAD_LOCK_ASSERT(td, MA_OWNED); 717 sc = SC_LOOKUP(sq->sq_wchan); 718 mtx_assert(&sc->sc_lock, MA_OWNED); 719 720 SDT_PROBE2(sched, , , wakeup, td, td->td_proc); 721 722 /* Remove the thread from the queue. */ 723 sq->sq_blockedcnt[td->td_sqqueue]--; 724 TAILQ_REMOVE(&sq->sq_blocked[td->td_sqqueue], td, td_slpq); 725 726 /* 727 * Get a sleep queue for this thread. If this is the last waiter, 728 * use the queue itself and take it out of the chain, otherwise, 729 * remove a queue from the free list. 730 */ 731 if (LIST_EMPTY(&sq->sq_free)) { 732 td->td_sleepqueue = sq; 733 #ifdef INVARIANTS 734 sq->sq_wchan = NULL; 735 #endif 736 #ifdef SLEEPQUEUE_PROFILING 737 sc->sc_depth--; 738 #endif 739 } else 740 td->td_sleepqueue = LIST_FIRST(&sq->sq_free); 741 LIST_REMOVE(td->td_sleepqueue, sq_hash); 742 743 td->td_wmesg = NULL; 744 td->td_wchan = NULL; 745 td->td_flags &= ~TDF_SINTR; 746 747 CTR3(KTR_PROC, "sleepq_wakeup: thread %p (pid %ld, %s)", 748 (void *)td, (long)td->td_proc->p_pid, td->td_name); 749 750 /* Adjust priority if requested. */ 751 MPASS(pri == 0 || (pri >= PRI_MIN && pri <= PRI_MAX)); 752 if (pri != 0 && td->td_priority > pri && 753 PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) 754 sched_prio(td, pri); 755 756 /* 757 * Note that thread td might not be sleeping if it is running 758 * sleepq_catch_signals() on another CPU or is blocked on its 759 * proc lock to check signals. There's no need to mark the 760 * thread runnable in that case. 761 */ 762 if (TD_IS_SLEEPING(td)) { 763 TD_CLR_SLEEPING(td); 764 return (setrunnable(td)); 765 } 766 return (0); 767 } 768 769 #ifdef INVARIANTS 770 /* 771 * UMA zone item deallocator. 772 */ 773 static void 774 sleepq_dtor(void *mem, int size, void *arg) 775 { 776 struct sleepqueue *sq; 777 int i; 778 779 sq = mem; 780 for (i = 0; i < NR_SLEEPQS; i++) { 781 MPASS(TAILQ_EMPTY(&sq->sq_blocked[i])); 782 MPASS(sq->sq_blockedcnt[i] == 0); 783 } 784 } 785 #endif 786 787 /* 788 * UMA zone item initializer. 789 */ 790 static int 791 sleepq_init(void *mem, int size, int flags) 792 { 793 struct sleepqueue *sq; 794 int i; 795 796 bzero(mem, size); 797 sq = mem; 798 for (i = 0; i < NR_SLEEPQS; i++) { 799 TAILQ_INIT(&sq->sq_blocked[i]); 800 sq->sq_blockedcnt[i] = 0; 801 } 802 LIST_INIT(&sq->sq_free); 803 return (0); 804 } 805 806 /* 807 * Find the highest priority thread sleeping on a wait channel and resume it. 808 */ 809 int 810 sleepq_signal(void *wchan, int flags, int pri, int queue) 811 { 812 struct sleepqueue *sq; 813 struct thread *td, *besttd; 814 int wakeup_swapper; 815 816 CTR2(KTR_PROC, "sleepq_signal(%p, %d)", wchan, flags); 817 KASSERT(wchan != NULL, ("%s: invalid NULL wait channel", __func__)); 818 MPASS((queue >= 0) && (queue < NR_SLEEPQS)); 819 sq = sleepq_lookup(wchan); 820 if (sq == NULL) 821 return (0); 822 KASSERT(sq->sq_type == (flags & SLEEPQ_TYPE), 823 ("%s: mismatch between sleep/wakeup and cv_*", __func__)); 824 825 /* 826 * Find the highest priority thread on the queue. If there is a 827 * tie, use the thread that first appears in the queue as it has 828 * been sleeping the longest since threads are always added to 829 * the tail of sleep queues. 830 */ 831 besttd = NULL; 832 TAILQ_FOREACH(td, &sq->sq_blocked[queue], td_slpq) { 833 if (besttd == NULL || td->td_priority < besttd->td_priority) 834 besttd = td; 835 } 836 MPASS(besttd != NULL); 837 thread_lock(besttd); 838 wakeup_swapper = sleepq_resume_thread(sq, besttd, pri); 839 thread_unlock(besttd); 840 return (wakeup_swapper); 841 } 842 843 /* 844 * Resume all threads sleeping on a specified wait channel. 845 */ 846 int 847 sleepq_broadcast(void *wchan, int flags, int pri, int queue) 848 { 849 struct sleepqueue *sq; 850 struct thread *td, *tdn; 851 int wakeup_swapper; 852 853 CTR2(KTR_PROC, "sleepq_broadcast(%p, %d)", wchan, flags); 854 KASSERT(wchan != NULL, ("%s: invalid NULL wait channel", __func__)); 855 MPASS((queue >= 0) && (queue < NR_SLEEPQS)); 856 sq = sleepq_lookup(wchan); 857 if (sq == NULL) 858 return (0); 859 KASSERT(sq->sq_type == (flags & SLEEPQ_TYPE), 860 ("%s: mismatch between sleep/wakeup and cv_*", __func__)); 861 862 /* Resume all blocked threads on the sleep queue. */ 863 wakeup_swapper = 0; 864 TAILQ_FOREACH_SAFE(td, &sq->sq_blocked[queue], td_slpq, tdn) { 865 thread_lock(td); 866 if (sleepq_resume_thread(sq, td, pri)) 867 wakeup_swapper = 1; 868 thread_unlock(td); 869 } 870 return (wakeup_swapper); 871 } 872 873 /* 874 * Time sleeping threads out. When the timeout expires, the thread is 875 * removed from the sleep queue and made runnable if it is still asleep. 876 */ 877 static void 878 sleepq_timeout(void *arg) 879 { 880 struct sleepqueue_chain *sc; 881 struct sleepqueue *sq; 882 struct thread *td; 883 void *wchan; 884 int wakeup_swapper; 885 886 td = arg; 887 wakeup_swapper = 0; 888 CTR3(KTR_PROC, "sleepq_timeout: thread %p (pid %ld, %s)", 889 (void *)td, (long)td->td_proc->p_pid, (void *)td->td_name); 890 891 /* 892 * First, see if the thread is asleep and get the wait channel if 893 * it is. 894 */ 895 thread_lock(td); 896 if (TD_IS_SLEEPING(td) && TD_ON_SLEEPQ(td)) { 897 wchan = td->td_wchan; 898 sc = SC_LOOKUP(wchan); 899 THREAD_LOCKPTR_ASSERT(td, &sc->sc_lock); 900 sq = sleepq_lookup(wchan); 901 MPASS(sq != NULL); 902 td->td_flags |= TDF_TIMEOUT; 903 wakeup_swapper = sleepq_resume_thread(sq, td, 0); 904 thread_unlock(td); 905 if (wakeup_swapper) 906 kick_proc0(); 907 return; 908 } 909 910 /* 911 * If the thread is on the SLEEPQ but isn't sleeping yet, it 912 * can either be on another CPU in between sleepq_add() and 913 * one of the sleepq_*wait*() routines or it can be in 914 * sleepq_catch_signals(). 915 */ 916 if (TD_ON_SLEEPQ(td)) { 917 td->td_flags |= TDF_TIMEOUT; 918 thread_unlock(td); 919 return; 920 } 921 922 /* 923 * Now check for the edge cases. First, if TDF_TIMEOUT is set, 924 * then the other thread has already yielded to us, so clear 925 * the flag and resume it. If TDF_TIMEOUT is not set, then the 926 * we know that the other thread is not on a sleep queue, but it 927 * hasn't resumed execution yet. In that case, set TDF_TIMOFAIL 928 * to let it know that the timeout has already run and doesn't 929 * need to be canceled. 930 */ 931 if (td->td_flags & TDF_TIMEOUT) { 932 MPASS(TD_IS_SLEEPING(td)); 933 td->td_flags &= ~TDF_TIMEOUT; 934 TD_CLR_SLEEPING(td); 935 wakeup_swapper = setrunnable(td); 936 } else 937 td->td_flags |= TDF_TIMOFAIL; 938 thread_unlock(td); 939 if (wakeup_swapper) 940 kick_proc0(); 941 } 942 943 /* 944 * Resumes a specific thread from the sleep queue associated with a specific 945 * wait channel if it is on that queue. 946 */ 947 void 948 sleepq_remove(struct thread *td, void *wchan) 949 { 950 struct sleepqueue *sq; 951 int wakeup_swapper; 952 953 /* 954 * Look up the sleep queue for this wait channel, then re-check 955 * that the thread is asleep on that channel, if it is not, then 956 * bail. 957 */ 958 MPASS(wchan != NULL); 959 sleepq_lock(wchan); 960 sq = sleepq_lookup(wchan); 961 /* 962 * We can not lock the thread here as it may be sleeping on a 963 * different sleepq. However, holding the sleepq lock for this 964 * wchan can guarantee that we do not miss a wakeup for this 965 * channel. The asserts below will catch any false positives. 966 */ 967 if (!TD_ON_SLEEPQ(td) || td->td_wchan != wchan) { 968 sleepq_release(wchan); 969 return; 970 } 971 /* Thread is asleep on sleep queue sq, so wake it up. */ 972 thread_lock(td); 973 MPASS(sq != NULL); 974 MPASS(td->td_wchan == wchan); 975 wakeup_swapper = sleepq_resume_thread(sq, td, 0); 976 thread_unlock(td); 977 sleepq_release(wchan); 978 if (wakeup_swapper) 979 kick_proc0(); 980 } 981 982 /* 983 * Abort a thread as if an interrupt had occurred. Only abort 984 * interruptible waits (unfortunately it isn't safe to abort others). 985 */ 986 int 987 sleepq_abort(struct thread *td, int intrval) 988 { 989 struct sleepqueue *sq; 990 void *wchan; 991 992 THREAD_LOCK_ASSERT(td, MA_OWNED); 993 MPASS(TD_ON_SLEEPQ(td)); 994 MPASS(td->td_flags & TDF_SINTR); 995 MPASS(intrval == EINTR || intrval == ERESTART); 996 997 /* 998 * If the TDF_TIMEOUT flag is set, just leave. A 999 * timeout is scheduled anyhow. 1000 */ 1001 if (td->td_flags & TDF_TIMEOUT) 1002 return (0); 1003 1004 CTR3(KTR_PROC, "sleepq_abort: thread %p (pid %ld, %s)", 1005 (void *)td, (long)td->td_proc->p_pid, (void *)td->td_name); 1006 td->td_intrval = intrval; 1007 td->td_flags |= TDF_SLEEPABORT; 1008 /* 1009 * If the thread has not slept yet it will find the signal in 1010 * sleepq_catch_signals() and call sleepq_resume_thread. Otherwise 1011 * we have to do it here. 1012 */ 1013 if (!TD_IS_SLEEPING(td)) 1014 return (0); 1015 wchan = td->td_wchan; 1016 MPASS(wchan != NULL); 1017 sq = sleepq_lookup(wchan); 1018 MPASS(sq != NULL); 1019 1020 /* Thread is asleep on sleep queue sq, so wake it up. */ 1021 return (sleepq_resume_thread(sq, td, 0)); 1022 } 1023 1024 #ifdef SLEEPQUEUE_PROFILING 1025 #define SLEEPQ_PROF_LOCATIONS 1024 1026 #define SLEEPQ_SBUFSIZE 512 1027 struct sleepq_prof { 1028 LIST_ENTRY(sleepq_prof) sp_link; 1029 const char *sp_wmesg; 1030 long sp_count; 1031 }; 1032 1033 LIST_HEAD(sqphead, sleepq_prof); 1034 1035 struct sqphead sleepq_prof_free; 1036 struct sqphead sleepq_hash[SC_TABLESIZE]; 1037 static struct sleepq_prof sleepq_profent[SLEEPQ_PROF_LOCATIONS]; 1038 static struct mtx sleepq_prof_lock; 1039 MTX_SYSINIT(sleepq_prof_lock, &sleepq_prof_lock, "sleepq_prof", MTX_SPIN); 1040 1041 static void 1042 sleepq_profile(const char *wmesg) 1043 { 1044 struct sleepq_prof *sp; 1045 1046 mtx_lock_spin(&sleepq_prof_lock); 1047 if (prof_enabled == 0) 1048 goto unlock; 1049 LIST_FOREACH(sp, &sleepq_hash[SC_HASH(wmesg)], sp_link) 1050 if (sp->sp_wmesg == wmesg) 1051 goto done; 1052 sp = LIST_FIRST(&sleepq_prof_free); 1053 if (sp == NULL) 1054 goto unlock; 1055 sp->sp_wmesg = wmesg; 1056 LIST_REMOVE(sp, sp_link); 1057 LIST_INSERT_HEAD(&sleepq_hash[SC_HASH(wmesg)], sp, sp_link); 1058 done: 1059 sp->sp_count++; 1060 unlock: 1061 mtx_unlock_spin(&sleepq_prof_lock); 1062 return; 1063 } 1064 1065 static void 1066 sleepq_prof_reset(void) 1067 { 1068 struct sleepq_prof *sp; 1069 int enabled; 1070 int i; 1071 1072 mtx_lock_spin(&sleepq_prof_lock); 1073 enabled = prof_enabled; 1074 prof_enabled = 0; 1075 for (i = 0; i < SC_TABLESIZE; i++) 1076 LIST_INIT(&sleepq_hash[i]); 1077 LIST_INIT(&sleepq_prof_free); 1078 for (i = 0; i < SLEEPQ_PROF_LOCATIONS; i++) { 1079 sp = &sleepq_profent[i]; 1080 sp->sp_wmesg = NULL; 1081 sp->sp_count = 0; 1082 LIST_INSERT_HEAD(&sleepq_prof_free, sp, sp_link); 1083 } 1084 prof_enabled = enabled; 1085 mtx_unlock_spin(&sleepq_prof_lock); 1086 } 1087 1088 static int 1089 enable_sleepq_prof(SYSCTL_HANDLER_ARGS) 1090 { 1091 int error, v; 1092 1093 v = prof_enabled; 1094 error = sysctl_handle_int(oidp, &v, v, req); 1095 if (error) 1096 return (error); 1097 if (req->newptr == NULL) 1098 return (error); 1099 if (v == prof_enabled) 1100 return (0); 1101 if (v == 1) 1102 sleepq_prof_reset(); 1103 mtx_lock_spin(&sleepq_prof_lock); 1104 prof_enabled = !!v; 1105 mtx_unlock_spin(&sleepq_prof_lock); 1106 1107 return (0); 1108 } 1109 1110 static int 1111 reset_sleepq_prof_stats(SYSCTL_HANDLER_ARGS) 1112 { 1113 int error, v; 1114 1115 v = 0; 1116 error = sysctl_handle_int(oidp, &v, 0, req); 1117 if (error) 1118 return (error); 1119 if (req->newptr == NULL) 1120 return (error); 1121 if (v == 0) 1122 return (0); 1123 sleepq_prof_reset(); 1124 1125 return (0); 1126 } 1127 1128 static int 1129 dump_sleepq_prof_stats(SYSCTL_HANDLER_ARGS) 1130 { 1131 struct sleepq_prof *sp; 1132 struct sbuf *sb; 1133 int enabled; 1134 int error; 1135 int i; 1136 1137 error = sysctl_wire_old_buffer(req, 0); 1138 if (error != 0) 1139 return (error); 1140 sb = sbuf_new_for_sysctl(NULL, NULL, SLEEPQ_SBUFSIZE, req); 1141 sbuf_printf(sb, "\nwmesg\tcount\n"); 1142 enabled = prof_enabled; 1143 mtx_lock_spin(&sleepq_prof_lock); 1144 prof_enabled = 0; 1145 mtx_unlock_spin(&sleepq_prof_lock); 1146 for (i = 0; i < SC_TABLESIZE; i++) { 1147 LIST_FOREACH(sp, &sleepq_hash[i], sp_link) { 1148 sbuf_printf(sb, "%s\t%ld\n", 1149 sp->sp_wmesg, sp->sp_count); 1150 } 1151 } 1152 mtx_lock_spin(&sleepq_prof_lock); 1153 prof_enabled = enabled; 1154 mtx_unlock_spin(&sleepq_prof_lock); 1155 1156 error = sbuf_finish(sb); 1157 sbuf_delete(sb); 1158 return (error); 1159 } 1160 1161 SYSCTL_PROC(_debug_sleepq, OID_AUTO, stats, CTLTYPE_STRING | CTLFLAG_RD, 1162 NULL, 0, dump_sleepq_prof_stats, "A", "Sleepqueue profiling statistics"); 1163 SYSCTL_PROC(_debug_sleepq, OID_AUTO, reset, CTLTYPE_INT | CTLFLAG_RW, 1164 NULL, 0, reset_sleepq_prof_stats, "I", 1165 "Reset sleepqueue profiling statistics"); 1166 SYSCTL_PROC(_debug_sleepq, OID_AUTO, enable, CTLTYPE_INT | CTLFLAG_RW, 1167 NULL, 0, enable_sleepq_prof, "I", "Enable sleepqueue profiling"); 1168 #endif 1169 1170 #ifdef DDB 1171 DB_SHOW_COMMAND(sleepq, db_show_sleepqueue) 1172 { 1173 struct sleepqueue_chain *sc; 1174 struct sleepqueue *sq; 1175 #ifdef INVARIANTS 1176 struct lock_object *lock; 1177 #endif 1178 struct thread *td; 1179 void *wchan; 1180 int i; 1181 1182 if (!have_addr) 1183 return; 1184 1185 /* 1186 * First, see if there is an active sleep queue for the wait channel 1187 * indicated by the address. 1188 */ 1189 wchan = (void *)addr; 1190 sc = SC_LOOKUP(wchan); 1191 LIST_FOREACH(sq, &sc->sc_queues, sq_hash) 1192 if (sq->sq_wchan == wchan) 1193 goto found; 1194 1195 /* 1196 * Second, see if there is an active sleep queue at the address 1197 * indicated. 1198 */ 1199 for (i = 0; i < SC_TABLESIZE; i++) 1200 LIST_FOREACH(sq, &sleepq_chains[i].sc_queues, sq_hash) { 1201 if (sq == (struct sleepqueue *)addr) 1202 goto found; 1203 } 1204 1205 db_printf("Unable to locate a sleep queue via %p\n", (void *)addr); 1206 return; 1207 found: 1208 db_printf("Wait channel: %p\n", sq->sq_wchan); 1209 db_printf("Queue type: %d\n", sq->sq_type); 1210 #ifdef INVARIANTS 1211 if (sq->sq_lock) { 1212 lock = sq->sq_lock; 1213 db_printf("Associated Interlock: %p - (%s) %s\n", lock, 1214 LOCK_CLASS(lock)->lc_name, lock->lo_name); 1215 } 1216 #endif 1217 db_printf("Blocked threads:\n"); 1218 for (i = 0; i < NR_SLEEPQS; i++) { 1219 db_printf("\nQueue[%d]:\n", i); 1220 if (TAILQ_EMPTY(&sq->sq_blocked[i])) 1221 db_printf("\tempty\n"); 1222 else 1223 TAILQ_FOREACH(td, &sq->sq_blocked[0], 1224 td_slpq) { 1225 db_printf("\t%p (tid %d, pid %d, \"%s\")\n", td, 1226 td->td_tid, td->td_proc->p_pid, 1227 td->td_name); 1228 } 1229 db_printf("(expected: %u)\n", sq->sq_blockedcnt[i]); 1230 } 1231 } 1232 1233 /* Alias 'show sleepqueue' to 'show sleepq'. */ 1234 DB_SHOW_ALIAS(sleepqueue, db_show_sleepqueue); 1235 #endif 1236