xref: /illumos-gate/usr/src/uts/common/fs/portfs/port.c (revision 3470957343f37ed9baa957980891dbbe4c2d7092)
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 2006 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/types.h>
30 #include <sys/systm.h>
31 #include <sys/cred.h>
32 #include <sys/modctl.h>
33 #include <sys/vfs.h>
34 #include <sys/sysmacros.h>
35 #include <sys/cmn_err.h>
36 #include <sys/stat.h>
37 #include <sys/errno.h>
38 #include <sys/kmem.h>
39 #include <sys/file.h>
40 #include <sys/kstat.h>
41 #include <sys/port_impl.h>
42 #include <sys/task.h>
43 #include <sys/project.h>
44 
45 /*
46  * Event Ports can be shared across threads or across processes.
47  * Every thread/process can use an own event port or a group of them
48  * can use a single port. A major request was also to get the ability
49  * to submit user-defined events to a port. The idea of the
50  * user-defined events is to use the event ports for communication between
51  * threads/processes (like message queues). User defined-events are queued
52  * in a port with the same priority as other event types.
53  *
54  * Events are delivered only once. The thread/process which is waiting
55  * for events with the "highest priority" (priority here is related to the
56  * internal strategy to wakeup waiting threads) will retrieve the event,
57  * all other threads/processes will not be notified. There is also
58  * the requirement to have events which should be submitted immediately
59  * to all "waiting" threads. That is the main task of the alert event.
60  * The alert event is submitted by the application to a port. The port
61  * changes from a standard mode to the alert mode. Now all waiting threads
62  * will be awaken immediately and they will return with the alert event.
63  * Threads trying to retrieve events from a port in alert mode will
64  * return immediately with the alert event.
65  *
66  *
67  * An event port is like a kernel queue, which accept events submitted from
68  * user level as well as events submitted from kernel sub-systems. Sub-systems
69  * able to submit events to a port are the so-called "event sources".
70  * Current event sources:
71  * PORT_SOURCE_AIO	 : events submitted per transaction completion from
72  *			   POSIX-I/O framework.
73  * PORT_SOURCE_TIMER	 : events submitted when a timer fires
74  *			   (see timer_create(3RT)).
75  * PORT_SOURCE_FD	 : events submitted per file descriptor (see poll(2)).
76  * PORT_SOURCE_ALERT	 : events submitted from user. This is not really a
77  *			   single event, this is actually a port mode
78  *			   (see port_alert(3c)).
79  * PORT_SOURCE_USER	 : events submitted by applications with
80  *			   port_send(3c) or port_sendn(3c).
81  *
82  * There is a user API implemented in the libc library as well as a
83  * kernel API implemented in port_subr.c in genunix.
84  * The available user API functions are:
85  * port_create() : create a port as a file descriptor of portfs file system
86  *		   The standard close(2) function closes a port.
87  * port_associate() : associate a file descriptor with a port to be able to
88  *		      retrieve events from that file descriptor.
89  * port_dissociate(): remove the association of a file descriptor with a port.
90  * port_alert()	 : set/unset a port in alert mode
91  * port_send()	 : send an event of type PORT_SOURCE_USER to a port
92  * port_sendn()	 : send an event of type PORT_SOURCE_USER to a list of ports
93  * port_get()	 : retrieve a single event from a port
94  * port_getn()	 : retrieve a list of events from a port
95  *
96  * The available kernel API functions are:
97  * port_allocate_event(): allocate an event slot/structure of/from a port
98  * port_init_event()    : set event data in the event structure
99  * port_send_event()    : send event to a port
100  * port_free_event()    : deliver allocated slot/structure back to a port
101  * port_associate_ksource(): associate a kernel event source with a port
102  * port_dissociate_ksource(): dissociate a kernel event source from a port
103  *
104  * The libc implementation consists of small functions which pass the
105  * arguments to the kernel using the "portfs" system call. It means, all the
106  * synchronisation work is being done in the kernel. The "portfs" system
107  * call loads the portfs file system into the kernel.
108  *
109  * PORT CREATION
110  * The first function to be used is port_create() which internally creates
111  * a vnode and a portfs node. The portfs node is represented by the port_t
112  * structure, which again includes all the data necessary to control a port.
113  * port_create() returns a file descriptor, which needs to be used in almost
114  * all other event port functions.
115  * The maximum number of ports per system is controlled by the resource
116  * control: project:port-max-ids.
117  *
118  * EVENT GENERATION
119  * The second step is the triggering of events, which could be sent to a port.
120  * Every event source implements an own method to generate events for a port:
121  * PORT_SOURCE_AIO:
122  * 	The sigevent structure of the standard POSIX-IO functions
123  * 	was extended by an additional notification type.
124  * 	Standard notification types:
125  * 	SIGEV_NONE, SIGEV_SIGNAL and SIGEV_THREAD
126  * 	Event ports introduced now SIGEV_PORT.
127  * 	The notification type SIGEV_PORT specifies that a structure
128  * 	of type port_notify_t has to be attached to the sigev_value.
129  * 	The port_notify_t structure contains the event port file
130  * 	descriptor and a user-defined pointer.
131  * 	Internally the AIO implementation will use the kernel API
132  * 	functions to allocate an event port slot per transaction (aiocb)
133  * 	and sent the event to the port as soon as the transaction completes.
134  * 	All the events submitted per transaction are of type
135  * 	PORT_SOURCE_AIO.
136  * PORT_SOURCE_TIMER:
137  * 	The timer_create() function uses the same method as the
138  * 	PORT_SOURCE_AIO event source. It also uses the sigevent structure
139  * 	to deliver the port information.
140  * 	Internally the timer code will allocate a single event slot/struct
141  * 	per timer and it will send the timer event as soon as the timer
142  * 	fires. If the timer-fired event is not delivered to the application
143  * 	before the next period elapsed, then an overrun counter will be
144  * 	incremented. The timer event source uses a callback function to
145  * 	detect the delivery of the event to the application. At that time
146  * 	the timer callback function will update the event overrun counter.
147  * PORT_SOURCE_FD:
148  * 	This event source uses the port_associate() function to allocate
149  * 	an event slot/struct from a port. The application defines in the
150  * 	events argument of port_associate() the type of events which it is
151  * 	interested on.
152  * 	The internal pollwakeup() function is used by all the file
153  * 	systems --which are supporting the VOP_POLL() interface- to notify
154  * 	the upper layer (poll(2), devpoll(7d) and now event ports) about
155  * 	the event triggered (see valid events in poll(2)).
156  * 	The pollwakeup() function forwards the event to the layer registered
157  * 	to receive the current event.
158  * 	The port_dissociate() function can be used to free the allocated
159  * 	event slot from the port. Anyway, file descriptors deliver events
160  * 	only one time and remain deactivated until the application
161  * 	reactivates the association of a file descriptor with port_associate().
162  * 	If an associated file descriptor is closed then the file descriptor
163  * 	will be dissociated automatically from the port.
164  *
165  * PORT_SOURCE_ALERT:
166  * 	This event type is generated when the port was previously set in
167  * 	alert mode using the port_alert() function.
168  * 	A single alert event is delivered to every thread which tries to
169  * 	retrieve events from a port.
170  * PORT_SOURCE_USER:
171  * 	This type of event is generated from user level using the port_send()
172  * 	function to send a user event to a port or the port_sendn() function
173  * 	to send an event to a list of ports.
174  *
175  * EVENT DELIVERY / RETRIEVING EVENTS
176  * Events remain in the port queue until:
177  * - the application uses port_get() or port_getn() to retrieve events,
178  * - the event source cancel the event,
179  * - the event port is closed or
180  * - the process exits.
181  * The maximal number of events in a port queue is the maximal number
182  * of event slots/structures which can be allocated by event sources.
183  * The allocation of event slots/structures is controlled by the resource
184  * control: process.port-max-events.
185  * The port_get() function retrieves a single event and the port_getn()
186  * function retrieves a list of events.
187  * Events are classified as shareable and non-shareable events across processes.
188  * Non-shareable events are invisible for the port_get(n)() functions of
189  * processes other than the owner of the event.
190  *    Shareable event types are:
191  *    PORT_SOURCE_USER events
192  * 	This type of event is unconditionally shareable and without
193  * 	limitations. If the parent process sends a user event and closes
194  * 	the port afterwards, the event remains in the port and the child
195  * 	process will still be able to retrieve the user event.
196  *    PORT_SOURCE_ALERT events
197  * 	This type of event is shareable between processes.
198  * 	Limitation:	The alert mode of the port is removed if the owner
199  * 			(process which set the port in alert mode) of the
200  * 			alert event closes the port.
201  *    PORT_SOURCE_FD events
202  * 	This type of event is conditional shareable between processes.
203  * 	After fork(2) all forked file descriptors are shareable between
204  * 	the processes. The child process is allowed to retrieve events
205  * 	from the associated file descriptors and it can also re-associate
206  * 	the fd with the port.
207  * 	Limitations:	The child process is not allowed to dissociate
208  * 			the file descriptor from the port. Only the
209  * 			owner (process) of the association is allowed to
210  * 			dissociate the file descriptor from the port.
211  * 			If the owner of the association closes the port
212  * 			the association will be removed.
213  *    PORT_SOURCE_AIO events
214  * 	This type of event is not shareable between processes.
215  *    PORT_SOURCE_TIMER events
216  * 	This type of event is not shareable between processes.
217  *
218  * FORK BEHAVIOUR
219  * On fork(2) the child process inherits all opened file descriptors from
220  * the parent process. This is also valid for port file descriptors.
221  * Associated file descriptors with a port maintain the association across the
222  * fork(2). It means, the child process gets full access to the port and
223  * it can retrieve events from all common associated file descriptors.
224  * Events of file descriptors created and associated with a port after the
225  * fork(2) are non-shareable and can only be retrieved by the same process.
226  *
227  * If the parent or the child process closes an exported port (using fork(2)
228  * or I_SENDFD) all the file descriptors associated with the port by the
229  * process will be dissociated from the port. Events of dissociated file
230  * descriptors as well as all non-shareable events will be discarded.
231  * The other process can continue working with the port as usual.
232  *
233  * CLOSING A PORT
234  * close(2) has to be used to close a port. See FORK BEHAVIOUR for details.
235  *
236  * PORT EVENT STRUCTURES
237  * The global control structure of the event ports framework is port_control_t.
238  * port_control_t keeps track of the number of created ports in the system.
239  * The cache of the port event structures is also located in port_control_t.
240  *
241  * On port_create() the vnode and the portfs node is also created.
242  * The portfs node is represented by the port_t structure.
243  * The port_t structure manages all port specific tasks:
244  * - management of resource control values
245  * - port VOP_POLL interface
246  * - creation time
247  * - uid and gid of the port
248  *
249  * The port_t structure contains the port_queue_t structure.
250  * The port_queue_t structure contains all the data necessary for the
251  * queue management:
252  * - locking
253  * - condition variables
254  * - event counters
255  * - submitted events	(represented by port_kevent_t structures)
256  * - threads waiting for event delivery (check portget_t structure)
257  * - PORT_SOURCE_FD cache	(managed by the port_fdcache_t structure)
258  * - event source management (managed by the port_source_t structure)
259  * - alert mode management	(check port_alert_t structure)
260  *
261  * EVENT MANAGEMENT
262  * The event port file system creates a kmem_cache for internal allocation of
263  * event port structures.
264  *
265  * 1. Event source association with a port:
266  * The first step to do for event sources is to get associated with a port
267  * using the port_associate_ksource() function or adding an entry to the
268  * port_ksource_tab[]. An event source can get dissociated from a port
269  * using the port_dissociate_ksource() function. An entry in the
270  * port_ksource_tab[] implies that the source will be associated
271  * automatically with every new created port.
272  * The event source can deliver a callback function, which is used by the
273  * port to notify the event source about close(2). The idea is that
274  * in such a case the event source should free all allocated resources
275  * and it must return to the port all allocated slots/structures.
276  * The port_close() function will wait until all allocated event
277  * structures/slots are returned to the port.
278  * The callback function is not necessary when the event source does not
279  * maintain local resources, a second condition is that the event source
280  * can guarantee that allocated event slots will be returned without
281  * delay to the port (it will not block and sleep somewhere).
282  *
283  * 2. Reservation of an event slot / event structure
284  * The event port reliability is based on the reservation of an event "slot"
285  * (allocation of an event structure) by the event source as part of the
286  * application call. If the maximal number of event slots is exhausted then
287  * the event source can return a corresponding error code to the application.
288  *
289  * The port_alloc_event() function has to be used by event sources to
290  * allocate an event slot (reserve an event structure). The port_alloc_event()
291  * doesn not block and it will return a 0 value on success or an error code
292  * if it fails.
293  * An argument of port_alloc_event() is a flag which determines the behavior
294  * of the event after it was delivered to the application:
295  * PORT_ALLOC_DEFAULT	: event slot becomes free after delivery to the
296  *			  application.
297  * PORT_ALLOC_PRIVATE	: event slot remains under the control of the event
298  *			  source. This kind of slots can not be used for
299  *			  event delivery and should only be used internally
300  *			  by the event source.
301  * PORT_KEV_CACHED	: event slot remains under the control of an event
302  *			  port cache. It does not become free after delivery
303  *			  to the application.
304  * PORT_ALLOC_SCACHED	: event slot remains under the control of the event
305  *			  source. The event source takes the control over
306  *			  the slot after the event is delivered to the
307  *			  application.
308  *
309  * 3. Delivery of events to the event port
310  * Earlier allocated event structure/slot has to be used to deliver
311  * event data to the port. Event source has to use the function
312  * port_send_event(). The single argument is a pointer to the previously
313  * reserved event structure/slot.
314  * The portkev_events field of the port_kevent_t structure can be updated/set
315  * in two ways:
316  * 1. using the port_set_event() function, or
317  * 2. updating the portkev_events field out of the callback function:
318  *    The event source can deliver a callback function to the port as an
319  *    argument of port_init_event().
320  *    One of the arguments of the callback function is a pointer to the
321  *    events field, which will be delivered to the application.
322  *    (see Delivery of events to the application).
323  * Event structures/slots can be delivered to the event port only one time,
324  * they remain blocked until the data is delivered to the application and the
325  * slot becomes free or it is delivered back to the event source
326  * (PORT_ALLOC_SCACHED). The activation of the callback function mentioned above
327  * is at the same time the indicator for the event source that the event
328  * structure/slot is free for reuse.
329  *
330  * 4. Delivery of events to the application
331  * The events structures/slots delivered by event sources remain in the
332  * port queue until they are retrieved by the application or the port
333  * is closed (exit(2) also closes all opened file descriptors)..
334  * The application uses port_get() or port_getn() to retrieve events from
335  * a port. port_get() retrieves a single event structure/slot and port_getn()
336  * retrieves a list of event structures/slots.
337  * Both functions are able to poll for events and return immediately or they
338  * can specify a timeout value.
339  * Before the events are delivered to the application they are moved to a
340  * second temporary internal queue. The idea is to avoid lock collisions or
341  * contentions of the global queue lock.
342  * The global queue lock is used every time when an event source delivers
343  * new events to the port.
344  * The port_get() and port_getn() functions
345  * a) retrieve single events from the temporary queue,
346  * b) prepare the data to be passed to the application memory,
347  * c) activate the callback function of the event sources:
348  *    - to get the latest event data,
349  *    - the event source can free all allocated resources associated with the
350  *      current event,
351  *    - the event source can re-use the current event slot/structure
352  *    - the event source can deny the delivery of the event to the application
353  *      (e.g. because of the wrong process).
354  * d) put the event back to the temporary queue if the event delivery was denied
355  * e) repeat a) until d) as long as there are events in the queue and
356  *    there is enough user space available.
357  *
358  * The loop described above could block for a very long time the global mutex,
359  * to avoid that a second mutex was introduced to synchronized concurrent
360  * threads accessing the temporary queue.
361  */
362 
363 static int64_t portfs(int, uintptr_t, uintptr_t, uintptr_t, uintptr_t,
364     uintptr_t);
365 
366 static struct sysent port_sysent = {
367 	6,
368 	SE_ARGC | SE_64RVAL | SE_NOUNLOAD,
369 	(int (*)())portfs,
370 };
371 
372 static struct modlsys modlsys = {
373 	&mod_syscallops, "event ports", &port_sysent
374 };
375 
376 #ifdef _SYSCALL32_IMPL
377 
378 static int64_t
379 portfs32(uint32_t arg1, int32_t arg2, uint32_t arg3, uint32_t arg4,
380     uint32_t arg5, uint32_t arg6);
381 
382 static struct sysent port_sysent32 = {
383 	6,
384 	SE_ARGC | SE_64RVAL | SE_NOUNLOAD,
385 	(int (*)())portfs32,
386 };
387 
388 static struct modlsys modlsys32 = {
389 	&mod_syscallops32,
390 	"32-bit event ports syscalls",
391 	&port_sysent32
392 };
393 #endif	/* _SYSCALL32_IMPL */
394 
395 static struct modlinkage modlinkage = {
396 	MODREV_1,
397 	&modlsys,
398 #ifdef _SYSCALL32_IMPL
399 	&modlsys32,
400 #endif
401 	NULL
402 };
403 
404 port_kstat_t port_kstat = {
405 	{ "ports",	KSTAT_DATA_UINT32 }
406 };
407 
408 dev_t	portdev;
409 struct	vnodeops *port_vnodeops;
410 struct	vfs port_vfs;
411 
412 extern	rctl_hndl_t rc_process_portev;
413 extern	rctl_hndl_t rc_project_portids;
414 extern	void aio_close_port(void *, int, pid_t, int);
415 
416 /*
417  * This table contains a list of event sources which need a static
418  * association with a port (every port).
419  * The last NULL entry in the table is required to detect "end of table".
420  */
421 struct port_ksource port_ksource_tab[] = {
422 	{PORT_SOURCE_AIO, aio_close_port, NULL, NULL},
423 	{0, NULL, NULL, NULL}
424 };
425 
426 /* local functions */
427 static int port_getn(port_t *, port_event_t *, uint_t, uint_t *,
428     port_gettimer_t *);
429 static int port_sendn(int [], int [], uint_t, int, void *, uint_t *);
430 static int port_alert(port_t *, int, int, void *);
431 static int port_dispatch_event(port_t *, int, int, int, uintptr_t, void *);
432 static int port_send(port_t *, int, int, void *);
433 static int port_create(int *);
434 static int port_get_alert(port_alert_t *, port_event_t *);
435 static int port_copy_event(port_event_t *, port_kevent_t *, list_t *);
436 static int *port_errorn(int *, int, int, int);
437 static int port_noshare(void *, int *, pid_t, int, void *);
438 static int port_get_timeout(timespec_t *, timespec_t *, timespec_t **, int *,
439     int);
440 static void port_init(port_t *);
441 static void port_remove_alert(port_queue_t *);
442 static void port_add_ksource_local(port_t *, port_ksource_t *);
443 static void port_check_return_cond(port_queue_t *);
444 static void port_dequeue_thread(port_queue_t *, portget_t *);
445 static portget_t *port_queue_thread(port_queue_t *, uint_t);
446 static void port_kstat_init(void);
447 
448 #ifdef	_SYSCALL32_IMPL
449 static int port_copy_event32(port_event32_t *, port_kevent_t *, list_t *);
450 #endif
451 
452 int
453 _init(void)
454 {
455 	static const fs_operation_def_t port_vfsops_template[] = {
456 		NULL, NULL
457 	};
458 	extern const	fs_operation_def_t port_vnodeops_template[];
459 	vfsops_t	*port_vfsops;
460 	int		error;
461 	major_t 	major;
462 
463 	if ((major = getudev()) == (major_t)-1)
464 		return (ENXIO);
465 	portdev = makedevice(major, 0);
466 
467 	/* Create a dummy vfs */
468 	error = vfs_makefsops(port_vfsops_template, &port_vfsops);
469 	if (error) {
470 		cmn_err(CE_WARN, "port init: bad vfs ops");
471 		return (error);
472 	}
473 	vfs_setops(&port_vfs, port_vfsops);
474 	port_vfs.vfs_flag = VFS_RDONLY;
475 	port_vfs.vfs_dev = portdev;
476 	vfs_make_fsid(&(port_vfs.vfs_fsid), portdev, 0);
477 
478 	error = vn_make_ops("portfs", port_vnodeops_template, &port_vnodeops);
479 	if (error) {
480 		vfs_freevfsops(port_vfsops);
481 		cmn_err(CE_WARN, "port init: bad vnode ops");
482 		return (error);
483 	}
484 
485 	mutex_init(&port_control.pc_mutex, NULL, MUTEX_DEFAULT, NULL);
486 	port_control.pc_nents = 0;	/* number of active ports */
487 
488 	/* create kmem_cache for port event structures */
489 	port_control.pc_cache = kmem_cache_create("port_cache",
490 	    sizeof (port_kevent_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
491 
492 	port_kstat_init();		/* init port kstats */
493 	return (mod_install(&modlinkage));
494 }
495 
496 int
497 _info(struct modinfo *modinfop)
498 {
499 	return (mod_info(&modlinkage, modinfop));
500 }
501 
502 /*
503  * System call wrapper for all port related system calls from 32-bit programs.
504  */
505 #ifdef _SYSCALL32_IMPL
506 static int64_t
507 portfs32(uint32_t opcode, int32_t a0, uint32_t a1, uint32_t a2, uint32_t a3,
508     uint32_t a4)
509 {
510 	int64_t	error;
511 
512 	switch (opcode & PORT_CODE_MASK) {
513 	case PORT_GET:
514 		error = portfs(PORT_GET, a0, a1, (int)a2, (int)a3, a4);
515 		break;
516 	case PORT_SENDN:
517 		error = portfs(opcode, (uint32_t)a0, a1, a2, a3, a4);
518 		break;
519 	default:
520 		error = portfs(opcode, a0, a1, a2, a3, a4);
521 		break;
522 	}
523 	return (error);
524 }
525 #endif	/* _SYSCALL32_IMPL */
526 
527 /*
528  * System entry point for port functions.
529  * a0 is a port file descriptor (except for PORT_SENDN and PORT_CREATE).
530  * The libc uses PORT_SYS_NOPORT in functions which do not deliver a
531  * port file descriptor as first argument.
532  */
533 static int64_t
534 portfs(int opcode, uintptr_t a0, uintptr_t a1, uintptr_t a2, uintptr_t a3,
535     uintptr_t a4)
536 {
537 	rval_t		r;
538 	port_t		*pp;
539 	int 		error = 0;
540 	uint_t		nget;
541 	file_t		*fp;
542 	port_gettimer_t	port_timer;
543 
544 	r.r_vals = 0;
545 	if (opcode & PORT_SYS_NOPORT) {
546 		opcode &= PORT_CODE_MASK;
547 		if (opcode == PORT_SENDN) {
548 			error = port_sendn((int *)a0, (int *)a1, (uint_t)a2,
549 			    (int)a3, (void *)a4, (uint_t *)&r.r_val1);
550 			if (error && (error != EIO))
551 				return ((int64_t)set_errno(error));
552 			return (r.r_vals);
553 		}
554 
555 		if (opcode == PORT_CREATE) {
556 			error = port_create(&r.r_val1);
557 			if (error)
558 				return ((int64_t)set_errno(error));
559 			return (r.r_vals);
560 		}
561 	}
562 
563 	/* opcodes using port as first argument (a0) */
564 
565 	if ((fp = getf((int)a0)) == NULL)
566 		return ((uintptr_t)set_errno(EBADF));
567 
568 	if (fp->f_vnode->v_type != VPORT) {
569 		releasef((int)a0);
570 		return ((uintptr_t)set_errno(EBADFD));
571 	}
572 
573 	pp = VTOEP(fp->f_vnode);
574 
575 	switch (opcode & PORT_CODE_MASK) {
576 	case	PORT_GET:
577 	{
578 		/* see PORT_GETN description */
579 		struct	timespec timeout;
580 
581 		port_timer.pgt_flags = PORTGET_ONE;
582 		port_timer.pgt_loop = 0;
583 		port_timer.pgt_rqtp = NULL;
584 		if (a4 != NULL) {
585 			port_timer.pgt_timeout = &timeout;
586 			timeout.tv_sec = (time_t)a2;
587 			timeout.tv_nsec = (long)a3;
588 		} else {
589 			port_timer.pgt_timeout = NULL;
590 		}
591 		do {
592 			nget = 1;
593 			error = port_getn(pp, (port_event_t *)a1, 1,
594 			    (uint_t *)&nget, &port_timer);
595 		} while (nget == 0 && error == 0 && port_timer.pgt_loop);
596 		break;
597 	}
598 	case	PORT_GETN:
599 	{
600 		/*
601 		 * port_getn() can only retrieve own or shareable events from
602 		 * other processes. The port_getn() function remains in the
603 		 * kernel until own or shareable events are available or the
604 		 * timeout elapses.
605 		 */
606 		port_timer.pgt_flags = 0;
607 		port_timer.pgt_loop = 0;
608 		port_timer.pgt_rqtp = NULL;
609 		port_timer.pgt_timeout = (struct timespec *)a4;
610 		do {
611 			nget = a3;
612 			error = port_getn(pp, (port_event_t *)a1, (uint_t)a2,
613 			    (uint_t *)&nget, &port_timer);
614 		} while (nget == 0 && error == 0 && port_timer.pgt_loop);
615 		r.r_val1 = nget;
616 		r.r_val2 = error;
617 		releasef((int)a0);
618 		if (error && error != ETIME)
619 			return ((int64_t)set_errno(error));
620 		return (r.r_vals);
621 	}
622 	case	PORT_ASSOCIATE:
623 	{
624 		/* currently only PORT_SOURCE_FD is implemented */
625 		if ((int)a1 != PORT_SOURCE_FD) {
626 			error = EINVAL;
627 			break;
628 		}
629 		error = port_associate_fd(pp, (int)a1, (uintptr_t)a2, (int)a3,
630 			    (void *)a4);
631 		break;
632 	}
633 	case	PORT_SEND:
634 	{
635 		/* user-defined events */
636 		error = port_send(pp, PORT_SOURCE_USER, (int)a1, (void *)a2);
637 		break;
638 	}
639 	case	PORT_DISPATCH:
640 	{
641 		/*
642 		 * library events, blocking
643 		 * Only events of type PORT_SOURCE_AIO or PORT_SOURCE_MQ
644 		 * are currently allowed.
645 		 */
646 		if ((int)a1 != PORT_SOURCE_AIO && (int)a1 != PORT_SOURCE_MQ) {
647 			error = EINVAL;
648 			break;
649 		}
650 		error = port_dispatch_event(pp, (int)opcode, (int)a1, (int)a2,
651 		    (uintptr_t)a3, (void *)a4);
652 		break;
653 	}
654 	case	PORT_DISSOCIATE:
655 	{
656 		/* currently only PORT_SOURCE_FD is implemented */
657 		if ((int)a1 != PORT_SOURCE_FD) {
658 			error = EINVAL;
659 			break;
660 		}
661 		error = port_dissociate_fd(pp, (uintptr_t)a2);
662 		break;
663 	}
664 	case	PORT_ALERT:
665 	{
666 		if ((int)a2)	/* a2 = events */
667 			error = port_alert(pp, (int)a1, (int)a2, (void *)a3);
668 		else
669 			port_remove_alert(&pp->port_queue);
670 		break;
671 	}
672 	default:
673 		error = EINVAL;
674 		break;
675 	}
676 
677 	releasef((int)a0);
678 	if (error)
679 		return ((int64_t)set_errno(error));
680 	return (r.r_vals);
681 }
682 
683 /*
684  * System call to create a port.
685  *
686  * The port_create() function creates a vnode of type VPORT per port.
687  * The port control data is associated with the vnode as vnode private data.
688  * The port_create() function returns an event port file descriptor.
689  */
690 static int
691 port_create(int *fdp)
692 {
693 	port_t		*pp;
694 	vnode_t		*vp;
695 	struct file	*fp;
696 	proc_t		*p = curproc;
697 
698 	/* initialize vnode and port private data */
699 	pp = kmem_zalloc(sizeof (port_t), KM_SLEEP);
700 
701 	pp->port_vnode = vn_alloc(KM_SLEEP);
702 	vp = EPTOV(pp);
703 	vn_setops(vp, port_vnodeops);
704 	vp->v_type = VPORT;
705 	vp->v_vfsp = &port_vfs;
706 	vp->v_data = (caddr_t)pp;
707 
708 	mutex_enter(&port_control.pc_mutex);
709 	/*
710 	 * Retrieve the maximal number of event ports allowed per system from
711 	 * the resource control: project.port-max-ids.
712 	 */
713 	mutex_enter(&p->p_lock);
714 	if (rctl_test(rc_project_portids, p->p_task->tk_proj->kpj_rctls, p,
715 	    port_control.pc_nents + 1, RCA_SAFE) & RCT_DENY) {
716 		mutex_exit(&p->p_lock);
717 		vn_free(vp);
718 		kmem_free(pp, sizeof (port_t));
719 		mutex_exit(&port_control.pc_mutex);
720 		return (EAGAIN);
721 	}
722 
723 	/*
724 	 * Retrieve the maximal number of events allowed per port from
725 	 * the resource control: process.port-max-events.
726 	 */
727 	pp->port_max_events = rctl_enforced_value(rc_process_portev,
728 	    p->p_rctls, p);
729 	mutex_exit(&p->p_lock);
730 
731 	/* allocate a new user file descriptor and a file structure */
732 	if (falloc(vp, 0, &fp, fdp)) {
733 		/*
734 		 * If the file table is full, free allocated resources.
735 		 */
736 		vn_free(vp);
737 		kmem_free(pp, sizeof (port_t));
738 		mutex_exit(&port_control.pc_mutex);
739 		return (EMFILE);
740 	}
741 
742 	mutex_exit(&fp->f_tlock);
743 
744 	pp->port_fd = *fdp;
745 	port_control.pc_nents++;
746 	p->p_portcnt++;
747 	port_kstat.pks_ports.value.ui32++;
748 	mutex_exit(&port_control.pc_mutex);
749 
750 	/* initializes port private data */
751 	port_init(pp);
752 	/* set user file pointer */
753 	setf(*fdp, fp);
754 	return (0);
755 }
756 
757 /*
758  * port_init() initializes event port specific data
759  */
760 static void
761 port_init(port_t *pp)
762 {
763 	port_queue_t	*portq;
764 	port_ksource_t	*pks;
765 
766 	mutex_init(&pp->port_mutex, NULL, MUTEX_DEFAULT, NULL);
767 	portq = &pp->port_queue;
768 	mutex_init(&portq->portq_mutex, NULL, MUTEX_DEFAULT, NULL);
769 	pp->port_flags |= PORT_INIT;
770 
771 	/*
772 	 * If it is not enough memory available to satisfy a user
773 	 * request using a single port_getn() call then port_getn()
774 	 * will reduce the size of the list to PORT_MAX_LIST.
775 	 */
776 	pp->port_max_list = port_max_list;
777 
778 	/* Set timestamp entries required for fstat(2) requests */
779 	gethrestime(&pp->port_ctime);
780 	pp->port_uid = crgetuid(curproc->p_cred);
781 	pp->port_gid = crgetgid(curproc->p_cred);
782 
783 	/* initialize port queue structs */
784 	list_create(&portq->portq_list, sizeof (port_kevent_t),
785 	    offsetof(port_kevent_t, portkev_node));
786 	list_create(&portq->portq_get_list, sizeof (port_kevent_t),
787 	    offsetof(port_kevent_t, portkev_node));
788 	portq->portq_flags = 0;
789 	pp->port_pid = curproc->p_pid;
790 
791 	/* Allocate cache skeleton for PORT_SOURCE_FD events */
792 	portq->portq_pcp = kmem_zalloc(sizeof (port_fdcache_t), KM_SLEEP);
793 	mutex_init(&portq->portq_pcp->pc_lock, NULL, MUTEX_DEFAULT, NULL);
794 
795 	/*
796 	 * Allocate cache skeleton for association of event sources.
797 	 */
798 	mutex_init(&portq->portq_source_mutex, NULL, MUTEX_DEFAULT, NULL);
799 	portq->portq_scache = kmem_zalloc(
800 	    PORT_SCACHE_SIZE * sizeof (port_source_t *), KM_SLEEP);
801 
802 	/*
803 	 * pre-associate some kernel sources with this port.
804 	 * The pre-association is required to create port_source_t
805 	 * structures for object association.
806 	 * Some sources can not get associated with a port before the first
807 	 * object association is requested. Another reason to pre_associate
808 	 * a particular source with a port is because of performance.
809 	 */
810 
811 	for (pks = port_ksource_tab; pks->pks_source != 0; pks++)
812 		port_add_ksource_local(pp, pks);
813 }
814 
815 /*
816  * The port_add_ksource_local() function is being used to associate
817  * event sources with every new port.
818  * The event sources need to be added to port_ksource_tab[].
819  */
820 static void
821 port_add_ksource_local(port_t *pp, port_ksource_t *pks)
822 {
823 	port_source_t	*pse;
824 	port_source_t	**ps;
825 
826 	mutex_enter(&pp->port_queue.portq_source_mutex);
827 	ps = &pp->port_queue.portq_scache[PORT_SHASH(pks->pks_source)];
828 	for (pse = *ps; pse != NULL; pse = pse->portsrc_next) {
829 		if (pse->portsrc_source == pks->pks_source)
830 			break;
831 	}
832 
833 	if (pse == NULL) {
834 		/* associate new source with the port */
835 		pse = kmem_zalloc(sizeof (port_source_t), KM_SLEEP);
836 		pse->portsrc_source = pks->pks_source;
837 		pse->portsrc_close = pks->pks_close;
838 		pse->portsrc_closearg = pks->pks_closearg;
839 		pse->portsrc_cnt = 1;
840 
841 		pks->pks_portsrc = pse;
842 		if (*ps != NULL)
843 			pse->portsrc_next = (*ps)->portsrc_next;
844 		*ps = pse;
845 	}
846 	mutex_exit(&pp->port_queue.portq_source_mutex);
847 }
848 
849 /*
850  * The port_send() function sends an event of type "source" to a
851  * port. This function is non-blocking. An event can be sent to
852  * a port as long as the number of events per port does not achieve the
853  * maximal allowed number of events. The max. number of events per port is
854  * defined by the resource control process.max-port-events.
855  * This function is used by the port library function port_send()
856  * and port_dispatch(). The port_send(3c) function is part of the
857  * event ports API and submits events of type PORT_SOURCE_USER. The
858  * port_dispatch() function is project private and it is used by library
859  * functions to submit events of other types than PORT_SOURCE_USER
860  * (e.g. PORT_SOURCE_AIO).
861  */
862 static int
863 port_send(port_t *pp, int source, int events, void *user)
864 {
865 	port_kevent_t	*pev;
866 	int		error;
867 
868 	error = port_alloc_event_local(pp, source, PORT_ALLOC_DEFAULT, &pev);
869 	if (error)
870 		return (error);
871 
872 	pev->portkev_object = 0;
873 	pev->portkev_events = events;
874 	pev->portkev_user = user;
875 	pev->portkev_callback = NULL;
876 	pev->portkev_arg = NULL;
877 	pev->portkev_flags = 0;
878 
879 	port_send_event(pev);
880 	return (0);
881 }
882 
883 /*
884  * The port_noshare() function returns 0 if the current event was generated
885  * by the same process. Otherwise is returns a value other than 0 and the
886  * event should not be delivered to the current processe.
887  * The port_noshare() function is normally used by the port_dispatch()
888  * function. The port_dispatch() function is project private and can only be
889  * used within the event port project.
890  * Currently the libaio uses the port_dispatch() function to deliver events
891  * of types PORT_SOURCE_AIO.
892  */
893 /* ARGSUSED */
894 static int
895 port_noshare(void *arg, int *events, pid_t pid, int flag, void *evp)
896 {
897 	if (flag == PORT_CALLBACK_DEFAULT && curproc->p_pid != pid)
898 		return (1);
899 	return (0);
900 }
901 
902 /*
903  * The port_dispatch_event() function is project private and it is used by
904  * libraries involved in the project to deliver events to the port.
905  * port_dispatch will sleep and wait for enough resources to satisfy the
906  * request, if necessary.
907  * The library can specify if the delivered event is shareable with other
908  * processes (see PORT_SYS_NOSHARE flag).
909  */
910 static int
911 port_dispatch_event(port_t *pp, int opcode, int source, int events,
912     uintptr_t object, void *user)
913 {
914 	port_kevent_t	*pev;
915 	int		error;
916 
917 	error = port_alloc_event_block(pp, source, PORT_ALLOC_DEFAULT, &pev);
918 	if (error)
919 		return (error);
920 
921 	pev->portkev_object = object;
922 	pev->portkev_events = events;
923 	pev->portkev_user = user;
924 	pev->portkev_arg = NULL;
925 	if (opcode & PORT_SYS_NOSHARE) {
926 		pev->portkev_flags = PORT_KEV_NOSHARE;
927 		pev->portkev_callback = port_noshare;
928 	} else {
929 		pev->portkev_flags = 0;
930 		pev->portkev_callback = NULL;
931 	}
932 
933 	port_send_event(pev);
934 	return (0);
935 }
936 
937 
938 /*
939  * The port_sendn() function is the kernel implementation of the event
940  * port API function port_sendn(3c).
941  * This function is able to send an event to a list of event ports.
942  */
943 static int
944 port_sendn(int ports[], int errors[], uint_t nent, int events, void *user,
945     uint_t *nget)
946 {
947 	port_kevent_t	*pev;
948 	int		errorcnt = 0;
949 	int		error = 0;
950 	int		count;
951 	int		port;
952 	int		*plist;
953 	int		*elist = NULL;
954 	file_t		*fp;
955 	port_t		*pp;
956 
957 	if (nent == 0 || nent > port_max_list)
958 		return (EINVAL);
959 
960 	plist = kmem_alloc(nent * sizeof (int), KM_SLEEP);
961 	if (copyin((void *)ports, plist, nent * sizeof (int))) {
962 		kmem_free(plist, nent * sizeof (int));
963 		return (EFAULT);
964 	}
965 
966 	/*
967 	 * Scan the list for event port file descriptors and send the
968 	 * attached user event data embedded in a event of type
969 	 * PORT_SOURCE_USER to every event port in the list.
970 	 * If a list entry is not a valid event port then the corresponding
971 	 * error code will be stored in the errors[] list with the same
972 	 * list offset as in the ports[] list.
973 	 */
974 
975 	for (count = 0; count < nent; count++) {
976 		port = plist[count];
977 		if ((fp = getf(port)) == NULL) {
978 			elist = port_errorn(elist, nent, EBADF, count);
979 			errorcnt++;
980 			continue;
981 		}
982 
983 		pp = VTOEP(fp->f_vnode);
984 		if (fp->f_vnode->v_type != VPORT) {
985 			releasef(port);
986 			elist = port_errorn(elist, nent, EBADFD, count);
987 			errorcnt++;
988 			continue;
989 		}
990 
991 		error = port_alloc_event_local(pp, PORT_SOURCE_USER,
992 		    PORT_ALLOC_DEFAULT, &pev);
993 		if (error) {
994 			releasef(port);
995 			elist = port_errorn(elist, nent, error, count);
996 			errorcnt++;
997 			continue;
998 		}
999 
1000 		pev->portkev_object = 0;
1001 		pev->portkev_events = events;
1002 		pev->portkev_user = user;
1003 		pev->portkev_callback = NULL;
1004 		pev->portkev_arg = NULL;
1005 		pev->portkev_flags = 0;
1006 
1007 		port_send_event(pev);
1008 		releasef(port);
1009 	}
1010 	if (errorcnt) {
1011 		error = EIO;
1012 		if (copyout(elist, (void *)errors, nent * sizeof (int)))
1013 			error = EFAULT;
1014 		kmem_free(elist, nent * sizeof (int));
1015 	}
1016 	*nget = nent - errorcnt;
1017 	kmem_free(plist, nent * sizeof (int));
1018 	return (error);
1019 }
1020 
1021 static int *
1022 port_errorn(int *elist, int nent, int error, int index)
1023 {
1024 	if (elist == NULL)
1025 		elist = kmem_zalloc(nent * sizeof (int), KM_SLEEP);
1026 	elist[index] = error;
1027 	return (elist);
1028 }
1029 
1030 /*
1031  * port_alert()
1032  * The port_alert() funcion is a high priority event and it is always set
1033  * on top of the queue. It is also delivered as single event.
1034  * flags:
1035  *	- SET	:overwrite current alert data
1036  *	- UPDATE:set alert data or return EBUSY if alert mode is already set
1037  *
1038  * - set the ALERT flag
1039  * - wakeup all sleeping threads
1040  */
1041 static int
1042 port_alert(port_t *pp, int flags, int events, void *user)
1043 {
1044 	port_queue_t	*portq;
1045 	portget_t	*pgetp;
1046 	port_alert_t	*pa;
1047 
1048 	if ((flags & PORT_ALERT_INVALID) == PORT_ALERT_INVALID)
1049 		return (EINVAL);
1050 
1051 	portq = &pp->port_queue;
1052 	pa = &portq->portq_alert;
1053 	mutex_enter(&portq->portq_mutex);
1054 
1055 	/* check alert conditions */
1056 	if (flags == PORT_ALERT_UPDATE) {
1057 		if (portq->portq_flags & PORTQ_ALERT) {
1058 			mutex_exit(&portq->portq_mutex);
1059 			return (EBUSY);
1060 		}
1061 	}
1062 
1063 	/*
1064 	 * Store alert data in the port to be delivered to threads
1065 	 * which are using port_get(n) to retrieve events.
1066 	 */
1067 
1068 	portq->portq_flags |= PORTQ_ALERT;
1069 	pa->portal_events = events;		/* alert info */
1070 	pa->portal_pid = curproc->p_pid;	/* process owner */
1071 	pa->portal_object = 0;			/* no object */
1072 	pa->portal_user = user;			/* user alert data */
1073 
1074 	/* alert and deliver alert data to waiting threads */
1075 	pgetp = portq->portq_thread;
1076 	if (pgetp == NULL) {
1077 		/* no threads waiting for events */
1078 		mutex_exit(&portq->portq_mutex);
1079 		return (0);
1080 	}
1081 
1082 	/*
1083 	 * Set waiting threads in alert mode (PORTGET_ALERT)..
1084 	 * Every thread waiting for events already allocated a portget_t
1085 	 * structure to sleep on.
1086 	 * The port alert arguments are stored in the portget_t structure.
1087 	 * The PORTGET_ALERT flag is set to indicate the thread to return
1088 	 * immediately with the alert event.
1089 	 */
1090 	do {
1091 		if ((pgetp->portget_state & PORTGET_ALERT) == 0) {
1092 			pa = &pgetp->portget_alert;
1093 			pa->portal_events = events;
1094 			pa->portal_object = 0;
1095 			pa->portal_user = user;
1096 			pgetp->portget_state |= PORTGET_ALERT;
1097 			cv_signal(&pgetp->portget_cv);
1098 		}
1099 	} while ((pgetp = pgetp->portget_next) != portq->portq_thread);
1100 	mutex_exit(&portq->portq_mutex);
1101 	return (0);
1102 }
1103 
1104 /*
1105  * Clear alert state of the port
1106  */
1107 static void
1108 port_remove_alert(port_queue_t *portq)
1109 {
1110 	mutex_enter(&portq->portq_mutex);
1111 	portq->portq_flags &= ~PORTQ_ALERT;
1112 	mutex_exit(&portq->portq_mutex);
1113 }
1114 
1115 /*
1116  * The port_getn() function is used to retrieve events from a port.
1117  *
1118  * The port_getn() function returns immediately if there are enough events
1119  * available in the port to satisfy the request or if the port is in alert
1120  * mode (see port_alert(3c)).
1121  * The timeout argument of port_getn(3c) -which is embedded in the
1122  * port_gettimer_t structure- specifies if the system call should block or if it
1123  * should return immediately depending on the number of events available.
1124  * This function is internally used by port_getn(3c) as well as by
1125  * port_get(3c).
1126  */
1127 static int
1128 port_getn(port_t *pp, port_event_t *uevp, uint_t max, uint_t *nget,
1129     port_gettimer_t *pgt)
1130 {
1131 	port_queue_t	*portq;
1132 	port_kevent_t 	*pev;
1133 	port_kevent_t 	*lev;
1134 	int		error = 0;
1135 	uint_t		nmax;
1136 	uint_t		nevents;
1137 	uint_t		eventsz;
1138 	port_event_t	*kevp;
1139 	list_t		*glist;
1140 	uint_t		tnent;
1141 	int		rval;
1142 	int		blocking = -1;
1143 	int		timecheck;
1144 	int		flag;
1145 	timespec_t	rqtime;
1146 	timespec_t	*rqtp = NULL;
1147 	portget_t	*pgetp;
1148 	void		*results;
1149 	model_t		model = get_udatamodel();
1150 
1151 	flag = pgt->pgt_flags;
1152 
1153 	if (*nget > max && max > 0)
1154 		return (EINVAL);
1155 
1156 	portq = &pp->port_queue;
1157 	mutex_enter(&portq->portq_mutex);
1158 	if (max == 0) {
1159 		/*
1160 		 * Return number of objects with events.
1161 		 * The port_block() call is required to synchronize this
1162 		 * thread with another possible thread, which could be
1163 		 * retrieving events from the port queue.
1164 		 */
1165 		port_block(portq);
1166 		/*
1167 		 * Check if a second thread is currently retrieving events
1168 		 * and it is using the temporary event queue.
1169 		 */
1170 		if (portq->portq_tnent) {
1171 			/* put remaining events back to the port queue */
1172 			port_push_eventq(portq);
1173 		}
1174 		*nget = portq->portq_nent;
1175 		port_unblock(portq);
1176 		mutex_exit(&portq->portq_mutex);
1177 		return (0);
1178 	}
1179 
1180 	if (uevp == NULL) {
1181 		mutex_exit(&portq->portq_mutex);
1182 		return (EFAULT);
1183 	}
1184 	if (*nget == 0) {		/* no events required */
1185 		mutex_exit(&portq->portq_mutex);
1186 		return (0);
1187 	}
1188 
1189 	/* port is being closed ... */
1190 	if (portq->portq_flags & PORTQ_CLOSE) {
1191 		mutex_exit(&portq->portq_mutex);
1192 		return (EBADFD);
1193 	}
1194 
1195 	/* return immediately if port in alert mode */
1196 	if (portq->portq_flags & PORTQ_ALERT) {
1197 		error = port_get_alert(&portq->portq_alert, uevp);
1198 		if (error == 0)
1199 			*nget = 1;
1200 		mutex_exit(&portq->portq_mutex);
1201 		return (error);
1202 	}
1203 
1204 	portq->portq_thrcnt++;
1205 
1206 	/*
1207 	 * Now check if the completed events satisfy the
1208 	 * "wait" requirements of the current thread:
1209 	 */
1210 
1211 	if (pgt->pgt_loop) {
1212 		/*
1213 		 * loop entry of same thread
1214 		 * pgt_loop is set when the current thread returns
1215 		 * prematurely from this function. That could happen
1216 		 * when a port is being shared between processes and
1217 		 * this thread could not find events to return.
1218 		 * It is not allowed to a thread to retrieve non-shareable
1219 		 * events generated in other processes.
1220 		 * PORTQ_WAIT_EVENTS is set when a thread already
1221 		 * checked the current event queue and no new events
1222 		 * are added to the queue.
1223 		 */
1224 		if (((portq->portq_flags & PORTQ_WAIT_EVENTS) == 0) &&
1225 		    (portq->portq_nent >= *nget)) {
1226 			/* some new events arrived ...check them */
1227 			goto portnowait;
1228 		}
1229 		rqtp = pgt->pgt_rqtp;
1230 		timecheck = pgt->pgt_timecheck;
1231 		pgt->pgt_flags |= PORTGET_WAIT_EVENTS;
1232 	} else {
1233 		/* check if enough events are available ... */
1234 		if (portq->portq_nent >= *nget)
1235 			goto portnowait;
1236 		/*
1237 		 * There are not enough events available to satisfy
1238 		 * the request, check timeout value and wait for
1239 		 * incoming events.
1240 		 */
1241 		error = port_get_timeout(pgt->pgt_timeout, &rqtime, &rqtp,
1242 		    &blocking, flag);
1243 		if (error) {
1244 			port_check_return_cond(portq);
1245 			mutex_exit(&portq->portq_mutex);
1246 			return (error);
1247 		}
1248 
1249 		if (blocking == 0) /* don't block, check fired events */
1250 			goto portnowait;
1251 
1252 		if (rqtp != NULL) {
1253 			timespec_t	now;
1254 			timecheck = timechanged;
1255 			gethrestime(&now);
1256 			timespecadd(rqtp, &now);
1257 		}
1258 	}
1259 
1260 	/* enqueue thread in the list of waiting threads */
1261 	pgetp = port_queue_thread(portq, *nget);
1262 
1263 
1264 	/* Wait here until return conditions met */
1265 	for (;;) {
1266 		if (pgetp->portget_state & PORTGET_ALERT) {
1267 			/* reap alert event and return */
1268 			error = port_get_alert(&pgetp->portget_alert, uevp);
1269 			if (error)
1270 				*nget = 0;
1271 			else
1272 				*nget = 1;
1273 			port_dequeue_thread(&pp->port_queue, pgetp);
1274 			portq->portq_thrcnt--;
1275 			mutex_exit(&portq->portq_mutex);
1276 			return (error);
1277 		}
1278 
1279 		/*
1280 		 * Check if some other thread is already retrieving
1281 		 * events (portq_getn > 0).
1282 		 */
1283 
1284 		if ((portq->portq_getn  == 0) &&
1285 		    ((portq)->portq_nent >= *nget) &&
1286 		    (!((pgt)->pgt_flags & PORTGET_WAIT_EVENTS) ||
1287 		    !((portq)->portq_flags & PORTQ_WAIT_EVENTS)))
1288 			break;
1289 
1290 		if (portq->portq_flags & PORTQ_CLOSE) {
1291 			error = EBADFD;
1292 			break;
1293 		}
1294 
1295 		rval = cv_waituntil_sig(&pgetp->portget_cv, &portq->portq_mutex,
1296 		    rqtp, timecheck);
1297 
1298 		if (rval <= 0) {
1299 			error = (rval == 0) ? EINTR : ETIME;
1300 			break;
1301 		}
1302 	}
1303 
1304 	/* take thread out of the wait queue */
1305 	port_dequeue_thread(portq, pgetp);
1306 
1307 	if (error != 0 && (error == EINTR || error == EBADFD ||
1308 	    (error == ETIME && flag))) {
1309 		/* return without events */
1310 		port_check_return_cond(portq);
1311 		mutex_exit(&portq->portq_mutex);
1312 		return (error);
1313 	}
1314 
1315 portnowait:
1316 	/*
1317 	 * Move port event queue to a temporary event queue .
1318 	 * New incoming events will be continue be posted to the event queue
1319 	 * and they will not be considered by the current thread.
1320 	 * The idea is to avoid lock contentions or an often locking/unlocking
1321 	 * of the port queue mutex. The contention and performance degradation
1322 	 * could happen because:
1323 	 * a) incoming events use the port queue mutex to enqueue new events and
1324 	 * b) before the event can be delivered to the application it is
1325 	 *    necessary to notify the event sources about the event delivery.
1326 	 *    Sometimes the event sources can require a long time to return and
1327 	 *    the queue mutex would block incoming events.
1328 	 * During this time incoming events (port_send_event()) do not need
1329 	 * to awake threads waiting for events. Before the current thread
1330 	 * returns it will check the conditions to awake other waiting threads.
1331 	 */
1332 	portq->portq_getn++;	/* number of threads retrieving events */
1333 	port_block(portq);	/* block other threads here */
1334 	nmax = max < portq->portq_nent ? max : portq->portq_nent;
1335 
1336 	if (portq->portq_tnent) {
1337 		/*
1338 		 * Move remaining events from previous thread back to the
1339 		 * port event queue.
1340 		 */
1341 		port_push_eventq(portq);
1342 	}
1343 	/* move port event queue to a temporary queue */
1344 	list_move_tail(&portq->portq_get_list, &portq->portq_list);
1345 	glist = &portq->portq_get_list;	/* use temporary event queue */
1346 	tnent = portq->portq_nent;	/* get current number of events */
1347 	portq->portq_nent = 0;		/* no events in the port event queue */
1348 	portq->portq_flags |= PORTQ_WAIT_EVENTS; /* detect incoming events */
1349 	mutex_exit(&portq->portq_mutex);    /* event queue can be reused now */
1350 
1351 	if (model == DATAMODEL_NATIVE) {
1352 		eventsz = sizeof (port_event_t);
1353 		kevp = kmem_alloc(eventsz * nmax, KM_NOSLEEP);
1354 		if (kevp == NULL) {
1355 			if (nmax > pp->port_max_list)
1356 				nmax = pp->port_max_list;
1357 			kevp = kmem_alloc(eventsz * nmax, KM_SLEEP);
1358 		}
1359 		results = kevp;
1360 		lev = NULL;	/* start with first event in the queue */
1361 		for (nevents = 0; nevents < nmax; ) {
1362 			pev = port_get_kevent(glist, lev);
1363 			if (pev == NULL)	/* no more events available */
1364 				break;
1365 			if (pev->portkev_flags & PORT_KEV_FREE) {
1366 				/* Just discard event */
1367 				list_remove(glist, pev);
1368 				pev->portkev_flags &= ~(PORT_CLEANUP_DONE);
1369 				if (PORT_FREE_EVENT(pev))
1370 					port_free_event_local(pev, 0);
1371 				tnent--;
1372 				continue;
1373 			}
1374 
1375 			/* move event data to copyout list */
1376 			if (port_copy_event(&kevp[nevents], pev, glist)) {
1377 				/*
1378 				 * Event can not be delivered to the
1379 				 * current process.
1380 				 */
1381 				if (lev != NULL)
1382 					list_insert_after(glist, lev, pev);
1383 				else
1384 					list_insert_head(glist, pev);
1385 				lev = pev;  /* last checked event */
1386 			} else {
1387 				nevents++;	/* # of events ready */
1388 			}
1389 		}
1390 #ifdef	_SYSCALL32_IMPL
1391 	} else {
1392 		port_event32_t	*kevp32;
1393 
1394 		eventsz = sizeof (port_event32_t);
1395 		kevp32 = kmem_alloc(eventsz * nmax, KM_NOSLEEP);
1396 		if (kevp32 == NULL) {
1397 			if (nmax > pp->port_max_list)
1398 				nmax = pp->port_max_list;
1399 			kevp32 = kmem_alloc(eventsz * nmax, KM_SLEEP);
1400 		}
1401 		results = kevp32;
1402 		lev = NULL;	/* start with first event in the queue */
1403 		for (nevents = 0; nevents < nmax; ) {
1404 			pev = port_get_kevent(glist, lev);
1405 			if (pev == NULL)	/* no more events available */
1406 				break;
1407 			if (pev->portkev_flags & PORT_KEV_FREE) {
1408 				/* Just discard event */
1409 				list_remove(glist, pev);
1410 				pev->portkev_flags &= ~(PORT_CLEANUP_DONE);
1411 				if (PORT_FREE_EVENT(pev))
1412 					port_free_event_local(pev, 0);
1413 				tnent--;
1414 				continue;
1415 			}
1416 
1417 			/* move event data to copyout list */
1418 			if (port_copy_event32(&kevp32[nevents], pev, glist)) {
1419 				/*
1420 				 * Event can not be delivered to the
1421 				 * current process.
1422 				 */
1423 				if (lev != NULL)
1424 					list_insert_after(glist, lev, pev);
1425 				else
1426 					list_insert_head(glist, pev);
1427 				lev = pev;  /* last checked event */
1428 			} else {
1429 				nevents++;	/* # of events ready */
1430 			}
1431 		}
1432 #endif	/* _SYSCALL32_IMPL */
1433 	}
1434 
1435 	/*
1436 	 *  Remember number of remaining events in the temporary event queue.
1437 	 */
1438 	portq->portq_tnent = tnent - nevents;
1439 
1440 	/*
1441 	 * Work to do before return :
1442 	 * - push list of remaining events back to the top of the standard
1443 	 *   port queue.
1444 	 * - if this is the last thread calling port_get(n) then wakeup the
1445 	 *   thread waiting on close(2).
1446 	 * - check for a deferred cv_signal from port_send_event() and wakeup
1447 	 *   the sleeping thread.
1448 	 */
1449 
1450 	mutex_enter(&portq->portq_mutex);
1451 	port_unblock(portq);
1452 	if (portq->portq_tnent) {
1453 		/*
1454 		 * move remaining events in the temporary event queue back
1455 		 * to the port event queue
1456 		 */
1457 		port_push_eventq(portq);
1458 	}
1459 	portq->portq_getn--;	/* update # of threads retrieving events */
1460 	if (--portq->portq_thrcnt == 0) { /* # of threads waiting ... */
1461 		/* Last thread => check close(2) conditions ... */
1462 		if (portq->portq_flags & PORTQ_CLOSE) {
1463 			cv_signal(&portq->portq_closecv);
1464 			mutex_exit(&portq->portq_mutex);
1465 			kmem_free(results, eventsz * nmax);
1466 			/* do not copyout events */
1467 			*nget = 0;
1468 			return (EBADFD);
1469 		}
1470 	} else if (portq->portq_getn == 0) {
1471 		/*
1472 		 * no other threads retrieving events ...
1473 		 * check wakeup conditions of sleeping threads
1474 		 */
1475 		if ((portq->portq_thread != NULL) &&
1476 		    (portq->portq_nent >= portq->portq_nget))
1477 			cv_signal(&portq->portq_thread->portget_cv);
1478 	}
1479 
1480 	/*
1481 	 * Check PORTQ_POLLIN here because the current thread set temporarily
1482 	 * the number of events in the queue to zero.
1483 	 */
1484 	if (portq->portq_flags & PORTQ_POLLIN) {
1485 		portq->portq_flags &= ~PORTQ_POLLIN;
1486 		mutex_exit(&portq->portq_mutex);
1487 		pollwakeup(&pp->port_pollhd, POLLIN);
1488 	} else {
1489 		mutex_exit(&portq->portq_mutex);
1490 	}
1491 
1492 	/* now copyout list of user event structures to user space */
1493 	if (nevents) {
1494 		if (copyout(results, uevp, nevents * eventsz))
1495 			error = EFAULT;
1496 	}
1497 	kmem_free(results, eventsz * nmax);
1498 
1499 	if (nevents == 0 && error == 0 && pgt->pgt_loop == 0 && blocking != 0) {
1500 		/* no events retrieved: check loop conditions */
1501 		if (blocking == -1) {
1502 			/* no timeout checked */
1503 			error = port_get_timeout(pgt->pgt_timeout,
1504 			    &pgt->pgt_rqtime, &rqtp, &blocking, flag);
1505 			if (error) {
1506 				*nget = nevents;
1507 				return (error);
1508 			}
1509 			if (rqtp != NULL) {
1510 				timespec_t	now;
1511 				pgt->pgt_timecheck = timechanged;
1512 				gethrestime(&now);
1513 				timespecadd(&pgt->pgt_rqtime, &now);
1514 			}
1515 			pgt->pgt_rqtp = rqtp;
1516 		} else {
1517 			/* timeout already checked -> remember values */
1518 			pgt->pgt_rqtp = rqtp;
1519 			if (rqtp != NULL) {
1520 				pgt->pgt_timecheck = timecheck;
1521 				pgt->pgt_rqtime = *rqtp;
1522 			}
1523 		}
1524 		if (blocking)
1525 			/* timeout remaining */
1526 			pgt->pgt_loop = 1;
1527 	}
1528 
1529 	/* set number of user event structures completed */
1530 	*nget = nevents;
1531 	return (error);
1532 }
1533 
1534 /*
1535  * 1. copy kernel event structure to user event structure.
1536  * 2. PORT_KEV_WIRED event structures will be reused by the "source"
1537  * 3. Remove PORT_KEV_DONEQ flag (event removed from the event queue)
1538  * 4. Other types of event structures can be delivered back to the port cache
1539  *    (port_free_event_local()).
1540  * 5. The event source callback function is the last opportunity for the
1541  *    event source to update events, to free local resources associated with
1542  *    the event or to deny the delivery of the event.
1543  */
1544 static int
1545 port_copy_event(port_event_t *puevp, port_kevent_t *pkevp, list_t *list)
1546 {
1547 	int	free_event = 0;
1548 	int	flags;
1549 	int	error;
1550 
1551 	puevp->portev_source = pkevp->portkev_source;
1552 	puevp->portev_object = pkevp->portkev_object;
1553 	puevp->portev_user = pkevp->portkev_user;
1554 	puevp->portev_events = pkevp->portkev_events;
1555 
1556 	/* remove event from the queue */
1557 	list_remove(list, pkevp);
1558 
1559 	/*
1560 	 * Events of type PORT_KEV_WIRED remain allocated by the
1561 	 * event source.
1562 	 */
1563 	flags = pkevp->portkev_flags;
1564 	if (pkevp->portkev_flags & PORT_KEV_WIRED)
1565 		pkevp->portkev_flags &= ~PORT_KEV_DONEQ;
1566 	else
1567 		free_event = 1;
1568 
1569 	if (pkevp->portkev_callback) {
1570 		error = (*pkevp->portkev_callback)(pkevp->portkev_arg,
1571 		    &puevp->portev_events, pkevp->portkev_pid,
1572 		    PORT_CALLBACK_DEFAULT, pkevp);
1573 
1574 		if (error) {
1575 			/*
1576 			 * Event can not be delivered.
1577 			 * Caller must reinsert the event into the queue.
1578 			 */
1579 			pkevp->portkev_flags = flags;
1580 			return (error);
1581 		}
1582 	}
1583 	if (free_event)
1584 		port_free_event_local(pkevp, 0);
1585 	return (0);
1586 }
1587 
1588 #ifdef	_SYSCALL32_IMPL
1589 /*
1590  * 1. copy kernel event structure to user event structure.
1591  * 2. PORT_KEV_WIRED event structures will be reused by the "source"
1592  * 3. Remove PORT_KEV_DONEQ flag (event removed from the event queue)
1593  * 4. Other types of event structures can be delivered back to the port cache
1594  *    (port_free_event_local()).
1595  * 5. The event source callback function is the last opportunity for the
1596  *    event source to update events, to free local resources associated with
1597  *    the event or to deny the delivery of the event.
1598  */
1599 static int
1600 port_copy_event32(port_event32_t *puevp, port_kevent_t *pkevp, list_t *list)
1601 {
1602 	int	free_event = 0;
1603 	int	error;
1604 	int	flags;
1605 
1606 	puevp->portev_source = pkevp->portkev_source;
1607 	puevp->portev_object = (daddr32_t)pkevp->portkev_object;
1608 	puevp->portev_user = (caddr32_t)(uintptr_t)pkevp->portkev_user;
1609 	puevp->portev_events = pkevp->portkev_events;
1610 
1611 	/* remove event from the queue */
1612 	list_remove(list, pkevp);
1613 
1614 	/*
1615 	 * Events if type PORT_KEV_WIRED remain allocated by the
1616 	 * sub-system (source).
1617 	 */
1618 
1619 	flags = pkevp->portkev_flags;
1620 	if (pkevp->portkev_flags & PORT_KEV_WIRED)
1621 		pkevp->portkev_flags &= ~PORT_KEV_DONEQ;
1622 	else
1623 		free_event = 1;
1624 
1625 	if (pkevp->portkev_callback != NULL) {
1626 		error = (*pkevp->portkev_callback)(pkevp->portkev_arg,
1627 		    &puevp->portev_events, pkevp->portkev_pid,
1628 		    PORT_CALLBACK_DEFAULT, pkevp);
1629 		if (error) {
1630 			/*
1631 			 * Event can not be delivered.
1632 			 * Caller must reinsert the event into the queue.
1633 			 */
1634 			pkevp->portkev_flags = flags;
1635 			return (error);
1636 		}
1637 	}
1638 	if (free_event)
1639 		port_free_event_local(pkevp, 0);
1640 	return (0);
1641 }
1642 #endif	/* _SYSCALL32_IMPL */
1643 
1644 /*
1645  * copyout alert event.
1646  */
1647 static int
1648 port_get_alert(port_alert_t *pa, port_event_t *uevp)
1649 {
1650 	model_t	model = get_udatamodel();
1651 
1652 	/* copyout alert event structures to user space */
1653 	if (model == DATAMODEL_NATIVE) {
1654 		port_event_t	uev;
1655 		uev.portev_source = PORT_SOURCE_ALERT;
1656 		uev.portev_object = pa->portal_object;
1657 		uev.portev_events = pa->portal_events;
1658 		uev.portev_user = pa->portal_user;
1659 		if (copyout(&uev, uevp, sizeof (port_event_t)))
1660 			return (EFAULT);
1661 #ifdef	_SYSCALL32_IMPL
1662 	} else {
1663 		port_event32_t	uev32;
1664 		uev32.portev_source = PORT_SOURCE_ALERT;
1665 		uev32.portev_object = (daddr32_t)pa->portal_object;
1666 		uev32.portev_events = pa->portal_events;
1667 		uev32.portev_user = (daddr32_t)(uintptr_t)pa->portal_user;
1668 		if (copyout(&uev32, uevp, sizeof (port_event32_t)))
1669 			return (EFAULT);
1670 #endif	/* _SYSCALL32_IMPL */
1671 	}
1672 	return (0);
1673 }
1674 
1675 /*
1676  * Check return conditions :
1677  * - pending port close(2)
1678  * - threads waiting for events
1679  */
1680 static void
1681 port_check_return_cond(port_queue_t *portq)
1682 {
1683 	ASSERT(MUTEX_HELD(&portq->portq_mutex));
1684 	portq->portq_thrcnt--;
1685 	if (portq->portq_flags & PORTQ_CLOSE) {
1686 		if (portq->portq_thrcnt == 0)
1687 			cv_signal(&portq->portq_closecv);
1688 		else
1689 			cv_signal(&portq->portq_thread->portget_cv);
1690 	}
1691 }
1692 
1693 /*
1694  * The port_get_kevent() function returns
1695  * - the event located at the head of the queue if 'last' pointer is NULL
1696  * - the next event after the event pointed by 'last'
1697  * The caller of this function is responsible for the integrity of the queue
1698  * in use:
1699  * - port_getn() is using a temporary queue protected with port_block().
1700  * - port_close_events() is working on the global event queue and protects
1701  *   the queue with portq->portq_mutex.
1702  */
1703 port_kevent_t *
1704 port_get_kevent(list_t *list, port_kevent_t *last)
1705 {
1706 	if (last == NULL)
1707 		return (list_head(list));
1708 	else
1709 		return (list_next(list, last));
1710 }
1711 
1712 /*
1713  * The port_get_timeout() function gets the timeout data from user space
1714  * and converts that info into a corresponding internal representation.
1715  * The kerneldata flag means that the timeout data is already loaded.
1716  */
1717 static int
1718 port_get_timeout(timespec_t *timeout, timespec_t *rqtime, timespec_t **rqtp,
1719     int *blocking, int kerneldata)
1720 {
1721 	model_t	model = get_udatamodel();
1722 
1723 	*rqtp = NULL;
1724 	if (timeout == NULL) {
1725 		*blocking = 1;
1726 		return (0);
1727 	}
1728 
1729 	if (kerneldata) {
1730 		*rqtime = *timeout;
1731 	} else {
1732 		if (model == DATAMODEL_NATIVE) {
1733 			if (copyin(timeout, rqtime, sizeof (*rqtime)))
1734 				return (EFAULT);
1735 #ifdef	_SYSCALL32_IMPL
1736 		} else {
1737 			timespec32_t 	wait_time_32;
1738 			if (copyin(timeout, &wait_time_32,
1739 			    sizeof (wait_time_32)))
1740 				return (EFAULT);
1741 			TIMESPEC32_TO_TIMESPEC(rqtime, &wait_time_32);
1742 #endif  /* _SYSCALL32_IMPL */
1743 		}
1744 	}
1745 
1746 	if (rqtime->tv_sec == 0 && rqtime->tv_nsec == 0) {
1747 		*blocking = 0;
1748 		return (0);
1749 	}
1750 
1751 	if (rqtime->tv_sec < 0 ||
1752 	    rqtime->tv_nsec < 0 || rqtime->tv_nsec >= NANOSEC)
1753 		return (EINVAL);
1754 
1755 	*rqtp = rqtime;
1756 	*blocking = 1;
1757 	return (0);
1758 }
1759 
1760 /*
1761  * port_queue_thread()
1762  * Threads requiring more events than available will be put in a wait queue.
1763  * There is a "thread wait queue" per port.
1764  * Threads requiring less events get a higher priority than others and they
1765  * will be awoken first.
1766  */
1767 static portget_t *
1768 port_queue_thread(port_queue_t *portq, uint_t nget)
1769 {
1770 	portget_t	*pgetp;
1771 	portget_t	*ttp;
1772 	portget_t	*htp;
1773 
1774 	pgetp = kmem_zalloc(sizeof (portget_t), KM_SLEEP);
1775 	pgetp->portget_nget = nget;
1776 	pgetp->portget_pid = curproc->p_pid;
1777 	if (portq->portq_thread == NULL) {
1778 		/* first waiting thread */
1779 		portq->portq_thread = pgetp;
1780 		portq->portq_nget = nget;
1781 		pgetp->portget_prev = pgetp;
1782 		pgetp->portget_next = pgetp;
1783 		return (pgetp);
1784 	}
1785 
1786 	/*
1787 	 * thread waiting for less events will be set on top of the queue.
1788 	 */
1789 	ttp = portq->portq_thread;
1790 	htp = ttp;
1791 	for (;;) {
1792 		if (nget <= ttp->portget_nget)
1793 			break;
1794 		if (htp == ttp->portget_next)
1795 			break;	/* last event */
1796 		ttp = ttp->portget_next;
1797 	}
1798 
1799 	/* add thread to the queue */
1800 	pgetp->portget_next = ttp;
1801 	pgetp->portget_prev = ttp->portget_prev;
1802 	ttp->portget_prev->portget_next = pgetp;
1803 	ttp->portget_prev = pgetp;
1804 	if (portq->portq_thread == ttp)
1805 		portq->portq_thread = pgetp;
1806 	portq->portq_nget = portq->portq_thread->portget_nget;
1807 	return (pgetp);
1808 }
1809 
1810 /*
1811  * Take thread out of the queue.
1812  */
1813 static void
1814 port_dequeue_thread(port_queue_t *portq, portget_t *pgetp)
1815 {
1816 	if (pgetp->portget_next == pgetp) {
1817 		/* last (single) waiting thread */
1818 		portq->portq_thread = NULL;
1819 		portq->portq_nget = 0;
1820 	} else {
1821 		pgetp->portget_prev->portget_next = pgetp->portget_next;
1822 		pgetp->portget_next->portget_prev = pgetp->portget_prev;
1823 		if (portq->portq_thread == pgetp)
1824 			portq->portq_thread = pgetp->portget_next;
1825 		portq->portq_nget = portq->portq_thread->portget_nget;
1826 	}
1827 	kmem_free(pgetp, sizeof (portget_t));
1828 }
1829 
1830 /*
1831  * Set up event port kstats.
1832  */
1833 static void
1834 port_kstat_init()
1835 {
1836 	kstat_t	*ksp;
1837 	uint_t	ndata;
1838 
1839 	ndata = sizeof (port_kstat) / sizeof (kstat_named_t);
1840 	ksp = kstat_create("portfs", 0, "Event Ports", "misc",
1841 	    KSTAT_TYPE_NAMED, ndata, KSTAT_FLAG_VIRTUAL);
1842 	if (ksp) {
1843 		ksp->ks_data = &port_kstat;
1844 		kstat_install(ksp);
1845 	}
1846 }
1847