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