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