xref: /dragonfly/sys/kern/uipc_socket.c (revision 62f7f702)
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.47 2008/01/05 14:02:38 swildner 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 
97 #include <sys/thread2.h>
98 #include <sys/socketvar2.h>
99 
100 #include <machine/limits.h>
101 
102 #ifdef INET
103 static int	 do_setopt_accept_filter(struct socket *so, struct sockopt *sopt);
104 #endif /* INET */
105 
106 static void 	filt_sordetach(struct knote *kn);
107 static int 	filt_soread(struct knote *kn, long hint);
108 static void 	filt_sowdetach(struct knote *kn);
109 static int	filt_sowrite(struct knote *kn, long hint);
110 static int	filt_solisten(struct knote *kn, long hint);
111 
112 static struct filterops solisten_filtops =
113 	{ 1, NULL, filt_sordetach, filt_solisten };
114 static struct filterops soread_filtops =
115 	{ 1, NULL, filt_sordetach, filt_soread };
116 static struct filterops sowrite_filtops =
117 	{ 1, NULL, filt_sowdetach, filt_sowrite };
118 
119 struct	vm_zone *socket_zone;
120 
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 from our zone, and initialize it.
139  * We don't implement `waitok' yet (see comments in uipc_domain.c).
140  * Note that it would probably be better to allocate socket
141  * and PCB at the same time, but I'm not convinced that all
142  * the protocols can be easily modified to do this.
143  */
144 struct socket *
145 soalloc(int waitok)
146 {
147 	struct socket *so;
148 
149 	so = zalloc(socket_zone);
150 	if (so) {
151 		/* XXX race condition for reentrant kernel */
152 		bzero(so, sizeof *so);
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 	zfree(socket_zone, so);
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 		space = ssb_space(&so->so_snd);
558 		if (flags & MSG_OOB)
559 			space += 1024;
560 		if ((atomic && resid > so->so_snd.ssb_hiwat) ||
561 		    clen > so->so_snd.ssb_hiwat)
562 			gotoerr(EMSGSIZE);
563 		if (space < resid + clen && uio &&
564 		    (atomic || space < so->so_snd.ssb_lowat || space < clen)) {
565 			if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
566 				gotoerr(EWOULDBLOCK);
567 			ssb_unlock(&so->so_snd);
568 			error = ssb_wait(&so->so_snd);
569 			crit_exit();
570 			if (error)
571 				goto out;
572 			goto restart;
573 		}
574 		crit_exit();
575 		mp = &top;
576 		space -= clen;
577 		do {
578 		    if (uio == NULL) {
579 			/*
580 			 * Data is prepackaged in "top".
581 			 */
582 			resid = 0;
583 			if (flags & MSG_EOR)
584 				top->m_flags |= M_EOR;
585 		    } else do {
586 			m = m_getl(resid, MB_WAIT, MT_DATA,
587 				   top == NULL ? M_PKTHDR : 0, &mlen);
588 			if (top == NULL) {
589 				m->m_pkthdr.len = 0;
590 				m->m_pkthdr.rcvif = (struct ifnet *)0;
591 			}
592 			len = min(min(mlen, resid), space);
593 			if (resid < MINCLSIZE) {
594 				/*
595 				 * For datagram protocols, leave room
596 				 * for protocol headers in first mbuf.
597 				 */
598 				if (atomic && top == 0 && len < mlen)
599 					MH_ALIGN(m, len);
600 			}
601 			space -= len;
602 			error = uiomove(mtod(m, caddr_t), (int)len, uio);
603 			resid = uio->uio_resid;
604 			m->m_len = len;
605 			*mp = m;
606 			top->m_pkthdr.len += len;
607 			if (error)
608 				goto release;
609 			mp = &m->m_next;
610 			if (resid <= 0) {
611 				if (flags & MSG_EOR)
612 					top->m_flags |= M_EOR;
613 				break;
614 			}
615 		    } while (space > 0 && atomic);
616 		    if (dontroute)
617 			    so->so_options |= SO_DONTROUTE;
618 		    if (flags & MSG_OOB) {
619 		    	    pru_flags = PRUS_OOB;
620 		    } else if ((flags & MSG_EOF) &&
621 		    	       (so->so_proto->pr_flags & PR_IMPLOPCL) &&
622 		    	       (resid <= 0)) {
623 			    /*
624 			     * If the user set MSG_EOF, the protocol
625 			     * understands this flag and nothing left to
626 			     * send then use PRU_SEND_EOF instead of PRU_SEND.
627 			     */
628 		    	    pru_flags = PRUS_EOF;
629 		    } else if (resid > 0 && space > 0) {
630 			    /* If there is more to send, set PRUS_MORETOCOME */
631 		    	    pru_flags = PRUS_MORETOCOME;
632 		    } else {
633 		    	    pru_flags = 0;
634 		    }
635 		    crit_enter();
636 		    /*
637 		     * XXX all the SS_CANTSENDMORE checks previously
638 		     * done could be out of date.  We could have recieved
639 		     * a reset packet in an interrupt or maybe we slept
640 		     * while doing page faults in uiomove() etc. We could
641 		     * probably recheck again inside the splnet() protection
642 		     * here, but there are probably other places that this
643 		     * also happens.  We must rethink this.
644 		     */
645 		    error = so_pru_send(so, pru_flags, top, addr, control, td);
646 		    crit_exit();
647 		    if (dontroute)
648 			    so->so_options &= ~SO_DONTROUTE;
649 		    clen = 0;
650 		    control = 0;
651 		    top = 0;
652 		    mp = &top;
653 		    if (error)
654 			    goto release;
655 		} while (resid && space > 0);
656 	} while (resid);
657 
658 release:
659 	ssb_unlock(&so->so_snd);
660 out:
661 	if (top)
662 		m_freem(top);
663 	if (control)
664 		m_freem(control);
665 	return (error);
666 }
667 
668 /*
669  * A specialization of sosend() for UDP based on protocol-specific knowledge:
670  *   so->so_proto->pr_flags has the PR_ATOMIC field set.  This means that
671  *	sosendallatonce() returns true,
672  *	the "atomic" variable is true,
673  *	and sosendudp() blocks until space is available for the entire send.
674  *   so->so_proto->pr_flags does not have the PR_CONNREQUIRED or
675  *	PR_IMPLOPCL flags set.
676  *   UDP has no out-of-band data.
677  *   UDP has no control data.
678  *   UDP does not support MSG_EOR.
679  */
680 int
681 sosendudp(struct socket *so, struct sockaddr *addr, struct uio *uio,
682 	  struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
683 {
684 	int resid, error;
685 	boolean_t dontroute;		/* temporary SO_DONTROUTE setting */
686 
687 	if (td->td_lwp != NULL)
688 		td->td_lwp->lwp_ru.ru_msgsnd++;
689 	if (control)
690 		m_freem(control);
691 
692 	KASSERT((uio && !top) || (top && !uio), ("bad arguments to sosendudp"));
693 	resid = uio ? uio->uio_resid : top->m_pkthdr.len;
694 
695 restart:
696 	error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
697 	if (error)
698 		goto out;
699 
700 	crit_enter();
701 	if (so->so_state & SS_CANTSENDMORE)
702 		gotoerr(EPIPE);
703 	if (so->so_error) {
704 		error = so->so_error;
705 		so->so_error = 0;
706 		crit_exit();
707 		goto release;
708 	}
709 	if (!(so->so_state & SS_ISCONNECTED) && addr == NULL)
710 		gotoerr(EDESTADDRREQ);
711 	if (resid > so->so_snd.ssb_hiwat)
712 		gotoerr(EMSGSIZE);
713 	if (uio && ssb_space(&so->so_snd) < resid) {
714 		if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
715 			gotoerr(EWOULDBLOCK);
716 		ssb_unlock(&so->so_snd);
717 		error = ssb_wait(&so->so_snd);
718 		crit_exit();
719 		if (error)
720 			goto out;
721 		goto restart;
722 	}
723 	crit_exit();
724 
725 	if (uio) {
726 		top = m_uiomove(uio);
727 		if (top == NULL)
728 			goto release;
729 	}
730 
731 	dontroute = (flags & MSG_DONTROUTE) && !(so->so_options & SO_DONTROUTE);
732 	if (dontroute)
733 		so->so_options |= SO_DONTROUTE;
734 
735 	error = so_pru_send(so, 0, top, addr, NULL, td);
736 	top = NULL;		/* sent or freed in lower layer */
737 
738 	if (dontroute)
739 		so->so_options &= ~SO_DONTROUTE;
740 
741 release:
742 	ssb_unlock(&so->so_snd);
743 out:
744 	if (top)
745 		m_freem(top);
746 	return (error);
747 }
748 
749 /*
750  * Implement receive operations on a socket.
751  * We depend on the way that records are added to the signalsockbuf
752  * by sbappend*.  In particular, each record (mbufs linked through m_next)
753  * must begin with an address if the protocol so specifies,
754  * followed by an optional mbuf or mbufs containing ancillary data,
755  * and then zero or more mbufs of data.
756  * In order to avoid blocking network interrupts for the entire time here,
757  * we exit the critical section while doing the actual copy to user space.
758  * Although the signalsockbuf is locked, new data may still be appended,
759  * and thus we must maintain consistency of the signalsockbuf during that time.
760  *
761  * The caller may receive the data as a single mbuf chain by supplying
762  * an mbuf **mp0 for use in returning the chain.  The uio is then used
763  * only for the count in uio_resid.
764  */
765 int
766 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
767 	  struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
768 {
769 	struct mbuf *m, *n;
770 	struct mbuf *free_chain = NULL;
771 	int flags, len, error, offset;
772 	struct protosw *pr = so->so_proto;
773 	int moff, type = 0;
774 	int resid, orig_resid;
775 
776 	if (uio)
777 		resid = uio->uio_resid;
778 	else
779 		resid = (int)(sio->sb_climit - sio->sb_cc);
780 	orig_resid = resid;
781 
782 	if (psa)
783 		*psa = NULL;
784 	if (controlp)
785 		*controlp = NULL;
786 	if (flagsp)
787 		flags = *flagsp &~ MSG_EOR;
788 	else
789 		flags = 0;
790 	if (flags & MSG_OOB) {
791 		m = m_get(MB_WAIT, MT_DATA);
792 		if (m == NULL)
793 			return (ENOBUFS);
794 		error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
795 		if (error)
796 			goto bad;
797 		if (sio) {
798 			do {
799 				sbappend(sio, m);
800 				resid -= m->m_len;
801 			} while (resid > 0 && m);
802 		} else {
803 			do {
804 				uio->uio_resid = resid;
805 				error = uiomove(mtod(m, caddr_t),
806 						(int)min(resid, m->m_len), uio);
807 				resid = uio->uio_resid;
808 				m = m_free(m);
809 			} while (uio->uio_resid && error == 0 && m);
810 		}
811 bad:
812 		if (m)
813 			m_freem(m);
814 		return (error);
815 	}
816 	if (so->so_state & SS_ISCONFIRMING && resid)
817 		so_pru_rcvd(so, 0);
818 
819 restart:
820 	crit_enter();
821 	error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
822 	if (error)
823 		goto done;
824 
825 	m = so->so_rcv.ssb_mb;
826 	/*
827 	 * If we have less data than requested, block awaiting more
828 	 * (subject to any timeout) if:
829 	 *   1. the current count is less than the low water mark, or
830 	 *   2. MSG_WAITALL is set, and it is possible to do the entire
831 	 *	receive operation at once if we block (resid <= hiwat).
832 	 *   3. MSG_DONTWAIT is not set
833 	 * If MSG_WAITALL is set but resid is larger than the receive buffer,
834 	 * we have to do the receive in sections, and thus risk returning
835 	 * a short count if a timeout or signal occurs after we start.
836 	 */
837 	if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
838 	    so->so_rcv.ssb_cc < resid) &&
839 	    (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
840 	    ((flags & MSG_WAITALL) && resid <= so->so_rcv.ssb_hiwat)) &&
841 	    m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
842 		KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
843 		if (so->so_error) {
844 			if (m)
845 				goto dontblock;
846 			error = so->so_error;
847 			if ((flags & MSG_PEEK) == 0)
848 				so->so_error = 0;
849 			goto release;
850 		}
851 		if (so->so_state & SS_CANTRCVMORE) {
852 			if (m)
853 				goto dontblock;
854 			else
855 				goto release;
856 		}
857 		for (; m; m = m->m_next) {
858 			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
859 				m = so->so_rcv.ssb_mb;
860 				goto dontblock;
861 			}
862 		}
863 		if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
864 		    (pr->pr_flags & PR_CONNREQUIRED)) {
865 			error = ENOTCONN;
866 			goto release;
867 		}
868 		if (resid == 0)
869 			goto release;
870 		if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
871 			error = EWOULDBLOCK;
872 			goto release;
873 		}
874 		ssb_unlock(&so->so_rcv);
875 		error = ssb_wait(&so->so_rcv);
876 		if (error)
877 			goto done;
878 		crit_exit();
879 		goto restart;
880 	}
881 dontblock:
882 	if (uio && uio->uio_td && uio->uio_td->td_proc)
883 		uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
884 
885 	/*
886 	 * note: m should be == sb_mb here.  Cache the next record while
887 	 * cleaning up.  Note that calling m_free*() will break out critical
888 	 * section.
889 	 */
890 	KKASSERT(m == so->so_rcv.ssb_mb);
891 
892 	/*
893 	 * Skip any address mbufs prepending the record.
894 	 */
895 	if (pr->pr_flags & PR_ADDR) {
896 		KASSERT(m->m_type == MT_SONAME, ("receive 1a"));
897 		orig_resid = 0;
898 		if (psa)
899 			*psa = dup_sockaddr(mtod(m, struct sockaddr *));
900 		if (flags & MSG_PEEK)
901 			m = m->m_next;
902 		else
903 			m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
904 	}
905 
906 	/*
907 	 * Skip any control mbufs prepending the record.
908 	 */
909 #ifdef SCTP
910 	if (pr->pr_flags & PR_ADDR_OPT) {
911 		/*
912 		 * For SCTP we may be getting a
913 		 * whole message OR a partial delivery.
914 		 */
915 		if (m && m->m_type == MT_SONAME) {
916 			orig_resid = 0;
917 			if (psa)
918 				*psa = dup_sockaddr(mtod(m, struct sockaddr *));
919 			if (flags & MSG_PEEK)
920 				m = m->m_next;
921 			else
922 				m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
923 		}
924 	}
925 #endif /* SCTP */
926 	while (m && m->m_type == MT_CONTROL && error == 0) {
927 		if (flags & MSG_PEEK) {
928 			if (controlp)
929 				*controlp = m_copy(m, 0, m->m_len);
930 			m = m->m_next;	/* XXX race */
931 		} else {
932 			if (controlp) {
933 				n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
934 				if (pr->pr_domain->dom_externalize &&
935 				    mtod(m, struct cmsghdr *)->cmsg_type ==
936 				    SCM_RIGHTS)
937 				   error = (*pr->pr_domain->dom_externalize)(m);
938 				*controlp = m;
939 				m = n;
940 			} else {
941 				m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
942 			}
943 		}
944 		if (controlp && *controlp) {
945 			orig_resid = 0;
946 			controlp = &(*controlp)->m_next;
947 		}
948 	}
949 
950 	/*
951 	 * flag OOB data.
952 	 */
953 	if (m) {
954 		type = m->m_type;
955 		if (type == MT_OOBDATA)
956 			flags |= MSG_OOB;
957 	}
958 
959 	/*
960 	 * Copy to the UIO or mbuf return chain (*mp).
961 	 */
962 	moff = 0;
963 	offset = 0;
964 	while (m && resid > 0 && error == 0) {
965 		if (m->m_type == MT_OOBDATA) {
966 			if (type != MT_OOBDATA)
967 				break;
968 		} else if (type == MT_OOBDATA)
969 			break;
970 		else
971 		    KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
972 			("receive 3"));
973 		so->so_state &= ~SS_RCVATMARK;
974 		len = resid;
975 		if (so->so_oobmark && len > so->so_oobmark - offset)
976 			len = so->so_oobmark - offset;
977 		if (len > m->m_len - moff)
978 			len = m->m_len - moff;
979 
980 		/*
981 		 * Copy out to the UIO or pass the mbufs back to the SIO.
982 		 * The SIO is dealt with when we eat the mbuf, but deal
983 		 * with the resid here either way.
984 		 */
985 		if (uio) {
986 			crit_exit();
987 			uio->uio_resid = resid;
988 			error = uiomove(mtod(m, caddr_t) + moff, len, uio);
989 			resid = uio->uio_resid;
990 			crit_enter();
991 			if (error)
992 				goto release;
993 		} else {
994 			resid -= len;
995 		}
996 
997 		/*
998 		 * Eat the entire mbuf or just a piece of it
999 		 */
1000 		if (len == m->m_len - moff) {
1001 			if (m->m_flags & M_EOR)
1002 				flags |= MSG_EOR;
1003 #ifdef SCTP
1004 			if (m->m_flags & M_NOTIFICATION)
1005 				flags |= MSG_NOTIFICATION;
1006 #endif /* SCTP */
1007 			if (flags & MSG_PEEK) {
1008 				m = m->m_next;
1009 				moff = 0;
1010 			} else {
1011 				if (sio) {
1012 					n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1013 					sbappend(sio, m);
1014 					m = n;
1015 				} else {
1016 					m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1017 				}
1018 			}
1019 		} else {
1020 			if (flags & MSG_PEEK) {
1021 				moff += len;
1022 			} else {
1023 				if (sio) {
1024 					n = m_copym(m, 0, len, MB_WAIT);
1025 					if (n)
1026 						sbappend(sio, n);
1027 				}
1028 				m->m_data += len;
1029 				m->m_len -= len;
1030 				so->so_rcv.ssb_cc -= len;
1031 			}
1032 		}
1033 		if (so->so_oobmark) {
1034 			if ((flags & MSG_PEEK) == 0) {
1035 				so->so_oobmark -= len;
1036 				if (so->so_oobmark == 0) {
1037 					so->so_state |= SS_RCVATMARK;
1038 					break;
1039 				}
1040 			} else {
1041 				offset += len;
1042 				if (offset == so->so_oobmark)
1043 					break;
1044 			}
1045 		}
1046 		if (flags & MSG_EOR)
1047 			break;
1048 		/*
1049 		 * If the MSG_WAITALL flag is set (for non-atomic socket),
1050 		 * we must not quit until resid == 0 or an error
1051 		 * termination.  If a signal/timeout occurs, return
1052 		 * with a short count but without error.
1053 		 * Keep signalsockbuf locked against other readers.
1054 		 */
1055 		while ((flags & MSG_WAITALL) && m == NULL &&
1056 		       resid > 0 && !sosendallatonce(so) &&
1057 		       so->so_rcv.ssb_mb == NULL) {
1058 			if (so->so_error || so->so_state & SS_CANTRCVMORE)
1059 				break;
1060 			/*
1061 			 * The window might have closed to zero, make
1062 			 * sure we send an ack now that we've drained
1063 			 * the buffer or we might end up blocking until
1064 			 * the idle takes over (5 seconds).
1065 			 */
1066 			if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1067 				so_pru_rcvd(so, flags);
1068 			error = ssb_wait(&so->so_rcv);
1069 			if (error) {
1070 				ssb_unlock(&so->so_rcv);
1071 				error = 0;
1072 				goto done;
1073 			}
1074 			m = so->so_rcv.ssb_mb;
1075 		}
1076 	}
1077 
1078 	/*
1079 	 * If an atomic read was requested but unread data still remains
1080 	 * in the record, set MSG_TRUNC.
1081 	 */
1082 	if (m && pr->pr_flags & PR_ATOMIC)
1083 		flags |= MSG_TRUNC;
1084 
1085 	/*
1086 	 * Cleanup.  If an atomic read was requested drop any unread data.
1087 	 */
1088 	if ((flags & MSG_PEEK) == 0) {
1089 		if (m && (pr->pr_flags & PR_ATOMIC))
1090 			sbdroprecord(&so->so_rcv.sb);
1091 		if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1092 			so_pru_rcvd(so, flags);
1093 	}
1094 
1095 	if (orig_resid == resid && orig_resid &&
1096 	    (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1097 		ssb_unlock(&so->so_rcv);
1098 		crit_exit();
1099 		goto restart;
1100 	}
1101 
1102 	if (flagsp)
1103 		*flagsp |= flags;
1104 release:
1105 	ssb_unlock(&so->so_rcv);
1106 done:
1107 	crit_exit();
1108 	if (free_chain)
1109 		m_freem(free_chain);
1110 	return (error);
1111 }
1112 
1113 int
1114 soshutdown(struct socket *so, int how)
1115 {
1116 	if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1117 		return (EINVAL);
1118 
1119 	if (how != SHUT_WR)
1120 		sorflush(so);
1121 	if (how != SHUT_RD)
1122 		return (so_pru_shutdown(so));
1123 	return (0);
1124 }
1125 
1126 void
1127 sorflush(struct socket *so)
1128 {
1129 	struct signalsockbuf *ssb = &so->so_rcv;
1130 	struct protosw *pr = so->so_proto;
1131 	struct signalsockbuf asb;
1132 
1133 	ssb->ssb_flags |= SSB_NOINTR;
1134 	(void) ssb_lock(ssb, M_WAITOK);
1135 
1136 	crit_enter();
1137 	socantrcvmore(so);
1138 	ssb_unlock(ssb);
1139 	asb = *ssb;
1140 	bzero((caddr_t)ssb, sizeof (*ssb));
1141 	if (asb.ssb_flags & SSB_KNOTE) {
1142 		ssb->ssb_sel.si_note = asb.ssb_sel.si_note;
1143 		ssb->ssb_flags = SSB_KNOTE;
1144 	}
1145 	crit_exit();
1146 
1147 	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose)
1148 		(*pr->pr_domain->dom_dispose)(asb.ssb_mb);
1149 	ssb_release(&asb, so);
1150 }
1151 
1152 #ifdef INET
1153 static int
1154 do_setopt_accept_filter(struct socket *so, struct sockopt *sopt)
1155 {
1156 	struct accept_filter_arg	*afap = NULL;
1157 	struct accept_filter	*afp;
1158 	struct so_accf	*af = so->so_accf;
1159 	int	error = 0;
1160 
1161 	/* do not set/remove accept filters on non listen sockets */
1162 	if ((so->so_options & SO_ACCEPTCONN) == 0) {
1163 		error = EINVAL;
1164 		goto out;
1165 	}
1166 
1167 	/* removing the filter */
1168 	if (sopt == NULL) {
1169 		if (af != NULL) {
1170 			if (af->so_accept_filter != NULL &&
1171 				af->so_accept_filter->accf_destroy != NULL) {
1172 				af->so_accept_filter->accf_destroy(so);
1173 			}
1174 			if (af->so_accept_filter_str != NULL) {
1175 				FREE(af->so_accept_filter_str, M_ACCF);
1176 			}
1177 			FREE(af, M_ACCF);
1178 			so->so_accf = NULL;
1179 		}
1180 		so->so_options &= ~SO_ACCEPTFILTER;
1181 		return (0);
1182 	}
1183 	/* adding a filter */
1184 	/* must remove previous filter first */
1185 	if (af != NULL) {
1186 		error = EINVAL;
1187 		goto out;
1188 	}
1189 	/* don't put large objects on the kernel stack */
1190 	MALLOC(afap, struct accept_filter_arg *, sizeof(*afap), M_TEMP, M_WAITOK);
1191 	error = sooptcopyin(sopt, afap, sizeof *afap, sizeof *afap);
1192 	afap->af_name[sizeof(afap->af_name)-1] = '\0';
1193 	afap->af_arg[sizeof(afap->af_arg)-1] = '\0';
1194 	if (error)
1195 		goto out;
1196 	afp = accept_filt_get(afap->af_name);
1197 	if (afp == NULL) {
1198 		error = ENOENT;
1199 		goto out;
1200 	}
1201 	MALLOC(af, struct so_accf *, sizeof(*af), M_ACCF, M_WAITOK | M_ZERO);
1202 	if (afp->accf_create != NULL) {
1203 		if (afap->af_name[0] != '\0') {
1204 			int len = strlen(afap->af_name) + 1;
1205 
1206 			MALLOC(af->so_accept_filter_str, char *, len, M_ACCF, M_WAITOK);
1207 			strcpy(af->so_accept_filter_str, afap->af_name);
1208 		}
1209 		af->so_accept_filter_arg = afp->accf_create(so, afap->af_arg);
1210 		if (af->so_accept_filter_arg == NULL) {
1211 			FREE(af->so_accept_filter_str, M_ACCF);
1212 			FREE(af, M_ACCF);
1213 			so->so_accf = NULL;
1214 			error = EINVAL;
1215 			goto out;
1216 		}
1217 	}
1218 	af->so_accept_filter = afp;
1219 	so->so_accf = af;
1220 	so->so_options |= SO_ACCEPTFILTER;
1221 out:
1222 	if (afap != NULL)
1223 		FREE(afap, M_TEMP);
1224 	return (error);
1225 }
1226 #endif /* INET */
1227 
1228 /*
1229  * Perhaps this routine, and sooptcopyout(), below, ought to come in
1230  * an additional variant to handle the case where the option value needs
1231  * to be some kind of integer, but not a specific size.
1232  * In addition to their use here, these functions are also called by the
1233  * protocol-level pr_ctloutput() routines.
1234  */
1235 int
1236 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
1237 {
1238 	size_t	valsize;
1239 
1240 	/*
1241 	 * If the user gives us more than we wanted, we ignore it,
1242 	 * but if we don't get the minimum length the caller
1243 	 * wants, we return EINVAL.  On success, sopt->sopt_valsize
1244 	 * is set to however much we actually retrieved.
1245 	 */
1246 	if ((valsize = sopt->sopt_valsize) < minlen)
1247 		return EINVAL;
1248 	if (valsize > len)
1249 		sopt->sopt_valsize = valsize = len;
1250 
1251 	if (sopt->sopt_td != NULL)
1252 		return (copyin(sopt->sopt_val, buf, valsize));
1253 
1254 	bcopy(sopt->sopt_val, buf, valsize);
1255 	return 0;
1256 }
1257 
1258 int
1259 sosetopt(struct socket *so, struct sockopt *sopt)
1260 {
1261 	int	error, optval;
1262 	struct	linger l;
1263 	struct	timeval tv;
1264 	u_long  val;
1265 
1266 	error = 0;
1267 	sopt->sopt_dir = SOPT_SET;
1268 	if (sopt->sopt_level != SOL_SOCKET) {
1269 		if (so->so_proto && so->so_proto->pr_ctloutput) {
1270 			return (so_pr_ctloutput(so, sopt));
1271 		}
1272 		error = ENOPROTOOPT;
1273 	} else {
1274 		switch (sopt->sopt_name) {
1275 #ifdef INET
1276 		case SO_ACCEPTFILTER:
1277 			error = do_setopt_accept_filter(so, sopt);
1278 			if (error)
1279 				goto bad;
1280 			break;
1281 #endif /* INET */
1282 		case SO_LINGER:
1283 			error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1284 			if (error)
1285 				goto bad;
1286 
1287 			so->so_linger = l.l_linger;
1288 			if (l.l_onoff)
1289 				so->so_options |= SO_LINGER;
1290 			else
1291 				so->so_options &= ~SO_LINGER;
1292 			break;
1293 
1294 		case SO_DEBUG:
1295 		case SO_KEEPALIVE:
1296 		case SO_DONTROUTE:
1297 		case SO_USELOOPBACK:
1298 		case SO_BROADCAST:
1299 		case SO_REUSEADDR:
1300 		case SO_REUSEPORT:
1301 		case SO_OOBINLINE:
1302 		case SO_TIMESTAMP:
1303 			error = sooptcopyin(sopt, &optval, sizeof optval,
1304 					    sizeof optval);
1305 			if (error)
1306 				goto bad;
1307 			if (optval)
1308 				so->so_options |= sopt->sopt_name;
1309 			else
1310 				so->so_options &= ~sopt->sopt_name;
1311 			break;
1312 
1313 		case SO_SNDBUF:
1314 		case SO_RCVBUF:
1315 		case SO_SNDLOWAT:
1316 		case SO_RCVLOWAT:
1317 			error = sooptcopyin(sopt, &optval, sizeof optval,
1318 					    sizeof optval);
1319 			if (error)
1320 				goto bad;
1321 
1322 			/*
1323 			 * Values < 1 make no sense for any of these
1324 			 * options, so disallow them.
1325 			 */
1326 			if (optval < 1) {
1327 				error = EINVAL;
1328 				goto bad;
1329 			}
1330 
1331 			switch (sopt->sopt_name) {
1332 			case SO_SNDBUF:
1333 			case SO_RCVBUF:
1334 				if (ssb_reserve(sopt->sopt_name == SO_SNDBUF ?
1335 				    &so->so_snd : &so->so_rcv, (u_long)optval,
1336 				    so,
1337 				    &curproc->p_rlimit[RLIMIT_SBSIZE]) == 0) {
1338 					error = ENOBUFS;
1339 					goto bad;
1340 				}
1341 				break;
1342 
1343 			/*
1344 			 * Make sure the low-water is never greater than
1345 			 * the high-water.
1346 			 */
1347 			case SO_SNDLOWAT:
1348 				so->so_snd.ssb_lowat =
1349 				    (optval > so->so_snd.ssb_hiwat) ?
1350 				    so->so_snd.ssb_hiwat : optval;
1351 				break;
1352 			case SO_RCVLOWAT:
1353 				so->so_rcv.ssb_lowat =
1354 				    (optval > so->so_rcv.ssb_hiwat) ?
1355 				    so->so_rcv.ssb_hiwat : optval;
1356 				break;
1357 			}
1358 			break;
1359 
1360 		case SO_SNDTIMEO:
1361 		case SO_RCVTIMEO:
1362 			error = sooptcopyin(sopt, &tv, sizeof tv,
1363 					    sizeof tv);
1364 			if (error)
1365 				goto bad;
1366 
1367 			/* assert(hz > 0); */
1368 			if (tv.tv_sec < 0 || tv.tv_sec > SHRT_MAX / hz ||
1369 			    tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1370 				error = EDOM;
1371 				goto bad;
1372 			}
1373 			/* assert(tick > 0); */
1374 			/* assert(ULONG_MAX - SHRT_MAX >= 1000000); */
1375 			val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
1376 			if (val > SHRT_MAX) {
1377 				error = EDOM;
1378 				goto bad;
1379 			}
1380 			if (val == 0 && tv.tv_usec != 0)
1381 				val = 1;
1382 
1383 			switch (sopt->sopt_name) {
1384 			case SO_SNDTIMEO:
1385 				so->so_snd.ssb_timeo = val;
1386 				break;
1387 			case SO_RCVTIMEO:
1388 				so->so_rcv.ssb_timeo = val;
1389 				break;
1390 			}
1391 			break;
1392 		default:
1393 			error = ENOPROTOOPT;
1394 			break;
1395 		}
1396 		if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
1397 			(void) so_pr_ctloutput(so, sopt);
1398 		}
1399 	}
1400 bad:
1401 	return (error);
1402 }
1403 
1404 /* Helper routine for getsockopt */
1405 int
1406 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
1407 {
1408 	int	error;
1409 	size_t	valsize;
1410 
1411 	error = 0;
1412 
1413 	/*
1414 	 * Documented get behavior is that we always return a value,
1415 	 * possibly truncated to fit in the user's buffer.
1416 	 * Traditional behavior is that we always tell the user
1417 	 * precisely how much we copied, rather than something useful
1418 	 * like the total amount we had available for her.
1419 	 * Note that this interface is not idempotent; the entire answer must
1420 	 * generated ahead of time.
1421 	 */
1422 	valsize = min(len, sopt->sopt_valsize);
1423 	sopt->sopt_valsize = valsize;
1424 	if (sopt->sopt_val != 0) {
1425 		if (sopt->sopt_td != NULL)
1426 			error = copyout(buf, sopt->sopt_val, valsize);
1427 		else
1428 			bcopy(buf, sopt->sopt_val, valsize);
1429 	}
1430 	return error;
1431 }
1432 
1433 int
1434 sogetopt(struct socket *so, struct sockopt *sopt)
1435 {
1436 	int	error, optval;
1437 	struct	linger l;
1438 	struct	timeval tv;
1439 #ifdef INET
1440 	struct accept_filter_arg *afap;
1441 #endif
1442 
1443 	error = 0;
1444 	sopt->sopt_dir = SOPT_GET;
1445 	if (sopt->sopt_level != SOL_SOCKET) {
1446 		if (so->so_proto && so->so_proto->pr_ctloutput) {
1447 			return (so_pr_ctloutput(so, sopt));
1448 		} else
1449 			return (ENOPROTOOPT);
1450 	} else {
1451 		switch (sopt->sopt_name) {
1452 #ifdef INET
1453 		case SO_ACCEPTFILTER:
1454 			if ((so->so_options & SO_ACCEPTCONN) == 0)
1455 				return (EINVAL);
1456 			MALLOC(afap, struct accept_filter_arg *, sizeof(*afap),
1457 				M_TEMP, M_WAITOK | M_ZERO);
1458 			if ((so->so_options & SO_ACCEPTFILTER) != 0) {
1459 				strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
1460 				if (so->so_accf->so_accept_filter_str != NULL)
1461 					strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
1462 			}
1463 			error = sooptcopyout(sopt, afap, sizeof(*afap));
1464 			FREE(afap, M_TEMP);
1465 			break;
1466 #endif /* INET */
1467 
1468 		case SO_LINGER:
1469 			l.l_onoff = so->so_options & SO_LINGER;
1470 			l.l_linger = so->so_linger;
1471 			error = sooptcopyout(sopt, &l, sizeof l);
1472 			break;
1473 
1474 		case SO_USELOOPBACK:
1475 		case SO_DONTROUTE:
1476 		case SO_DEBUG:
1477 		case SO_KEEPALIVE:
1478 		case SO_REUSEADDR:
1479 		case SO_REUSEPORT:
1480 		case SO_BROADCAST:
1481 		case SO_OOBINLINE:
1482 		case SO_TIMESTAMP:
1483 			optval = so->so_options & sopt->sopt_name;
1484 integer:
1485 			error = sooptcopyout(sopt, &optval, sizeof optval);
1486 			break;
1487 
1488 		case SO_TYPE:
1489 			optval = so->so_type;
1490 			goto integer;
1491 
1492 		case SO_ERROR:
1493 			optval = so->so_error;
1494 			so->so_error = 0;
1495 			goto integer;
1496 
1497 		case SO_SNDBUF:
1498 			optval = so->so_snd.ssb_hiwat;
1499 			goto integer;
1500 
1501 		case SO_RCVBUF:
1502 			optval = so->so_rcv.ssb_hiwat;
1503 			goto integer;
1504 
1505 		case SO_SNDLOWAT:
1506 			optval = so->so_snd.ssb_lowat;
1507 			goto integer;
1508 
1509 		case SO_RCVLOWAT:
1510 			optval = so->so_rcv.ssb_lowat;
1511 			goto integer;
1512 
1513 		case SO_SNDTIMEO:
1514 		case SO_RCVTIMEO:
1515 			optval = (sopt->sopt_name == SO_SNDTIMEO ?
1516 				  so->so_snd.ssb_timeo : so->so_rcv.ssb_timeo);
1517 
1518 			tv.tv_sec = optval / hz;
1519 			tv.tv_usec = (optval % hz) * tick;
1520 			error = sooptcopyout(sopt, &tv, sizeof tv);
1521 			break;
1522 
1523 		default:
1524 			error = ENOPROTOOPT;
1525 			break;
1526 		}
1527 		return (error);
1528 	}
1529 }
1530 
1531 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
1532 int
1533 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
1534 {
1535 	struct mbuf *m, *m_prev;
1536 	int sopt_size = sopt->sopt_valsize, msize;
1537 
1538 	m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT, MT_DATA,
1539 		   0, &msize);
1540 	if (m == NULL)
1541 		return (ENOBUFS);
1542 	m->m_len = min(msize, sopt_size);
1543 	sopt_size -= m->m_len;
1544 	*mp = m;
1545 	m_prev = m;
1546 
1547 	while (sopt_size > 0) {
1548 		m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT,
1549 			   MT_DATA, 0, &msize);
1550 		if (m == NULL) {
1551 			m_freem(*mp);
1552 			return (ENOBUFS);
1553 		}
1554 		m->m_len = min(msize, sopt_size);
1555 		sopt_size -= m->m_len;
1556 		m_prev->m_next = m;
1557 		m_prev = m;
1558 	}
1559 	return (0);
1560 }
1561 
1562 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
1563 int
1564 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
1565 {
1566 	struct mbuf *m0 = m;
1567 
1568 	if (sopt->sopt_val == NULL)
1569 		return 0;
1570 	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
1571 		if (sopt->sopt_td != NULL) {
1572 			int error;
1573 
1574 			error = copyin(sopt->sopt_val, mtod(m, char *),
1575 				       m->m_len);
1576 			if (error != 0) {
1577 				m_freem(m0);
1578 				return (error);
1579 			}
1580 		} else
1581 			bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
1582 		sopt->sopt_valsize -= m->m_len;
1583 		sopt->sopt_val = (caddr_t)sopt->sopt_val + m->m_len;
1584 		m = m->m_next;
1585 	}
1586 	if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
1587 		panic("ip6_sooptmcopyin");
1588 	return 0;
1589 }
1590 
1591 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
1592 int
1593 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
1594 {
1595 	struct mbuf *m0 = m;
1596 	size_t valsize = 0;
1597 
1598 	if (sopt->sopt_val == NULL)
1599 		return 0;
1600 	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
1601 		if (sopt->sopt_td != NULL) {
1602 			int error;
1603 
1604 			error = copyout(mtod(m, char *), sopt->sopt_val,
1605 				       m->m_len);
1606 			if (error != 0) {
1607 				m_freem(m0);
1608 				return (error);
1609 			}
1610 		} else
1611 			bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
1612 	       sopt->sopt_valsize -= m->m_len;
1613 	       sopt->sopt_val = (caddr_t)sopt->sopt_val + m->m_len;
1614 	       valsize += m->m_len;
1615 	       m = m->m_next;
1616 	}
1617 	if (m != NULL) {
1618 		/* enough soopt buffer should be given from user-land */
1619 		m_freem(m0);
1620 		return (EINVAL);
1621 	}
1622 	sopt->sopt_valsize = valsize;
1623 	return 0;
1624 }
1625 
1626 void
1627 sohasoutofband(struct socket *so)
1628 {
1629 	if (so->so_sigio != NULL)
1630 		pgsigio(so->so_sigio, SIGURG, 0);
1631 	selwakeup(&so->so_rcv.ssb_sel);
1632 }
1633 
1634 int
1635 sopoll(struct socket *so, int events, struct ucred *cred, struct thread *td)
1636 {
1637 	int revents = 0;
1638 
1639 	crit_enter();
1640 
1641 	if (events & (POLLIN | POLLRDNORM))
1642 		if (soreadable(so))
1643 			revents |= events & (POLLIN | POLLRDNORM);
1644 
1645 	if (events & POLLINIGNEOF)
1646 		if (so->so_rcv.ssb_cc >= so->so_rcv.ssb_lowat ||
1647 			!TAILQ_EMPTY(&so->so_comp) || so->so_error)
1648 			revents |= POLLINIGNEOF;
1649 
1650 	if (events & (POLLOUT | POLLWRNORM))
1651 		if (sowriteable(so))
1652 			revents |= events & (POLLOUT | POLLWRNORM);
1653 
1654 	if (events & (POLLPRI | POLLRDBAND))
1655 		if (so->so_oobmark || (so->so_state & SS_RCVATMARK))
1656 			revents |= events & (POLLPRI | POLLRDBAND);
1657 
1658 	if (revents == 0) {
1659 		if (events &
1660 			(POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
1661 			 POLLRDBAND)) {
1662 			selrecord(td, &so->so_rcv.ssb_sel);
1663 			so->so_rcv.ssb_flags |= SSB_SEL;
1664 		}
1665 
1666 		if (events & (POLLOUT | POLLWRNORM)) {
1667 			selrecord(td, &so->so_snd.ssb_sel);
1668 			so->so_snd.ssb_flags |= SSB_SEL;
1669 		}
1670 	}
1671 
1672 	crit_exit();
1673 	return (revents);
1674 }
1675 
1676 int
1677 sokqfilter(struct file *fp, struct knote *kn)
1678 {
1679 	struct socket *so = (struct socket *)kn->kn_fp->f_data;
1680 	struct signalsockbuf *ssb;
1681 
1682 	switch (kn->kn_filter) {
1683 	case EVFILT_READ:
1684 		if (so->so_options & SO_ACCEPTCONN)
1685 			kn->kn_fop = &solisten_filtops;
1686 		else
1687 			kn->kn_fop = &soread_filtops;
1688 		ssb = &so->so_rcv;
1689 		break;
1690 	case EVFILT_WRITE:
1691 		kn->kn_fop = &sowrite_filtops;
1692 		ssb = &so->so_snd;
1693 		break;
1694 	default:
1695 		return (1);
1696 	}
1697 
1698 	crit_enter();
1699 	SLIST_INSERT_HEAD(&ssb->ssb_sel.si_note, kn, kn_selnext);
1700 	ssb->ssb_flags |= SSB_KNOTE;
1701 	crit_exit();
1702 	return (0);
1703 }
1704 
1705 static void
1706 filt_sordetach(struct knote *kn)
1707 {
1708 	struct socket *so = (struct socket *)kn->kn_fp->f_data;
1709 
1710 	crit_enter();
1711 	SLIST_REMOVE(&so->so_rcv.ssb_sel.si_note, kn, knote, kn_selnext);
1712 	if (SLIST_EMPTY(&so->so_rcv.ssb_sel.si_note))
1713 		so->so_rcv.ssb_flags &= ~SSB_KNOTE;
1714 	crit_exit();
1715 }
1716 
1717 /*ARGSUSED*/
1718 static int
1719 filt_soread(struct knote *kn, long hint)
1720 {
1721 	struct socket *so = (struct socket *)kn->kn_fp->f_data;
1722 
1723 	kn->kn_data = so->so_rcv.ssb_cc;
1724 	if (so->so_state & SS_CANTRCVMORE) {
1725 		kn->kn_flags |= EV_EOF;
1726 		kn->kn_fflags = so->so_error;
1727 		return (1);
1728 	}
1729 	if (so->so_error)	/* temporary udp error */
1730 		return (1);
1731 	if (kn->kn_sfflags & NOTE_LOWAT)
1732 		return (kn->kn_data >= kn->kn_sdata);
1733 	return (kn->kn_data >= so->so_rcv.ssb_lowat);
1734 }
1735 
1736 static void
1737 filt_sowdetach(struct knote *kn)
1738 {
1739 	struct socket *so = (struct socket *)kn->kn_fp->f_data;
1740 
1741 	crit_enter();
1742 	SLIST_REMOVE(&so->so_snd.ssb_sel.si_note, kn, knote, kn_selnext);
1743 	if (SLIST_EMPTY(&so->so_snd.ssb_sel.si_note))
1744 		so->so_snd.ssb_flags &= ~SSB_KNOTE;
1745 	crit_exit();
1746 }
1747 
1748 /*ARGSUSED*/
1749 static int
1750 filt_sowrite(struct knote *kn, long hint)
1751 {
1752 	struct socket *so = (struct socket *)kn->kn_fp->f_data;
1753 
1754 	kn->kn_data = ssb_space(&so->so_snd);
1755 	if (so->so_state & SS_CANTSENDMORE) {
1756 		kn->kn_flags |= EV_EOF;
1757 		kn->kn_fflags = so->so_error;
1758 		return (1);
1759 	}
1760 	if (so->so_error)	/* temporary udp error */
1761 		return (1);
1762 	if (((so->so_state & SS_ISCONNECTED) == 0) &&
1763 	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
1764 		return (0);
1765 	if (kn->kn_sfflags & NOTE_LOWAT)
1766 		return (kn->kn_data >= kn->kn_sdata);
1767 	return (kn->kn_data >= so->so_snd.ssb_lowat);
1768 }
1769 
1770 /*ARGSUSED*/
1771 static int
1772 filt_solisten(struct knote *kn, long hint)
1773 {
1774 	struct socket *so = (struct socket *)kn->kn_fp->f_data;
1775 
1776 	kn->kn_data = so->so_qlen;
1777 	return (! TAILQ_EMPTY(&so->so_comp));
1778 }
1779