1 /* 2 * CDDL HEADER START 3 * 4 * The contents of this file are subject to the terms of the 5 * Common Development and Distribution License (the "License"). 6 * You may not use this file except in compliance with the License. 7 * 8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE 9 * or http://www.opensolaris.org/os/licensing. 10 * See the License for the specific language governing permissions 11 * and limitations under the License. 12 * 13 * When distributing Covered Code, include this CDDL HEADER in each 14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE. 15 * If applicable, add the following below this CDDL HEADER, with the 16 * fields enclosed by brackets "[]" replaced with your own identifying 17 * information: Portions Copyright [yyyy] [name of copyright owner] 18 * 19 * CDDL HEADER END 20 */ 21 22 /* 23 * Copyright 2007 Sun Microsystems, Inc. All rights reserved. 24 * Use is subject to license terms. 25 */ 26 27 /* Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T */ 28 /* All Rights Reserved */ 29 30 /* 31 * Portions of this source code were derived from Berkeley 4.3 BSD 32 * under license from the Regents of the University of California. 33 */ 34 35 #pragma ident "@(#)poll.c 1.133 07/10/25 SMI" 36 37 #include <sys/param.h> 38 #include <sys/isa_defs.h> 39 #include <sys/types.h> 40 #include <sys/sysmacros.h> 41 #include <sys/user.h> 42 #include <sys/systm.h> 43 #include <sys/errno.h> 44 #include <sys/time.h> 45 #include <sys/vnode.h> 46 #include <sys/file.h> 47 #include <sys/mode.h> 48 #include <sys/proc.h> 49 #include <sys/uio.h> 50 #include <sys/poll_impl.h> 51 #include <sys/kmem.h> 52 #include <sys/cmn_err.h> 53 #include <sys/debug.h> 54 #include <sys/bitmap.h> 55 #include <sys/kstat.h> 56 #include <sys/rctl.h> 57 #include <sys/port_impl.h> 58 #include <sys/schedctl.h> 59 60 #define NPHLOCKS 64 /* Number of locks; must be power of 2 */ 61 #define PHLOCKADDR(php) &plocks[(((uintptr_t)(php)) >> 8) & (NPHLOCKS - 1)] 62 #define PHLOCK(php) PHLOCKADDR(php).pp_lock 63 #define PH_ENTER(php) mutex_enter(PHLOCK(php)) 64 #define PH_EXIT(php) mutex_exit(PHLOCK(php)) 65 #define VALID_POLL_EVENTS (POLLIN | POLLPRI | POLLOUT | POLLRDNORM \ 66 | POLLRDBAND | POLLWRBAND | POLLHUP | POLLERR | POLLNVAL) 67 68 /* 69 * global counters to collect some stats 70 */ 71 static struct { 72 kstat_named_t polllistmiss; /* failed to find a cached poll list */ 73 kstat_named_t pollcachehit; /* list matched 100% w/ cached one */ 74 kstat_named_t pollcachephit; /* list matched < 100% w/ cached one */ 75 kstat_named_t pollcachemiss; /* every list entry is dif from cache */ 76 } pollstats = { 77 { "polllistmiss", KSTAT_DATA_UINT64 }, 78 { "pollcachehit", KSTAT_DATA_UINT64 }, 79 { "pollcachephit", KSTAT_DATA_UINT64 }, 80 { "pollcachemiss", KSTAT_DATA_UINT64 } 81 }; 82 83 kstat_named_t *pollstats_ptr = (kstat_named_t *)&pollstats; 84 uint_t pollstats_ndata = sizeof (pollstats) / sizeof (kstat_named_t); 85 86 struct pplock { 87 kmutex_t pp_lock; 88 short pp_flag; 89 kcondvar_t pp_wait_cv; 90 int32_t pp_pad; /* to a nice round 16 bytes */ 91 }; 92 93 static struct pplock plocks[NPHLOCKS]; /* Hash array of pollhead locks */ 94 95 #ifdef DEBUG 96 static int pollchecksanity(pollstate_t *, nfds_t); 97 static int pollcheckxref(pollstate_t *, int); 98 static void pollcheckphlist(void); 99 static int pollcheckrevents(pollstate_t *, int, int, int); 100 static void checkpolldat(pollstate_t *); 101 #endif /* DEBUG */ 102 static int plist_chkdupfd(file_t *, polldat_t *, pollstate_t *, pollfd_t *, int, 103 int *); 104 105 /* 106 * Data structure overview: 107 * The per-thread poll state consists of 108 * one pollstate_t 109 * one pollcache_t 110 * one bitmap with one event bit per fd 111 * a (two-dimensional) hashed array of polldat_t structures - one entry 112 * per fd 113 * 114 * This conglomerate of data structures interact with 115 * the pollhead which is used by VOP_POLL and pollwakeup 116 * (protected by the PHLOCK, cached array of plocks), and 117 * the fpollinfo list hanging off the fi_list which is used to notify 118 * poll when a cached fd is closed. This is protected by uf_lock. 119 * 120 * Invariants: 121 * pd_php (pollhead pointer) is set iff (if and only if) the polldat 122 * is on that pollhead. This is modified atomically under pc_lock. 123 * 124 * pd_fp (file_t pointer) is set iff the thread is on the fpollinfo 125 * list for that open file. 126 * This is modified atomically under pc_lock. 127 * 128 * pd_count is the sum (over all values of i) of pd_ref[i].xf_refcnt. 129 * Iff pd_ref[i].xf_refcnt >= 1 then 130 * ps_pcacheset[i].pcs_pollfd[pd_ref[i].xf_position].fd == pd_fd 131 * Iff pd_ref[i].xf_refcnt > 1 then 132 * In ps_pcacheset[i].pcs_pollfd between index 133 * pd_ref[i].xf_position] and the end of the list 134 * there are xf_refcnt entries with .fd == pd_fd 135 * 136 * Locking design: 137 * Whenever possible the design relies on the fact that the poll cache state 138 * is per thread thus for both poll and exit it is self-synchronizing. 139 * Thus the key interactions where other threads access the state are: 140 * pollwakeup (and polltime), and 141 * close cleaning up the cached references to an open file 142 * 143 * The two key locks in poll proper is ps_lock and pc_lock. 144 * 145 * The ps_lock is used for synchronization between poll, (lwp_)exit and close 146 * to ensure that modifications to pollcacheset structure are serialized. 147 * This lock is held through most of poll() except where poll sleeps 148 * since there is little need to handle closes concurrently with the execution 149 * of poll. 150 * The pc_lock protects most of the fields in pollcache structure and polldat 151 * structures (which are accessed by poll, pollwakeup, and polltime) 152 * with the exception of fields that are only modified when only one thread 153 * can access this per-thread state. 154 * Those exceptions occur in poll when first allocating the per-thread state, 155 * when poll grows the number of polldat (never shrinks), and when 156 * exit/pollcleanup has ensured that there are no references from either 157 * pollheads or fpollinfo to the threads poll state. 158 * 159 * Poll(2) system call is the only path which ps_lock and pc_lock are both 160 * held, in that order. It needs ps_lock to synchronize with close and 161 * lwp_exit; and pc_lock with pollwakeup. 162 * 163 * The locking interaction between pc_lock and PHLOCK take into account 164 * that poll acquires these locks in the order of pc_lock and then PHLOCK 165 * while pollwakeup does it in the reverse order. Thus pollwakeup implements 166 * deadlock avoidance by dropping the locks and reacquiring them in the 167 * reverse order. For this to work pollwakeup needs to prevent the thread 168 * from exiting and freeing all of the poll related state. Thus is done 169 * using 170 * the pc_no_exit lock 171 * the pc_busy counter 172 * the pc_busy_cv condition variable 173 * 174 * The locking interaction between pc_lock and uf_lock has similar 175 * issues. Poll holds ps_lock and/or pc_lock across calls to getf/releasef 176 * which acquire uf_lock. The poll cleanup in close needs to hold uf_lock 177 * to prevent poll or exit from doing a delfpollinfo after which the thread 178 * might exit. But the cleanup needs to acquire pc_lock when modifying 179 * the poll cache state. The solution is to use pc_busy and do the close 180 * cleanup in two phases: 181 * First close calls pollblockexit which increments pc_busy. 182 * This prevents the per-thread poll related state from being freed. 183 * Then close drops uf_lock and calls pollcacheclean. 184 * This routine can then acquire pc_lock and remove any references 185 * to the closing fd (as well as recording that it has been closed 186 * so that a POLLNVAL can be generated even if the fd is reused before 187 * poll has been woken up and checked getf() again). 188 * 189 * When removing a polled fd from poll cache, the fd is always removed 190 * from pollhead list first and then from fpollinfo list, i.e., 191 * pollhead_delete() is called before delfpollinfo(). 192 * 193 * 194 * Locking hierarchy: 195 * pc_no_exit is a leaf level lock. 196 * ps_lock is held when acquiring pc_lock (except when pollwakeup 197 * acquires pc_lock). 198 * pc_lock might be held when acquiring PHLOCK (pollhead_insert/ 199 * pollhead_delete) 200 * pc_lock is always held (but this is not required) 201 * when acquiring PHLOCK (in polladd/pollhead_delete and pollwakeup called 202 * from pcache_clean_entry). 203 * pc_lock is held across addfpollinfo/delfpollinfo which acquire 204 * uf_lock. 205 * pc_lock is held across getf/releasef which acquire uf_lock. 206 * ps_lock might be held across getf/releasef which acquire uf_lock. 207 * pollwakeup tries to acquire pc_lock while holding PHLOCK 208 * but drops the locks and reacquire them in reverse order to avoid 209 * deadlock. 210 * 211 * Note also that there is deadlock avoidance support for VOP_POLL routines 212 * and pollwakeup involving a file system or driver lock. 213 * See below. 214 */ 215 216 /* 217 * Deadlock avoidance support for VOP_POLL() routines. This is 218 * sometimes necessary to prevent deadlock between polling threads 219 * (which hold poll locks on entry to xx_poll(), then acquire foo) 220 * and pollwakeup() threads (which hold foo, then acquire poll locks). 221 * 222 * pollunlock(void) releases whatever poll locks the current thread holds, 223 * returning a cookie for use by pollrelock(); 224 * 225 * pollrelock(cookie) reacquires previously dropped poll locks; 226 * 227 * polllock(php, mutex) does the common case: pollunlock(), 228 * acquire the problematic mutex, pollrelock(). 229 */ 230 int 231 pollunlock(void) 232 { 233 pollcache_t *pcp; 234 int lockstate = 0; 235 236 /* 237 * t_pollcache is set by /dev/poll and event ports (port_fd.c). 238 * If the pollrelock/pollunlock is called as a result of poll(2), 239 * the t_pollcache should be NULL. 240 */ 241 if (curthread->t_pollcache == NULL) 242 pcp = curthread->t_pollstate->ps_pcache; 243 else 244 pcp = curthread->t_pollcache; 245 246 if (mutex_owned(&pcp->pc_lock)) { 247 lockstate = 1; 248 mutex_exit(&pcp->pc_lock); 249 } 250 return (lockstate); 251 } 252 253 void 254 pollrelock(int lockstate) 255 { 256 pollcache_t *pcp; 257 258 /* 259 * t_pollcache is set by /dev/poll and event ports (port_fd.c). 260 * If the pollrelock/pollunlock is called as a result of poll(2), 261 * the t_pollcache should be NULL. 262 */ 263 if (curthread->t_pollcache == NULL) 264 pcp = curthread->t_pollstate->ps_pcache; 265 else 266 pcp = curthread->t_pollcache; 267 268 if (lockstate > 0) 269 mutex_enter(&pcp->pc_lock); 270 } 271 272 /* ARGSUSED */ 273 void 274 polllock(pollhead_t *php, kmutex_t *lp) 275 { 276 if (!mutex_tryenter(lp)) { 277 int lockstate = pollunlock(); 278 mutex_enter(lp); 279 pollrelock(lockstate); 280 } 281 } 282 283 static int 284 poll_common(pollfd_t *fds, nfds_t nfds, timespec_t *tsp, k_sigset_t *ksetp) 285 { 286 kthread_t *t = curthread; 287 klwp_t *lwp = ttolwp(t); 288 proc_t *p = ttoproc(t); 289 int fdcnt = 0; 290 int rval; 291 int i; 292 timespec_t *rqtp = NULL; 293 int timecheck = 0; 294 int imm_timeout = 0; 295 pollfd_t *pollfdp; 296 pollstate_t *ps; 297 pollcache_t *pcp; 298 int error = 0; 299 nfds_t old_nfds; 300 int cacheindex = 0; /* which cache set is used */ 301 302 /* 303 * Determine the precise future time of the requested timeout, if any. 304 */ 305 if (tsp != NULL) { 306 if (tsp->tv_sec == 0 && tsp->tv_nsec == 0) 307 imm_timeout = 1; 308 else { 309 timespec_t now; 310 timecheck = timechanged; 311 gethrestime(&now); 312 rqtp = tsp; 313 timespecadd(rqtp, &now); 314 } 315 } 316 317 /* 318 * Reset our signal mask, if requested. 319 */ 320 if (ksetp != NULL) { 321 mutex_enter(&p->p_lock); 322 schedctl_finish_sigblock(t); 323 lwp->lwp_sigoldmask = t->t_hold; 324 t->t_hold = *ksetp; 325 t->t_flag |= T_TOMASK; 326 /* 327 * Call cv_timedwait_sig() just to check for signals. 328 * We will return immediately with either 0 or -1. 329 */ 330 if (!cv_timedwait_sig(&t->t_delay_cv, &p->p_lock, lbolt)) { 331 mutex_exit(&p->p_lock); 332 error = EINTR; 333 goto pollout; 334 } 335 mutex_exit(&p->p_lock); 336 } 337 338 /* 339 * Check to see if this guy just wants to use poll() as a timeout. 340 * If yes then bypass all the other stuff and make him sleep. 341 */ 342 if (nfds == 0) { 343 /* 344 * Sleep until we have passed the requested future 345 * time or until interrupted by a signal. 346 * Do not check for signals if we have a zero timeout. 347 */ 348 if (!imm_timeout) { 349 mutex_enter(&t->t_delay_lock); 350 while ((rval = cv_waituntil_sig(&t->t_delay_cv, 351 &t->t_delay_lock, rqtp, timecheck)) > 0) 352 continue; 353 mutex_exit(&t->t_delay_lock); 354 if (rval == 0) 355 error = EINTR; 356 } 357 goto pollout; 358 } 359 360 if (nfds > p->p_fno_ctl) { 361 mutex_enter(&p->p_lock); 362 (void) rctl_action(rctlproc_legacy[RLIMIT_NOFILE], 363 p->p_rctls, p, RCA_SAFE); 364 mutex_exit(&p->p_lock); 365 error = EINVAL; 366 goto pollout; 367 } 368 369 /* 370 * Need to allocate memory for pollstate before anything because 371 * the mutex and cv are created in this space 372 */ 373 if ((ps = t->t_pollstate) == NULL) { 374 t->t_pollstate = pollstate_create(); 375 ps = t->t_pollstate; 376 } 377 378 if (ps->ps_pcache == NULL) 379 ps->ps_pcache = pcache_alloc(); 380 pcp = ps->ps_pcache; 381 382 /* 383 * NOTE: for performance, buffers are saved across poll() calls. 384 * The theory is that if a process polls heavily, it tends to poll 385 * on the same set of descriptors. Therefore, we only reallocate 386 * buffers when nfds changes. There is no hysteresis control, 387 * because there is no data to suggest that this is necessary; 388 * the penalty of reallocating is not *that* great in any event. 389 */ 390 old_nfds = ps->ps_nfds; 391 if (nfds != old_nfds) { 392 393 kmem_free(ps->ps_pollfd, old_nfds * sizeof (pollfd_t)); 394 pollfdp = kmem_alloc(nfds * sizeof (pollfd_t), KM_SLEEP); 395 ps->ps_pollfd = pollfdp; 396 ps->ps_nfds = nfds; 397 } 398 399 pollfdp = ps->ps_pollfd; 400 if (copyin(fds, pollfdp, nfds * sizeof (pollfd_t))) { 401 error = EFAULT; 402 goto pollout; 403 } 404 405 if (fds == NULL) { 406 /* 407 * If the process has page 0 mapped, then the copyin() above 408 * will succeed even if fds is NULL. However, our cached 409 * poll lists are keyed by the address of the passed-in fds 410 * structure, and we use the value NULL to indicate an unused 411 * poll cache list entry. As such, we elect not to support 412 * NULL as a valid (user) memory address and fail the poll() 413 * call. 414 */ 415 error = EINVAL; 416 goto pollout; 417 } 418 419 /* 420 * If this thread polls for the first time, allocate ALL poll 421 * cache data structures and cache the poll fd list. This 422 * allocation is delayed till now because lwp's polling 0 fd 423 * (i.e. using poll as timeout()) don't need this memory. 424 */ 425 mutex_enter(&ps->ps_lock); 426 pcp = ps->ps_pcache; 427 ASSERT(pcp != NULL); 428 if (pcp->pc_bitmap == NULL) { 429 pcache_create(pcp, nfds); 430 /* 431 * poll and cache this poll fd list in ps_pcacheset[0]. 432 */ 433 error = pcacheset_cache_list(ps, fds, &fdcnt, cacheindex); 434 if (fdcnt || error) { 435 mutex_exit(&ps->ps_lock); 436 goto pollout; 437 } 438 } else { 439 pollcacheset_t *pcset = ps->ps_pcacheset; 440 441 /* 442 * Not first time polling. Select a cached poll list by 443 * matching user pollfd list buffer address. 444 */ 445 for (cacheindex = 0; cacheindex < ps->ps_nsets; cacheindex++) { 446 if (pcset[cacheindex].pcs_usradr == (uintptr_t)fds) { 447 if ((++pcset[cacheindex].pcs_count) == 0) { 448 /* 449 * counter is wrapping around. 450 */ 451 pcacheset_reset_count(ps, cacheindex); 452 } 453 /* 454 * examine and resolve possible 455 * difference of the current poll 456 * list and previously cached one. 457 * If there is an error during resolve(), 458 * the callee will guarantee the consistency 459 * of cached poll list and cache content. 460 */ 461 error = pcacheset_resolve(ps, nfds, &fdcnt, 462 cacheindex); 463 if (error) { 464 mutex_exit(&ps->ps_lock); 465 goto pollout; 466 } 467 break; 468 } 469 470 /* 471 * Note that pcs_usradr field of an used entry won't be 472 * NULL because it stores the address of passed-in fds, 473 * and NULL fds will not be cached (Then it is either 474 * the special timeout case when nfds is 0 or it returns 475 * failure directly). 476 */ 477 if (pcset[cacheindex].pcs_usradr == NULL) { 478 /* 479 * found an unused entry. Use it to cache 480 * this poll list. 481 */ 482 error = pcacheset_cache_list(ps, fds, &fdcnt, 483 cacheindex); 484 if (fdcnt || error) { 485 mutex_exit(&ps->ps_lock); 486 goto pollout; 487 } 488 break; 489 } 490 } 491 if (cacheindex == ps->ps_nsets) { 492 /* 493 * We failed to find a matching cached poll fd list. 494 * replace an old list. 495 */ 496 pollstats.polllistmiss.value.ui64++; 497 cacheindex = pcacheset_replace(ps); 498 ASSERT(cacheindex < ps->ps_nsets); 499 pcset[cacheindex].pcs_usradr = (uintptr_t)fds; 500 error = pcacheset_resolve(ps, nfds, &fdcnt, cacheindex); 501 if (error) { 502 mutex_exit(&ps->ps_lock); 503 goto pollout; 504 } 505 } 506 } 507 508 /* 509 * Always scan the bitmap with the lock on the pollcache held. 510 * This is to make sure that a wakeup does not come undetected. 511 * If the lock is not held, a pollwakeup could have come for an 512 * fd we already checked but before this thread sleeps, in which 513 * case the wakeup is missed. Now we hold the pcache lock and 514 * check the bitmap again. This will prevent wakeup from happening 515 * while we hold pcache lock since pollwakeup() will also lock 516 * the pcache before updating poll bitmap. 517 */ 518 mutex_enter(&pcp->pc_lock); 519 for (;;) { 520 pcp->pc_flag = 0; 521 error = pcache_poll(pollfdp, ps, nfds, &fdcnt, cacheindex); 522 if (fdcnt || error) { 523 mutex_exit(&pcp->pc_lock); 524 mutex_exit(&ps->ps_lock); 525 break; 526 } 527 528 /* 529 * If T_POLLWAKE is set, a pollwakeup() was performed on 530 * one of the file descriptors. This can happen only if 531 * one of the VOP_POLL() functions dropped pcp->pc_lock. 532 * The only current cases of this is in procfs (prpoll()) 533 * and STREAMS (strpoll()). 534 */ 535 if (pcp->pc_flag & T_POLLWAKE) 536 continue; 537 538 /* 539 * If you get here, the poll of fds was unsuccessful. 540 * Wait until some fd becomes readable, writable, or gets 541 * an exception, or until a signal or a timeout occurs. 542 * Do not check for signals if we have a zero timeout. 543 */ 544 mutex_exit(&ps->ps_lock); 545 if (imm_timeout) 546 rval = -1; 547 else 548 rval = cv_waituntil_sig(&pcp->pc_cv, &pcp->pc_lock, 549 rqtp, timecheck); 550 mutex_exit(&pcp->pc_lock); 551 /* 552 * If we have received a signal or timed out 553 * then break out and return. 554 */ 555 if (rval <= 0) { 556 if (rval == 0) 557 error = EINTR; 558 break; 559 } 560 /* 561 * We have not received a signal or timed out. 562 * Continue around and poll fds again. 563 */ 564 mutex_enter(&ps->ps_lock); 565 mutex_enter(&pcp->pc_lock); 566 } 567 568 pollout: 569 /* 570 * If we changed the signal mask but we received 571 * no signal then restore the signal mask. 572 * Otherwise psig() will deal with the signal mask. 573 */ 574 if (ksetp != NULL) { 575 mutex_enter(&p->p_lock); 576 if (lwp->lwp_cursig == 0) { 577 t->t_hold = lwp->lwp_sigoldmask; 578 t->t_flag &= ~T_TOMASK; 579 } 580 mutex_exit(&p->p_lock); 581 } 582 583 if (error) 584 return (set_errno(error)); 585 586 /* 587 * Copy out the events and return the fdcnt to the user. 588 */ 589 if (nfds != 0 && 590 copyout(pollfdp, fds, nfds * sizeof (pollfd_t))) 591 return (set_errno(EFAULT)); 592 593 #ifdef DEBUG 594 /* 595 * Another sanity check: 596 */ 597 if (fdcnt) { 598 int reventcnt = 0; 599 600 for (i = 0; i < nfds; i++) { 601 if (pollfdp[i].fd < 0) { 602 ASSERT(pollfdp[i].revents == 0); 603 continue; 604 } 605 if (pollfdp[i].revents) { 606 reventcnt++; 607 } 608 } 609 ASSERT(fdcnt == reventcnt); 610 } else { 611 for (i = 0; i < nfds; i++) { 612 ASSERT(pollfdp[i].revents == 0); 613 } 614 } 615 #endif /* DEBUG */ 616 617 return (fdcnt); 618 } 619 620 /* 621 * This system call trap exists solely for binary compatibility with 622 * old statically-linked applications. It is not called from libc. 623 * It should be removed in the next release. 624 */ 625 int 626 poll(pollfd_t *fds, nfds_t nfds, int time_out) 627 { 628 timespec_t ts; 629 timespec_t *tsp; 630 631 if (time_out < 0) 632 tsp = NULL; 633 else { 634 ts.tv_sec = time_out / MILLISEC; 635 ts.tv_nsec = (time_out % MILLISEC) * MICROSEC; 636 tsp = &ts; 637 } 638 639 return (poll_common(fds, nfds, tsp, NULL)); 640 } 641 642 /* 643 * This is the system call trap that poll(), 644 * select() and pselect() are built upon. 645 * It is a private interface between libc and the kernel. 646 */ 647 int 648 pollsys(pollfd_t *fds, nfds_t nfds, timespec_t *timeoutp, sigset_t *setp) 649 { 650 timespec_t ts; 651 timespec_t *tsp; 652 sigset_t set; 653 k_sigset_t kset; 654 k_sigset_t *ksetp; 655 model_t datamodel = get_udatamodel(); 656 657 if (timeoutp == NULL) 658 tsp = NULL; 659 else { 660 if (datamodel == DATAMODEL_NATIVE) { 661 if (copyin(timeoutp, &ts, sizeof (ts))) 662 return (set_errno(EFAULT)); 663 } else { 664 timespec32_t ts32; 665 666 if (copyin(timeoutp, &ts32, sizeof (ts32))) 667 return (set_errno(EFAULT)); 668 TIMESPEC32_TO_TIMESPEC(&ts, &ts32) 669 } 670 671 if (itimerspecfix(&ts)) 672 return (set_errno(EINVAL)); 673 tsp = &ts; 674 } 675 676 if (setp == NULL) 677 ksetp = NULL; 678 else { 679 if (copyin(setp, &set, sizeof (set))) 680 return (set_errno(EFAULT)); 681 sigutok(&set, &kset); 682 ksetp = &kset; 683 } 684 685 return (poll_common(fds, nfds, tsp, ksetp)); 686 } 687 688 /* 689 * Clean up any state left around by poll(2). Called when a thread exits. 690 */ 691 void 692 pollcleanup() 693 { 694 pollstate_t *ps = curthread->t_pollstate; 695 pollcache_t *pcp; 696 697 if (ps == NULL) 698 return; 699 pcp = ps->ps_pcache; 700 /* 701 * free up all cached poll fds 702 */ 703 if (pcp == NULL) { 704 /* this pollstate is used by /dev/poll */ 705 goto pollcleanout; 706 } 707 708 if (pcp->pc_bitmap != NULL) { 709 ASSERT(MUTEX_NOT_HELD(&ps->ps_lock)); 710 /* 711 * a close lwp can race with us when cleaning up a polldat 712 * entry. We hold the ps_lock when cleaning hash table. 713 * Since this pollcache is going away anyway, there is no 714 * need to hold the pc_lock. 715 */ 716 mutex_enter(&ps->ps_lock); 717 pcache_clean(pcp); 718 mutex_exit(&ps->ps_lock); 719 #ifdef DEBUG 720 /* 721 * At this point, all fds cached by this lwp should be 722 * cleaned up. There should be no fd in fi_list still 723 * reference this thread. 724 */ 725 checkfpollinfo(); /* sanity check */ 726 pollcheckphlist(); /* sanity check */ 727 #endif /* DEBUG */ 728 } 729 /* 730 * Be sure no one is referencing thread before exiting 731 */ 732 mutex_enter(&pcp->pc_no_exit); 733 ASSERT(pcp->pc_busy >= 0); 734 while (pcp->pc_busy > 0) 735 cv_wait(&pcp->pc_busy_cv, &pcp->pc_no_exit); 736 mutex_exit(&pcp->pc_no_exit); 737 pollcleanout: 738 pollstate_destroy(ps); 739 curthread->t_pollstate = NULL; 740 } 741 742 /* 743 * pollwakeup() - poke threads waiting in poll() for some event 744 * on a particular object. 745 * 746 * The threads hanging off of the specified pollhead structure are scanned. 747 * If their event mask matches the specified event(s), then pollnotify() is 748 * called to poke the thread. 749 * 750 * Multiple events may be specified. When POLLHUP or POLLERR are specified, 751 * all waiting threads are poked. 752 * 753 * It is important that pollnotify() not drop the lock protecting the list 754 * of threads. 755 */ 756 void 757 pollwakeup(pollhead_t *php, short events_arg) 758 { 759 polldat_t *pdp; 760 int events = (ushort_t)events_arg; 761 struct plist { 762 port_t *pp; 763 int pevents; 764 struct plist *next; 765 }; 766 struct plist *plhead = NULL, *pltail = NULL; 767 768 retry: 769 PH_ENTER(php); 770 771 for (pdp = php->ph_list; pdp; pdp = pdp->pd_next) { 772 if ((pdp->pd_events & events) || 773 (events & (POLLHUP | POLLERR))) { 774 775 pollcache_t *pcp; 776 777 if (pdp->pd_portev != NULL) { 778 port_kevent_t *pkevp = pdp->pd_portev; 779 /* 780 * Object (fd) is associated with an event port, 781 * => send event notification to the port. 782 */ 783 ASSERT(pkevp->portkev_source == PORT_SOURCE_FD); 784 mutex_enter(&pkevp->portkev_lock); 785 if (pkevp->portkev_flags & PORT_KEV_VALID) { 786 int pevents; 787 788 pkevp->portkev_flags &= ~PORT_KEV_VALID; 789 pkevp->portkev_events |= events & 790 (pdp->pd_events | POLLHUP | 791 POLLERR); 792 /* 793 * portkev_lock mutex will be released 794 * by port_send_event(). 795 */ 796 port_send_event(pkevp); 797 798 /* 799 * If we have some thread polling the 800 * port's fd, add it to the list. They 801 * will be notified later. 802 * The port_pollwkup() will flag the 803 * port_t so that it will not disappear 804 * till port_pollwkdone() is called. 805 */ 806 pevents = 807 port_pollwkup(pkevp->portkev_port); 808 if (pevents) { 809 struct plist *t; 810 t = kmem_zalloc( 811 sizeof (struct plist), 812 KM_SLEEP); 813 t->pp = pkevp->portkev_port; 814 t->pevents = pevents; 815 if (plhead == NULL) { 816 plhead = t; 817 } else { 818 pltail->next = t; 819 } 820 pltail = t; 821 } 822 } else { 823 mutex_exit(&pkevp->portkev_lock); 824 } 825 continue; 826 } 827 828 pcp = pdp->pd_pcache; 829 830 /* 831 * Try to grab the lock for this thread. If 832 * we don't get it then we may deadlock so 833 * back out and restart all over again. Note 834 * that the failure rate is very very low. 835 */ 836 if (mutex_tryenter(&pcp->pc_lock)) { 837 pollnotify(pcp, pdp->pd_fd); 838 mutex_exit(&pcp->pc_lock); 839 } else { 840 /* 841 * We are here because: 842 * 1) This thread has been woke up 843 * and is trying to get out of poll(). 844 * 2) Some other thread is also here 845 * but with a different pollhead lock. 846 * 847 * So, we need to drop the lock on pollhead 848 * because of (1) but we want to prevent 849 * that thread from doing lwp_exit() or 850 * devpoll close. We want to ensure that 851 * the pollcache pointer is still invalid. 852 * 853 * Solution: Grab the pcp->pc_no_exit lock, 854 * increment the pc_busy counter, drop every 855 * lock in sight. Get out of the way and wait 856 * for type (2) threads to finish. 857 */ 858 859 mutex_enter(&pcp->pc_no_exit); 860 pcp->pc_busy++; /* prevents exit()'s */ 861 mutex_exit(&pcp->pc_no_exit); 862 863 PH_EXIT(php); 864 mutex_enter(&pcp->pc_lock); 865 mutex_exit(&pcp->pc_lock); 866 mutex_enter(&pcp->pc_no_exit); 867 pcp->pc_busy--; 868 if (pcp->pc_busy == 0) { 869 /* 870 * Wakeup the thread waiting in 871 * thread_exit(). 872 */ 873 cv_signal(&pcp->pc_busy_cv); 874 } 875 mutex_exit(&pcp->pc_no_exit); 876 goto retry; 877 } 878 } 879 } 880 881 882 /* 883 * Event ports - If this php is of the port on the list, 884 * call port_pollwkdone() to release it. The port_pollwkdone() 885 * needs to be called before dropping the PH lock so that any new 886 * thread attempting to poll this port are blocked. There can be 887 * only one thread here in pollwakeup notifying this port's fd. 888 */ 889 if (plhead != NULL && &plhead->pp->port_pollhd == php) { 890 struct plist *t; 891 port_pollwkdone(plhead->pp); 892 t = plhead; 893 plhead = plhead->next; 894 kmem_free(t, sizeof (struct plist)); 895 } 896 PH_EXIT(php); 897 898 /* 899 * Event ports - Notify threads polling the event port's fd. 900 * This is normally done in port_send_event() where it calls 901 * pollwakeup() on the port. But, for PORT_SOURCE_FD source alone, 902 * we do it here in pollwakeup() to avoid a recursive call. 903 */ 904 if (plhead != NULL) { 905 php = &plhead->pp->port_pollhd; 906 events = plhead->pevents; 907 goto retry; 908 } 909 } 910 911 /* 912 * This function is called to inform a thread that 913 * an event being polled for has occurred. 914 * The pollstate lock on the thread should be held on entry. 915 */ 916 void 917 pollnotify(pollcache_t *pcp, int fd) 918 { 919 ASSERT(fd < pcp->pc_mapsize); 920 ASSERT(MUTEX_HELD(&pcp->pc_lock)); 921 BT_SET(pcp->pc_bitmap, fd); 922 pcp->pc_flag |= T_POLLWAKE; 923 cv_signal(&pcp->pc_cv); 924 } 925 926 /* 927 * add a polldat entry to pollhead ph_list. The polldat struct is used 928 * by pollwakeup to wake sleeping pollers when polled events has happened. 929 */ 930 void 931 pollhead_insert(pollhead_t *php, polldat_t *pdp) 932 { 933 PH_ENTER(php); 934 ASSERT(pdp->pd_next == NULL); 935 #ifdef DEBUG 936 { 937 /* 938 * the polldat should not be already on the list 939 */ 940 polldat_t *wp; 941 for (wp = php->ph_list; wp; wp = wp->pd_next) { 942 ASSERT(wp != pdp); 943 } 944 } 945 #endif /* DEBUG */ 946 pdp->pd_next = php->ph_list; 947 php->ph_list = pdp; 948 PH_EXIT(php); 949 } 950 951 /* 952 * Delete the polldat entry from ph_list. 953 */ 954 void 955 pollhead_delete(pollhead_t *php, polldat_t *pdp) 956 { 957 polldat_t *wp; 958 polldat_t **wpp; 959 960 PH_ENTER(php); 961 for (wpp = &php->ph_list; (wp = *wpp) != NULL; wpp = &wp->pd_next) { 962 if (wp == pdp) { 963 *wpp = pdp->pd_next; 964 pdp->pd_next = NULL; 965 break; 966 } 967 } 968 #ifdef DEBUG 969 /* assert that pdp is no longer in the list */ 970 for (wp = *wpp; wp; wp = wp->pd_next) { 971 ASSERT(wp != pdp); 972 } 973 #endif /* DEBUG */ 974 PH_EXIT(php); 975 } 976 977 /* 978 * walk through the poll fd lists to see if they are identical. This is an 979 * expensive operation and should not be done more than once for each poll() 980 * call. 981 * 982 * As an optimization (i.e., not having to go through the lists more than 983 * once), this routine also clear the revents field of pollfd in 'current'. 984 * Zeroing out the revents field of each entry in current poll list is 985 * required by poll man page. 986 * 987 * Since the events field of cached list has illegal poll events filtered 988 * out, the current list applies the same filtering before comparison. 989 * 990 * The routine stops when it detects a meaningful difference, or when it 991 * exhausts the lists. 992 */ 993 int 994 pcacheset_cmp(pollfd_t *current, pollfd_t *cached, pollfd_t *newlist, int n) 995 { 996 int ix; 997 998 for (ix = 0; ix < n; ix++) { 999 if (current[ix].fd == cached[ix].fd) { 1000 /* 1001 * Filter out invalid poll events while we are in 1002 * inside the loop. 1003 */ 1004 if (current[ix].events & ~VALID_POLL_EVENTS) { 1005 current[ix].events &= VALID_POLL_EVENTS; 1006 if (newlist != NULL) 1007 newlist[ix].events = current[ix].events; 1008 } 1009 if (current[ix].events == cached[ix].events) { 1010 current[ix].revents = 0; 1011 continue; 1012 } 1013 } 1014 if ((current[ix].fd < 0) && (cached[ix].fd < 0)) { 1015 current[ix].revents = 0; 1016 continue; 1017 } 1018 return (ix); 1019 } 1020 return (ix); 1021 } 1022 1023 /* 1024 * This routine returns a pointer to a cached poll fd entry, or NULL if it 1025 * does not find it in the hash table. 1026 */ 1027 polldat_t * 1028 pcache_lookup_fd(pollcache_t *pcp, int fd) 1029 { 1030 int hashindex; 1031 polldat_t *pdp; 1032 1033 hashindex = POLLHASH(pcp->pc_hashsize, fd); 1034 pdp = pcp->pc_hash[hashindex]; 1035 while (pdp != NULL) { 1036 if (pdp->pd_fd == fd) 1037 break; 1038 pdp = pdp->pd_hashnext; 1039 } 1040 return (pdp); 1041 } 1042 1043 polldat_t * 1044 pcache_alloc_fd(int nsets) 1045 { 1046 polldat_t *pdp; 1047 1048 pdp = kmem_zalloc(sizeof (polldat_t), KM_SLEEP); 1049 if (nsets > 0) { 1050 pdp->pd_ref = kmem_zalloc(sizeof (xref_t) * nsets, KM_SLEEP); 1051 pdp->pd_nsets = nsets; 1052 } 1053 return (pdp); 1054 } 1055 1056 /* 1057 * This routine inserts a polldat into the pollcache's hash table. It 1058 * may be necessary to grow the size of the hash table. 1059 */ 1060 void 1061 pcache_insert_fd(pollcache_t *pcp, polldat_t *pdp, nfds_t nfds) 1062 { 1063 int hashindex; 1064 int fd; 1065 1066 if ((pcp->pc_fdcount > pcp->pc_hashsize * POLLHASHTHRESHOLD) || 1067 (nfds > pcp->pc_hashsize * POLLHASHTHRESHOLD)) { 1068 pcache_grow_hashtbl(pcp, nfds); 1069 } 1070 fd = pdp->pd_fd; 1071 hashindex = POLLHASH(pcp->pc_hashsize, fd); 1072 pdp->pd_hashnext = pcp->pc_hash[hashindex]; 1073 pcp->pc_hash[hashindex] = pdp; 1074 pcp->pc_fdcount++; 1075 1076 #ifdef DEBUG 1077 { 1078 /* 1079 * same fd should not appear on a hash list twice 1080 */ 1081 polldat_t *pdp1; 1082 for (pdp1 = pdp->pd_hashnext; pdp1; pdp1 = pdp1->pd_hashnext) { 1083 ASSERT(pdp->pd_fd != pdp1->pd_fd); 1084 } 1085 } 1086 #endif /* DEBUG */ 1087 } 1088 1089 /* 1090 * Grow the hash table -- either double the table size or round it to the 1091 * nearest multiples of POLLHASHCHUNKSZ, whichever is bigger. Rehash all the 1092 * elements on the hash table. 1093 */ 1094 void 1095 pcache_grow_hashtbl(pollcache_t *pcp, nfds_t nfds) 1096 { 1097 int oldsize; 1098 polldat_t **oldtbl; 1099 polldat_t *pdp, *pdp1; 1100 int i; 1101 #ifdef DEBUG 1102 int count = 0; 1103 #endif 1104 1105 ASSERT(pcp->pc_hashsize % POLLHASHCHUNKSZ == 0); 1106 oldsize = pcp->pc_hashsize; 1107 oldtbl = pcp->pc_hash; 1108 if (nfds > pcp->pc_hashsize * POLLHASHINC) { 1109 pcp->pc_hashsize = (nfds + POLLHASHCHUNKSZ - 1) & 1110 ~(POLLHASHCHUNKSZ - 1); 1111 } else { 1112 pcp->pc_hashsize = pcp->pc_hashsize * POLLHASHINC; 1113 } 1114 pcp->pc_hash = kmem_zalloc(pcp->pc_hashsize * sizeof (polldat_t *), 1115 KM_SLEEP); 1116 /* 1117 * rehash existing elements 1118 */ 1119 pcp->pc_fdcount = 0; 1120 for (i = 0; i < oldsize; i++) { 1121 pdp = oldtbl[i]; 1122 while (pdp != NULL) { 1123 pdp1 = pdp->pd_hashnext; 1124 pcache_insert_fd(pcp, pdp, nfds); 1125 pdp = pdp1; 1126 #ifdef DEBUG 1127 count++; 1128 #endif 1129 } 1130 } 1131 kmem_free(oldtbl, oldsize * sizeof (polldat_t *)); 1132 ASSERT(pcp->pc_fdcount == count); 1133 } 1134 1135 void 1136 pcache_grow_map(pollcache_t *pcp, int fd) 1137 { 1138 int newsize; 1139 ulong_t *newmap; 1140 1141 /* 1142 * grow to nearest multiple of POLLMAPCHUNK, assuming POLLMAPCHUNK is 1143 * power of 2. 1144 */ 1145 newsize = (fd + POLLMAPCHUNK) & ~(POLLMAPCHUNK - 1); 1146 newmap = kmem_zalloc((newsize / BT_NBIPUL) * sizeof (ulong_t), 1147 KM_SLEEP); 1148 /* 1149 * don't want pollwakeup to set a bit while growing the bitmap. 1150 */ 1151 ASSERT(mutex_owned(&pcp->pc_lock) == 0); 1152 mutex_enter(&pcp->pc_lock); 1153 bcopy(pcp->pc_bitmap, newmap, 1154 (pcp->pc_mapsize / BT_NBIPUL) * sizeof (ulong_t)); 1155 kmem_free(pcp->pc_bitmap, 1156 (pcp->pc_mapsize /BT_NBIPUL) * sizeof (ulong_t)); 1157 pcp->pc_bitmap = newmap; 1158 pcp->pc_mapsize = newsize; 1159 mutex_exit(&pcp->pc_lock); 1160 } 1161 1162 /* 1163 * remove all the reference from pollhead list and fpollinfo lists. 1164 */ 1165 void 1166 pcache_clean(pollcache_t *pcp) 1167 { 1168 int i; 1169 polldat_t **hashtbl; 1170 polldat_t *pdp; 1171 1172 ASSERT(MUTEX_HELD(&curthread->t_pollstate->ps_lock)); 1173 hashtbl = pcp->pc_hash; 1174 for (i = 0; i < pcp->pc_hashsize; i++) { 1175 for (pdp = hashtbl[i]; pdp; pdp = pdp->pd_hashnext) { 1176 if (pdp->pd_php != NULL) { 1177