xref: /dflybsd-src/sys/kern/uipc_socket.c (revision e7302aa08274de307cd2c3345fc64c56dbe56e21)
1 /*
2  * Copyright (c) 2004 Jeffrey M. Hsu.  All rights reserved.
3  * Copyright (c) 2004 The DragonFly Project.  All rights reserved.
4  *
5  * This code is derived from software contributed to The DragonFly Project
6  * by Jeffrey M. Hsu.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of The DragonFly Project nor the names of its
17  *    contributors may be used to endorse or promote products derived
18  *    from this software without specific, prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 /*
35  * Copyright (c) 1982, 1986, 1988, 1990, 1993
36  *	The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *	This product includes software developed by the University of
49  *	California, Berkeley and its contributors.
50  * 4. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *	@(#)uipc_socket.c	8.3 (Berkeley) 4/15/94
67  * $FreeBSD: src/sys/kern/uipc_socket.c,v 1.68.2.24 2003/11/11 17:18:18 silby Exp $
68  * $DragonFly: src/sys/kern/uipc_socket.c,v 1.55 2008/09/02 16:17:52 dillon Exp $
69  */
70 
71 #include "opt_inet.h"
72 #include "opt_sctp.h"
73 
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/fcntl.h>
77 #include <sys/malloc.h>
78 #include <sys/mbuf.h>
79 #include <sys/domain.h>
80 #include <sys/file.h>			/* for struct knote */
81 #include <sys/kernel.h>
82 #include <sys/malloc.h>
83 #include <sys/event.h>
84 #include <sys/poll.h>
85 #include <sys/proc.h>
86 #include <sys/protosw.h>
87 #include <sys/socket.h>
88 #include <sys/socketvar.h>
89 #include <sys/socketops.h>
90 #include <sys/resourcevar.h>
91 #include <sys/signalvar.h>
92 #include <sys/sysctl.h>
93 #include <sys/uio.h>
94 #include <sys/jail.h>
95 #include <vm/vm_zone.h>
96 #include <vm/pmap.h>
97 
98 #include <sys/thread2.h>
99 #include <sys/socketvar2.h>
100 
101 #include <machine/limits.h>
102 
103 #ifdef INET
104 static int	 do_setopt_accept_filter(struct socket *so, struct sockopt *sopt);
105 #endif /* INET */
106 
107 static void 	filt_sordetach(struct knote *kn);
108 static int 	filt_soread(struct knote *kn, long hint);
109 static void 	filt_sowdetach(struct knote *kn);
110 static int	filt_sowrite(struct knote *kn, long hint);
111 static int	filt_solisten(struct knote *kn, long hint);
112 
113 static struct filterops solisten_filtops =
114 	{ 1, NULL, filt_sordetach, filt_solisten };
115 static struct filterops soread_filtops =
116 	{ 1, NULL, filt_sordetach, filt_soread };
117 static struct filterops sowrite_filtops =
118 	{ 1, NULL, filt_sowdetach, filt_sowrite };
119 
120 MALLOC_DEFINE(M_SOCKET, "socket", "socket struct");
121 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
122 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
123 
124 
125 static int somaxconn = SOMAXCONN;
126 SYSCTL_INT(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLFLAG_RW,
127     &somaxconn, 0, "Maximum pending socket connection queue size");
128 
129 /*
130  * Socket operation routines.
131  * These routines are called by the routines in
132  * sys_socket.c or from a system process, and
133  * implement the semantics of socket operations by
134  * switching out to the protocol specific routines.
135  */
136 
137 /*
138  * Get a socket structure, and initialize it.
139  * Note that it would probably be better to allocate socket
140  * and PCB at the same time, but I'm not convinced that all
141  * the protocols can be easily modified to do this.
142  */
143 struct socket *
144 soalloc(int waitok)
145 {
146 	struct socket *so;
147 	unsigned waitmask;
148 
149 	waitmask = waitok ? M_WAITOK : M_NOWAIT;
150 	so = kmalloc(sizeof(struct socket), M_SOCKET, M_ZERO|waitmask);
151 	if (so) {
152 		/* XXX race condition for reentrant kernel */
153 		TAILQ_INIT(&so->so_aiojobq);
154 		TAILQ_INIT(&so->so_rcv.ssb_sel.si_mlist);
155 		TAILQ_INIT(&so->so_snd.ssb_sel.si_mlist);
156 	}
157 	return so;
158 }
159 
160 int
161 socreate(int dom, struct socket **aso, int type,
162 	int proto, struct thread *td)
163 {
164 	struct proc *p = td->td_proc;
165 	struct protosw *prp;
166 	struct socket *so;
167 	struct pru_attach_info ai;
168 	int error;
169 
170 	if (proto)
171 		prp = pffindproto(dom, proto, type);
172 	else
173 		prp = pffindtype(dom, type);
174 
175 	if (prp == 0 || prp->pr_usrreqs->pru_attach == 0)
176 		return (EPROTONOSUPPORT);
177 
178 	if (p->p_ucred->cr_prison && jail_socket_unixiproute_only &&
179 	    prp->pr_domain->dom_family != PF_LOCAL &&
180 	    prp->pr_domain->dom_family != PF_INET &&
181 	    prp->pr_domain->dom_family != PF_INET6 &&
182 	    prp->pr_domain->dom_family != PF_ROUTE) {
183 		return (EPROTONOSUPPORT);
184 	}
185 
186 	if (prp->pr_type != type)
187 		return (EPROTOTYPE);
188 	so = soalloc(p != 0);
189 	if (so == 0)
190 		return (ENOBUFS);
191 
192 	/*
193 	 * Set a default port for protocol processing.  No action will occur
194 	 * on the socket on this port until an inpcb is attached to it and
195 	 * is able to match incoming packets, or until the socket becomes
196 	 * available to userland.
197 	 */
198 	so->so_port = cpu0_soport(so, NULL, NULL);
199 
200 	TAILQ_INIT(&so->so_incomp);
201 	TAILQ_INIT(&so->so_comp);
202 	so->so_type = type;
203 	so->so_cred = crhold(p->p_ucred);
204 	so->so_proto = prp;
205 	ai.sb_rlimit = &p->p_rlimit[RLIMIT_SBSIZE];
206 	ai.p_ucred = p->p_ucred;
207 	ai.fd_rdir = p->p_fd->fd_rdir;
208 
209 	/*
210 	 * Auto-sizing of socket buffers is managed by the protocols and
211 	 * the appropriate flags must be set in the pru_attach function.
212 	 */
213 	error = so_pru_attach(so, proto, &ai);
214 	if (error) {
215 		so->so_state |= SS_NOFDREF;
216 		sofree(so);
217 		return (error);
218 	}
219 
220 	*aso = so;
221 	return (0);
222 }
223 
224 int
225 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
226 {
227 	int error;
228 
229 	crit_enter();
230 	error = so_pru_bind(so, nam, td);
231 	crit_exit();
232 	return (error);
233 }
234 
235 void
236 sodealloc(struct socket *so)
237 {
238 	if (so->so_rcv.ssb_hiwat)
239 		(void)chgsbsize(so->so_cred->cr_uidinfo,
240 		    &so->so_rcv.ssb_hiwat, 0, RLIM_INFINITY);
241 	if (so->so_snd.ssb_hiwat)
242 		(void)chgsbsize(so->so_cred->cr_uidinfo,
243 		    &so->so_snd.ssb_hiwat, 0, RLIM_INFINITY);
244 #ifdef INET
245 	/* remove accept filter if present */
246 	if (so->so_accf != NULL)
247 		do_setopt_accept_filter(so, NULL);
248 #endif /* INET */
249 	crfree(so->so_cred);
250 	kfree(so, M_SOCKET);
251 }
252 
253 int
254 solisten(struct socket *so, int backlog, struct thread *td)
255 {
256 	int error;
257 #ifdef SCTP
258 	short oldopt, oldqlimit;
259 #endif /* SCTP */
260 
261 	crit_enter();
262 	if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING)) {
263 		crit_exit();
264 		return (EINVAL);
265 	}
266 
267 #ifdef SCTP
268 	oldopt = so->so_options;
269 	oldqlimit = so->so_qlimit;
270 #endif /* SCTP */
271 
272 	if (TAILQ_EMPTY(&so->so_comp))
273 		so->so_options |= SO_ACCEPTCONN;
274 	if (backlog < 0 || backlog > somaxconn)
275 		backlog = somaxconn;
276 	so->so_qlimit = backlog;
277 	/* SCTP needs to look at tweak both the inbound backlog parameter AND
278 	 * the so_options (UDP model both connect's and gets inbound
279 	 * connections .. implicitly).
280 	 */
281 	error = so_pru_listen(so, td);
282 	if (error) {
283 #ifdef SCTP
284 		/* Restore the params */
285 		so->so_options = oldopt;
286 		so->so_qlimit = oldqlimit;
287 #endif /* SCTP */
288 		crit_exit();
289 		return (error);
290 	}
291 	crit_exit();
292 	return (0);
293 }
294 
295 /*
296  * Destroy a disconnected socket.  This routine is a NOP if entities
297  * still have a reference on the socket:
298  *
299  *	so_pcb -	The protocol stack still has a reference
300  *	SS_NOFDREF -	There is no longer a file pointer reference
301  *	SS_ABORTING -	An abort netmsg is in-flight
302  */
303 void
304 sofree(struct socket *so)
305 {
306 	struct socket *head = so->so_head;
307 
308 	if (so->so_pcb || (so->so_state & SS_NOFDREF) == 0)
309 		return;
310 	if (so->so_state & SS_ABORTING)
311 		return;
312 	if (head != NULL) {
313 		if (so->so_state & SS_INCOMP) {
314 			TAILQ_REMOVE(&head->so_incomp, so, so_list);
315 			head->so_incqlen--;
316 		} else if (so->so_state & SS_COMP) {
317 			/*
318 			 * We must not decommission a socket that's
319 			 * on the accept(2) queue.  If we do, then
320 			 * accept(2) may hang after select(2) indicated
321 			 * that the listening socket was ready.
322 			 */
323 			return;
324 		} else {
325 			panic("sofree: not queued");
326 		}
327 		so->so_state &= ~SS_INCOMP;
328 		so->so_head = NULL;
329 	}
330 	ssb_release(&so->so_snd, so);
331 	sorflush(so);
332 	sodealloc(so);
333 }
334 
335 /*
336  * Close a socket on last file table reference removal.
337  * Initiate disconnect if connected.
338  * Free socket when disconnect complete.
339  */
340 int
341 soclose(struct socket *so, int fflag)
342 {
343 	int error = 0;
344 
345 	crit_enter();
346 	funsetown(so->so_sigio);
347 	if (so->so_pcb == NULL)
348 		goto discard;
349 	if (so->so_state & SS_ISCONNECTED) {
350 		if ((so->so_state & SS_ISDISCONNECTING) == 0) {
351 			error = sodisconnect(so);
352 			if (error)
353 				goto drop;
354 		}
355 		if (so->so_options & SO_LINGER) {
356 			if ((so->so_state & SS_ISDISCONNECTING) &&
357 			    (fflag & FNONBLOCK))
358 				goto drop;
359 			while (so->so_state & SS_ISCONNECTED) {
360 				error = tsleep((caddr_t)&so->so_timeo,
361 				    PCATCH, "soclos", so->so_linger * hz);
362 				if (error)
363 					break;
364 			}
365 		}
366 	}
367 drop:
368 	if (so->so_pcb) {
369 		int error2;
370 
371 		error2 = so_pru_detach(so);
372 		if (error == 0)
373 			error = error2;
374 	}
375 discard:
376 	if (so->so_options & SO_ACCEPTCONN) {
377 		struct socket *sp;
378 
379 		while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
380 			TAILQ_REMOVE(&so->so_incomp, sp, so_list);
381 			sp->so_state &= ~SS_INCOMP;
382 			sp->so_head = NULL;
383 			so->so_incqlen--;
384 			soaborta(sp);
385 		}
386 		while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
387 			TAILQ_REMOVE(&so->so_comp, sp, so_list);
388 			sp->so_state &= ~SS_COMP;
389 			sp->so_head = NULL;
390 			so->so_qlen--;
391 			soaborta(sp);
392 		}
393 	}
394 	if (so->so_state & SS_NOFDREF)
395 		panic("soclose: NOFDREF");
396 	so->so_state |= SS_NOFDREF;
397 	sofree(so);
398 	crit_exit();
399 	return (error);
400 }
401 
402 /*
403  * Abort and destroy a socket.  Only one abort can be in progress
404  * at any given moment.
405  */
406 void
407 soabort(struct socket *so)
408 {
409 	if ((so->so_state & SS_ABORTING) == 0) {
410 		so->so_state |= SS_ABORTING;
411 		so_pru_abort(so);
412 	}
413 }
414 
415 void
416 soaborta(struct socket *so)
417 {
418 	if ((so->so_state & SS_ABORTING) == 0) {
419 		so->so_state |= SS_ABORTING;
420 		so_pru_aborta(so);
421 	}
422 }
423 
424 void
425 soabort_oncpu(struct socket *so)
426 {
427 	if ((so->so_state & SS_ABORTING) == 0) {
428 		so->so_state |= SS_ABORTING;
429 		so_pru_abort_oncpu(so);
430 	}
431 }
432 
433 int
434 soaccept(struct socket *so, struct sockaddr **nam)
435 {
436 	int error;
437 
438 	crit_enter();
439 	if ((so->so_state & SS_NOFDREF) == 0)
440 		panic("soaccept: !NOFDREF");
441 	so->so_state &= ~SS_NOFDREF;
442 	error = so_pru_accept(so, nam);
443 	crit_exit();
444 	return (error);
445 }
446 
447 int
448 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
449 {
450 	int error;
451 
452 	if (so->so_options & SO_ACCEPTCONN)
453 		return (EOPNOTSUPP);
454 	crit_enter();
455 	/*
456 	 * If protocol is connection-based, can only connect once.
457 	 * Otherwise, if connected, try to disconnect first.
458 	 * This allows user to disconnect by connecting to, e.g.,
459 	 * a null address.
460 	 */
461 	if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
462 	    ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
463 	    (error = sodisconnect(so)))) {
464 		error = EISCONN;
465 	} else {
466 		/*
467 		 * Prevent accumulated error from previous connection
468 		 * from biting us.
469 		 */
470 		so->so_error = 0;
471 		error = so_pru_connect(so, nam, td);
472 	}
473 	crit_exit();
474 	return (error);
475 }
476 
477 int
478 soconnect2(struct socket *so1, struct socket *so2)
479 {
480 	int error;
481 
482 	crit_enter();
483 	error = so_pru_connect2(so1, so2);
484 	crit_exit();
485 	return (error);
486 }
487 
488 int
489 sodisconnect(struct socket *so)
490 {
491 	int error;
492 
493 	crit_enter();
494 	if ((so->so_state & SS_ISCONNECTED) == 0) {
495 		error = ENOTCONN;
496 		goto bad;
497 	}
498 	if (so->so_state & SS_ISDISCONNECTING) {
499 		error = EALREADY;
500 		goto bad;
501 	}
502 	error = so_pru_disconnect(so);
503 bad:
504 	crit_exit();
505 	return (error);
506 }
507 
508 #define	SBLOCKWAIT(f)	(((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
509 /*
510  * Send on a socket.
511  * If send must go all at once and message is larger than
512  * send buffering, then hard error.
513  * Lock against other senders.
514  * If must go all at once and not enough room now, then
515  * inform user that this would block and do nothing.
516  * Otherwise, if nonblocking, send as much as possible.
517  * The data to be sent is described by "uio" if nonzero,
518  * otherwise by the mbuf chain "top" (which must be null
519  * if uio is not).  Data provided in mbuf chain must be small
520  * enough to send all at once.
521  *
522  * Returns nonzero on error, timeout or signal; callers
523  * must check for short counts if EINTR/ERESTART are returned.
524  * Data and control buffers are freed on return.
525  */
526 int
527 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
528 	struct mbuf *top, struct mbuf *control, int flags,
529 	struct thread *td)
530 {
531 	struct mbuf **mp;
532 	struct mbuf *m;
533 	size_t resid;
534 	int space, len;
535 	int clen = 0, error, dontroute, mlen;
536 	int atomic = sosendallatonce(so) || top;
537 	int pru_flags;
538 
539 	if (uio)
540 		resid = uio->uio_resid;
541 	else
542 		resid = (size_t)top->m_pkthdr.len;
543 
544 	/*
545 	 * WARNING!  resid is unsigned, space and len are signed.  space
546 	 * 	     can wind up negative if the sockbuf is overcommitted.
547 	 *
548 	 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
549 	 * type sockets since that's an error.
550 	 */
551 	if (so->so_type == SOCK_STREAM && (flags & MSG_EOR)) {
552 		error = EINVAL;
553 		goto out;
554 	}
555 
556 	dontroute =
557 	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
558 	    (so->so_proto->pr_flags & PR_ATOMIC);
559 	if (td->td_lwp != NULL)
560 		td->td_lwp->lwp_ru.ru_msgsnd++;
561 	if (control)
562 		clen = control->m_len;
563 #define	gotoerr(errcode)	{ error = errcode; crit_exit(); goto release; }
564 
565 restart:
566 	error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
567 	if (error)
568 		goto out;
569 
570 	do {
571 		crit_enter();
572 		if (so->so_state & SS_CANTSENDMORE)
573 			gotoerr(EPIPE);
574 		if (so->so_error) {
575 			error = so->so_error;
576 			so->so_error = 0;
577 			crit_exit();
578 			goto release;
579 		}
580 		if ((so->so_state & SS_ISCONNECTED) == 0) {
581 			/*
582 			 * `sendto' and `sendmsg' is allowed on a connection-
583 			 * based socket if it supports implied connect.
584 			 * Return ENOTCONN if not connected and no address is
585 			 * supplied.
586 			 */
587 			if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
588 			    (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
589 				if ((so->so_state & SS_ISCONFIRMING) == 0 &&
590 				    !(resid == 0 && clen != 0))
591 					gotoerr(ENOTCONN);
592 			} else if (addr == 0)
593 			    gotoerr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
594 				   ENOTCONN : EDESTADDRREQ);
595 		}
596 		if ((atomic && resid > so->so_snd.ssb_hiwat) ||
597 		    clen > so->so_snd.ssb_hiwat) {
598 			gotoerr(EMSGSIZE);
599 		}
600 		space = ssb_space(&so->so_snd);
601 		if (flags & MSG_OOB)
602 			space += 1024;
603 		if ((space < 0 || (size_t)space < resid + clen) && uio &&
604 		    (atomic || space < so->so_snd.ssb_lowat || space < clen)) {
605 			if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
606 				gotoerr(EWOULDBLOCK);
607 			ssb_unlock(&so->so_snd);
608 			error = ssb_wait(&so->so_snd);
609 			crit_exit();
610 			if (error)
611 				goto out;
612 			goto restart;
613 		}
614 		crit_exit();
615 		mp = &top;
616 		space -= clen;
617 		do {
618 		    if (uio == NULL) {
619 			/*
620 			 * Data is prepackaged in "top".
621 			 */
622 			resid = 0;
623 			if (flags & MSG_EOR)
624 				top->m_flags |= M_EOR;
625 		    } else do {
626 			if (resid > INT_MAX)
627 				resid = INT_MAX;
628 			m = m_getl((int)resid, MB_WAIT, MT_DATA,
629 				   top == NULL ? M_PKTHDR : 0, &mlen);
630 			if (top == NULL) {
631 				m->m_pkthdr.len = 0;
632 				m->m_pkthdr.rcvif = NULL;
633 			}
634 			len = imin((int)szmin(mlen, resid), space);
635 			if (resid < MINCLSIZE) {
636 				/*
637 				 * For datagram protocols, leave room
638 				 * for protocol headers in first mbuf.
639 				 */
640 				if (atomic && top == 0 && len < mlen)
641 					MH_ALIGN(m, len);
642 			}
643 			space -= len;
644 			error = uiomove(mtod(m, caddr_t), (size_t)len, uio);
645 			resid = uio->uio_resid;
646 			m->m_len = len;
647 			*mp = m;
648 			top->m_pkthdr.len += len;
649 			if (error)
650 				goto release;
651 			mp = &m->m_next;
652 			if (resid == 0) {
653 				if (flags & MSG_EOR)
654 					top->m_flags |= M_EOR;
655 				break;
656 			}
657 		    } while (space > 0 && atomic);
658 		    if (dontroute)
659 			    so->so_options |= SO_DONTROUTE;
660 		    if (flags & MSG_OOB) {
661 		    	    pru_flags = PRUS_OOB;
662 		    } else if ((flags & MSG_EOF) &&
663 		    	       (so->so_proto->pr_flags & PR_IMPLOPCL) &&
664 			       (resid == 0)) {
665 			    /*
666 			     * If the user set MSG_EOF, the protocol
667 			     * understands this flag and nothing left to
668 			     * send then use PRU_SEND_EOF instead of PRU_SEND.
669 			     */
670 		    	    pru_flags = PRUS_EOF;
671 		    } else if (resid > 0 && space > 0) {
672 			    /* If there is more to send, set PRUS_MORETOCOME */
673 		    	    pru_flags = PRUS_MORETOCOME;
674 		    } else {
675 		    	    pru_flags = 0;
676 		    }
677 		    crit_enter();
678 		    /*
679 		     * XXX all the SS_CANTSENDMORE checks previously
680 		     * done could be out of date.  We could have recieved
681 		     * a reset packet in an interrupt or maybe we slept
682 		     * while doing page faults in uiomove() etc. We could
683 		     * probably recheck again inside the splnet() protection
684 		     * here, but there are probably other places that this
685 		     * also happens.  We must rethink this.
686 		     */
687 		    error = so_pru_send(so, pru_flags, top, addr, control, td);
688 		    crit_exit();
689 		    if (dontroute)
690 			    so->so_options &= ~SO_DONTROUTE;
691 		    clen = 0;
692 		    control = 0;
693 		    top = 0;
694 		    mp = &top;
695 		    if (error)
696 			    goto release;
697 		} while (resid && space > 0);
698 	} while (resid);
699 
700 release:
701 	ssb_unlock(&so->so_snd);
702 out:
703 	if (top)
704 		m_freem(top);
705 	if (control)
706 		m_freem(control);
707 	return (error);
708 }
709 
710 /*
711  * A specialization of sosend() for UDP based on protocol-specific knowledge:
712  *   so->so_proto->pr_flags has the PR_ATOMIC field set.  This means that
713  *	sosendallatonce() returns true,
714  *	the "atomic" variable is true,
715  *	and sosendudp() blocks until space is available for the entire send.
716  *   so->so_proto->pr_flags does not have the PR_CONNREQUIRED or
717  *	PR_IMPLOPCL flags set.
718  *   UDP has no out-of-band data.
719  *   UDP has no control data.
720  *   UDP does not support MSG_EOR.
721  */
722 int
723 sosendudp(struct socket *so, struct sockaddr *addr, struct uio *uio,
724 	  struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
725 {
726 	boolean_t dontroute;		/* temporary SO_DONTROUTE setting */
727 	size_t resid;
728 	int error;
729 	int space;
730 
731 	if (td->td_lwp != NULL)
732 		td->td_lwp->lwp_ru.ru_msgsnd++;
733 	if (control)
734 		m_freem(control);
735 
736 	KASSERT((uio && !top) || (top && !uio), ("bad arguments to sosendudp"));
737 	resid = uio ? uio->uio_resid : (size_t)top->m_pkthdr.len;
738 
739 restart:
740 	error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
741 	if (error)
742 		goto out;
743 
744 	crit_enter();
745 	if (so->so_state & SS_CANTSENDMORE)
746 		gotoerr(EPIPE);
747 	if (so->so_error) {
748 		error = so->so_error;
749 		so->so_error = 0;
750 		crit_exit();
751 		goto release;
752 	}
753 	if (!(so->so_state & SS_ISCONNECTED) && addr == NULL)
754 		gotoerr(EDESTADDRREQ);
755 	if (resid > so->so_snd.ssb_hiwat)
756 		gotoerr(EMSGSIZE);
757 	space = ssb_space(&so->so_snd);
758 	if (uio && (space < 0 || (size_t)space < resid)) {
759 		if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
760 			gotoerr(EWOULDBLOCK);
761 		ssb_unlock(&so->so_snd);
762 		error = ssb_wait(&so->so_snd);
763 		crit_exit();
764 		if (error)
765 			goto out;
766 		goto restart;
767 	}
768 	crit_exit();
769 
770 	if (uio) {
771 		top = m_uiomove(uio);
772 		if (top == NULL)
773 			goto release;
774 	}
775 
776 	dontroute = (flags & MSG_DONTROUTE) && !(so->so_options & SO_DONTROUTE);
777 	if (dontroute)
778 		so->so_options |= SO_DONTROUTE;
779 
780 	error = so_pru_send(so, 0, top, addr, NULL, td);
781 	top = NULL;		/* sent or freed in lower layer */
782 
783 	if (dontroute)
784 		so->so_options &= ~SO_DONTROUTE;
785 
786 release:
787 	ssb_unlock(&so->so_snd);
788 out:
789 	if (top)
790 		m_freem(top);
791 	return (error);
792 }
793 
794 /*
795  * Implement receive operations on a socket.
796  * We depend on the way that records are added to the signalsockbuf
797  * by sbappend*.  In particular, each record (mbufs linked through m_next)
798  * must begin with an address if the protocol so specifies,
799  * followed by an optional mbuf or mbufs containing ancillary data,
800  * and then zero or more mbufs of data.
801  * In order to avoid blocking network interrupts for the entire time here,
802  * we exit the critical section while doing the actual copy to user space.
803  * Although the signalsockbuf is locked, new data may still be appended,
804  * and thus we must maintain consistency of the signalsockbuf during that time.
805  *
806  * The caller may receive the data as a single mbuf chain by supplying
807  * an mbuf **mp0 for use in returning the chain.  The uio is then used
808  * only for the count in uio_resid.
809  */
810 int
811 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
812 	  struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
813 {
814 	struct mbuf *m, *n;
815 	struct mbuf *free_chain = NULL;
816 	int flags, len, error, offset;
817 	struct protosw *pr = so->so_proto;
818 	int moff, type = 0;
819 	size_t resid, orig_resid;
820 
821 	if (uio)
822 		resid = uio->uio_resid;
823 	else
824 		resid = (size_t)(sio->sb_climit - sio->sb_cc);
825 	orig_resid = resid;
826 
827 	if (psa)
828 		*psa = NULL;
829 	if (controlp)
830 		*controlp = NULL;
831 	if (flagsp)
832 		flags = *flagsp &~ MSG_EOR;
833 	else
834 		flags = 0;
835 	if (flags & MSG_OOB) {
836 		m = m_get(MB_WAIT, MT_DATA);
837 		if (m == NULL)
838 			return (ENOBUFS);
839 		error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
840 		if (error)
841 			goto bad;
842 		if (sio) {
843 			do {
844 				sbappend(sio, m);
845 				KKASSERT(resid >= (size_t)m->m_len);
846 				resid -= (size_t)m->m_len;
847 			} while (resid > 0 && m);
848 		} else {
849 			do {
850 				uio->uio_resid = resid;
851 				error = uiomove(mtod(m, caddr_t),
852 						(int)szmin(resid, m->m_len),
853 						uio);
854 				resid = uio->uio_resid;
855 				m = m_free(m);
856 			} while (uio->uio_resid && error == 0 && m);
857 		}
858 bad:
859 		if (m)
860 			m_freem(m);
861 		return (error);
862 	}
863 	if ((so->so_state & SS_ISCONFIRMING) && resid)
864 		so_pru_rcvd(so, 0);
865 
866 restart:
867 	crit_enter();
868 	error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
869 	if (error)
870 		goto done;
871 
872 	m = so->so_rcv.ssb_mb;
873 	/*
874 	 * If we have less data than requested, block awaiting more
875 	 * (subject to any timeout) if:
876 	 *   1. the current count is less than the low water mark, or
877 	 *   2. MSG_WAITALL is set, and it is possible to do the entire
878 	 *	receive operation at once if we block (resid <= hiwat).
879 	 *   3. MSG_DONTWAIT is not set
880 	 * If MSG_WAITALL is set but resid is larger than the receive buffer,
881 	 * we have to do the receive in sections, and thus risk returning
882 	 * a short count if a timeout or signal occurs after we start.
883 	 */
884 	if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
885 	    (size_t)so->so_rcv.ssb_cc < resid) &&
886 	    (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
887 	    ((flags & MSG_WAITALL) && resid <= (size_t)so->so_rcv.ssb_hiwat)) &&
888 	    m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
889 		KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
890 		if (so->so_error) {
891 			if (m)
892 				goto dontblock;
893 			error = so->so_error;
894 			if ((flags & MSG_PEEK) == 0)
895 				so->so_error = 0;
896 			goto release;
897 		}
898 		if (so->so_state & SS_CANTRCVMORE) {
899 			if (m)
900 				goto dontblock;
901 			else
902 				goto release;
903 		}
904 		for (; m; m = m->m_next) {
905 			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
906 				m = so->so_rcv.ssb_mb;
907 				goto dontblock;
908 			}
909 		}
910 		if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
911 		    (pr->pr_flags & PR_CONNREQUIRED)) {
912 			error = ENOTCONN;
913 			goto release;
914 		}
915 		if (resid == 0)
916 			goto release;
917 		if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
918 			error = EWOULDBLOCK;
919 			goto release;
920 		}
921 		ssb_unlock(&so->so_rcv);
922 		error = ssb_wait(&so->so_rcv);
923 		if (error)
924 			goto done;
925 		crit_exit();
926 		goto restart;
927 	}
928 dontblock:
929 	if (uio && uio->uio_td && uio->uio_td->td_proc)
930 		uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
931 
932 	/*
933 	 * note: m should be == sb_mb here.  Cache the next record while
934 	 * cleaning up.  Note that calling m_free*() will break out critical
935 	 * section.
936 	 */
937 	KKASSERT(m == so->so_rcv.ssb_mb);
938 
939 	/*
940 	 * Skip any address mbufs prepending the record.
941 	 */
942 	if (pr->pr_flags & PR_ADDR) {
943 		KASSERT(m->m_type == MT_SONAME, ("receive 1a"));
944 		orig_resid = 0;
945 		if (psa)
946 			*psa = dup_sockaddr(mtod(m, struct sockaddr *));
947 		if (flags & MSG_PEEK)
948 			m = m->m_next;
949 		else
950 			m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
951 	}
952 
953 	/*
954 	 * Skip any control mbufs prepending the record.
955 	 */
956 #ifdef SCTP
957 	if (pr->pr_flags & PR_ADDR_OPT) {
958 		/*
959 		 * For SCTP we may be getting a
960 		 * whole message OR a partial delivery.
961 		 */
962 		if (m && m->m_type == MT_SONAME) {
963 			orig_resid = 0;
964 			if (psa)
965 				*psa = dup_sockaddr(mtod(m, struct sockaddr *));
966 			if (flags & MSG_PEEK)
967 				m = m->m_next;
968 			else
969 				m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
970 		}
971 	}
972 #endif /* SCTP */
973 	while (m && m->m_type == MT_CONTROL && error == 0) {
974 		if (flags & MSG_PEEK) {
975 			if (controlp)
976 				*controlp = m_copy(m, 0, m->m_len);
977 			m = m->m_next;	/* XXX race */
978 		} else {
979 			if (controlp) {
980 				n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
981 				if (pr->pr_domain->dom_externalize &&
982 				    mtod(m, struct cmsghdr *)->cmsg_type ==
983 				    SCM_RIGHTS)
984 				   error = (*pr->pr_domain->dom_externalize)(m);
985 				*controlp = m;
986 				m = n;
987 			} else {
988 				m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
989 			}
990 		}
991 		if (controlp && *controlp) {
992 			orig_resid = 0;
993 			controlp = &(*controlp)->m_next;
994 		}
995 	}
996 
997 	/*
998 	 * flag OOB data.
999 	 */
1000 	if (m) {
1001 		type = m->m_type;
1002 		if (type == MT_OOBDATA)
1003 			flags |= MSG_OOB;
1004 	}
1005 
1006 	/*
1007 	 * Copy to the UIO or mbuf return chain (*mp).
1008 	 */
1009 	moff = 0;
1010 	offset = 0;
1011 	while (m && resid > 0 && error == 0) {
1012 		if (m->m_type == MT_OOBDATA) {
1013 			if (type != MT_OOBDATA)
1014 				break;
1015 		} else if (type == MT_OOBDATA)
1016 			break;
1017 		else
1018 		    KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1019 			("receive 3"));
1020 		so->so_state &= ~SS_RCVATMARK;
1021 		len = (resid > INT_MAX) ? INT_MAX : resid;
1022 		if (so->so_oobmark && len > so->so_oobmark - offset)
1023 			len = so->so_oobmark - offset;
1024 		if (len > m->m_len - moff)
1025 			len = m->m_len - moff;
1026 
1027 		/*
1028 		 * Copy out to the UIO or pass the mbufs back to the SIO.
1029 		 * The SIO is dealt with when we eat the mbuf, but deal
1030 		 * with the resid here either way.
1031 		 */
1032 		if (uio) {
1033 			crit_exit();
1034 			uio->uio_resid = resid;
1035 			error = uiomove(mtod(m, caddr_t) + moff, len, uio);
1036 			resid = uio->uio_resid;
1037 			crit_enter();
1038 			if (error)
1039 				goto release;
1040 		} else {
1041 			resid -= (size_t)len;
1042 		}
1043 
1044 		/*
1045 		 * Eat the entire mbuf or just a piece of it
1046 		 */
1047 		if (len == m->m_len - moff) {
1048 			if (m->m_flags & M_EOR)
1049 				flags |= MSG_EOR;
1050 #ifdef SCTP
1051 			if (m->m_flags & M_NOTIFICATION)
1052 				flags |= MSG_NOTIFICATION;
1053 #endif /* SCTP */
1054 			if (flags & MSG_PEEK) {
1055 				m = m->m_next;
1056 				moff = 0;
1057 			} else {
1058 				if (sio) {
1059 					n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1060 					sbappend(sio, m);
1061 					m = n;
1062 				} else {
1063 					m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1064 				}
1065 			}
1066 		} else {
1067 			if (flags & MSG_PEEK) {
1068 				moff += len;
1069 			} else {
1070 				if (sio) {
1071 					n = m_copym(m, 0, len, MB_WAIT);
1072 					if (n)
1073 						sbappend(sio, n);
1074 				}
1075 				m->m_data += len;
1076 				m->m_len -= len;
1077 				so->so_rcv.ssb_cc -= len;
1078 			}
1079 		}
1080 		if (so->so_oobmark) {
1081 			if ((flags & MSG_PEEK) == 0) {
1082 				so->so_oobmark -= len;
1083 				if (so->so_oobmark == 0) {
1084 					so->so_state |= SS_RCVATMARK;
1085 					break;
1086 				}
1087 			} else {
1088 				offset += len;
1089 				if (offset == so->so_oobmark)
1090 					break;
1091 			}
1092 		}
1093 		if (flags & MSG_EOR)
1094 			break;
1095 		/*
1096 		 * If the MSG_WAITALL flag is set (for non-atomic socket),
1097 		 * we must not quit until resid == 0 or an error
1098 		 * termination.  If a signal/timeout occurs, return
1099 		 * with a short count but without error.
1100 		 * Keep signalsockbuf locked against other readers.
1101 		 */
1102 		while ((flags & MSG_WAITALL) && m == NULL &&
1103 		       resid > 0 && !sosendallatonce(so) &&
1104 		       so->so_rcv.ssb_mb == NULL) {
1105 			if (so->so_error || so->so_state & SS_CANTRCVMORE)
1106 				break;
1107 			/*
1108 			 * The window might have closed to zero, make
1109 			 * sure we send an ack now that we've drained
1110 			 * the buffer or we might end up blocking until
1111 			 * the idle takes over (5 seconds).
1112 			 */
1113 			if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1114 				so_pru_rcvd(so, flags);
1115 			error = ssb_wait(&so->so_rcv);
1116 			if (error) {
1117 				ssb_unlock(&so->so_rcv);
1118 				error = 0;
1119 				goto done;
1120 			}
1121 			m = so->so_rcv.ssb_mb;
1122 		}
1123 	}
1124 
1125 	/*
1126 	 * If an atomic read was requested but unread data still remains
1127 	 * in the record, set MSG_TRUNC.
1128 	 */
1129 	if (m && pr->pr_flags & PR_ATOMIC)
1130 		flags |= MSG_TRUNC;
1131 
1132 	/*
1133 	 * Cleanup.  If an atomic read was requested drop any unread data.
1134 	 */
1135 	if ((flags & MSG_PEEK) == 0) {
1136 		if (m && (pr->pr_flags & PR_ATOMIC))
1137 			sbdroprecord(&so->so_rcv.sb);
1138 		if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1139 			so_pru_rcvd(so, flags);
1140 	}
1141 
1142 	if (orig_resid == resid && orig_resid &&
1143 	    (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1144 		ssb_unlock(&so->so_rcv);
1145 		crit_exit();
1146 		goto restart;
1147 	}
1148 
1149 	if (flagsp)
1150 		*flagsp |= flags;
1151 release:
1152 	ssb_unlock(&so->so_rcv);
1153 done:
1154 	crit_exit();
1155 	if (free_chain)
1156 		m_freem(free_chain);
1157 	return (error);
1158 }
1159 
1160 int
1161 soshutdown(struct socket *so, int how)
1162 {
1163 	if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1164 		return (EINVAL);
1165 
1166 	if (how != SHUT_WR)
1167 		sorflush(so);
1168 	if (how != SHUT_RD)
1169 		return (so_pru_shutdown(so));
1170 	return (0);
1171 }
1172 
1173 void
1174 sorflush(struct socket *so)
1175 {
1176 	struct signalsockbuf *ssb = &so->so_rcv;
1177 	struct protosw *pr = so->so_proto;
1178 	struct signalsockbuf asb;
1179 
1180 	ssb->ssb_flags |= SSB_NOINTR;
1181 	(void) ssb_lock(ssb, M_WAITOK);
1182 
1183 	crit_enter();
1184 	socantrcvmore(so);
1185 	ssb_unlock(ssb);
1186 	asb = *ssb;
1187 	bzero((caddr_t)ssb, sizeof (*ssb));
1188 	if (asb.ssb_flags & SSB_KNOTE) {
1189 		ssb->ssb_sel.si_note = asb.ssb_sel.si_note;
1190 		ssb->ssb_flags = SSB_KNOTE;
1191 	}
1192 	crit_exit();
1193 
1194 	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose)
1195 		(*pr->pr_domain->dom_dispose)(asb.ssb_mb);
1196 	ssb_release(&asb, so);
1197 }
1198 
1199 #ifdef INET
1200 static int
1201 do_setopt_accept_filter(struct socket *so, struct sockopt *sopt)
1202 {
1203 	struct accept_filter_arg	*afap = NULL;
1204 	struct accept_filter	*afp;
1205 	struct so_accf	*af = so->so_accf;
1206 	int	error = 0;
1207 
1208 	/* do not set/remove accept filters on non listen sockets */
1209 	if ((so->so_options & SO_ACCEPTCONN) == 0) {
1210 		error = EINVAL;
1211 		goto out;
1212 	}
1213 
1214 	/* removing the filter */
1215 	if (sopt == NULL) {
1216 		if (af != NULL) {
1217 			if (af->so_accept_filter != NULL &&
1218 				af->so_accept_filter->accf_destroy != NULL) {
1219 				af->so_accept_filter->accf_destroy(so);
1220 			}
1221 			if (af->so_accept_filter_str != NULL) {
1222 				FREE(af->so_accept_filter_str, M_ACCF);
1223 			}
1224 			FREE(af, M_ACCF);
1225 			so->so_accf = NULL;
1226 		}
1227 		so->so_options &= ~SO_ACCEPTFILTER;
1228 		return (0);
1229 	}
1230 	/* adding a filter */
1231 	/* must remove previous filter first */
1232 	if (af != NULL) {
1233 		error = EINVAL;
1234 		goto out;
1235 	}
1236 	/* don't put large objects on the kernel stack */
1237 	MALLOC(afap, struct accept_filter_arg *, sizeof(*afap), M_TEMP, M_WAITOK);
1238 	error = sooptcopyin(sopt, afap, sizeof *afap, sizeof *afap);
1239 	afap->af_name[sizeof(afap->af_name)-1] = '\0';
1240 	afap->af_arg[sizeof(afap->af_arg)-1] = '\0';
1241 	if (error)
1242 		goto out;
1243 	afp = accept_filt_get(afap->af_name);
1244 	if (afp == NULL) {
1245 		error = ENOENT;
1246 		goto out;
1247 	}
1248 	MALLOC(af, struct so_accf *, sizeof(*af), M_ACCF, M_WAITOK | M_ZERO);
1249 	if (afp->accf_create != NULL) {
1250 		if (afap->af_name[0] != '\0') {
1251 			int len = strlen(afap->af_name) + 1;
1252 
1253 			MALLOC(af->so_accept_filter_str, char *, len, M_ACCF, M_WAITOK);
1254 			strcpy(af->so_accept_filter_str, afap->af_name);
1255 		}
1256 		af->so_accept_filter_arg = afp->accf_create(so, afap->af_arg);
1257 		if (af->so_accept_filter_arg == NULL) {
1258 			FREE(af->so_accept_filter_str, M_ACCF);
1259 			FREE(af, M_ACCF);
1260 			so->so_accf = NULL;
1261 			error = EINVAL;
1262 			goto out;
1263 		}
1264 	}
1265 	af->so_accept_filter = afp;
1266 	so->so_accf = af;
1267 	so->so_options |= SO_ACCEPTFILTER;
1268 out:
1269 	if (afap != NULL)
1270 		FREE(afap, M_TEMP);
1271 	return (error);
1272 }
1273 #endif /* INET */
1274 
1275 /*
1276  * Perhaps this routine, and sooptcopyout(), below, ought to come in
1277  * an additional variant to handle the case where the option value needs
1278  * to be some kind of integer, but not a specific size.
1279  * In addition to their use here, these functions are also called by the
1280  * protocol-level pr_ctloutput() routines.
1281  */
1282 int
1283 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
1284 {
1285 	return soopt_to_kbuf(sopt, buf, len, minlen);
1286 }
1287 
1288 int
1289 soopt_to_kbuf(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
1290 {
1291 	size_t	valsize;
1292 
1293 	KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1294 	KKASSERT(kva_p(buf));
1295 
1296 	/*
1297 	 * If the user gives us more than we wanted, we ignore it,
1298 	 * but if we don't get the minimum length the caller
1299 	 * wants, we return EINVAL.  On success, sopt->sopt_valsize
1300 	 * is set to however much we actually retrieved.
1301 	 */
1302 	if ((valsize = sopt->sopt_valsize) < minlen)
1303 		return EINVAL;
1304 	if (valsize > len)
1305 		sopt->sopt_valsize = valsize = len;
1306 
1307 	bcopy(sopt->sopt_val, buf, valsize);
1308 	return 0;
1309 }
1310 
1311 
1312 int
1313 sosetopt(struct socket *so, struct sockopt *sopt)
1314 {
1315 	int	error, optval;
1316 	struct	linger l;
1317 	struct	timeval tv;
1318 	u_long  val;
1319 
1320 	error = 0;
1321 	sopt->sopt_dir = SOPT_SET;
1322 	if (sopt->sopt_level != SOL_SOCKET) {
1323 		if (so->so_proto && so->so_proto->pr_ctloutput) {
1324 			return (so_pru_ctloutput(so, sopt));
1325 		}
1326 		error = ENOPROTOOPT;
1327 	} else {
1328 		switch (sopt->sopt_name) {
1329 #ifdef INET
1330 		case SO_ACCEPTFILTER:
1331 			error = do_setopt_accept_filter(so, sopt);
1332 			if (error)
1333 				goto bad;
1334 			break;
1335 #endif /* INET */
1336 		case SO_LINGER:
1337 			error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1338 			if (error)
1339 				goto bad;
1340 
1341 			so->so_linger = l.l_linger;
1342 			if (l.l_onoff)
1343 				so->so_options |= SO_LINGER;
1344 			else
1345 				so->so_options &= ~SO_LINGER;
1346 			break;
1347 
1348 		case SO_DEBUG:
1349 		case SO_KEEPALIVE:
1350 		case SO_DONTROUTE:
1351 		case SO_USELOOPBACK:
1352 		case SO_BROADCAST:
1353 		case SO_REUSEADDR:
1354 		case SO_REUSEPORT:
1355 		case SO_OOBINLINE:
1356 		case SO_TIMESTAMP:
1357 			error = sooptcopyin(sopt, &optval, sizeof optval,
1358 					    sizeof optval);
1359 			if (error)
1360 				goto bad;
1361 			if (optval)
1362 				so->so_options |= sopt->sopt_name;
1363 			else
1364 				so->so_options &= ~sopt->sopt_name;
1365 			break;
1366 
1367 		case SO_SNDBUF:
1368 		case SO_RCVBUF:
1369 		case SO_SNDLOWAT:
1370 		case SO_RCVLOWAT:
1371 			error = sooptcopyin(sopt, &optval, sizeof optval,
1372 					    sizeof optval);
1373 			if (error)
1374 				goto bad;
1375 
1376 			/*
1377 			 * Values < 1 make no sense for any of these
1378 			 * options, so disallow them.
1379 			 */
1380 			if (optval < 1) {
1381 				error = EINVAL;
1382 				goto bad;
1383 			}
1384 
1385 			switch (sopt->sopt_name) {
1386 			case SO_SNDBUF:
1387 			case SO_RCVBUF:
1388 				if (ssb_reserve(sopt->sopt_name == SO_SNDBUF ?
1389 				    &so->so_snd : &so->so_rcv, (u_long)optval,
1390 				    so,
1391 				    &curproc->p_rlimit[RLIMIT_SBSIZE]) == 0) {
1392 					error = ENOBUFS;
1393 					goto bad;
1394 				}
1395 				(sopt->sopt_name == SO_SNDBUF ? &so->so_snd :
1396 				    &so->so_rcv)->ssb_flags &= ~SSB_AUTOSIZE;
1397 				break;
1398 
1399 			/*
1400 			 * Make sure the low-water is never greater than
1401 			 * the high-water.
1402 			 */
1403 			case SO_SNDLOWAT:
1404 				so->so_snd.ssb_lowat =
1405 				    (optval > so->so_snd.ssb_hiwat) ?
1406 				    so->so_snd.ssb_hiwat : optval;
1407 				so->so_snd.ssb_flags &= ~SSB_AUTOLOWAT;
1408 				break;
1409 			case SO_RCVLOWAT:
1410 				so->so_rcv.ssb_lowat =
1411 				    (optval > so->so_rcv.ssb_hiwat) ?
1412 				    so->so_rcv.ssb_hiwat : optval;
1413 				so->so_rcv.ssb_flags &= ~SSB_AUTOLOWAT;
1414 				break;
1415 			}
1416 			break;
1417 
1418 		case SO_SNDTIMEO:
1419 		case SO_RCVTIMEO:
1420 			error = sooptcopyin(sopt, &tv, sizeof tv,
1421 					    sizeof tv);
1422 			if (error)
1423 				goto bad;
1424 
1425 			/* assert(hz > 0); */
1426 			if (tv.tv_sec < 0 || tv.tv_sec > SHRT_MAX / hz ||
1427 			    tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1428 				error = EDOM;
1429 				goto bad;
1430 			}
1431 			/* assert(tick > 0); */
1432 			/* assert(ULONG_MAX - SHRT_MAX >= 1000000); */
1433 			val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / ustick;
1434 			if (val > SHRT_MAX) {
1435 				error = EDOM;
1436 				goto bad;
1437 			}
1438 			if (val == 0 && tv.tv_usec != 0)
1439 				val = 1;
1440 
1441 			switch (sopt->sopt_name) {
1442 			case SO_SNDTIMEO:
1443 				so->so_snd.ssb_timeo = val;
1444 				break;
1445 			case SO_RCVTIMEO:
1446 				so->so_rcv.ssb_timeo = val;
1447 				break;
1448 			}
1449 			break;
1450 		default:
1451 			error = ENOPROTOOPT;
1452 			break;
1453 		}
1454 		if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
1455 			(void) so_pru_ctloutput(so, sopt);
1456 		}
1457 	}
1458 bad:
1459 	return (error);
1460 }
1461 
1462 /* Helper routine for getsockopt */
1463 int
1464 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
1465 {
1466 	soopt_from_kbuf(sopt, buf, len);
1467 	return 0;
1468 }
1469 
1470 void
1471 soopt_from_kbuf(struct sockopt *sopt, const void *buf, size_t len)
1472 {
1473 	size_t	valsize;
1474 
1475 	if (len == 0) {
1476 		sopt->sopt_valsize = 0;
1477 		return;
1478 	}
1479 
1480 	KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1481 	KKASSERT(kva_p(buf));
1482 
1483 	/*
1484 	 * Documented get behavior is that we always return a value,
1485 	 * possibly truncated to fit in the user's buffer.
1486 	 * Traditional behavior is that we always tell the user
1487 	 * precisely how much we copied, rather than something useful
1488 	 * like the total amount we had available for her.
1489 	 * Note that this interface is not idempotent; the entire answer must
1490 	 * generated ahead of time.
1491 	 */
1492 	valsize = szmin(len, sopt->sopt_valsize);
1493 	sopt->sopt_valsize = valsize;
1494 	if (sopt->sopt_val != 0) {
1495 		bcopy(buf, sopt->sopt_val, valsize);
1496 	}
1497 }
1498 
1499 int
1500 sogetopt(struct socket *so, struct sockopt *sopt)
1501 {
1502 	int	error, optval;
1503 	struct	linger l;
1504 	struct	timeval tv;
1505 #ifdef INET
1506 	struct accept_filter_arg *afap;
1507 #endif
1508 
1509 	error = 0;
1510 	sopt->sopt_dir = SOPT_GET;
1511 	if (sopt->sopt_level != SOL_SOCKET) {
1512 		if (so->so_proto && so->so_proto->pr_ctloutput) {
1513 			return (so_pru_ctloutput(so, sopt));
1514 		} else
1515 			return (ENOPROTOOPT);
1516 	} else {
1517 		switch (sopt->sopt_name) {
1518 #ifdef INET
1519 		case SO_ACCEPTFILTER:
1520 			if ((so->so_options & SO_ACCEPTCONN) == 0)
1521 				return (EINVAL);
1522 			MALLOC(afap, struct accept_filter_arg *, sizeof(*afap),
1523 				M_TEMP, M_WAITOK | M_ZERO);
1524 			if ((so->so_options & SO_ACCEPTFILTER) != 0) {
1525 				strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
1526 				if (so->so_accf->so_accept_filter_str != NULL)
1527 					strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
1528 			}
1529 			error = sooptcopyout(sopt, afap, sizeof(*afap));
1530 			FREE(afap, M_TEMP);
1531 			break;
1532 #endif /* INET */
1533 
1534 		case SO_LINGER:
1535 			l.l_onoff = so->so_options & SO_LINGER;
1536 			l.l_linger = so->so_linger;
1537 			error = sooptcopyout(sopt, &l, sizeof l);
1538 			break;
1539 
1540 		case SO_USELOOPBACK:
1541 		case SO_DONTROUTE:
1542 		case SO_DEBUG:
1543 		case SO_KEEPALIVE:
1544 		case SO_REUSEADDR:
1545 		case SO_REUSEPORT:
1546 		case SO_BROADCAST:
1547 		case SO_OOBINLINE:
1548 		case SO_TIMESTAMP:
1549 			optval = so->so_options & sopt->sopt_name;
1550 integer:
1551 			error = sooptcopyout(sopt, &optval, sizeof optval);
1552 			break;
1553 
1554 		case SO_TYPE:
1555 			optval = so->so_type;
1556 			goto integer;
1557 
1558 		case SO_ERROR:
1559 			optval = so->so_error;
1560 			so->so_error = 0;
1561 			goto integer;
1562 
1563 		case SO_SNDBUF:
1564 			optval = so->so_snd.ssb_hiwat;
1565 			goto integer;
1566 
1567 		case SO_RCVBUF:
1568 			optval = so->so_rcv.ssb_hiwat;
1569 			goto integer;
1570 
1571 		case SO_SNDLOWAT:
1572 			optval = so->so_snd.ssb_lowat;
1573 			goto integer;
1574 
1575 		case SO_RCVLOWAT:
1576 			optval = so->so_rcv.ssb_lowat;
1577 			goto integer;
1578 
1579 		case SO_SNDTIMEO:
1580 		case SO_RCVTIMEO:
1581 			optval = (sopt->sopt_name == SO_SNDTIMEO ?
1582 				  so->so_snd.ssb_timeo : so->so_rcv.ssb_timeo);
1583 
1584 			tv.tv_sec = optval / hz;
1585 			tv.tv_usec = (optval % hz) * ustick;
1586 			error = sooptcopyout(sopt, &tv, sizeof tv);
1587 			break;
1588 
1589 		default:
1590 			error = ENOPROTOOPT;
1591 			break;
1592 		}
1593 		return (error);
1594 	}
1595 }
1596 
1597 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
1598 int
1599 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
1600 {
1601 	struct mbuf *m, *m_prev;
1602 	int sopt_size = sopt->sopt_valsize, msize;
1603 
1604 	m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT, MT_DATA,
1605 		   0, &msize);
1606 	if (m == NULL)
1607 		return (ENOBUFS);
1608 	m->m_len = min(msize, sopt_size);
1609 	sopt_size -= m->m_len;
1610 	*mp = m;
1611 	m_prev = m;
1612 
1613 	while (sopt_size > 0) {
1614 		m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT,
1615 			   MT_DATA, 0, &msize);
1616 		if (m == NULL) {
1617 			m_freem(*mp);
1618 			return (ENOBUFS);
1619 		}
1620 		m->m_len = min(msize, sopt_size);
1621 		sopt_size -= m->m_len;
1622 		m_prev->m_next = m;
1623 		m_prev = m;
1624 	}
1625 	return (0);
1626 }
1627 
1628 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
1629 int
1630 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
1631 {
1632 	soopt_to_mbuf(sopt, m);
1633 	return 0;
1634 }
1635 
1636 void
1637 soopt_to_mbuf(struct sockopt *sopt, struct mbuf *m)
1638 {
1639 	size_t valsize;
1640 	void *val;
1641 
1642 	KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1643 	KKASSERT(kva_p(m));
1644 	if (sopt->sopt_val == NULL)
1645 		return;
1646 	val = sopt->sopt_val;
1647 	valsize = sopt->sopt_valsize;
1648 	while (m != NULL && valsize >= m->m_len) {
1649 		bcopy(val, mtod(m, char *), m->m_len);
1650 		valsize -= m->m_len;
1651 		val = (caddr_t)val + m->m_len;
1652 		m = m->m_next;
1653 	}
1654 	if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
1655 		panic("ip6_sooptmcopyin");
1656 }
1657 
1658 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
1659 int
1660 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
1661 {
1662 	return soopt_from_mbuf(sopt, m);
1663 }
1664 
1665 int
1666 soopt_from_mbuf(struct sockopt *sopt, struct mbuf *m)
1667 {
1668 	struct mbuf *m0 = m;
1669 	size_t valsize = 0;
1670 	size_t maxsize;
1671 	void *val;
1672 
1673 	KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1674 	KKASSERT(kva_p(m));
1675 	if (sopt->sopt_val == NULL)
1676 		return 0;
1677 	val = sopt->sopt_val;
1678 	maxsize = sopt->sopt_valsize;
1679 	while (m != NULL && maxsize >= m->m_len) {
1680 		bcopy(mtod(m, char *), val, m->m_len);
1681 	       maxsize -= m->m_len;
1682 	       val = (caddr_t)val + m->m_len;
1683 	       valsize += m->m_len;
1684 	       m = m->m_next;
1685 	}
1686 	if (m != NULL) {
1687 		/* enough soopt buffer should be given from user-land */
1688 		m_freem(m0);
1689 		return (EINVAL);
1690 	}
1691 	sopt->sopt_valsize = valsize;
1692 	return 0;
1693 }
1694 
1695 void
1696 sohasoutofband(struct socket *so)
1697 {
1698 	if (so->so_sigio != NULL)
1699 		pgsigio(so->so_sigio, SIGURG, 0);
1700 	selwakeup(&so->so_rcv.ssb_sel);
1701 }
1702 
1703 int
1704 sopoll(struct socket *so, int events, struct ucred *cred, struct thread *td)
1705 {
1706 	int revents = 0;
1707 
1708 	crit_enter();
1709 
1710 	if (events & (POLLIN | POLLRDNORM))
1711 		if (soreadable(so))
1712 			revents |= events & (POLLIN | POLLRDNORM);
1713 
1714 	if (events & POLLINIGNEOF)
1715 		if (so->so_rcv.ssb_cc >= so->so_rcv.ssb_lowat ||
1716 			!TAILQ_EMPTY(&so->so_comp) || so->so_error)
1717 			revents |= POLLINIGNEOF;
1718 
1719 	if (events & (POLLOUT | POLLWRNORM))
1720 		if (sowriteable(so))
1721 			revents |= events & (POLLOUT | POLLWRNORM);
1722 
1723 	if (events & (POLLPRI | POLLRDBAND))
1724 		if (so->so_oobmark || (so->so_state & SS_RCVATMARK))
1725 			revents |= events & (POLLPRI | POLLRDBAND);
1726 
1727 	if (revents == 0) {
1728 		if (events &
1729 			(POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
1730 			 POLLRDBAND)) {
1731 			selrecord(td, &so->so_rcv.ssb_sel);
1732 			so->so_rcv.ssb_flags |= SSB_SEL;
1733 		}
1734 
1735 		if (events & (POLLOUT | POLLWRNORM)) {
1736 			selrecord(td, &so->so_snd.ssb_sel);
1737 			so->so_snd.ssb_flags |= SSB_SEL;
1738 		}
1739 	}
1740 
1741 	crit_exit();
1742 	return (revents);
1743 }
1744 
1745 int
1746 sokqfilter(struct file *fp, struct knote *kn)
1747 {
1748 	struct socket *so = (struct socket *)kn->kn_fp->f_data;
1749 	struct signalsockbuf *ssb;
1750 
1751 	switch (kn->kn_filter) {
1752 	case EVFILT_READ:
1753 		if (so->so_options & SO_ACCEPTCONN)
1754 			kn->kn_fop = &solisten_filtops;
1755 		else
1756 			kn->kn_fop = &soread_filtops;
1757 		ssb = &so->so_rcv;
1758 		break;
1759 	case EVFILT_WRITE:
1760 		kn->kn_fop = &sowrite_filtops;
1761 		ssb = &so->so_snd;
1762 		break;
1763 	default:
1764 		return (1);
1765 	}
1766 
1767 	crit_enter();
1768 	SLIST_INSERT_HEAD(&ssb->ssb_sel.si_note, kn, kn_selnext);
1769 	ssb->ssb_flags |= SSB_KNOTE;
1770 	crit_exit();
1771 	return (0);
1772 }
1773 
1774 static void
1775 filt_sordetach(struct knote *kn)
1776 {
1777 	struct socket *so = (struct socket *)kn->kn_fp->f_data;
1778 
1779 	crit_enter();
1780 	SLIST_REMOVE(&so->so_rcv.ssb_sel.si_note, kn, knote, kn_selnext);
1781 	if (SLIST_EMPTY(&so->so_rcv.ssb_sel.si_note))
1782 		so->so_rcv.ssb_flags &= ~SSB_KNOTE;
1783 	crit_exit();
1784 }
1785 
1786 /*ARGSUSED*/
1787 static int
1788 filt_soread(struct knote *kn, long hint)
1789 {
1790 	struct socket *so = (struct socket *)kn->kn_fp->f_data;
1791 
1792 	kn->kn_data = so->so_rcv.ssb_cc;
1793 	if (so->so_state & SS_CANTRCVMORE) {
1794 		kn->kn_flags |= EV_EOF;
1795 		kn->kn_fflags = so->so_error;
1796 		return (1);
1797 	}
1798 	if (so->so_error)	/* temporary udp error */
1799 		return (1);
1800 	if (kn->kn_sfflags & NOTE_LOWAT)
1801 		return (kn->kn_data >= kn->kn_sdata);
1802 	return (kn->kn_data >= so->so_rcv.ssb_lowat);
1803 }
1804 
1805 static void
1806 filt_sowdetach(struct knote *kn)
1807 {
1808 	struct socket *so = (struct socket *)kn->kn_fp->f_data;
1809 
1810 	crit_enter();
1811 	SLIST_REMOVE(&so->so_snd.ssb_sel.si_note, kn, knote, kn_selnext);
1812 	if (SLIST_EMPTY(&so->so_snd.ssb_sel.si_note))
1813 		so->so_snd.ssb_flags &= ~SSB_KNOTE;
1814 	crit_exit();
1815 }
1816 
1817 /*ARGSUSED*/
1818 static int
1819 filt_sowrite(struct knote *kn, long hint)
1820 {
1821 	struct socket *so = (struct socket *)kn->kn_fp->f_data;
1822 
1823 	kn->kn_data = ssb_space(&so->so_snd);
1824 	if (so->so_state & SS_CANTSENDMORE) {
1825 		kn->kn_flags |= EV_EOF;
1826 		kn->kn_fflags = so->so_error;
1827 		return (1);
1828 	}
1829 	if (so->so_error)	/* temporary udp error */
1830 		return (1);
1831 	if (((so->so_state & SS_ISCONNECTED) == 0) &&
1832 	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
1833 		return (0);
1834 	if (kn->kn_sfflags & NOTE_LOWAT)
1835 		return (kn->kn_data >= kn->kn_sdata);
1836 	return (kn->kn_data >= so->so_snd.ssb_lowat);
1837 }
1838 
1839 /*ARGSUSED*/
1840 static int
1841 filt_solisten(struct knote *kn, long hint)
1842 {
1843 	struct socket *so = (struct socket *)kn->kn_fp->f_data;
1844 
1845 	kn->kn_data = so->so_qlen;
1846 	return (! TAILQ_EMPTY(&so->so_comp));
1847 }
1848