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