xref: /titanic_50/usr/src/uts/common/syscall/poll.c (revision 25cf1a301a396c38e8adf52c15f537b80d2483f7)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2006 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	"%Z%%M%	%I%	%E% 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_kernel.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 
762 retry:
763 	PH_ENTER(php);
764 
765 	/*
766 	 * About half of all pollwakeups don't do anything, because the
767 	 * pollhead list is empty (i.e, nobody is interested in the event).
768 	 * For this common case, we can optimize out locking overhead.
769 	 */
770 	if (php->ph_list == NULL) {
771 		PH_EXIT(php);
772 		return;
773 	}
774 
775 	for (pdp = php->ph_list; pdp; pdp = pdp->pd_next) {
776 		if ((pdp->pd_events & events) ||
777 		    (events & (POLLHUP | POLLERR))) {
778 
779 			pollcache_t 	*pcp;
780 
781 			if (pdp->pd_portev != NULL) {
782 				port_kevent_t	*pkevp = pdp->pd_portev;
783 				/*
784 				 * Object (fd) is associated with an event port,
785 				 * => send event notification to the port.
786 				 */
787 				ASSERT(pkevp->portkev_flags
788 				    & PORT_ALLOC_CACHED);
789 				mutex_enter(&pkevp->portkev_lock);
790 				if (pkevp->portkev_flags & PORT_KEV_VALID) {
791 					pkevp->portkev_flags &= ~PORT_KEV_VALID;
792 					pkevp->portkev_events |= events &
793 					    (pdp->pd_events | POLLHUP |
794 					    POLLERR);
795 					/*
796 					 * portkev_lock mutex will be released
797 					 * by port_send_event()
798 					 */
799 					(void) port_send_event(pdp->pd_portev);
800 				} else {
801 					mutex_exit(&pkevp->portkev_lock);
802 				}
803 				continue;
804 			}
805 
806 			pcp = pdp->pd_pcache;
807 
808 			/*
809 			 * Try to grab the lock for this thread. If
810 			 * we don't get it then we may deadlock so
811 			 * back out and restart all over again. Note
812 			 * that the failure rate is very very low.
813 			 */
814 			if (mutex_tryenter(&pcp->pc_lock)) {
815 				pollnotify(pcp, pdp->pd_fd);
816 				mutex_exit(&pcp->pc_lock);
817 			} else {
818 				/*
819 				 * We are here because:
820 				 *	1) This thread has been woke up
821 				 *	   and is trying to get out of poll().
822 				 *	2) Some other thread is also here
823 				 *	   but with a different pollhead lock.
824 				 *
825 				 * So, we need to drop the lock on pollhead
826 				 * because of (1) but we want to prevent
827 				 * that thread from doing lwp_exit() or
828 				 * devpoll close. We want to ensure that
829 				 * the pollcache pointer is still invalid.
830 				 *
831 				 * Solution: Grab the pcp->pc_no_exit lock,
832 				 * increment the pc_busy counter, drop every
833 				 * lock in sight. Get out of the way and wait
834 				 * for type (2) threads to finish.
835 				 */
836 
837 				mutex_enter(&pcp->pc_no_exit);
838 				pcp->pc_busy++;	/* prevents exit()'s */
839 				mutex_exit(&pcp->pc_no_exit);
840 
841 				PH_EXIT(php);
842 				mutex_enter(&pcp->pc_lock);
843 				mutex_exit(&pcp->pc_lock);
844 				mutex_enter(&pcp->pc_no_exit);
845 				pcp->pc_busy--;
846 				if (pcp->pc_busy == 0) {
847 					/*
848 					 * Wakeup the thread waiting in
849 					 * thread_exit().
850 					 */
851 					cv_signal(&pcp->pc_busy_cv);
852 				}
853 				mutex_exit(&pcp->pc_no_exit);
854 				goto retry;
855 			}
856 		}
857 	}
858 	PH_EXIT(php);
859 }
860 
861 /*
862  * This function is called to inform a thread that
863  * an event being polled for has occurred.
864  * The pollstate lock on the thread should be held on entry.
865  */
866 void
867 pollnotify(pollcache_t *pcp, int fd)
868 {
869 	ASSERT(fd < pcp->pc_mapsize);
870 	ASSERT(MUTEX_HELD(&pcp->pc_lock));
871 	BT_SET(pcp->pc_bitmap, fd);
872 	pcp->pc_flag |= T_POLLWAKE;
873 	cv_signal(&pcp->pc_cv);
874 }
875 
876 /*
877  * add a polldat entry to pollhead ph_list. The polldat struct is used
878  * by pollwakeup to wake sleeping pollers when polled events has happened.
879  */
880 void
881 pollhead_insert(pollhead_t *php, polldat_t *pdp)
882 {
883 	PH_ENTER(php);
884 	ASSERT(pdp->pd_next == NULL);
885 #ifdef DEBUG
886 	{
887 		/*
888 		 * the polldat should not be already on the list
889 		 */
890 		polldat_t *wp;
891 		for (wp = php->ph_list; wp; wp = wp->pd_next) {
892 			ASSERT(wp != pdp);
893 		}
894 	}
895 #endif	/* DEBUG */
896 	pdp->pd_next = php->ph_list;
897 	php->ph_list = pdp;
898 	PH_EXIT(php);
899 }
900 
901 /*
902  * Delete the polldat entry from ph_list.
903  */
904 void
905 pollhead_delete(pollhead_t *php, polldat_t *pdp)
906 {
907 	polldat_t *wp;
908 	polldat_t **wpp;
909 
910 	PH_ENTER(php);
911 	for (wpp = &php->ph_list; (wp = *wpp) != NULL; wpp = &wp->pd_next) {
912 		if (wp == pdp) {
913 			*wpp = pdp->pd_next;
914 			pdp->pd_next = NULL;
915 			break;
916 		}
917 	}
918 #ifdef DEBUG
919 	/* assert that pdp is no longer in the list */
920 	for (wp = *wpp; wp; wp = wp->pd_next) {
921 		ASSERT(wp != pdp);
922 	}
923 #endif	/* DEBUG */
924 	PH_EXIT(php);
925 }
926 
927 /*
928  * walk through the poll fd lists to see if they are identical. This is an
929  * expensive operation and should not be done more than once for each poll()
930  * call.
931  *
932  * As an optimization (i.e., not having to go through the lists more than
933  * once), this routine also clear the revents field of pollfd in 'current'.
934  * Zeroing out the revents field of each entry in current poll list is
935  * required by poll man page.
936  *
937  * Since the events field of cached list has illegal poll events filtered
938  * out, the current list applies the same filtering before comparison.
939  *
940  * The routine stops when it detects a meaningful difference, or when it
941  * exhausts the lists.
942  */
943 int
944 pcacheset_cmp(pollfd_t *current, pollfd_t *cached, pollfd_t *newlist, int n)
945 {
946 	int    ix;
947 
948 	for (ix = 0; ix < n; ix++) {
949 		if (current[ix].fd == cached[ix].fd) {
950 			/*
951 			 * Filter out invalid poll events while we are in
952 			 * inside the loop.
953 			 */
954 			if (current[ix].events & ~VALID_POLL_EVENTS) {
955 				current[ix].events &= VALID_POLL_EVENTS;
956 				if (newlist != NULL)
957 					newlist[ix].events = current[ix].events;
958 			}
959 			if (current[ix].events == cached[ix].events) {
960 				current[ix].revents = 0;
961 				continue;
962 			}
963 		}
964 		if ((current[ix].fd < 0) && (cached[ix].fd < 0)) {
965 			current[ix].revents = 0;
966 			continue;
967 		}
968 		return (ix);
969 	}
970 	return (ix);
971 }
972 
973 /*
974  * This routine returns a pointer to a cached poll fd entry, or NULL if it
975  * does not find it in the hash table.
976  */
977 polldat_t *
978 pcache_lookup_fd(pollcache_t *pcp, int fd)
979 {
980 	int hashindex;
981 	polldat_t *pdp;
982 
983 	hashindex = POLLHASH(pcp->pc_hashsize, fd);
984 	pdp = pcp->pc_hash[hashindex];
985 	while (pdp != NULL) {
986 		if (pdp->pd_fd == fd)
987 			break;
988 		pdp = pdp->pd_hashnext;
989 	}
990 	return (pdp);
991 }
992 
993 polldat_t *
994 pcache_alloc_fd(int nsets)
995 {
996 	polldat_t *pdp;
997 
998 	pdp = kmem_zalloc(sizeof (polldat_t), KM_SLEEP);
999 	if (nsets > 0) {
1000 		pdp->pd_ref = kmem_zalloc(sizeof (xref_t) * nsets, KM_SLEEP);
1001 		pdp->pd_nsets = nsets;
1002 	}
1003 	return (pdp);
1004 }
1005 
1006 /*
1007  * This routine  inserts a polldat into the pollcache's hash table. It
1008  * may be necessary to grow the size of the hash table.
1009  */
1010 void
1011 pcache_insert_fd(pollcache_t *pcp, polldat_t *pdp, nfds_t nfds)
1012 {
1013 	int hashindex;
1014 	int fd;
1015 
1016 	if ((pcp->pc_fdcount > pcp->pc_hashsize * POLLHASHTHRESHOLD) ||
1017 	    (nfds > pcp->pc_hashsize * POLLHASHTHRESHOLD)) {
1018 		pcache_grow_hashtbl(pcp, nfds);
1019 	}
1020 	fd = pdp->pd_fd;
1021 	hashindex = POLLHASH(pcp->pc_hashsize, fd);
1022 	pdp->pd_hashnext = pcp->pc_hash[hashindex];
1023 	pcp->pc_hash[hashindex] = pdp;
1024 	pcp->pc_fdcount++;
1025 
1026 #ifdef DEBUG
1027 	{
1028 		/*
1029 		 * same fd should not appear on a hash list twice
1030 		 */
1031 		polldat_t *pdp1;
1032 		for (pdp1 = pdp->pd_hashnext; pdp1; pdp1 = pdp1->pd_hashnext) {
1033 			ASSERT(pdp->pd_fd != pdp1->pd_fd);
1034 		}
1035 	}
1036 #endif	/* DEBUG */
1037 }
1038 
1039 /*
1040  * Grow the hash table -- either double the table size or round it to the
1041  * nearest multiples of POLLHASHCHUNKSZ, whichever is bigger. Rehash all the
1042  * elements on the hash table.
1043  */
1044 void
1045 pcache_grow_hashtbl(pollcache_t *pcp, nfds_t nfds)
1046 {
1047 	int	oldsize;
1048 	polldat_t **oldtbl;
1049 	polldat_t *pdp, *pdp1;
1050 	int	i;
1051 #ifdef DEBUG
1052 	int	count = 0;
1053 #endif
1054 
1055 	ASSERT(pcp->pc_hashsize % POLLHASHCHUNKSZ == 0);
1056 	oldsize = pcp->pc_hashsize;
1057 	oldtbl = pcp->pc_hash;
1058 	if (nfds > pcp->pc_hashsize * POLLHASHINC) {
1059 		pcp->pc_hashsize = (nfds + POLLHASHCHUNKSZ - 1) &
1060 		    ~(POLLHASHCHUNKSZ - 1);
1061 	} else {
1062 		pcp->pc_hashsize = pcp->pc_hashsize * POLLHASHINC;
1063 	}
1064 	pcp->pc_hash = kmem_zalloc(pcp->pc_hashsize * sizeof (polldat_t *),
1065 	    KM_SLEEP);
1066 	/*
1067 	 * rehash existing elements
1068 	 */
1069 	pcp->pc_fdcount = 0;
1070 	for (i = 0; i < oldsize; i++) {
1071 		pdp = oldtbl[i];
1072 		while (pdp != NULL) {
1073 			pdp1 = pdp->pd_hashnext;
1074 			pcache_insert_fd(pcp, pdp, nfds);
1075 			pdp = pdp1;
1076 #ifdef DEBUG
1077 			count++;
1078 #endif
1079 		}
1080 	}
1081 	kmem_free(oldtbl, oldsize * sizeof (polldat_t *));
1082 	ASSERT(pcp->pc_fdcount == count);
1083 }
1084 
1085 void
1086 pcache_grow_map(pollcache_t *pcp, int fd)
1087 {
1088 	int  	newsize;
1089 	ulong_t	*newmap;
1090 
1091 	/*
1092 	 * grow to nearest multiple of POLLMAPCHUNK, assuming POLLMAPCHUNK is
1093 	 * power of 2.
1094 	 */
1095 	newsize = (fd + POLLMAPCHUNK) & ~(POLLMAPCHUNK - 1);
1096 	newmap = kmem_zalloc((newsize / BT_NBIPUL) * sizeof (ulong_t),
1097 	    KM_SLEEP);
1098 	/*
1099 	 * don't want pollwakeup to set a bit while growing the bitmap.
1100 	 */
1101 	ASSERT(mutex_owned(&pcp->pc_lock) == 0);
1102 	mutex_enter(&pcp->pc_lock);
1103 	bcopy(pcp->pc_bitmap, newmap,
1104 	    (pcp->pc_mapsize / BT_NBIPUL) * sizeof (ulong_t));
1105 	kmem_free(pcp->pc_bitmap,
1106 	    (pcp->pc_mapsize /BT_NBIPUL) * sizeof (ulong_t));
1107 	pcp->pc_bitmap = newmap;
1108 	pcp->pc_mapsize = newsize;
1109 	mutex_exit(&pcp->pc_lock);
1110 }
1111 
1112 /*
1113  * remove all the reference from pollhead list and fpollinfo lists.
1114  */
1115 void
1116 pcache_clean(pollcache_t *pcp)
1117 {
1118 	int i;
1119 	polldat_t **hashtbl;
1120 	polldat_t *pdp;
1121 
1122 	ASSERT(MUTEX_HELD(&curthread->t_pollstate->ps_lock));
1123 	hashtbl = pcp->pc_hash;
1124 	for (i = 0; i < pcp->pc_hashsize; i++) {
1125 		for (pdp = hashtbl[i]; pdp; pdp = pdp->pd_hashnext) {
1126 			if (pdp->pd_php != NULL) {
1127 				pollhead_delete(pdp->pd_php, pdp);
1128 				pdp->pd_php = NULL;
1129 			}
1130 			if (pdp->pd_fp != NULL) {
1131 				delfpollinfo(pdp->pd_fd);
1132 				pdp->pd_fp = NULL;
1133 			}
1134 		}
1135 	}
1136 }
1137 
1138 void
1139 pcacheset_invalidate(pollstate_t *ps, polldat_t *pdp)
1140 {
1141 	int 	i;
1142 	int	fd = pdp->pd_fd;
1143 
1144 	/*
1145 	 * we come here because an earlier close() on this cached poll fd.
1146 	 */
1147 	ASSERT(pdp->pd_fp == NULL);
1148 	ASSERT(MUTEX_HELD(&ps->ps_lock));
1149 	pdp->pd_events = 0;
1150 	for (i = 0; i < ps->ps_nsets; i++) {
1151 		xref_t		*refp;
1152 		pollcacheset_t	*pcsp;
1153 
1154 		ASSERT(pdp->pd_ref != NULL);
1155 		refp = &pdp->pd_ref[i];
1156 		if (refp->xf_refcnt) {
1157 			ASSERT(refp->xf_position >= 0);
1158 			pcsp = &ps->ps_pcacheset[i];
1159 			if (refp->xf_refcnt == 1) {
1160 				pcsp->pcs_pollfd[refp->xf_position].fd = -1;
1161 				refp->xf_refcnt = 0;
1162 				pdp->pd_count--;
1163 			} else if (refp->xf_refcnt > 1) {
1164 				int	j;
1165 
1166 				/*
1167 				 * turn off every appearance in pcs_pollfd list
1168 				 */
1169 				for (j = refp->xf_position;
1170 				    j < pcsp->pcs_nfds; j++) {
1171 					if (pcsp->pcs_pollfd[j].fd == fd) {
1172 						pcsp->pcs_pollfd[j].fd = -1;
1173 						refp->xf_refcnt--;
1174 						pdp->pd_count--;
1175 					}
1176 				}
1177 			}
1178 			ASSERT(refp->xf_refcnt == 0);
1179 			refp->xf_position = POLLPOSINVAL;
1180 		}
1181 	}
1182 	ASSERT(pdp->pd_count == 0);
1183 }
1184 
1185 /*
1186  * Insert poll fd into the pollcache, and add poll registration.
1187  * This routine is called after getf() and before releasef(). So the vnode
1188  * can not disappear even if we block here.
1189  * If there is an error, the polled fd is not cached.
1190  */
1191 int
1192 pcache_insert(pollstate_t *ps, file_t *fp, pollfd_t *pollfdp, int *fdcntp,
1193     ssize_t pos, int which)
1194 {
1195 	pollcache_t	*pcp = ps->ps_pcache;
1196 	polldat_t	*pdp;
1197 	int		error;
1198 	int		fd;
1199 	pollhead_t	*memphp = NULL;
1200 	xref_t		*refp;
1201 	int		newpollfd = 0;
1202 
1203 	ASSERT(MUTEX_HELD(&ps->ps_lock));
1204 	/*
1205 	 * The poll caching uses the existing VOP_POLL interface. If there
1206 	 * is no polled events, we want the polled device to set its "some
1207 	 * one is sleeping in poll" flag. When the polled events happen
1208 	 * later, the driver will call pollwakeup(). We achieve this by
1209 	 * always passing 0 in the third parameter ("anyyet") when calling
1210 	 * VOP_POLL. This parameter is not looked at by drivers when the
1211 	 * polled events exist. If a driver chooses to ignore this parameter
1212 	 * and call pollwakeup whenever the polled events happen, that will
1213 	 * be OK too.
1214 	 */
1215 	ASSERT(curthread->t_pollcache == NULL);
1216 	error = VOP_POLL(fp->f_vnode, pollfdp->events, 0, &pollfdp->revents,
1217 	    &memphp);
1218 	if (error) {
1219 		return (error);
1220 	}
1221 	if (pollfdp->revents) {
1222 		(*fdcntp)++;
1223 	}
1224 	/*
1225 	 * polling the underlying device succeeded. Now we can cache it.
1226 	 * A close can't come in here because we have not done a releasef()
1227 	 * yet.
1228 	 */
1229 	fd = pollfdp->fd;
1230 	pdp = pcache_lookup_fd(pcp, fd);
1231 	if (pdp == NULL) {
1232 		ASSERT(ps->ps_nsets > 0);
1233 		pdp = pcache_alloc_fd(ps->ps_nsets);
1234 		newpollfd = 1;
1235 	}
1236 	/*
1237 	 * If this entry was used to cache a poll fd which was closed, and
1238 	 * this entry has not been cleaned, do it now.
1239 	 */
1240 	if ((pdp->pd_count > 0) && (pdp->pd_fp == NULL)) {
1241 		pcacheset_invalidate(ps, pdp);
1242 		ASSERT(pdp->pd_next == NULL);
1243 	}
1244 	if (pdp->pd_count == 0) {
1245 		pdp->pd_fd = fd;
1246 		pdp->pd_fp = fp;
1247 		addfpollinfo(fd);
1248 		pdp->pd_thread = curthread;
1249 		pdp->pd_pcache = pcp;
1250 		/*
1251 		 * the entry is never used or cleared by removing a cached
1252 		 * pollfd (pcache_delete_fd). So all the fields should be clear.
1253 		 */
1254 		ASSERT(pdp->pd_next == NULL);
1255 	}
1256 
1257 	/*
1258 	 * A polled fd is considered cached. So there should be a fpollinfo
1259 	 * entry on uf_fpollinfo list.
1260 	 */
1261 	ASSERT(infpollinfo(fd));
1262 	/*
1263 	 * If there is an inconsistency, we want to know it here.
1264 	 */
1265 	ASSERT(pdp->pd_fp == fp);
1266 
1267 	/*
1268 	 * XXX pd_events is a union of all polled events on this fd, possibly
1269 	 * by different threads. Unless this is a new first poll(), pd_events
1270 	 * never shrinks. If an event is no longer polled by a process, there
1271 	 * is no way to cancel that event. In that case, poll degrade to its
1272 	 * old form -- polling on this fd every time poll() is called. The
1273 	 * assumption is an app always polls the same type of events.
1274 	 */
1275 	pdp->pd_events |= pollfdp->events;
1276 
1277 	pdp->pd_count++;
1278 	/*
1279 	 * There is not much special handling for multiple appearances of
1280 	 * same fd other than xf_position always recording the first
1281 	 * appearance in poll list. If this is called from pcacheset_cache_list,
1282 	 * a VOP_POLL is called on every pollfd entry; therefore each
1283 	 * revents and fdcnt should be set correctly. If this is called from
1284 	 * pcacheset_resolve, we don't care about fdcnt here. Pollreadmap will
1285 	 * pick up the right count and handle revents field of each pollfd
1286 	 * entry.
1287 	 */
1288 	ASSERT(pdp->pd_ref != NULL);
1289 	refp = &pdp->pd_ref[which];
1290 	if (refp->xf_refcnt == 0) {
1291 		refp->xf_position = pos;
1292 	} else {
1293 		/*
1294 		 * xf_position records the fd's first appearance in poll list
1295 		 */
1296 		if (pos < refp->xf_position) {
1297 			refp->xf_position = pos;
1298 		}
1299 	}
1300 	ASSERT(pollfdp->fd == ps->ps_pollfd[refp->xf_position].fd);
1301 	refp->xf_refcnt++;
1302 	if (fd >= pcp->pc_mapsize) {
1303 		pcache_grow_map(pcp, fd);
1304 	}
1305 	if (fd > pcp->pc_mapend) {
1306 		pcp->pc_mapend = fd;
1307 	}
1308 	if (newpollfd != 0) {
1309 		pcache_insert_fd(ps->ps_pcache, pdp, ps->ps_nfds);
1310 	}
1311 	if (memphp) {
1312 		if (pdp->pd_php == NULL) {
1313 			pollhead_insert(memphp, pdp);
1314 			pdp->pd_php = memphp;
1315 		} else {
1316 			if (memphp != pdp->pd_php) {
1317 				/*
1318 				 * layered devices (e.g. console driver)
1319 				 * may change the vnode and thus the pollhead
1320 				 * pointer out from underneath us.
1321 				 */
1322 				pollhead_delete(pdp->pd_php, pdp);
1323 				pollhead_insert(memphp, pdp);
1324 				pdp->pd_php = memphp;
1325 			}
1326 		}
1327 	}
1328 	/*
1329 	 * Since there is a considerable window between VOP_POLL and when
1330 	 * we actually put the polldat struct on the pollhead list, we could
1331 	 * miss a pollwakeup. In the case of polling additional events, we
1332 	 * don't update the events until after VOP_POLL. So we could miss
1333 	 * pollwakeup there too. So we always set the bit here just to be
1334 	 * safe. The real performance gain is in subsequent pcache_poll.
1335 	 */
1336 	mutex_enter(&pcp->pc_lock);
1337 	BT_SET(pcp->pc_bitmap, fd);
1338 	mutex_exit(&pcp->pc_lock);
1339 	return (0);
1340 }
1341 
1342 /*
1343  * The entry is not really deleted. The fields are cleared so that the
1344  * entry is no longer useful, but it will remain in the hash table for reuse
1345  * later. It will be freed when the polling lwp exits.
1346  */
1347 int
1348 pcache_delete_fd(pollstate_t *ps, int fd, size_t pos, int which, uint_t cevent)
1349 {
1350 	pollcache_t	*pcp = ps->ps_pcache;
1351 	polldat_t	*pdp;
1352 	xref_t		*refp;
1353 
1354 	ASSERT(fd < pcp->pc_mapsize);
1355 	ASSERT(MUTEX_HELD(&ps->ps_lock));
1356 
1357 	pdp = pcache_lookup_fd(pcp, fd);
1358 	ASSERT(pdp != NULL);
1359 	ASSERT(pdp->pd_count > 0);
1360 	ASSERT(pdp->pd_ref != NULL);
1361 	refp = &pdp->pd_ref[which];
1362 	if (pdp->pd_count == 1) {
1363 		pdp->pd_events = 0;
1364 		refp->xf_position = POLLPOSINVAL;
1365 		ASSERT(refp->xf_refcnt == 1);
1366 		refp->xf_refcnt = 0;
1367 		if (pdp->pd_php) {
1368 			/*
1369 			 * It is possible for a wakeup thread to get ahead
1370 			 * of the following pollhead_delete and set the bit in
1371 			 * bitmap.  It is OK because the bit will be cleared
1372 			 * here anyway.
1373 			 */
1374 			pollhead_delete(pdp->pd_php, pdp);
1375 			pdp->pd_php = NULL;
1376 		}
1377 		pdp->pd_count = 0;
1378 		if (pdp->pd_fp != NULL) {
1379 			pdp->pd_fp = NULL;
1380 			delfpollinfo(fd);
1381 		}
1382 		mutex_enter(&pcp->pc_lock);
1383 		BT_CLEAR(pcp->pc_bitmap, fd);
1384 		mutex_exit(&pcp->pc_lock);
1385 		return (0);
1386 	}
1387 	if ((cevent & POLLCLOSED) == POLLCLOSED) {
1388 		/*
1389 		 * fd cached here has been closed. This is the first
1390 		 * pcache_delete_fd called after the close. Clean up the
1391 		 * entire entry.
1392 		 */
1393 		pcacheset_invalidate(ps, pdp);
1394 		ASSERT(pdp->pd_php == NULL);
1395 		mutex_enter(&pcp->pc_lock);
1396 		BT_CLEAR(pcp->pc_bitmap, fd);
1397 		mutex_exit(&pcp->pc_lock);
1398 		return (0);
1399 	}
1400 #ifdef DEBUG
1401 	if (getf(fd) != NULL) {
1402 		ASSERT(infpollinfo(fd));
1403 		releasef(fd);
1404 	}
1405 #endif	/* DEBUG */
1406 	pdp->pd_count--;
1407 	ASSERT(refp->xf_refcnt > 0);
1408 	if (--refp->xf_refcnt == 0) {
1409 		refp->xf_position = POLLPOSINVAL;
1410 	} else {
1411 		ASSERT(pos >= refp->xf_position);
1412 		if (pos == refp->xf_position) {
1413 			/*
1414 			 * The xref position is no longer valid.
1415 			 * Reset it to a special value and let
1416 			 * caller know it needs to updatexref()
1417 			 * with a new xf_position value.
1418 			 */
1419 			refp->xf_position = POLLPOSTRANS;
1420 			return (1);
1421 		}
1422 	}
1423 	return (0);
1424 }
1425 
1426 void
1427 pcache_update_xref(pollcache_t *pcp, int fd, ssize_t pos, int which)
1428 {
1429 	polldat_t	*pdp;
1430 
1431 	pdp = pcache_lookup_fd(pcp, fd);
1432 	ASSERT(pdp != NULL);
1433 	ASSERT(pdp->pd_ref != NULL);
1434 	pdp->pd_ref[which].xf_position = pos;
1435 }
1436 
1437 #ifdef DEBUG
1438 /*
1439  * For each polled fd, it's either in the bitmap or cached in
1440  * pcache hash table. If this routine returns 0, something is wrong.
1441  */
1442 static int
1443 pollchecksanity(pollstate_t *ps, nfds_t nfds)
1444 {
1445 	int    		i;
1446 	int		fd;
1447 	pollcache_t	*pcp = ps->ps_pcache;
1448 	polldat_t	*pdp;
1449 	pollfd_t	*pollfdp = ps->ps_pollfd;
1450 	file_t		*fp;
1451 
1452 	ASSERT(MUTEX_HELD(&ps->ps_lock));
1453 	for (i = 0; i < nfds; i++) {
1454 		fd = pollfdp[i].fd;
1455 		if (fd < 0) {
1456 			ASSERT(pollfdp[i].revents == 0);
1457 			continue;
1458 		}
1459 		if (pollfdp[i].revents == POLLNVAL)
1460 			continue;
1461 		if ((fp = getf(fd)) == NULL)
1462 			continue;
1463 		pdp = pcache_lookup_fd(pcp, fd);
1464 		ASSERT(pdp != NULL);
1465 		ASSERT(infpollinfo(fd));
1466 		ASSERT(pdp->pd_fp == fp);
1467 		releasef(fd);
1468 		if (BT_TEST(pcp->pc_bitmap, fd))
1469 			continue;
1470 		if (pdp->pd_php == NULL)
1471 			return (0);
1472 	}
1473 	return (1);
1474 }
1475 #endif	/* DEBUG */
1476 
1477 /*
1478  * resolve the difference between the current poll list and a cached one.
1479  */
1480 int
1481 pcacheset_resolve(pollstate_t *ps, nfds_t nfds, int *fdcntp, int which)
1482 {
1483 	int    		i;
1484 	pollcache_t	*pcp = ps->ps_pcache;
1485 	pollfd_t	*newlist = NULL;
1486 	pollfd_t	*current = ps->ps_pollfd;
1487 	pollfd_t	*cached;
1488 	pollcacheset_t	*pcsp;
1489 	int		common;
1490 	int		count = 0;
1491 	int		offset;
1492 	int		remain;
1493 	int		fd;
1494 	file_t		*fp;
1495 	int		fdcnt = 0;
1496 	int		cnt = 0;
1497 	nfds_t		old_nfds;
1498 	int		error = 0;
1499 	int		mismatch = 0;
1500 
1501 	ASSERT(MUTEX_HELD(&ps->ps_lock));
1502 #ifdef DEBUG
1503 	checkpolldat(ps);
1504 #endif
1505 	pcsp = &ps->ps_pcacheset[which];
1506 	old_nfds = pcsp->pcs_nfds;
1507 	common = (nfds > old_nfds) ? old_nfds : nfds;
1508 	if (nfds != old_nfds) {
1509 		/*
1510 		 * the length of poll list has changed. allocate a new
1511 		 * pollfd list.
1512 		 */
1513 		newlist = kmem_alloc(nfds * sizeof (pollfd_t), KM_SLEEP);
1514 		bcopy(current, newlist, sizeof (pollfd_t) * nfds);
1515 	}
1516 	/*
1517 	 * Compare the overlapping part of the current fd list with the
1518 	 * cached one. Whenever a difference is found, resolve it.
1519 	 * The comparison is done on the current poll list and the
1520 	 * cached list. But we may be setting up the newlist to be the
1521 	 * cached list for next poll.
1522 	 */
1523 	cached = pcsp->pcs_pollfd;
1524 	remain = common;
1525 
1526 	while (count < common) {
1527 		int	tmpfd;
1528 		pollfd_t *np;
1529 
1530 		np = (newlist != NULL) ? &newlist[count] : NULL;
1531 		offset = pcacheset_cmp(&current[count], &cached[count], np,
1532 		    remain);
1533 		/*
1534 		 * Collect stats. If lists are completed the first time,
1535 		 * it's a hit. Otherwise, it's a partial hit or miss.
1536 		 */
1537 		if ((count == 0) && (offset == common)) {
1538 			pollstats.pollcachehit.value.ui64++;
1539 		} else {
1540 			mismatch++;
1541 		}
1542 		count += offset;
1543 		if (offset < remain) {
1544 			ASSERT(count < common);
1545 			ASSERT((current[count].fd != cached[count].fd) ||
1546 			    (current[count].events != cached[count].events));
1547 			/*
1548 			 * Filter out invalid events.
1549 			 */
1550 			if (current[count].events & ~VALID_POLL_EVENTS) {
1551 				if (newlist != NULL) {
1552 					newlist[count].events =
1553 						current[count].events &=
1554 							VALID_POLL_EVENTS;
1555 				} else {
1556 					current[count].events &=
1557 						VALID_POLL_EVENTS;
1558 				}
1559 			}
1560 			/*
1561 			 * when resolving a difference, we always remove the
1562 			 * fd from cache before inserting one into cache.
1563 			 */
1564 			if (cached[count].fd >= 0) {
1565 				tmpfd = cached[count].fd;
1566 				if (pcache_delete_fd(ps, tmpfd, count, which,
1567 				    (uint_t)cached[count].events)) {
1568 					/*
1569 					 * This should be rare but needed for
1570 					 * correctness.
1571 					 *
1572 					 * The first appearance in cached list
1573 					 * is being "turned off". The same fd
1574 					 * appear more than once in the cached
1575 					 * poll list. Find the next one on the
1576 					 * list and update the cached
1577 					 * xf_position field.
1578 					 */
1579 					for (i = count + 1; i < old_nfds; i++) {
1580 						if (cached[i].fd == tmpfd) {
1581 							pcache_update_xref(pcp,
1582 							    tmpfd, (ssize_t)i,
1583 							    which);
1584 						    break;
1585 						}
1586 					}
1587 					ASSERT(i <= old_nfds);
1588 				}
1589 				/*
1590 				 * In case a new cache list is allocated,
1591 				 * need to keep both cache lists in sync
1592 				 * b/c the new one can be freed if we have
1593 				 * an error later.
1594 				 */
1595 				cached[count].fd = -1;
1596 				if (newlist != NULL) {
1597 					newlist[count].fd = -1;
1598 				}
1599 			}
1600 			if ((tmpfd = current[count].fd) >= 0) {
1601 				/*
1602 				 * add to the cached fd tbl and bitmap.
1603 				 */
1604 				if ((fp = getf(tmpfd)) == NULL) {
1605 					current[count].revents = POLLNVAL;
1606 					if (newlist != NULL) {
1607 						newlist[count].fd = -1;
1608 					}
1609 					cached[count].fd = -1;
1610 					fdcnt++;
1611 				} else {
1612 					/*
1613 					 * Here we don't care about the
1614 					 * fdcnt. We will examine the bitmap
1615 					 * later and pick up the correct
1616 					 * fdcnt there. So we never bother
1617 					 * to check value of 'cnt'.
1618 					 */
1619 					error = pcache_insert(ps, fp,
1620 					    &current[count], &cnt,
1621 					    (ssize_t)count, which);
1622 					/*
1623 					 * if no error, we want to do releasef
1624 					 * after we updated cache poll list
1625 					 * entry so that close() won't race
1626 					 * us.
1627 					 */
1628 					if (error) {
1629 						/*
1630 						 * If we encountered an error,
1631 						 * we have invalidated an
1632 						 * entry in cached poll list
1633 						 * (in pcache_delete_fd() above)
1634 						 * but failed to add one here.
1635 						 * This is OK b/c what's in the
1636 						 * cached list is consistent
1637 						 * with content of cache.
1638 						 * It will not have any ill
1639 						 * effect on next poll().
1640 						 */
1641 						releasef(tmpfd);
1642 						if (newlist != NULL) {
1643 							kmem_free(newlist,
1644 							    nfds *
1645 							    sizeof (pollfd_t));
1646 						}
1647 						return (error);
1648 					}
1649 					/*
1650 					 * If we have allocated a new(temp)
1651 					 * cache list, we need to keep both
1652 					 * in sync b/c the new one can be freed
1653 					 * if we have an error later.
1654 					 */
1655 					if (newlist != NULL) {
1656 						newlist[count].fd =
1657 						    current[count].fd;
1658 						newlist[count].events =
1659 						    current[count].events;
1660 					}
1661 					cached[count].fd = current[count].fd;
1662 					cached[count].events =
1663 					    current[count].events;
1664 					releasef(tmpfd);
1665 				}
1666 			} else {
1667 				current[count].revents = 0;
1668 			}
1669 			count++;
1670 			remain = common - count;
1671 		}
1672 	}
1673 	if (mismatch != 0) {
1674 		if (mismatch == common) {
1675 			pollstats.pollcachemiss.value.ui64++;
1676 		} else {
1677 			pollstats.pollcachephit.value.ui64++;
1678 		}
1679 	}
1680 	/*
1681 	 * take care of the non overlapping part of a list
1682 	 */
1683 	if (nfds > old_nfds) {
1684 		ASSERT(newlist != NULL);
1685 		for (i = old_nfds; i < nfds; i++) {
1686 			/* filter out invalid events */
1687 			if (current[i].events & ~VALID_POLL_EVENTS) {
1688 				newlist[i].events = current[i].events =
1689 				current[i].events & VALID_POLL_EVENTS;
1690 			}
1691 			if ((fd = current[i].fd) < 0) {
1692 				current[i].revents = 0;
1693 				continue;
1694 			}
1695 			/*
1696 			 * add to the cached fd tbl and bitmap.
1697 			 */
1698 			if ((fp = getf(fd)) == NULL) {
1699 				current[i].revents = POLLNVAL;
1700 				newlist[i].fd = -1;
1701 				fdcnt++;
1702 				continue;
1703 			}
1704 			/*
1705 			 * Here we don't care about the
1706 			 * fdcnt. We will examine the bitmap
1707 			 * later and pick up the correct
1708 			 * fdcnt there. So we never bother to
1709 			 * check 'cnt'.
1710 			 */
1711 			error = pcache_insert(ps, fp, &current[i], &cnt,
1712 			    (ssize_t)i, which);
1713 			releasef(fd);
1714 			if (error) {
1715 				/*
1716 				 * Here we are half way through adding newly
1717 				 * polled fd. Undo enough to keep the cache
1718 				 * list consistent with the cache content.
1719 				 */
1720 				pcacheset_remove_list(ps, current, old_nfds,
1721 				    i, which, 0);
1722 				kmem_free(newlist, nfds * sizeof (pollfd_t));
1723 				return (error);
1724 			}
1725 		}
1726 	}
1727 	if (old_nfds > nfds) {
1728 		/*
1729 		 * remove the fd's which are no longer polled.
1730 		 */
1731 		pcacheset_remove_list(ps, pcsp->pcs_pollfd, nfds, old_nfds,
1732 		    which, 1);
1733 	}
1734 	/*
1735 	 * set difference resolved. update nfds and cachedlist
1736 	 * in pollstate struct.
1737 	 */
1738 	if (newlist != NULL) {
1739 		kmem_free(pcsp->pcs_pollfd, old_nfds * sizeof (pollfd_t));
1740 		/*
1741 		 * By now, the pollfd.revents field should
1742 		 * all be zeroed.
1743 		 */
1744 		pcsp->pcs_pollfd = newlist;
1745 		pcsp->pcs_nfds = nfds;
1746 	}
1747 	ASSERT(*fdcntp == 0);
1748 	*fdcntp = fdcnt;
1749 	/*
1750 	 * By now for every fd in pollfdp, one of the following should be
1751 	 * true. Otherwise we will miss a polled event.
1752 	 *
1753 	 * 1. the bit corresponding to the fd in bitmap is set. So VOP_POLL
1754 	 *    will be called on this fd in next poll.
1755 	 * 2. the fd is cached in the pcache (i.e. pd_php is set). So
1756 	 *    pollnotify will happen.
1757 	 */
1758 	ASSERT(pollchecksanity(ps, nfds));
1759 	/*
1760 	 * make sure cross reference between cached poll lists and cached
1761 	 * poll fds are correct.
1762 	 */
1763 	ASSERT(pollcheckxref(ps, which));
1764 	/*
1765 	 * ensure each polldat in pollcache reference a polled fd in
1766 	 * pollcacheset.
1767 	 */
1768 #ifdef DEBUG
1769 	checkpolldat(ps);
1770 #endif
1771 	return (0);
1772 }
1773 
1774 #ifdef DEBUG
1775 static int
1776 pollscanrevents(pollcache_t *pcp, pollfd_t *pollfdp, nfds_t nfds)
1777 {
1778 	int i;
1779 	int reventcnt = 0;
1780 
1781 	for (i = 0; i < nfds; i++) {
1782 		if (pollfdp[i].fd < 0) {
1783 			ASSERT(pollfdp[i].revents == 0);
1784 			continue;
1785 		}
1786 		if (pollfdp[i].revents) {
1787 			reventcnt++;
1788 		}
1789 		if (pollfdp[i].revents && (pollfdp[i].revents != POLLNVAL)) {
1790 			ASSERT(BT_TEST(pcp->pc_bitmap, pollfdp[i].fd));
1791 		}
1792 	}
1793 	return (reventcnt);
1794 }
1795 #endif	/* DEBUG */
1796 
1797 /*
1798  * read the bitmap and poll on fds corresponding to the '1' bits. The ps_lock
1799  * is held upon entry.
1800  */
1801 int
1802 pcache_poll(pollfd_t *pollfdp, pollstate_t *ps, nfds_t nfds, int *fdcntp,
1803     int which)
1804 {
1805 	int		i;
1806 	pollcache_t	*pcp;
1807 	int 		fd;
1808 	int 		begin, end, done;
1809 	pollhead_t	*php;
1810 	int		fdcnt;
1811 	int		error = 0;
1812 	file_t		*fp;
1813 	polldat_t	*pdp;
1814 	xref_t		*refp;
1815 	int		entry;
1816 
1817 	pcp = ps->ps_pcache;
1818 	ASSERT(MUTEX_HELD(&ps->ps_lock));
1819 	ASSERT(MUTEX_HELD(&pcp->pc_lock));
1820 retry:
1821 	done = 0;
1822 	begin = 0;
1823 	fdcnt = 0;
1824 	end = pcp->pc_mapend;
1825 	while ((fdcnt < nfds) && !done) {
1826 		php = NULL;
1827 		/*
1828 		 * only poll fds which may have events
1829 		 */
1830 		fd = bt_getlowbit(pcp->pc_bitmap, begin, end);
1831 		ASSERT(fd <= end);
1832 		if (fd >= 0) {
1833 			ASSERT(pollcheckrevents(ps, begin, fd, which));
1834 			/*
1835 			 * adjust map pointers for next round
1836 			 */
1837 			if (fd == end) {
1838 				done = 1;
1839 			} else {
1840 				begin = fd + 1;
1841 			}
1842 			/*
1843 			 * A bitmap caches poll state information of
1844 			 * multiple poll lists. Call VOP_POLL only if
1845 			 * the bit corresponds to an fd in this poll
1846 			 * list.
1847 			 */
1848 			pdp = pcache_lookup_fd(pcp, fd);
1849 			ASSERT(pdp != NULL);
1850 			ASSERT(pdp->pd_ref != NULL);
1851 			refp = &pdp->pd_ref[which];
1852 			if (refp->xf_refcnt == 0)
1853 				continue;
1854 			entry = refp->xf_position;
1855 			ASSERT((entry >= 0) && (entry < nfds));
1856 			ASSERT(pollfdp[entry].fd == fd);
1857 			/*
1858 			 * we are in this routine implies that we have
1859 			 * successfully polled this fd in the past.
1860 			 * Check to see this fd is closed while we are
1861 			 * blocked in poll. This ensures that we don't
1862 			 * miss a close on the fd in the case this fd is
1863 			 * reused.
1864 			 */
1865 			if (pdp->pd_fp == NULL) {
1866 				ASSERT(pdp->pd_count > 0);
1867 				pollfdp[entry].revents = POLLNVAL;
1868 				fdcnt++;
1869 				if (refp->xf_refcnt > 1) {
1870 					/*
1871 					 * this fd appeared multiple time
1872 					 * in the poll list. Find all of them.
1873 					 */
1874 					for (i = entry + 1; i < nfds; i++) {
1875 						if (pollfdp[i].fd == fd) {
1876 							pollfdp[i].revents =
1877 							    POLLNVAL;
1878 							fdcnt++;
1879 						}
1880 					}
1881 				}
1882 				pcacheset_invalidate(ps, pdp);
1883 				continue;
1884 			}
1885 			/*
1886 			 * We can be here polling a device that is being
1887 			 * closed (i.e. the file pointer is set to NULL,
1888 			 * but pollcacheclean has not happened yet).
1889 			 */
1890 			if ((fp = getf(fd)) == NULL) {
1891 				pollfdp[entry].revents = POLLNVAL;
1892 				fdcnt++;
1893 				if (refp->xf_refcnt > 1) {
1894 					/*
1895 					 * this fd appeared multiple time
1896 					 * in the poll list. Find all of them.
1897 					 */
1898 					for (i = entry + 1; i < nfds; i++) {
1899 						if (pollfdp[i].fd == fd) {
1900 							pollfdp[i].revents =
1901 							    POLLNVAL;
1902 							fdcnt++;
1903 						}
1904 					}
1905 				}
1906 				continue;
1907 			}
1908 			ASSERT(pdp->pd_fp == fp);
1909 			ASSERT(infpollinfo(fd));
1910 			/*
1911 			 * Since we no longer hold poll head lock across
1912 			 * VOP_POLL, pollunlock logic can be simplifed.
1913 			 */
1914 			ASSERT(pdp->pd_php == NULL ||
1915 			    MUTEX_NOT_HELD(PHLOCK(pdp->pd_php)));
1916 			/*
1917 			 * underlying file systems may set a "pollpending"
1918 			 * flag when it sees the poll may block. Pollwakeup()
1919 			 * is called by wakeup thread if pollpending is set.
1920 			 * Pass a 0 fdcnt so that the underlying file system
1921 			 * will set the "pollpending" flag set when there is
1922 			 * no polled events.
1923 			 *
1924 			 * Use pollfdp[].events for actual polling because
1925 			 * the pd_events is union of all cached poll events
1926 			 * on this fd. The events parameter also affects
1927 			 * how the polled device sets the "poll pending"
1928 			 * flag.
1929 			 */
1930 			ASSERT(curthread->t_pollcache == NULL);
1931 			error = VOP_POLL(fp->f_vnode, pollfdp[entry].events, 0,
1932 			    &pollfdp[entry].revents, &php);
1933 			/*
1934 			 * releasef after completely done with this cached
1935 			 * poll entry. To prevent close() coming in to clear
1936 			 * this entry.
1937 			 */
1938 			if (error) {
1939 				releasef(fd);
1940 				break;
1941 			}
1942 			/*
1943 			 * layered devices (e.g. console driver)
1944 			 * may change the vnode and thus the pollhead
1945 			 * pointer out from underneath us.
1946 			 */
1947 			if (php != NULL && pdp->pd_php != NULL &&
1948 			    php != pdp->pd_php) {
1949 				releasef(fd);
1950 				pollhead_delete(pdp->pd_php, pdp);
1951 				pdp->pd_php = php;
1952 				pollhead_insert(php, pdp);
1953 				/*
1954 				 * We could have missed a wakeup on the new
1955 				 * target device. Make sure the new target
1956 				 * gets polled once.
1957 				 */
1958 				BT_SET(pcp->pc_bitmap, fd);
1959 				goto retry;
1960 			}
1961 
1962 			if (pollfdp[entry].revents) {
1963 				ASSERT(refp->xf_refcnt >= 1);
1964 				fdcnt++;
1965 				if (refp->xf_refcnt > 1) {
1966 					/*
1967 					 * this fd appeared multiple time
1968 					 * in the poll list. This is rare but
1969 					 * we have to look at all of them for
1970 					 * correctness.
1971 					 */
1972 					error = plist_chkdupfd(fp, pdp, ps,
1973 					    pollfdp, entry, &fdcnt);
1974 					if (error > 0) {
1975 						releasef(fd);
1976 						break;
1977 					}
1978 					if (error < 0) {
1979 						goto retry;
1980 					}
1981 				}
1982 				releasef(fd);
1983 			} else {
1984 				/*
1985 				 * VOP_POLL didn't return any revents. We can
1986 				 * clear the bit in bitmap only if we have the
1987 				 * pollhead ptr cached and no other cached
1988 				 * entry is polling different events on this fd.
1989 				 * VOP_POLL may have dropped the ps_lock. Make
1990 				 * sure pollwakeup has not happened before clear
1991 				 * the bit.
1992 				 */
1993 				if ((pdp->pd_php != NULL) &&
1994 				    (pollfdp[entry].events == pdp->pd_events) &&
1995 				    ((pcp->pc_flag & T_POLLWAKE) == 0)) {
1996 					BT_CLEAR(pcp->pc_bitmap, fd);
1997 				}
1998 				/*
1999 				 * if the fd can be cached now but not before,
2000 				 * do it now.
2001 				 */
2002 				if ((pdp->pd_php == NULL) && (php != NULL)) {
2003 					pdp->pd_php = php;
2004 					pollhead_insert(php, pdp);
2005 					/*
2006 					 * We are inserting a polldat struct for
2007 					 * the first time. We may have missed a
2008 					 * wakeup on this device. Re-poll once.
2009 					 * This should be a rare event.
2010 					 */
2011 					releasef(fd);
2012 					goto retry;
2013 				}
2014 				if (refp->xf_refcnt > 1) {
2015 					/*
2016 					 * this fd appeared multiple time
2017 					 * in the poll list. This is rare but
2018 					 * we have to look at all of them for
2019 					 * correctness.
2020 					 */
2021 					error = plist_chkdupfd(fp, pdp, ps,
2022 					    pollfdp, entry, &fdcnt);
2023 					if (error > 0) {
2024 						releasef(fd);
2025 						break;
2026 					}
2027 					if (error < 0) {
2028 						goto retry;
2029 					}
2030 				}
2031 				releasef(fd);
2032 			}
2033 		} else {
2034 			done = 1;
2035 			ASSERT(pollcheckrevents(ps, begin, end + 1, which));
2036 		}
2037 	}
2038 	if (!error) {
2039 		ASSERT(*fdcntp + fdcnt == pollscanrevents(pcp, pollfdp, nfds));
2040 		*fdcntp += fdcnt;
2041 	}
2042 	return (error);
2043 }
2044 
2045 /*
2046  * Going through the poll list without much locking. Poll all fds and
2047  * cache all valid fds in the pollcache.
2048  */
2049 int
2050 pcacheset_cache_list(pollstate_t *ps, pollfd_t *fds, int *fdcntp, int which)
2051 {
2052 	pollfd_t	*pollfdp = ps->ps_pollfd;
2053 	pollcacheset_t	*pcacheset = ps->ps_pcacheset;
2054 	pollfd_t	*newfdlist;
2055 	int		i;
2056 	int		fd;
2057 	file_t		*fp;
2058 	int		error = 0;
2059 
2060 	ASSERT(MUTEX_HELD(&ps->ps_lock));
2061 	ASSERT(which < ps->ps_nsets);
2062 	ASSERT(pcacheset != NULL);
2063 	ASSERT(pcacheset[which].pcs_pollfd == NULL);
2064 	newfdlist  = kmem_alloc(ps->ps_nfds * sizeof (pollfd_t), KM_SLEEP);
2065 	/*
2066 	 * cache the new poll list in pollcachset.
2067 	 */
2068 	bcopy(pollfdp, newfdlist, sizeof (pollfd_t) * ps->ps_nfds);
2069 
2070 	pcacheset[which].pcs_pollfd = newfdlist;
2071 	pcacheset[which].pcs_nfds = ps->ps_nfds;
2072 	pcacheset[which].pcs_usradr = (uintptr_t)fds;
2073 
2074 	/*
2075 	 * We have saved a copy of current poll fd list in one pollcacheset.
2076 	 * The 'revents' field of the new list is not yet set to 0. Loop
2077 	 * through the new list just to do that is expensive. We do that
2078 	 * while polling the list.
2079 	 */
2080 	for (i = 0; i < ps->ps_nfds; i++) {
2081 		fd = pollfdp[i].fd;
2082 		/*
2083 		 * We also filter out the illegal poll events in the event
2084 		 * field for the cached poll list/set.
2085 		 */
2086 		if (pollfdp[i].events & ~VALID_POLL_EVENTS) {
2087 			newfdlist[i].events = pollfdp[i].events =
2088 			pollfdp[i].events & VALID_POLL_EVENTS;
2089 		}
2090 		if (fd < 0) {
2091 			pollfdp[i].revents = 0;
2092 			continue;
2093 		}
2094 		if ((fp = getf(fd)) == NULL) {
2095 			pollfdp[i].revents = POLLNVAL;
2096 			/*
2097 			 * invalidate this cache entry in the cached poll list
2098 			 */
2099 			newfdlist[i].fd = -1;
2100 			(*fdcntp)++;
2101 			continue;
2102 		}
2103 		/*
2104 		 * cache this fd.
2105 		 */
2106 		error = pcache_insert(ps, fp, &pollfdp[i], fdcntp, (ssize_t)i,
2107 		    which);
2108 		releasef(fd);
2109 		if (error) {
2110 			/*
2111 			 * Here we are half way through caching a new
2112 			 * poll list. Undo every thing.
2113 			 */
2114 			pcacheset_remove_list(ps, pollfdp, 0, i, which, 0);
2115 			kmem_free(newfdlist, ps->ps_nfds * sizeof (pollfd_t));
2116 			pcacheset[which].pcs_pollfd = NULL;
2117 			pcacheset[which].pcs_usradr = NULL;
2118 			break;
2119 		}
2120 	}
2121 	return (error);
2122 }
2123 
2124 /*
2125  * called by pollcacheclean() to set the fp NULL. It also sets polled events
2126  * in pcacheset entries to a special events 'POLLCLOSED'. Do a pollwakeup to
2127  * wake any sleeping poller, then remove the polldat from the driver.
2128  * The routine is called with ps_pcachelock held.
2129  */
2130 void
2131 pcache_clean_entry(pollstate_t *ps, int fd)
2132 {
2133 	pollcache_t	*pcp;
2134 	polldat_t	*pdp;
2135 	int		i;
2136 
2137 	ASSERT(ps != NULL);
2138 	ASSERT(MUTEX_HELD(&ps->ps_lock));
2139 	pcp = ps->ps_pcache;
2140 	ASSERT(pcp);
2141 	pdp = pcache_lookup_fd(pcp, fd);
2142 	ASSERT(pdp != NULL);
2143 	/*
2144 	 * the corresponding fpollinfo in fi_list has been removed by
2145 	 * a close on this fd. Reset the cached fp ptr here.
2146 	 */
2147 	pdp->pd_fp = NULL;
2148 	/*
2149 	 * XXX - This routine also touches data in pcacheset struct.
2150 	 *
2151 	 * set the event in cached poll lists to POLLCLOSED. This invalidate
2152 	 * the cached poll fd entry in that poll list, which will force a
2153 	 * removal of this cached entry in next poll(). The cleanup is done
2154 	 * at the removal time.
2155 	 */
2156 	ASSERT(pdp->pd_ref != NULL);
2157 	for (i = 0; i < ps->ps_nsets; i++) {
2158 		xref_t		*refp;
2159 		pollcacheset_t	*pcsp;
2160 
2161 		refp = &pdp->pd_ref[i];
2162 		if (refp->xf_refcnt) {
2163 			ASSERT(refp->xf_position >= 0);
2164 			pcsp = &ps->ps_pcacheset[i];
2165 			if (refp->xf_refcnt == 1) {
2166 				pcsp->pcs_pollfd[refp->xf_position].events =
2167 				    (short)POLLCLOSED;
2168 			}
2169 			if (refp->xf_refcnt > 1) {
2170 				int	j;
2171 				/*
2172 				 * mark every matching entry in pcs_pollfd
2173 				 */
2174 				for (j = refp->xf_position;
2175 				    j < pcsp->pcs_nfds; j++) {
2176 					if (pcsp->pcs_pollfd[j].fd == fd) {
2177 						pcsp->pcs_pollfd[j].events =
2178 						    (short)POLLCLOSED;
2179 					}
2180 				}
2181 			}
2182 		}
2183 	}
2184 	if (pdp->pd_php) {
2185 		pollwakeup(pdp->pd_php, POLLHUP);
2186 		pollhead_delete(pdp->pd_php, pdp);
2187 		pdp->pd_php = NULL;
2188 	}
2189 }
2190 
2191 /*
2192  * This is the first time this thread has ever polled,
2193  * so we have to create its pollstate structure.
2194  * This will persist for the life of the thread,
2195  * until it calls pollcleanup().
2196  */
2197 pollstate_t *
2198 pollstate_create(void)
2199 {
2200 	pollstate_t *ps;
2201 
2202 	ps = kmem_zalloc(sizeof (pollstate_t), KM_SLEEP);
2203 	ps->ps_nsets = POLLFDSETS;
2204 	ps->ps_pcacheset = pcacheset_create(ps->ps_nsets);
2205 	return (ps);
2206 }
2207 
2208 void
2209 pollstate_destroy(pollstate_t *ps)
2210 {
2211 	if (ps->ps_pollfd != NULL) {
2212 		kmem_free(ps->ps_pollfd, ps->ps_nfds * sizeof (pollfd_t));
2213 		ps->ps_pollfd = NULL;
2214 	}
2215 	if (ps->ps_pcache != NULL) {
2216 		pcache_destroy(ps->ps_pcache);
2217 		ps->ps_pcache = NULL;
2218 	}
2219 	pcacheset_destroy(ps->ps_pcacheset, ps->ps_nsets);
2220 	ps->ps_pcacheset = NULL;
2221 	if (ps->ps_dpbuf != NULL) {
2222 		kmem_free(ps->ps_dpbuf, ps->ps_dpbufsize * sizeof (pollfd_t));
2223 		ps->ps_dpbuf = NULL;
2224 	}
2225 	mutex_destroy(&ps->ps_lock);
2226 	kmem_free(ps, sizeof (pollstate_t));
2227 }
2228 
2229 /*
2230  * We are holding the appropriate uf_lock entering this routine.
2231  * Bump up the ps_busy count to prevent the thread from exiting.
2232  */
2233 void
2234 pollblockexit(fpollinfo_t *fpip)
2235 {
2236 	for (; fpip; fpip = fpip->fp_next) {
2237 		pollcache_t *pcp = fpip->fp_thread->t_pollstate->ps_pcache;
2238 
2239 		mutex_enter(&pcp->pc_no_exit);
2240 		pcp->pc_busy++;  /* prevents exit()'s */
2241 		mutex_exit(&pcp->pc_no_exit);
2242 	}
2243 }
2244 
2245 /*
2246  * Complete phase 2 of cached poll fd cleanup. Call pcache_clean_entry to mark
2247  * the pcacheset events field POLLCLOSED to force the next poll() to remove
2248  * this cache entry. We can't clean the polldat entry clean up here because
2249  * lwp block in poll() needs the info to return. Wakeup anyone blocked in
2250  * poll and let exiting lwp go. No lock is help upon entry. So it's OK for
2251  * pcache_clean_entry to call pollwakeup().
2252  */
2253 void
2254 pollcacheclean(fpollinfo_t *fip, int fd)
2255 {
2256 	struct fpollinfo	*fpip, *fpip2;
2257 
2258 	fpip = fip;
2259 	while (fpip) {
2260 		pollstate_t *ps = fpip->fp_thread->t_pollstate;
2261 		pollcache_t *pcp = ps->ps_pcache;
2262 
2263 		mutex_enter(&ps->ps_lock);
2264 		pcache_clean_entry(ps, fd);
2265 		mutex_exit(&ps->ps_lock);
2266 		mutex_enter(&pcp->pc_no_exit);
2267 		pcp->pc_busy--;
2268 		if (pcp->pc_busy == 0) {
2269 			/*
2270 			 * Wakeup the thread waiting in
2271 			 * thread_exit().
2272 			 */
2273 			cv_signal(&pcp->pc_busy_cv);
2274 		}
2275 		mutex_exit(&pcp->pc_no_exit);
2276 
2277 		fpip2 = fpip;
2278 		fpip = fpip->fp_next;
2279 		kmem_free(fpip2, sizeof (fpollinfo_t));
2280 	}
2281 }
2282 
2283 /*
2284  * one of the cache line's counter is wrapping around. Reset all cache line
2285  * counters to zero except one. This is simplistic, but probably works
2286  * effectively.
2287  */
2288 void
2289 pcacheset_reset_count(pollstate_t *ps, int index)
2290 {
2291 	int	i;
2292 
2293 	ASSERT(MUTEX_HELD(&ps->ps_lock));
2294 	for (i = 0; i < ps->ps_nsets; i++) {
2295 		if (ps->ps_pcacheset[i].pcs_pollfd != NULL) {
2296 			ps->ps_pcacheset[i].pcs_count = 0;
2297 		}
2298 	}
2299 	ps->ps_pcacheset[index].pcs_count = 1;
2300 }
2301 
2302 /*
2303  * this routine implements poll cache list replacement policy.
2304  * It is currently choose the "least used".
2305  */
2306 int
2307 pcacheset_replace(pollstate_t *ps)
2308 {
2309 	int i;
2310 	int index = 0;
2311 
2312 	ASSERT(MUTEX_HELD(&ps->ps_lock));
2313 	for (i = 1; i < ps->ps_nsets; i++) {
2314 		if (ps->ps_pcacheset[index].pcs_count >
2315 		    ps->ps_pcacheset[i].pcs_count) {
2316 			index = i;
2317 		}
2318 	}
2319 	ps->ps_pcacheset[index].pcs_count = 0;
2320 	return (index);
2321 }
2322 
2323 /*
2324  * this routine is called by strclose to remove remaining polldat struct on
2325  * the pollhead list of the device being closed. There are two reasons as why
2326  * the polldat structures still remain on the pollhead list:
2327  *
2328  * (1) The layered device(e.g.the console driver).
2329  * In this case, the existence of a polldat implies that the thread putting
2330  * the polldat on this list has not exited yet. Before the thread exits, it
2331  * will have to hold this pollhead lock to remove the polldat. So holding the
2332  * pollhead lock here effectively prevents the thread which put the polldat
2333  * on this list from exiting.
2334  *
2335  * (2) /dev/poll.
2336  * When a polled fd is cached in /dev/poll, its polldat will remain on the
2337  * pollhead list if the process has not done a POLLREMOVE before closing the
2338  * polled fd. We just unlink it here.
2339  */
2340 void
2341 pollhead_clean(pollhead_t *php)
2342 {
2343 	polldat_t	*pdp;
2344 
2345 	/*
2346 	 * In case(1), while we must prevent the thread in question from
2347 	 * exiting, we must also obey the proper locking order, i.e.
2348 	 * (ps_lock -> phlock).
2349 	 */
2350 	PH_ENTER(php);
2351 	while (php->ph_list != NULL) {
2352 		pollstate_t	*ps;
2353 		pollcache_t	*pcp;
2354 
2355 		pdp = php->ph_list;
2356 		ASSERT(pdp->pd_php == php);
2357 		if (pdp->pd_thread == NULL) {
2358 			/*
2359 			 * This is case(2). Since the ph_lock is sufficient
2360 			 * to synchronize this lwp with any other /dev/poll
2361 			 * lwp, just unlink the polldat.
2362 			 */
2363 			php->ph_list = pdp->pd_next;
2364 			pdp->pd_php = NULL;
2365 			pdp->pd_next = NULL;
2366 			continue;
2367 		}
2368 		ps = pdp->pd_thread->t_pollstate;
2369 		ASSERT(ps != NULL);
2370 		pcp = pdp->pd_pcache;
2371 		ASSERT(pcp != NULL);
2372 		mutex_enter(&pcp->pc_no_exit);
2373 		pcp->pc_busy++;  /* prevents exit()'s */
2374 		mutex_exit(&pcp->pc_no_exit);
2375 		/*
2376 		 * Now get the locks in proper order to avoid deadlock.
2377 		 */
2378 		PH_EXIT(php);
2379 		mutex_enter(&ps->ps_lock);
2380 		/*
2381 		 * while we dropped the pollhead lock, the element could be
2382 		 * taken off the list already.
2383 		 */
2384 		PH_ENTER(php);
2385 		if (pdp->pd_php == php) {
2386 			ASSERT(pdp == php->ph_list);
2387 			php->ph_list = pdp->pd_next;
2388 			pdp->pd_php = NULL;
2389 			pdp->pd_next = NULL;
2390 		}
2391 		PH_EXIT(php);
2392 		mutex_exit(&ps->ps_lock);
2393 		mutex_enter(&pcp->pc_no_exit);
2394 		pcp->pc_busy--;
2395 		if (pcp->pc_busy == 0) {
2396 			/*
2397 			 * Wakeup the thread waiting in
2398 			 * thread_exit().
2399 			 */
2400 			cv_signal(&pcp->pc_busy_cv);
2401 		}
2402 		mutex_exit(&pcp->pc_no_exit);
2403 		PH_ENTER(php);
2404 	}
2405 	PH_EXIT(php);
2406 }
2407 
2408 /*
2409  * The remove_list is called to cleanup a partially cached 'current' list or
2410  * to remove a partial list which is no longer cached. The flag value of 1
2411  * indicates the second case.
2412  */
2413 void
2414 pcacheset_remove_list(pollstate_t *ps, pollfd_t *pollfdp, int start, int end,
2415     int cacheindex, int flag)
2416 {
2417 	int i;
2418 
2419 	ASSERT(MUTEX_HELD(&ps->ps_lock));
2420 	for (i = start; i < end; i++) {
2421 		if ((pollfdp[i].fd >= 0) &&
2422 		    (flag || !(pollfdp[i].revents & POLLNVAL))) {
2423 			if (pcache_delete_fd(ps, pollfdp[i].fd, i, cacheindex,
2424 			    (uint_t)pollfdp[i].events)) {
2425 				int j;
2426 				int fd = pollfdp[i].fd;
2427 
2428 				for (j = i + 1; j < end; j++) {
2429 					if (pollfdp[j].fd == fd) {
2430 						pcache_update_xref(
2431 						    ps->ps_pcache, fd,
2432 						    (ssize_t)j, cacheindex);
2433 						break;
2434 					}
2435 				}
2436 				ASSERT(j <= end);
2437 			}
2438 		}
2439 	}
2440 }
2441 
2442 #ifdef DEBUG
2443 
2444 #include<sys/strsubr.h>
2445 /*
2446  * make sure curthread is not on anyone's pollhead list any more.
2447  */
2448 static void
2449 pollcheckphlist()
2450 {
2451 	int i;
2452 	file_t *fp;
2453 	uf_entry_t *ufp;
2454 	uf_info_t *fip = P_FINFO(curproc);
2455 	struct stdata *stp;
2456 	polldat_t *pdp;
2457 
2458 	mutex_enter(&fip->fi_lock);
2459 	for (i = 0; i < fip->fi_nfiles; i++) {
2460 		UF_ENTER(ufp, fip, i);
2461 		if ((fp = ufp->uf_file) != NULL) {
2462 			if ((stp = fp->f_vnode->v_stream) != NULL) {
2463 				PH_ENTER(&stp->sd_pollist);
2464 				pdp = stp->sd_pollist.ph_list;
2465 				while (pdp) {
2466 					ASSERT(pdp->pd_thread != curthread);
2467 					pdp = pdp->pd_next;
2468 				}
2469 				PH_EXIT(&stp->sd_pollist);
2470 			}
2471 		}
2472 		UF_EXIT(ufp);
2473 	}
2474 	mutex_exit(&fip->fi_lock);
2475 }
2476 
2477 /*
2478  * for resolved set poll list, the xref info in the pcache should be
2479  * consistent with this poll list.
2480  */
2481 static int
2482 pollcheckxref(pollstate_t *ps, int cacheindex)
2483 {
2484 	pollfd_t *pollfdp = ps->ps_pcacheset[cacheindex].pcs_pollfd;
2485 	pollcache_t *pcp = ps->ps_pcache;
2486 	polldat_t *pdp;
2487 	int	i;
2488 	xref_t	*refp;
2489 
2490 	for (i = 0; i < ps->ps_pcacheset[cacheindex].pcs_nfds; i++) {
2491 		if (pollfdp[i].fd < 0) {
2492 			continue;
2493 		}
2494 		pdp = pcache_lookup_fd(pcp, pollfdp[i].fd);
2495 		ASSERT(pdp != NULL);
2496 		ASSERT(pdp->pd_ref != NULL);
2497 		refp = &pdp->pd_ref[cacheindex];
2498 		if (refp->xf_position >= 0) {
2499 			ASSERT(refp->xf_refcnt >= 1);
2500 			ASSERT(pollfdp[refp->xf_position].fd == pdp->pd_fd);
2501 			if (refp->xf_refcnt > 1) {
2502 				int	j;
2503 				int	count = 0;
2504 
2505 				for (j = refp->xf_position;
2506 				    j < ps->ps_pcacheset[cacheindex].pcs_nfds;
2507 				    j++) {
2508 					if (pollfdp[j].fd == pdp->pd_fd) {
2509 						count++;
2510 					}
2511 				}
2512 				ASSERT(count == refp->xf_refcnt);
2513 			}
2514 		}
2515 	}
2516 	return (1);
2517 }
2518 
2519 /*
2520  * For every cached pollfd, its polldat struct should be consistent with
2521  * what is in the pcacheset lists.
2522  */
2523 static void
2524 checkpolldat(pollstate_t *ps)
2525 {
2526 	pollcache_t	*pcp = ps->ps_pcache;
2527 	polldat_t	**hashtbl;
2528 	int		i;
2529 
2530 	hashtbl = pcp->pc_hash;
2531 	for (i = 0; i < pcp->pc_hashsize; i++) {
2532 		polldat_t	*pdp;
2533 
2534 		for (pdp = hashtbl[i]; pdp; pdp = pdp->pd_hashnext) {
2535 			ASSERT(pdp->pd_ref != NULL);
2536 			if (pdp->pd_count > 0) {
2537 				xref_t		*refp;
2538 				int		j;
2539 				pollcacheset_t	*pcsp;
2540 				pollfd_t	*pollfd;
2541 
2542 				for (j = 0; j < ps->ps_nsets; j++) {
2543 					refp = &pdp->pd_ref[j];
2544 					if (refp->xf_refcnt > 0) {
2545 						pcsp = &ps->ps_pcacheset[j];
2546 				ASSERT(refp->xf_position < pcsp->pcs_nfds);
2547 						pollfd = pcsp->pcs_pollfd;
2548 			ASSERT(pdp->pd_fd == pollfd[refp->xf_position].fd);
2549 					}
2550 				}
2551 			}
2552 		}
2553 	}
2554 }
2555 
2556 /*
2557  * every wfd element on ph_list must have a corresponding fpollinfo on the
2558  * uf_fpollinfo list. This is a variation of infpollinfo() w/o holding locks.
2559  */
2560 void
2561 checkwfdlist(vnode_t *vp, fpollinfo_t *fpip)
2562 {
2563 	stdata_t *stp;
2564 	polldat_t *pdp;
2565 	fpollinfo_t *fpip2;
2566 
2567 	if ((stp = vp->v_stream) == NULL) {
2568 		return;
2569 	}
2570 	PH_ENTER(&stp->sd_pollist);
2571 	for (pdp = stp->sd_pollist.ph_list; pdp; pdp = pdp->pd_next) {
2572 		if (pdp->pd_thread->t_procp == curthread->t_procp) {
2573 			for (fpip2 = fpip; fpip2; fpip2 = fpip2->fp_next) {
2574 				if (pdp->pd_thread == fpip2->fp_thread) {
2575 					break;
2576 				}
2577 			}
2578 			ASSERT(fpip2 != NULL);
2579 		}
2580 	}
2581 	PH_EXIT(&stp->sd_pollist);
2582 }
2583 
2584 /*
2585  * For each cached fd whose bit is not set in bitmap, its revents field in
2586  * current poll list should be 0.
2587  */
2588 static int
2589 pollcheckrevents(pollstate_t *ps, int begin, int end, int cacheindex)
2590 {
2591 	pollcache_t	*pcp = ps->ps_pcache;
2592 	pollfd_t	*pollfdp = ps->ps_pollfd;
2593 	int		i;
2594 
2595 	for (i = begin; i < end; i++) {
2596 		polldat_t	*pdp;
2597 
2598 		ASSERT(!BT_TEST(pcp->pc_bitmap, i));
2599 		pdp = pcache_lookup_fd(pcp, i);
2600 		if (pdp && pdp->pd_fp != NULL) {
2601 			xref_t *refp;
2602 			int entry;
2603 
2604 			ASSERT(pdp->pd_ref != NULL);
2605 			refp = &pdp->pd_ref[cacheindex];
2606 			if (refp->xf_refcnt == 0) {
2607 				continue;
2608 			}
2609 			entry = refp->xf_position;
2610 			ASSERT(entry >= 0);
2611 			ASSERT(pollfdp[entry].revents == 0);
2612 			if (refp->xf_refcnt > 1) {
2613 				int j;
2614 
2615 				for (j = entry + 1; j < ps->ps_nfds; j++) {
2616 					if (pollfdp[j].fd == i) {
2617 						ASSERT(pollfdp[j].revents == 0);
2618 					}
2619 				}
2620 			}
2621 		}
2622 	}
2623 	return (1);
2624 }
2625 
2626 #endif	/* DEBUG */
2627 
2628 pollcache_t *
2629 pcache_alloc()
2630 {
2631 	return (kmem_zalloc(sizeof (pollcache_t), KM_SLEEP));
2632 }
2633 
2634 void
2635 pcache_create(pollcache_t *pcp, nfds_t nfds)
2636 {
2637 	size_t	mapsize;
2638 
2639 	/*
2640 	 * allocate enough bits for the poll fd list
2641 	 */
2642 	if ((mapsize = POLLMAPCHUNK) <= nfds) {
2643 		mapsize = (nfds + POLLMAPCHUNK - 1) & ~(POLLMAPCHUNK - 1);
2644 	}
2645 	pcp->pc_bitmap = kmem_zalloc((mapsize / BT_NBIPUL) * sizeof (ulong_t),
2646 	    KM_SLEEP);
2647 	pcp->pc_mapsize = mapsize;
2648 	/*
2649 	 * The hash size is at least POLLHASHCHUNKSZ. If user polls a large
2650 	 * number of fd to start with, allocate a bigger hash table (to the
2651 	 * nearest multiple of POLLHASHCHUNKSZ) because dynamically growing a
2652 	 * hash table is expensive.
2653 	 */
2654 	if (nfds < POLLHASHCHUNKSZ) {
2655 		pcp->pc_hashsize = POLLHASHCHUNKSZ;
2656 	} else {
2657 		pcp->pc_hashsize = (nfds + POLLHASHCHUNKSZ - 1) &
2658 		    ~(POLLHASHCHUNKSZ - 1);
2659 	}
2660 	pcp->pc_hash = kmem_zalloc(pcp->pc_hashsize * sizeof (polldat_t *),
2661 	    KM_SLEEP);
2662 }
2663 
2664 void
2665 pcache_destroy(pollcache_t *pcp)
2666 {
2667 	polldat_t	**hashtbl;
2668 	int i;
2669 
2670 	hashtbl = pcp->pc_hash;
2671 	for (i = 0; i < pcp->pc_hashsize; i++) {
2672 		if (hashtbl[i] != NULL) {
2673 			polldat_t *pdp, *pdp2;
2674 
2675 			pdp = hashtbl[i];
2676 			while (pdp != NULL) {
2677 				pdp2 = pdp->pd_hashnext;
2678 				if (pdp->pd_ref != NULL) {
2679 					kmem_free(pdp->pd_ref, sizeof (xref_t) *
2680 					    pdp->pd_nsets);
2681 				}
2682 				kmem_free(pdp, sizeof (polldat_t));
2683 				pdp = pdp2;
2684 				pcp->pc_fdcount--;
2685 			}
2686 		}
2687 	}
2688 	ASSERT(pcp->pc_fdcount == 0);
2689 	kmem_free(pcp->pc_hash, sizeof (polldat_t *) * pcp->pc_hashsize);
2690 	kmem_free(pcp->pc_bitmap,
2691 	    sizeof (ulong_t) * (pcp->pc_mapsize/BT_NBIPUL));
2692 	mutex_destroy(&pcp->pc_no_exit);
2693 	mutex_destroy(&pcp->pc_lock);
2694 	cv_destroy(&pcp->pc_cv);
2695 	cv_destroy(&pcp->pc_busy_cv);
2696 	kmem_free(pcp, sizeof (pollcache_t));
2697 }
2698 
2699 pollcacheset_t *
2700 pcacheset_create(int nsets)
2701 {
2702 	return (kmem_zalloc(sizeof (pollcacheset_t) * nsets, KM_SLEEP));
2703 }
2704 
2705 void
2706 pcacheset_destroy(pollcacheset_t *pcsp, int nsets)
2707 {
2708 	int i;
2709 
2710 	for (i = 0; i < nsets; i++) {
2711 		if (pcsp[i].pcs_pollfd != NULL) {
2712 			kmem_free(pcsp[i].pcs_pollfd, pcsp[i].pcs_nfds *
2713 			    sizeof (pollfd_t));
2714 		}
2715 	}
2716 	kmem_free(pcsp, sizeof (pollcacheset_t) * nsets);
2717 }
2718 
2719 /*
2720  * Check each duplicated poll fd in the poll list. It may be necessary to
2721  * VOP_POLL the same fd again using different poll events. getf() has been
2722  * done by caller. This routine returns 0 if it can sucessfully process the
2723  * entire poll fd list. It returns -1 if underlying vnode has changed during
2724  * a VOP_POLL, in which case the caller has to repoll. It returns a positive
2725  * value if VOP_POLL failed.
2726  */
2727 static int
2728 plist_chkdupfd(file_t *fp, polldat_t *pdp, pollstate_t *psp, pollfd_t *pollfdp,
2729     int entry, int *fdcntp)
2730 {
2731 	int	i;
2732 	int	fd;
2733 	nfds_t	nfds = psp->ps_nfds;
2734 
2735 	fd = pollfdp[entry].fd;
2736 	for (i = entry + 1; i < nfds; i++) {
2737 		if (pollfdp[i].fd == fd) {
2738 			if (pollfdp[i].events == pollfdp[entry].events) {
2739 				if ((pollfdp[i].revents =
2740 				    pollfdp[entry].revents) != 0) {
2741 					(*fdcntp)++;
2742 				}
2743 			} else {
2744 
2745 				int	error;
2746 				pollhead_t *php;
2747 				pollcache_t *pcp = psp->ps_pcache;
2748 
2749 				/*
2750 				 * the events are different. VOP_POLL on this
2751 				 * fd so that we don't miss any revents.
2752 				 */
2753 				php = NULL;
2754 				ASSERT(curthread->t_pollcache == NULL);
2755 				error = VOP_POLL(fp->f_vnode,
2756 				    pollfdp[i].events, 0,
2757 				    &pollfdp[i].revents, &php);
2758 				if (error) {
2759 					return (error);
2760 				}
2761 				/*
2762 				 * layered devices(e.g. console driver)
2763 				 * may change the vnode and thus the pollhead
2764 				 * pointer out from underneath us.
2765 				 */
2766 				if (php != NULL && pdp->pd_php != NULL &&
2767 				    php != pdp->pd_php) {
2768 					pollhead_delete(pdp->pd_php, pdp);
2769 					pdp->pd_php = php;
2770 					pollhead_insert(php, pdp);
2771 					/*
2772 					 * We could have missed a wakeup on the
2773 					 * new target device. Make sure the new
2774 					 * target gets polled once.
2775 					 */
2776 					BT_SET(pcp->pc_bitmap, fd);
2777 					return (-1);
2778 				}
2779 				if (pollfdp[i].revents) {
2780 					(*fdcntp)++;
2781 				}
2782 			}
2783 		}
2784 	}
2785 	return (0);
2786 }
2787