2 * Copyright (c) 2004 The FreeBSD Foundation
3 * Copyright (c) 2004-2005 Robert N. M. Watson
4 * Copyright (c) 1982, 1986, 1988, 1990, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 4. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * @(#)uipc_socket.c 8.3 (Berkeley) 4/15/94
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/fcntl.h>
44 #include <sys/limits.h>
47 #include <sys/malloc.h>
49 #include <sys/mutex.h>
50 #include <sys/domain.h>
51 #include <sys/file.h> /* for struct knote */
52 #include <sys/kernel.h>
53 #include <sys/event.h>
56 #include <sys/protosw.h>
57 #include <sys/socket.h>
58 #include <sys/socketvar.h>
59 #include <sys/resourcevar.h>
60 #include <sys/signalvar.h>
61 #include <sys/sysctl.h>
68 static int soreceive_rcvoob(struct socket *so, struct uio *uio,
71 static void filt_sordetach(struct knote *kn);
72 static int filt_soread(struct knote *kn, long hint);
73 static void filt_sowdetach(struct knote *kn);
74 static int filt_sowrite(struct knote *kn, long hint);
75 static int filt_solisten(struct knote *kn, long hint);
77 static struct filterops solisten_filtops =
78 { 1, NULL, filt_sordetach, filt_solisten };
79 static struct filterops soread_filtops =
80 { 1, NULL, filt_sordetach, filt_soread };
81 static struct filterops sowrite_filtops =
82 { 1, NULL, filt_sowdetach, filt_sowrite };
84 uma_zone_t socket_zone;
85 so_gen_t so_gencnt; /* generation count for sockets */
87 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
88 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
90 SYSCTL_DECL(_kern_ipc);
92 static int somaxconn = SOMAXCONN;
93 static int somaxconn_sysctl(SYSCTL_HANDLER_ARGS);
94 /* XXX: we dont have SYSCTL_USHORT */
95 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLTYPE_UINT | CTLFLAG_RW,
96 0, sizeof(int), somaxconn_sysctl, "I", "Maximum pending socket connection "
98 static int numopensockets;
99 SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
100 &numopensockets, 0, "Number of open sockets");
101 #ifdef ZERO_COPY_SOCKETS
102 /* These aren't static because they're used in other files. */
103 int so_zero_copy_send = 1;
104 int so_zero_copy_receive = 1;
105 SYSCTL_NODE(_kern_ipc, OID_AUTO, zero_copy, CTLFLAG_RD, 0,
106 "Zero copy controls");
107 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, receive, CTLFLAG_RW,
108 &so_zero_copy_receive, 0, "Enable zero copy receive");
109 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, send, CTLFLAG_RW,
110 &so_zero_copy_send, 0, "Enable zero copy send");
111 #endif /* ZERO_COPY_SOCKETS */
114 * accept_mtx locks down per-socket fields relating to accept queues. See
115 * socketvar.h for an annotation of the protected fields of struct socket.
117 struct mtx accept_mtx;
118 MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
121 * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
124 static struct mtx so_global_mtx;
125 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
128 * Socket operation routines.
129 * These routines are called by the routines in
130 * sys_socket.c or from a system process, and
131 * implement the semantics of socket operations by
132 * switching out to the protocol specific routines.
136 * Get a socket structure from our zone, and initialize it.
137 * Note that it would probably be better to allocate socket
138 * and PCB at the same time, but I'm not convinced that all
139 * the protocols can be easily modified to do this.
141 * soalloc() returns a socket with a ref count of 0.
148 so = uma_zalloc(socket_zone, mflags | M_ZERO);
151 if (mac_init_socket(so, mflags) != 0) {
152 uma_zfree(socket_zone, so);
156 SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
157 SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
158 TAILQ_INIT(&so->so_aiojobq);
159 mtx_lock(&so_global_mtx);
160 so->so_gencnt = ++so_gencnt;
162 mtx_unlock(&so_global_mtx);
168 * socreate returns a socket with a ref count of 1. The socket should be
169 * closed with soclose().
172 socreate(dom, aso, type, proto, cred, td)
185 prp = pffindproto(dom, proto, type);
187 prp = pffindtype(dom, type);
189 if (prp == NULL || prp->pr_usrreqs->pru_attach == NULL ||
190 prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
191 return (EPROTONOSUPPORT);
193 if (jailed(cred) && jail_socket_unixiproute_only &&
194 prp->pr_domain->dom_family != PF_LOCAL &&
195 prp->pr_domain->dom_family != PF_INET &&
196 prp->pr_domain->dom_family != PF_ROUTE) {
197 return (EPROTONOSUPPORT);
200 if (prp->pr_type != type)
202 so = soalloc(M_WAITOK);
206 TAILQ_INIT(&so->so_incomp);
207 TAILQ_INIT(&so->so_comp);
209 so->so_cred = crhold(cred);
212 mac_create_socket(cred, so);
214 knlist_init(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
215 knlist_init(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
217 error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
221 so->so_state |= SS_NOFDREF;
232 struct sockaddr *nam;
236 return ((*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td));
240 sodealloc(struct socket *so)
243 KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
244 mtx_lock(&so_global_mtx);
245 so->so_gencnt = ++so_gencnt;
246 mtx_unlock(&so_global_mtx);
247 if (so->so_rcv.sb_hiwat)
248 (void)chgsbsize(so->so_cred->cr_uidinfo,
249 &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
250 if (so->so_snd.sb_hiwat)
251 (void)chgsbsize(so->so_cred->cr_uidinfo,
252 &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
254 /* remove acccept filter if one is present. */
255 if (so->so_accf != NULL)
256 do_setopt_accept_filter(so, NULL);
259 mac_destroy_socket(so);
262 SOCKBUF_LOCK_DESTROY(&so->so_snd);
263 SOCKBUF_LOCK_DESTROY(&so->so_rcv);
264 uma_zfree(socket_zone, so);
265 mtx_lock(&so_global_mtx);
267 mtx_unlock(&so_global_mtx);
271 * solisten() transitions a socket from a non-listening state to a listening
272 * state, but can also be used to update the listen queue depth on an
273 * existing listen socket. The protocol will call back into the sockets
274 * layer using solisten_proto_check() and solisten_proto() to check and set
275 * socket-layer listen state. Call backs are used so that the protocol can
276 * acquire both protocol and socket layer locks in whatever order is reuiqred
279 * Protocol implementors are advised to hold the socket lock across the
280 * socket-layer test and set to avoid races at the socket layer.
283 solisten(so, backlog, td)
290 error = (*so->so_proto->pr_usrreqs->pru_listen)(so, td);
295 * XXXRW: The following state adjustment should occur in
296 * solisten_proto(), but we don't currently pass the backlog request
297 * to the protocol via pru_listen().
299 if (backlog < 0 || backlog > somaxconn)
301 so->so_qlimit = backlog;
306 solisten_proto_check(so)
310 SOCK_LOCK_ASSERT(so);
312 if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
323 SOCK_LOCK_ASSERT(so);
325 so->so_options |= SO_ACCEPTCONN;
329 * Attempt to free a socket. This should really be sotryfree().
331 * We free the socket if the protocol is no longer interested in the socket,
332 * there's no file descriptor reference, and the refcount is 0. While the
333 * calling macro sotryfree() tests the refcount, sofree() has to test it
334 * again as it's possible to race with an accept()ing thread if the socket is
335 * in an listen queue of a listen socket, as being in the listen queue
336 * doesn't elevate the reference count. sofree() acquires the accept mutex
337 * early for this test in order to avoid that race.
345 ACCEPT_LOCK_ASSERT();
346 SOCK_LOCK_ASSERT(so);
348 if (so->so_pcb != NULL || (so->so_state & SS_NOFDREF) == 0 ||
357 KASSERT((so->so_qstate & SQ_COMP) != 0 ||
358 (so->so_qstate & SQ_INCOMP) != 0,
359 ("sofree: so_head != NULL, but neither SQ_COMP nor "
361 KASSERT((so->so_qstate & SQ_COMP) == 0 ||
362 (so->so_qstate & SQ_INCOMP) == 0,
363 ("sofree: so->so_qstate is SQ_COMP and also SQ_INCOMP"));
365 * accept(2) is responsible draining the completed
366 * connection queue and freeing those sockets, so
367 * we just return here if this socket is currently
368 * on the completed connection queue. Otherwise,
369 * accept(2) may hang after select(2) has indicating
370 * that a listening socket was ready. If it's an
371 * incomplete connection, we remove it from the queue
372 * and free it; otherwise, it won't be released until
373 * the listening socket is closed.
375 if ((so->so_qstate & SQ_COMP) != 0) {
380 TAILQ_REMOVE(&head->so_incomp, so, so_list);
382 so->so_qstate &= ~SQ_INCOMP;
385 KASSERT((so->so_qstate & SQ_COMP) == 0 &&
386 (so->so_qstate & SQ_INCOMP) == 0,
387 ("sofree: so_head == NULL, but still SQ_COMP(%d) or SQ_INCOMP(%d)",
388 so->so_qstate & SQ_COMP, so->so_qstate & SQ_INCOMP));
391 SOCKBUF_LOCK(&so->so_snd);
392 so->so_snd.sb_flags |= SB_NOINTR;
393 (void)sblock(&so->so_snd, M_WAITOK);
395 * socantsendmore_locked() drops the socket buffer mutex so that it
396 * can safely perform wakeups. Re-acquire the mutex before
399 socantsendmore_locked(so);
400 SOCKBUF_LOCK(&so->so_snd);
401 sbunlock(&so->so_snd);
402 sbrelease_locked(&so->so_snd, so);
403 SOCKBUF_UNLOCK(&so->so_snd);
405 knlist_destroy(&so->so_rcv.sb_sel.si_note);
406 knlist_destroy(&so->so_snd.sb_sel.si_note);
411 * Close a socket on last file table reference removal.
412 * Initiate disconnect if connected.
413 * Free socket when disconnect complete.
415 * This function will sorele() the socket. Note that soclose() may be
416 * called prior to the ref count reaching zero. The actual socket
417 * structure will not be freed until the ref count reaches zero.
425 KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
427 funsetown(&so->so_sigio);
428 if (so->so_options & SO_ACCEPTCONN) {
431 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
432 TAILQ_REMOVE(&so->so_incomp, sp, so_list);
434 sp->so_qstate &= ~SQ_INCOMP;
440 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
441 TAILQ_REMOVE(&so->so_comp, sp, so_list);
443 sp->so_qstate &= ~SQ_COMP;
451 if (so->so_pcb == NULL)
453 if (so->so_state & SS_ISCONNECTED) {
454 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
455 error = sodisconnect(so);
459 if (so->so_options & SO_LINGER) {
460 if ((so->so_state & SS_ISDISCONNECTING) &&
461 (so->so_state & SS_NBIO))
463 while (so->so_state & SS_ISCONNECTED) {
464 error = tsleep(&so->so_timeo,
465 PSOCK | PCATCH, "soclos", so->so_linger * hz);
472 if (so->so_pcb != NULL) {
473 int error2 = (*so->so_proto->pr_usrreqs->pru_detach)(so);
480 KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
481 so->so_state |= SS_NOFDREF;
487 * soabort() must not be called with any socket locks held, as it calls
488 * into the protocol, which will call back into the socket code causing
489 * it to acquire additional socket locks that may cause recursion or lock
498 error = (*so->so_proto->pr_usrreqs->pru_abort)(so);
502 sotryfree(so); /* note: does not decrement the ref count */
511 struct sockaddr **nam;
516 KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
517 so->so_state &= ~SS_NOFDREF;
519 error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
524 soconnect(so, nam, td)
526 struct sockaddr *nam;
531 if (so->so_options & SO_ACCEPTCONN)
534 * If protocol is connection-based, can only connect once.
535 * Otherwise, if connected, try to disconnect first.
536 * This allows user to disconnect by connecting to, e.g.,
539 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
540 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
541 (error = sodisconnect(so)))) {
545 * Prevent accumulated error from previous connection
549 error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, td);
561 return ((*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2));
570 if ((so->so_state & SS_ISCONNECTED) == 0)
572 if (so->so_state & SS_ISDISCONNECTING)
574 error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
578 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
581 * If send must go all at once and message is larger than
582 * send buffering, then hard error.
583 * Lock against other senders.
584 * If must go all at once and not enough room now, then
585 * inform user that this would block and do nothing.
586 * Otherwise, if nonblocking, send as much as possible.
587 * The data to be sent is described by "uio" if nonzero,
588 * otherwise by the mbuf chain "top" (which must be null
589 * if uio is not). Data provided in mbuf chain must be small
590 * enough to send all at once.
592 * Returns nonzero on error, timeout or signal; callers
593 * must check for short counts if EINTR/ERESTART are returned.
594 * Data and control buffers are freed on return.
597 #ifdef ZERO_COPY_SOCKETS
598 struct so_zerocopy_stats{
603 struct so_zerocopy_stats so_zerocp_stats = {0,0,0};
604 #include <netinet/in.h>
605 #include <net/route.h>
606 #include <netinet/in_pcb.h>
608 #include <vm/vm_page.h>
609 #include <vm/vm_object.h>
610 #endif /*ZERO_COPY_SOCKETS*/
613 sosend(so, addr, uio, top, control, flags, td)
615 struct sockaddr *addr;
618 struct mbuf *control;
624 long space, len = 0, resid;
625 int clen = 0, error, dontroute;
626 int atomic = sosendallatonce(so) || top;
627 #ifdef ZERO_COPY_SOCKETS
629 #endif /* ZERO_COPY_SOCKETS */
632 resid = uio->uio_resid;
634 resid = top->m_pkthdr.len;
636 * In theory resid should be unsigned.
637 * However, space must be signed, as it might be less than 0
638 * if we over-committed, and we must use a signed comparison
639 * of space and resid. On the other hand, a negative resid
640 * causes us to loop sending 0-length segments to the protocol.
642 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
643 * type sockets since that's an error.
645 if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
651 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
652 (so->so_proto->pr_flags & PR_ATOMIC);
654 td->td_proc->p_stats->p_ru.ru_msgsnd++;
656 clen = control->m_len;
657 #define snderr(errno) { error = (errno); goto release; }
659 SOCKBUF_LOCK(&so->so_snd);
661 SOCKBUF_LOCK_ASSERT(&so->so_snd);
662 error = sblock(&so->so_snd, SBLOCKWAIT(flags));
666 SOCKBUF_LOCK_ASSERT(&so->so_snd);
667 if (so->so_snd.sb_state & SBS_CANTSENDMORE)
670 error = so->so_error;
674 if ((so->so_state & SS_ISCONNECTED) == 0) {
676 * `sendto' and `sendmsg' is allowed on a connection-
677 * based socket if it supports implied connect.
678 * Return ENOTCONN if not connected and no address is
681 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
682 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
683 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
684 !(resid == 0 && clen != 0))
686 } else if (addr == NULL)
687 snderr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
688 ENOTCONN : EDESTADDRREQ);
690 space = sbspace(&so->so_snd);
693 if ((atomic && resid > so->so_snd.sb_hiwat) ||
694 clen > so->so_snd.sb_hiwat)
696 if (space < resid + clen &&
697 (atomic || space < so->so_snd.sb_lowat || space < clen)) {
698 if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO))
700 sbunlock(&so->so_snd);
701 error = sbwait(&so->so_snd);
706 SOCKBUF_UNLOCK(&so->so_snd);
712 * Data is prepackaged in "top".
716 top->m_flags |= M_EOR;
718 #ifdef ZERO_COPY_SOCKETS
720 #endif /* ZERO_COPY_SOCKETS */
721 if (resid >= MINCLSIZE) {
722 #ifdef ZERO_COPY_SOCKETS
724 MGETHDR(m, M_TRYWAIT, MT_DATA);
727 SOCKBUF_LOCK(&so->so_snd);
731 m->m_pkthdr.rcvif = (struct ifnet *)0;
733 MGET(m, M_TRYWAIT, MT_DATA);
736 SOCKBUF_LOCK(&so->so_snd);
740 if (so_zero_copy_send &&
743 uio->uio_iov->iov_len>=PAGE_SIZE) {
744 so_zerocp_stats.size_ok++;
745 so_zerocp_stats.align_ok++;
746 cow_send = socow_setup(m, uio);
750 MCLGET(m, M_TRYWAIT);
751 if ((m->m_flags & M_EXT) == 0) {
755 len = min(min(MCLBYTES, resid), space);
758 #else /* ZERO_COPY_SOCKETS */
760 m = m_getcl(M_TRYWAIT, MT_DATA, M_PKTHDR);
762 m->m_pkthdr.rcvif = (struct ifnet *)0;
764 m = m_getcl(M_TRYWAIT, MT_DATA, 0);
765 len = min(min(MCLBYTES, resid), space);
766 #endif /* ZERO_COPY_SOCKETS */
769 m = m_gethdr(M_TRYWAIT, MT_DATA);
771 m->m_pkthdr.rcvif = (struct ifnet *)0;
773 len = min(min(MHLEN, resid), space);
775 * For datagram protocols, leave room
776 * for protocol headers in first mbuf.
778 if (atomic && m && len < MHLEN)
781 m = m_get(M_TRYWAIT, MT_DATA);
782 len = min(min(MLEN, resid), space);
787 SOCKBUF_LOCK(&so->so_snd);
792 #ifdef ZERO_COPY_SOCKETS
796 #endif /* ZERO_COPY_SOCKETS */
797 error = uiomove(mtod(m, void *), (int)len, uio);
798 resid = uio->uio_resid;
801 top->m_pkthdr.len += len;
803 SOCKBUF_LOCK(&so->so_snd);
809 top->m_flags |= M_EOR;
812 } while (space > 0 && atomic);
815 so->so_options |= SO_DONTROUTE;
819 * XXX all the SBS_CANTSENDMORE checks previously
820 * done could be out of date. We could have recieved
821 * a reset packet in an interrupt or maybe we slept
822 * while doing page faults in uiomove() etc. We could
823 * probably recheck again inside the locking protection
824 * here, but there are probably other places that this
825 * also happens. We must rethink this.
827 error = (*so->so_proto->pr_usrreqs->pru_send)(so,
828 (flags & MSG_OOB) ? PRUS_OOB :
830 * If the user set MSG_EOF, the protocol
831 * understands this flag and nothing left to
832 * send then use PRU_SEND_EOF instead of PRU_SEND.
834 ((flags & MSG_EOF) &&
835 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
838 /* If there is more to send set PRUS_MORETOCOME */
839 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
840 top, addr, control, td);
843 so->so_options &= ~SO_DONTROUTE;
851 SOCKBUF_LOCK(&so->so_snd);
854 } while (resid && space > 0);
855 SOCKBUF_LOCK(&so->so_snd);
859 SOCKBUF_LOCK_ASSERT(&so->so_snd);
860 sbunlock(&so->so_snd);
862 SOCKBUF_LOCK_ASSERT(&so->so_snd);
863 SOCKBUF_UNLOCK(&so->so_snd);
873 * The part of soreceive() that implements reading non-inline out-of-band
874 * data from a socket. For more complete comments, see soreceive(), from
875 * which this code originated.
877 * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
878 * unable to return an mbuf chain to the caller.
881 soreceive_rcvoob(so, uio, flags)
886 struct protosw *pr = so->so_proto;
890 KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
892 m = m_get(M_TRYWAIT, MT_DATA);
895 error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
899 #ifdef ZERO_COPY_SOCKETS
900 if (so_zero_copy_receive) {
903 if ((m->m_flags & M_EXT)
904 && (m->m_ext.ext_type == EXT_DISPOSABLE))
909 error = uiomoveco(mtod(m, void *),
910 min(uio->uio_resid, m->m_len),
913 #endif /* ZERO_COPY_SOCKETS */
914 error = uiomove(mtod(m, void *),
915 (int) min(uio->uio_resid, m->m_len), uio);
917 } while (uio->uio_resid && error == 0 && m);
925 * Following replacement or removal of the first mbuf on the first mbuf chain
926 * of a socket buffer, push necessary state changes back into the socket
927 * buffer so that other consumers see the values consistently. 'nextrecord'
928 * is the callers locally stored value of the original value of
929 * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
930 * NOTE: 'nextrecord' may be NULL.
933 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
936 SOCKBUF_LOCK_ASSERT(sb);
938 * First, update for the new value of nextrecord. If necessary, make
939 * it the first record.
941 if (sb->sb_mb != NULL)
942 sb->sb_mb->m_nextpkt = nextrecord;
944 sb->sb_mb = nextrecord;
947 * Now update any dependent socket buffer fields to reflect the new
948 * state. This is an expanded inline of SB_EMPTY_FIXUP(), with the
949 * addition of a second clause that takes care of the case where
950 * sb_mb has been updated, but remains the last record.
952 if (sb->sb_mb == NULL) {
953 sb->sb_mbtail = NULL;
954 sb->sb_lastrecord = NULL;
955 } else if (sb->sb_mb->m_nextpkt == NULL)
956 sb->sb_lastrecord = sb->sb_mb;
961 * Implement receive operations on a socket.
962 * We depend on the way that records are added to the sockbuf
963 * by sbappend*. In particular, each record (mbufs linked through m_next)
964 * must begin with an address if the protocol so specifies,
965 * followed by an optional mbuf or mbufs containing ancillary data,
966 * and then zero or more mbufs of data.
967 * In order to avoid blocking network interrupts for the entire time here,
968 * we splx() while doing the actual copy to user space.
969 * Although the sockbuf is locked, new data may still be appended,
970 * and thus we must maintain consistency of the sockbuf during that time.
972 * The caller may receive the data as a single mbuf chain by supplying
973 * an mbuf **mp0 for use in returning the chain. The uio is then used
974 * only for the count in uio_resid.
977 soreceive(so, psa, uio, mp0, controlp, flagsp)
979 struct sockaddr **psa;
982 struct mbuf **controlp;
985 struct mbuf *m, **mp;
986 int flags, len, error, offset;
987 struct protosw *pr = so->so_proto;
988 struct mbuf *nextrecord;
990 int orig_resid = uio->uio_resid;
995 if (controlp != NULL)
998 flags = *flagsp &~ MSG_EOR;
1001 if (flags & MSG_OOB)
1002 return (soreceive_rcvoob(so, uio, flags));
1005 if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
1007 (*pr->pr_usrreqs->pru_rcvd)(so, 0);
1009 SOCKBUF_LOCK(&so->so_rcv);
1011 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1012 error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
1016 m = so->so_rcv.sb_mb;
1018 * If we have less data than requested, block awaiting more
1019 * (subject to any timeout) if:
1020 * 1. the current count is less than the low water mark, or
1021 * 2. MSG_WAITALL is set, and it is possible to do the entire
1022 * receive operation at once if we block (resid <= hiwat).
1023 * 3. MSG_DONTWAIT is not set
1024 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1025 * we have to do the receive in sections, and thus risk returning
1026 * a short count if a timeout or signal occurs after we start.
1028 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1029 so->so_rcv.sb_cc < uio->uio_resid) &&
1030 (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
1031 ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
1032 m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
1033 KASSERT(m != NULL || !so->so_rcv.sb_cc,
1034 ("receive: m == %p so->so_rcv.sb_cc == %u",
1035 m, so->so_rcv.sb_cc));
1039 error = so->so_error;
1040 if ((flags & MSG_PEEK) == 0)
1044 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1045 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1051 for (; m != NULL; m = m->m_next)
1052 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
1053 m = so->so_rcv.sb_mb;
1056 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1057 (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1061 if (uio->uio_resid == 0)
1063 if ((so->so_state & SS_NBIO) ||
1064 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1065 error = EWOULDBLOCK;
1068 SBLASTRECORDCHK(&so->so_rcv);
1069 SBLASTMBUFCHK(&so->so_rcv);
1070 sbunlock(&so->so_rcv);
1071 error = sbwait(&so->so_rcv);
1078 * From this point onward, we maintain 'nextrecord' as a cache of the
1079 * pointer to the next record in the socket buffer. We must keep the
1080 * various socket buffer pointers and local stack versions of the
1081 * pointers in sync, pushing out modifications before dropping the
1082 * socket buffer mutex, and re-reading them when picking it up.
1084 * Otherwise, we will race with the network stack appending new data
1085 * or records onto the socket buffer by using inconsistent/stale
1086 * versions of the field, possibly resulting in socket buffer
1089 * By holding the high-level sblock(), we prevent simultaneous
1090 * readers from pulling off the front of the socket buffer.
1092 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1094 uio->uio_td->td_proc->p_stats->p_ru.ru_msgrcv++;
1095 KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
1096 SBLASTRECORDCHK(&so->so_rcv);
1097 SBLASTMBUFCHK(&so->so_rcv);
1098 nextrecord = m->m_nextpkt;
1099 if (pr->pr_flags & PR_ADDR) {
1100 KASSERT(m->m_type == MT_SONAME,
1101 ("m->m_type == %d", m->m_type));
1104 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
1106 if (flags & MSG_PEEK) {
1109 sbfree(&so->so_rcv, m);
1110 so->so_rcv.sb_mb = m_free(m);
1111 m = so->so_rcv.sb_mb;
1112 sockbuf_pushsync(&so->so_rcv, nextrecord);
1117 * Process one or more MT_CONTROL mbufs present before any data mbufs
1118 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
1119 * just copy the data; if !MSG_PEEK, we call into the protocol to
1120 * perform externalization (or freeing if controlp == NULL).
1122 if (m != NULL && m->m_type == MT_CONTROL) {
1123 struct mbuf *cm = NULL, *cmn;
1124 struct mbuf **cme = &cm;
1127 if (flags & MSG_PEEK) {
1128 if (controlp != NULL) {
1129 *controlp = m_copy(m, 0, m->m_len);
1130 controlp = &(*controlp)->m_next;
1134 sbfree(&so->so_rcv, m);
1135 so->so_rcv.sb_mb = m->m_next;
1138 cme = &(*cme)->m_next;
1139 m = so->so_rcv.sb_mb;
1141 } while (m != NULL && m->m_type == MT_CONTROL);
1142 if ((flags & MSG_PEEK) == 0)
1143 sockbuf_pushsync(&so->so_rcv, nextrecord);
1144 while (cm != NULL) {
1147 if (pr->pr_domain->dom_externalize != NULL) {
1148 SOCKBUF_UNLOCK(&so->so_rcv);
1149 error = (*pr->pr_domain->dom_externalize)
1151 SOCKBUF_LOCK(&so->so_rcv);
1152 } else if (controlp != NULL)
1156 if (controlp != NULL) {
1158 while (*controlp != NULL)
1159 controlp = &(*controlp)->m_next;
1163 nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1167 if ((flags & MSG_PEEK) == 0) {
1168 KASSERT(m->m_nextpkt == nextrecord,
1169 ("soreceive: post-control, nextrecord !sync"));
1170 if (nextrecord == NULL) {
1171 KASSERT(so->so_rcv.sb_mb == m,
1172 ("soreceive: post-control, sb_mb!=m"));
1173 KASSERT(so->so_rcv.sb_lastrecord == m,
1174 ("soreceive: post-control, lastrecord!=m"));
1178 if (type == MT_OOBDATA)
1181 if ((flags & MSG_PEEK) == 0) {
1182 KASSERT(so->so_rcv.sb_mb == nextrecord,
1183 ("soreceive: sb_mb != nextrecord"));
1184 if (so->so_rcv.sb_mb == NULL) {
1185 KASSERT(so->so_rcv.sb_lastrecord == NULL,
1186 ("soreceive: sb_lastercord != NULL"));
1190 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1191 SBLASTRECORDCHK(&so->so_rcv);
1192 SBLASTMBUFCHK(&so->so_rcv);
1195 * Now continue to read any data mbufs off of the head of the socket
1196 * buffer until the read request is satisfied. Note that 'type' is
1197 * used to store the type of any mbuf reads that have happened so far
1198 * such that soreceive() can stop reading if the type changes, which
1199 * causes soreceive() to return only one of regular data and inline
1200 * out-of-band data in a single socket receive operation.
1204 while (m != NULL && uio->uio_resid > 0 && error == 0) {
1206 * If the type of mbuf has changed since the last mbuf
1207 * examined ('type'), end the receive operation.
1209 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1210 if (m->m_type == MT_OOBDATA) {
1211 if (type != MT_OOBDATA)
1213 } else if (type == MT_OOBDATA)
1216 KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1217 ("m->m_type == %d", m->m_type));
1218 so->so_rcv.sb_state &= ~SBS_RCVATMARK;
1219 len = uio->uio_resid;
1220 if (so->so_oobmark && len > so->so_oobmark - offset)
1221 len = so->so_oobmark - offset;
1222 if (len > m->m_len - moff)
1223 len = m->m_len - moff;
1225 * If mp is set, just pass back the mbufs.
1226 * Otherwise copy them out via the uio, then free.
1227 * Sockbuf must be consistent here (points to current mbuf,
1228 * it points to next record) when we drop priority;
1229 * we must note any additions to the sockbuf when we
1230 * block interrupts again.
1233 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1234 SBLASTRECORDCHK(&so->so_rcv);
1235 SBLASTMBUFCHK(&so->so_rcv);
1236 SOCKBUF_UNLOCK(&so->so_rcv);
1237 #ifdef ZERO_COPY_SOCKETS
1238 if (so_zero_copy_receive) {
1241 if ((m->m_flags & M_EXT)
1242 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1247 error = uiomoveco(mtod(m, char *) + moff,
1251 #endif /* ZERO_COPY_SOCKETS */
1252 error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1253 SOCKBUF_LOCK(&so->so_rcv);
1257 uio->uio_resid -= len;
1258 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1259 if (len == m->m_len - moff) {
1260 if (m->m_flags & M_EOR)
1262 if (flags & MSG_PEEK) {
1266 nextrecord = m->m_nextpkt;
1267 sbfree(&so->so_rcv, m);
1271 so->so_rcv.sb_mb = m = m->m_next;
1274 so->so_rcv.sb_mb = m_free(m);
1275 m = so->so_rcv.sb_mb;
1278 m->m_nextpkt = nextrecord;
1279 if (nextrecord == NULL)
1280 so->so_rcv.sb_lastrecord = m;
1282 so->so_rcv.sb_mb = nextrecord;
1283 SB_EMPTY_FIXUP(&so->so_rcv);
1285 SBLASTRECORDCHK(&so->so_rcv);
1286 SBLASTMBUFCHK(&so->so_rcv);
1289 if (flags & MSG_PEEK)
1295 if (flags & MSG_DONTWAIT)
1296 copy_flag = M_DONTWAIT;
1298 copy_flag = M_TRYWAIT;
1299 if (copy_flag == M_TRYWAIT)
1300 SOCKBUF_UNLOCK(&so->so_rcv);
1301 *mp = m_copym(m, 0, len, copy_flag);
1302 if (copy_flag == M_TRYWAIT)
1303 SOCKBUF_LOCK(&so->so_rcv);
1306 * m_copym() couldn't allocate an mbuf.
1307 * Adjust uio_resid back (it was adjusted
1308 * down by len bytes, which we didn't end
1309 * up "copying" over).
1311 uio->uio_resid += len;
1317 so->so_rcv.sb_cc -= len;
1320 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1321 if (so->so_oobmark) {
1322 if ((flags & MSG_PEEK) == 0) {
1323 so->so_oobmark -= len;
1324 if (so->so_oobmark == 0) {
1325 so->so_rcv.sb_state |= SBS_RCVATMARK;
1330 if (offset == so->so_oobmark)
1334 if (flags & MSG_EOR)
1337 * If the MSG_WAITALL flag is set (for non-atomic socket),
1338 * we must not quit until "uio->uio_resid == 0" or an error
1339 * termination. If a signal/timeout occurs, return
1340 * with a short count but without error.
1341 * Keep sockbuf locked against other readers.
1343 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1344 !sosendallatonce(so) && nextrecord == NULL) {
1345 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1346 if (so->so_error || so->so_rcv.sb_state & SBS_CANTRCVMORE)
1349 * Notify the protocol that some data has been
1350 * drained before blocking.
1352 if (pr->pr_flags & PR_WANTRCVD && so->so_pcb != NULL) {
1353 SOCKBUF_UNLOCK(&so->so_rcv);
1354 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1355 SOCKBUF_LOCK(&so->so_rcv);
1357 SBLASTRECORDCHK(&so->so_rcv);
1358 SBLASTMBUFCHK(&so->so_rcv);
1359 error = sbwait(&so->so_rcv);
1362 m = so->so_rcv.sb_mb;
1364 nextrecord = m->m_nextpkt;
1368 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1369 if (m != NULL && pr->pr_flags & PR_ATOMIC) {
1371 if ((flags & MSG_PEEK) == 0)
1372 (void) sbdroprecord_locked(&so->so_rcv);
1374 if ((flags & MSG_PEEK) == 0) {
1377 * First part is an inline SB_EMPTY_FIXUP(). Second
1378 * part makes sure sb_lastrecord is up-to-date if
1379 * there is still data in the socket buffer.
1381 so->so_rcv.sb_mb = nextrecord;
1382 if (so->so_rcv.sb_mb == NULL) {
1383 so->so_rcv.sb_mbtail = NULL;
1384 so->so_rcv.sb_lastrecord = NULL;
1385 } else if (nextrecord->m_nextpkt == NULL)
1386 so->so_rcv.sb_lastrecord = nextrecord;
1388 SBLASTRECORDCHK(&so->so_rcv);
1389 SBLASTMBUFCHK(&so->so_rcv);
1391 * If soreceive() is being done from the socket callback, then
1392 * don't need to generate ACK to peer to update window, since
1393 * ACK will be generated on return to TCP.
1395 if (!(flags & MSG_SOCALLBCK) &&
1396 (pr->pr_flags & PR_WANTRCVD) && so->so_pcb) {
1397 SOCKBUF_UNLOCK(&so->so_rcv);
1398 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1399 SOCKBUF_LOCK(&so->so_rcv);
1402 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1403 if (orig_resid == uio->uio_resid && orig_resid &&
1404 (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
1405 sbunlock(&so->so_rcv);
1412 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1413 sbunlock(&so->so_rcv);
1415 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1416 SOCKBUF_UNLOCK(&so->so_rcv);
1425 struct protosw *pr = so->so_proto;
1427 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1433 return ((*pr->pr_usrreqs->pru_shutdown)(so));
1441 struct sockbuf *sb = &so->so_rcv;
1442 struct protosw *pr = so->so_proto;
1446 * XXXRW: This is quite ugly. Previously, this code made a copy of
1447 * the socket buffer, then zero'd the original to clear the buffer
1448 * fields. However, with mutexes in the socket buffer, this causes
1449 * problems. We only clear the zeroable bits of the original;
1450 * however, we have to initialize and destroy the mutex in the copy
1451 * so that dom_dispose() and sbrelease() can lock t as needed.
1454 sb->sb_flags |= SB_NOINTR;
1455 (void) sblock(sb, M_WAITOK);
1457 * socantrcvmore_locked() drops the socket buffer mutex so that it
1458 * can safely perform wakeups. Re-acquire the mutex before
1461 socantrcvmore_locked(so);
1465 * Invalidate/clear most of the sockbuf structure, but leave
1466 * selinfo and mutex data unchanged.
1468 bzero(&asb, offsetof(struct sockbuf, sb_startzero));
1469 bcopy(&sb->sb_startzero, &asb.sb_startzero,
1470 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1471 bzero(&sb->sb_startzero,
1472 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1475 SOCKBUF_LOCK_INIT(&asb, "so_rcv");
1476 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
1477 (*pr->pr_domain->dom_dispose)(asb.sb_mb);
1478 sbrelease(&asb, so);
1479 SOCKBUF_LOCK_DESTROY(&asb);
1483 * Perhaps this routine, and sooptcopyout(), below, ought to come in
1484 * an additional variant to handle the case where the option value needs
1485 * to be some kind of integer, but not a specific size.
1486 * In addition to their use here, these functions are also called by the
1487 * protocol-level pr_ctloutput() routines.
1490 sooptcopyin(sopt, buf, len, minlen)
1491 struct sockopt *sopt;
1499 * If the user gives us more than we wanted, we ignore it,
1500 * but if we don't get the minimum length the caller
1501 * wants, we return EINVAL. On success, sopt->sopt_valsize
1502 * is set to however much we actually retrieved.
1504 if ((valsize = sopt->sopt_valsize) < minlen)
1507 sopt->sopt_valsize = valsize = len;
1509 if (sopt->sopt_td != NULL)
1510 return (copyin(sopt->sopt_val, buf, valsize));
1512 bcopy(sopt->sopt_val, buf, valsize);
1517 * Kernel version of setsockopt(2)/
1518 * XXX: optlen is size_t, not socklen_t
1521 so_setsockopt(struct socket *so, int level, int optname, void *optval,
1524 struct sockopt sopt;
1526 sopt.sopt_level = level;
1527 sopt.sopt_name = optname;
1528 sopt.sopt_dir = SOPT_SET;
1529 sopt.sopt_val = optval;
1530 sopt.sopt_valsize = optlen;
1531 sopt.sopt_td = NULL;
1532 return (sosetopt(so, &sopt));
1538 struct sockopt *sopt;
1549 if (sopt->sopt_level != SOL_SOCKET) {
1550 if (so->so_proto && so->so_proto->pr_ctloutput)
1551 return ((*so->so_proto->pr_ctloutput)
1553 error = ENOPROTOOPT;
1555 switch (sopt->sopt_name) {
1557 case SO_ACCEPTFILTER:
1558 error = do_setopt_accept_filter(so, sopt);
1564 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1569 so->so_linger = l.l_linger;
1571 so->so_options |= SO_LINGER;
1573 so->so_options &= ~SO_LINGER;
1580 case SO_USELOOPBACK:
1588 error = sooptcopyin(sopt, &optval, sizeof optval,
1594 so->so_options |= sopt->sopt_name;
1596 so->so_options &= ~sopt->sopt_name;
1604 error = sooptcopyin(sopt, &optval, sizeof optval,
1610 * Values < 1 make no sense for any of these
1611 * options, so disallow them.
1618 switch (sopt->sopt_name) {
1621 if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
1622 &so->so_snd : &so->so_rcv, (u_long)optval,
1623 so, curthread) == 0) {
1630 * Make sure the low-water is never greater than
1634 SOCKBUF_LOCK(&so->so_snd);
1635 so->so_snd.sb_lowat =
1636 (optval > so->so_snd.sb_hiwat) ?
1637 so->so_snd.sb_hiwat : optval;
1638 SOCKBUF_UNLOCK(&so->so_snd);
1641 SOCKBUF_LOCK(&so->so_rcv);
1642 so->so_rcv.sb_lowat =
1643 (optval > so->so_rcv.sb_hiwat) ?
1644 so->so_rcv.sb_hiwat : optval;
1645 SOCKBUF_UNLOCK(&so->so_rcv);
1652 error = sooptcopyin(sopt, &tv, sizeof tv,
1657 /* assert(hz > 0); */
1658 if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
1659 tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1663 /* assert(tick > 0); */
1664 /* assert(ULONG_MAX - INT_MAX >= 1000000); */
1665 val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
1666 if (val > INT_MAX) {
1670 if (val == 0 && tv.tv_usec != 0)
1673 switch (sopt->sopt_name) {
1675 so->so_snd.sb_timeo = val;
1678 so->so_rcv.sb_timeo = val;
1684 error = sooptcopyin(sopt, &extmac, sizeof extmac,
1688 error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
1695 error = ENOPROTOOPT;
1698 if (error == 0 && so->so_proto != NULL &&
1699 so->so_proto->pr_ctloutput != NULL) {
1700 (void) ((*so->so_proto->pr_ctloutput)
1708 /* Helper routine for getsockopt */
1710 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
1718 * Documented get behavior is that we always return a value,
1719 * possibly truncated to fit in the user's buffer.
1720 * Traditional behavior is that we always tell the user
1721 * precisely how much we copied, rather than something useful
1722 * like the total amount we had available for her.
1723 * Note that this interface is not idempotent; the entire answer must
1724 * generated ahead of time.
1726 valsize = min(len, sopt->sopt_valsize);
1727 sopt->sopt_valsize = valsize;
1728 if (sopt->sopt_val != NULL) {
1729 if (sopt->sopt_td != NULL)
1730 error = copyout(buf, sopt->sopt_val, valsize);
1732 bcopy(buf, sopt->sopt_val, valsize);
1740 struct sockopt *sopt;
1750 if (sopt->sopt_level != SOL_SOCKET) {
1751 if (so->so_proto && so->so_proto->pr_ctloutput) {
1752 return ((*so->so_proto->pr_ctloutput)
1755 return (ENOPROTOOPT);
1757 switch (sopt->sopt_name) {
1759 case SO_ACCEPTFILTER:
1760 error = do_getopt_accept_filter(so, sopt);
1765 l.l_onoff = so->so_options & SO_LINGER;
1766 l.l_linger = so->so_linger;
1768 error = sooptcopyout(sopt, &l, sizeof l);
1771 case SO_USELOOPBACK:
1782 optval = so->so_options & sopt->sopt_name;
1784 error = sooptcopyout(sopt, &optval, sizeof optval);
1788 optval = so->so_type;
1792 optval = so->so_error;
1797 optval = so->so_snd.sb_hiwat;
1801 optval = so->so_rcv.sb_hiwat;
1805 optval = so->so_snd.sb_lowat;
1809 optval = so->so_rcv.sb_lowat;
1814 optval = (sopt->sopt_name == SO_SNDTIMEO ?
1815 so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1817 tv.tv_sec = optval / hz;
1818 tv.tv_usec = (optval % hz) * tick;
1819 error = sooptcopyout(sopt, &tv, sizeof tv);
1823 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
1827 error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
1831 error = sooptcopyout(sopt, &extmac, sizeof extmac);
1838 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
1842 error = mac_getsockopt_peerlabel(
1843 sopt->sopt_td->td_ucred, so, &extmac);
1846 error = sooptcopyout(sopt, &extmac, sizeof extmac);
1852 error = ENOPROTOOPT;
1859 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
1861 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
1863 struct mbuf *m, *m_prev;
1864 int sopt_size = sopt->sopt_valsize;
1866 MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
1869 if (sopt_size > MLEN) {
1870 MCLGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT);
1871 if ((m->m_flags & M_EXT) == 0) {
1875 m->m_len = min(MCLBYTES, sopt_size);
1877 m->m_len = min(MLEN, sopt_size);
1879 sopt_size -= m->m_len;
1884 MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
1889 if (sopt_size > MLEN) {
1890 MCLGET(m, sopt->sopt_td != NULL ? M_TRYWAIT :
1892 if ((m->m_flags & M_EXT) == 0) {
1897 m->m_len = min(MCLBYTES, sopt_size);
1899 m->m_len = min(MLEN, sopt_size);
1901 sopt_size -= m->m_len;
1908 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
1910 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
1912 struct mbuf *m0 = m;
1914 if (sopt->sopt_val == NULL)
1916 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
1917 if (sopt->sopt_td != NULL) {
1920 error = copyin(sopt->sopt_val, mtod(m, char *),
1927 bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
1928 sopt->sopt_valsize -= m->m_len;
1929 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
1932 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
1933 panic("ip6_sooptmcopyin");
1937 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
1939 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
1941 struct mbuf *m0 = m;
1944 if (sopt->sopt_val == NULL)
1946 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
1947 if (sopt->sopt_td != NULL) {
1950 error = copyout(mtod(m, char *), sopt->sopt_val,
1957 bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
1958 sopt->sopt_valsize -= m->m_len;
1959 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
1960 valsize += m->m_len;
1964 /* enough soopt buffer should be given from user-land */
1968 sopt->sopt_valsize = valsize;
1976 if (so->so_sigio != NULL)
1977 pgsigio(&so->so_sigio, SIGURG, 0);
1978 selwakeuppri(&so->so_rcv.sb_sel, PSOCK);
1982 sopoll(struct socket *so, int events, struct ucred *active_cred,
1987 SOCKBUF_LOCK(&so->so_snd);
1988 SOCKBUF_LOCK(&so->so_rcv);
1989 if (events & (POLLIN | POLLRDNORM))
1991 revents |= events & (POLLIN | POLLRDNORM);
1993 if (events & POLLINIGNEOF)
1994 if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
1995 !TAILQ_EMPTY(&so->so_comp) || so->so_error)
1996 revents |= POLLINIGNEOF;
1998 if (events & (POLLOUT | POLLWRNORM))
1999 if (sowriteable(so))
2000 revents |= events & (POLLOUT | POLLWRNORM);
2002 if (events & (POLLPRI | POLLRDBAND))
2003 if (so->so_oobmark || (so->so_rcv.sb_state & SBS_RCVATMARK))
2004 revents |= events & (POLLPRI | POLLRDBAND);
2008 (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
2010 selrecord(td, &so->so_rcv.sb_sel);
2011 so->so_rcv.sb_flags |= SB_SEL;
2014 if (events & (POLLOUT | POLLWRNORM)) {
2015 selrecord(td, &so->so_snd.sb_sel);
2016 so->so_snd.sb_flags |= SB_SEL;
2020 SOCKBUF_UNLOCK(&so->so_rcv);
2021 SOCKBUF_UNLOCK(&so->so_snd);
2026 soo_kqfilter(struct file *fp, struct knote *kn)
2028 struct socket *so = kn->kn_fp->f_data;
2031 switch (kn->kn_filter) {
2033 if (so->so_options & SO_ACCEPTCONN)
2034 kn->kn_fop = &solisten_filtops;
2036 kn->kn_fop = &soread_filtops;
2040 kn->kn_fop = &sowrite_filtops;
2048 knlist_add(&sb->sb_sel.si_note, kn, 1);
2049 sb->sb_flags |= SB_KNOTE;
2055 filt_sordetach(struct knote *kn)
2057 struct socket *so = kn->kn_fp->f_data;
2059 SOCKBUF_LOCK(&so->so_rcv);
2060 knlist_remove(&so->so_rcv.sb_sel.si_note, kn, 1);
2061 if (knlist_empty(&so->so_rcv.sb_sel.si_note))
2062 so->so_rcv.sb_flags &= ~SB_KNOTE;
2063 SOCKBUF_UNLOCK(&so->so_rcv);
2068 filt_soread(struct knote *kn, long hint)
2072 so = kn->kn_fp->f_data;
2073 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2075 kn->kn_data = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
2076 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2077 kn->kn_flags |= EV_EOF;
2078 kn->kn_fflags = so->so_error;
2080 } else if (so->so_error) /* temporary udp error */
2082 else if (kn->kn_sfflags & NOTE_LOWAT)
2083 return (kn->kn_data >= kn->kn_sdata);
2085 return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat);
2089 filt_sowdetach(struct knote *kn)
2091 struct socket *so = kn->kn_fp->f_data;
2093 SOCKBUF_LOCK(&so->so_snd);
2094 knlist_remove(&so->so_snd.sb_sel.si_note, kn, 1);
2095 if (knlist_empty(&so->so_snd.sb_sel.si_note))
2096 so->so_snd.sb_flags &= ~SB_KNOTE;
2097 SOCKBUF_UNLOCK(&so->so_snd);
2102 filt_sowrite(struct knote *kn, long hint)
2106 so = kn->kn_fp->f_data;
2107 SOCKBUF_LOCK_ASSERT(&so->so_snd);
2108 kn->kn_data = sbspace(&so->so_snd);
2109 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2110 kn->kn_flags |= EV_EOF;
2111 kn->kn_fflags = so->so_error;
2113 } else if (so->so_error) /* temporary udp error */
2115 else if (((so->so_state & SS_ISCONNECTED) == 0) &&
2116 (so->so_proto->pr_flags & PR_CONNREQUIRED))
2118 else if (kn->kn_sfflags & NOTE_LOWAT)
2119 return (kn->kn_data >= kn->kn_sdata);
2121 return (kn->kn_data >= so->so_snd.sb_lowat);
2126 filt_solisten(struct knote *kn, long hint)
2128 struct socket *so = kn->kn_fp->f_data;
2130 kn->kn_data = so->so_qlen;
2131 return (! TAILQ_EMPTY(&so->so_comp));
2135 socheckuid(struct socket *so, uid_t uid)
2140 if (so->so_cred->cr_uid != uid)
2146 somaxconn_sysctl(SYSCTL_HANDLER_ARGS)
2152 error = sysctl_handle_int(oidp, &val, sizeof(int), req);
2153 if (error || !req->newptr )
2156 if (val < 1 || val > USHRT_MAX)