xref: /titanic_41/usr/src/uts/common/syscall/poll.c (revision 3afe87ebb25691cb6d158edaa34a6fb9b703a691)
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 2008 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_timedwait_sig() just to check for signals.
327 		 * We will return immediately with either 0 or -1.
328 		 */
329 		if (!cv_timedwait_sig(&t->t_delay_cv, &p->p_lock, lbolt)) {
330 			mutex_exit(&p->p_lock);
331 			error = EINTR;
332 			goto pollout;
333 		}
334 		mutex_exit(&p->p_lock);
335 	}
336 
337 	/*
338 	 * Check to see if this guy just wants to use poll() as a timeout.
339 	 * If yes then bypass all the other stuff and make him sleep.
340 	 */
341 	if (nfds == 0) {
342 		/*
343 		 * Sleep until we have passed the requested future
344 		 * time or until interrupted by a signal.
345 		 * Do not check for signals if we have a zero timeout.
346 		 */
347 		if (!imm_timeout) {
348 			mutex_enter(&t->t_delay_lock);
349 			while ((rval = cv_waituntil_sig(&t->t_delay_cv,
350 			    &t->t_delay_lock, rqtp, timecheck)) > 0)
351 				continue;
352 			mutex_exit(&t->t_delay_lock);
353 			if (rval == 0)
354 				error = EINTR;
355 		}
356 		goto pollout;
357 	}
358 
359 	if (nfds > p->p_fno_ctl) {
360 		mutex_enter(&p->p_lock);
361 		(void) rctl_action(rctlproc_legacy[RLIMIT_NOFILE],
362 		    p->p_rctls, p, RCA_SAFE);
363 		mutex_exit(&p->p_lock);
364 		error = EINVAL;
365 		goto pollout;
366 	}
367 
368 	/*
369 	 * Need to allocate memory for pollstate before anything because
370 	 * the mutex and cv are created in this space
371 	 */
372 	if ((ps = t->t_pollstate) == NULL) {
373 		t->t_pollstate = pollstate_create();
374 		ps = t->t_pollstate;
375 	}
376 
377 	if (ps->ps_pcache == NULL)
378 		ps->ps_pcache = pcache_alloc();
379 	pcp = ps->ps_pcache;
380 
381 	/*
382 	 * NOTE: for performance, buffers are saved across poll() calls.
383 	 * The theory is that if a process polls heavily, it tends to poll
384 	 * on the same set of descriptors.  Therefore, we only reallocate
385 	 * buffers when nfds changes.  There is no hysteresis control,
386 	 * because there is no data to suggest that this is necessary;
387 	 * the penalty of reallocating is not *that* great in any event.
388 	 */
389 	old_nfds = ps->ps_nfds;
390 	if (nfds != old_nfds) {
391 
392 		kmem_free(ps->ps_pollfd, old_nfds * sizeof (pollfd_t));
393 		pollfdp = kmem_alloc(nfds * sizeof (pollfd_t), KM_SLEEP);
394 		ps->ps_pollfd = pollfdp;
395 		ps->ps_nfds = nfds;
396 	}
397 
398 	pollfdp = ps->ps_pollfd;
399 	if (copyin(fds, pollfdp, nfds * sizeof (pollfd_t))) {
400 		error = EFAULT;
401 		goto pollout;
402 	}
403 
404 	if (fds == NULL) {
405 		/*
406 		 * If the process has page 0 mapped, then the copyin() above
407 		 * will succeed even if fds is NULL.  However, our cached
408 		 * poll lists are keyed by the address of the passed-in fds
409 		 * structure, and we use the value NULL to indicate an unused
410 		 * poll cache list entry.  As such, we elect not to support
411 		 * NULL as a valid (user) memory address and fail the poll()
412 		 * call.
413 		 */
414 		error = EINVAL;
415 		goto pollout;
416 	}
417 
418 	/*
419 	 * If this thread polls for the first time, allocate ALL poll
420 	 * cache data structures and cache the poll fd list. This
421 	 * allocation is delayed till now because lwp's polling 0 fd
422 	 * (i.e. using poll as timeout()) don't need this memory.
423 	 */
424 	mutex_enter(&ps->ps_lock);
425 	pcp = ps->ps_pcache;
426 	ASSERT(pcp != NULL);
427 	if (pcp->pc_bitmap == NULL) {
428 		pcache_create(pcp, nfds);
429 		/*
430 		 * poll and cache this poll fd list in ps_pcacheset[0].
431 		 */
432 		error = pcacheset_cache_list(ps, fds, &fdcnt, cacheindex);
433 		if (fdcnt || error) {
434 			mutex_exit(&ps->ps_lock);
435 			goto pollout;
436 		}
437 	} else {
438 		pollcacheset_t	*pcset = ps->ps_pcacheset;
439 
440 		/*
441 		 * Not first time polling. Select a cached poll list by
442 		 * matching user pollfd list buffer address.
443 		 */
444 		for (cacheindex = 0; cacheindex < ps->ps_nsets; cacheindex++) {
445 			if (pcset[cacheindex].pcs_usradr == (uintptr_t)fds) {
446 				if ((++pcset[cacheindex].pcs_count) == 0) {
447 					/*
448 					 * counter is wrapping around.
449 					 */
450 					pcacheset_reset_count(ps, cacheindex);
451 				}
452 				/*
453 				 * examine and resolve possible
454 				 * difference of the current poll
455 				 * list and previously cached one.
456 				 * If there is an error during resolve(),
457 				 * the callee will guarantee the consistency
458 				 * of cached poll list and cache content.
459 				 */
460 				error = pcacheset_resolve(ps, nfds, &fdcnt,
461 				    cacheindex);
462 				if (error) {
463 					mutex_exit(&ps->ps_lock);
464 					goto pollout;
465 				}
466 				break;
467 			}
468 
469 			/*
470 			 * Note that pcs_usradr field of an used entry won't be
471 			 * NULL because it stores the address of passed-in fds,
472 			 * and NULL fds will not be cached (Then it is either
473 			 * the special timeout case when nfds is 0 or it returns
474 			 * failure directly).
475 			 */
476 			if (pcset[cacheindex].pcs_usradr == NULL) {
477 				/*
478 				 * found an unused entry. Use it to cache
479 				 * this poll list.
480 				 */
481 				error = pcacheset_cache_list(ps, fds, &fdcnt,
482 				    cacheindex);
483 				if (fdcnt || error) {
484 					mutex_exit(&ps->ps_lock);
485 					goto pollout;
486 				}
487 				break;
488 			}
489 		}
490 		if (cacheindex == ps->ps_nsets) {
491 			/*
492 			 * We failed to find a matching cached poll fd list.
493 			 * replace an old list.
494 			 */
495 			pollstats.polllistmiss.value.ui64++;
496 			cacheindex = pcacheset_replace(ps);
497 			ASSERT(cacheindex < ps->ps_nsets);
498 			pcset[cacheindex].pcs_usradr = (uintptr_t)fds;
499 			error = pcacheset_resolve(ps, nfds, &fdcnt, cacheindex);
500 			if (error) {
501 				mutex_exit(&ps->ps_lock);
502 				goto pollout;
503 			}
504 		}
505 	}
506 
507 	/*
508 	 * Always scan the bitmap with the lock on the pollcache held.
509 	 * This is to make sure that a wakeup does not come undetected.
510 	 * If the lock is not held, a pollwakeup could have come for an
511 	 * fd we already checked but before this thread sleeps, in which
512 	 * case the wakeup is missed. Now we hold the pcache lock and
513 	 * check the bitmap again. This will prevent wakeup from happening
514 	 * while we hold pcache lock since pollwakeup() will also lock
515 	 * the pcache before updating poll bitmap.
516 	 */
517 	mutex_enter(&pcp->pc_lock);
518 	for (;;) {
519 		pcp->pc_flag = 0;
520 		error = pcache_poll(pollfdp, ps, nfds, &fdcnt, cacheindex);
521 		if (fdcnt || error) {
522 			mutex_exit(&pcp->pc_lock);
523 			mutex_exit(&ps->ps_lock);
524 			break;
525 		}
526 
527 		/*
528 		 * If T_POLLWAKE is set, a pollwakeup() was performed on
529 		 * one of the file descriptors.  This can happen only if
530 		 * one of the VOP_POLL() functions dropped pcp->pc_lock.
531 		 * The only current cases of this is in procfs (prpoll())
532 		 * and STREAMS (strpoll()).
533 		 */
534 		if (pcp->pc_flag & T_POLLWAKE)
535 			continue;
536 
537 		/*
538 		 * If you get here, the poll of fds was unsuccessful.
539 		 * Wait until some fd becomes readable, writable, or gets
540 		 * an exception, or until a signal or a timeout occurs.
541 		 * Do not check for signals if we have a zero timeout.
542 		 */
543 		mutex_exit(&ps->ps_lock);
544 		if (imm_timeout)
545 			rval = -1;
546 		else
547 			rval = cv_waituntil_sig(&pcp->pc_cv, &pcp->pc_lock,
548 			    rqtp, timecheck);
549 		mutex_exit(&pcp->pc_lock);
550 		/*
551 		 * If we have received a signal or timed out
552 		 * then break out and return.
553 		 */
554 		if (rval <= 0) {
555 			if (rval == 0)
556 				error = EINTR;
557 			break;
558 		}
559 		/*
560 		 * We have not received a signal or timed out.
561 		 * Continue around and poll fds again.
562 		 */
563 		mutex_enter(&ps->ps_lock);
564 		mutex_enter(&pcp->pc_lock);
565 	}
566 
567 pollout:
568 	/*
569 	 * If we changed the signal mask but we received
570 	 * no signal then restore the signal mask.
571 	 * Otherwise psig() will deal with the signal mask.
572 	 */
573 	if (ksetp != NULL) {
574 		mutex_enter(&p->p_lock);
575 		if (lwp->lwp_cursig == 0) {
576 			t->t_hold = lwp->lwp_sigoldmask;
577 			t->t_flag &= ~T_TOMASK;
578 		}
579 		mutex_exit(&p->p_lock);
580 	}
581 
582 	if (error)
583 		return (set_errno(error));
584 
585 	/*
586 	 * Copy out the events and return the fdcnt to the user.
587 	 */
588 	if (nfds != 0 &&
589 	    copyout(pollfdp, fds, nfds * sizeof (pollfd_t)))
590 		return (set_errno(EFAULT));
591 
592 #ifdef DEBUG
593 	/*
594 	 * Another sanity check:
595 	 */
596 	if (fdcnt) {
597 		int	reventcnt = 0;
598 
599 		for (i = 0; i < nfds; i++) {
600 			if (pollfdp[i].fd < 0) {
601 				ASSERT(pollfdp[i].revents == 0);
602 				continue;
603 			}
604 			if (pollfdp[i].revents) {
605 				reventcnt++;
606 			}
607 		}
608 		ASSERT(fdcnt == reventcnt);
609 	} else {
610 		for (i = 0; i < nfds; i++) {
611 			ASSERT(pollfdp[i].revents == 0);
612 		}
613 	}
614 #endif	/* DEBUG */
615 
616 	return (fdcnt);
617 }
618 
619 /*
620  * This system call trap exists solely for binary compatibility with
621  * old statically-linked applications.  It is not called from libc.
622  * It should be removed in the next release.
623  */
624 int
625 poll(pollfd_t *fds, nfds_t nfds, int time_out)
626 {
627 	timespec_t ts;
628 	timespec_t *tsp;
629 
630 	if (time_out < 0)
631 		tsp = NULL;
632 	else {
633 		ts.tv_sec = time_out / MILLISEC;
634 		ts.tv_nsec = (time_out % MILLISEC) * MICROSEC;
635 		tsp = &ts;
636 	}
637 
638 	return (poll_common(fds, nfds, tsp, NULL));
639 }
640 
641 /*
642  * This is the system call trap that poll(),
643  * select() and pselect() are built upon.
644  * It is a private interface between libc and the kernel.
645  */
646 int
647 pollsys(pollfd_t *fds, nfds_t nfds, timespec_t *timeoutp, sigset_t *setp)
648 {
649 	timespec_t ts;
650 	timespec_t *tsp;
651 	sigset_t set;
652 	k_sigset_t kset;
653 	k_sigset_t *ksetp;
654 	model_t datamodel = get_udatamodel();
655 
656 	if (timeoutp == NULL)
657 		tsp = NULL;
658 	else {
659 		if (datamodel == DATAMODEL_NATIVE) {
660 			if (copyin(timeoutp, &ts, sizeof (ts)))
661 				return (set_errno(EFAULT));
662 		} else {
663 			timespec32_t ts32;
664 
665 			if (copyin(timeoutp, &ts32, sizeof (ts32)))
666 				return (set_errno(EFAULT));
667 			TIMESPEC32_TO_TIMESPEC(&ts, &ts32)
668 		}
669 
670 		if (itimerspecfix(&ts))
671 			return (set_errno(EINVAL));
672 		tsp = &ts;
673 	}
674 
675 	if (setp == NULL)
676 		ksetp = NULL;
677 	else {
678 		if (copyin(setp, &set, sizeof (set)))
679 			return (set_errno(EFAULT));
680 		sigutok(&set, &kset);
681 		ksetp = &kset;
682 	}
683 
684 	return (poll_common(fds, nfds, tsp, ksetp));
685 }
686 
687 /*
688  * Clean up any state left around by poll(2). Called when a thread exits.
689  */
690 void
691 pollcleanup()
692 {
693 	pollstate_t *ps = curthread->t_pollstate;
694 	pollcache_t *pcp;
695 
696 	if (ps == NULL)
697 		return;
698 	pcp = ps->ps_pcache;
699 	/*
700 	 * free up all cached poll fds
701 	 */
702 	if (pcp == NULL) {
703 		/* this pollstate is used by /dev/poll */
704 		goto pollcleanout;
705 	}
706 
707 	if (pcp->pc_bitmap != NULL) {
708 		ASSERT(MUTEX_NOT_HELD(&ps->ps_lock));
709 		/*
710 		 * a close lwp can race with us when cleaning up a polldat
711 		 * entry. We hold the ps_lock when cleaning hash table.
712 		 * Since this pollcache is going away anyway, there is no
713 		 * need to hold the pc_lock.
714 		 */
715 		mutex_enter(&ps->ps_lock);
716 		pcache_clean(pcp);
717 		mutex_exit(&ps->ps_lock);
718 #ifdef DEBUG
719 		/*
720 		 * At this point, all fds cached by this lwp should be
721 		 * cleaned up. There should be no fd in fi_list still
722 		 * reference this thread.
723 		 */
724 		checkfpollinfo();	/* sanity check */
725 		pollcheckphlist();	/* sanity check */
726 #endif	/* DEBUG */
727 	}
728 	/*
729 	 * Be sure no one is referencing thread before exiting
730 	 */
731 	mutex_enter(&pcp->pc_no_exit);
732 	ASSERT(pcp->pc_busy >= 0);
733 	while (pcp->pc_busy > 0)
734 		cv_wait(&pcp->pc_busy_cv, &pcp->pc_no_exit);
735 	mutex_exit(&pcp->pc_no_exit);
736 pollcleanout:
737 	pollstate_destroy(ps);
738 	curthread->t_pollstate = NULL;
739 }
740 
741 /*
742  * pollwakeup() - poke threads waiting in poll() for some event
743  * on a particular object.
744  *
745  * The threads hanging off of the specified pollhead structure are scanned.
746  * If their event mask matches the specified event(s), then pollnotify() is
747  * called to poke the thread.
748  *
749  * Multiple events may be specified.  When POLLHUP or POLLERR are specified,
750  * all waiting threads are poked.
751  *
752  * It is important that pollnotify() not drop the lock protecting the list
753  * of threads.
754  */
755 void
756 pollwakeup(pollhead_t *php, short events_arg)
757 {
758 	polldat_t	*pdp;
759 	int		events = (ushort_t)events_arg;
760 	struct plist {
761 		port_t *pp;
762 		int	pevents;
763 		struct plist *next;
764 		};
765 	struct plist *plhead = NULL, *pltail = NULL;
766 
767 retry:
768 	PH_ENTER(php);
769 
770 	for (pdp = php->ph_list; pdp; pdp = pdp->pd_next) {
771 		if ((pdp->pd_events & events) ||
772 		    (events & (POLLHUP | POLLERR))) {
773 
774 			pollcache_t 	*pcp;
775 
776 			if (pdp->pd_portev != NULL) {
777 				port_kevent_t	*pkevp = pdp->pd_portev;
778 				/*
779 				 * Object (fd) is associated with an event port,
780 				 * => send event notification to the port.
781 				 */
782 				ASSERT(pkevp->portkev_source == PORT_SOURCE_FD);
783 				mutex_enter(&pkevp->portkev_lock);
784 				if (pkevp->portkev_flags & PORT_KEV_VALID) {
785 					int pevents;
786 
787 					pkevp->portkev_flags &= ~PORT_KEV_VALID;
788 					pkevp->portkev_events |= events &
789 					    (pdp->pd_events | POLLHUP |
790 					    POLLERR);
791 					/*
792 					 * portkev_lock mutex will be released
793 					 * by port_send_event().
794 					 */
795 					port_send_event(pkevp);
796 
797 					/*
798 					 * If we have some thread polling the
799 					 * port's fd, add it to the list. They
800 					 * will be notified later.
801 					 * The port_pollwkup() will flag the
802 					 * port_t so that it will not disappear
803 					 * till port_pollwkdone() is called.
804 					 */
805 					pevents =
806 					    port_pollwkup(pkevp->portkev_port);
807 					if (pevents) {
808 						struct plist *t;
809 						t = kmem_zalloc(
810 						    sizeof (struct plist),
811 						    KM_SLEEP);
812 						t->pp = pkevp->portkev_port;
813 						t->pevents = pevents;
814 						if (plhead == NULL) {
815 							plhead = t;
816 						} else {
817 							pltail->next = t;
818 						}
819 						pltail = t;
820 					}
821 				} else {
822 					mutex_exit(&pkevp->portkev_lock);
823 				}
824 				continue;
825 			}
826 
827 			pcp = pdp->pd_pcache;
828 
829 			/*
830 			 * Try to grab the lock for this thread. If
831 			 * we don't get it then we may deadlock so
832 			 * back out and restart all over again. Note
833 			 * that the failure rate is very very low.
834 			 */
835 			if (mutex_tryenter(&pcp->pc_lock)) {
836 				pollnotify(pcp, pdp->pd_fd);
837 				mutex_exit(&pcp->pc_lock);
838 			} else {
839 				/*
840 				 * We are here because:
841 				 *	1) This thread has been woke up
842 				 *	   and is trying to get out of poll().
843 				 *	2) Some other thread is also here
844 				 *	   but with a different pollhead lock.
845 				 *
846 				 * So, we need to drop the lock on pollhead
847 				 * because of (1) but we want to prevent
848 				 * that thread from doing lwp_exit() or
849 				 * devpoll close. We want to ensure that
850 				 * the pollcache pointer is still invalid.
851 				 *
852 				 * Solution: Grab the pcp->pc_no_exit lock,
853 				 * increment the pc_busy counter, drop every
854 				 * lock in sight. Get out of the way and wait
855 				 * for type (2) threads to finish.
856 				 */
857 
858 				mutex_enter(&pcp->pc_no_exit);
859 				pcp->pc_busy++;	/* prevents exit()'s */
860 				mutex_exit(&pcp->pc_no_exit);
861 
862 				PH_EXIT(php);
863 				mutex_enter(&pcp->pc_lock);
864 				mutex_exit(&pcp->pc_lock);
865 				mutex_enter(&pcp->pc_no_exit);
866 				pcp->pc_busy--;
867 				if (pcp->pc_busy == 0) {
868 					/*
869 					 * Wakeup the thread waiting in
870 					 * thread_exit().
871 					 */
872 					cv_signal(&pcp->pc_busy_cv);
873 				}
874 				mutex_exit(&pcp->pc_no_exit);
875 				goto retry;
876 			}
877 		}
878 	}
879 
880 
881 	/*
882 	 * Event ports - If this php is of the port on the list,
883 	 * call port_pollwkdone() to release it. The port_pollwkdone()
884 	 * needs to be called before dropping the PH lock so that any new
885 	 * thread attempting to poll this port are blocked. There can be
886 	 * only one thread here in pollwakeup notifying this port's fd.
887 	 */
888 	if (plhead != NULL && &plhead->pp->port_pollhd == php) {
889 		struct plist *t;
890 		port_pollwkdone(plhead->pp);
891 		t = plhead;
892 		plhead = plhead->next;
893 		kmem_free(t, sizeof (struct plist));
894 	}
895 	PH_EXIT(php);
896 
897 	/*
898 	 * Event ports - Notify threads polling the event port's fd.
899 	 * This is normally done in port_send_event() where it calls
900 	 * pollwakeup() on the port. But, for PORT_SOURCE_FD source alone,
901 	 * we do it here in pollwakeup() to avoid a recursive call.
902 	 */
903 	if (plhead != NULL) {
904 		php = &plhead->pp->port_pollhd;
905 		events = plhead->pevents;
906 		goto retry;
907 	}
908 }
909 
910 /*
911  * This function is called to inform a thread that
912  * an event being polled for has occurred.
913  * The pollstate lock on the thread should be held on entry.
914  */
915 void
916 pollnotify(pollcache_t *pcp, int fd)
917 {
918 	ASSERT(fd < pcp->pc_mapsize);
919 	ASSERT(MUTEX_HELD(&pcp->pc_lock));
920 	BT_SET(pcp->pc_bitmap, fd);
921 	pcp->pc_flag |= T_POLLWAKE;
922 	cv_signal(&pcp->pc_cv);
923 }
924 
925 /*
926  * add a polldat entry to pollhead ph_list. The polldat struct is used
927  * by pollwakeup to wake sleeping pollers when polled events has happened.
928  */
929 void
930 pollhead_insert(pollhead_t *php, polldat_t *pdp)
931 {
932 	PH_ENTER(php);
933 	ASSERT(pdp->pd_next == NULL);
934 #ifdef DEBUG
935 	{
936 		/*
937 		 * the polldat should not be already on the list
938 		 */
939 		polldat_t *wp;
940 		for (wp = php->ph_list; wp; wp = wp->pd_next) {
941 			ASSERT(wp != pdp);
942 		}
943 	}
944 #endif	/* DEBUG */
945 	pdp->pd_next = php->ph_list;
946 	php->ph_list = pdp;
947 	PH_EXIT(php);
948 }
949 
950 /*
951  * Delete the polldat entry from ph_list.
952  */
953 void
954 pollhead_delete(pollhead_t *php, polldat_t *pdp)
955 {
956 	polldat_t *wp;
957 	polldat_t **wpp;
958 
959 	PH_ENTER(php);
960 	for (wpp = &php->ph_list; (wp = *wpp) != NULL; wpp = &wp->pd_next) {
961 		if (wp == pdp) {
962 			*wpp = pdp->pd_next;
963 			pdp->pd_next = NULL;
964 			break;
965 		}
966 	}
967 #ifdef DEBUG
968 	/* assert that pdp is no longer in the list */
969 	for (wp = *wpp; wp; wp = wp->pd_next) {
970 		ASSERT(wp != pdp);
971 	}
972 #endif	/* DEBUG */
973 	PH_EXIT(php);
974 }
975 
976 /*
977  * walk through the poll fd lists to see if they are identical. This is an
978  * expensive operation and should not be done more than once for each poll()
979  * call.
980  *
981  * As an optimization (i.e., not having to go through the lists more than
982  * once), this routine also clear the revents field of pollfd in 'current'.
983  * Zeroing out the revents field of each entry in current poll list is
984  * required by poll man page.
985  *
986  * Since the events field of cached list has illegal poll events filtered
987  * out, the current list applies the same filtering before comparison.
988  *
989  * The routine stops when it detects a meaningful difference, or when it
990  * exhausts the lists.
991  */
992 int
993 pcacheset_cmp(pollfd_t *current, pollfd_t *cached, pollfd_t *newlist, int n)
994 {
995 	int    ix;
996 
997 	for (ix = 0; ix < n; ix++) {
998 		/* Prefetch 64 bytes worth of 8-byte elements */
999 		if ((ix & 0x7) == 0) {
1000 			prefetch64((caddr_t)&current[ix + 8]);
1001 			prefetch64((caddr_t)&cached[ix + 8]);
1002 		}
1003 		if (current[ix].fd == cached[ix].fd) {
1004 			/*
1005 			 * Filter out invalid poll events while we are in
1006 			 * inside the loop.
1007 			 */
1008 			if (current[ix].events & ~VALID_POLL_EVENTS) {
1009 				current[ix].events &= VALID_POLL_EVENTS;
1010 				if (newlist != NULL)
1011 					newlist[ix].events = current[ix].events;
1012 			}
1013 			if (current[ix].events == cached[ix].events) {
1014 				current[ix].revents = 0;
1015 				continue;
1016 			}
1017 		}
1018 		if ((current[ix].fd < 0) && (cached[ix].fd < 0)) {
1019 			current[ix].revents = 0;
1020 			continue;
1021 		}
1022 		return (ix);
1023 	}
1024 	return (ix);
1025 }
1026 
1027 /*
1028  * This routine returns a pointer to a cached poll fd entry, or NULL if it
1029  * does not find it in the hash table.
1030  */
1031 polldat_t *
1032 pcache_lookup_fd(pollcache_t *pcp, int fd)
1033 {
1034 	int hashindex;
1035 	polldat_t *pdp;
1036 
1037 	hashindex = POLLHASH(pcp->pc_hashsize, fd);
1038 	pdp = pcp->pc_hash[hashindex];
1039 	while (pdp != NULL) {
1040 		if (pdp->pd_fd == fd)
1041 			break;
1042 		pdp = pdp->pd_hashnext;
1043 	}
1044 	return (pdp);
1045 }
1046 
1047 polldat_t *
1048 pcache_alloc_fd(int nsets)
1049 {
1050 	polldat_t *pdp;
1051 
1052 	pdp = kmem_zalloc(sizeof (polldat_t), KM_SLEEP);
1053 	if (nsets > 0) {
1054 		pdp->pd_ref = kmem_zalloc(sizeof (xref_t) * nsets, KM_SLEEP);
1055 		pdp->pd_nsets = nsets;
1056 	}
1057 	return (pdp);
1058 }
1059 
1060 /*
1061  * This routine  inserts a polldat into the pollcache's hash table. It
1062  * may be necessary to grow the size of the hash table.
1063  */
1064 void
1065 pcache_insert_fd(pollcache_t *pcp, polldat_t *pdp, nfds_t nfds)
1066 {
1067 	int hashindex;
1068 	int fd;
1069 
1070 	if ((pcp->pc_fdcount > pcp->pc_hashsize * POLLHASHTHRESHOLD) ||
1071 	    (nfds > pcp->pc_hashsize * POLLHASHTHRESHOLD)) {
1072 		pcache_grow_hashtbl(pcp, nfds);
1073 	}
1074 	fd = pdp->pd_fd;
1075 	hashindex = POLLHASH(pcp->pc_hashsize, fd);
1076 	pdp->pd_hashnext = pcp->pc_hash[hashindex];
1077 	pcp->pc_hash[hashindex] = pdp;
1078 	pcp->pc_fdcount++;
1079 
1080 #ifdef DEBUG
1081 	{
1082 		/*
1083 		 * same fd should not appear on a hash list twice
1084 		 */
1085 		polldat_t *pdp1;
1086 		for (pdp1 = pdp->pd_hashnext; pdp1; pdp1 = pdp1->pd_hashnext) {
1087 			ASSERT(pdp->pd_fd != pdp1->pd_fd);
1088 		}
1089 	}
1090 #endif	/* DEBUG */
1091 }
1092 
1093 /*
1094  * Grow the hash table -- either double the table size or round it to the
1095  * nearest multiples of POLLHASHCHUNKSZ, whichever is bigger. Rehash all the
1096  * elements on the hash table.
1097  */
1098 void
1099 pcache_grow_hashtbl(pollcache_t *pcp, nfds_t nfds)
1100 {
1101 	int	oldsize;
1102 	polldat_t **oldtbl;
1103 	polldat_t *pdp, *pdp1;
1104 	int	i;
1105 #ifdef DEBUG
1106 	int	count = 0;
1107 #endif
1108 
1109 	ASSERT(pcp->pc_hashsize % POLLHASHCHUNKSZ == 0);
1110 	oldsize = pcp->pc_hashsize;
1111 	oldtbl = pcp->pc_hash;
1112 	if (nfds > pcp->pc_hashsize * POLLHASHINC) {
1113 		pcp->pc_hashsize = (nfds + POLLHASHCHUNKSZ - 1) &
1114 		    ~(POLLHASHCHUNKSZ - 1);
1115 	} else {
1116 		pcp->pc_hashsize = pcp->pc_hashsize * POLLHASHINC;
1117 	}
1118 	pcp->pc_hash = kmem_zalloc(pcp->pc_hashsize * sizeof (polldat_t *),
1119 	    KM_SLEEP);
1120 	/*
1121 	 * rehash existing elements
1122 	 */
1123 	pcp->pc_fdcount = 0;
1124 	for (i = 0; i < oldsize; i++) {
1125 		pdp = oldtbl[i];
1126 		while (pdp != NULL) {
1127 			pdp1 = pdp->pd_hashnext;
1128 			pcache_insert_fd(pcp, pdp, nfds);
1129 			pdp = pdp1;
1130 #ifdef DEBUG
1131 			count++;
1132 #endif
1133 		}
1134 	}
1135 	kmem_free(oldtbl, oldsize * sizeof (polldat_t *));
1136 	ASSERT(pcp->pc_fdcount == count);
1137 }
1138 
1139 void
1140 pcache_grow_map(pollcache_t *pcp, int fd)
1141 {
1142 	int  	newsize;
1143 	ulong_t	*newmap;
1144 
1145 	/*
1146 	 * grow to nearest multiple of POLLMAPCHUNK, assuming POLLMAPCHUNK is
1147 	 * power of 2.
1148 	 */
1149 	newsize = (fd + POLLMAPCHUNK) & ~(POLLMAPCHUNK - 1);
1150 	newmap = kmem_zalloc((newsize / BT_NBIPUL) * sizeof (ulong_t),
1151 	    KM_SLEEP);
1152 	/*
1153 	 * don't want pollwakeup to set a bit while growing the bitmap.
1154 	 */
1155 	ASSERT(mutex_owned(&pcp->pc_lock) == 0);
1156 	mutex_enter(&pcp->pc_lock);
1157 	bcopy(pcp->pc_bitmap, newmap,
1158 	    (pcp->pc_mapsize / BT_NBIPUL) * sizeof (ulong_t));
1159 	kmem_free(pcp->pc_bitmap,
1160 	    (pcp->pc_mapsize /BT_NBIPUL) * sizeof (ulong_t));
1161 	pcp->pc_bitmap = newmap;
1162 	pcp->pc_mapsize = newsize;
1163 	mutex_exit(&pcp->pc_lock);
1164 }
1165 
1166 /*
1167  * remove all the reference from pollhead list and fpollinfo lists.
1168  */
1169 void
1170 pcache_clean(pollcache_t *pcp)
1171 {
1172 	int i;
1173 	polldat_t **hashtbl;
1174 	polldat_t *pdp;
1175 
1176 	ASSERT(MUTEX_HELD(&curthread->t_pollstate->ps_lock));
1177 	hashtbl = pcp->pc_hash;
1178 	for (i = 0; i < pcp->pc_hashsize; i++) {
1179 		for (pdp = hashtbl[i]; pdp; pdp = pdp->pd_hashnext) {
1180 			if (pdp->pd_php != NULL) {
1181 				pollhead_delete(pdp->pd_php, pdp);
1182 				pdp->pd_php = NULL;
1183 			}
1184 			if (pdp->pd_fp != NULL) {
1185 				delfpollinfo(pdp->pd_fd);
1186 				pdp->pd_fp = NULL;
1187 			}
1188 		}
1189 	}
1190 }
1191 
1192 void
1193 pcacheset_invalidate(pollstate_t *ps, polldat_t *pdp)
1194 {
1195 	int 	i;
1196 	int	fd = pdp->pd_fd;
1197 
1198 	/*
1199 	 * we come here because an earlier close() on this cached poll fd.
1200 	 */
1201 	ASSERT(pdp->pd_fp == NULL);
1202 	ASSERT(MUTEX_HELD(&ps->ps_lock));
1203 	pdp->pd_events = 0;
1204 	for (i = 0; i < ps->ps_nsets; i++) {
1205 		xref_t		*refp;
1206 		pollcacheset_t	*pcsp;
1207 
1208 		ASSERT(pdp->pd_ref != NULL);
1209 		refp = &pdp->pd_ref[i];
1210 		if (refp->xf_refcnt) {
1211 			ASSERT(refp->xf_position >= 0);
1212 			pcsp = &ps->ps_pcacheset[i];
1213 			if (refp->xf_refcnt == 1) {
1214 				pcsp->pcs_pollfd[refp->xf_position].fd = -1;
1215 				refp->xf_refcnt = 0;
1216 				pdp->pd_count--;
1217 			} else if (refp->xf_refcnt > 1) {
1218 				int	j;
1219 
1220 				/*
1221 				 * turn off every appearance in pcs_pollfd list
1222 				 */
1223 				for (j = refp->xf_position;
1224 				    j < pcsp->pcs_nfds; j++) {
1225 					if (pcsp->pcs_pollfd[j].fd == fd) {
1226 						pcsp->pcs_pollfd[j].fd = -1;
1227 						refp->xf_refcnt--;
1228 						pdp->pd_count--;
1229 					}
1230 				}
1231 			}
1232 			ASSERT(refp->xf_refcnt == 0);
1233 			refp->xf_position = POLLPOSINVAL;
1234 		}
1235 	}
1236 	ASSERT(pdp->pd_count == 0);
1237 }
1238 
1239 /*
1240  * Insert poll fd into the pollcache, and add poll registration.
1241  * This routine is called after getf() and before releasef(). So the vnode
1242  * can not disappear even if we block here.
1243  * If there is an error, the polled fd is not cached.
1244  */
1245 int
1246 pcache_insert(pollstate_t *ps, file_t *fp, pollfd_t *pollfdp, int *fdcntp,
1247     ssize_t pos, int which)
1248 {
1249 	pollcache_t	*pcp = ps->ps_pcache;
1250 	polldat_t	*pdp;
1251 	int		error;
1252 	int		fd;
1253 	pollhead_t	*memphp = NULL;
1254 	xref_t		*refp;
1255 	int		newpollfd = 0;
1256 
1257 	ASSERT(MUTEX_HELD(&ps->ps_lock));
1258 	/*
1259 	 * The poll caching uses the existing VOP_POLL interface. If there
1260 	 * is no polled events, we want the polled device to set its "some
1261 	 * one is sleeping in poll" flag. When the polled events happen
1262 	 * later, the driver will call pollwakeup(). We achieve this by
1263 	 * always passing 0 in the third parameter ("anyyet") when calling
1264 	 * VOP_POLL. This parameter is not looked at by drivers when the
1265 	 * polled events exist. If a driver chooses to ignore this parameter
1266 	 * and call pollwakeup whenever the polled events happen, that will
1267 	 * be OK too.
1268 	 */
1269 	ASSERT(curthread->t_pollcache == NULL);
1270 	error = VOP_POLL(fp->f_vnode, pollfdp->events, 0, &pollfdp->revents,
1271 	    &memphp, NULL);
1272 	if (error) {
1273 		return (error);
1274 	}
1275 	if (pollfdp->revents) {
1276 		(*fdcntp)++;
1277 	}
1278 	/*
1279 	 * polling the underlying device succeeded. Now we can cache it.
1280 	 * A close can't come in here because we have not done a releasef()
1281 	 * yet.
1282 	 */
1283 	fd = pollfdp->fd;
1284 	pdp = pcache_lookup_fd(pcp, fd);
1285 	if (pdp == NULL) {
1286 		ASSERT(ps->ps_nsets > 0);
1287 		pdp = pcache_alloc_fd(ps->ps_nsets);
1288 		newpollfd = 1;
1289 	}
1290 	/*
1291 	 * If this entry was used to cache a poll fd which was closed, and
1292 	 * this entry has not been cleaned, do it now.
1293 	 */
1294 	if ((pdp->pd_count > 0) && (pdp->pd_fp == NULL)) {
1295 		pcacheset_invalidate(ps, pdp);
1296 		ASSERT(pdp->pd_next == NULL);
1297 	}
1298 	if (pdp->pd_count == 0) {
1299 		pdp->pd_fd = fd;
1300 		pdp->pd_fp = fp;
1301 		addfpollinfo(fd);
1302 		pdp->pd_thread = curthread;
1303 		pdp->pd_pcache = pcp;
1304 		/*
1305 		 * the entry is never used or cleared by removing a cached
1306 		 * pollfd (pcache_delete_fd). So all the fields should be clear.
1307 		 */
1308 		ASSERT(pdp->pd_next == NULL);
1309 	}
1310 
1311 	/*
1312 	 * A polled fd is considered cached. So there should be a fpollinfo
1313 	 * entry on uf_fpollinfo list.
1314 	 */
1315 	ASSERT(infpollinfo(fd));
1316 	/*
1317 	 * If there is an inconsistency, we want to know it here.
1318 	 */
1319 	ASSERT(pdp->pd_fp == fp);
1320 
1321 	/*
1322 	 * XXX pd_events is a union of all polled events on this fd, possibly
1323 	 * by different threads. Unless this is a new first poll(), pd_events
1324 	 * never shrinks. If an event is no longer polled by a process, there
1325 	 * is no way to cancel that event. In that case, poll degrade to its
1326 	 * old form -- polling on this fd every time poll() is called. The
1327 	 * assumption is an app always polls the same type of events.
1328 	 */
1329 	pdp->pd_events |= pollfdp->events;
1330 
1331 	pdp->pd_count++;
1332 	/*
1333 	 * There is not much special handling for multiple appearances of
1334 	 * same fd other than xf_position always recording the first
1335 	 * appearance in poll list. If this is called from pcacheset_cache_list,
1336 	 * a VOP_POLL is called on every pollfd entry; therefore each
1337 	 * revents and fdcnt should be set correctly. If this is called from
1338 	 * pcacheset_resolve, we don't care about fdcnt here. Pollreadmap will
1339 	 * pick up the right count and handle revents field of each pollfd
1340 	 * entry.
1341 	 */
1342 	ASSERT(pdp->pd_ref != NULL);
1343 	refp = &pdp->pd_ref[which];
1344 	if (refp->xf_refcnt == 0) {
1345 		refp->xf_position = pos;
1346 	} else {
1347 		/*
1348 		 * xf_position records the fd's first appearance in poll list
1349 		 */
1350 		if (pos < refp->xf_position) {
1351 			refp->xf_position = pos;
1352 		}
1353 	}
1354 	ASSERT(pollfdp->fd == ps->ps_pollfd[refp->xf_position].fd);
1355 	refp->xf_refcnt++;
1356 	if (fd >= pcp->pc_mapsize) {
1357 		pcache_grow_map(pcp, fd);
1358 	}
1359 	if (fd > pcp->pc_mapend) {
1360 		pcp->pc_mapend = fd;
1361 	}
1362 	if (newpollfd != 0) {
1363 		pcache_insert_fd(ps->ps_pcache, pdp, ps->ps_nfds);
1364 	}
1365 	if (memphp) {
1366 		if (pdp->pd_php == NULL) {
1367 			pollhead_insert(memphp, pdp);
1368 			pdp->pd_php = memphp;
1369 		} else {
1370 			if (memphp != pdp->pd_php) {
1371 				/*
1372 				 * layered devices (e.g. console driver)
1373 				 * may change the vnode and thus the pollhead
1374 				 * pointer out from underneath us.
1375 				 */
1376 				pollhead_delete(pdp->pd_php, pdp);
1377 				pollhead_insert(memphp, pdp);
1378 				pdp->pd_php = memphp;
1379 			}
1380 		}
1381 	}
1382 	/*
1383 	 * Since there is a considerable window between VOP_POLL and when
1384 	 * we actually put the polldat struct on the pollhead list, we could
1385 	 * miss a pollwakeup. In the case of polling additional events, we
1386 	 * don't update the events until after VOP_POLL. So we could miss
1387 	 * pollwakeup there too. So we always set the bit here just to be
1388 	 * safe. The real performance gain is in subsequent pcache_poll.
1389 	 */
1390 	mutex_enter(&pcp->pc_lock);
1391 	BT_SET(pcp->pc_bitmap, fd);
1392 	mutex_exit(&pcp->pc_lock);
1393 	return (0);
1394 }
1395 
1396 /*
1397  * The entry is not really deleted. The fields are cleared so that the
1398  * entry is no longer useful, but it will remain in the hash table for reuse
1399  * later. It will be freed when the polling lwp exits.
1400  */
1401 int
1402 pcache_delete_fd(pollstate_t *ps, int fd, size_t pos, int which, uint_t cevent)
1403 {
1404 	pollcache_t	*pcp = ps->ps_pcache;
1405 	polldat_t	*pdp;
1406 	xref_t		*refp;
1407 
1408 	ASSERT(fd < pcp->pc_mapsize);
1409 	ASSERT(MUTEX_HELD(&ps->ps_lock));
1410 
1411 	pdp = pcache_lookup_fd(pcp, fd);
1412 	ASSERT(pdp != NULL);
1413 	ASSERT(pdp->pd_count > 0);
1414 	ASSERT(pdp->pd_ref != NULL);
1415 	refp = &pdp->pd_ref[which];
1416 	if (pdp->pd_count == 1) {
1417 		pdp->pd_events = 0;
1418 		refp->xf_position = POLLPOSINVAL;
1419 		ASSERT(refp->xf_refcnt == 1);
1420 		refp->xf_refcnt = 0;
1421 		if (pdp->pd_php) {
1422 			/*
1423 			 * It is possible for a wakeup thread to get ahead
1424 			 * of the following pollhead_delete and set the bit in
1425 			 * bitmap.  It is OK because the bit will be cleared
1426 			 * here anyway.
1427 			 */
1428 			pollhead_delete(pdp->pd_php, pdp);
1429 			pdp->pd_php = NULL;
1430 		}
1431 		pdp->pd_count = 0;
1432 		if (pdp->pd_fp != NULL) {
1433 			pdp->pd_fp = NULL;
1434 			delfpollinfo(fd);
1435 		}
1436 		mutex_enter(&pcp->pc_lock);
1437 		BT_CLEAR(pcp->pc_bitmap, fd);
1438 		mutex_exit(&pcp->pc_lock);
1439 		return (0);
1440 	}
1441 	if ((cevent & POLLCLOSED) == POLLCLOSED) {
1442 		/*
1443 		 * fd cached here has been closed. This is the first
1444 		 * pcache_delete_fd called after the close. Clean up the
1445 		 * entire entry.
1446 		 */
1447 		pcacheset_invalidate(ps, pdp);
1448 		ASSERT(pdp->pd_php == NULL);
1449 		mutex_enter(&pcp->pc_lock);
1450 		BT_CLEAR(pcp->pc_bitmap, fd);
1451 		mutex_exit(&pcp->pc_lock);
1452 		return (0);
1453 	}
1454 #ifdef DEBUG
1455 	if (getf(fd) != NULL) {
1456 		ASSERT(infpollinfo(fd));
1457 		releasef(fd);
1458 	}
1459 #endif	/* DEBUG */
1460 	pdp->pd_count--;
1461 	ASSERT(refp->xf_refcnt > 0);
1462 	if (--refp->xf_refcnt == 0) {
1463 		refp->xf_position = POLLPOSINVAL;
1464 	} else {
1465 		ASSERT(pos >= refp->xf_position);
1466 		if (pos == refp->xf_position) {
1467 			/*
1468 			 * The xref position is no longer valid.
1469 			 * Reset it to a special value and let
1470 			 * caller know it needs to updatexref()
1471 			 * with a new xf_position value.
1472 			 */
1473 			refp->xf_position = POLLPOSTRANS;
1474 			return (1);
1475 		}
1476 	}
1477 	return (0);
1478 }
1479 
1480 void
1481 pcache_update_xref(pollcache_t *pcp, int fd, ssize_t pos, int which)
1482 {
1483 	polldat_t	*pdp;
1484 
1485 	pdp = pcache_lookup_fd(pcp, fd);
1486 	ASSERT(pdp != NULL);
1487 	ASSERT(pdp->pd_ref != NULL);
1488 	pdp->pd_ref[which].xf_position = pos;
1489 }
1490 
1491 #ifdef DEBUG
1492 /*
1493  * For each polled fd, it's either in the bitmap or cached in
1494  * pcache hash table. If this routine returns 0, something is wrong.
1495  */
1496 static int
1497 pollchecksanity(pollstate_t *ps, nfds_t nfds)
1498 {
1499 	int    		i;
1500 	int		fd;
1501 	pollcache_t	*pcp = ps->ps_pcache;
1502 	polldat_t	*pdp;
1503 	pollfd_t	*pollfdp = ps->ps_pollfd;
1504 	file_t		*fp;
1505 
1506 	ASSERT(MUTEX_HELD(&ps->ps_lock));
1507 	for (i = 0; i < nfds; i++) {
1508 		fd = pollfdp[i].fd;
1509 		if (fd < 0) {
1510 			ASSERT(pollfdp[i].revents == 0);
1511 			continue;
1512 		}
1513 		if (pollfdp[i].revents == POLLNVAL)
1514 			continue;
1515 		if ((fp = getf(fd)) == NULL)
1516 			continue;
1517 		pdp = pcache_lookup_fd(pcp, fd);
1518 		ASSERT(pdp != NULL);
1519 		ASSERT(infpollinfo(fd));
1520 		ASSERT(pdp->pd_fp == fp);
1521 		releasef(fd);
1522 		if (BT_TEST(pcp->pc_bitmap, fd))
1523 			continue;
1524 		if (pdp->pd_php == NULL)
1525 			return (0);
1526 	}
1527 	return (1);
1528 }
1529 #endif	/* DEBUG */
1530 
1531 /*
1532  * resolve the difference between the current poll list and a cached one.
1533  */
1534 int
1535 pcacheset_resolve(pollstate_t *ps, nfds_t nfds, int *fdcntp, int which)
1536 {
1537 	int    		i;
1538 	pollcache_t	*pcp = ps->ps_pcache;
1539 	pollfd_t	*newlist = NULL;
1540 	pollfd_t	*current = ps->ps_pollfd;
1541 	pollfd_t	*cached;
1542 	pollcacheset_t	*pcsp;
1543 	int		common;
1544 	int		count = 0;
1545 	int		offset;
1546 	int		remain;
1547 	int		fd;
1548 	file_t		*fp;
1549 	int		fdcnt = 0;
1550 	int		cnt = 0;
1551 	nfds_t		old_nfds;
1552 	int		error = 0;
1553 	int		mismatch = 0;
1554 
1555 	ASSERT(MUTEX_HELD(&ps->ps_lock));
1556 #ifdef DEBUG
1557 	checkpolldat(ps);
1558 #endif
1559 	pcsp = &ps->ps_pcacheset[which];
1560 	old_nfds = pcsp->pcs_nfds;
1561 	common = (nfds > old_nfds) ? old_nfds : nfds;
1562 	if (nfds != old_nfds) {
1563 		/*
1564 		 * the length of poll list has changed. allocate a new
1565 		 * pollfd list.
1566 		 */
1567 		newlist = kmem_alloc(nfds * sizeof (pollfd_t), KM_SLEEP);
1568 		bcopy(current, newlist, sizeof (pollfd_t) * nfds);
1569 	}
1570 	/*
1571 	 * Compare the overlapping part of the current fd list with the
1572 	 * cached one. Whenever a difference is found, resolve it.
1573 	 * The comparison is done on the current poll list and the
1574 	 * cached list. But we may be setting up the newlist to be the
1575 	 * cached list for next poll.
1576 	 */
1577 	cached = pcsp->pcs_pollfd;
1578 	remain = common;
1579 
1580 	while (count < common) {
1581 		int	tmpfd;
1582 		pollfd_t *np;
1583 
1584 		np = (newlist != NULL) ? &newlist[count] : NULL;
1585 		offset = pcacheset_cmp(&current[count], &cached[count], np,
1586 		    remain);
1587 		/*
1588 		 * Collect stats. If lists are completed the first time,
1589 		 * it's a hit. Otherwise, it's a partial hit or miss.
1590 		 */
1591 		if ((count == 0) && (offset == common)) {
1592 			pollstats.pollcachehit.value.ui64++;
1593 		} else {
1594 			mismatch++;
1595 		}
1596 		count += offset;
1597 		if (offset < remain) {
1598 			ASSERT(count < common);
1599 			ASSERT((current[count].fd != cached[count].fd) ||
1600 			    (current[count].events != cached[count].events));
1601 			/*
1602 			 * Filter out invalid events.
1603 			 */
1604 			if (current[count].events & ~VALID_POLL_EVENTS) {
1605 				if (newlist != NULL) {
1606 					newlist[count].events =
1607 					    current[count].events &=
1608 					    VALID_POLL_EVENTS;
1609 				} else {
1610 					current[count].events &=
1611 					    VALID_POLL_EVENTS;
1612 				}
1613 			}
1614 			/*
1615 			 * when resolving a difference, we always remove the
1616 			 * fd from cache before inserting one into cache.
1617 			 */
1618 			if (cached[count].fd >= 0) {
1619 				tmpfd = cached[count].fd;
1620 				if (pcache_delete_fd(ps, tmpfd, count, which,
1621 				    (uint_t)cached[count].events)) {
1622 					/*
1623 					 * This should be rare but needed for
1624 					 * correctness.
1625 					 *
1626 					 * The first appearance in cached list
1627 					 * is being "turned off". The same fd
1628 					 * appear more than once in the cached
1629 					 * poll list. Find the next one on the
1630 					 * list and update the cached
1631 					 * xf_position field.
1632 					 */
1633 					for (i = count + 1; i < old_nfds; i++) {
1634 						if (cached[i].fd == tmpfd) {
1635 							pcache_update_xref(pcp,
1636 							    tmpfd, (ssize_t)i,
1637 							    which);
1638 							break;
1639 						}
1640 					}
1641 					ASSERT(i <= old_nfds);
1642 				}
1643 				/*
1644 				 * In case a new cache list is allocated,
1645 				 * need to keep both cache lists in sync
1646 				 * b/c the new one can be freed if we have
1647 				 * an error later.
1648 				 */
1649 				cached[count].fd = -1;
1650 				if (newlist != NULL) {
1651 					newlist[count].fd = -1;
1652 				}
1653 			}
1654 			if ((tmpfd = current[count].fd) >= 0) {
1655 				/*
1656 				 * add to the cached fd tbl and bitmap.
1657 				 */
1658 				if ((fp = getf(tmpfd)) == NULL) {
1659 					current[count].revents = POLLNVAL;
1660 					if (newlist != NULL) {
1661 						newlist[count].fd = -1;
1662 					}
1663 					cached[count].fd = -1;
1664 					fdcnt++;
1665 				} else {
1666 					/*
1667 					 * Here we don't care about the
1668 					 * fdcnt. We will examine the bitmap
1669 					 * later and pick up the correct
1670 					 * fdcnt there. So we never bother
1671 					 * to check value of 'cnt'.
1672 					 */
1673 					error = pcache_insert(ps, fp,
1674 					    &current[count], &cnt,
1675 					    (ssize_t)count, which);
1676 					/*
1677 					 * if no error, we want to do releasef
1678 					 * after we updated cache poll list
1679 					 * entry so that close() won't race
1680 					 * us.
1681 					 */
1682 					if (error) {
1683 						/*
1684 						 * If we encountered an error,
1685 						 * we have invalidated an
1686 						 * entry in cached poll list
1687 						 * (in pcache_delete_fd() above)
1688 						 * but failed to add one here.
1689 						 * This is OK b/c what's in the
1690 						 * cached list is consistent
1691 						 * with content of cache.
1692 						 * It will not have any ill
1693 						 * effect on next poll().
1694 						 */
1695 						releasef(tmpfd);
1696 						if (newlist != NULL) {
1697 							kmem_free(newlist,
1698 							    nfds *
1699 							    sizeof (pollfd_t));
1700 						}
1701 						return (error);
1702 					}
1703 					/*
1704 					 * If we have allocated a new(temp)
1705 					 * cache list, we need to keep both
1706 					 * in sync b/c the new one can be freed
1707 					 * if we have an error later.
1708 					 */
1709 					if (newlist != NULL) {
1710 						newlist[count].fd =
1711 						    current[count].fd;
1712 						newlist[count].events =
1713 						    current[count].events;
1714 					}
1715 					cached[count].fd = current[count].fd;
1716 					cached[count].events =
1717 					    current[count].events;
1718 					releasef(tmpfd);
1719 				}
1720 			} else {
1721 				current[count].revents = 0;
1722 			}
1723 			count++;
1724 			remain = common - count;
1725 		}
1726 	}
1727 	if (mismatch != 0) {
1728 		if (mismatch == common) {
1729 			pollstats.pollcachemiss.value.ui64++;
1730 		} else {
1731 			pollstats.pollcachephit.value.ui64++;
1732 		}
1733 	}
1734 	/*
1735 	 * take care of the non overlapping part of a list
1736 	 */
1737 	if (nfds > old_nfds) {
1738 		ASSERT(newlist != NULL);
1739 		for (i = old_nfds; i < nfds; i++) {
1740 			/* filter out invalid events */
1741 			if (current[i].events & ~VALID_POLL_EVENTS) {
1742 				newlist[i].events = current[i].events =
1743 				    current[i].events & VALID_POLL_EVENTS;
1744 			}
1745 			if ((fd = current[i].fd) < 0) {
1746 				current[i].revents = 0;
1747 				continue;
1748 			}
1749 			/*
1750 			 * add to the cached fd tbl and bitmap.
1751 			 */
1752 			if ((fp = getf(fd)) == NULL) {
1753 				current[i].revents = POLLNVAL;
1754 				newlist[i].fd = -1;
1755 				fdcnt++;
1756 				continue;
1757 			}
1758 			/*
1759 			 * Here we don't care about the
1760 			 * fdcnt. We will examine the bitmap
1761 			 * later and pick up the correct
1762 			 * fdcnt there. So we never bother to
1763 			 * check 'cnt'.
1764 			 */
1765 			error = pcache_insert(ps, fp, &current[i], &cnt,
1766 			    (ssize_t)i, which);
1767 			releasef(fd);
1768 			if (error) {
1769 				/*
1770 				 * Here we are half way through adding newly
1771 				 * polled fd. Undo enough to keep the cache
1772 				 * list consistent with the cache content.
1773 				 */
1774 				pcacheset_remove_list(ps, current, old_nfds,
1775 				    i, which, 0);
1776 				kmem_free(newlist, nfds * sizeof (pollfd_t));
1777 				return (error);
1778 			}
1779 		}
1780 	}
1781 	if (old_nfds > nfds) {
1782 		/*
1783 		 * remove the fd's which are no longer polled.
1784 		 */
1785 		pcacheset_remove_list(ps, pcsp->pcs_pollfd, nfds, old_nfds,
1786 		    which, 1);
1787 	}
1788 	/*
1789 	 * set difference resolved. update nfds and cachedlist
1790 	 * in pollstate struct.
1791 	 */
1792 	if (newlist != NULL) {
1793 		kmem_free(pcsp->pcs_pollfd, old_nfds * sizeof (pollfd_t));
1794 		/*
1795 		 * By now, the pollfd.revents field should
1796 		 * all be zeroed.
1797 		 */
1798 		pcsp->pcs_pollfd = newlist;
1799 		pcsp->pcs_nfds = nfds;
1800 	}
1801 	ASSERT(*fdcntp == 0);
1802 	*fdcntp = fdcnt;
1803 	/*
1804 	 * By now for every fd in pollfdp, one of the following should be
1805 	 * true. Otherwise we will miss a polled event.
1806 	 *
1807 	 * 1. the bit corresponding to the fd in bitmap is set. So VOP_POLL
1808 	 *    will be called on this fd in next poll.
1809 	 * 2. the fd is cached in the pcache (i.e. pd_php is set). So
1810 	 *    pollnotify will happen.
1811 	 */
1812 	ASSERT(pollchecksanity(ps, nfds));
1813 	/*
1814 	 * make sure cross reference between cached poll lists and cached
1815 	 * poll fds are correct.
1816 	 */
1817 	ASSERT(pollcheckxref(ps, which));
1818 	/*
1819 	 * ensure each polldat in pollcache reference a polled fd in
1820 	 * pollcacheset.
1821 	 */
1822 #ifdef DEBUG
1823 	checkpolldat(ps);
1824 #endif
1825 	return (0);
1826 }
1827 
1828 #ifdef DEBUG
1829 static int
1830 pollscanrevents(pollcache_t *pcp, pollfd_t *pollfdp, nfds_t nfds)
1831 {
1832 	int i;
1833 	int reventcnt = 0;
1834 
1835 	for (i = 0; i < nfds; i++) {
1836 		if (pollfdp[i].fd < 0) {
1837 			ASSERT(pollfdp[i].revents == 0);
1838 			continue;
1839 		}
1840 		if (pollfdp[i].revents) {
1841 			reventcnt++;
1842 		}
1843 		if (pollfdp[i].revents && (pollfdp[i].revents != POLLNVAL)) {
1844 			ASSERT(BT_TEST(pcp->pc_bitmap, pollfdp[i].fd));
1845 		}
1846 	}
1847 	return (reventcnt);
1848 }
1849 #endif	/* DEBUG */
1850 
1851 /*
1852  * read the bitmap and poll on fds corresponding to the '1' bits. The ps_lock
1853  * is held upon entry.
1854  */
1855 int
1856 pcache_poll(pollfd_t *pollfdp, pollstate_t *ps, nfds_t nfds, int *fdcntp,
1857     int which)
1858 {
1859 	int		i;
1860 	pollcache_t	*pcp;
1861 	int 		fd;
1862 	int 		begin, end, done;
1863 	pollhead_t	*php;
1864 	int		fdcnt;
1865 	int		error = 0;
1866 	file_t		*fp;
1867 	polldat_t	*pdp;
1868 	xref_t		*refp;
1869 	int		entry;
1870 
1871 	pcp = ps->ps_pcache;
1872 	ASSERT(MUTEX_HELD(&ps->ps_lock));
1873 	ASSERT(MUTEX_HELD(&pcp->pc_lock));
1874 retry:
1875 	done = 0;
1876 	begin = 0;
1877 	fdcnt = 0;
1878 	end = pcp->pc_mapend;
1879 	while ((fdcnt < nfds) && !done) {
1880 		php = NULL;
1881 		/*
1882 		 * only poll fds which may have events
1883 		 */
1884 		fd = bt_getlowbit(pcp->pc_bitmap, begin, end);
1885 		ASSERT(fd <= end);
1886 		if (fd >= 0) {
1887 			ASSERT(pollcheckrevents(ps, begin, fd, which));
1888 			/*
1889 			 * adjust map pointers for next round
1890 			 */
1891 			if (fd == end) {
1892 				done = 1;
1893 			} else {
1894 				begin = fd + 1;
1895 			}
1896 			/*
1897 			 * A bitmap caches poll state information of
1898 			 * multiple poll lists. Call VOP_POLL only if
1899 			 * the bit corresponds to an fd in this poll
1900 			 * list.
1901 			 */
1902 			pdp = pcache_lookup_fd(pcp, fd);
1903 			ASSERT(pdp != NULL);
1904 			ASSERT(pdp->pd_ref != NULL);
1905 			refp = &pdp->pd_ref[which];
1906 			if (refp->xf_refcnt == 0)
1907 				continue;
1908 			entry = refp->xf_position;
1909 			ASSERT((entry >= 0) && (entry < nfds));
1910 			ASSERT(pollfdp[entry].fd == fd);
1911 			/*
1912 			 * we are in this routine implies that we have
1913 			 * successfully polled this fd in the past.
1914 			 * Check to see this fd is closed while we are
1915 			 * blocked in poll. This ensures that we don't
1916 			 * miss a close on the fd in the case this fd is
1917 			 * reused.
1918 			 */
1919 			if (pdp->pd_fp == NULL) {
1920 				ASSERT(pdp->pd_count > 0);
1921 				pollfdp[entry].revents = POLLNVAL;
1922 				fdcnt++;
1923 				if (refp->xf_refcnt > 1) {
1924 					/*
1925 					 * this fd appeared multiple time
1926 					 * in the poll list. Find all of them.
1927 					 */
1928 					for (i = entry + 1; i < nfds; i++) {
1929 						if (pollfdp[i].fd == fd) {
1930 							pollfdp[i].revents =
1931 							    POLLNVAL;
1932 							fdcnt++;
1933 						}
1934 					}
1935 				}
1936 				pcacheset_invalidate(ps, pdp);
1937 				continue;
1938 			}
1939 			/*
1940 			 * We can be here polling a device that is being
1941 			 * closed (i.e. the file pointer is set to NULL,
1942 			 * but pollcacheclean has not happened yet).
1943 			 */
1944 			if ((fp = getf(fd)) == NULL) {
1945 				pollfdp[entry].revents = POLLNVAL;
1946 				fdcnt++;
1947 				if (refp->xf_refcnt > 1) {
1948 					/*
1949 					 * this fd appeared multiple time
1950 					 * in the poll list. Find all of them.
1951 					 */
1952 					for (i = entry + 1; i < nfds; i++) {
1953 						if (pollfdp[i].fd == fd) {
1954 							pollfdp[i].revents =
1955 							    POLLNVAL;
1956 							fdcnt++;
1957 						}
1958 					}
1959 				}
1960 				continue;
1961 			}
1962 			ASSERT(pdp->pd_fp == fp);
1963 			ASSERT(infpollinfo(fd));
1964 			/*
1965 			 * Since we no longer hold poll head lock across
1966 			 * VOP_POLL, pollunlock logic can be simplifed.
1967 			 */
1968 			ASSERT(pdp->pd_php == NULL ||
1969 			    MUTEX_NOT_HELD(PHLOCK(pdp->pd_php)));
1970 			/*
1971 			 * underlying file systems may set a "pollpending"
1972 			 * flag when it sees the poll may block. Pollwakeup()
1973 			 * is called by wakeup thread if pollpending is set.
1974 			 * Pass a 0 fdcnt so that the underlying file system
1975 			 * will set the "pollpending" flag set when there is
1976 			 * no polled events.
1977 			 *
1978 			 * Use pollfdp[].events for actual polling because
1979 			 * the pd_events is union of all cached poll events
1980 			 * on this fd. The events parameter also affects
1981 			 * how the polled device sets the "poll pending"
1982 			 * flag.
1983 			 */
1984 			ASSERT(curthread->t_pollcache == NULL);
1985 			error = VOP_POLL(fp->f_vnode, pollfdp[entry].events, 0,
1986 			    &pollfdp[entry].revents, &php, NULL);
1987 			/*
1988 			 * releasef after completely done with this cached
1989 			 * poll entry. To prevent close() coming in to clear
1990 			 * this entry.
1991 			 */
1992 			if (error) {
1993 				releasef(fd);
1994 				break;
1995 			}
1996 			/*
1997 			 * layered devices (e.g. console driver)
1998 			 * may change the vnode and thus the pollhead
1999 			 * pointer out from underneath us.
2000 			 */
2001 			if (php != NULL && pdp->pd_php != NULL &&
2002 			    php != pdp->pd_php) {
2003 				releasef(fd);
2004 				pollhead_delete(pdp->pd_php, pdp);
2005 				pdp->pd_php = php;
2006 				pollhead_insert(php, pdp);
2007 				/*
2008 				 * We could have missed a wakeup on the new
2009 				 * target device. Make sure the new target
2010 				 * gets polled once.
2011 				 */
2012 				BT_SET(pcp->pc_bitmap, fd);
2013 				goto retry;
2014 			}
2015 
2016 			if (pollfdp[entry].revents) {
2017 				ASSERT(refp->xf_refcnt >= 1);
2018 				fdcnt++;
2019 				if (refp->xf_refcnt > 1) {
2020 					/*
2021 					 * this fd appeared multiple time
2022 					 * in the poll list. This is rare but
2023 					 * we have to look at all of them for
2024 					 * correctness.
2025 					 */
2026 					error = plist_chkdupfd(fp, pdp, ps,
2027 					    pollfdp, entry, &fdcnt);
2028 					if (error > 0) {
2029 						releasef(fd);
2030 						break;
2031 					}
2032 					if (error < 0) {
2033 						goto retry;
2034 					}
2035 				}
2036 				releasef(fd);
2037 			} else {
2038 				/*
2039 				 * VOP_POLL didn't return any revents. We can
2040 				 * clear the bit in bitmap only if we have the
2041 				 * pollhead ptr cached and no other cached
2042 				 * entry is polling different events on this fd.
2043 				 * VOP_POLL may have dropped the ps_lock. Make
2044 				 * sure pollwakeup has not happened before clear
2045 				 * the bit.
2046 				 */
2047 				if ((pdp->pd_php != NULL) &&
2048 				    (pollfdp[entry].events == pdp->pd_events) &&
2049 				    ((pcp->pc_flag & T_POLLWAKE) == 0)) {
2050 					BT_CLEAR(pcp->pc_bitmap, fd);
2051 				}
2052 				/*
2053 				 * if the fd can be cached now but not before,
2054 				 * do it now.
2055 				 */
2056 				if ((pdp->pd_php == NULL) && (php != NULL)) {
2057 					pdp->pd_php = php;
2058 					pollhead_insert(php, pdp);
2059 					/*
2060 					 * We are inserting a polldat struct for
2061 					 * the first time. We may have missed a
2062 					 * wakeup on this device. Re-poll once.
2063 					 * This should be a rare event.
2064 					 */
2065 					releasef(fd);
2066 					goto retry;
2067 				}
2068 				if (refp->xf_refcnt > 1) {
2069 					/*
2070 					 * this fd appeared multiple time
2071 					 * in the poll list. This is rare but
2072 					 * we have to look at all of them for
2073 					 * correctness.
2074 					 */
2075 					error = plist_chkdupfd(fp, pdp, ps,
2076 					    pollfdp, entry, &fdcnt);
2077 					if (error > 0) {
2078 						releasef(fd);
2079 						break;
2080 					}
2081 					if (error < 0) {
2082 						goto retry;
2083 					}
2084 				}
2085 				releasef(fd);
2086 			}
2087 		} else {
2088 			done = 1;
2089 			ASSERT(pollcheckrevents(ps, begin, end + 1, which));
2090 		}
2091 	}
2092 	if (!error) {
2093 		ASSERT(*fdcntp + fdcnt == pollscanrevents(pcp, pollfdp, nfds));
2094 		*fdcntp += fdcnt;
2095 	}
2096 	return (error);
2097 }
2098 
2099 /*
2100  * Going through the poll list without much locking. Poll all fds and
2101  * cache all valid fds in the pollcache.
2102  */
2103 int
2104 pcacheset_cache_list(pollstate_t *ps, pollfd_t *fds, int *fdcntp, int which)
2105 {
2106 	pollfd_t	*pollfdp = ps->ps_pollfd;
2107 	pollcacheset_t	*pcacheset = ps->ps_pcacheset;
2108 	pollfd_t	*newfdlist;
2109 	int		i;
2110 	int		fd;
2111 	file_t		*fp;
2112 	int		error = 0;
2113 
2114 	ASSERT(MUTEX_HELD(&ps->ps_lock));
2115 	ASSERT(which < ps->ps_nsets);
2116 	ASSERT(pcacheset != NULL);
2117 	ASSERT(pcacheset[which].pcs_pollfd == NULL);
2118 	newfdlist  = kmem_alloc(ps->ps_nfds * sizeof (pollfd_t), KM_SLEEP);
2119 	/*
2120 	 * cache the new poll list in pollcachset.
2121 	 */
2122 	bcopy(pollfdp, newfdlist, sizeof (pollfd_t) * ps->ps_nfds);
2123 
2124 	pcacheset[which].pcs_pollfd = newfdlist;
2125 	pcacheset[which].pcs_nfds = ps->ps_nfds;
2126 	pcacheset[which].pcs_usradr = (uintptr_t)fds;
2127 
2128 	/*
2129 	 * We have saved a copy of current poll fd list in one pollcacheset.
2130 	 * The 'revents' field of the new list is not yet set to 0. Loop
2131 	 * through the new list just to do that is expensive. We do that
2132 	 * while polling the list.
2133 	 */
2134 	for (i = 0; i < ps->ps_nfds; i++) {
2135 		fd = pollfdp[i].fd;
2136 		/*
2137 		 * We also filter out the illegal poll events in the event
2138 		 * field for the cached poll list/set.
2139 		 */
2140 		if (pollfdp[i].events & ~VALID_POLL_EVENTS) {
2141 			newfdlist[i].events = pollfdp[i].events =
2142 			    pollfdp[i].events & VALID_POLL_EVENTS;
2143 		}
2144 		if (fd < 0) {
2145 			pollfdp[i].revents = 0;
2146 			continue;
2147 		}
2148 		if ((fp = getf(fd)) == NULL) {
2149 			pollfdp[i].revents = POLLNVAL;
2150 			/*
2151 			 * invalidate this cache entry in the cached poll list
2152 			 */
2153 			newfdlist[i].fd = -1;
2154 			(*fdcntp)++;
2155 			continue;
2156 		}
2157 		/*
2158 		 * cache this fd.
2159 		 */
2160 		error = pcache_insert(ps, fp, &pollfdp[i], fdcntp, (ssize_t)i,
2161 		    which);
2162 		releasef(fd);
2163 		if (error) {
2164 			/*
2165 			 * Here we are half way through caching a new
2166 			 * poll list. Undo every thing.
2167 			 */
2168 			pcacheset_remove_list(ps, pollfdp, 0, i, which, 0);
2169 			kmem_free(newfdlist, ps->ps_nfds * sizeof (pollfd_t));
2170 			pcacheset[which].pcs_pollfd = NULL;
2171 			pcacheset[which].pcs_usradr = NULL;
2172 			break;
2173 		}
2174 	}
2175 	return (error);
2176 }
2177 
2178 /*
2179  * called by pollcacheclean() to set the fp NULL. It also sets polled events
2180  * in pcacheset entries to a special events 'POLLCLOSED'. Do a pollwakeup to
2181  * wake any sleeping poller, then remove the polldat from the driver.
2182  * The routine is called with ps_pcachelock held.
2183  */
2184 void
2185 pcache_clean_entry(pollstate_t *ps, int fd)
2186 {
2187 	pollcache_t	*pcp;
2188 	polldat_t	*pdp;
2189 	int		i;
2190 
2191 	ASSERT(ps != NULL);
2192 	ASSERT(MUTEX_HELD(&ps->ps_lock));
2193 	pcp = ps->ps_pcache;
2194 	ASSERT(pcp);
2195 	pdp = pcache_lookup_fd(pcp, fd);
2196 	ASSERT(pdp != NULL);
2197 	/*
2198 	 * the corresponding fpollinfo in fi_list has been removed by
2199 	 * a close on this fd. Reset the cached fp ptr here.
2200 	 */
2201 	pdp->pd_fp = NULL;
2202 	/*
2203 	 * XXX - This routine also touches data in pcacheset struct.
2204 	 *
2205 	 * set the event in cached poll lists to POLLCLOSED. This invalidate
2206 	 * the cached poll fd entry in that poll list, which will force a
2207 	 * removal of this cached entry in next poll(). The cleanup is done
2208 	 * at the removal time.
2209 	 */
2210 	ASSERT(pdp->pd_ref != NULL);
2211 	for (i = 0; i < ps->ps_nsets; i++) {
2212 		xref_t		*refp;
2213 		pollcacheset_t	*pcsp;
2214 
2215 		refp = &pdp->pd_ref[i];
2216 		if (refp->xf_refcnt) {
2217 			ASSERT(refp->xf_position >= 0);
2218 			pcsp = &ps->ps_pcacheset[i];
2219 			if (refp->xf_refcnt == 1) {
2220 				pcsp->pcs_pollfd[refp->xf_position].events =
2221 				    (short)POLLCLOSED;
2222 			}
2223 			if (refp->xf_refcnt > 1) {
2224 				int	j;
2225 				/*
2226 				 * mark every matching entry in pcs_pollfd
2227 				 */
2228 				for (j = refp->xf_position;
2229 				    j < pcsp->pcs_nfds; j++) {
2230 					if (pcsp->pcs_pollfd[j].fd == fd) {
2231 						pcsp->pcs_pollfd[j].events =
2232 						    (short)POLLCLOSED;
2233 					}
2234 				}
2235 			}
2236 		}
2237 	}
2238 	if (pdp->pd_php) {
2239 		pollwakeup(pdp->pd_php, POLLHUP);
2240 		pollhead_delete(pdp->pd_php, pdp);
2241 		pdp->pd_php = NULL;
2242 	}
2243 }
2244 
2245 /*
2246  * This is the first time this thread has ever polled,
2247  * so we have to create its pollstate structure.
2248  * This will persist for the life of the thread,
2249  * until it calls pollcleanup().
2250  */
2251 pollstate_t *
2252 pollstate_create(void)
2253 {
2254 	pollstate_t *ps;
2255 
2256 	ps = kmem_zalloc(sizeof (pollstate_t), KM_SLEEP);
2257 	ps->ps_nsets = POLLFDSETS;
2258 	ps->ps_pcacheset = pcacheset_create(ps->ps_nsets);
2259 	return (ps);
2260 }
2261 
2262 void
2263 pollstate_destroy(pollstate_t *ps)
2264 {
2265 	if (ps->ps_pollfd != NULL) {
2266 		kmem_free(ps->ps_pollfd, ps->ps_nfds * sizeof (pollfd_t));
2267 		ps->ps_pollfd = NULL;
2268 	}
2269 	if (ps->ps_pcache != NULL) {
2270 		pcache_destroy(ps->ps_pcache);
2271 		ps->ps_pcache = NULL;
2272 	}
2273 	pcacheset_destroy(ps->ps_pcacheset, ps->ps_nsets);
2274 	ps->ps_pcacheset = NULL;
2275 	if (ps->ps_dpbuf != NULL) {
2276 		kmem_free(ps->ps_dpbuf, ps->ps_dpbufsize * sizeof (pollfd_t));
2277 		ps->ps_dpbuf = NULL;
2278 	}
2279 	mutex_destroy(&ps->ps_lock);
2280 	kmem_free(ps, sizeof (pollstate_t));
2281 }
2282 
2283 /*
2284  * We are holding the appropriate uf_lock entering this routine.
2285  * Bump up the ps_busy count to prevent the thread from exiting.
2286  */
2287 void
2288 pollblockexit(fpollinfo_t *fpip)
2289 {
2290 	for (; fpip; fpip = fpip->fp_next) {
2291 		pollcache_t *pcp = fpip->fp_thread->t_pollstate->ps_pcache;
2292 
2293 		mutex_enter(&pcp->pc_no_exit);
2294 		pcp->pc_busy++;  /* prevents exit()'s */
2295 		mutex_exit(&pcp->pc_no_exit);
2296 	}
2297 }
2298 
2299 /*
2300  * Complete phase 2 of cached poll fd cleanup. Call pcache_clean_entry to mark
2301  * the pcacheset events field POLLCLOSED to force the next poll() to remove
2302  * this cache entry. We can't clean the polldat entry clean up here because
2303  * lwp block in poll() needs the info to return. Wakeup anyone blocked in
2304  * poll and let exiting lwp go. No lock is help upon entry. So it's OK for
2305  * pcache_clean_entry to call pollwakeup().
2306  */
2307 void
2308 pollcacheclean(fpollinfo_t *fip, int fd)
2309 {
2310 	struct fpollinfo	*fpip, *fpip2;
2311 
2312 	fpip = fip;
2313 	while (fpip) {
2314 		pollstate_t *ps = fpip->fp_thread->t_pollstate;
2315 		pollcache_t *pcp = ps->ps_pcache;
2316 
2317 		mutex_enter(&ps->ps_lock);
2318 		pcache_clean_entry(ps, fd);
2319 		mutex_exit(&ps->ps_lock);
2320 		mutex_enter(&pcp->pc_no_exit);
2321 		pcp->pc_busy--;
2322 		if (pcp->pc_busy == 0) {
2323 			/*
2324 			 * Wakeup the thread waiting in
2325 			 * thread_exit().
2326 			 */
2327 			cv_signal(&pcp->pc_busy_cv);
2328 		}
2329 		mutex_exit(&pcp->pc_no_exit);
2330 
2331 		fpip2 = fpip;
2332 		fpip = fpip->fp_next;
2333 		kmem_free(fpip2, sizeof (fpollinfo_t));
2334 	}
2335 }
2336 
2337 /*
2338  * one of the cache line's counter is wrapping around. Reset all cache line
2339  * counters to zero except one. This is simplistic, but probably works
2340  * effectively.
2341  */
2342 void
2343 pcacheset_reset_count(pollstate_t *ps, int index)
2344 {
2345 	int	i;
2346 
2347 	ASSERT(MUTEX_HELD(&ps->ps_lock));
2348 	for (i = 0; i < ps->ps_nsets; i++) {
2349 		if (ps->ps_pcacheset[i].pcs_pollfd != NULL) {
2350 			ps->ps_pcacheset[i].pcs_count = 0;
2351 		}
2352 	}
2353 	ps->ps_pcacheset[index].pcs_count = 1;
2354 }
2355 
2356 /*
2357  * this routine implements poll cache list replacement policy.
2358  * It is currently choose the "least used".
2359  */
2360 int
2361 pcacheset_replace(pollstate_t *ps)
2362 {
2363 	int i;
2364 	int index = 0;
2365 
2366 	ASSERT(MUTEX_HELD(&ps->ps_lock));
2367 	for (i = 1; i < ps->ps_nsets; i++) {
2368 		if (ps->ps_pcacheset[index].pcs_count >
2369 		    ps->ps_pcacheset[i].pcs_count) {
2370 			index = i;
2371 		}
2372 	}
2373 	ps->ps_pcacheset[index].pcs_count = 0;
2374 	return (index);
2375 }
2376 
2377 /*
2378  * this routine is called by strclose to remove remaining polldat struct on
2379  * the pollhead list of the device being closed. There are two reasons as why
2380  * the polldat structures still remain on the pollhead list:
2381  *
2382  * (1) The layered device(e.g.the console driver).
2383  * In this case, the existence of a polldat implies that the thread putting
2384  * the polldat on this list has not exited yet. Before the thread exits, it
2385  * will have to hold this pollhead lock to remove the polldat. So holding the
2386  * pollhead lock here effectively prevents the thread which put the polldat
2387  * on this list from exiting.
2388  *
2389  * (2) /dev/poll.
2390  * When a polled fd is cached in /dev/poll, its polldat will remain on the
2391  * pollhead list if the process has not done a POLLREMOVE before closing the
2392  * polled fd. We just unlink it here.
2393  */
2394 void
2395 pollhead_clean(pollhead_t *php)
2396 {
2397 	polldat_t	*pdp;
2398 
2399 	/*
2400 	 * In case(1), while we must prevent the thread in question from
2401 	 * exiting, we must also obey the proper locking order, i.e.
2402 	 * (ps_lock -> phlock).
2403 	 */
2404 	PH_ENTER(php);
2405 	while (php->ph_list != NULL) {
2406 		pollstate_t	*ps;
2407 		pollcache_t	*pcp;
2408 
2409 		pdp = php->ph_list;
2410 		ASSERT(pdp->pd_php == php);
2411 		if (pdp->pd_thread == NULL) {
2412 			/*
2413 			 * This is case(2). Since the ph_lock is sufficient
2414 			 * to synchronize this lwp with any other /dev/poll
2415 			 * lwp, just unlink the polldat.
2416 			 */
2417 			php->ph_list = pdp->pd_next;
2418 			pdp->pd_php = NULL;
2419 			pdp->pd_next = NULL;
2420 			continue;
2421 		}
2422 		ps = pdp->pd_thread->t_pollstate;
2423 		ASSERT(ps != NULL);
2424 		pcp = pdp->pd_pcache;
2425 		ASSERT(pcp != NULL);
2426 		mutex_enter(&pcp->pc_no_exit);
2427 		pcp->pc_busy++;  /* prevents exit()'s */
2428 		mutex_exit(&pcp->pc_no_exit);
2429 		/*
2430 		 * Now get the locks in proper order to avoid deadlock.
2431 		 */
2432 		PH_EXIT(php);
2433 		mutex_enter(&ps->ps_lock);
2434 		/*
2435 		 * while we dropped the pollhead lock, the element could be
2436 		 * taken off the list already.
2437 		 */
2438 		PH_ENTER(php);
2439 		if (pdp->pd_php == php) {
2440 			ASSERT(pdp == php->ph_list);
2441 			php->ph_list = pdp->pd_next;
2442 			pdp->pd_php = NULL;
2443 			pdp->pd_next = NULL;
2444 		}
2445 		PH_EXIT(php);
2446 		mutex_exit(&ps->ps_lock);
2447 		mutex_enter(&pcp->pc_no_exit);
2448 		pcp->pc_busy--;
2449 		if (pcp->pc_busy == 0) {
2450 			/*
2451 			 * Wakeup the thread waiting in
2452 			 * thread_exit().
2453 			 */
2454 			cv_signal(&pcp->pc_busy_cv);
2455 		}
2456 		mutex_exit(&pcp->pc_no_exit);
2457 		PH_ENTER(php);
2458 	}
2459 	PH_EXIT(php);
2460 }
2461 
2462 /*
2463  * The remove_list is called to cleanup a partially cached 'current' list or
2464  * to remove a partial list which is no longer cached. The flag value of 1
2465  * indicates the second case.
2466  */
2467 void
2468 pcacheset_remove_list(pollstate_t *ps, pollfd_t *pollfdp, int start, int end,
2469     int cacheindex, int flag)
2470 {
2471 	int i;
2472 
2473 	ASSERT(MUTEX_HELD(&ps->ps_lock));
2474 	for (i = start; i < end; i++) {
2475 		if ((pollfdp[i].fd >= 0) &&
2476 		    (flag || !(pollfdp[i].revents & POLLNVAL))) {
2477 			if (pcache_delete_fd(ps, pollfdp[i].fd, i, cacheindex,
2478 			    (uint_t)pollfdp[i].events)) {
2479 				int j;
2480 				int fd = pollfdp[i].fd;
2481 
2482 				for (j = i + 1; j < end; j++) {
2483 					if (pollfdp[j].fd == fd) {
2484 						pcache_update_xref(
2485 						    ps->ps_pcache, fd,
2486 						    (ssize_t)j, cacheindex);
2487 						break;
2488 					}
2489 				}
2490 				ASSERT(j <= end);
2491 			}
2492 		}
2493 	}
2494 }
2495 
2496 #ifdef DEBUG
2497 
2498 #include<sys/strsubr.h>
2499 /*
2500  * make sure curthread is not on anyone's pollhead list any more.
2501  */
2502 static void
2503 pollcheckphlist()
2504 {
2505 	int i;
2506 	file_t *fp;
2507 	uf_entry_t *ufp;
2508 	uf_info_t *fip = P_FINFO(curproc);
2509 	struct stdata *stp;
2510 	polldat_t *pdp;
2511 
2512 	mutex_enter(&fip->fi_lock);
2513 	for (i = 0; i < fip->fi_nfiles; i++) {
2514 		UF_ENTER(ufp, fip, i);
2515 		if ((fp = ufp->uf_file) != NULL) {
2516 			if ((stp = fp->f_vnode->v_stream) != NULL) {
2517 				PH_ENTER(&stp->sd_pollist);
2518 				pdp = stp->sd_pollist.ph_list;
2519 				while (pdp) {
2520 					ASSERT(pdp->pd_thread != curthread);
2521 					pdp = pdp->pd_next;
2522 				}
2523 				PH_EXIT(&stp->sd_pollist);
2524 			}
2525 		}
2526 		UF_EXIT(ufp);
2527 	}
2528 	mutex_exit(&fip->fi_lock);
2529 }
2530 
2531 /*
2532  * for resolved set poll list, the xref info in the pcache should be
2533  * consistent with this poll list.
2534  */
2535 static int
2536 pollcheckxref(pollstate_t *ps, int cacheindex)
2537 {
2538 	pollfd_t *pollfdp = ps->ps_pcacheset[cacheindex].pcs_pollfd;
2539 	pollcache_t *pcp = ps->ps_pcache;
2540 	polldat_t *pdp;
2541 	int	i;
2542 	xref_t	*refp;
2543 
2544 	for (i = 0; i < ps->ps_pcacheset[cacheindex].pcs_nfds; i++) {
2545 		if (pollfdp[i].fd < 0) {
2546 			continue;
2547 		}
2548 		pdp = pcache_lookup_fd(pcp, pollfdp[i].fd);
2549 		ASSERT(pdp != NULL);
2550 		ASSERT(pdp->pd_ref != NULL);
2551 		refp = &pdp->pd_ref[cacheindex];
2552 		if (refp->xf_position >= 0) {
2553 			ASSERT(refp->xf_refcnt >= 1);
2554 			ASSERT(pollfdp[refp->xf_position].fd == pdp->pd_fd);
2555 			if (refp->xf_refcnt > 1) {
2556 				int	j;
2557 				int	count = 0;
2558 
2559 				for (j = refp->xf_position;
2560 				    j < ps->ps_pcacheset[cacheindex].pcs_nfds;
2561 				    j++) {
2562 					if (pollfdp[j].fd == pdp->pd_fd) {
2563 						count++;
2564 					}
2565 				}
2566 				ASSERT(count == refp->xf_refcnt);
2567 			}
2568 		}
2569 	}
2570 	return (1);
2571 }
2572 
2573 /*
2574  * For every cached pollfd, its polldat struct should be consistent with
2575  * what is in the pcacheset lists.
2576  */
2577 static void
2578 checkpolldat(pollstate_t *ps)
2579 {
2580 	pollcache_t	*pcp = ps->ps_pcache;
2581 	polldat_t	**hashtbl;
2582 	int		i;
2583 
2584 	hashtbl = pcp->pc_hash;
2585 	for (i = 0; i < pcp->pc_hashsize; i++) {
2586 		polldat_t	*pdp;
2587 
2588 		for (pdp = hashtbl[i]; pdp; pdp = pdp->pd_hashnext) {
2589 			ASSERT(pdp->pd_ref != NULL);
2590 			if (pdp->pd_count > 0) {
2591 				xref_t		*refp;
2592 				int		j;
2593 				pollcacheset_t	*pcsp;
2594 				pollfd_t	*pollfd;
2595 
2596 				for (j = 0; j < ps->ps_nsets; j++) {
2597 					refp = &pdp->pd_ref[j];
2598 					if (refp->xf_refcnt > 0) {
2599 						pcsp = &ps->ps_pcacheset[j];
2600 				ASSERT(refp->xf_position < pcsp->pcs_nfds);
2601 						pollfd = pcsp->pcs_pollfd;
2602 			ASSERT(pdp->pd_fd == pollfd[refp->xf_position].fd);
2603 					}
2604 				}
2605 			}
2606 		}
2607 	}
2608 }
2609 
2610 /*
2611  * every wfd element on ph_list must have a corresponding fpollinfo on the
2612  * uf_fpollinfo list. This is a variation of infpollinfo() w/o holding locks.
2613  */
2614 void
2615 checkwfdlist(vnode_t *vp, fpollinfo_t *fpip)
2616 {
2617 	stdata_t *stp;
2618 	polldat_t *pdp;
2619 	fpollinfo_t *fpip2;
2620 
2621 	if ((stp = vp->v_stream) == NULL) {
2622 		return;
2623 	}
2624 	PH_ENTER(&stp->sd_pollist);
2625 	for (pdp = stp->sd_pollist.ph_list; pdp; pdp = pdp->pd_next) {
2626 		if (pdp->pd_thread->t_procp == curthread->t_procp) {
2627 			for (fpip2 = fpip; fpip2; fpip2 = fpip2->fp_next) {
2628 				if (pdp->pd_thread == fpip2->fp_thread) {
2629 					break;
2630 				}
2631 			}
2632 			ASSERT(fpip2 != NULL);
2633 		}
2634 	}
2635 	PH_EXIT(&stp->sd_pollist);
2636 }
2637 
2638 /*
2639  * For each cached fd whose bit is not set in bitmap, its revents field in
2640  * current poll list should be 0.
2641  */
2642 static int
2643 pollcheckrevents(pollstate_t *ps, int begin, int end, int cacheindex)
2644 {
2645 	pollcache_t	*pcp = ps->ps_pcache;
2646 	pollfd_t	*pollfdp = ps->ps_pollfd;
2647 	int		i;
2648 
2649 	for (i = begin; i < end; i++) {
2650 		polldat_t	*pdp;
2651 
2652 		ASSERT(!BT_TEST(pcp->pc_bitmap, i));
2653 		pdp = pcache_lookup_fd(pcp, i);
2654 		if (pdp && pdp->pd_fp != NULL) {
2655 			xref_t *refp;
2656 			int entry;
2657 
2658 			ASSERT(pdp->pd_ref != NULL);
2659 			refp = &pdp->pd_ref[cacheindex];
2660 			if (refp->xf_refcnt == 0) {
2661 				continue;
2662 			}
2663 			entry = refp->xf_position;
2664 			ASSERT(entry >= 0);
2665 			ASSERT(pollfdp[entry].revents == 0);
2666 			if (refp->xf_refcnt > 1) {
2667 				int j;
2668 
2669 				for (j = entry + 1; j < ps->ps_nfds; j++) {
2670 					if (pollfdp[j].fd == i) {
2671 						ASSERT(pollfdp[j].revents == 0);
2672 					}
2673 				}
2674 			}
2675 		}
2676 	}
2677 	return (1);
2678 }
2679 
2680 #endif	/* DEBUG */
2681 
2682 pollcache_t *
2683 pcache_alloc()
2684 {
2685 	return (kmem_zalloc(sizeof (pollcache_t), KM_SLEEP));
2686 }
2687 
2688 void
2689 pcache_create(pollcache_t *pcp, nfds_t nfds)
2690 {
2691 	size_t	mapsize;
2692 
2693 	/*
2694 	 * allocate enough bits for the poll fd list
2695 	 */
2696 	if ((mapsize = POLLMAPCHUNK) <= nfds) {
2697 		mapsize = (nfds + POLLMAPCHUNK - 1) & ~(POLLMAPCHUNK - 1);
2698 	}
2699 	pcp->pc_bitmap = kmem_zalloc((mapsize / BT_NBIPUL) * sizeof (ulong_t),
2700 	    KM_SLEEP);
2701 	pcp->pc_mapsize = mapsize;
2702 	/*
2703 	 * The hash size is at least POLLHASHCHUNKSZ. If user polls a large
2704 	 * number of fd to start with, allocate a bigger hash table (to the
2705 	 * nearest multiple of POLLHASHCHUNKSZ) because dynamically growing a
2706 	 * hash table is expensive.
2707 	 */
2708 	if (nfds < POLLHASHCHUNKSZ) {
2709 		pcp->pc_hashsize = POLLHASHCHUNKSZ;
2710 	} else {
2711 		pcp->pc_hashsize = (nfds + POLLHASHCHUNKSZ - 1) &
2712 		    ~(POLLHASHCHUNKSZ - 1);
2713 	}
2714 	pcp->pc_hash = kmem_zalloc(pcp->pc_hashsize * sizeof (polldat_t *),
2715 	    KM_SLEEP);
2716 }
2717 
2718 void
2719 pcache_destroy(pollcache_t *pcp)
2720 {
2721 	polldat_t	**hashtbl;
2722 	int i;
2723 
2724 	hashtbl = pcp->pc_hash;
2725 	for (i = 0; i < pcp->pc_hashsize; i++) {
2726 		if (hashtbl[i] != NULL) {
2727 			polldat_t *pdp, *pdp2;
2728 
2729 			pdp = hashtbl[i];
2730 			while (pdp != NULL) {
2731 				pdp2 = pdp->pd_hashnext;
2732 				if (pdp->pd_ref != NULL) {
2733 					kmem_free(pdp->pd_ref, sizeof (xref_t) *
2734 					    pdp->pd_nsets);
2735 				}
2736 				kmem_free(pdp, sizeof (polldat_t));
2737 				pdp = pdp2;
2738 				pcp->pc_fdcount--;
2739 			}
2740 		}
2741 	}
2742 	ASSERT(pcp->pc_fdcount == 0);
2743 	kmem_free(pcp->pc_hash, sizeof (polldat_t *) * pcp->pc_hashsize);
2744 	kmem_free(pcp->pc_bitmap,
2745 	    sizeof (ulong_t) * (pcp->pc_mapsize/BT_NBIPUL));
2746 	mutex_destroy(&pcp->pc_no_exit);
2747 	mutex_destroy(&pcp->pc_lock);
2748 	cv_destroy(&pcp->pc_cv);
2749 	cv_destroy(&pcp->pc_busy_cv);
2750 	kmem_free(pcp, sizeof (pollcache_t));
2751 }
2752 
2753 pollcacheset_t *
2754 pcacheset_create(int nsets)
2755 {
2756 	return (kmem_zalloc(sizeof (pollcacheset_t) * nsets, KM_SLEEP));
2757 }
2758 
2759 void
2760 pcacheset_destroy(pollcacheset_t *pcsp, int nsets)
2761 {
2762 	int i;
2763 
2764 	for (i = 0; i < nsets; i++) {
2765 		if (pcsp[i].pcs_pollfd != NULL) {
2766 			kmem_free(pcsp[i].pcs_pollfd, pcsp[i].pcs_nfds *
2767 			    sizeof (pollfd_t));
2768 		}
2769 	}
2770 	kmem_free(pcsp, sizeof (pollcacheset_t) * nsets);
2771 }
2772 
2773 /*
2774  * Check each duplicated poll fd in the poll list. It may be necessary to
2775  * VOP_POLL the same fd again using different poll events. getf() has been
2776  * done by caller. This routine returns 0 if it can sucessfully process the
2777  * entire poll fd list. It returns -1 if underlying vnode has changed during
2778  * a VOP_POLL, in which case the caller has to repoll. It returns a positive
2779  * value if VOP_POLL failed.
2780  */
2781 static int
2782 plist_chkdupfd(file_t *fp, polldat_t *pdp, pollstate_t *psp, pollfd_t *pollfdp,
2783     int entry, int *fdcntp)
2784 {
2785 	int	i;
2786 	int	fd;
2787 	nfds_t	nfds = psp->ps_nfds;
2788 
2789 	fd = pollfdp[entry].fd;
2790 	for (i = entry + 1; i < nfds; i++) {
2791 		if (pollfdp[i].fd == fd) {
2792 			if (pollfdp[i].events == pollfdp[entry].events) {
2793 				if ((pollfdp[i].revents =
2794 				    pollfdp[entry].revents) != 0) {
2795 					(*fdcntp)++;
2796 				}
2797 			} else {
2798 
2799 				int	error;
2800 				pollhead_t *php;
2801 				pollcache_t *pcp = psp->ps_pcache;
2802 
2803 				/*
2804 				 * the events are different. VOP_POLL on this
2805 				 * fd so that we don't miss any revents.
2806 				 */
2807 				php = NULL;
2808 				ASSERT(curthread->t_pollcache == NULL);
2809 				error = VOP_POLL(fp->f_vnode,
2810 				    pollfdp[i].events, 0,
2811 				    &pollfdp[i].revents, &php, NULL);
2812 				if (error) {
2813 					return (error);
2814 				}
2815 				/*
2816 				 * layered devices(e.g. console driver)
2817 				 * may change the vnode and thus the pollhead
2818 				 * pointer out from underneath us.
2819 				 */
2820 				if (php != NULL && pdp->pd_php != NULL &&
2821 				    php != pdp->pd_php) {
2822 					pollhead_delete(pdp->pd_php, pdp);
2823 					pdp->pd_php = php;
2824 					pollhead_insert(php, pdp);
2825 					/*
2826 					 * We could have missed a wakeup on the
2827 					 * new target device. Make sure the new
2828 					 * target gets polled once.
2829 					 */
2830 					BT_SET(pcp->pc_bitmap, fd);
2831 					return (-1);
2832 				}
2833 				if (pollfdp[i].revents) {
2834 					(*fdcntp)++;
2835 				}
2836 			}
2837 		}
2838 	}
2839 	return (0);
2840 }
2841