2 * Copyright (c) 1982, 1986, 1988, 1990, 1993
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 2004 The FreeBSD Foundation
5 * Copyright (c) 2004-2006 Robert N. M. Watson
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
35 * Comments on the socket life cycle:
37 * soalloc() sets of socket layer state for a socket, called only by
38 * socreate() and sonewconn(). Socket layer private.
40 * sdealloc() tears down socket layer state for a socket, called only by
41 * sofree() and sonewconn(). Socket layer private.
43 * pru_attach() associates protocol layer state with an allocated socket;
44 * called only once, may fail, aborting socket allocation. This is called
45 * from socreate() and sonewconn(). Socket layer private.
47 * pru_detach() disassociates protocol layer state from an attached socket,
48 * and will be called exactly once for sockets in which pru_attach() has
49 * been successfully called. If pru_attach() returned an error,
50 * pru_detach() will not be called. Socket layer private.
52 * socreate() creates a socket and attaches protocol state. This is a public
53 * interface that may be used by socket layer consumers to create new
56 * sonewconn() creates a socket and attaches protocol state. This is a
57 * public interface that may be used by protocols to create new sockets when
58 * a new connection is received and will be available for accept() on a
61 * soclose() destroys a socket after possibly waiting for it to disconnect.
62 * This is a public interface that socket consumers should use to close and
63 * release a socket when done with it.
65 * soabort() destroys a socket without waiting for it to disconnect (used
66 * only for incoming connections that are already partially or fully
67 * connected). This is used internally by the socket layer when clearing
68 * listen socket queues (due to overflow or close on the listen socket), but
69 * is also a public interface protocols may use to abort connections in
70 * their incomplete listen queues should they no longer be required. Sockets
71 * placed in completed connection listen queues should not be aborted.
73 * sofree() will free a socket and its protocol state if all references on
74 * the socket have been released, and is the public interface to attempt to
75 * free a socket when a reference is removed. This is a socket layer private
78 * NOTE: In addition to socreate() and soclose(), which provide a single
79 * socket reference to the consumer to be managed as required, there are two
80 * calls to explicitly manage socket references, soref(), and sorele().
81 * Currently, these are generally required only when transitioning a socket
82 * from a listen queue to a file descriptor, in order to prevent garbage
83 * collection of the socket at an untimely moment. For a number of reasons,
84 * these interfaces are not preferred, and should be avoided.
86 * XXXRW: The behavior of sockets after soclose() but before the last
87 * sorele() is poorly defined. We can probably entirely eliminate them with
88 * a little work, since consumers are managing references anyway.
91 #include <sys/cdefs.h>
92 __FBSDID("$FreeBSD$");
97 #include "opt_compat.h"
99 #include <sys/param.h>
100 #include <sys/systm.h>
101 #include <sys/fcntl.h>
102 #include <sys/limits.h>
103 #include <sys/lock.h>
105 #include <sys/malloc.h>
106 #include <sys/mbuf.h>
107 #include <sys/mutex.h>
108 #include <sys/domain.h>
109 #include <sys/file.h> /* for struct knote */
110 #include <sys/kernel.h>
111 #include <sys/event.h>
112 #include <sys/poll.h>
113 #include <sys/proc.h>
114 #include <sys/protosw.h>
115 #include <sys/socket.h>
116 #include <sys/socketvar.h>
117 #include <sys/resourcevar.h>
118 #include <sys/signalvar.h>
119 #include <sys/sysctl.h>
121 #include <sys/jail.h>
126 #include <sys/mount.h>
127 #include <compat/freebsd32/freebsd32.h>
129 extern struct sysentvec ia32_freebsd_sysvec;
132 static int soreceive_rcvoob(struct socket *so, struct uio *uio,
135 static void filt_sordetach(struct knote *kn);
136 static int filt_soread(struct knote *kn, long hint);
137 static void filt_sowdetach(struct knote *kn);
138 static int filt_sowrite(struct knote *kn, long hint);
139 static int filt_solisten(struct knote *kn, long hint);
141 static struct filterops solisten_filtops =
142 { 1, NULL, filt_sordetach, filt_solisten };
143 static struct filterops soread_filtops =
144 { 1, NULL, filt_sordetach, filt_soread };
145 static struct filterops sowrite_filtops =
146 { 1, NULL, filt_sowdetach, filt_sowrite };
148 uma_zone_t socket_zone;
149 so_gen_t so_gencnt; /* generation count for sockets */
151 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
152 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
154 SYSCTL_DECL(_kern_ipc);
156 static int somaxconn = SOMAXCONN;
157 static int somaxconn_sysctl(SYSCTL_HANDLER_ARGS);
158 /* XXX: we dont have SYSCTL_USHORT */
159 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLTYPE_UINT | CTLFLAG_RW,
160 0, sizeof(int), somaxconn_sysctl, "I", "Maximum pending socket connection "
162 static int numopensockets;
163 SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
164 &numopensockets, 0, "Number of open sockets");
165 #ifdef ZERO_COPY_SOCKETS
166 /* These aren't static because they're used in other files. */
167 int so_zero_copy_send = 1;
168 int so_zero_copy_receive = 1;
169 SYSCTL_NODE(_kern_ipc, OID_AUTO, zero_copy, CTLFLAG_RD, 0,
170 "Zero copy controls");
171 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, receive, CTLFLAG_RW,
172 &so_zero_copy_receive, 0, "Enable zero copy receive");
173 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, send, CTLFLAG_RW,
174 &so_zero_copy_send, 0, "Enable zero copy send");
175 #endif /* ZERO_COPY_SOCKETS */
178 * accept_mtx locks down per-socket fields relating to accept queues. See
179 * socketvar.h for an annotation of the protected fields of struct socket.
181 struct mtx accept_mtx;
182 MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
185 * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
188 static struct mtx so_global_mtx;
189 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
192 * Socket operation routines.
193 * These routines are called by the routines in
194 * sys_socket.c or from a system process, and
195 * implement the semantics of socket operations by
196 * switching out to the protocol specific routines.
200 * Get a socket structure from our zone, and initialize it.
201 * Note that it would probably be better to allocate socket
202 * and PCB at the same time, but I'm not convinced that all
203 * the protocols can be easily modified to do this.
205 * soalloc() returns a socket with a ref count of 0.
212 so = uma_zalloc(socket_zone, mflags | M_ZERO);
215 if (mac_init_socket(so, mflags) != 0) {
216 uma_zfree(socket_zone, so);
220 SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
221 SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
222 TAILQ_INIT(&so->so_aiojobq);
223 mtx_lock(&so_global_mtx);
224 so->so_gencnt = ++so_gencnt;
226 mtx_unlock(&so_global_mtx);
232 * socreate returns a socket with a ref count of 1. The socket should be
233 * closed with soclose().
236 socreate(dom, aso, type, proto, cred, td)
249 prp = pffindproto(dom, proto, type);
251 prp = pffindtype(dom, type);
253 if (prp == NULL || prp->pr_usrreqs->pru_attach == NULL ||
254 prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
255 return (EPROTONOSUPPORT);
257 if (jailed(cred) && jail_socket_unixiproute_only &&
258 prp->pr_domain->dom_family != PF_LOCAL &&
259 prp->pr_domain->dom_family != PF_INET &&
260 prp->pr_domain->dom_family != PF_ROUTE) {
261 return (EPROTONOSUPPORT);
264 if (prp->pr_type != type)
266 so = soalloc(M_WAITOK);
270 TAILQ_INIT(&so->so_incomp);
271 TAILQ_INIT(&so->so_comp);
273 so->so_cred = crhold(cred);
276 mac_create_socket(cred, so);
278 knlist_init(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv),
280 knlist_init(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd),
283 error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
287 so->so_state |= SS_NOFDREF;
298 struct sockaddr *nam;
302 return ((*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td));
306 sodealloc(struct socket *so)
309 KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
310 KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
312 mtx_lock(&so_global_mtx);
313 so->so_gencnt = ++so_gencnt;
314 mtx_unlock(&so_global_mtx);
315 if (so->so_rcv.sb_hiwat)
316 (void)chgsbsize(so->so_cred->cr_uidinfo,
317 &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
318 if (so->so_snd.sb_hiwat)
319 (void)chgsbsize(so->so_cred->cr_uidinfo,
320 &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
322 /* remove acccept filter if one is present. */
323 if (so->so_accf != NULL)
324 do_setopt_accept_filter(so, NULL);
327 mac_destroy_socket(so);
330 SOCKBUF_LOCK_DESTROY(&so->so_snd);
331 SOCKBUF_LOCK_DESTROY(&so->so_rcv);
332 uma_zfree(socket_zone, so);
333 mtx_lock(&so_global_mtx);
335 mtx_unlock(&so_global_mtx);
339 * solisten() transitions a socket from a non-listening state to a listening
340 * state, but can also be used to update the listen queue depth on an
341 * existing listen socket. The protocol will call back into the sockets
342 * layer using solisten_proto_check() and solisten_proto() to check and set
343 * socket-layer listen state. Call backs are used so that the protocol can
344 * acquire both protocol and socket layer locks in whatever order is required
347 * Protocol implementors are advised to hold the socket lock across the
348 * socket-layer test and set to avoid races at the socket layer.
351 solisten(so, backlog, td)
357 return ((*so->so_proto->pr_usrreqs->pru_listen)(so, backlog, td));
361 solisten_proto_check(so)
365 SOCK_LOCK_ASSERT(so);
367 if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
374 solisten_proto(so, backlog)
379 SOCK_LOCK_ASSERT(so);
381 if (backlog < 0 || backlog > somaxconn)
383 so->so_qlimit = backlog;
384 so->so_options |= SO_ACCEPTCONN;
388 * Attempt to free a socket. This should really be sotryfree().
390 * sofree() will succeed if:
392 * - There are no outstanding file descriptor references or related consumers
395 * - The socket has been closed by user space, if ever open (SS_NOFDREF).
397 * - The protocol does not have an outstanding strong reference on the socket
400 * - The socket is not in a completed connection queue, so a process has been
401 * notified that it is present. If it is removed, the user process may
402 * block in accept() despite select() saying the socket was ready.
404 * Otherwise, it will quietly abort so that a future call to sofree(), when
405 * conditions are right, can succeed.
413 ACCEPT_LOCK_ASSERT();
414 SOCK_LOCK_ASSERT(so);
416 if ((so->so_state & SS_NOFDREF) == 0 || so->so_count != 0 ||
417 (so->so_state & SS_PROTOREF) || (so->so_qstate & SQ_COMP)) {
425 KASSERT((so->so_qstate & SQ_COMP) != 0 ||
426 (so->so_qstate & SQ_INCOMP) != 0,
427 ("sofree: so_head != NULL, but neither SQ_COMP nor "
429 KASSERT((so->so_qstate & SQ_COMP) == 0 ||
430 (so->so_qstate & SQ_INCOMP) == 0,
431 ("sofree: so->so_qstate is SQ_COMP and also SQ_INCOMP"));
432 TAILQ_REMOVE(&head->so_incomp, so, so_list);
434 so->so_qstate &= ~SQ_INCOMP;
437 KASSERT((so->so_qstate & SQ_COMP) == 0 &&
438 (so->so_qstate & SQ_INCOMP) == 0,
439 ("sofree: so_head == NULL, but still SQ_COMP(%d) or SQ_INCOMP(%d)",
440 so->so_qstate & SQ_COMP, so->so_qstate & SQ_INCOMP));
444 SOCKBUF_LOCK(&so->so_snd);
445 so->so_snd.sb_flags |= SB_NOINTR;
446 (void)sblock(&so->so_snd, M_WAITOK);
448 * socantsendmore_locked() drops the socket buffer mutex so that it
449 * can safely perform wakeups. Re-acquire the mutex before
452 socantsendmore_locked(so);
453 SOCKBUF_LOCK(&so->so_snd);
454 sbunlock(&so->so_snd);
455 sbrelease_locked(&so->so_snd, so);
456 SOCKBUF_UNLOCK(&so->so_snd);
458 knlist_destroy(&so->so_rcv.sb_sel.si_note);
459 knlist_destroy(&so->so_snd.sb_sel.si_note);
464 * Close a socket on last file table reference removal.
465 * Initiate disconnect if connected.
466 * Free socket when disconnect complete.
468 * This function will sorele() the socket. Note that soclose() may be
469 * called prior to the ref count reaching zero. The actual socket
470 * structure will not be freed until the ref count reaches zero.
478 KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
480 funsetown(&so->so_sigio);
481 if (so->so_options & SO_ACCEPTCONN) {
484 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
485 TAILQ_REMOVE(&so->so_incomp, sp, so_list);
487 sp->so_qstate &= ~SQ_INCOMP;
493 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
494 TAILQ_REMOVE(&so->so_comp, sp, so_list);
496 sp->so_qstate &= ~SQ_COMP;
504 if (so->so_state & SS_ISCONNECTED) {
505 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
506 error = sodisconnect(so);
510 if (so->so_options & SO_LINGER) {
511 if ((so->so_state & SS_ISDISCONNECTING) &&
512 (so->so_state & SS_NBIO))
514 while (so->so_state & SS_ISCONNECTED) {
515 error = tsleep(&so->so_timeo,
516 PSOCK | PCATCH, "soclos", so->so_linger * hz);
524 (*so->so_proto->pr_usrreqs->pru_detach)(so);
527 KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
528 so->so_state |= SS_NOFDREF;
534 * soabort() allows the socket code or protocol code to detach a socket that
535 * has been in an incomplete or completed listen queue, but has not yet been
538 * This interface is tricky, because it is called on an unreferenced socket,
539 * and must be called only by a thread that has actually removed the socket
540 * from the listen queue it was on, or races with other threads are risked.
542 * This interface will call into the protocol code, so must not be called
543 * with any socket locks held. Protocols do call it while holding their own
544 * recursible protocol mutexes, but this is something that should be subject
545 * to review in the future.
547 * XXXRW: Why do we maintain a distinction between pru_abort() and
556 * In as much as is possible, assert that no references to this
557 * socket are held. This is not quite the same as asserting that the
558 * current thread is responsible for arranging for no references, but
559 * is as close as we can get for now.
561 KASSERT(so->so_count == 0, ("soabort: so_count"));
562 KASSERT((so->so_state & SS_PROTOREF) == 0, ("soabort: SS_PROTOREF"));
563 KASSERT(so->so_state & SS_NOFDREF, ("soabort: !SS_NOFDREF"));
564 KASSERT((so->so_state & SQ_COMP) == 0, ("soabort: SQ_COMP"));
565 KASSERT((so->so_state & SQ_INCOMP) == 0, ("soabort: SQ_INCOMP"));
567 (*so->so_proto->pr_usrreqs->pru_abort)(so);
576 struct sockaddr **nam;
581 KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
582 so->so_state &= ~SS_NOFDREF;
584 error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
589 soconnect(so, nam, td)
591 struct sockaddr *nam;
596 if (so->so_options & SO_ACCEPTCONN)
599 * If protocol is connection-based, can only connect once.
600 * Otherwise, if connected, try to disconnect first.
601 * This allows user to disconnect by connecting to, e.g.,
604 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
605 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
606 (error = sodisconnect(so)))) {
610 * Prevent accumulated error from previous connection
614 error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, td);
626 return ((*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2));
635 if ((so->so_state & SS_ISCONNECTED) == 0)
637 if (so->so_state & SS_ISDISCONNECTING)
639 error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
643 #ifdef ZERO_COPY_SOCKETS
644 struct so_zerocopy_stats{
649 struct so_zerocopy_stats so_zerocp_stats = {0,0,0};
650 #include <netinet/in.h>
651 #include <net/route.h>
652 #include <netinet/in_pcb.h>
654 #include <vm/vm_page.h>
655 #include <vm/vm_object.h>
656 #endif /*ZERO_COPY_SOCKETS*/
659 * sosend_copyin() accepts a uio and prepares an mbuf chain holding part or
660 * all of the data referenced by the uio. If desired, it uses zero-copy.
661 * *space will be updated to reflect data copied in.
663 * NB: If atomic I/O is requested, the caller must already have checked that
664 * space can hold resid bytes.
666 * NB: In the event of an error, the caller may need to free the partial
667 * chain pointed to by *mpp. The contents of both *uio and *space may be
668 * modified even in the case of an error.
671 sosend_copyin(struct uio *uio, struct mbuf **retmp, int atomic, long *space,
674 struct mbuf *m, **mp, *top;
677 #ifdef ZERO_COPY_SOCKETS
684 resid = uio->uio_resid;
687 #ifdef ZERO_COPY_SOCKETS
689 #endif /* ZERO_COPY_SOCKETS */
690 if (resid >= MINCLSIZE) {
691 #ifdef ZERO_COPY_SOCKETS
693 MGETHDR(m, M_TRYWAIT, MT_DATA);
699 m->m_pkthdr.rcvif = NULL;
701 MGET(m, M_TRYWAIT, MT_DATA);
707 if (so_zero_copy_send &&
710 uio->uio_iov->iov_len>=PAGE_SIZE) {
711 so_zerocp_stats.size_ok++;
712 so_zerocp_stats.align_ok++;
713 cow_send = socow_setup(m, uio);
717 MCLGET(m, M_TRYWAIT);
718 if ((m->m_flags & M_EXT) == 0) {
722 len = min(min(MCLBYTES, resid),
726 #else /* ZERO_COPY_SOCKETS */
728 m = m_getcl(M_TRYWAIT, MT_DATA, M_PKTHDR);
730 m->m_pkthdr.rcvif = NULL;
732 m = m_getcl(M_TRYWAIT, MT_DATA, 0);
733 len = min(min(MCLBYTES, resid), *space);
734 #endif /* ZERO_COPY_SOCKETS */
737 m = m_gethdr(M_TRYWAIT, MT_DATA);
739 m->m_pkthdr.rcvif = NULL;
741 len = min(min(MHLEN, resid), *space);
743 * For datagram protocols, leave room
744 * for protocol headers in first mbuf.
746 if (atomic && m && len < MHLEN)
749 m = m_get(M_TRYWAIT, MT_DATA);
750 len = min(min(MLEN, resid), *space);
759 #ifdef ZERO_COPY_SOCKETS
763 #endif /* ZERO_COPY_SOCKETS */
764 error = uiomove(mtod(m, void *), (int)len, uio);
765 resid = uio->uio_resid;
768 top->m_pkthdr.len += len;
774 top->m_flags |= M_EOR;
777 } while (*space > 0 && atomic);
783 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
786 sosend_dgram(so, addr, uio, top, control, flags, td)
788 struct sockaddr *addr;
791 struct mbuf *control;
796 int clen = 0, error, dontroute;
797 int atomic = sosendallatonce(so) || top;
799 KASSERT(so->so_type == SOCK_DGRAM, ("sodgram_send: !SOCK_DGRAM"));
800 KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
801 ("sodgram_send: !PR_ATOMIC"));
804 resid = uio->uio_resid;
806 resid = top->m_pkthdr.len;
808 * In theory resid should be unsigned.
809 * However, space must be signed, as it might be less than 0
810 * if we over-committed, and we must use a signed comparison
811 * of space and resid. On the other hand, a negative resid
812 * causes us to loop sending 0-length segments to the protocol.
814 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
815 * type sockets since that's an error.
823 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
825 td->td_proc->p_stats->p_ru.ru_msgsnd++;
827 clen = control->m_len;
829 SOCKBUF_LOCK(&so->so_snd);
830 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
831 SOCKBUF_UNLOCK(&so->so_snd);
836 error = so->so_error;
838 SOCKBUF_UNLOCK(&so->so_snd);
841 if ((so->so_state & SS_ISCONNECTED) == 0) {
843 * `sendto' and `sendmsg' is allowed on a connection-
844 * based socket if it supports implied connect.
845 * Return ENOTCONN if not connected and no address is
848 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
849 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
850 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
851 !(resid == 0 && clen != 0)) {
852 SOCKBUF_UNLOCK(&so->so_snd);
856 } else if (addr == NULL) {
857 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
860 error = EDESTADDRREQ;
861 SOCKBUF_UNLOCK(&so->so_snd);
867 * Do we need MSG_OOB support in SOCK_DGRAM? Signs here may be a
868 * problem and need fixing.
870 space = sbspace(&so->so_snd);
878 SOCKBUF_UNLOCK(&so->so_snd);
882 top->m_flags |= M_EOR;
884 error = sosend_copyin(uio, &top, atomic, &space, flags);
887 resid = uio->uio_resid;
889 KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
891 * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
896 so->so_options |= SO_DONTROUTE;
900 * XXX all the SBS_CANTSENDMORE checks previously
901 * done could be out of date. We could have recieved
902 * a reset packet in an interrupt or maybe we slept
903 * while doing page faults in uiomove() etc. We could
904 * probably recheck again inside the locking protection
905 * here, but there are probably other places that this
906 * also happens. We must rethink this.
908 error = (*so->so_proto->pr_usrreqs->pru_send)(so,
909 (flags & MSG_OOB) ? PRUS_OOB :
911 * If the user set MSG_EOF, the protocol
912 * understands this flag and nothing left to
913 * send then use PRU_SEND_EOF instead of PRU_SEND.
915 ((flags & MSG_EOF) &&
916 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
919 /* If there is more to send set PRUS_MORETOCOME */
920 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
921 top, addr, control, td);
924 so->so_options &= ~SO_DONTROUTE;
940 * If send must go all at once and message is larger than
941 * send buffering, then hard error.
942 * Lock against other senders.
943 * If must go all at once and not enough room now, then
944 * inform user that this would block and do nothing.
945 * Otherwise, if nonblocking, send as much as possible.
946 * The data to be sent is described by "uio" if nonzero,
947 * otherwise by the mbuf chain "top" (which must be null
948 * if uio is not). Data provided in mbuf chain must be small
949 * enough to send all at once.
951 * Returns nonzero on error, timeout or signal; callers
952 * must check for short counts if EINTR/ERESTART are returned.
953 * Data and control buffers are freed on return.
955 #define snderr(errno) { error = (errno); goto release; }
957 sosend(so, addr, uio, top, control, flags, td)
959 struct sockaddr *addr;
962 struct mbuf *control;
967 int clen = 0, error, dontroute;
968 int atomic = sosendallatonce(so) || top;
971 resid = uio->uio_resid;
973 resid = top->m_pkthdr.len;
975 * In theory resid should be unsigned.
976 * However, space must be signed, as it might be less than 0
977 * if we over-committed, and we must use a signed comparison
978 * of space and resid. On the other hand, a negative resid
979 * causes us to loop sending 0-length segments to the protocol.
981 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
982 * type sockets since that's an error.
984 if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
990 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
991 (so->so_proto->pr_flags & PR_ATOMIC);
993 td->td_proc->p_stats->p_ru.ru_msgsnd++;
995 clen = control->m_len;
997 SOCKBUF_LOCK(&so->so_snd);
999 SOCKBUF_LOCK_ASSERT(&so->so_snd);
1000 error = sblock(&so->so_snd, SBLOCKWAIT(flags));
1004 SOCKBUF_LOCK_ASSERT(&so->so_snd);
1005 if (so->so_snd.sb_state & SBS_CANTSENDMORE)
1008 error = so->so_error;
1012 if ((so->so_state & SS_ISCONNECTED) == 0) {
1014 * `sendto' and `sendmsg' is allowed on a connection-
1015 * based socket if it supports implied connect.
1016 * Return ENOTCONN if not connected and no address is
1019 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1020 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1021 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1022 !(resid == 0 && clen != 0))
1024 } else if (addr == NULL)
1025 snderr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
1026 ENOTCONN : EDESTADDRREQ);
1028 space = sbspace(&so->so_snd);
1029 if (flags & MSG_OOB)
1031 if ((atomic && resid > so->so_snd.sb_hiwat) ||
1032 clen > so->so_snd.sb_hiwat)
1034 if (space < resid + clen &&
1035 (atomic || space < so->so_snd.sb_lowat || space < clen)) {
1036 if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO))
1037 snderr(EWOULDBLOCK);
1038 sbunlock(&so->so_snd);
1039 error = sbwait(&so->so_snd);
1044 SOCKBUF_UNLOCK(&so->so_snd);
1049 if (flags & MSG_EOR)
1050 top->m_flags |= M_EOR;
1052 error = sosend_copyin(uio, &top, atomic,
1055 SOCKBUF_LOCK(&so->so_snd);
1058 resid = uio->uio_resid;
1062 so->so_options |= SO_DONTROUTE;
1066 * XXX all the SBS_CANTSENDMORE checks previously
1067 * done could be out of date. We could have recieved
1068 * a reset packet in an interrupt or maybe we slept
1069 * while doing page faults in uiomove() etc. We could
1070 * probably recheck again inside the locking protection
1071 * here, but there are probably other places that this
1072 * also happens. We must rethink this.
1074 error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1075 (flags & MSG_OOB) ? PRUS_OOB :
1077 * If the user set MSG_EOF, the protocol
1078 * understands this flag and nothing left to
1079 * send then use PRU_SEND_EOF instead of PRU_SEND.
1081 ((flags & MSG_EOF) &&
1082 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1085 /* If there is more to send set PRUS_MORETOCOME */
1086 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1087 top, addr, control, td);
1090 so->so_options &= ~SO_DONTROUTE;
1097 SOCKBUF_LOCK(&so->so_snd);
1100 } while (resid && space > 0);
1101 SOCKBUF_LOCK(&so->so_snd);
1105 SOCKBUF_LOCK_ASSERT(&so->so_snd);
1106 sbunlock(&so->so_snd);
1108 SOCKBUF_LOCK_ASSERT(&so->so_snd);
1109 SOCKBUF_UNLOCK(&so->so_snd);
1113 if (control != NULL)
1120 * The part of soreceive() that implements reading non-inline out-of-band
1121 * data from a socket. For more complete comments, see soreceive(), from
1122 * which this code originated.
1124 * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
1125 * unable to return an mbuf chain to the caller.
1128 soreceive_rcvoob(so, uio, flags)
1133 struct protosw *pr = so->so_proto;
1137 KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
1139 m = m_get(M_TRYWAIT, MT_DATA);
1142 error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
1146 #ifdef ZERO_COPY_SOCKETS
1147 if (so_zero_copy_receive) {
1150 if ((m->m_flags & M_EXT)
1151 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1156 error = uiomoveco(mtod(m, void *),
1157 min(uio->uio_resid, m->m_len),
1160 #endif /* ZERO_COPY_SOCKETS */
1161 error = uiomove(mtod(m, void *),
1162 (int) min(uio->uio_resid, m->m_len), uio);
1164 } while (uio->uio_resid && error == 0 && m);
1172 * Following replacement or removal of the first mbuf on the first mbuf chain
1173 * of a socket buffer, push necessary state changes back into the socket
1174 * buffer so that other consumers see the values consistently. 'nextrecord'
1175 * is the callers locally stored value of the original value of
1176 * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
1177 * NOTE: 'nextrecord' may be NULL.
1179 static __inline void
1180 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
1183 SOCKBUF_LOCK_ASSERT(sb);
1185 * First, update for the new value of nextrecord. If necessary, make
1186 * it the first record.
1188 if (sb->sb_mb != NULL)
1189 sb->sb_mb->m_nextpkt = nextrecord;
1191 sb->sb_mb = nextrecord;
1194 * Now update any dependent socket buffer fields to reflect the new
1195 * state. This is an expanded inline of SB_EMPTY_FIXUP(), with the
1196 * addition of a second clause that takes care of the case where
1197 * sb_mb has been updated, but remains the last record.
1199 if (sb->sb_mb == NULL) {
1200 sb->sb_mbtail = NULL;
1201 sb->sb_lastrecord = NULL;
1202 } else if (sb->sb_mb->m_nextpkt == NULL)
1203 sb->sb_lastrecord = sb->sb_mb;
1208 * Implement receive operations on a socket.
1209 * We depend on the way that records are added to the sockbuf
1210 * by sbappend*. In particular, each record (mbufs linked through m_next)
1211 * must begin with an address if the protocol so specifies,
1212 * followed by an optional mbuf or mbufs containing ancillary data,
1213 * and then zero or more mbufs of data.
1214 * In order to avoid blocking network interrupts for the entire time here,
1215 * we splx() while doing the actual copy to user space.
1216 * Although the sockbuf is locked, new data may still be appended,
1217 * and thus we must maintain consistency of the sockbuf during that time.
1219 * The caller may receive the data as a single mbuf chain by supplying
1220 * an mbuf **mp0 for use in returning the chain. The uio is then used
1221 * only for the count in uio_resid.
1224 soreceive(so, psa, uio, mp0, controlp, flagsp)
1226 struct sockaddr **psa;
1229 struct mbuf **controlp;
1232 struct mbuf *m, **mp;
1233 int flags, len, error, offset;
1234 struct protosw *pr = so->so_proto;
1235 struct mbuf *nextrecord;
1237 int orig_resid = uio->uio_resid;
1242 if (controlp != NULL)
1245 flags = *flagsp &~ MSG_EOR;
1248 if (flags & MSG_OOB)
1249 return (soreceive_rcvoob(so, uio, flags));
1252 if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
1254 (*pr->pr_usrreqs->pru_rcvd)(so, 0);
1256 SOCKBUF_LOCK(&so->so_rcv);
1258 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1259 error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
1263 m = so->so_rcv.sb_mb;
1265 * If we have less data than requested, block awaiting more
1266 * (subject to any timeout) if:
1267 * 1. the current count is less than the low water mark, or
1268 * 2. MSG_WAITALL is set, and it is possible to do the entire
1269 * receive operation at once if we block (resid <= hiwat).
1270 * 3. MSG_DONTWAIT is not set
1271 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1272 * we have to do the receive in sections, and thus risk returning
1273 * a short count if a timeout or signal occurs after we start.
1275 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1276 so->so_rcv.sb_cc < uio->uio_resid) &&
1277 (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
1278 ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
1279 m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
1280 KASSERT(m != NULL || !so->so_rcv.sb_cc,
1281 ("receive: m == %p so->so_rcv.sb_cc == %u",
1282 m, so->so_rcv.sb_cc));
1286 error = so->so_error;
1287 if ((flags & MSG_PEEK) == 0)
1291 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1292 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1298 for (; m != NULL; m = m->m_next)
1299 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
1300 m = so->so_rcv.sb_mb;
1303 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1304 (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1308 if (uio->uio_resid == 0)
1310 if ((so->so_state & SS_NBIO) ||
1311 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1312 error = EWOULDBLOCK;
1315 SBLASTRECORDCHK(&so->so_rcv);
1316 SBLASTMBUFCHK(&so->so_rcv);
1317 sbunlock(&so->so_rcv);
1318 error = sbwait(&so->so_rcv);
1325 * From this point onward, we maintain 'nextrecord' as a cache of the
1326 * pointer to the next record in the socket buffer. We must keep the
1327 * various socket buffer pointers and local stack versions of the
1328 * pointers in sync, pushing out modifications before dropping the
1329 * socket buffer mutex, and re-reading them when picking it up.
1331 * Otherwise, we will race with the network stack appending new data
1332 * or records onto the socket buffer by using inconsistent/stale
1333 * versions of the field, possibly resulting in socket buffer
1336 * By holding the high-level sblock(), we prevent simultaneous
1337 * readers from pulling off the front of the socket buffer.
1339 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1341 uio->uio_td->td_proc->p_stats->p_ru.ru_msgrcv++;
1342 KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
1343 SBLASTRECORDCHK(&so->so_rcv);
1344 SBLASTMBUFCHK(&so->so_rcv);
1345 nextrecord = m->m_nextpkt;
1346 if (pr->pr_flags & PR_ADDR) {
1347 KASSERT(m->m_type == MT_SONAME,
1348 ("m->m_type == %d", m->m_type));
1351 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
1353 if (flags & MSG_PEEK) {
1356 sbfree(&so->so_rcv, m);
1357 so->so_rcv.sb_mb = m_free(m);
1358 m = so->so_rcv.sb_mb;
1359 sockbuf_pushsync(&so->so_rcv, nextrecord);
1364 * Process one or more MT_CONTROL mbufs present before any data mbufs
1365 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
1366 * just copy the data; if !MSG_PEEK, we call into the protocol to
1367 * perform externalization (or freeing if controlp == NULL).
1369 if (m != NULL && m->m_type == MT_CONTROL) {
1370 struct mbuf *cm = NULL, *cmn;
1371 struct mbuf **cme = &cm;
1374 if (flags & MSG_PEEK) {
1375 if (controlp != NULL) {
1376 *controlp = m_copy(m, 0, m->m_len);
1377 controlp = &(*controlp)->m_next;
1381 sbfree(&so->so_rcv, m);
1382 so->so_rcv.sb_mb = m->m_next;
1385 cme = &(*cme)->m_next;
1386 m = so->so_rcv.sb_mb;
1388 } while (m != NULL && m->m_type == MT_CONTROL);
1389 if ((flags & MSG_PEEK) == 0)
1390 sockbuf_pushsync(&so->so_rcv, nextrecord);
1391 while (cm != NULL) {
1394 if (pr->pr_domain->dom_externalize != NULL) {
1395 SOCKBUF_UNLOCK(&so->so_rcv);
1396 error = (*pr->pr_domain->dom_externalize)
1398 SOCKBUF_LOCK(&so->so_rcv);
1399 } else if (controlp != NULL)
1403 if (controlp != NULL) {
1405 while (*controlp != NULL)
1406 controlp = &(*controlp)->m_next;
1410 if (so->so_rcv.sb_mb)
1411 nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1417 if ((flags & MSG_PEEK) == 0) {
1418 KASSERT(m->m_nextpkt == nextrecord,
1419 ("soreceive: post-control, nextrecord !sync"));
1420 if (nextrecord == NULL) {
1421 KASSERT(so->so_rcv.sb_mb == m,
1422 ("soreceive: post-control, sb_mb!=m"));
1423 KASSERT(so->so_rcv.sb_lastrecord == m,
1424 ("soreceive: post-control, lastrecord!=m"));
1428 if (type == MT_OOBDATA)
1431 if ((flags & MSG_PEEK) == 0) {
1432 KASSERT(so->so_rcv.sb_mb == nextrecord,
1433 ("soreceive: sb_mb != nextrecord"));
1434 if (so->so_rcv.sb_mb == NULL) {
1435 KASSERT(so->so_rcv.sb_lastrecord == NULL,
1436 ("soreceive: sb_lastercord != NULL"));
1440 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1441 SBLASTRECORDCHK(&so->so_rcv);
1442 SBLASTMBUFCHK(&so->so_rcv);
1445 * Now continue to read any data mbufs off of the head of the socket
1446 * buffer until the read request is satisfied. Note that 'type' is
1447 * used to store the type of any mbuf reads that have happened so far
1448 * such that soreceive() can stop reading if the type changes, which
1449 * causes soreceive() to return only one of regular data and inline
1450 * out-of-band data in a single socket receive operation.
1454 while (m != NULL && uio->uio_resid > 0 && error == 0) {
1456 * If the type of mbuf has changed since the last mbuf
1457 * examined ('type'), end the receive operation.
1459 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1460 if (m->m_type == MT_OOBDATA) {
1461 if (type != MT_OOBDATA)
1463 } else if (type == MT_OOBDATA)
1466 KASSERT(m->m_type == MT_DATA,
1467 ("m->m_type == %d", m->m_type));
1468 so->so_rcv.sb_state &= ~SBS_RCVATMARK;
1469 len = uio->uio_resid;
1470 if (so->so_oobmark && len > so->so_oobmark - offset)
1471 len = so->so_oobmark - offset;
1472 if (len > m->m_len - moff)
1473 len = m->m_len - moff;
1475 * If mp is set, just pass back the mbufs.
1476 * Otherwise copy them out via the uio, then free.
1477 * Sockbuf must be consistent here (points to current mbuf,
1478 * it points to next record) when we drop priority;
1479 * we must note any additions to the sockbuf when we
1480 * block interrupts again.
1483 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1484 SBLASTRECORDCHK(&so->so_rcv);
1485 SBLASTMBUFCHK(&so->so_rcv);
1486 SOCKBUF_UNLOCK(&so->so_rcv);
1487 #ifdef ZERO_COPY_SOCKETS
1488 if (so_zero_copy_receive) {
1491 if ((m->m_flags & M_EXT)
1492 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1497 error = uiomoveco(mtod(m, char *) + moff,
1501 #endif /* ZERO_COPY_SOCKETS */
1502 error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1503 SOCKBUF_LOCK(&so->so_rcv);
1507 uio->uio_resid -= len;
1508 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1509 if (len == m->m_len - moff) {
1510 if (m->m_flags & M_EOR)
1512 if (flags & MSG_PEEK) {
1516 nextrecord = m->m_nextpkt;
1517 sbfree(&so->so_rcv, m);
1521 so->so_rcv.sb_mb = m = m->m_next;
1524 so->so_rcv.sb_mb = m_free(m);
1525 m = so->so_rcv.sb_mb;
1527 sockbuf_pushsync(&so->so_rcv, nextrecord);
1528 SBLASTRECORDCHK(&so->so_rcv);
1529 SBLASTMBUFCHK(&so->so_rcv);
1532 if (flags & MSG_PEEK)
1538 if (flags & MSG_DONTWAIT)
1539 copy_flag = M_DONTWAIT;
1541 copy_flag = M_TRYWAIT;
1542 if (copy_flag == M_TRYWAIT)
1543 SOCKBUF_UNLOCK(&so->so_rcv);
1544 *mp = m_copym(m, 0, len, copy_flag);
1545 if (copy_flag == M_TRYWAIT)
1546 SOCKBUF_LOCK(&so->so_rcv);
1549 * m_copym() couldn't allocate an mbuf.
1550 * Adjust uio_resid back (it was adjusted
1551 * down by len bytes, which we didn't end
1552 * up "copying" over).
1554 uio->uio_resid += len;
1560 so->so_rcv.sb_cc -= len;
1563 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1564 if (so->so_oobmark) {
1565 if ((flags & MSG_PEEK) == 0) {
1566 so->so_oobmark -= len;
1567 if (so->so_oobmark == 0) {
1568 so->so_rcv.sb_state |= SBS_RCVATMARK;
1573 if (offset == so->so_oobmark)
1577 if (flags & MSG_EOR)
1580 * If the MSG_WAITALL flag is set (for non-atomic socket),
1581 * we must not quit until "uio->uio_resid == 0" or an error
1582 * termination. If a signal/timeout occurs, return
1583 * with a short count but without error.
1584 * Keep sockbuf locked against other readers.
1586 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1587 !sosendallatonce(so) && nextrecord == NULL) {
1588 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1589 if (so->so_error || so->so_rcv.sb_state & SBS_CANTRCVMORE)
1592 * Notify the protocol that some data has been
1593 * drained before blocking.
1595 if (pr->pr_flags & PR_WANTRCVD) {
1596 SOCKBUF_UNLOCK(&so->so_rcv);
1597 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1598 SOCKBUF_LOCK(&so->so_rcv);
1600 SBLASTRECORDCHK(&so->so_rcv);
1601 SBLASTMBUFCHK(&so->so_rcv);
1602 error = sbwait(&so->so_rcv);
1605 m = so->so_rcv.sb_mb;
1607 nextrecord = m->m_nextpkt;
1611 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1612 if (m != NULL && pr->pr_flags & PR_ATOMIC) {
1614 if ((flags & MSG_PEEK) == 0)
1615 (void) sbdroprecord_locked(&so->so_rcv);
1617 if ((flags & MSG_PEEK) == 0) {
1620 * First part is an inline SB_EMPTY_FIXUP(). Second
1621 * part makes sure sb_lastrecord is up-to-date if
1622 * there is still data in the socket buffer.
1624 so->so_rcv.sb_mb = nextrecord;
1625 if (so->so_rcv.sb_mb == NULL) {
1626 so->so_rcv.sb_mbtail = NULL;
1627 so->so_rcv.sb_lastrecord = NULL;
1628 } else if (nextrecord->m_nextpkt == NULL)
1629 so->so_rcv.sb_lastrecord = nextrecord;
1631 SBLASTRECORDCHK(&so->so_rcv);
1632 SBLASTMBUFCHK(&so->so_rcv);
1634 * If soreceive() is being done from the socket callback, then
1635 * don't need to generate ACK to peer to update window, since
1636 * ACK will be generated on return to TCP.
1638 if (!(flags & MSG_SOCALLBCK) &&
1639 (pr->pr_flags & PR_WANTRCVD)) {
1640 SOCKBUF_UNLOCK(&so->so_rcv);
1641 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1642 SOCKBUF_LOCK(&so->so_rcv);
1645 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1646 if (orig_resid == uio->uio_resid && orig_resid &&
1647 (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
1648 sbunlock(&so->so_rcv);
1655 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1656 sbunlock(&so->so_rcv);
1658 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1659 SOCKBUF_UNLOCK(&so->so_rcv);
1668 struct protosw *pr = so->so_proto;
1670 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1676 return ((*pr->pr_usrreqs->pru_shutdown)(so));
1684 struct sockbuf *sb = &so->so_rcv;
1685 struct protosw *pr = so->so_proto;
1689 * XXXRW: This is quite ugly. Previously, this code made a copy of
1690 * the socket buffer, then zero'd the original to clear the buffer
1691 * fields. However, with mutexes in the socket buffer, this causes
1692 * problems. We only clear the zeroable bits of the original;
1693 * however, we have to initialize and destroy the mutex in the copy
1694 * so that dom_dispose() and sbrelease() can lock t as needed.
1697 sb->sb_flags |= SB_NOINTR;
1698 (void) sblock(sb, M_WAITOK);
1700 * socantrcvmore_locked() drops the socket buffer mutex so that it
1701 * can safely perform wakeups. Re-acquire the mutex before
1704 socantrcvmore_locked(so);
1708 * Invalidate/clear most of the sockbuf structure, but leave
1709 * selinfo and mutex data unchanged.
1711 bzero(&asb, offsetof(struct sockbuf, sb_startzero));
1712 bcopy(&sb->sb_startzero, &asb.sb_startzero,
1713 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1714 bzero(&sb->sb_startzero,
1715 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
1718 SOCKBUF_LOCK_INIT(&asb, "so_rcv");
1719 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
1720 (*pr->pr_domain->dom_dispose)(asb.sb_mb);
1721 sbrelease(&asb, so);
1722 SOCKBUF_LOCK_DESTROY(&asb);
1726 * Perhaps this routine, and sooptcopyout(), below, ought to come in
1727 * an additional variant to handle the case where the option value needs
1728 * to be some kind of integer, but not a specific size.
1729 * In addition to their use here, these functions are also called by the
1730 * protocol-level pr_ctloutput() routines.
1733 sooptcopyin(sopt, buf, len, minlen)
1734 struct sockopt *sopt;
1742 * If the user gives us more than we wanted, we ignore it,
1743 * but if we don't get the minimum length the caller
1744 * wants, we return EINVAL. On success, sopt->sopt_valsize
1745 * is set to however much we actually retrieved.
1747 if ((valsize = sopt->sopt_valsize) < minlen)
1750 sopt->sopt_valsize = valsize = len;
1752 if (sopt->sopt_td != NULL)
1753 return (copyin(sopt->sopt_val, buf, valsize));
1755 bcopy(sopt->sopt_val, buf, valsize);
1760 * Kernel version of setsockopt(2)/
1761 * XXX: optlen is size_t, not socklen_t
1764 so_setsockopt(struct socket *so, int level, int optname, void *optval,
1767 struct sockopt sopt;
1769 sopt.sopt_level = level;
1770 sopt.sopt_name = optname;
1771 sopt.sopt_dir = SOPT_SET;
1772 sopt.sopt_val = optval;
1773 sopt.sopt_valsize = optlen;
1774 sopt.sopt_td = NULL;
1775 return (sosetopt(so, &sopt));
1781 struct sockopt *sopt;
1792 if (sopt->sopt_level != SOL_SOCKET) {
1793 if (so->so_proto && so->so_proto->pr_ctloutput)
1794 return ((*so->so_proto->pr_ctloutput)
1796 error = ENOPROTOOPT;
1798 switch (sopt->sopt_name) {
1800 case SO_ACCEPTFILTER:
1801 error = do_setopt_accept_filter(so, sopt);
1807 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1812 so->so_linger = l.l_linger;
1814 so->so_options |= SO_LINGER;
1816 so->so_options &= ~SO_LINGER;
1823 case SO_USELOOPBACK:
1831 error = sooptcopyin(sopt, &optval, sizeof optval,
1837 so->so_options |= sopt->sopt_name;
1839 so->so_options &= ~sopt->sopt_name;
1847 error = sooptcopyin(sopt, &optval, sizeof optval,
1853 * Values < 1 make no sense for any of these
1854 * options, so disallow them.
1861 switch (sopt->sopt_name) {
1864 if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
1865 &so->so_snd : &so->so_rcv, (u_long)optval,
1866 so, curthread) == 0) {
1873 * Make sure the low-water is never greater than
1877 SOCKBUF_LOCK(&so->so_snd);
1878 so->so_snd.sb_lowat =
1879 (optval > so->so_snd.sb_hiwat) ?
1880 so->so_snd.sb_hiwat : optval;
1881 SOCKBUF_UNLOCK(&so->so_snd);
1884 SOCKBUF_LOCK(&so->so_rcv);
1885 so->so_rcv.sb_lowat =
1886 (optval > so->so_rcv.sb_hiwat) ?
1887 so->so_rcv.sb_hiwat : optval;
1888 SOCKBUF_UNLOCK(&so->so_rcv);
1896 if (curthread->td_proc->p_sysent == &ia32_freebsd_sysvec) {
1897 struct timeval32 tv32;
1899 error = sooptcopyin(sopt, &tv32, sizeof tv32,
1901 CP(tv32, tv, tv_sec);
1902 CP(tv32, tv, tv_usec);
1905 error = sooptcopyin(sopt, &tv, sizeof tv,
1910 /* assert(hz > 0); */
1911 if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
1912 tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1916 /* assert(tick > 0); */
1917 /* assert(ULONG_MAX - INT_MAX >= 1000000); */
1918 val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
1919 if (val > INT_MAX) {
1923 if (val == 0 && tv.tv_usec != 0)
1926 switch (sopt->sopt_name) {
1928 so->so_snd.sb_timeo = val;
1931 so->so_rcv.sb_timeo = val;
1938 error = sooptcopyin(sopt, &extmac, sizeof extmac,
1942 error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
1950 error = ENOPROTOOPT;
1953 if (error == 0 && so->so_proto != NULL &&
1954 so->so_proto->pr_ctloutput != NULL) {
1955 (void) ((*so->so_proto->pr_ctloutput)
1963 /* Helper routine for getsockopt */
1965 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
1973 * Documented get behavior is that we always return a value,
1974 * possibly truncated to fit in the user's buffer.
1975 * Traditional behavior is that we always tell the user
1976 * precisely how much we copied, rather than something useful
1977 * like the total amount we had available for her.
1978 * Note that this interface is not idempotent; the entire answer must
1979 * generated ahead of time.
1981 valsize = min(len, sopt->sopt_valsize);
1982 sopt->sopt_valsize = valsize;
1983 if (sopt->sopt_val != NULL) {
1984 if (sopt->sopt_td != NULL)
1985 error = copyout(buf, sopt->sopt_val, valsize);
1987 bcopy(buf, sopt->sopt_val, valsize);
1995 struct sockopt *sopt;
2005 if (sopt->sopt_level != SOL_SOCKET) {
2006 if (so->so_proto && so->so_proto->pr_ctloutput) {
2007 return ((*so->so_proto->pr_ctloutput)
2010 return (ENOPROTOOPT);
2012 switch (sopt->sopt_name) {
2014 case SO_ACCEPTFILTER:
2015 error = do_getopt_accept_filter(so, sopt);
2020 l.l_onoff = so->so_options & SO_LINGER;
2021 l.l_linger = so->so_linger;
2023 error = sooptcopyout(sopt, &l, sizeof l);
2026 case SO_USELOOPBACK:
2038 optval = so->so_options & sopt->sopt_name;
2040 error = sooptcopyout(sopt, &optval, sizeof optval);
2044 optval = so->so_type;
2048 optval = so->so_error;
2053 optval = so->so_snd.sb_hiwat;
2057 optval = so->so_rcv.sb_hiwat;
2061 optval = so->so_snd.sb_lowat;
2065 optval = so->so_rcv.sb_lowat;
2070 optval = (sopt->sopt_name == SO_SNDTIMEO ?
2071 so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
2073 tv.tv_sec = optval / hz;
2074 tv.tv_usec = (optval % hz) * tick;
2076 if (curthread->td_proc->p_sysent == &ia32_freebsd_sysvec) {
2077 struct timeval32 tv32;
2079 CP(tv, tv32, tv_sec);
2080 CP(tv, tv32, tv_usec);
2081 error = sooptcopyout(sopt, &tv32, sizeof tv32);
2084 error = sooptcopyout(sopt, &tv, sizeof tv);
2089 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2093 error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
2097 error = sooptcopyout(sopt, &extmac, sizeof extmac);
2105 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2109 error = mac_getsockopt_peerlabel(
2110 sopt->sopt_td->td_ucred, so, &extmac);
2113 error = sooptcopyout(sopt, &extmac, sizeof extmac);
2119 case SO_LISTENQLIMIT:
2120 optval = so->so_qlimit;
2124 optval = so->so_qlen;
2127 case SO_LISTENINCQLEN:
2128 optval = so->so_incqlen;
2132 error = ENOPROTOOPT;
2139 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
2141 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
2143 struct mbuf *m, *m_prev;
2144 int sopt_size = sopt->sopt_valsize;
2146 MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
2149 if (sopt_size > MLEN) {
2150 MCLGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT);
2151 if ((m->m_flags & M_EXT) == 0) {
2155 m->m_len = min(MCLBYTES, sopt_size);
2157 m->m_len = min(MLEN, sopt_size);
2159 sopt_size -= m->m_len;
2164 MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
2169 if (sopt_size > MLEN) {
2170 MCLGET(m, sopt->sopt_td != NULL ? M_TRYWAIT :
2172 if ((m->m_flags & M_EXT) == 0) {
2177 m->m_len = min(MCLBYTES, sopt_size);
2179 m->m_len = min(MLEN, sopt_size);
2181 sopt_size -= m->m_len;
2188 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
2190 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
2192 struct mbuf *m0 = m;
2194 if (sopt->sopt_val == NULL)
2196 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2197 if (sopt->sopt_td != NULL) {
2200 error = copyin(sopt->sopt_val, mtod(m, char *),
2207 bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
2208 sopt->sopt_valsize -= m->m_len;
2209 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2212 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
2213 panic("ip6_sooptmcopyin");
2217 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
2219 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
2221 struct mbuf *m0 = m;
2224 if (sopt->sopt_val == NULL)
2226 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2227 if (sopt->sopt_td != NULL) {
2230 error = copyout(mtod(m, char *), sopt->sopt_val,
2237 bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
2238 sopt->sopt_valsize -= m->m_len;
2239 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2240 valsize += m->m_len;
2244 /* enough soopt buffer should be given from user-land */
2248 sopt->sopt_valsize = valsize;
2256 if (so->so_sigio != NULL)
2257 pgsigio(&so->so_sigio, SIGURG, 0);
2258 selwakeuppri(&so->so_rcv.sb_sel, PSOCK);
2262 sopoll(struct socket *so, int events, struct ucred *active_cred,
2267 SOCKBUF_LOCK(&so->so_snd);
2268 SOCKBUF_LOCK(&so->so_rcv);
2269 if (events & (POLLIN | POLLRDNORM))
2271 revents |= events & (POLLIN | POLLRDNORM);
2273 if (events & POLLINIGNEOF)
2274 if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
2275 !TAILQ_EMPTY(&so->so_comp) || so->so_error)
2276 revents |= POLLINIGNEOF;
2278 if (events & (POLLOUT | POLLWRNORM))
2279 if (sowriteable(so))
2280 revents |= events & (POLLOUT | POLLWRNORM);
2282 if (events & (POLLPRI | POLLRDBAND))
2283 if (so->so_oobmark || (so->so_rcv.sb_state & SBS_RCVATMARK))
2284 revents |= events & (POLLPRI | POLLRDBAND);
2288 (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
2290 selrecord(td, &so->so_rcv.sb_sel);
2291 so->so_rcv.sb_flags |= SB_SEL;
2294 if (events & (POLLOUT | POLLWRNORM)) {
2295 selrecord(td, &so->so_snd.sb_sel);
2296 so->so_snd.sb_flags |= SB_SEL;
2300 SOCKBUF_UNLOCK(&so->so_rcv);
2301 SOCKBUF_UNLOCK(&so->so_snd);
2306 soo_kqfilter(struct file *fp, struct knote *kn)
2308 struct socket *so = kn->kn_fp->f_data;
2311 switch (kn->kn_filter) {
2313 if (so->so_options & SO_ACCEPTCONN)
2314 kn->kn_fop = &solisten_filtops;
2316 kn->kn_fop = &soread_filtops;
2320 kn->kn_fop = &sowrite_filtops;
2328 knlist_add(&sb->sb_sel.si_note, kn, 1);
2329 sb->sb_flags |= SB_KNOTE;
2335 filt_sordetach(struct knote *kn)
2337 struct socket *so = kn->kn_fp->f_data;
2339 SOCKBUF_LOCK(&so->so_rcv);
2340 knlist_remove(&so->so_rcv.sb_sel.si_note, kn, 1);
2341 if (knlist_empty(&so->so_rcv.sb_sel.si_note))
2342 so->so_rcv.sb_flags &= ~SB_KNOTE;
2343 SOCKBUF_UNLOCK(&so->so_rcv);
2348 filt_soread(struct knote *kn, long hint)
2352 so = kn->kn_fp->f_data;
2353 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2355 kn->kn_data = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
2356 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2357 kn->kn_flags |= EV_EOF;
2358 kn->kn_fflags = so->so_error;
2360 } else if (so->so_error) /* temporary udp error */
2362 else if (kn->kn_sfflags & NOTE_LOWAT)
2363 return (kn->kn_data >= kn->kn_sdata);
2365 return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat);
2369 filt_sowdetach(struct knote *kn)
2371 struct socket *so = kn->kn_fp->f_data;
2373 SOCKBUF_LOCK(&so->so_snd);
2374 knlist_remove(&so->so_snd.sb_sel.si_note, kn, 1);
2375 if (knlist_empty(&so->so_snd.sb_sel.si_note))
2376 so->so_snd.sb_flags &= ~SB_KNOTE;
2377 SOCKBUF_UNLOCK(&so->so_snd);
2382 filt_sowrite(struct knote *kn, long hint)
2386 so = kn->kn_fp->f_data;
2387 SOCKBUF_LOCK_ASSERT(&so->so_snd);
2388 kn->kn_data = sbspace(&so->so_snd);
2389 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2390 kn->kn_flags |= EV_EOF;
2391 kn->kn_fflags = so->so_error;
2393 } else if (so->so_error) /* temporary udp error */
2395 else if (((so->so_state & SS_ISCONNECTED) == 0) &&
2396 (so->so_proto->pr_flags & PR_CONNREQUIRED))
2398 else if (kn->kn_sfflags & NOTE_LOWAT)
2399 return (kn->kn_data >= kn->kn_sdata);
2401 return (kn->kn_data >= so->so_snd.sb_lowat);
2406 filt_solisten(struct knote *kn, long hint)
2408 struct socket *so = kn->kn_fp->f_data;
2410 kn->kn_data = so->so_qlen;
2411 return (! TAILQ_EMPTY(&so->so_comp));
2415 socheckuid(struct socket *so, uid_t uid)
2420 if (so->so_cred->cr_uid != uid)
2426 somaxconn_sysctl(SYSCTL_HANDLER_ARGS)
2432 error = sysctl_handle_int(oidp, &val, sizeof(int), req);
2433 if (error || !req->newptr )
2436 if (val < 1 || val > USHRT_MAX)