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