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