2 * Copyright (c) 2004 Jeffrey M. Hsu. All rights reserved.
3 * Copyright (c) 2004 The DragonFly Project. All rights reserved.
5 * This code is derived from software contributed to The DragonFly Project
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of The DragonFly Project nor the names of its
17 * contributors may be used to endorse or promote products derived
18 * from this software without specific, prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * Copyright (c) 1982, 1986, 1988, 1990, 1993
36 * The Regents of the University of California. All rights reserved.
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. All advertising materials mentioning features or use of this software
47 * must display the following acknowledgement:
48 * This product includes software developed by the University of
49 * California, Berkeley and its contributors.
50 * 4. Neither the name of the University nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66 * @(#)uipc_socket.c 8.3 (Berkeley) 4/15/94
67 * $FreeBSD: src/sys/kern/uipc_socket.c,v 1.68.2.24 2003/11/11 17:18:18 silby Exp $
68 * $DragonFly: src/sys/kern/uipc_socket.c,v 1.55 2008/09/02 16:17:52 dillon Exp $
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/fcntl.h>
77 #include <sys/malloc.h>
79 #include <sys/domain.h>
80 #include <sys/file.h> /* for struct knote */
81 #include <sys/kernel.h>
82 #include <sys/malloc.h>
83 #include <sys/event.h>
86 #include <sys/protosw.h>
87 #include <sys/socket.h>
88 #include <sys/socketvar.h>
89 #include <sys/socketops.h>
90 #include <sys/resourcevar.h>
91 #include <sys/signalvar.h>
92 #include <sys/sysctl.h>
95 #include <vm/vm_zone.h>
98 #include <sys/thread2.h>
99 #include <sys/socketvar2.h>
101 #include <machine/limits.h>
104 static int do_setopt_accept_filter(struct socket *so, struct sockopt *sopt);
107 static void filt_sordetach(struct knote *kn);
108 static int filt_soread(struct knote *kn, long hint);
109 static void filt_sowdetach(struct knote *kn);
110 static int filt_sowrite(struct knote *kn, long hint);
111 static int filt_solisten(struct knote *kn, long hint);
113 static struct filterops solisten_filtops =
114 { 1, NULL, filt_sordetach, filt_solisten };
115 static struct filterops soread_filtops =
116 { 1, NULL, filt_sordetach, filt_soread };
117 static struct filterops sowrite_filtops =
118 { 1, NULL, filt_sowdetach, filt_sowrite };
120 MALLOC_DEFINE(M_SOCKET, "socket", "socket struct");
121 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
122 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
125 static int somaxconn = SOMAXCONN;
126 SYSCTL_INT(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLFLAG_RW,
127 &somaxconn, 0, "Maximum pending socket connection queue size");
130 * Socket operation routines.
131 * These routines are called by the routines in
132 * sys_socket.c or from a system process, and
133 * implement the semantics of socket operations by
134 * switching out to the protocol specific routines.
138 * Get a socket structure, and initialize it.
139 * Note that it would probably be better to allocate socket
140 * and PCB at the same time, but I'm not convinced that all
141 * the protocols can be easily modified to do this.
149 waitmask = waitok ? M_WAITOK : M_NOWAIT;
150 so = kmalloc(sizeof(struct socket), M_SOCKET, M_ZERO|waitmask);
152 /* XXX race condition for reentrant kernel */
153 TAILQ_INIT(&so->so_aiojobq);
154 TAILQ_INIT(&so->so_rcv.ssb_sel.si_mlist);
155 TAILQ_INIT(&so->so_snd.ssb_sel.si_mlist);
161 socreate(int dom, struct socket **aso, int type,
162 int proto, struct thread *td)
164 struct proc *p = td->td_proc;
167 struct pru_attach_info ai;
171 prp = pffindproto(dom, proto, type);
173 prp = pffindtype(dom, type);
175 if (prp == 0 || prp->pr_usrreqs->pru_attach == 0)
176 return (EPROTONOSUPPORT);
178 if (p->p_ucred->cr_prison && jail_socket_unixiproute_only &&
179 prp->pr_domain->dom_family != PF_LOCAL &&
180 prp->pr_domain->dom_family != PF_INET &&
181 prp->pr_domain->dom_family != PF_INET6 &&
182 prp->pr_domain->dom_family != PF_ROUTE) {
183 return (EPROTONOSUPPORT);
186 if (prp->pr_type != type)
188 so = soalloc(p != 0);
192 TAILQ_INIT(&so->so_incomp);
193 TAILQ_INIT(&so->so_comp);
195 so->so_cred = crhold(p->p_ucred);
197 ai.sb_rlimit = &p->p_rlimit[RLIMIT_SBSIZE];
198 ai.p_ucred = p->p_ucred;
199 ai.fd_rdir = p->p_fd->fd_rdir;
201 * Auto-sizing of socket buffers is managed by the protocols and
202 * the appropriate flags must be set in the pru_attach function.
204 error = so_pru_attach(so, proto, &ai);
206 so->so_state |= SS_NOFDREF;
215 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
220 error = so_pru_bind(so, nam, td);
226 sodealloc(struct socket *so)
228 if (so->so_rcv.ssb_hiwat)
229 (void)chgsbsize(so->so_cred->cr_uidinfo,
230 &so->so_rcv.ssb_hiwat, 0, RLIM_INFINITY);
231 if (so->so_snd.ssb_hiwat)
232 (void)chgsbsize(so->so_cred->cr_uidinfo,
233 &so->so_snd.ssb_hiwat, 0, RLIM_INFINITY);
235 /* remove accept filter if present */
236 if (so->so_accf != NULL)
237 do_setopt_accept_filter(so, NULL);
244 solisten(struct socket *so, int backlog, struct thread *td)
248 short oldopt, oldqlimit;
252 if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING)) {
258 oldopt = so->so_options;
259 oldqlimit = so->so_qlimit;
262 if (TAILQ_EMPTY(&so->so_comp))
263 so->so_options |= SO_ACCEPTCONN;
264 if (backlog < 0 || backlog > somaxconn)
266 so->so_qlimit = backlog;
267 /* SCTP needs to look at tweak both the inbound backlog parameter AND
268 * the so_options (UDP model both connect's and gets inbound
269 * connections .. implicitly).
271 error = so_pru_listen(so, td);
274 /* Restore the params */
275 so->so_options = oldopt;
276 so->so_qlimit = oldqlimit;
286 * Destroy a disconnected socket. This routine is a NOP if entities
287 * still have a reference on the socket:
289 * so_pcb - The protocol stack still has a reference
290 * SS_NOFDREF - There is no longer a file pointer reference
291 * SS_ABORTING - An abort netmsg is in-flight
294 sofree(struct socket *so)
296 struct socket *head = so->so_head;
298 if (so->so_pcb || (so->so_state & SS_NOFDREF) == 0)
300 if (so->so_state & SS_ABORTING)
303 if (so->so_state & SS_INCOMP) {
304 TAILQ_REMOVE(&head->so_incomp, so, so_list);
306 } else if (so->so_state & SS_COMP) {
308 * We must not decommission a socket that's
309 * on the accept(2) queue. If we do, then
310 * accept(2) may hang after select(2) indicated
311 * that the listening socket was ready.
315 panic("sofree: not queued");
317 so->so_state &= ~SS_INCOMP;
320 ssb_release(&so->so_snd, so);
326 * Close a socket on last file table reference removal.
327 * Initiate disconnect if connected.
328 * Free socket when disconnect complete.
331 soclose(struct socket *so, int fflag)
336 funsetown(so->so_sigio);
337 if (so->so_pcb == NULL)
339 if (so->so_state & SS_ISCONNECTED) {
340 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
341 error = sodisconnect(so);
345 if (so->so_options & SO_LINGER) {
346 if ((so->so_state & SS_ISDISCONNECTING) &&
349 while (so->so_state & SS_ISCONNECTED) {
350 error = tsleep((caddr_t)&so->so_timeo,
351 PCATCH, "soclos", so->so_linger * hz);
361 error2 = so_pru_detach(so);
366 if (so->so_options & SO_ACCEPTCONN) {
369 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
370 TAILQ_REMOVE(&so->so_incomp, sp, so_list);
371 sp->so_state &= ~SS_INCOMP;
376 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
377 TAILQ_REMOVE(&so->so_comp, sp, so_list);
378 sp->so_state &= ~SS_COMP;
384 if (so->so_state & SS_NOFDREF)
385 panic("soclose: NOFDREF");
386 so->so_state |= SS_NOFDREF;
393 * Abort and destroy a socket. Only one abort can be in progress
394 * at any given moment.
397 soabort(struct socket *so)
399 if ((so->so_state & SS_ABORTING) == 0) {
400 so->so_state |= SS_ABORTING;
406 soaborta(struct socket *so)
408 if ((so->so_state & SS_ABORTING) == 0) {
409 so->so_state |= SS_ABORTING;
415 soabort_oncpu(struct socket *so)
417 if ((so->so_state & SS_ABORTING) == 0) {
418 so->so_state |= SS_ABORTING;
419 so_pru_abort_oncpu(so);
424 soaccept(struct socket *so, struct sockaddr **nam)
429 if ((so->so_state & SS_NOFDREF) == 0)
430 panic("soaccept: !NOFDREF");
431 so->so_state &= ~SS_NOFDREF;
432 error = so_pru_accept(so, nam);
438 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
442 if (so->so_options & SO_ACCEPTCONN)
446 * If protocol is connection-based, can only connect once.
447 * Otherwise, if connected, try to disconnect first.
448 * This allows user to disconnect by connecting to, e.g.,
451 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
452 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
453 (error = sodisconnect(so)))) {
457 * Prevent accumulated error from previous connection
461 error = so_pru_connect(so, nam, td);
468 soconnect2(struct socket *so1, struct socket *so2)
473 error = so_pru_connect2(so1, so2);
479 sodisconnect(struct socket *so)
484 if ((so->so_state & SS_ISCONNECTED) == 0) {
488 if (so->so_state & SS_ISDISCONNECTING) {
492 error = so_pru_disconnect(so);
498 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
501 * If send must go all at once and message is larger than
502 * send buffering, then hard error.
503 * Lock against other senders.
504 * If must go all at once and not enough room now, then
505 * inform user that this would block and do nothing.
506 * Otherwise, if nonblocking, send as much as possible.
507 * The data to be sent is described by "uio" if nonzero,
508 * otherwise by the mbuf chain "top" (which must be null
509 * if uio is not). Data provided in mbuf chain must be small
510 * enough to send all at once.
512 * Returns nonzero on error, timeout or signal; callers
513 * must check for short counts if EINTR/ERESTART are returned.
514 * Data and control buffers are freed on return.
517 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
518 struct mbuf *top, struct mbuf *control, int flags,
525 int clen = 0, error, dontroute, mlen;
526 int atomic = sosendallatonce(so) || top;
530 resid = uio->uio_resid;
532 resid = (size_t)top->m_pkthdr.len;
534 * WARNING! resid is unsigned, space and len are signed. space
535 * can wind up negative if the sockbuf is overcommitted.
537 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
538 * type sockets since that's an error.
540 if (so->so_type == SOCK_STREAM && (flags & MSG_EOR)) {
546 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
547 (so->so_proto->pr_flags & PR_ATOMIC);
548 if (td->td_lwp != NULL)
549 td->td_lwp->lwp_ru.ru_msgsnd++;
551 clen = control->m_len;
552 #define gotoerr(errcode) { error = errcode; crit_exit(); goto release; }
555 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
560 if (so->so_state & SS_CANTSENDMORE)
563 error = so->so_error;
568 if ((so->so_state & SS_ISCONNECTED) == 0) {
570 * `sendto' and `sendmsg' is allowed on a connection-
571 * based socket if it supports implied connect.
572 * Return ENOTCONN if not connected and no address is
575 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
576 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
577 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
578 !(resid == 0 && clen != 0))
580 } else if (addr == 0)
581 gotoerr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
582 ENOTCONN : EDESTADDRREQ);
584 if ((atomic && resid > so->so_snd.ssb_hiwat) ||
585 clen > so->so_snd.ssb_hiwat) {
588 space = ssb_space(&so->so_snd);
591 if ((space < 0 || (size_t)space < resid + clen) && uio &&
592 (atomic || space < so->so_snd.ssb_lowat || space < clen)) {
593 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
594 gotoerr(EWOULDBLOCK);
595 ssb_unlock(&so->so_snd);
596 error = ssb_wait(&so->so_snd);
608 * Data is prepackaged in "top".
612 top->m_flags |= M_EOR;
616 m = m_getl((int)resid, MB_WAIT, MT_DATA,
617 top == NULL ? M_PKTHDR : 0, &mlen);
620 m->m_pkthdr.rcvif = NULL;
622 len = imin((int)szmin(mlen, resid), space);
623 if (resid < MINCLSIZE) {
625 * For datagram protocols, leave room
626 * for protocol headers in first mbuf.
628 if (atomic && top == 0 && len < mlen)
632 error = uiomove(mtod(m, caddr_t), (size_t)len, uio);
633 resid = uio->uio_resid;
636 top->m_pkthdr.len += len;
642 top->m_flags |= M_EOR;
645 } while (space > 0 && atomic);
647 so->so_options |= SO_DONTROUTE;
648 if (flags & MSG_OOB) {
649 pru_flags = PRUS_OOB;
650 } else if ((flags & MSG_EOF) &&
651 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
654 * If the user set MSG_EOF, the protocol
655 * understands this flag and nothing left to
656 * send then use PRU_SEND_EOF instead of PRU_SEND.
658 pru_flags = PRUS_EOF;
659 } else if (resid > 0 && space > 0) {
660 /* If there is more to send, set PRUS_MORETOCOME */
661 pru_flags = PRUS_MORETOCOME;
667 * XXX all the SS_CANTSENDMORE checks previously
668 * done could be out of date. We could have recieved
669 * a reset packet in an interrupt or maybe we slept
670 * while doing page faults in uiomove() etc. We could
671 * probably recheck again inside the splnet() protection
672 * here, but there are probably other places that this
673 * also happens. We must rethink this.
675 error = so_pru_send(so, pru_flags, top, addr, control, td);
678 so->so_options &= ~SO_DONTROUTE;
685 } while (resid && space > 0);
689 ssb_unlock(&so->so_snd);
699 * A specialization of sosend() for UDP based on protocol-specific knowledge:
700 * so->so_proto->pr_flags has the PR_ATOMIC field set. This means that
701 * sosendallatonce() returns true,
702 * the "atomic" variable is true,
703 * and sosendudp() blocks until space is available for the entire send.
704 * so->so_proto->pr_flags does not have the PR_CONNREQUIRED or
705 * PR_IMPLOPCL flags set.
706 * UDP has no out-of-band data.
707 * UDP has no control data.
708 * UDP does not support MSG_EOR.
711 sosendudp(struct socket *so, struct sockaddr *addr, struct uio *uio,
712 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
714 boolean_t dontroute; /* temporary SO_DONTROUTE setting */
719 if (td->td_lwp != NULL)
720 td->td_lwp->lwp_ru.ru_msgsnd++;
724 KASSERT((uio && !top) || (top && !uio), ("bad arguments to sosendudp"));
725 resid = uio ? uio->uio_resid : (size_t)top->m_pkthdr.len;
728 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
733 if (so->so_state & SS_CANTSENDMORE)
736 error = so->so_error;
741 if (!(so->so_state & SS_ISCONNECTED) && addr == NULL)
742 gotoerr(EDESTADDRREQ);
743 if (resid > so->so_snd.ssb_hiwat)
745 space = ssb_space(&so->so_snd);
746 if (uio && (space < 0 || (size_t)space < resid)) {
747 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
748 gotoerr(EWOULDBLOCK);
749 ssb_unlock(&so->so_snd);
750 error = ssb_wait(&so->so_snd);
759 top = m_uiomove(uio);
764 dontroute = (flags & MSG_DONTROUTE) && !(so->so_options & SO_DONTROUTE);
766 so->so_options |= SO_DONTROUTE;
768 error = so_pru_send(so, 0, top, addr, NULL, td);
769 top = NULL; /* sent or freed in lower layer */
772 so->so_options &= ~SO_DONTROUTE;
775 ssb_unlock(&so->so_snd);
783 * Implement receive operations on a socket.
784 * We depend on the way that records are added to the signalsockbuf
785 * by sbappend*. In particular, each record (mbufs linked through m_next)
786 * must begin with an address if the protocol so specifies,
787 * followed by an optional mbuf or mbufs containing ancillary data,
788 * and then zero or more mbufs of data.
789 * In order to avoid blocking network interrupts for the entire time here,
790 * we exit the critical section while doing the actual copy to user space.
791 * Although the signalsockbuf is locked, new data may still be appended,
792 * and thus we must maintain consistency of the signalsockbuf during that time.
794 * The caller may receive the data as a single mbuf chain by supplying
795 * an mbuf **mp0 for use in returning the chain. The uio is then used
796 * only for the count in uio_resid.
799 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
800 struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
803 struct mbuf *free_chain = NULL;
804 int flags, len, error, offset;
805 struct protosw *pr = so->so_proto;
807 size_t resid, orig_resid;
810 resid = uio->uio_resid;
812 resid = (size_t)(sio->sb_climit - sio->sb_cc);
820 flags = *flagsp &~ MSG_EOR;
823 if (flags & MSG_OOB) {
824 m = m_get(MB_WAIT, MT_DATA);
827 error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
833 KKASSERT(resid >= (size_t)m->m_len);
834 resid -= (size_t)m->m_len;
835 } while (resid > 0 && m);
838 uio->uio_resid = resid;
839 error = uiomove(mtod(m, caddr_t),
840 (int)szmin(resid, m->m_len),
842 resid = uio->uio_resid;
844 } while (uio->uio_resid && error == 0 && m);
851 if ((so->so_state & SS_ISCONFIRMING) && resid)
856 error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
860 m = so->so_rcv.ssb_mb;
862 * If we have less data than requested, block awaiting more
863 * (subject to any timeout) if:
864 * 1. the current count is less than the low water mark, or
865 * 2. MSG_WAITALL is set, and it is possible to do the entire
866 * receive operation at once if we block (resid <= hiwat).
867 * 3. MSG_DONTWAIT is not set
868 * If MSG_WAITALL is set but resid is larger than the receive buffer,
869 * we have to do the receive in sections, and thus risk returning
870 * a short count if a timeout or signal occurs after we start.
872 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
873 (size_t)so->so_rcv.ssb_cc < resid) &&
874 (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
875 ((flags & MSG_WAITALL) && resid <= (size_t)so->so_rcv.ssb_hiwat)) &&
876 m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
877 KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
881 error = so->so_error;
882 if ((flags & MSG_PEEK) == 0)
886 if (so->so_state & SS_CANTRCVMORE) {
892 for (; m; m = m->m_next) {
893 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
894 m = so->so_rcv.ssb_mb;
898 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
899 (pr->pr_flags & PR_CONNREQUIRED)) {
905 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
909 ssb_unlock(&so->so_rcv);
910 error = ssb_wait(&so->so_rcv);
917 if (uio && uio->uio_td && uio->uio_td->td_proc)
918 uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
921 * note: m should be == sb_mb here. Cache the next record while
922 * cleaning up. Note that calling m_free*() will break out critical
925 KKASSERT(m == so->so_rcv.ssb_mb);
928 * Skip any address mbufs prepending the record.
930 if (pr->pr_flags & PR_ADDR) {
931 KASSERT(m->m_type == MT_SONAME, ("receive 1a"));
934 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
935 if (flags & MSG_PEEK)
938 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
942 * Skip any control mbufs prepending the record.
945 if (pr->pr_flags & PR_ADDR_OPT) {
947 * For SCTP we may be getting a
948 * whole message OR a partial delivery.
950 if (m && m->m_type == MT_SONAME) {
953 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
954 if (flags & MSG_PEEK)
957 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
961 while (m && m->m_type == MT_CONTROL && error == 0) {
962 if (flags & MSG_PEEK) {
964 *controlp = m_copy(m, 0, m->m_len);
965 m = m->m_next; /* XXX race */
968 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
969 if (pr->pr_domain->dom_externalize &&
970 mtod(m, struct cmsghdr *)->cmsg_type ==
972 error = (*pr->pr_domain->dom_externalize)(m);
976 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
979 if (controlp && *controlp) {
981 controlp = &(*controlp)->m_next;
990 if (type == MT_OOBDATA)
995 * Copy to the UIO or mbuf return chain (*mp).
999 while (m && resid > 0 && error == 0) {
1000 if (m->m_type == MT_OOBDATA) {
1001 if (type != MT_OOBDATA)
1003 } else if (type == MT_OOBDATA)
1006 KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1008 so->so_state &= ~SS_RCVATMARK;
1009 len = (resid > INT_MAX) ? INT_MAX : resid;
1010 if (so->so_oobmark && len > so->so_oobmark - offset)
1011 len = so->so_oobmark - offset;
1012 if (len > m->m_len - moff)
1013 len = m->m_len - moff;
1016 * Copy out to the UIO or pass the mbufs back to the SIO.
1017 * The SIO is dealt with when we eat the mbuf, but deal
1018 * with the resid here either way.
1022 uio->uio_resid = resid;
1023 error = uiomove(mtod(m, caddr_t) + moff, len, uio);
1024 resid = uio->uio_resid;
1029 resid -= (size_t)len;
1033 * Eat the entire mbuf or just a piece of it
1035 if (len == m->m_len - moff) {
1036 if (m->m_flags & M_EOR)
1039 if (m->m_flags & M_NOTIFICATION)
1040 flags |= MSG_NOTIFICATION;
1042 if (flags & MSG_PEEK) {
1047 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1051 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1055 if (flags & MSG_PEEK) {
1059 n = m_copym(m, 0, len, MB_WAIT);
1065 so->so_rcv.ssb_cc -= len;
1068 if (so->so_oobmark) {
1069 if ((flags & MSG_PEEK) == 0) {
1070 so->so_oobmark -= len;
1071 if (so->so_oobmark == 0) {
1072 so->so_state |= SS_RCVATMARK;
1077 if (offset == so->so_oobmark)
1081 if (flags & MSG_EOR)
1084 * If the MSG_WAITALL flag is set (for non-atomic socket),
1085 * we must not quit until resid == 0 or an error
1086 * termination. If a signal/timeout occurs, return
1087 * with a short count but without error.
1088 * Keep signalsockbuf locked against other readers.
1090 while ((flags & MSG_WAITALL) && m == NULL &&
1091 resid > 0 && !sosendallatonce(so) &&
1092 so->so_rcv.ssb_mb == NULL) {
1093 if (so->so_error || so->so_state & SS_CANTRCVMORE)
1096 * The window might have closed to zero, make
1097 * sure we send an ack now that we've drained
1098 * the buffer or we might end up blocking until
1099 * the idle takes over (5 seconds).
1101 if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1102 so_pru_rcvd(so, flags);
1103 error = ssb_wait(&so->so_rcv);
1105 ssb_unlock(&so->so_rcv);
1109 m = so->so_rcv.ssb_mb;
1114 * If an atomic read was requested but unread data still remains
1115 * in the record, set MSG_TRUNC.
1117 if (m && pr->pr_flags & PR_ATOMIC)
1121 * Cleanup. If an atomic read was requested drop any unread data.
1123 if ((flags & MSG_PEEK) == 0) {
1124 if (m && (pr->pr_flags & PR_ATOMIC))
1125 sbdroprecord(&so->so_rcv.sb);
1126 if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1127 so_pru_rcvd(so, flags);
1130 if (orig_resid == resid && orig_resid &&
1131 (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1132 ssb_unlock(&so->so_rcv);
1140 ssb_unlock(&so->so_rcv);
1144 m_freem(free_chain);
1149 soshutdown(struct socket *so, int how)
1151 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1157 return (so_pru_shutdown(so));
1162 sorflush(struct socket *so)
1164 struct signalsockbuf *ssb = &so->so_rcv;
1165 struct protosw *pr = so->so_proto;
1166 struct signalsockbuf asb;
1168 ssb->ssb_flags |= SSB_NOINTR;
1169 (void) ssb_lock(ssb, M_WAITOK);
1175 bzero((caddr_t)ssb, sizeof (*ssb));
1176 if (asb.ssb_flags & SSB_KNOTE) {
1177 ssb->ssb_sel.si_note = asb.ssb_sel.si_note;
1178 ssb->ssb_flags = SSB_KNOTE;
1182 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose)
1183 (*pr->pr_domain->dom_dispose)(asb.ssb_mb);
1184 ssb_release(&asb, so);
1189 do_setopt_accept_filter(struct socket *so, struct sockopt *sopt)
1191 struct accept_filter_arg *afap = NULL;
1192 struct accept_filter *afp;
1193 struct so_accf *af = so->so_accf;
1196 /* do not set/remove accept filters on non listen sockets */
1197 if ((so->so_options & SO_ACCEPTCONN) == 0) {
1202 /* removing the filter */
1205 if (af->so_accept_filter != NULL &&
1206 af->so_accept_filter->accf_destroy != NULL) {
1207 af->so_accept_filter->accf_destroy(so);
1209 if (af->so_accept_filter_str != NULL) {
1210 FREE(af->so_accept_filter_str, M_ACCF);
1215 so->so_options &= ~SO_ACCEPTFILTER;
1218 /* adding a filter */
1219 /* must remove previous filter first */
1224 /* don't put large objects on the kernel stack */
1225 MALLOC(afap, struct accept_filter_arg *, sizeof(*afap), M_TEMP, M_WAITOK);
1226 error = sooptcopyin(sopt, afap, sizeof *afap, sizeof *afap);
1227 afap->af_name[sizeof(afap->af_name)-1] = '\0';
1228 afap->af_arg[sizeof(afap->af_arg)-1] = '\0';
1231 afp = accept_filt_get(afap->af_name);
1236 MALLOC(af, struct so_accf *, sizeof(*af), M_ACCF, M_WAITOK | M_ZERO);
1237 if (afp->accf_create != NULL) {
1238 if (afap->af_name[0] != '\0') {
1239 int len = strlen(afap->af_name) + 1;
1241 MALLOC(af->so_accept_filter_str, char *, len, M_ACCF, M_WAITOK);
1242 strcpy(af->so_accept_filter_str, afap->af_name);
1244 af->so_accept_filter_arg = afp->accf_create(so, afap->af_arg);
1245 if (af->so_accept_filter_arg == NULL) {
1246 FREE(af->so_accept_filter_str, M_ACCF);
1253 af->so_accept_filter = afp;
1255 so->so_options |= SO_ACCEPTFILTER;
1264 * Perhaps this routine, and sooptcopyout(), below, ought to come in
1265 * an additional variant to handle the case where the option value needs
1266 * to be some kind of integer, but not a specific size.
1267 * In addition to their use here, these functions are also called by the
1268 * protocol-level pr_ctloutput() routines.
1271 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
1273 return soopt_to_kbuf(sopt, buf, len, minlen);
1277 soopt_to_kbuf(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
1281 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1282 KKASSERT(kva_p(buf));
1285 * If the user gives us more than we wanted, we ignore it,
1286 * but if we don't get the minimum length the caller
1287 * wants, we return EINVAL. On success, sopt->sopt_valsize
1288 * is set to however much we actually retrieved.
1290 if ((valsize = sopt->sopt_valsize) < minlen)
1293 sopt->sopt_valsize = valsize = len;
1295 bcopy(sopt->sopt_val, buf, valsize);
1301 sosetopt(struct socket *so, struct sockopt *sopt)
1309 sopt->sopt_dir = SOPT_SET;
1310 if (sopt->sopt_level != SOL_SOCKET) {
1311 if (so->so_proto && so->so_proto->pr_ctloutput) {
1312 return (so_pru_ctloutput(so, sopt));
1314 error = ENOPROTOOPT;
1316 switch (sopt->sopt_name) {
1318 case SO_ACCEPTFILTER:
1319 error = do_setopt_accept_filter(so, sopt);
1325 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1329 so->so_linger = l.l_linger;
1331 so->so_options |= SO_LINGER;
1333 so->so_options &= ~SO_LINGER;
1339 case SO_USELOOPBACK:
1345 error = sooptcopyin(sopt, &optval, sizeof optval,
1350 so->so_options |= sopt->sopt_name;
1352 so->so_options &= ~sopt->sopt_name;
1359 error = sooptcopyin(sopt, &optval, sizeof optval,
1365 * Values < 1 make no sense for any of these
1366 * options, so disallow them.
1373 switch (sopt->sopt_name) {
1376 if (ssb_reserve(sopt->sopt_name == SO_SNDBUF ?
1377 &so->so_snd : &so->so_rcv, (u_long)optval,
1379 &curproc->p_rlimit[RLIMIT_SBSIZE]) == 0) {
1383 (sopt->sopt_name == SO_SNDBUF ? &so->so_snd :
1384 &so->so_rcv)->ssb_flags &= ~SSB_AUTOSIZE;
1388 * Make sure the low-water is never greater than
1392 so->so_snd.ssb_lowat =
1393 (optval > so->so_snd.ssb_hiwat) ?
1394 so->so_snd.ssb_hiwat : optval;
1395 so->so_snd.ssb_flags &= ~SSB_AUTOLOWAT;
1398 so->so_rcv.ssb_lowat =
1399 (optval > so->so_rcv.ssb_hiwat) ?
1400 so->so_rcv.ssb_hiwat : optval;
1401 so->so_rcv.ssb_flags &= ~SSB_AUTOLOWAT;
1408 error = sooptcopyin(sopt, &tv, sizeof tv,
1413 /* assert(hz > 0); */
1414 if (tv.tv_sec < 0 || tv.tv_sec > SHRT_MAX / hz ||
1415 tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1419 /* assert(tick > 0); */
1420 /* assert(ULONG_MAX - SHRT_MAX >= 1000000); */
1421 val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
1422 if (val > SHRT_MAX) {
1426 if (val == 0 && tv.tv_usec != 0)
1429 switch (sopt->sopt_name) {
1431 so->so_snd.ssb_timeo = val;
1434 so->so_rcv.ssb_timeo = val;
1439 error = ENOPROTOOPT;
1442 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
1443 (void) so_pru_ctloutput(so, sopt);
1450 /* Helper routine for getsockopt */
1452 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
1454 soopt_from_kbuf(sopt, buf, len);
1459 soopt_from_kbuf(struct sockopt *sopt, const void *buf, size_t len)
1464 sopt->sopt_valsize = 0;
1468 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1469 KKASSERT(kva_p(buf));
1472 * Documented get behavior is that we always return a value,
1473 * possibly truncated to fit in the user's buffer.
1474 * Traditional behavior is that we always tell the user
1475 * precisely how much we copied, rather than something useful
1476 * like the total amount we had available for her.
1477 * Note that this interface is not idempotent; the entire answer must
1478 * generated ahead of time.
1480 valsize = szmin(len, sopt->sopt_valsize);
1481 sopt->sopt_valsize = valsize;
1482 if (sopt->sopt_val != 0) {
1483 bcopy(buf, sopt->sopt_val, valsize);
1488 sogetopt(struct socket *so, struct sockopt *sopt)
1494 struct accept_filter_arg *afap;
1498 sopt->sopt_dir = SOPT_GET;
1499 if (sopt->sopt_level != SOL_SOCKET) {
1500 if (so->so_proto && so->so_proto->pr_ctloutput) {
1501 return (so_pru_ctloutput(so, sopt));
1503 return (ENOPROTOOPT);
1505 switch (sopt->sopt_name) {
1507 case SO_ACCEPTFILTER:
1508 if ((so->so_options & SO_ACCEPTCONN) == 0)
1510 MALLOC(afap, struct accept_filter_arg *, sizeof(*afap),
1511 M_TEMP, M_WAITOK | M_ZERO);
1512 if ((so->so_options & SO_ACCEPTFILTER) != 0) {
1513 strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
1514 if (so->so_accf->so_accept_filter_str != NULL)
1515 strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
1517 error = sooptcopyout(sopt, afap, sizeof(*afap));
1523 l.l_onoff = so->so_options & SO_LINGER;
1524 l.l_linger = so->so_linger;
1525 error = sooptcopyout(sopt, &l, sizeof l);
1528 case SO_USELOOPBACK:
1537 optval = so->so_options & sopt->sopt_name;
1539 error = sooptcopyout(sopt, &optval, sizeof optval);
1543 optval = so->so_type;
1547 optval = so->so_error;
1552 optval = so->so_snd.ssb_hiwat;
1556 optval = so->so_rcv.ssb_hiwat;
1560 optval = so->so_snd.ssb_lowat;
1564 optval = so->so_rcv.ssb_lowat;
1569 optval = (sopt->sopt_name == SO_SNDTIMEO ?
1570 so->so_snd.ssb_timeo : so->so_rcv.ssb_timeo);
1572 tv.tv_sec = optval / hz;
1573 tv.tv_usec = (optval % hz) * tick;
1574 error = sooptcopyout(sopt, &tv, sizeof tv);
1578 error = ENOPROTOOPT;
1585 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
1587 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
1589 struct mbuf *m, *m_prev;
1590 int sopt_size = sopt->sopt_valsize, msize;
1592 m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT, MT_DATA,
1596 m->m_len = min(msize, sopt_size);
1597 sopt_size -= m->m_len;
1601 while (sopt_size > 0) {
1602 m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT,
1603 MT_DATA, 0, &msize);
1608 m->m_len = min(msize, sopt_size);
1609 sopt_size -= m->m_len;
1616 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
1618 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
1620 soopt_to_mbuf(sopt, m);
1625 soopt_to_mbuf(struct sockopt *sopt, struct mbuf *m)
1630 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1632 if (sopt->sopt_val == NULL)
1634 val = sopt->sopt_val;
1635 valsize = sopt->sopt_valsize;
1636 while (m != NULL && valsize >= m->m_len) {
1637 bcopy(val, mtod(m, char *), m->m_len);
1638 valsize -= m->m_len;
1639 val = (caddr_t)val + m->m_len;
1642 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
1643 panic("ip6_sooptmcopyin");
1646 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
1648 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
1650 return soopt_from_mbuf(sopt, m);
1654 soopt_from_mbuf(struct sockopt *sopt, struct mbuf *m)
1656 struct mbuf *m0 = m;
1661 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1663 if (sopt->sopt_val == NULL)
1665 val = sopt->sopt_val;
1666 maxsize = sopt->sopt_valsize;
1667 while (m != NULL && maxsize >= m->m_len) {
1668 bcopy(mtod(m, char *), val, m->m_len);
1669 maxsize -= m->m_len;
1670 val = (caddr_t)val + m->m_len;
1671 valsize += m->m_len;
1675 /* enough soopt buffer should be given from user-land */
1679 sopt->sopt_valsize = valsize;
1684 sohasoutofband(struct socket *so)
1686 if (so->so_sigio != NULL)
1687 pgsigio(so->so_sigio, SIGURG, 0);
1688 selwakeup(&so->so_rcv.ssb_sel);
1692 sopoll(struct socket *so, int events, struct ucred *cred, struct thread *td)
1698 if (events & (POLLIN | POLLRDNORM))
1700 revents |= events & (POLLIN | POLLRDNORM);
1702 if (events & POLLINIGNEOF)
1703 if (so->so_rcv.ssb_cc >= so->so_rcv.ssb_lowat ||
1704 !TAILQ_EMPTY(&so->so_comp) || so->so_error)
1705 revents |= POLLINIGNEOF;
1707 if (events & (POLLOUT | POLLWRNORM))
1708 if (sowriteable(so))
1709 revents |= events & (POLLOUT | POLLWRNORM);
1711 if (events & (POLLPRI | POLLRDBAND))
1712 if (so->so_oobmark || (so->so_state & SS_RCVATMARK))
1713 revents |= events & (POLLPRI | POLLRDBAND);
1717 (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
1719 selrecord(td, &so->so_rcv.ssb_sel);
1720 so->so_rcv.ssb_flags |= SSB_SEL;
1723 if (events & (POLLOUT | POLLWRNORM)) {
1724 selrecord(td, &so->so_snd.ssb_sel);
1725 so->so_snd.ssb_flags |= SSB_SEL;
1734 sokqfilter(struct file *fp, struct knote *kn)
1736 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1737 struct signalsockbuf *ssb;
1739 switch (kn->kn_filter) {
1741 if (so->so_options & SO_ACCEPTCONN)
1742 kn->kn_fop = &solisten_filtops;
1744 kn->kn_fop = &soread_filtops;
1748 kn->kn_fop = &sowrite_filtops;
1756 SLIST_INSERT_HEAD(&ssb->ssb_sel.si_note, kn, kn_selnext);
1757 ssb->ssb_flags |= SSB_KNOTE;
1763 filt_sordetach(struct knote *kn)
1765 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1768 SLIST_REMOVE(&so->so_rcv.ssb_sel.si_note, kn, knote, kn_selnext);
1769 if (SLIST_EMPTY(&so->so_rcv.ssb_sel.si_note))
1770 so->so_rcv.ssb_flags &= ~SSB_KNOTE;
1776 filt_soread(struct knote *kn, long hint)
1778 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1780 kn->kn_data = so->so_rcv.ssb_cc;
1781 if (so->so_state & SS_CANTRCVMORE) {
1782 kn->kn_flags |= EV_EOF;
1783 kn->kn_fflags = so->so_error;
1786 if (so->so_error) /* temporary udp error */
1788 if (kn->kn_sfflags & NOTE_LOWAT)
1789 return (kn->kn_data >= kn->kn_sdata);
1790 return (kn->kn_data >= so->so_rcv.ssb_lowat);
1794 filt_sowdetach(struct knote *kn)
1796 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1799 SLIST_REMOVE(&so->so_snd.ssb_sel.si_note, kn, knote, kn_selnext);
1800 if (SLIST_EMPTY(&so->so_snd.ssb_sel.si_note))
1801 so->so_snd.ssb_flags &= ~SSB_KNOTE;
1807 filt_sowrite(struct knote *kn, long hint)
1809 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1811 kn->kn_data = ssb_space(&so->so_snd);
1812 if (so->so_state & SS_CANTSENDMORE) {
1813 kn->kn_flags |= EV_EOF;
1814 kn->kn_fflags = so->so_error;
1817 if (so->so_error) /* temporary udp error */
1819 if (((so->so_state & SS_ISCONNECTED) == 0) &&
1820 (so->so_proto->pr_flags & PR_CONNREQUIRED))
1822 if (kn->kn_sfflags & NOTE_LOWAT)
1823 return (kn->kn_data >= kn->kn_sdata);
1824 return (kn->kn_data >= so->so_snd.ssb_lowat);
1829 filt_solisten(struct knote *kn, long hint)
1831 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1833 kn->kn_data = so->so_qlen;
1834 return (! TAILQ_EMPTY(&so->so_comp));