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