xref: /titanic_41/usr/src/uts/common/syscall/poll.c (revision cbdcbd056f15c9c9fd82d5543b3a502677c4d391)
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 2009 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 #include <sys/param.h>
36 #include <sys/isa_defs.h>
37 #include <sys/types.h>
38 #include <sys/sysmacros.h>
39 #include <sys/user.h>
40 #include <sys/systm.h>
41 #include <sys/errno.h>
42 #include <sys/time.h>
43 #include <sys/vnode.h>
44 #include <sys/file.h>
45 #include <sys/mode.h>
46 #include <sys/proc.h>
47 #include <sys/uio.h>
48 #include <sys/poll_impl.h>
49 #include <sys/kmem.h>
50 #include <sys/cmn_err.h>
51 #include <sys/debug.h>
52 #include <sys/bitmap.h>
53 #include <sys/kstat.h>
54 #include <sys/rctl.h>
55 #include <sys/port_impl.h>
56 #include <sys/schedctl.h>
57 #include <sys/cpu.h>
58 
59 #define	NPHLOCKS	64	/* Number of locks; must be power of 2 */
60 #define	PHLOCKADDR(php)	&plocks[(((uintptr_t)(php)) >> 8) & (NPHLOCKS - 1)]
61 #define	PHLOCK(php)	PHLOCKADDR(php).pp_lock
62 #define	PH_ENTER(php)	mutex_enter(PHLOCK(php))
63 #define	PH_EXIT(php)	mutex_exit(PHLOCK(php))
64 #define	VALID_POLL_EVENTS	(POLLIN | POLLPRI | POLLOUT | POLLRDNORM \
65 	| POLLRDBAND | POLLWRBAND | POLLHUP | POLLERR | POLLNVAL)
66 
67 /*
68  * global counters to collect some stats
69  */
70 static struct {
71 	kstat_named_t	polllistmiss;	/* failed to find a cached poll list */
72 	kstat_named_t	pollcachehit;	/* list matched 100% w/ cached one */
73 	kstat_named_t	pollcachephit;	/* list matched < 100% w/ cached one */
74 	kstat_named_t	pollcachemiss;	/* every list entry is dif from cache */
75 } pollstats = {
76 	{ "polllistmiss",	KSTAT_DATA_UINT64 },
77 	{ "pollcachehit",	KSTAT_DATA_UINT64 },
78 	{ "pollcachephit",	KSTAT_DATA_UINT64 },
79 	{ "pollcachemiss",	KSTAT_DATA_UINT64 }
80 };
81 
82 kstat_named_t *pollstats_ptr = (kstat_named_t *)&pollstats;
83 uint_t pollstats_ndata = sizeof (pollstats) / sizeof (kstat_named_t);
84 
85 struct pplock	{
86 	kmutex_t	pp_lock;
87 	short		pp_flag;
88 	kcondvar_t	pp_wait_cv;
89 	int32_t		pp_pad;		/* to a nice round 16 bytes */
90 };
91 
92 static struct pplock plocks[NPHLOCKS];	/* Hash array of pollhead locks */
93 
94 #ifdef DEBUG
95 static int pollchecksanity(pollstate_t *, nfds_t);
96 static int pollcheckxref(pollstate_t *, int);
97 static void pollcheckphlist(void);
98 static int pollcheckrevents(pollstate_t *, int, int, int);
99 static void checkpolldat(pollstate_t *);
100 #endif	/* DEBUG */
101 static int plist_chkdupfd(file_t *, polldat_t *, pollstate_t *, pollfd_t *, int,
102     int *);
103 
104 /*
105  * Data structure overview:
106  * The per-thread poll state consists of
107  *	one pollstate_t
108  *	one pollcache_t
109  *	one bitmap with one event bit per fd
110  *	a (two-dimensional) hashed array of polldat_t structures - one entry
111  *	per fd
112  *
113  * This conglomerate of data structures interact with
114  *	the pollhead which is used by VOP_POLL and pollwakeup
115  *	(protected by the PHLOCK, cached array of plocks), and
116  *	the fpollinfo list hanging off the fi_list which is used to notify
117  *	poll when a cached fd is closed. This is protected by uf_lock.
118  *
119  * Invariants:
120  *	pd_php (pollhead pointer) is set iff (if and only if) the polldat
121  *	is on that pollhead. This is modified atomically under pc_lock.
122  *
123  *	pd_fp (file_t pointer) is set iff the thread is on the fpollinfo
124  *	list for that open file.
125  *	This is modified atomically under pc_lock.
126  *
127  *	pd_count is the sum (over all values of i) of pd_ref[i].xf_refcnt.
128  *	Iff pd_ref[i].xf_refcnt >= 1 then
129  *		ps_pcacheset[i].pcs_pollfd[pd_ref[i].xf_position].fd == pd_fd
130  *	Iff pd_ref[i].xf_refcnt > 1 then
131  *		In ps_pcacheset[i].pcs_pollfd between index
132  *		pd_ref[i].xf_position] and the end of the list
133  *		there are xf_refcnt entries with .fd == pd_fd
134  *
135  * Locking design:
136  * Whenever possible the design relies on the fact that the poll cache state
137  * is per thread thus for both poll and exit it is self-synchronizing.
138  * Thus the key interactions where other threads access the state are:
139  *	pollwakeup (and polltime), and
140  *	close cleaning up the cached references to an open file
141  *
142  * The two key locks in poll proper is ps_lock and pc_lock.
143  *
144  * The ps_lock is used for synchronization between poll, (lwp_)exit and close
145  * to ensure that modifications to pollcacheset structure are serialized.
146  * This lock is held through most of poll() except where poll sleeps
147  * since there is little need to handle closes concurrently with the execution
148  * of poll.
149  * The pc_lock protects most of the fields in pollcache structure and polldat
150  * structures (which are accessed by poll, pollwakeup, and polltime)
151  * with the exception of fields that are only modified when only one thread
152  * can access this per-thread state.
153  * Those exceptions occur in poll when first allocating the per-thread state,
154  * when poll grows the number of polldat (never shrinks), and when
155  * exit/pollcleanup has ensured that there are no references from either
156  * pollheads or fpollinfo to the threads poll state.
157  *
158  * Poll(2) system call is the only path which ps_lock and pc_lock are both
159  * held, in that order. It needs ps_lock to synchronize with close and
160  * lwp_exit; and pc_lock with pollwakeup.
161  *
162  * The locking interaction between pc_lock and PHLOCK take into account
163  * that poll acquires these locks in the order of pc_lock and then PHLOCK
164  * while pollwakeup does it in the reverse order. Thus pollwakeup implements
165  * deadlock avoidance by dropping the locks and reacquiring them in the
166  * reverse order. For this to work pollwakeup needs to prevent the thread
167  * from exiting and freeing all of the poll related state. Thus is done
168  * using
169  *	the pc_no_exit lock
170  *	the pc_busy counter
171  *	the pc_busy_cv condition variable
172  *
173  * The locking interaction between pc_lock and uf_lock has similar
174  * issues. Poll holds ps_lock and/or pc_lock across calls to getf/releasef
175  * which acquire uf_lock. The poll cleanup in close needs to hold uf_lock
176  * to prevent poll or exit from doing a delfpollinfo after which the thread
177  * might exit. But the cleanup needs to acquire pc_lock when modifying
178  * the poll cache state. The solution is to use pc_busy and do the close
179  * cleanup in two phases:
180  *	First close calls pollblockexit which increments pc_busy.
181  *	This prevents the per-thread poll related state from being freed.
182  *	Then close drops uf_lock and calls pollcacheclean.
183  *	This routine can then acquire pc_lock and remove any references
184  *	to the closing fd (as well as recording that it has been closed
185  *	so that a POLLNVAL can be generated even if the fd is reused before
186  *	poll has been woken up and checked getf() again).
187  *
188  * When removing a polled fd from poll cache, the fd is always removed
189  * from pollhead list first and then from fpollinfo list, i.e.,
190  * pollhead_delete() is called before delfpollinfo().
191  *
192  *
193  * Locking hierarchy:
194  *	pc_no_exit is a leaf level lock.
195  *	ps_lock is held when acquiring pc_lock (except when pollwakeup
196  *	acquires pc_lock).
197  *	pc_lock might be held when acquiring PHLOCK (pollhead_insert/
198  *	pollhead_delete)
199  *	pc_lock is always held (but this is not required)
200  *	when acquiring PHLOCK (in polladd/pollhead_delete and pollwakeup called
201  *	from pcache_clean_entry).
202  *	pc_lock is held across addfpollinfo/delfpollinfo which acquire
203  *	uf_lock.
204  *	pc_lock is held across getf/releasef which acquire uf_lock.
205  *	ps_lock might be held across getf/releasef which acquire uf_lock.
206  *	pollwakeup tries to acquire pc_lock while holding PHLOCK
207  *	but drops the locks and reacquire them in reverse order to avoid
208  *	deadlock.
209  *
210  * Note also that there is deadlock avoidance support for VOP_POLL routines
211  * and pollwakeup involving a file system or driver lock.
212  * See below.
213  */
214 
215 /*
216  * Deadlock avoidance support for VOP_POLL() routines.  This is
217  * sometimes necessary to prevent deadlock between polling threads
218  * (which hold poll locks on entry to xx_poll(), then acquire foo)
219  * and pollwakeup() threads (which hold foo, then acquire poll locks).
220  *
221  * pollunlock(void) releases whatever poll locks the current thread holds,
222  *	returning a cookie for use by pollrelock();
223  *
224  * pollrelock(cookie) reacquires previously dropped poll locks;
225  *
226  * polllock(php, mutex) does the common case: pollunlock(),
227  *	acquire the problematic mutex, pollrelock().
228  */
229 int
230 pollunlock(void)
231 {
232 	pollcache_t *pcp;
233 	int lockstate = 0;
234 
235 	/*
236 	 * t_pollcache is set by /dev/poll and event ports (port_fd.c).
237 	 * If the pollrelock/pollunlock is called as a result of poll(2),
238 	 * the t_pollcache should be NULL.
239 	 */
240 	if (curthread->t_pollcache == NULL)
241 		pcp = curthread->t_pollstate->ps_pcache;
242 	else
243 		pcp = curthread->t_pollcache;
244 
245 	if (mutex_owned(&pcp->pc_lock)) {
246 		lockstate = 1;
247 		mutex_exit(&pcp->pc_lock);
248 	}
249 	return (lockstate);
250 }
251 
252 void
253 pollrelock(int lockstate)
254 {
255 	pollcache_t *pcp;
256 
257 	/*
258 	 * t_pollcache is set by /dev/poll and event ports (port_fd.c).
259 	 * If the pollrelock/pollunlock is called as a result of poll(2),
260 	 * the t_pollcache should be NULL.
261 	 */
262 	if (curthread->t_pollcache == NULL)
263 		pcp = curthread->t_pollstate->ps_pcache;
264 	else
265 		pcp = curthread->t_pollcache;
266 
267 	if (lockstate > 0)
268 		mutex_enter(&pcp->pc_lock);
269 }
270 
271 /* ARGSUSED */
272 void
273 polllock(pollhead_t *php, kmutex_t *lp)
274 {
275 	if (!mutex_tryenter(lp)) {
276 		int lockstate = pollunlock();
277 		mutex_enter(lp);
278 		pollrelock(lockstate);
279 	}
280 }
281 
282 static int
283 poll_common(pollfd_t *fds, nfds_t nfds, timespec_t *tsp, k_sigset_t *ksetp)
284 {
285 	kthread_t *t = curthread;
286 	klwp_t *lwp = ttolwp(t);
287 	proc_t *p = ttoproc(t);
288 	int fdcnt = 0;
289 	int rval;
290 	int i;
291 	timespec_t *rqtp = NULL;
292 	int timecheck = 0;
293 	int imm_timeout = 0;
294 	pollfd_t *pollfdp;
295 	pollstate_t *ps;
296 	pollcache_t *pcp;
297 	int error = 0;
298 	nfds_t old_nfds;
299 	int cacheindex = 0;	/* which cache set is used */
300 
301 	/*
302 	 * Determine the precise future time of the requested timeout, if any.
303 	 */
304 	if (tsp != NULL) {
305 		if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
306 			imm_timeout = 1;
307 		else {
308 			timespec_t now;
309 			timecheck = timechanged;
310 			gethrestime(&now);
311 			rqtp = tsp;
312 			timespecadd(rqtp, &now);
313 		}
314 	}
315 
316 	/*
317 	 * Reset our signal mask, if requested.
318 	 */
319 	if (ksetp != NULL) {
320 		mutex_enter(&p->p_lock);
321 		schedctl_finish_sigblock(t);
322 		lwp->lwp_sigoldmask = t->t_hold;
323 		t->t_hold = *ksetp;
324 		t->t_flag |= T_TOMASK;
325 		/*
326 		 * Call cv_reltimedwait_sig() just to check for signals.
327 		 * We will return immediately with either 0 or -1.
328 		 */
329 		if (!cv_reltimedwait_sig(&t->t_delay_cv, &p->p_lock, 0,
330 		    TR_CLOCK_TICK)) {
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 		/* Prefetch 64 bytes worth of 8-byte elements */
1000 		if ((ix & 0x7) == 0) {
1001 			prefetch_write_many((caddr_t)&current[ix + 8]);
1002 			prefetch_write_many((caddr_t)&cached[ix + 8]);
1003 		}
1004 		if (current[ix].fd == cached[ix].fd) {
1005 			/*
1006 			 * Filter out invalid poll events while we are in
1007 			 * inside the loop.
1008 			 */
1009 			if (current[ix].events & ~VALID_POLL_EVENTS) {
1010 				current[ix].events &= VALID_POLL_EVENTS;
1011 				if (newlist != NULL)
1012 					newlist[ix].events = current[ix].events;
1013 			}
1014 			if (current[ix].events == cached[ix].events) {
1015 				current[ix].revents = 0;
1016 				continue;
1017 			}
1018 		}
1019 		if ((current[ix].fd < 0) && (cached[ix].fd < 0)) {
1020 			current[ix].revents = 0;
1021 			continue;
1022 		}
1023 		return (ix);
1024 	}
1025 	return (ix);
1026 }
1027 
1028 /*
1029  * This routine returns a pointer to a cached poll fd entry, or NULL if it
1030  * does not find it in the hash table.
1031  */
1032 polldat_t *
1033 pcache_lookup_fd(pollcache_t *pcp, int fd)
1034 {
1035 	int hashindex;
1036 	polldat_t *pdp;
1037 
1038 	hashindex = POLLHASH(pcp->pc_hashsize, fd);
1039 	pdp = pcp->pc_hash[hashindex];
1040 	while (pdp != NULL) {
1041 		if (pdp->pd_fd == fd)
1042 			break;
1043 		pdp = pdp->pd_hashnext;
1044 	}
1045 	return (pdp);
1046 }
1047 
1048 polldat_t *
1049 pcache_alloc_fd(int nsets)
1050 {
1051 	polldat_t *pdp;
1052 
1053 	pdp = kmem_zalloc(sizeof (polldat_t), KM_SLEEP);
1054 	if (nsets > 0) {
1055 		pdp->pd_ref = kmem_zalloc(sizeof (xref_t) * nsets, KM_SLEEP);
1056 		pdp->pd_nsets = nsets;
1057 	}
1058 	return (pdp);
1059 }
1060 
1061 /*
1062  * This routine  inserts a polldat into the pollcache's hash table. It
1063  * may be necessary to grow the size of the hash table.
1064  */
1065 void
1066 pcache_insert_fd(pollcache_t *pcp, polldat_t *pdp, nfds_t nfds)
1067 {
1068 	int hashindex;
1069 	int fd;
1070 
1071 	if ((pcp->pc_fdcount > pcp->pc_hashsize * POLLHASHTHRESHOLD) ||
1072 	    (nfds > pcp->pc_hashsize * POLLHASHTHRESHOLD)) {
1073 		pcache_grow_hashtbl(pcp, nfds);
1074 	}
1075 	fd = pdp->pd_fd;
1076 	hashindex = POLLHASH(pcp->pc_hashsize, fd);
1077 	pdp->pd_hashnext = pcp->pc_hash[hashindex];
1078 	pcp->pc_hash[hashindex] = pdp;
1079 	pcp->pc_fdcount++;
1080 
1081 #ifdef DEBUG
1082 	{
1083 		/*
1084 		 * same fd should not appear on a hash list twice
1085 		 */
1086 		polldat_t *pdp1;
1087 		for (pdp1 = pdp->pd_hashnext; pdp1; pdp1 = pdp1->pd_hashnext) {
1088 			ASSERT(pdp->pd_fd != pdp1->pd_fd);
1089 		}
1090 	}
1091 #endif	/* DEBUG */
1092 }
1093 
1094 /*
1095  * Grow the hash table -- either double the table size or round it to the
1096  * nearest multiples of POLLHASHCHUNKSZ, whichever is bigger. Rehash all the
1097  * elements on the hash table.
1098  */
1099 void
1100 pcache_grow_hashtbl(pollcache_t *pcp, nfds_t nfds)
1101 {
1102 	int	oldsize;
1103 	polldat_t **oldtbl;
1104 	polldat_t *pdp, *pdp1;
1105 	int	i;
1106 #ifdef DEBUG
1107 	int	count = 0;
1108 #endif
1109 
1110 	ASSERT(pcp->pc_hashsize % POLLHASHCHUNKSZ == 0);
1111 	oldsize = pcp->pc_hashsize;
1112 	oldtbl = pcp->pc_hash;
1113 	if (nfds > pcp->pc_hashsize * POLLHASHINC) {
1114 		pcp->pc_hashsize = (nfds + POLLHASHCHUNKSZ - 1) &
1115 		    ~(POLLHASHCHUNKSZ - 1);
1116 	} else {
1117 		pcp->pc_hashsize = pcp->pc_hashsize * POLLHASHINC;
1118 	}
1119 	pcp->pc_hash = kmem_zalloc(pcp->pc_hashsize * sizeof (polldat_t *),
1120 	    KM_SLEEP);
1121 	/*
1122 	 * rehash existing elements
1123 	 */
1124 	pcp->pc_fdcount = 0;
1125 	for (i = 0; i < oldsize; i++) {
1126 		pdp = oldtbl[i];
1127 		while (pdp != NULL) {
1128 			pdp1 = pdp->pd_hashnext;
1129 			pcache_insert_fd(pcp, pdp, nfds);
1130 			pdp = pdp1;
1131 #ifdef DEBUG
1132 			count++;
1133 #endif
1134 		}
1135 	}
1136 	kmem_free(oldtbl, oldsize * sizeof (polldat_t *));
1137 	ASSERT(pcp->pc_fdcount == count);
1138 }
1139 
1140 void
1141 pcache_grow_map(pollcache_t *pcp, int fd)
1142 {
1143 	int  	newsize;
1144 	ulong_t	*newmap;
1145 
1146 	/*
1147 	 * grow to nearest multiple of POLLMAPCHUNK, assuming POLLMAPCHUNK is
1148 	 * power of 2.
1149 	 */
1150 	newsize = (fd + POLLMAPCHUNK) & ~(POLLMAPCHUNK - 1);
1151 	newmap = kmem_zalloc((newsize / BT_NBIPUL) * sizeof (ulong_t),
1152 	    KM_SLEEP);
1153 	/*
1154 	 * don't want pollwakeup to set a bit while growing the bitmap.
1155 	 */
1156 	ASSERT(mutex_owned(&pcp->pc_lock) == 0);
1157 	mutex_enter(&pcp->pc_lock);
1158 	bcopy(pcp->pc_bitmap, newmap,
1159 	    (pcp->pc_mapsize / BT_NBIPUL) * sizeof (ulong_t));
1160 	kmem_free(pcp->pc_bitmap,
1161 	    (pcp->pc_mapsize /BT_NBIPUL) * sizeof (ulong_t));
1162 	pcp->pc_bitmap = newmap;
1163 	pcp->pc_mapsize = newsize;
1164 	mutex_exit(&pcp->pc_lock);
1165 }
1166 
1167 /*
1168  * remove all the reference from pollhead list and fpollinfo lists.
1169  */
1170 void
1171 pcache_clean(pollcache_t *pcp)
1172 {
1173 	int i;
1174 	polldat_t **hashtbl;
1175 	polldat_t *pdp;
1176 
1177 	ASSERT(MUTEX_HELD(&curthread->t_pollstate->ps_lock));
1178 	hashtbl = pcp->pc_hash;
1179 	for (i = 0; i < pcp->pc_hashsize; i++) {
1180 		for (pdp = hashtbl[i]; pdp; pdp = pdp->pd_hashnext) {
1181 			if (pdp->pd_php != NULL) {
1182 				pollhead_delete(pdp->pd_php, pdp);
1183 				pdp->pd_php = NULL;
1184 			}
1185 			if (pdp->pd_fp != NULL) {
1186 				delfpollinfo(pdp->pd_fd);
1187 				pdp->pd_fp = NULL;
1188 			}
1189 		}
1190 	}
1191 }
1192 
1193 void
1194 pcacheset_invalidate(pollstate_t *ps, polldat_t *pdp)
1195 {
1196 	int 	i;
1197 	int	fd = pdp->pd_fd;
1198 
1199 	/*
1200 	 * we come here because an earlier close() on this cached poll fd.
1201 	 */
1202 	ASSERT(pdp->pd_fp == NULL);
1203 	ASSERT(MUTEX_HELD(&ps->ps_lock));
1204 	pdp->pd_events = 0;
1205 	for (i = 0; i < ps->ps_nsets; i++) {
1206 		xref_t		*refp;
1207 		pollcacheset_t	*pcsp;
1208 
1209 		ASSERT(pdp->pd_ref != NULL);
1210 		refp = &pdp->pd_ref[i];
1211 		if (refp->xf_refcnt) {
1212 			ASSERT(refp->xf_position >= 0);
1213 			pcsp = &ps->ps_pcacheset[i];
1214 			if (refp->xf_refcnt == 1) {
1215 				pcsp->pcs_pollfd[refp->xf_position].fd = -1;
1216 				refp->xf_refcnt = 0;
1217 				pdp->pd_count--;
1218 			} else if (refp->xf_refcnt > 1) {
1219 				int	j;
1220 
1221 				/*
1222 				 * turn off every appearance in pcs_pollfd list
1223 				 */
1224 				for (j = refp->xf_position;
1225 				    j < pcsp->pcs_nfds; j++) {
1226 					if (pcsp->pcs_pollfd[j].fd == fd) {
1227 						pcsp->pcs_pollfd[j].fd = -1;
1228 						refp->xf_refcnt--;
1229 						pdp->pd_count--;
1230 					}
1231 				}
1232 			}
1233 			ASSERT(refp->xf_refcnt == 0);
1234 			refp->xf_position = POLLPOSINVAL;
1235 		}
1236 	}
1237 	ASSERT(pdp->pd_count == 0);
1238 }
1239 
1240 /*
1241  * Insert poll fd into the pollcache, and add poll registration.
1242  * This routine is called after getf() and before releasef(). So the vnode
1243  * can not disappear even if we block here.
1244  * If there is an error, the polled fd is not cached.
1245  */
1246 int
1247 pcache_insert(pollstate_t *ps, file_t *fp, pollfd_t *pollfdp, int *fdcntp,
1248     ssize_t pos, int which)
1249 {
1250 	pollcache_t	*pcp = ps->ps_pcache;
1251 	polldat_t	*pdp;
1252 	int		error;
1253 	int		fd;
1254 	pollhead_t	*memphp = NULL;
1255 	xref_t		*refp;
1256 	int		newpollfd = 0;
1257 
1258 	ASSERT(MUTEX_HELD(&ps->ps_lock));
1259 	/*
1260 	 * The poll caching uses the existing VOP_POLL interface. If there
1261 	 * is no polled events, we want the polled device to set its "some
1262 	 * one is sleeping in poll" flag. When the polled events happen
1263 	 * later, the driver will call pollwakeup(). We achieve this by
1264 	 * always passing 0 in the third parameter ("anyyet") when calling
1265 	 * VOP_POLL. This parameter is not looked at by drivers when the
1266 	 * polled events exist. If a driver chooses to ignore this parameter
1267 	 * and call pollwakeup whenever the polled events happen, that will
1268 	 * be OK too.
1269 	 */
1270 	ASSERT(curthread->t_pollcache == NULL);
1271 	error = VOP_POLL(fp->f_vnode, pollfdp->events, 0, &pollfdp->revents,
1272 	    &memphp, NULL);
1273 	if (error) {
1274 		return (error);
1275 	}
1276 	if (pollfdp->revents) {
1277 		(*fdcntp)++;
1278 	}
1279 	/*
1280 	 * polling the underlying device succeeded. Now we can cache it.
1281 	 * A close can't come in here because we have not done a releasef()
1282 	 * yet.
1283 	 */
1284 	fd = pollfdp->fd;
1285 	pdp = pcache_lookup_fd(pcp, fd);
1286 	if (pdp == NULL) {
1287 		ASSERT(ps->ps_nsets > 0);
1288 		pdp = pcache_alloc_fd(ps->ps_nsets);
1289 		newpollfd = 1;
1290 	}
1291 	/*
1292 	 * If this entry was used to cache a poll fd which was closed, and
1293 	 * this entry has not been cleaned, do it now.
1294 	 */
1295 	if ((pdp->pd_count > 0) && (pdp->pd_fp == NULL)) {
1296 		pcacheset_invalidate(ps, pdp);
1297 		ASSERT(pdp->pd_next == NULL);
1298 	}
1299 	if (pdp->pd_count == 0) {
1300 		pdp->pd_fd = fd;
1301 		pdp->pd_fp = fp;
1302 		addfpollinfo(fd);
1303 		pdp->pd_thread = curthread;
1304 		pdp->pd_pcache = pcp;
1305 		/*
1306 		 * the entry is never used or cleared by removing a cached
1307 		 * pollfd (pcache_delete_fd). So all the fields should be clear.
1308 		 */
1309 		ASSERT(pdp->pd_next == NULL);
1310 	}
1311 
1312 	/*
1313 	 * A polled fd is considered cached. So there should be a fpollinfo
1314 	 * entry on uf_fpollinfo list.
1315 	 */
1316 	ASSERT(infpollinfo(fd));
1317 	/*
1318 	 * If there is an inconsistency, we want to know it here.
1319 	 */
1320 	ASSERT(pdp->pd_fp == fp);
1321 
1322 	/*
1323 	 * XXX pd_events is a union of all polled events on this fd, possibly
1324 	 * by different threads. Unless this is a new first poll(), pd_events
1325 	 * never shrinks. If an event is no longer polled by a process, there
1326 	 * is no way to cancel that event. In that case, poll degrade to its
1327 	 * old form -- polling on this fd every time poll() is called. The
1328 	 * assumption is an app always polls the same type of events.
1329 	 */
1330 	pdp->pd_events |= pollfdp->events;
1331 
1332 	pdp->pd_count++;
1333 	/*
1334 	 * There is not much special handling for multiple appearances of
1335 	 * same fd other than xf_position always recording the first
1336 	 * appearance in poll list. If this is called from pcacheset_cache_list,
1337 	 * a VOP_POLL is called on every pollfd entry; therefore each
1338 	 * revents and fdcnt should be set correctly. If this is called from
1339 	 * pcacheset_resolve, we don't care about fdcnt here. Pollreadmap will
1340 	 * pick up the right count and handle revents field of each pollfd
1341 	 * entry.
1342 	 */
1343 	ASSERT(pdp->pd_ref != NULL);
1344 	refp = &pdp->pd_ref[which];
1345 	if (refp->xf_refcnt == 0) {
1346 		refp->xf_position = pos;
1347 	} else {
1348 		/*
1349 		 * xf_position records the fd's first appearance in poll list
1350 		 */
1351 		if (pos < refp->xf_position) {
1352 			refp->xf_position = pos;
1353 		}
1354 	}
1355 	ASSERT(pollfdp->fd == ps->ps_pollfd[refp->xf_position].fd);
1356 	refp->xf_refcnt++;
1357 	if (fd >= pcp->pc_mapsize) {
1358 		pcache_grow_map(pcp, fd);
1359 	}
1360 	if (fd > pcp->pc_mapend) {
1361 		pcp->pc_mapend = fd;
1362 	}
1363 	if (newpollfd != 0) {
1364 		pcache_insert_fd(ps->ps_pcache, pdp, ps->ps_nfds);
1365 	}
1366 	if (memphp) {
1367 		if (pdp->pd_php == NULL) {
1368 			pollhead_insert(memphp, pdp);
1369 			pdp->pd_php = memphp;
1370 		} else {
1371 			if (memphp != pdp->pd_php) {
1372 				/*
1373 				 * layered devices (e.g. console driver)
1374 				 * may change the vnode and thus the pollhead
1375 				 * pointer out from underneath us.
1376 				 */
1377 				pollhead_delete(pdp->pd_php, pdp);
1378 				pollhead_insert(memphp, pdp);
1379 				pdp->pd_php = memphp;
1380 			}
1381 		}
1382 	}
1383 	/*
1384 	 * Since there is a considerable window between VOP_POLL and when
1385 	 * we actually put the polldat struct on the pollhead list, we could
1386 	 * miss a pollwakeup. In the case of polling additional events, we
1387 	 * don't update the events until after VOP_POLL. So we could miss
1388 	 * pollwakeup there too. So we always set the bit here just to be
1389 	 * safe. The real performance gain is in subsequent pcache_poll.
1390 	 */
1391 	mutex_enter(&pcp->pc_lock);
1392 	BT_SET(pcp->pc_bitmap, fd);
1393 	mutex_exit(&pcp->pc_lock);
1394 	return (0);
1395 }
1396 
1397 /*
1398  * The entry is not really deleted. The fields are cleared so that the
1399  * entry is no longer useful, but it will remain in the hash table for reuse
1400  * later. It will be freed when the polling lwp exits.
1401  */
1402 int
1403 pcache_delete_fd(pollstate_t *ps, int fd, size_t pos, int which, uint_t cevent)
1404 {
1405 	pollcache_t	*pcp = ps->ps_pcache;
1406 	polldat_t	*pdp;
1407 	xref_t		*refp;
1408 
1409 	ASSERT(fd < pcp->pc_mapsize);
1410 	ASSERT(MUTEX_HELD(&ps->ps_lock));
1411 
1412 	pdp = pcache_lookup_fd(pcp, fd);
1413 	ASSERT(pdp != NULL);
1414 	ASSERT(pdp->pd_count > 0);
1415 	ASSERT(pdp->pd_ref != NULL);
1416 	refp = &pdp->pd_ref[which];
1417 	if (pdp->pd_count == 1) {
1418 		pdp->pd_events = 0;
1419 		refp->xf_position = POLLPOSINVAL;
1420 		ASSERT(refp->xf_refcnt == 1);
1421 		refp->xf_refcnt = 0;
1422 		if (pdp->pd_php) {
1423 			/*
1424 			 * It is possible for a wakeup thread to get ahead
1425 			 * of the following pollhead_delete and set the bit in
1426 			 * bitmap.  It is OK because the bit will be cleared
1427 			 * here anyway.
1428 			 */
1429 			pollhead_delete(pdp->pd_php, pdp);
1430 			pdp->pd_php = NULL;
1431 		}
1432 		pdp->pd_count = 0;
1433 		if (pdp->pd_fp != NULL) {
1434 			pdp->pd_fp = NULL;
1435 			delfpollinfo(fd);
1436 		}
1437 		mutex_enter(&pcp->pc_lock);
1438 		BT_CLEAR(pcp->pc_bitmap, fd);
1439 		mutex_exit(&pcp->pc_lock);
1440 		return (0);
1441 	}
1442 	if ((cevent & POLLCLOSED) == POLLCLOSED) {
1443 		/*
1444 		 * fd cached here has been closed. This is the first
1445 		 * pcache_delete_fd called after the close. Clean up the
1446 		 * entire entry.
1447 		 */
1448 		pcacheset_invalidate(ps, pdp);
1449 		ASSERT(pdp->pd_php == NULL);
1450 		mutex_enter(&pcp->pc_lock);
1451 		BT_CLEAR(pcp->pc_bitmap, fd);
1452 		mutex_exit(&pcp->pc_lock);
1453 		return (0);
1454 	}
1455 #ifdef DEBUG
1456 	if (getf(fd) != NULL) {
1457 		ASSERT(infpollinfo(fd));
1458 		releasef(fd);
1459 	}
1460 #endif	/* DEBUG */
1461 	pdp->pd_count--;
1462 	ASSERT(refp->xf_refcnt > 0);
1463 	if (--refp->xf_refcnt == 0) {
1464 		refp->xf_position = POLLPOSINVAL;
1465 	} else {
1466 		ASSERT(pos >= refp->xf_position);
1467 		if (pos == refp->xf_position) {
1468 			/*
1469 			 * The xref position is no longer valid.
1470 			 * Reset it to a special value and let
1471 			 * caller know it needs to updatexref()
1472 			 * with a new xf_position value.
1473 			 */
1474 			refp->xf_position = POLLPOSTRANS;
1475 			return (1);
1476 		}
1477 	}
1478 	return (0);
1479 }
1480 
1481 void
1482 pcache_update_xref(pollcache_t *pcp, int fd, ssize_t pos, int which)
1483 {
1484 	polldat_t	*pdp;
1485 
1486 	pdp = pcache_lookup_fd(pcp, fd);
1487 	ASSERT(pdp != NULL);
1488 	ASSERT(pdp->pd_ref != NULL);
1489 	pdp->pd_ref[which].xf_position = pos;
1490 }
1491 
1492 #ifdef DEBUG
1493 /*
1494  * For each polled fd, it's either in the bitmap or cached in
1495  * pcache hash table. If this routine returns 0, something is wrong.
1496  */
1497 static int
1498 pollchecksanity(pollstate_t *ps, nfds_t nfds)
1499 {
1500 	int    		i;
1501 	int		fd;
1502 	pollcache_t	*pcp = ps->ps_pcache;
1503 	polldat_t	*pdp;
1504 	pollfd_t	*pollfdp = ps->ps_pollfd;
1505 	file_t		*fp;
1506 
1507 	ASSERT(MUTEX_HELD(&ps->ps_lock));
1508 	for (i = 0; i < nfds; i++) {
1509 		fd = pollfdp[i].fd;
1510 		if (fd < 0) {
1511 			ASSERT(pollfdp[i].revents == 0);
1512 			continue;
1513 		}
1514 		if (pollfdp[i].revents == POLLNVAL)
1515 			continue;
1516 		if ((fp = getf(fd)) == NULL)
1517 			continue;
1518 		pdp = pcache_lookup_fd(pcp, fd);
1519 		ASSERT(pdp != NULL);
1520 		ASSERT(infpollinfo(fd));
1521 		ASSERT(pdp->pd_fp == fp);
1522 		releasef(fd);
1523 		if (BT_TEST(pcp->pc_bitmap, fd))
1524 			continue;
1525 		if (pdp->pd_php == NULL)
1526 			return (0);
1527 	}
1528 	return (1);
1529 }
1530 #endif	/* DEBUG */
1531 
1532 /*
1533  * resolve the difference between the current poll list and a cached one.
1534  */
1535 int
1536 pcacheset_resolve(pollstate_t *ps, nfds_t nfds, int *fdcntp, int which)
1537 {
1538 	int    		i;
1539 	pollcache_t	*pcp = ps->ps_pcache;
1540 	pollfd_t	*newlist = NULL;
1541 	pollfd_t	*current = ps->ps_pollfd;
1542 	pollfd_t	*cached;
1543 	pollcacheset_t	*pcsp;
1544 	int		common;
1545 	int		count = 0;
1546 	int		offset;
1547 	int		remain;
1548 	int		fd;
1549 	file_t		*fp;
1550 	int		fdcnt = 0;
1551 	int		cnt = 0;
1552 	nfds_t		old_nfds;
1553 	int		error = 0;
1554 	int		mismatch = 0;
1555 
1556 	ASSERT(MUTEX_HELD(&ps->ps_lock));
1557 #ifdef DEBUG
1558 	checkpolldat(ps);
1559 #endif
1560 	pcsp = &ps->ps_pcacheset[which];
1561 	old_nfds = pcsp->pcs_nfds;
1562 	common = (nfds > old_nfds) ? old_nfds : nfds;
1563 	if (nfds != old_nfds) {
1564 		/*
1565 		 * the length of poll list has changed. allocate a new
1566 		 * pollfd list.
1567 		 */
1568 		newlist = kmem_alloc(nfds * sizeof (pollfd_t), KM_SLEEP);
1569 		bcopy(current, newlist, sizeof (pollfd_t) * nfds);
1570 	}
1571 	/*
1572 	 * Compare the overlapping part of the current fd list with the
1573 	 * cached one. Whenever a difference is found, resolve it.
1574 	 * The comparison is done on the current poll list and the
1575 	 * cached list. But we may be setting up the newlist to be the
1576 	 * cached list for next poll.
1577 	 */
1578 	cached = pcsp->pcs_pollfd;
1579 	remain = common;
1580 
1581 	while (count < common) {
1582 		int	tmpfd;
1583 		pollfd_t *np;
1584 
1585 		np = (newlist != NULL) ? &newlist[count] : NULL;
1586 		offset = pcacheset_cmp(&current[count], &cached[count], np,
1587 		    remain);
1588 		/*
1589 		 * Collect stats. If lists are completed the first time,
1590 		 * it's a hit. Otherwise, it's a partial hit or miss.
1591 		 */
1592 		if ((count == 0) && (offset == common)) {
1593 			pollstats.pollcachehit.value.ui64++;
1594 		} else {
1595 			mismatch++;
1596 		}
1597 		count += offset;
1598 		if (offset < remain) {
1599 			ASSERT(count < common);
1600 			ASSERT((current[count].fd != cached[count].fd) ||
1601 			    (current[count].events != cached[count].events));
1602 			/*
1603 			 * Filter out invalid events.
1604 			 */
1605 			if (current[count].events & ~VALID_POLL_EVENTS) {
1606 				if (newlist != NULL) {
1607 					newlist[count].events =
1608 					    current[count].events &=
1609 					    VALID_POLL_EVENTS;
1610 				} else {
1611 					current[count].events &=
1612 					    VALID_POLL_EVENTS;
1613 				}
1614 			}
1615 			/*
1616 			 * when resolving a difference, we always remove the
1617 			 * fd from cache before inserting one into cache.
1618 			 */
1619 			if (cached[count].fd >= 0) {
1620 				tmpfd = cached[count].fd;
1621 				if (pcache_delete_fd(ps, tmpfd, count, which,
1622 				    (uint_t)cached[count].events)) {
1623 					/*
1624 					 * This should be rare but needed for
1625 					 * correctness.
1626 					 *
1627 					 * The first appearance in cached list
1628 					 * is being "turned off". The same fd
1629 					 * appear more than once in the cached
1630 					 * poll list. Find the next one on the
1631 					 * list and update the cached
1632 					 * xf_position field.
1633 					 */
1634 					for (i = count + 1; i < old_nfds; i++) {
1635 						if (cached[i].fd == tmpfd) {
1636 							pcache_update_xref(pcp,
1637 							    tmpfd, (ssize_t)i,
1638 							    which);
1639 							break;
1640 						}
1641 					}
1642 					ASSERT(i <= old_nfds);
1643 				}
1644 				/*
1645 				 * In case a new cache list is allocated,
1646 				 * need to keep both cache lists in sync
1647 				 * b/c the new one can be freed if we have
1648 				 * an error later.
1649 				 */
1650 				cached[count].fd = -1;
1651 				if (newlist != NULL) {
1652 					newlist[count].fd = -1;
1653 				}
1654 			}
1655 			if ((tmpfd = current[count].fd) >= 0) {
1656 				/*
1657 				 * add to the cached fd tbl and bitmap.
1658 				 */
1659 				if ((fp = getf(tmpfd)) == NULL) {
1660 					current[count].revents = POLLNVAL;
1661 					if (newlist != NULL) {
1662 						newlist[count].fd = -1;
1663 					}
1664 					cached[count].fd = -1;
1665 					fdcnt++;
1666 				} else {
1667 					/*
1668 					 * Here we don't care about the
1669 					 * fdcnt. We will examine the bitmap
1670 					 * later and pick up the correct
1671 					 * fdcnt there. So we never bother
1672 					 * to check value of 'cnt'.
1673 					 */
1674 					error = pcache_insert(ps, fp,
1675 					    &current[count], &cnt,
1676 					    (ssize_t)count, which);
1677 					/*
1678 					 * if no error, we want to do releasef
1679 					 * after we updated cache poll list
1680 					 * entry so that close() won't race
1681 					 * us.
1682 					 */
1683 					if (error) {
1684 						/*
1685 						 * If we encountered an error,
1686 						 * we have invalidated an
1687 						 * entry in cached poll list
1688 						 * (in pcache_delete_fd() above)
1689 						 * but failed to add one here.
1690 						 * This is OK b/c what's in the
1691 						 * cached list is consistent
1692 						 * with content of cache.
1693 						 * It will not have any ill
1694 						 * effect on next poll().
1695 						 */
1696 						releasef(tmpfd);
1697 						if (newlist != NULL) {
1698 							kmem_free(newlist,
1699 							    nfds *
1700 							    sizeof (pollfd_t));
1701 						}
1702 						return (error);
1703 					}
1704 					/*
1705 					 * If we have allocated a new(temp)
1706 					 * cache list, we need to keep both
1707 					 * in sync b/c the new one can be freed
1708 					 * if we have an error later.
1709 					 */
1710 					if (newlist != NULL) {
1711 						newlist[count].fd =
1712 						    current[count].fd;
1713 						newlist[count].events =
1714 						    current[count].events;
1715 					}
1716 					cached[count].fd = current[count].fd;
1717 					cached[count].events =
1718 					    current[count].events;
1719 					releasef(tmpfd);
1720 				}
1721 			} else {
1722 				current[count].revents = 0;
1723 			}
1724 			count++;
1725 			remain = common - count;
1726 		}
1727 	}
1728 	if (mismatch != 0) {
1729 		if (mismatch == common) {
1730 			pollstats.pollcachemiss.value.ui64++;
1731 		} else {
1732 			pollstats.pollcachephit.value.ui64++;
1733 		}
1734 	}
1735 	/*
1736 	 * take care of the non overlapping part of a list
1737 	 */
1738 	if (nfds > old_nfds) {
1739 		ASSERT(newlist != NULL);
1740 		for (i = old_nfds; i < nfds; i++) {
1741 			/* filter out invalid events */
1742 			if (current[i].events & ~VALID_POLL_EVENTS) {
1743 				newlist[i].events = current[i].events =
1744 				    current[i].events & VALID_POLL_EVENTS;
1745 			}
1746 			if ((fd = current[i].fd) < 0) {
1747 				current[i].revents = 0;
1748 				continue;
1749 			}
1750 			/*
1751 			 * add to the cached fd tbl and bitmap.
1752 			 */
1753 			if ((fp = getf(fd)) == NULL) {
1754 				current[i].revents = POLLNVAL;
1755 				newlist[i].fd = -1;
1756 				fdcnt++;
1757 				continue;
1758 			}
1759 			/*
1760 			 * Here we don't care about the
1761 			 * fdcnt. We will examine the bitmap
1762 			 * later and pick up the correct
1763 			 * fdcnt there. So we never bother to
1764 			 * check 'cnt'.
1765 			 */
1766 			error = pcache_insert(ps, fp, &current[i], &cnt,
1767 			    (ssize_t)i, which);
1768 			releasef(fd);
1769 			if (error) {
1770 				/*
1771 				 * Here we are half way through adding newly
1772 				 * polled fd. Undo enough to keep the cache
1773 				 * list consistent with the cache content.
1774 				 */
1775 				pcacheset_remove_list(ps, current, old_nfds,
1776 				    i, which, 0);
1777 				kmem_free(newlist, nfds * sizeof (pollfd_t));
1778 				return (error);
1779 			}
1780 		}
1781 	}
1782 	if (old_nfds > nfds) {
1783 		/*
1784 		 * remove the fd's which are no longer polled.
1785 		 */
1786 		pcacheset_remove_list(ps, pcsp->pcs_pollfd, nfds, old_nfds,
1787 		    which, 1);
1788 	}
1789 	/*
1790 	 * set difference resolved. update nfds and cachedlist
1791 	 * in pollstate struct.
1792 	 */
1793 	if (newlist != NULL) {
1794 		kmem_free(pcsp->pcs_pollfd, old_nfds * sizeof (pollfd_t));
1795 		/*
1796 		 * By now, the pollfd.revents field should
1797 		 * all be zeroed.
1798 		 */
1799 		pcsp->pcs_pollfd = newlist;
1800 		pcsp->pcs_nfds = nfds;
1801 	}
1802 	ASSERT(*fdcntp == 0);
1803 	*fdcntp = fdcnt;
1804 	/*
1805 	 * By now for every fd in pollfdp, one of the following should be
1806 	 * true. Otherwise we will miss a polled event.
1807 	 *
1808 	 * 1. the bit corresponding to the fd in bitmap is set. So VOP_POLL
1809 	 *    will be called on this fd in next poll.
1810 	 * 2. the fd is cached in the pcache (i.e. pd_php is set). So
1811 	 *    pollnotify will happen.
1812 	 */
1813 	ASSERT(pollchecksanity(ps, nfds));
1814 	/*
1815 	 * make sure cross reference between cached poll lists and cached
1816 	 * poll fds are correct.
1817 	 */
1818 	ASSERT(pollcheckxref(ps, which));
1819 	/*
1820 	 * ensure each polldat in pollcache reference a polled fd in
1821 	 * pollcacheset.
1822 	 */
1823 #ifdef DEBUG
1824 	checkpolldat(ps);
1825 #endif
1826 	return (0);
1827 }
1828 
1829 #ifdef DEBUG
1830 static int
1831 pollscanrevents(pollcache_t *pcp, pollfd_t *pollfdp, nfds_t nfds)
1832 {
1833 	int i;
1834 	int reventcnt = 0;
1835 
1836 	for (i = 0; i < nfds; i++) {
1837 		if (pollfdp[i].fd < 0) {
1838 			ASSERT(pollfdp[i].revents == 0);
1839 			continue;
1840 		}
1841 		if (pollfdp[i].revents) {
1842 			reventcnt++;
1843 		}
1844 		if (pollfdp[i].revents && (pollfdp[i].revents != POLLNVAL)) {
1845 			ASSERT(BT_TEST(pcp->pc_bitmap, pollfdp[i].fd));
1846 		}
1847 	}
1848 	return (reventcnt);
1849 }
1850 #endif	/* DEBUG */
1851 
1852 /*
1853  * read the bitmap and poll on fds corresponding to the '1' bits. The ps_lock
1854  * is held upon entry.
1855  */
1856 int
1857 pcache_poll(pollfd_t *pollfdp, pollstate_t *ps, nfds_t nfds, int *fdcntp,
1858     int which)
1859 {
1860 	int		i;
1861 	pollcache_t	*pcp;
1862 	int 		fd;
1863 	int 		begin, end, done;
1864 	pollhead_t	*php;
1865 	int		fdcnt;
1866 	int		error = 0;
1867 	file_t		*fp;
1868 	polldat_t	*pdp;
1869 	xref_t		*refp;
1870 	int		entry;
1871 
1872 	pcp = ps->ps_pcache;
1873 	ASSERT(MUTEX_HELD(&ps->ps_lock));
1874 	ASSERT(MUTEX_HELD(&pcp->pc_lock));
1875 retry:
1876 	done = 0;
1877 	begin = 0;
1878 	fdcnt = 0;
1879 	end = pcp->pc_mapend;
1880 	while ((fdcnt < nfds) && !done) {
1881 		php = NULL;
1882 		/*
1883 		 * only poll fds which may have events
1884 		 */
1885 		fd = bt_getlowbit(pcp->pc_bitmap, begin, end);
1886 		ASSERT(fd <= end);
1887 		if (fd >= 0) {
1888 			ASSERT(pollcheckrevents(ps, begin, fd, which));
1889 			/*
1890 			 * adjust map pointers for next round
1891 			 */
1892 			if (fd == end) {
1893 				done = 1;
1894 			} else {
1895 				begin = fd + 1;
1896 			}
1897 			/*
1898 			 * A bitmap caches poll state information of
1899 			 * multiple poll lists. Call VOP_POLL only if
1900 			 * the bit corresponds to an fd in this poll
1901 			 * list.
1902 			 */
1903 			pdp = pcache_lookup_fd(pcp, fd);
1904 			ASSERT(pdp != NULL);
1905 			ASSERT(pdp->pd_ref != NULL);
1906 			refp = &pdp->pd_ref[which];
1907 			if (refp->xf_refcnt == 0)
1908 				continue;
1909 			entry = refp->xf_position;
1910 			ASSERT((entry >= 0) && (entry < nfds));
1911 			ASSERT(pollfdp[entry].fd == fd);
1912 			/*
1913 			 * we are in this routine implies that we have
1914 			 * successfully polled this fd in the past.
1915 			 * Check to see this fd is closed while we are
1916 			 * blocked in poll. This ensures that we don't
1917 			 * miss a close on the fd in the case this fd is
1918 			 * reused.
1919 			 */
1920 			if (pdp->pd_fp == NULL) {
1921 				ASSERT(pdp->pd_count > 0);
1922 				pollfdp[entry].revents = POLLNVAL;
1923 				fdcnt++;
1924 				if (refp->xf_refcnt > 1) {
1925 					/*
1926 					 * this fd appeared multiple time
1927 					 * in the poll list. Find all of them.
1928 					 */
1929 					for (i = entry + 1; i < nfds; i++) {
1930 						if (pollfdp[i].fd == fd) {
1931 							pollfdp[i].revents =
1932 							    POLLNVAL;
1933 							fdcnt++;
1934 						}
1935 					}
1936 				}
1937 				pcacheset_invalidate(ps, pdp);
1938 				continue;
1939 			}
1940 			/*
1941 			 * We can be here polling a device that is being
1942 			 * closed (i.e. the file pointer is set to NULL,
1943 			 * but pollcacheclean has not happened yet).
1944 			 */
1945 			if ((fp = getf(fd)) == NULL) {
1946 				pollfdp[entry].revents = POLLNVAL;
1947 				fdcnt++;
1948 				if (refp->xf_refcnt > 1) {
1949 					/*
1950 					 * this fd appeared multiple time
1951 					 * in the poll list. Find all of them.
1952 					 */
1953 					for (i = entry + 1; i < nfds; i++) {
1954 						if (pollfdp[i].fd == fd) {
1955 							pollfdp[i].revents =
1956 							    POLLNVAL;
1957 							fdcnt++;
1958 						}
1959 					}
1960 				}
1961 				continue;
1962 			}
1963 			ASSERT(pdp->pd_fp == fp);
1964 			ASSERT(infpollinfo(fd));
1965 			/*
1966 			 * Since we no longer hold poll head lock across
1967 			 * VOP_POLL, pollunlock logic can be simplifed.
1968 			 */
1969 			ASSERT(pdp->pd_php == NULL ||
1970 			    MUTEX_NOT_HELD(PHLOCK(pdp->pd_php)));
1971 			/*
1972 			 * underlying file systems may set a "pollpending"
1973 			 * flag when it sees the poll may block. Pollwakeup()
1974 			 * is called by wakeup thread if pollpending is set.
1975 			 * Pass a 0 fdcnt so that the underlying file system
1976 			 * will set the "pollpending" flag set when there is
1977 			 * no polled events.
1978 			 *
1979 			 * Use pollfdp[].events for actual polling because
1980 			 * the pd_events is union of all cached poll events
1981 			 * on this fd. The events parameter also affects
1982 			 * how the polled device sets the "poll pending"
1983 			 * flag.
1984 			 */
1985 			ASSERT(curthread->t_pollcache == NULL);
1986 			error = VOP_POLL(fp->f_vnode, pollfdp[entry].events, 0,
1987 			    &pollfdp[entry].revents, &php, NULL);
1988 			/*
1989 			 * releasef after completely done with this cached
1990 			 * poll entry. To prevent close() coming in to clear
1991 			 * this entry.
1992 			 */
1993 			if (error) {
1994 				releasef(fd);
1995 				break;
1996 			}
1997 			/*
1998 			 * layered devices (e.g. console driver)
1999 			 * may change the vnode and thus the pollhead
2000 			 * pointer out from underneath us.
2001 			 */
2002 			if (php != NULL && pdp->pd_php != NULL &&
2003 			    php != pdp->pd_php) {
2004 				releasef(fd);
2005 				pollhead_delete(pdp->pd_php, pdp);
2006 				pdp->pd_php = php;
2007 				pollhead_insert(php, pdp);
2008 				/*
2009 				 * We could have missed a wakeup on the new
2010 				 * target device. Make sure the new target
2011 				 * gets polled once.
2012 				 */
2013 				BT_SET(pcp->pc_bitmap, fd);
2014 				goto retry;
2015 			}
2016 
2017 			if (pollfdp[entry].revents) {
2018 				ASSERT(refp->xf_refcnt >= 1);
2019 				fdcnt++;
2020 				if (refp->xf_refcnt > 1) {
2021 					/*
2022 					 * this fd appeared multiple time
2023 					 * in the poll list. This is rare but
2024 					 * we have to look at all of them for
2025 					 * correctness.
2026 					 */
2027 					error = plist_chkdupfd(fp, pdp, ps,
2028 					    pollfdp, entry, &fdcnt);
2029 					if (error > 0) {
2030 						releasef(fd);
2031 						break;
2032 					}
2033 					if (error < 0) {
2034 						goto retry;
2035 					}
2036 				}
2037 				releasef(fd);
2038 			} else {
2039 				/*
2040 				 * VOP_POLL didn't return any revents. We can
2041 				 * clear the bit in bitmap only if we have the
2042 				 * pollhead ptr cached and no other cached
2043 				 * entry is polling different events on this fd.
2044 				 * VOP_POLL may have dropped the ps_lock. Make
2045 				 * sure pollwakeup has not happened before clear
2046 				 * the bit.
2047 				 */
2048 				if ((pdp->pd_php != NULL) &&
2049 				    (pollfdp[entry].events == pdp->pd_events) &&
2050 				    ((pcp->pc_flag & T_POLLWAKE) == 0)) {
2051 					BT_CLEAR(pcp->pc_bitmap, fd);
2052 				}
2053 				/*
2054 				 * if the fd can be cached now but not before,
2055 				 * do it now.
2056 				 */
2057 				if ((pdp->pd_php == NULL) && (php != NULL)) {
2058 					pdp->pd_php = php;
2059 					pollhead_insert(php, pdp);
2060 					/*
2061 					 * We are inserting a polldat struct for
2062 					 * the first time. We may have missed a
2063 					 * wakeup on this device. Re-poll once.
2064 					 * This should be a rare event.
2065 					 */
2066 					releasef(fd);
2067 					goto retry;
2068 				}
2069 				if (refp->xf_refcnt > 1) {
2070 					/*
2071 					 * this fd appeared multiple time
2072 					 * in the poll list. This is rare but
2073 					 * we have to look at all of them for
2074 					 * correctness.
2075 					 */
2076 					error = plist_chkdupfd(fp, pdp, ps,
2077 					    pollfdp, entry, &fdcnt);
2078 					if (error > 0) {
2079 						releasef(fd);
2080 						break;
2081 					}
2082 					if (error < 0) {
2083 						goto retry;
2084 					}
2085 				}
2086 				releasef(fd);
2087 			}
2088 		} else {
2089 			done = 1;
2090 			ASSERT(pollcheckrevents(ps, begin, end + 1, which));
2091 		}
2092 	}
2093 	if (!error) {
2094 		ASSERT(*fdcntp + fdcnt == pollscanrevents(pcp, pollfdp, nfds));
2095 		*fdcntp += fdcnt;
2096 	}
2097 	return (error);
2098 }
2099 
2100 /*
2101  * Going through the poll list without much locking. Poll all fds and
2102  * cache all valid fds in the pollcache.
2103  */
2104 int
2105 pcacheset_cache_list(pollstate_t *ps, pollfd_t *fds, int *fdcntp, int which)
2106 {
2107 	pollfd_t	*pollfdp = ps->ps_pollfd;
2108 	pollcacheset_t	*pcacheset = ps->ps_pcacheset;
2109 	pollfd_t	*newfdlist;
2110 	int		i;
2111 	int		fd;
2112 	file_t		*fp;
2113 	int		error = 0;
2114 
2115 	ASSERT(MUTEX_HELD(&ps->ps_lock));
2116 	ASSERT(which < ps->ps_nsets);
2117 	ASSERT(pcacheset != NULL);
2118 	ASSERT(pcacheset[which].pcs_pollfd == NULL);
2119 	newfdlist  = kmem_alloc(ps->ps_nfds * sizeof (pollfd_t), KM_SLEEP);
2120 	/*
2121 	 * cache the new poll list in pollcachset.
2122 	 */
2123 	bcopy(pollfdp, newfdlist, sizeof (pollfd_t) * ps->ps_nfds);
2124 
2125 	pcacheset[which].pcs_pollfd = newfdlist;
2126 	pcacheset[which].pcs_nfds = ps->ps_nfds;
2127 	pcacheset[which].pcs_usradr = (uintptr_t)fds;
2128 
2129 	/*
2130 	 * We have saved a copy of current poll fd list in one pollcacheset.
2131 	 * The 'revents' field of the new list is not yet set to 0. Loop
2132 	 * through the new list just to do that is expensive. We do that
2133 	 * while polling the list.
2134 	 */
2135 	for (i = 0; i < ps->ps_nfds; i++) {
2136 		fd = pollfdp[i].fd;
2137 		/*
2138 		 * We also filter out the illegal poll events in the event
2139 		 * field for the cached poll list/set.
2140 		 */
2141 		if (pollfdp[i].events & ~VALID_POLL_EVENTS) {
2142 			newfdlist[i].events = pollfdp[i].events =
2143 			    pollfdp[i].events & VALID_POLL_EVENTS;
2144 		}
2145 		if (fd < 0) {
2146 			pollfdp[i].revents = 0;
2147 			continue;
2148 		}
2149 		if ((fp = getf(fd)) == NULL) {
2150 			pollfdp[i].revents = POLLNVAL;
2151 			/*
2152 			 * invalidate this cache entry in the cached poll list
2153 			 */
2154 			newfdlist[i].fd = -1;
2155 			(*fdcntp)++;
2156 			continue;
2157 		}
2158 		/*
2159 		 * cache this fd.
2160 		 */
2161 		error = pcache_insert(ps, fp, &pollfdp[i], fdcntp, (ssize_t)i,
2162 		    which);
2163 		releasef(fd);
2164 		if (error) {
2165 			/*
2166 			 * Here we are half way through caching a new
2167 			 * poll list. Undo every thing.
2168 			 */
2169 			pcacheset_remove_list(ps, pollfdp, 0, i, which, 0);
2170 			kmem_free(newfdlist, ps->ps_nfds * sizeof (pollfd_t));
2171 			pcacheset[which].pcs_pollfd = NULL;
2172 			pcacheset[which].pcs_usradr = NULL;
2173 			break;
2174 		}
2175 	}
2176 	return (error);
2177 }
2178 
2179 /*
2180  * called by pollcacheclean() to set the fp NULL. It also sets polled events
2181  * in pcacheset entries to a special events 'POLLCLOSED'. Do a pollwakeup to
2182  * wake any sleeping poller, then remove the polldat from the driver.
2183  * The routine is called with ps_pcachelock held.
2184  */
2185 void
2186 pcache_clean_entry(pollstate_t *ps, int fd)
2187 {
2188 	pollcache_t	*pcp;
2189 	polldat_t	*pdp;
2190 	int		i;
2191 
2192 	ASSERT(ps != NULL);
2193 	ASSERT(MUTEX_HELD(&ps->ps_lock));
2194 	pcp = ps->ps_pcache;
2195 	ASSERT(pcp);
2196 	pdp = pcache_lookup_fd(pcp, fd);
2197 	ASSERT(pdp != NULL);
2198 	/*
2199 	 * the corresponding fpollinfo in fi_list has been removed by
2200 	 * a close on this fd. Reset the cached fp ptr here.
2201 	 */
2202 	pdp->pd_fp = NULL;
2203 	/*
2204 	 * XXX - This routine also touches data in pcacheset struct.
2205 	 *
2206 	 * set the event in cached poll lists to POLLCLOSED. This invalidate
2207 	 * the cached poll fd entry in that poll list, which will force a
2208 	 * removal of this cached entry in next poll(). The cleanup is done
2209 	 * at the removal time.
2210 	 */
2211 	ASSERT(pdp->pd_ref != NULL);
2212 	for (i = 0; i < ps->ps_nsets; i++) {
2213 		xref_t		*refp;
2214 		pollcacheset_t	*pcsp;
2215 
2216 		refp = &pdp->pd_ref[i];
2217 		if (refp->xf_refcnt) {
2218 			ASSERT(refp->xf_position >= 0);
2219 			pcsp = &ps->ps_pcacheset[i];
2220 			if (refp->xf_refcnt == 1) {
2221 				pcsp->pcs_pollfd[refp->xf_position].events =
2222 				    (short)POLLCLOSED;
2223 			}
2224 			if (refp->xf_refcnt > 1) {
2225 				int	j;
2226 				/*
2227 				 * mark every matching entry in pcs_pollfd
2228 				 */
2229 				for (j = refp->xf_position;
2230 				    j < pcsp->pcs_nfds; j++) {
2231 					if (pcsp->pcs_pollfd[j].fd == fd) {
2232 						pcsp->pcs_pollfd[j].events =
2233 						    (short)POLLCLOSED;
2234 					}
2235 				}
2236 			}
2237 		}
2238 	}
2239 	if (pdp->pd_php) {
2240 		pollwakeup(pdp->pd_php, POLLHUP);
2241 		pollhead_delete(pdp->pd_php, pdp);
2242 		pdp->pd_php = NULL;
2243 	}
2244 }
2245 
2246 /*
2247  * This is the first time this thread has ever polled,
2248  * so we have to create its pollstate structure.
2249  * This will persist for the life of the thread,
2250  * until it calls pollcleanup().
2251  */
2252 pollstate_t *
2253 pollstate_create(void)
2254 {
2255 	pollstate_t *ps;
2256 
2257 	ps = kmem_zalloc(sizeof (pollstate_t), KM_SLEEP);
2258 	ps->ps_nsets = POLLFDSETS;
2259 	ps->ps_pcacheset = pcacheset_create(ps->ps_nsets);
2260 	return (ps);
2261 }
2262 
2263 void
2264 pollstate_destroy(pollstate_t *ps)
2265 {
2266 	if (ps->ps_pollfd != NULL) {
2267 		kmem_free(ps->ps_pollfd, ps->ps_nfds * sizeof (pollfd_t));
2268 		ps->ps_pollfd = NULL;
2269 	}
2270 	if (ps->ps_pcache != NULL) {
2271 		pcache_destroy(ps->ps_pcache);
2272 		ps->ps_pcache = NULL;
2273 	}
2274 	pcacheset_destroy(ps->ps_pcacheset, ps->ps_nsets);
2275 	ps->ps_pcacheset = NULL;
2276 	if (ps->ps_dpbuf != NULL) {
2277 		kmem_free(ps->ps_dpbuf, ps->ps_dpbufsize * sizeof (pollfd_t));
2278 		ps->ps_dpbuf = NULL;
2279 	}
2280 	mutex_destroy(&ps->ps_lock);
2281 	kmem_free(ps, sizeof (pollstate_t));
2282 }
2283 
2284 /*
2285  * We are holding the appropriate uf_lock entering this routine.
2286  * Bump up the ps_busy count to prevent the thread from exiting.
2287  */
2288 void
2289 pollblockexit(fpollinfo_t *fpip)
2290 {
2291 	for (; fpip; fpip = fpip->fp_next) {
2292 		pollcache_t *pcp = fpip->fp_thread->t_pollstate->ps_pcache;
2293 
2294 		mutex_enter(&pcp->pc_no_exit);
2295 		pcp->pc_busy++;  /* prevents exit()'s */
2296 		mutex_exit(&pcp->pc_no_exit);
2297 	}
2298 }
2299 
2300 /*
2301  * Complete phase 2 of cached poll fd cleanup. Call pcache_clean_entry to mark
2302  * the pcacheset events field POLLCLOSED to force the next poll() to remove
2303  * this cache entry. We can't clean the polldat entry clean up here because
2304  * lwp block in poll() needs the info to return. Wakeup anyone blocked in
2305  * poll and let exiting lwp go. No lock is help upon entry. So it's OK for
2306  * pcache_clean_entry to call pollwakeup().
2307  */
2308 void
2309 pollcacheclean(fpollinfo_t *fip, int fd)
2310 {
2311 	struct fpollinfo	*fpip, *fpip2;
2312 
2313 	fpip = fip;
2314 	while (fpip) {
2315 		pollstate_t *ps = fpip->fp_thread->t_pollstate;
2316 		pollcache_t *pcp = ps->ps_pcache;
2317 
2318 		mutex_enter(&ps->ps_lock);
2319 		pcache_clean_entry(ps, fd);
2320 		mutex_exit(&ps->ps_lock);
2321 		mutex_enter(&pcp->pc_no_exit);
2322 		pcp->pc_busy--;
2323 		if (pcp->pc_busy == 0) {
2324 			/*
2325 			 * Wakeup the thread waiting in
2326 			 * thread_exit().
2327 			 */
2328 			cv_signal(&pcp->pc_busy_cv);
2329 		}
2330 		mutex_exit(&pcp->pc_no_exit);
2331 
2332 		fpip2 = fpip;
2333 		fpip = fpip->fp_next;
2334 		kmem_free(fpip2, sizeof (fpollinfo_t));
2335 	}
2336 }
2337 
2338 /*
2339  * one of the cache line's counter is wrapping around. Reset all cache line
2340  * counters to zero except one. This is simplistic, but probably works
2341  * effectively.
2342  */
2343 void
2344 pcacheset_reset_count(pollstate_t *ps, int index)
2345 {
2346 	int	i;
2347 
2348 	ASSERT(MUTEX_HELD(&ps->ps_lock));
2349 	for (i = 0; i < ps->ps_nsets; i++) {
2350 		if (ps->ps_pcacheset[i].pcs_pollfd != NULL) {
2351 			ps->ps_pcacheset[i].pcs_count = 0;
2352 		}
2353 	}
2354 	ps->ps_pcacheset[index].pcs_count = 1;
2355 }
2356 
2357 /*
2358  * this routine implements poll cache list replacement policy.
2359  * It is currently choose the "least used".
2360  */
2361 int
2362 pcacheset_replace(pollstate_t *ps)
2363 {
2364 	int i;
2365 	int index = 0;
2366 
2367 	ASSERT(MUTEX_HELD(&ps->ps_lock));
2368 	for (i = 1; i < ps->ps_nsets; i++) {
2369 		if (ps->ps_pcacheset[index].pcs_count >
2370 		    ps->ps_pcacheset[i].pcs_count) {
2371 			index = i;
2372 		}
2373 	}
2374 	ps->ps_pcacheset[index].pcs_count = 0;
2375 	return (index);
2376 }
2377 
2378 /*
2379  * this routine is called by strclose to remove remaining polldat struct on
2380  * the pollhead list of the device being closed. There are two reasons as why
2381  * the polldat structures still remain on the pollhead list:
2382  *
2383  * (1) The layered device(e.g.the console driver).
2384  * In this case, the existence of a polldat implies that the thread putting
2385  * the polldat on this list has not exited yet. Before the thread exits, it
2386  * will have to hold this pollhead lock to remove the polldat. So holding the
2387  * pollhead lock here effectively prevents the thread which put the polldat
2388  * on this list from exiting.
2389  *
2390  * (2) /dev/poll.
2391  * When a polled fd is cached in /dev/poll, its polldat will remain on the
2392  * pollhead list if the process has not done a POLLREMOVE before closing the
2393  * polled fd. We just unlink it here.
2394  */
2395 void
2396 pollhead_clean(pollhead_t *php)
2397 {
2398 	polldat_t	*pdp;
2399 
2400 	/*
2401 	 * In case(1), while we must prevent the thread in question from
2402 	 * exiting, we must also obey the proper locking order, i.e.
2403 	 * (ps_lock -> phlock).
2404 	 */
2405 	PH_ENTER(php);
2406 	while (php->ph_list != NULL) {
2407 		pollstate_t	*ps;
2408 		pollcache_t	*pcp;
2409 
2410 		pdp = php->ph_list;
2411 		ASSERT(pdp->pd_php == php);
2412 		if (pdp->pd_thread == NULL) {
2413 			/*
2414 			 * This is case(2). Since the ph_lock is sufficient
2415 			 * to synchronize this lwp with any other /dev/poll
2416 			 * lwp, just unlink the polldat.
2417 			 */
2418 			php->ph_list = pdp->pd_next;
2419 			pdp->pd_php = NULL;
2420 			pdp->pd_next = NULL;
2421 			continue;
2422 		}
2423 		ps = pdp->pd_thread->t_pollstate;
2424 		ASSERT(ps != NULL);
2425 		pcp = pdp->pd_pcache;
2426 		ASSERT(pcp != NULL);
2427 		mutex_enter(&pcp->pc_no_exit);
2428 		pcp->pc_busy++;  /* prevents exit()'s */
2429 		mutex_exit(&pcp->pc_no_exit);
2430 		/*
2431 		 * Now get the locks in proper order to avoid deadlock.
2432 		 */
2433 		PH_EXIT(php);
2434 		mutex_enter(&ps->ps_lock);
2435 		/*
2436 		 * while we dropped the pollhead lock, the element could be
2437 		 * taken off the list already.
2438 		 */
2439 		PH_ENTER(php);
2440 		if (pdp->pd_php == php) {
2441 			ASSERT(pdp == php->ph_list);
2442 			php->ph_list = pdp->pd_next;
2443 			pdp->pd_php = NULL;
2444 			pdp->pd_next = NULL;
2445 		}
2446 		PH_EXIT(php);
2447 		mutex_exit(&ps->ps_lock);
2448 		mutex_enter(&pcp->pc_no_exit);
2449 		pcp->pc_busy--;
2450 		if (pcp->pc_busy == 0) {
2451 			/*
2452 			 * Wakeup the thread waiting in
2453 			 * thread_exit().
2454 			 */
2455 			cv_signal(&pcp->pc_busy_cv);
2456 		}
2457 		mutex_exit(&pcp->pc_no_exit);
2458 		PH_ENTER(php);
2459 	}
2460 	PH_EXIT(php);
2461 }
2462 
2463 /*
2464  * The remove_list is called to cleanup a partially cached 'current' list or
2465  * to remove a partial list which is no longer cached. The flag value of 1
2466  * indicates the second case.
2467  */
2468 void
2469 pcacheset_remove_list(pollstate_t *ps, pollfd_t *pollfdp, int start, int end,
2470     int cacheindex, int flag)
2471 {
2472 	int i;
2473 
2474 	ASSERT(MUTEX_HELD(&ps->ps_lock));
2475 	for (i = start; i < end; i++) {
2476 		if ((pollfdp[i].fd >= 0) &&
2477 		    (flag || !(pollfdp[i].revents & POLLNVAL))) {
2478 			if (pcache_delete_fd(ps, pollfdp[i].fd, i, cacheindex,
2479 			    (uint_t)pollfdp[i].events)) {
2480 				int j;
2481 				int fd = pollfdp[i].fd;
2482 
2483 				for (j = i + 1; j < end; j++) {
2484 					if (pollfdp[j].fd == fd) {
2485 						pcache_update_xref(
2486 						    ps->ps_pcache, fd,
2487 						    (ssize_t)j, cacheindex);
2488 						break;
2489 					}
2490 				}
2491 				ASSERT(j <= end);
2492 			}
2493 		}
2494 	}
2495 }
2496 
2497 #ifdef DEBUG
2498 
2499 #include<sys/strsubr.h>
2500 /*
2501  * make sure curthread is not on anyone's pollhead list any more.
2502  */
2503 static void
2504 pollcheckphlist()
2505 {
2506 	int i;
2507 	file_t *fp;
2508 	uf_entry_t *ufp;
2509 	uf_info_t *fip = P_FINFO(curproc);
2510 	struct stdata *stp;
2511 	polldat_t *pdp;
2512 
2513 	mutex_enter(&fip->fi_lock);
2514 	for (i = 0; i < fip->fi_nfiles; i++) {
2515 		UF_ENTER(ufp, fip, i);
2516 		if ((fp = ufp->uf_file) != NULL) {
2517 			if ((stp = fp->f_vnode->v_stream) != NULL) {
2518 				PH_ENTER(&stp->sd_pollist);
2519 				pdp = stp->sd_pollist.ph_list;
2520 				while (pdp) {
2521 					ASSERT(pdp->pd_thread != curthread);
2522 					pdp = pdp->pd_next;
2523 				}
2524 				PH_EXIT(&stp->sd_pollist);
2525 			}
2526 		}
2527 		UF_EXIT(ufp);
2528 	}
2529 	mutex_exit(&fip->fi_lock);
2530 }
2531 
2532 /*
2533  * for resolved set poll list, the xref info in the pcache should be
2534  * consistent with this poll list.
2535  */
2536 static int
2537 pollcheckxref(pollstate_t *ps, int cacheindex)
2538 {
2539 	pollfd_t *pollfdp = ps->ps_pcacheset[cacheindex].pcs_pollfd;
2540 	pollcache_t *pcp = ps->ps_pcache;
2541 	polldat_t *pdp;
2542 	int	i;
2543 	xref_t	*refp;
2544 
2545 	for (i = 0; i < ps->ps_pcacheset[cacheindex].pcs_nfds; i++) {
2546 		if (pollfdp[i].fd < 0) {
2547 			continue;
2548 		}
2549 		pdp = pcache_lookup_fd(pcp, pollfdp[i].fd);
2550 		ASSERT(pdp != NULL);
2551 		ASSERT(pdp->pd_ref != NULL);
2552 		refp = &pdp->pd_ref[cacheindex];
2553 		if (refp->xf_position >= 0) {
2554 			ASSERT(refp->xf_refcnt >= 1);
2555 			ASSERT(pollfdp[refp->xf_position].fd == pdp->pd_fd);
2556 			if (refp->xf_refcnt > 1) {
2557 				int	j;
2558 				int	count = 0;
2559 
2560 				for (j = refp->xf_position;
2561 				    j < ps->ps_pcacheset[cacheindex].pcs_nfds;
2562 				    j++) {
2563 					if (pollfdp[j].fd == pdp->pd_fd) {
2564 						count++;
2565 					}
2566 				}
2567 				ASSERT(count == refp->xf_refcnt);
2568 			}
2569 		}
2570 	}
2571 	return (1);
2572 }
2573 
2574 /*
2575  * For every cached pollfd, its polldat struct should be consistent with
2576  * what is in the pcacheset lists.
2577  */
2578 static void
2579 checkpolldat(pollstate_t *ps)
2580 {
2581 	pollcache_t	*pcp = ps->ps_pcache;
2582 	polldat_t	**hashtbl;
2583 	int		i;
2584 
2585 	hashtbl = pcp->pc_hash;
2586 	for (i = 0; i < pcp->pc_hashsize; i++) {
2587 		polldat_t	*pdp;
2588 
2589 		for (pdp = hashtbl[i]; pdp; pdp = pdp->pd_hashnext) {
2590 			ASSERT(pdp->pd_ref != NULL);
2591 			if (pdp->pd_count > 0) {
2592 				xref_t		*refp;
2593 				int		j;
2594 				pollcacheset_t	*pcsp;
2595 				pollfd_t	*pollfd;
2596 
2597 				for (j = 0; j < ps->ps_nsets; j++) {
2598 					refp = &pdp->pd_ref[j];
2599 					if (refp->xf_refcnt > 0) {
2600 						pcsp = &ps->ps_pcacheset[j];
2601 				ASSERT(refp->xf_position < pcsp->pcs_nfds);
2602 						pollfd = pcsp->pcs_pollfd;
2603 			ASSERT(pdp->pd_fd == pollfd[refp->xf_position].fd);
2604 					}
2605 				}
2606 			}
2607 		}
2608 	}
2609 }
2610 
2611 /*
2612  * every wfd element on ph_list must have a corresponding fpollinfo on the
2613  * uf_fpollinfo list. This is a variation of infpollinfo() w/o holding locks.
2614  */
2615 void
2616 checkwfdlist(vnode_t *vp, fpollinfo_t *fpip)
2617 {
2618 	stdata_t *stp;
2619 	polldat_t *pdp;
2620 	fpollinfo_t *fpip2;
2621 
2622 	if ((stp = vp->v_stream) == NULL) {
2623 		return;
2624 	}
2625 	PH_ENTER(&stp->sd_pollist);
2626 	for (pdp = stp->sd_pollist.ph_list; pdp; pdp = pdp->pd_next) {
2627 		if (pdp->pd_thread != NULL &&
2628 		    pdp->pd_thread->t_procp == curthread->t_procp) {
2629 			for (fpip2 = fpip; fpip2; fpip2 = fpip2->fp_next) {
2630 				if (pdp->pd_thread == fpip2->fp_thread) {
2631 					break;
2632 				}
2633 			}
2634 			ASSERT(fpip2 != NULL);
2635 		}
2636 	}
2637 	PH_EXIT(&stp->sd_pollist);
2638 }
2639 
2640 /*
2641  * For each cached fd whose bit is not set in bitmap, its revents field in
2642  * current poll list should be 0.
2643  */
2644 static int
2645 pollcheckrevents(pollstate_t *ps, int begin, int end, int cacheindex)
2646 {
2647 	pollcache_t	*pcp = ps->ps_pcache;
2648 	pollfd_t	*pollfdp = ps->ps_pollfd;
2649 	int		i;
2650 
2651 	for (i = begin; i < end; i++) {
2652 		polldat_t	*pdp;
2653 
2654 		ASSERT(!BT_TEST(pcp->pc_bitmap, i));
2655 		pdp = pcache_lookup_fd(pcp, i);
2656 		if (pdp && pdp->pd_fp != NULL) {
2657 			xref_t *refp;
2658 			int entry;
2659 
2660 			ASSERT(pdp->pd_ref != NULL);
2661 			refp = &pdp->pd_ref[cacheindex];
2662 			if (refp->xf_refcnt == 0) {
2663 				continue;
2664 			}
2665 			entry = refp->xf_position;
2666 			ASSERT(entry >= 0);
2667 			ASSERT(pollfdp[entry].revents == 0);
2668 			if (refp->xf_refcnt > 1) {
2669 				int j;
2670 
2671 				for (j = entry + 1; j < ps->ps_nfds; j++) {
2672 					if (pollfdp[j].fd == i) {
2673 						ASSERT(pollfdp[j].revents == 0);
2674 					}
2675 				}
2676 			}
2677 		}
2678 	}
2679 	return (1);
2680 }
2681 
2682 #endif	/* DEBUG */
2683 
2684 pollcache_t *
2685 pcache_alloc()
2686 {
2687 	return (kmem_zalloc(sizeof (pollcache_t), KM_SLEEP));
2688 }
2689 
2690 void
2691 pcache_create(pollcache_t *pcp, nfds_t nfds)
2692 {
2693 	size_t	mapsize;
2694 
2695 	/*
2696 	 * allocate enough bits for the poll fd list
2697 	 */
2698 	if ((mapsize = POLLMAPCHUNK) <= nfds) {
2699 		mapsize = (nfds + POLLMAPCHUNK - 1) & ~(POLLMAPCHUNK - 1);
2700 	}
2701 	pcp->pc_bitmap = kmem_zalloc((mapsize / BT_NBIPUL) * sizeof (ulong_t),
2702 	    KM_SLEEP);
2703 	pcp->pc_mapsize = mapsize;
2704 	/*
2705 	 * The hash size is at least POLLHASHCHUNKSZ. If user polls a large
2706 	 * number of fd to start with, allocate a bigger hash table (to the
2707 	 * nearest multiple of POLLHASHCHUNKSZ) because dynamically growing a
2708 	 * hash table is expensive.
2709 	 */
2710 	if (nfds < POLLHASHCHUNKSZ) {
2711 		pcp->pc_hashsize = POLLHASHCHUNKSZ;
2712 	} else {
2713 		pcp->pc_hashsize = (nfds + POLLHASHCHUNKSZ - 1) &
2714 		    ~(POLLHASHCHUNKSZ - 1);
2715 	}
2716 	pcp->pc_hash = kmem_zalloc(pcp->pc_hashsize * sizeof (polldat_t *),
2717 	    KM_SLEEP);
2718 }
2719 
2720 void
2721 pcache_destroy(pollcache_t *pcp)
2722 {
2723 	polldat_t	**hashtbl;
2724 	int i;
2725 
2726 	hashtbl = pcp->pc_hash;
2727 	for (i = 0; i < pcp->pc_hashsize; i++) {
2728 		if (hashtbl[i] != NULL) {
2729 			polldat_t *pdp, *pdp2;
2730 
2731 			pdp = hashtbl[i];
2732 			while (pdp != NULL) {
2733 				pdp2 = pdp->pd_hashnext;
2734 				if (pdp->pd_ref != NULL) {
2735 					kmem_free(pdp->pd_ref, sizeof (xref_t) *
2736 					    pdp->pd_nsets);
2737 				}
2738 				kmem_free(pdp, sizeof (polldat_t));
2739 				pdp = pdp2;
2740 				pcp->pc_fdcount--;
2741 			}
2742 		}
2743 	}
2744 	ASSERT(pcp->pc_fdcount == 0);
2745 	kmem_free(pcp->pc_hash, sizeof (polldat_t *) * pcp->pc_hashsize);
2746 	kmem_free(pcp->pc_bitmap,
2747 	    sizeof (ulong_t) * (pcp->pc_mapsize/BT_NBIPUL));
2748 	mutex_destroy(&pcp->pc_no_exit);
2749 	mutex_destroy(&pcp->pc_lock);
2750 	cv_destroy(&pcp->pc_cv);
2751 	cv_destroy(&pcp->pc_busy_cv);
2752 	kmem_free(pcp, sizeof (pollcache_t));
2753 }
2754 
2755 pollcacheset_t *
2756 pcacheset_create(int nsets)
2757 {
2758 	return (kmem_zalloc(sizeof (pollcacheset_t) * nsets, KM_SLEEP));
2759 }
2760 
2761 void
2762 pcacheset_destroy(pollcacheset_t *pcsp, int nsets)
2763 {
2764 	int i;
2765 
2766 	for (i = 0; i < nsets; i++) {
2767 		if (pcsp[i].pcs_pollfd != NULL) {
2768 			kmem_free(pcsp[i].pcs_pollfd, pcsp[i].pcs_nfds *
2769 			    sizeof (pollfd_t));
2770 		}
2771 	}
2772 	kmem_free(pcsp, sizeof (pollcacheset_t) * nsets);
2773 }
2774 
2775 /*
2776  * Check each duplicated poll fd in the poll list. It may be necessary to
2777  * VOP_POLL the same fd again using different poll events. getf() has been
2778  * done by caller. This routine returns 0 if it can sucessfully process the
2779  * entire poll fd list. It returns -1 if underlying vnode has changed during
2780  * a VOP_POLL, in which case the caller has to repoll. It returns a positive
2781  * value if VOP_POLL failed.
2782  */
2783 static int
2784 plist_chkdupfd(file_t *fp, polldat_t *pdp, pollstate_t *psp, pollfd_t *pollfdp,
2785     int entry, int *fdcntp)
2786 {
2787 	int	i;
2788 	int	fd;
2789 	nfds_t	nfds = psp->ps_nfds;
2790 
2791 	fd = pollfdp[entry].fd;
2792 	for (i = entry + 1; i < nfds; i++) {
2793 		if (pollfdp[i].fd == fd) {
2794 			if (pollfdp[i].events == pollfdp[entry].events) {
2795 				if ((pollfdp[i].revents =
2796 				    pollfdp[entry].revents) != 0) {
2797 					(*fdcntp)++;
2798 				}
2799 			} else {
2800 
2801 				int	error;
2802 				pollhead_t *php;
2803 				pollcache_t *pcp = psp->ps_pcache;
2804 
2805 				/*
2806 				 * the events are different. VOP_POLL on this
2807 				 * fd so that we don't miss any revents.
2808 				 */
2809 				php = NULL;
2810 				ASSERT(curthread->t_pollcache == NULL);
2811 				error = VOP_POLL(fp->f_vnode,
2812 				    pollfdp[i].events, 0,
2813 				    &pollfdp[i].revents, &php, NULL);
2814 				if (error) {
2815 					return (error);
2816 				}
2817 				/*
2818 				 * layered devices(e.g. console driver)
2819 				 * may change the vnode and thus the pollhead
2820 				 * pointer out from underneath us.
2821 				 */
2822 				if (php != NULL && pdp->pd_php != NULL &&
2823 				    php != pdp->pd_php) {
2824 					pollhead_delete(pdp->pd_php, pdp);
2825 					pdp->pd_php = php;
2826 					pollhead_insert(php, pdp);
2827 					/*
2828 					 * We could have missed a wakeup on the
2829 					 * new target device. Make sure the new
2830 					 * target gets polled once.
2831 					 */
2832 					BT_SET(pcp->pc_bitmap, fd);
2833 					return (-1);
2834 				}
2835 				if (pollfdp[i].revents) {
2836 					(*fdcntp)++;
2837 				}
2838 			}
2839 		}
2840 	}
2841 	return (0);
2842 }
2843