2 * Copyright (c) 1982, 1986, 1988, 1990, 1993
3 * The Regents of the University of California.
4 * Copyright (c) 2004 The FreeBSD Foundation
5 * Copyright (c) 2004-2008 Robert N. M. Watson
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * @(#)uipc_socket.c 8.3 (Berkeley) 4/15/94
36 * Comments on the socket life cycle:
38 * soalloc() sets of socket layer state for a socket, called only by
39 * socreate() and sonewconn(). Socket layer private.
41 * sodealloc() tears down socket layer state for a socket, called only by
42 * sofree() and sonewconn(). Socket layer private.
44 * pru_attach() associates protocol layer state with an allocated socket;
45 * called only once, may fail, aborting socket allocation. This is called
46 * from socreate() and sonewconn(). Socket layer private.
48 * pru_detach() disassociates protocol layer state from an attached socket,
49 * and will be called exactly once for sockets in which pru_attach() has
50 * been successfully called. If pru_attach() returned an error,
51 * pru_detach() will not be called. Socket layer private.
53 * pru_abort() and pru_close() notify the protocol layer that the last
54 * consumer of a socket is starting to tear down the socket, and that the
55 * protocol should terminate the connection. Historically, pru_abort() also
56 * detached protocol state from the socket state, but this is no longer the
59 * socreate() creates a socket and attaches protocol state. This is a public
60 * interface that may be used by socket layer consumers to create new
63 * sonewconn() creates a socket and attaches protocol state. This is a
64 * public interface that may be used by protocols to create new sockets when
65 * a new connection is received and will be available for accept() on a
68 * soclose() destroys a socket after possibly waiting for it to disconnect.
69 * This is a public interface that socket consumers should use to close and
70 * release a socket when done with it.
72 * soabort() destroys a socket without waiting for it to disconnect (used
73 * only for incoming connections that are already partially or fully
74 * connected). This is used internally by the socket layer when clearing
75 * listen socket queues (due to overflow or close on the listen socket), but
76 * is also a public interface protocols may use to abort connections in
77 * their incomplete listen queues should they no longer be required. Sockets
78 * placed in completed connection listen queues should not be aborted for
79 * reasons described in the comment above the soclose() implementation. This
80 * is not a general purpose close routine, and except in the specific
81 * circumstances described here, should not be used.
83 * sofree() will free a socket and its protocol state if all references on
84 * the socket have been released, and is the public interface to attempt to
85 * free a socket when a reference is removed. This is a socket layer private
88 * NOTE: In addition to socreate() and soclose(), which provide a single
89 * socket reference to the consumer to be managed as required, there are two
90 * calls to explicitly manage socket references, soref(), and sorele().
91 * Currently, these are generally required only when transitioning a socket
92 * from a listen queue to a file descriptor, in order to prevent garbage
93 * collection of the socket at an untimely moment. For a number of reasons,
94 * these interfaces are not preferred, and should be avoided.
97 #include <sys/cdefs.h>
98 __FBSDID("$FreeBSD$");
100 #include "opt_inet.h"
101 #include "opt_inet6.h"
103 #include "opt_zero.h"
104 #include "opt_compat.h"
106 #include <sys/param.h>
107 #include <sys/systm.h>
108 #include <sys/fcntl.h>
109 #include <sys/limits.h>
110 #include <sys/lock.h>
112 #include <sys/malloc.h>
113 #include <sys/mbuf.h>
114 #include <sys/mutex.h>
115 #include <sys/domain.h>
116 #include <sys/file.h> /* for struct knote */
117 #include <sys/kernel.h>
118 #include <sys/event.h>
119 #include <sys/eventhandler.h>
120 #include <sys/poll.h>
121 #include <sys/proc.h>
122 #include <sys/protosw.h>
123 #include <sys/socket.h>
124 #include <sys/socketvar.h>
125 #include <sys/resourcevar.h>
126 #include <net/route.h>
127 #include <sys/signalvar.h>
128 #include <sys/stat.h>
130 #include <sys/sysctl.h>
132 #include <sys/jail.h>
133 #include <sys/vimage.h>
135 #include <security/mac/mac_framework.h>
140 #include <sys/mount.h>
141 #include <sys/sysent.h>
142 #include <compat/freebsd32/freebsd32.h>
145 static int soreceive_rcvoob(struct socket *so, struct uio *uio,
148 static void filt_sordetach(struct knote *kn);
149 static int filt_soread(struct knote *kn, long hint);
150 static void filt_sowdetach(struct knote *kn);
151 static int filt_sowrite(struct knote *kn, long hint);
152 static int filt_solisten(struct knote *kn, long hint);
154 static struct filterops solisten_filtops =
155 { 1, NULL, filt_sordetach, filt_solisten };
156 static struct filterops soread_filtops =
157 { 1, NULL, filt_sordetach, filt_soread };
158 static struct filterops sowrite_filtops =
159 { 1, NULL, filt_sowdetach, filt_sowrite };
161 uma_zone_t socket_zone;
162 so_gen_t so_gencnt; /* generation count for sockets */
166 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
167 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
169 static int somaxconn = SOMAXCONN;
170 static int sysctl_somaxconn(SYSCTL_HANDLER_ARGS);
171 /* XXX: we dont have SYSCTL_USHORT */
172 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLTYPE_UINT | CTLFLAG_RW,
173 0, sizeof(int), sysctl_somaxconn, "I", "Maximum pending socket connection "
175 static int numopensockets;
176 SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
177 &numopensockets, 0, "Number of open sockets");
178 #ifdef ZERO_COPY_SOCKETS
179 /* These aren't static because they're used in other files. */
180 int so_zero_copy_send = 1;
181 int so_zero_copy_receive = 1;
182 SYSCTL_NODE(_kern_ipc, OID_AUTO, zero_copy, CTLFLAG_RD, 0,
183 "Zero copy controls");
184 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, receive, CTLFLAG_RW,
185 &so_zero_copy_receive, 0, "Enable zero copy receive");
186 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, send, CTLFLAG_RW,
187 &so_zero_copy_send, 0, "Enable zero copy send");
188 #endif /* ZERO_COPY_SOCKETS */
191 * accept_mtx locks down per-socket fields relating to accept queues. See
192 * socketvar.h for an annotation of the protected fields of struct socket.
194 struct mtx accept_mtx;
195 MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
198 * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
201 static struct mtx so_global_mtx;
202 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
205 * General IPC sysctl name space, used by sockets and a variety of other IPC
208 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
211 * Sysctl to get and set the maximum global sockets limit. Notify protocols
212 * of the change so that they can update their dependent limits as required.
215 sysctl_maxsockets(SYSCTL_HANDLER_ARGS)
217 int error, newmaxsockets;
219 newmaxsockets = maxsockets;
220 error = sysctl_handle_int(oidp, &newmaxsockets, 0, req);
221 if (error == 0 && req->newptr) {
222 if (newmaxsockets > maxsockets) {
223 maxsockets = newmaxsockets;
224 if (maxsockets > ((maxfiles / 4) * 3)) {
225 maxfiles = (maxsockets * 5) / 4;
226 maxfilesperproc = (maxfiles * 9) / 10;
228 EVENTHANDLER_INVOKE(maxsockets_change);
235 SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets, CTLTYPE_INT|CTLFLAG_RW,
236 &maxsockets, 0, sysctl_maxsockets, "IU",
237 "Maximum number of sockets avaliable");
240 * Initialise maxsockets. This SYSINIT must be run after
244 init_maxsockets(void *ignored)
247 TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
248 maxsockets = imax(maxsockets, imax(maxfiles, nmbclusters));
250 SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);
253 * Socket operation routines. These routines are called by the routines in
254 * sys_socket.c or from a system process, and implement the semantics of
255 * socket operations by switching out to the protocol specific routines.
259 * Get a socket structure from our zone, and initialize it. Note that it
260 * would probably be better to allocate socket and PCB at the same time, but
261 * I'm not convinced that all the protocols can be easily modified to do
264 * soalloc() returns a socket with a ref count of 0.
266 static struct socket *
267 soalloc(struct vnet *vnet)
271 so = uma_zalloc(socket_zone, M_NOWAIT | M_ZERO);
275 if (mac_socket_init(so, M_NOWAIT) != 0) {
276 uma_zfree(socket_zone, so);
280 SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
281 SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
282 sx_init(&so->so_snd.sb_sx, "so_snd_sx");
283 sx_init(&so->so_rcv.sb_sx, "so_rcv_sx");
284 TAILQ_INIT(&so->so_aiojobq);
285 mtx_lock(&so_global_mtx);
286 so->so_gencnt = ++so_gencnt;
289 ++vnet->sockcnt; /* Locked with so_global_mtx. */
292 mtx_unlock(&so_global_mtx);
297 * Free the storage associated with a socket at the socket layer, tear down
298 * locks, labels, etc. All protocol state is assumed already to have been
299 * torn down (and possibly never set up) by the caller.
302 sodealloc(struct socket *so)
305 KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
306 KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
308 mtx_lock(&so_global_mtx);
309 so->so_gencnt = ++so_gencnt;
310 --numopensockets; /* Could be below, but faster here. */
312 --so->so_vnet->sockcnt;
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_socket_destroy(so);
330 sx_destroy(&so->so_snd.sb_sx);
331 sx_destroy(&so->so_rcv.sb_sx);
332 SOCKBUF_LOCK_DESTROY(&so->so_snd);
333 SOCKBUF_LOCK_DESTROY(&so->so_rcv);
334 uma_zfree(socket_zone, so);
338 * socreate returns a socket with a ref count of 1. The socket should be
339 * closed with soclose().
342 socreate(int dom, struct socket **aso, int type, int proto,
343 struct ucred *cred, struct thread *td)
350 prp = pffindproto(dom, proto, type);
352 prp = pffindtype(dom, type);
354 if (prp == NULL || prp->pr_usrreqs->pru_attach == NULL ||
355 prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
356 return (EPROTONOSUPPORT);
358 if (prison_check_af(cred, prp->pr_domain->dom_family) != 0)
359 return (EPROTONOSUPPORT);
361 if (prp->pr_type != type)
363 so = soalloc(TD_TO_VNET(td));
367 TAILQ_INIT(&so->so_incomp);
368 TAILQ_INIT(&so->so_comp);
370 so->so_cred = crhold(cred);
371 if ((prp->pr_domain->dom_family == PF_INET) ||
372 (prp->pr_domain->dom_family == PF_ROUTE))
373 so->so_fibnum = td->td_proc->p_fibnum;
378 mac_socket_create(cred, so);
380 knlist_init(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv),
382 knlist_init(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd),
386 * Auto-sizing of socket buffers is managed by the protocols and
387 * the appropriate flags must be set in the pru_attach function.
389 CURVNET_SET(so->so_vnet);
390 error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
393 KASSERT(so->so_count == 1, ("socreate: so_count %d",
404 static int regression_sonewconn_earlytest = 1;
405 SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW,
406 ®ression_sonewconn_earlytest, 0, "Perform early sonewconn limit test");
410 * When an attempt at a new connection is noted on a socket which accepts
411 * connections, sonewconn is called. If the connection is possible (subject
412 * to space constraints, etc.) then we allocate a new structure, propoerly
413 * linked into the data structure of the original socket, and return this.
414 * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
416 * Note: the ref count on the socket is 0 on return.
419 sonewconn(struct socket *head, int connstatus)
425 over = (head->so_qlen > 3 * head->so_qlimit / 2);
428 if (regression_sonewconn_earlytest && over)
433 VNET_ASSERT(head->so_vnet);
434 so = soalloc(head->so_vnet);
437 if ((head->so_options & SO_ACCEPTFILTER) != 0)
440 so->so_type = head->so_type;
441 so->so_options = head->so_options &~ SO_ACCEPTCONN;
442 so->so_linger = head->so_linger;
443 so->so_state = head->so_state | SS_NOFDREF;
444 so->so_proto = head->so_proto;
445 so->so_cred = crhold(head->so_cred);
448 mac_socket_newconn(head, so);
451 knlist_init(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv),
453 knlist_init(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd),
455 if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat) ||
456 (*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
460 so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
461 so->so_snd.sb_lowat = head->so_snd.sb_lowat;
462 so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
463 so->so_snd.sb_timeo = head->so_snd.sb_timeo;
464 so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
465 so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
466 so->so_state |= connstatus;
469 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
470 so->so_qstate |= SQ_COMP;
474 * Keep removing sockets from the head until there's room for
475 * us to insert on the tail. In pre-locking revisions, this
476 * was a simple if(), but as we could be racing with other
477 * threads and soabort() requires dropping locks, we must
478 * loop waiting for the condition to be true.
480 while (head->so_incqlen > head->so_qlimit) {
482 sp = TAILQ_FIRST(&head->so_incomp);
483 TAILQ_REMOVE(&head->so_incomp, sp, so_list);
485 sp->so_qstate &= ~SQ_INCOMP;
491 TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
492 so->so_qstate |= SQ_INCOMP;
498 wakeup_one(&head->so_timeo);
504 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
508 CURVNET_SET(so->so_vnet);
509 error = (*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td);
515 * solisten() transitions a socket from a non-listening state to a listening
516 * state, but can also be used to update the listen queue depth on an
517 * existing listen socket. The protocol will call back into the sockets
518 * layer using solisten_proto_check() and solisten_proto() to check and set
519 * socket-layer listen state. Call backs are used so that the protocol can
520 * acquire both protocol and socket layer locks in whatever order is required
523 * Protocol implementors are advised to hold the socket lock across the
524 * socket-layer test and set to avoid races at the socket layer.
527 solisten(struct socket *so, int backlog, struct thread *td)
530 return ((*so->so_proto->pr_usrreqs->pru_listen)(so, backlog, td));
534 solisten_proto_check(struct socket *so)
537 SOCK_LOCK_ASSERT(so);
539 if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
546 solisten_proto(struct socket *so, int backlog)
549 SOCK_LOCK_ASSERT(so);
551 if (backlog < 0 || backlog > somaxconn)
553 so->so_qlimit = backlog;
554 so->so_options |= SO_ACCEPTCONN;
558 * Attempt to free a socket. This should really be sotryfree().
560 * sofree() will succeed if:
562 * - There are no outstanding file descriptor references or related consumers
565 * - The socket has been closed by user space, if ever open (SS_NOFDREF).
567 * - The protocol does not have an outstanding strong reference on the socket
570 * - The socket is not in a completed connection queue, so a process has been
571 * notified that it is present. If it is removed, the user process may
572 * block in accept() despite select() saying the socket was ready.
574 * Otherwise, it will quietly abort so that a future call to sofree(), when
575 * conditions are right, can succeed.
578 sofree(struct socket *so)
580 struct protosw *pr = so->so_proto;
583 ACCEPT_LOCK_ASSERT();
584 SOCK_LOCK_ASSERT(so);
586 if ((so->so_state & SS_NOFDREF) == 0 || so->so_count != 0 ||
587 (so->so_state & SS_PROTOREF) || (so->so_qstate & SQ_COMP)) {
595 KASSERT((so->so_qstate & SQ_COMP) != 0 ||
596 (so->so_qstate & SQ_INCOMP) != 0,
597 ("sofree: so_head != NULL, but neither SQ_COMP nor "
599 KASSERT((so->so_qstate & SQ_COMP) == 0 ||
600 (so->so_qstate & SQ_INCOMP) == 0,
601 ("sofree: so->so_qstate is SQ_COMP and also SQ_INCOMP"));
602 TAILQ_REMOVE(&head->so_incomp, so, so_list);
604 so->so_qstate &= ~SQ_INCOMP;
607 KASSERT((so->so_qstate & SQ_COMP) == 0 &&
608 (so->so_qstate & SQ_INCOMP) == 0,
609 ("sofree: so_head == NULL, but still SQ_COMP(%d) or SQ_INCOMP(%d)",
610 so->so_qstate & SQ_COMP, so->so_qstate & SQ_INCOMP));
611 if (so->so_options & SO_ACCEPTCONN) {
612 KASSERT((TAILQ_EMPTY(&so->so_comp)), ("sofree: so_comp populated"));
613 KASSERT((TAILQ_EMPTY(&so->so_incomp)), ("sofree: so_comp populated"));
618 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
619 (*pr->pr_domain->dom_dispose)(so->so_rcv.sb_mb);
620 if (pr->pr_usrreqs->pru_detach != NULL)
621 (*pr->pr_usrreqs->pru_detach)(so);
624 * From this point on, we assume that no other references to this
625 * socket exist anywhere else in the stack. Therefore, no locks need
626 * to be acquired or held.
628 * We used to do a lot of socket buffer and socket locking here, as
629 * well as invoke sorflush() and perform wakeups. The direct call to
630 * dom_dispose() and sbrelease_internal() are an inlining of what was
631 * necessary from sorflush().
633 * Notice that the socket buffer and kqueue state are torn down
634 * before calling pru_detach. This means that protocols shold not
635 * assume they can perform socket wakeups, etc, in their detach code.
637 sbdestroy(&so->so_snd, so);
638 sbdestroy(&so->so_rcv, so);
639 knlist_destroy(&so->so_rcv.sb_sel.si_note);
640 knlist_destroy(&so->so_snd.sb_sel.si_note);
645 * Close a socket on last file table reference removal. Initiate disconnect
646 * if connected. Free socket when disconnect complete.
648 * This function will sorele() the socket. Note that soclose() may be called
649 * prior to the ref count reaching zero. The actual socket structure will
650 * not be freed until the ref count reaches zero.
653 soclose(struct socket *so)
657 KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
659 CURVNET_SET(so->so_vnet);
660 funsetown(&so->so_sigio);
661 if (so->so_state & SS_ISCONNECTED) {
662 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
663 error = sodisconnect(so);
667 if (so->so_options & SO_LINGER) {
668 if ((so->so_state & SS_ISDISCONNECTING) &&
669 (so->so_state & SS_NBIO))
671 while (so->so_state & SS_ISCONNECTED) {
672 error = tsleep(&so->so_timeo,
673 PSOCK | PCATCH, "soclos", so->so_linger * hz);
681 if (so->so_proto->pr_usrreqs->pru_close != NULL)
682 (*so->so_proto->pr_usrreqs->pru_close)(so);
683 if (so->so_options & SO_ACCEPTCONN) {
686 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
687 TAILQ_REMOVE(&so->so_incomp, sp, so_list);
689 sp->so_qstate &= ~SQ_INCOMP;
695 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
696 TAILQ_REMOVE(&so->so_comp, sp, so_list);
698 sp->so_qstate &= ~SQ_COMP;
708 KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
709 so->so_state |= SS_NOFDREF;
716 * soabort() is used to abruptly tear down a connection, such as when a
717 * resource limit is reached (listen queue depth exceeded), or if a listen
718 * socket is closed while there are sockets waiting to be accepted.
720 * This interface is tricky, because it is called on an unreferenced socket,
721 * and must be called only by a thread that has actually removed the socket
722 * from the listen queue it was on, or races with other threads are risked.
724 * This interface will call into the protocol code, so must not be called
725 * with any socket locks held. Protocols do call it while holding their own
726 * recursible protocol mutexes, but this is something that should be subject
727 * to review in the future.
730 soabort(struct socket *so)
734 * In as much as is possible, assert that no references to this
735 * socket are held. This is not quite the same as asserting that the
736 * current thread is responsible for arranging for no references, but
737 * is as close as we can get for now.
739 KASSERT(so->so_count == 0, ("soabort: so_count"));
740 KASSERT((so->so_state & SS_PROTOREF) == 0, ("soabort: SS_PROTOREF"));
741 KASSERT(so->so_state & SS_NOFDREF, ("soabort: !SS_NOFDREF"));
742 KASSERT((so->so_state & SQ_COMP) == 0, ("soabort: SQ_COMP"));
743 KASSERT((so->so_state & SQ_INCOMP) == 0, ("soabort: SQ_INCOMP"));
745 if (so->so_proto->pr_usrreqs->pru_abort != NULL)
746 (*so->so_proto->pr_usrreqs->pru_abort)(so);
753 soaccept(struct socket *so, struct sockaddr **nam)
758 KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
759 so->so_state &= ~SS_NOFDREF;
761 error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
766 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
770 if (so->so_options & SO_ACCEPTCONN)
773 * If protocol is connection-based, can only connect once.
774 * Otherwise, if connected, try to disconnect first. This allows
775 * user to disconnect by connecting to, e.g., a null address.
777 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
778 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
779 (error = sodisconnect(so)))) {
783 * Prevent accumulated error from previous connection from
787 CURVNET_SET(so->so_vnet);
788 error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, td);
796 soconnect2(struct socket *so1, struct socket *so2)
799 return ((*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2));
803 sodisconnect(struct socket *so)
807 if ((so->so_state & SS_ISCONNECTED) == 0)
809 if (so->so_state & SS_ISDISCONNECTING)
811 error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
815 #ifdef ZERO_COPY_SOCKETS
816 struct so_zerocopy_stats{
821 struct so_zerocopy_stats so_zerocp_stats = {0,0,0};
822 #include <netinet/in.h>
823 #include <net/route.h>
824 #include <netinet/in_pcb.h>
826 #include <vm/vm_page.h>
827 #include <vm/vm_object.h>
830 * sosend_copyin() is only used if zero copy sockets are enabled. Otherwise
831 * sosend_dgram() and sosend_generic() use m_uiotombuf().
833 * sosend_copyin() accepts a uio and prepares an mbuf chain holding part or
834 * all of the data referenced by the uio. If desired, it uses zero-copy.
835 * *space will be updated to reflect data copied in.
837 * NB: If atomic I/O is requested, the caller must already have checked that
838 * space can hold resid bytes.
840 * NB: In the event of an error, the caller may need to free the partial
841 * chain pointed to by *mpp. The contents of both *uio and *space may be
842 * modified even in the case of an error.
845 sosend_copyin(struct uio *uio, struct mbuf **retmp, int atomic, long *space,
848 struct mbuf *m, **mp, *top;
851 #ifdef ZERO_COPY_SOCKETS
858 resid = uio->uio_resid;
861 #ifdef ZERO_COPY_SOCKETS
863 #endif /* ZERO_COPY_SOCKETS */
864 if (resid >= MINCLSIZE) {
865 #ifdef ZERO_COPY_SOCKETS
867 m = m_gethdr(M_WAITOK, MT_DATA);
869 m->m_pkthdr.rcvif = NULL;
871 m = m_get(M_WAITOK, MT_DATA);
872 if (so_zero_copy_send &&
875 uio->uio_iov->iov_len>=PAGE_SIZE) {
876 so_zerocp_stats.size_ok++;
877 so_zerocp_stats.align_ok++;
878 cow_send = socow_setup(m, uio);
882 m_clget(m, M_WAITOK);
883 len = min(min(MCLBYTES, resid), *space);
885 #else /* ZERO_COPY_SOCKETS */
887 m = m_getcl(M_WAIT, MT_DATA, M_PKTHDR);
889 m->m_pkthdr.rcvif = NULL;
891 m = m_getcl(M_WAIT, MT_DATA, 0);
892 len = min(min(MCLBYTES, resid), *space);
893 #endif /* ZERO_COPY_SOCKETS */
896 m = m_gethdr(M_WAIT, MT_DATA);
898 m->m_pkthdr.rcvif = NULL;
900 len = min(min(MHLEN, resid), *space);
902 * For datagram protocols, leave room
903 * for protocol headers in first mbuf.
905 if (atomic && m && len < MHLEN)
908 m = m_get(M_WAIT, MT_DATA);
909 len = min(min(MLEN, resid), *space);
918 #ifdef ZERO_COPY_SOCKETS
922 #endif /* ZERO_COPY_SOCKETS */
923 error = uiomove(mtod(m, void *), (int)len, uio);
924 resid = uio->uio_resid;
927 top->m_pkthdr.len += len;
933 top->m_flags |= M_EOR;
936 } while (*space > 0 && atomic);
941 #endif /*ZERO_COPY_SOCKETS*/
943 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? 0 : SBL_WAIT)
946 sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
947 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
950 int clen = 0, error, dontroute;
951 #ifdef ZERO_COPY_SOCKETS
952 int atomic = sosendallatonce(so) || top;
955 KASSERT(so->so_type == SOCK_DGRAM, ("sodgram_send: !SOCK_DGRAM"));
956 KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
957 ("sodgram_send: !PR_ATOMIC"));
960 resid = uio->uio_resid;
962 resid = top->m_pkthdr.len;
964 * In theory resid should be unsigned. However, space must be
965 * signed, as it might be less than 0 if we over-committed, and we
966 * must use a signed comparison of space and resid. On the other
967 * hand, a negative resid causes us to loop sending 0-length
968 * segments to the protocol.
970 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
971 * type sockets since that's an error.
979 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
981 td->td_ru.ru_msgsnd++;
983 clen = control->m_len;
985 SOCKBUF_LOCK(&so->so_snd);
986 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
987 SOCKBUF_UNLOCK(&so->so_snd);
992 error = so->so_error;
994 SOCKBUF_UNLOCK(&so->so_snd);
997 if ((so->so_state & SS_ISCONNECTED) == 0) {
999 * `sendto' and `sendmsg' is allowed on a connection-based
1000 * socket if it supports implied connect. Return ENOTCONN if
1001 * not connected and no address is supplied.
1003 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1004 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1005 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1006 !(resid == 0 && clen != 0)) {
1007 SOCKBUF_UNLOCK(&so->so_snd);
1011 } else if (addr == NULL) {
1012 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1015 error = EDESTADDRREQ;
1016 SOCKBUF_UNLOCK(&so->so_snd);
1022 * Do we need MSG_OOB support in SOCK_DGRAM? Signs here may be a
1023 * problem and need fixing.
1025 space = sbspace(&so->so_snd);
1026 if (flags & MSG_OOB)
1029 SOCKBUF_UNLOCK(&so->so_snd);
1030 if (resid > space) {
1036 if (flags & MSG_EOR)
1037 top->m_flags |= M_EOR;
1039 #ifdef ZERO_COPY_SOCKETS
1040 error = sosend_copyin(uio, &top, atomic, &space, flags);
1045 * Copy the data from userland into a mbuf chain.
1046 * If no data is to be copied in, a single empty mbuf
1049 top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
1050 (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
1052 error = EFAULT; /* only possible error */
1055 space -= resid - uio->uio_resid;
1057 resid = uio->uio_resid;
1059 KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
1061 * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
1066 so->so_options |= SO_DONTROUTE;
1070 * XXX all the SBS_CANTSENDMORE checks previously done could be out
1071 * of date. We could have recieved a reset packet in an interrupt or
1072 * maybe we slept while doing page faults in uiomove() etc. We could
1073 * probably recheck again inside the locking protection here, but
1074 * there are probably other places that this also happens. We must
1077 error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1078 (flags & MSG_OOB) ? PRUS_OOB :
1080 * If the user set MSG_EOF, the protocol understands this flag and
1081 * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
1083 ((flags & MSG_EOF) &&
1084 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1087 /* If there is more to send set PRUS_MORETOCOME */
1088 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1089 top, addr, control, td);
1092 so->so_options &= ~SO_DONTROUTE;
1101 if (control != NULL)
1107 * Send on a socket. If send must go all at once and message is larger than
1108 * send buffering, then hard error. Lock against other senders. If must go
1109 * all at once and not enough room now, then inform user that this would
1110 * block and do nothing. Otherwise, if nonblocking, send as much as
1111 * possible. The data to be sent is described by "uio" if nonzero, otherwise
1112 * by the mbuf chain "top" (which must be null if uio is not). Data provided
1113 * in mbuf chain must be small enough to send all at once.
1115 * Returns nonzero on error, timeout or signal; callers must check for short
1116 * counts if EINTR/ERESTART are returned. Data and control buffers are freed
1120 sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
1121 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1124 int clen = 0, error, dontroute;
1125 int atomic = sosendallatonce(so) || top;
1128 resid = uio->uio_resid;
1130 resid = top->m_pkthdr.len;
1132 * In theory resid should be unsigned. However, space must be
1133 * signed, as it might be less than 0 if we over-committed, and we
1134 * must use a signed comparison of space and resid. On the other
1135 * hand, a negative resid causes us to loop sending 0-length
1136 * segments to the protocol.
1138 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
1139 * type sockets since that's an error.
1141 if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
1147 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
1148 (so->so_proto->pr_flags & PR_ATOMIC);
1150 td->td_ru.ru_msgsnd++;
1151 if (control != NULL)
1152 clen = control->m_len;
1154 error = sblock(&so->so_snd, SBLOCKWAIT(flags));
1160 SOCKBUF_LOCK(&so->so_snd);
1161 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1162 SOCKBUF_UNLOCK(&so->so_snd);
1167 error = so->so_error;
1169 SOCKBUF_UNLOCK(&so->so_snd);
1172 if ((so->so_state & SS_ISCONNECTED) == 0) {
1174 * `sendto' and `sendmsg' is allowed on a connection-
1175 * based socket if it supports implied connect.
1176 * Return ENOTCONN if not connected and no address is
1179 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1180 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1181 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1182 !(resid == 0 && clen != 0)) {
1183 SOCKBUF_UNLOCK(&so->so_snd);
1187 } else if (addr == NULL) {
1188 SOCKBUF_UNLOCK(&so->so_snd);
1189 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1192 error = EDESTADDRREQ;
1196 space = sbspace(&so->so_snd);
1197 if (flags & MSG_OOB)
1199 if ((atomic && resid > so->so_snd.sb_hiwat) ||
1200 clen > so->so_snd.sb_hiwat) {
1201 SOCKBUF_UNLOCK(&so->so_snd);
1205 if (space < resid + clen &&
1206 (atomic || space < so->so_snd.sb_lowat || space < clen)) {
1207 if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO)) {
1208 SOCKBUF_UNLOCK(&so->so_snd);
1209 error = EWOULDBLOCK;
1212 error = sbwait(&so->so_snd);
1213 SOCKBUF_UNLOCK(&so->so_snd);
1218 SOCKBUF_UNLOCK(&so->so_snd);
1223 if (flags & MSG_EOR)
1224 top->m_flags |= M_EOR;
1226 #ifdef ZERO_COPY_SOCKETS
1227 error = sosend_copyin(uio, &top, atomic,
1233 * Copy the data from userland into a mbuf
1234 * chain. If no data is to be copied in,
1235 * a single empty mbuf is returned.
1237 top = m_uiotombuf(uio, M_WAITOK, space,
1238 (atomic ? max_hdr : 0),
1239 (atomic ? M_PKTHDR : 0) |
1240 ((flags & MSG_EOR) ? M_EOR : 0));
1242 error = EFAULT; /* only possible error */
1245 space -= resid - uio->uio_resid;
1247 resid = uio->uio_resid;
1251 so->so_options |= SO_DONTROUTE;
1255 * XXX all the SBS_CANTSENDMORE checks previously
1256 * done could be out of date. We could have recieved
1257 * a reset packet in an interrupt or maybe we slept
1258 * while doing page faults in uiomove() etc. We
1259 * could probably recheck again inside the locking
1260 * protection here, but there are probably other
1261 * places that this also happens. We must rethink
1264 error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1265 (flags & MSG_OOB) ? PRUS_OOB :
1267 * If the user set MSG_EOF, the protocol understands
1268 * this flag and nothing left to send then use
1269 * PRU_SEND_EOF instead of PRU_SEND.
1271 ((flags & MSG_EOF) &&
1272 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1275 /* If there is more to send set PRUS_MORETOCOME. */
1276 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1277 top, addr, control, td);
1280 so->so_options &= ~SO_DONTROUTE;
1288 } while (resid && space > 0);
1292 sbunlock(&so->so_snd);
1296 if (control != NULL)
1302 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
1303 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1307 CURVNET_SET(so->so_vnet);
1308 error = so->so_proto->pr_usrreqs->pru_sosend(so, addr, uio, top,
1309 control, flags, td);
1315 * The part of soreceive() that implements reading non-inline out-of-band
1316 * data from a socket. For more complete comments, see soreceive(), from
1317 * which this code originated.
1319 * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
1320 * unable to return an mbuf chain to the caller.
1323 soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
1325 struct protosw *pr = so->so_proto;
1329 KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
1331 m = m_get(M_WAIT, MT_DATA);
1332 error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
1336 #ifdef ZERO_COPY_SOCKETS
1337 if (so_zero_copy_receive) {
1340 if ((m->m_flags & M_EXT)
1341 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1346 error = uiomoveco(mtod(m, void *),
1347 min(uio->uio_resid, m->m_len),
1350 #endif /* ZERO_COPY_SOCKETS */
1351 error = uiomove(mtod(m, void *),
1352 (int) min(uio->uio_resid, m->m_len), uio);
1354 } while (uio->uio_resid && error == 0 && m);
1362 * Following replacement or removal of the first mbuf on the first mbuf chain
1363 * of a socket buffer, push necessary state changes back into the socket
1364 * buffer so that other consumers see the values consistently. 'nextrecord'
1365 * is the callers locally stored value of the original value of
1366 * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
1367 * NOTE: 'nextrecord' may be NULL.
1369 static __inline void
1370 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
1373 SOCKBUF_LOCK_ASSERT(sb);
1375 * First, update for the new value of nextrecord. If necessary, make
1376 * it the first record.
1378 if (sb->sb_mb != NULL)
1379 sb->sb_mb->m_nextpkt = nextrecord;
1381 sb->sb_mb = nextrecord;
1384 * Now update any dependent socket buffer fields to reflect the new
1385 * state. This is an expanded inline of SB_EMPTY_FIXUP(), with the
1386 * addition of a second clause that takes care of the case where
1387 * sb_mb has been updated, but remains the last record.
1389 if (sb->sb_mb == NULL) {
1390 sb->sb_mbtail = NULL;
1391 sb->sb_lastrecord = NULL;
1392 } else if (sb->sb_mb->m_nextpkt == NULL)
1393 sb->sb_lastrecord = sb->sb_mb;
1398 * Implement receive operations on a socket. We depend on the way that
1399 * records are added to the sockbuf by sbappend. In particular, each record
1400 * (mbufs linked through m_next) must begin with an address if the protocol
1401 * so specifies, followed by an optional mbuf or mbufs containing ancillary
1402 * data, and then zero or more mbufs of data. In order to allow parallelism
1403 * between network receive and copying to user space, as well as avoid
1404 * sleeping with a mutex held, we release the socket buffer mutex during the
1405 * user space copy. Although the sockbuf is locked, new data may still be
1406 * appended, and thus we must maintain consistency of the sockbuf during that
1409 * The caller may receive the data as a single mbuf chain by supplying an
1410 * mbuf **mp0 for use in returning the chain. The uio is then used only for
1411 * the count in uio_resid.
1414 soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
1415 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1417 struct mbuf *m, **mp;
1418 int flags, len, error, offset;
1419 struct protosw *pr = so->so_proto;
1420 struct mbuf *nextrecord;
1422 int orig_resid = uio->uio_resid;
1427 if (controlp != NULL)
1430 flags = *flagsp &~ MSG_EOR;
1433 if (flags & MSG_OOB)
1434 return (soreceive_rcvoob(so, uio, flags));
1437 if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
1439 (*pr->pr_usrreqs->pru_rcvd)(so, 0);
1441 error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
1446 SOCKBUF_LOCK(&so->so_rcv);
1447 m = so->so_rcv.sb_mb;
1449 * If we have less data than requested, block awaiting more (subject
1450 * to any timeout) if:
1451 * 1. the current count is less than the low water mark, or
1452 * 2. MSG_WAITALL is set, and it is possible to do the entire
1453 * receive operation at once if we block (resid <= hiwat).
1454 * 3. MSG_DONTWAIT is not set
1455 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1456 * we have to do the receive in sections, and thus risk returning a
1457 * short count if a timeout or signal occurs after we start.
1459 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1460 so->so_rcv.sb_cc < uio->uio_resid) &&
1461 (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
1462 ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
1463 m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
1464 KASSERT(m != NULL || !so->so_rcv.sb_cc,
1465 ("receive: m == %p so->so_rcv.sb_cc == %u",
1466 m, so->so_rcv.sb_cc));
1470 error = so->so_error;
1471 if ((flags & MSG_PEEK) == 0)
1473 SOCKBUF_UNLOCK(&so->so_rcv);
1476 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1477 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1479 SOCKBUF_UNLOCK(&so->so_rcv);
1484 for (; m != NULL; m = m->m_next)
1485 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
1486 m = so->so_rcv.sb_mb;
1489 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1490 (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1491 SOCKBUF_UNLOCK(&so->so_rcv);
1495 if (uio->uio_resid == 0) {
1496 SOCKBUF_UNLOCK(&so->so_rcv);
1499 if ((so->so_state & SS_NBIO) ||
1500 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1501 SOCKBUF_UNLOCK(&so->so_rcv);
1502 error = EWOULDBLOCK;
1505 SBLASTRECORDCHK(&so->so_rcv);
1506 SBLASTMBUFCHK(&so->so_rcv);
1507 error = sbwait(&so->so_rcv);
1508 SOCKBUF_UNLOCK(&so->so_rcv);
1515 * From this point onward, we maintain 'nextrecord' as a cache of the
1516 * pointer to the next record in the socket buffer. We must keep the
1517 * various socket buffer pointers and local stack versions of the
1518 * pointers in sync, pushing out modifications before dropping the
1519 * socket buffer mutex, and re-reading them when picking it up.
1521 * Otherwise, we will race with the network stack appending new data
1522 * or records onto the socket buffer by using inconsistent/stale
1523 * versions of the field, possibly resulting in socket buffer
1526 * By holding the high-level sblock(), we prevent simultaneous
1527 * readers from pulling off the front of the socket buffer.
1529 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1531 uio->uio_td->td_ru.ru_msgrcv++;
1532 KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
1533 SBLASTRECORDCHK(&so->so_rcv);
1534 SBLASTMBUFCHK(&so->so_rcv);
1535 nextrecord = m->m_nextpkt;
1536 if (pr->pr_flags & PR_ADDR) {
1537 KASSERT(m->m_type == MT_SONAME,
1538 ("m->m_type == %d", m->m_type));
1541 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
1543 if (flags & MSG_PEEK) {
1546 sbfree(&so->so_rcv, m);
1547 so->so_rcv.sb_mb = m_free(m);
1548 m = so->so_rcv.sb_mb;
1549 sockbuf_pushsync(&so->so_rcv, nextrecord);
1554 * Process one or more MT_CONTROL mbufs present before any data mbufs
1555 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
1556 * just copy the data; if !MSG_PEEK, we call into the protocol to
1557 * perform externalization (or freeing if controlp == NULL).
1559 if (m != NULL && m->m_type == MT_CONTROL) {
1560 struct mbuf *cm = NULL, *cmn;
1561 struct mbuf **cme = &cm;
1564 if (flags & MSG_PEEK) {
1565 if (controlp != NULL) {
1566 *controlp = m_copy(m, 0, m->m_len);
1567 controlp = &(*controlp)->m_next;
1571 sbfree(&so->so_rcv, m);
1572 so->so_rcv.sb_mb = m->m_next;
1575 cme = &(*cme)->m_next;
1576 m = so->so_rcv.sb_mb;
1578 } while (m != NULL && m->m_type == MT_CONTROL);
1579 if ((flags & MSG_PEEK) == 0)
1580 sockbuf_pushsync(&so->so_rcv, nextrecord);
1581 while (cm != NULL) {
1584 if (pr->pr_domain->dom_externalize != NULL) {
1585 SOCKBUF_UNLOCK(&so->so_rcv);
1586 error = (*pr->pr_domain->dom_externalize)
1588 SOCKBUF_LOCK(&so->so_rcv);
1589 } else if (controlp != NULL)
1593 if (controlp != NULL) {
1595 while (*controlp != NULL)
1596 controlp = &(*controlp)->m_next;
1601 nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1603 nextrecord = so->so_rcv.sb_mb;
1607 if ((flags & MSG_PEEK) == 0) {
1608 KASSERT(m->m_nextpkt == nextrecord,
1609 ("soreceive: post-control, nextrecord !sync"));
1610 if (nextrecord == NULL) {
1611 KASSERT(so->so_rcv.sb_mb == m,
1612 ("soreceive: post-control, sb_mb!=m"));
1613 KASSERT(so->so_rcv.sb_lastrecord == m,
1614 ("soreceive: post-control, lastrecord!=m"));
1618 if (type == MT_OOBDATA)
1621 if ((flags & MSG_PEEK) == 0) {
1622 KASSERT(so->so_rcv.sb_mb == nextrecord,
1623 ("soreceive: sb_mb != nextrecord"));
1624 if (so->so_rcv.sb_mb == NULL) {
1625 KASSERT(so->so_rcv.sb_lastrecord == NULL,
1626 ("soreceive: sb_lastercord != NULL"));
1630 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1631 SBLASTRECORDCHK(&so->so_rcv);
1632 SBLASTMBUFCHK(&so->so_rcv);
1635 * Now continue to read any data mbufs off of the head of the socket
1636 * buffer until the read request is satisfied. Note that 'type' is
1637 * used to store the type of any mbuf reads that have happened so far
1638 * such that soreceive() can stop reading if the type changes, which
1639 * causes soreceive() to return only one of regular data and inline
1640 * out-of-band data in a single socket receive operation.
1644 while (m != NULL && uio->uio_resid > 0 && error == 0) {
1646 * If the type of mbuf has changed since the last mbuf
1647 * examined ('type'), end the receive operation.
1649 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1650 if (m->m_type == MT_OOBDATA) {
1651 if (type != MT_OOBDATA)
1653 } else if (type == MT_OOBDATA)
1656 KASSERT(m->m_type == MT_DATA,
1657 ("m->m_type == %d", m->m_type));
1658 so->so_rcv.sb_state &= ~SBS_RCVATMARK;
1659 len = uio->uio_resid;
1660 if (so->so_oobmark && len > so->so_oobmark - offset)
1661 len = so->so_oobmark - offset;
1662 if (len > m->m_len - moff)
1663 len = m->m_len - moff;
1665 * If mp is set, just pass back the mbufs. Otherwise copy
1666 * them out via the uio, then free. Sockbuf must be
1667 * consistent here (points to current mbuf, it points to next
1668 * record) when we drop priority; we must note any additions
1669 * to the sockbuf when we block interrupts again.
1672 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1673 SBLASTRECORDCHK(&so->so_rcv);
1674 SBLASTMBUFCHK(&so->so_rcv);
1675 SOCKBUF_UNLOCK(&so->so_rcv);
1676 #ifdef ZERO_COPY_SOCKETS
1677 if (so_zero_copy_receive) {
1680 if ((m->m_flags & M_EXT)
1681 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1686 error = uiomoveco(mtod(m, char *) + moff,
1690 #endif /* ZERO_COPY_SOCKETS */
1691 error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1692 SOCKBUF_LOCK(&so->so_rcv);
1695 * The MT_SONAME mbuf has already been removed
1696 * from the record, so it is necessary to
1697 * remove the data mbufs, if any, to preserve
1698 * the invariant in the case of PR_ADDR that
1699 * requires MT_SONAME mbufs at the head of
1702 if (m && pr->pr_flags & PR_ATOMIC &&
1703 ((flags & MSG_PEEK) == 0))
1704 (void)sbdroprecord_locked(&so->so_rcv);
1705 SOCKBUF_UNLOCK(&so->so_rcv);
1709 uio->uio_resid -= len;
1710 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1711 if (len == m->m_len - moff) {
1712 if (m->m_flags & M_EOR)
1714 if (flags & MSG_PEEK) {
1718 nextrecord = m->m_nextpkt;
1719 sbfree(&so->so_rcv, m);
1723 so->so_rcv.sb_mb = m = m->m_next;
1726 so->so_rcv.sb_mb = m_free(m);
1727 m = so->so_rcv.sb_mb;
1729 sockbuf_pushsync(&so->so_rcv, nextrecord);
1730 SBLASTRECORDCHK(&so->so_rcv);
1731 SBLASTMBUFCHK(&so->so_rcv);
1734 if (flags & MSG_PEEK)
1740 if (flags & MSG_DONTWAIT)
1741 copy_flag = M_DONTWAIT;
1744 if (copy_flag == M_WAIT)
1745 SOCKBUF_UNLOCK(&so->so_rcv);
1746 *mp = m_copym(m, 0, len, copy_flag);
1747 if (copy_flag == M_WAIT)
1748 SOCKBUF_LOCK(&so->so_rcv);
1751 * m_copym() couldn't
1752 * allocate an mbuf. Adjust
1753 * uio_resid back (it was
1754 * adjusted down by len
1755 * bytes, which we didn't end
1756 * up "copying" over).
1758 uio->uio_resid += len;
1764 so->so_rcv.sb_cc -= len;
1767 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1768 if (so->so_oobmark) {
1769 if ((flags & MSG_PEEK) == 0) {
1770 so->so_oobmark -= len;
1771 if (so->so_oobmark == 0) {
1772 so->so_rcv.sb_state |= SBS_RCVATMARK;
1777 if (offset == so->so_oobmark)
1781 if (flags & MSG_EOR)
1784 * If the MSG_WAITALL flag is set (for non-atomic socket), we
1785 * must not quit until "uio->uio_resid == 0" or an error
1786 * termination. If a signal/timeout occurs, return with a
1787 * short count but without error. Keep sockbuf locked
1788 * against other readers.
1790 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1791 !sosendallatonce(so) && nextrecord == NULL) {
1792 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1793 if (so->so_error || so->so_rcv.sb_state & SBS_CANTRCVMORE)
1796 * Notify the protocol that some data has been
1797 * drained before blocking.
1799 if (pr->pr_flags & PR_WANTRCVD) {
1800 SOCKBUF_UNLOCK(&so->so_rcv);
1801 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1802 SOCKBUF_LOCK(&so->so_rcv);
1804 SBLASTRECORDCHK(&so->so_rcv);
1805 SBLASTMBUFCHK(&so->so_rcv);
1806 error = sbwait(&so->so_rcv);
1808 SOCKBUF_UNLOCK(&so->so_rcv);
1811 m = so->so_rcv.sb_mb;
1813 nextrecord = m->m_nextpkt;
1817 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1818 if (m != NULL && pr->pr_flags & PR_ATOMIC) {
1820 if ((flags & MSG_PEEK) == 0)
1821 (void) sbdroprecord_locked(&so->so_rcv);
1823 if ((flags & MSG_PEEK) == 0) {
1826 * First part is an inline SB_EMPTY_FIXUP(). Second
1827 * part makes sure sb_lastrecord is up-to-date if
1828 * there is still data in the socket buffer.
1830 so->so_rcv.sb_mb = nextrecord;
1831 if (so->so_rcv.sb_mb == NULL) {
1832 so->so_rcv.sb_mbtail = NULL;
1833 so->so_rcv.sb_lastrecord = NULL;
1834 } else if (nextrecord->m_nextpkt == NULL)
1835 so->so_rcv.sb_lastrecord = nextrecord;
1837 SBLASTRECORDCHK(&so->so_rcv);
1838 SBLASTMBUFCHK(&so->so_rcv);
1840 * If soreceive() is being done from the socket callback,
1841 * then don't need to generate ACK to peer to update window,
1842 * since ACK will be generated on return to TCP.
1844 if (!(flags & MSG_SOCALLBCK) &&
1845 (pr->pr_flags & PR_WANTRCVD)) {
1846 SOCKBUF_UNLOCK(&so->so_rcv);
1847 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1848 SOCKBUF_LOCK(&so->so_rcv);
1851 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1852 if (orig_resid == uio->uio_resid && orig_resid &&
1853 (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
1854 SOCKBUF_UNLOCK(&so->so_rcv);
1857 SOCKBUF_UNLOCK(&so->so_rcv);
1862 sbunlock(&so->so_rcv);
1867 * Optimized version of soreceive() for simple datagram cases from userspace.
1868 * Unlike in the stream case, we're able to drop a datagram if copyout()
1869 * fails, and because we handle datagrams atomically, we don't need to use a
1870 * sleep lock to prevent I/O interlacing.
1873 soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
1874 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1876 struct mbuf *m, *m2;
1877 int flags, len, error;
1878 struct protosw *pr = so->so_proto;
1879 struct mbuf *nextrecord;
1883 if (controlp != NULL)
1886 flags = *flagsp &~ MSG_EOR;
1891 * For any complicated cases, fall back to the full
1892 * soreceive_generic().
1894 if (mp0 != NULL || (flags & MSG_PEEK) || (flags & MSG_OOB))
1895 return (soreceive_generic(so, psa, uio, mp0, controlp,
1899 * Enforce restrictions on use.
1901 KASSERT((pr->pr_flags & PR_WANTRCVD) == 0,
1902 ("soreceive_dgram: wantrcvd"));
1903 KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic"));
1904 KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0,
1905 ("soreceive_dgram: SBS_RCVATMARK"));
1906 KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0,
1907 ("soreceive_dgram: P_CONNREQUIRED"));
1910 * Loop blocking while waiting for a datagram.
1912 SOCKBUF_LOCK(&so->so_rcv);
1913 while ((m = so->so_rcv.sb_mb) == NULL) {
1914 KASSERT(so->so_rcv.sb_cc == 0,
1915 ("soreceive_dgram: sb_mb NULL but sb_cc %u",
1918 error = so->so_error;
1920 SOCKBUF_UNLOCK(&so->so_rcv);
1923 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
1924 uio->uio_resid == 0) {
1925 SOCKBUF_UNLOCK(&so->so_rcv);
1928 if ((so->so_state & SS_NBIO) ||
1929 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1930 SOCKBUF_UNLOCK(&so->so_rcv);
1931 return (EWOULDBLOCK);
1933 SBLASTRECORDCHK(&so->so_rcv);
1934 SBLASTMBUFCHK(&so->so_rcv);
1935 error = sbwait(&so->so_rcv);
1937 SOCKBUF_UNLOCK(&so->so_rcv);
1941 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1944 uio->uio_td->td_ru.ru_msgrcv++;
1945 SBLASTRECORDCHK(&so->so_rcv);
1946 SBLASTMBUFCHK(&so->so_rcv);
1947 nextrecord = m->m_nextpkt;
1948 if (nextrecord == NULL) {
1949 KASSERT(so->so_rcv.sb_lastrecord == m,
1950 ("soreceive_dgram: lastrecord != m"));
1953 KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord,
1954 ("soreceive_dgram: m_nextpkt != nextrecord"));
1957 * Pull 'm' and its chain off the front of the packet queue.
1959 so->so_rcv.sb_mb = NULL;
1960 sockbuf_pushsync(&so->so_rcv, nextrecord);
1963 * Walk 'm's chain and free that many bytes from the socket buffer.
1965 for (m2 = m; m2 != NULL; m2 = m2->m_next)
1966 sbfree(&so->so_rcv, m2);
1969 * Do a few last checks before we let go of the lock.
1971 SBLASTRECORDCHK(&so->so_rcv);
1972 SBLASTMBUFCHK(&so->so_rcv);
1973 SOCKBUF_UNLOCK(&so->so_rcv);
1975 if (pr->pr_flags & PR_ADDR) {
1976 KASSERT(m->m_type == MT_SONAME,
1977 ("m->m_type == %d", m->m_type));
1979 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
1984 /* XXXRW: Can this happen? */
1989 * Packet to copyout() is now in 'm' and it is disconnected from the
1992 * Process one or more MT_CONTROL mbufs present before any data mbufs
1993 * in the first mbuf chain on the socket buffer. We call into the
1994 * protocol to perform externalization (or freeing if controlp ==
1997 if (m->m_type == MT_CONTROL) {
1998 struct mbuf *cm = NULL, *cmn;
1999 struct mbuf **cme = &cm;
2005 cme = &(*cme)->m_next;
2007 } while (m != NULL && m->m_type == MT_CONTROL);
2008 while (cm != NULL) {
2011 if (pr->pr_domain->dom_externalize != NULL) {
2012 error = (*pr->pr_domain->dom_externalize)
2014 } else if (controlp != NULL)
2018 if (controlp != NULL) {
2019 while (*controlp != NULL)
2020 controlp = &(*controlp)->m_next;
2025 KASSERT(m->m_type == MT_DATA, ("soreceive_dgram: !data"));
2027 while (m != NULL && uio->uio_resid > 0) {
2028 len = uio->uio_resid;
2031 error = uiomove(mtod(m, char *), (int)len, uio);
2047 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
2048 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2051 return (so->so_proto->pr_usrreqs->pru_soreceive(so, psa, uio, mp0,
2056 soshutdown(struct socket *so, int how)
2058 struct protosw *pr = so->so_proto;
2061 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
2063 if (pr->pr_usrreqs->pru_flush != NULL) {
2064 (*pr->pr_usrreqs->pru_flush)(so, how);
2068 if (how != SHUT_RD) {
2069 CURVNET_SET(so->so_vnet);
2070 error = (*pr->pr_usrreqs->pru_shutdown)(so);
2078 sorflush(struct socket *so)
2080 struct sockbuf *sb = &so->so_rcv;
2081 struct protosw *pr = so->so_proto;
2085 * In order to avoid calling dom_dispose with the socket buffer mutex
2086 * held, and in order to generally avoid holding the lock for a long
2087 * time, we make a copy of the socket buffer and clear the original
2088 * (except locks, state). The new socket buffer copy won't have
2089 * initialized locks so we can only call routines that won't use or
2090 * assert those locks.
2092 * Dislodge threads currently blocked in receive and wait to acquire
2093 * a lock against other simultaneous readers before clearing the
2094 * socket buffer. Don't let our acquire be interrupted by a signal
2095 * despite any existing socket disposition on interruptable waiting.
2097 CURVNET_SET(so->so_vnet);
2099 (void) sblock(sb, SBL_WAIT | SBL_NOINTR);
2102 * Invalidate/clear most of the sockbuf structure, but leave selinfo
2103 * and mutex data unchanged.
2106 bzero(&asb, offsetof(struct sockbuf, sb_startzero));
2107 bcopy(&sb->sb_startzero, &asb.sb_startzero,
2108 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2109 bzero(&sb->sb_startzero,
2110 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2115 * Dispose of special rights and flush the socket buffer. Don't call
2116 * any unsafe routines (that rely on locks being initialized) on asb.
2118 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
2119 (*pr->pr_domain->dom_dispose)(asb.sb_mb);
2120 sbrelease_internal(&asb, so);
2125 * Perhaps this routine, and sooptcopyout(), below, ought to come in an
2126 * additional variant to handle the case where the option value needs to be
2127 * some kind of integer, but not a specific size. In addition to their use
2128 * here, these functions are also called by the protocol-level pr_ctloutput()
2132 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2137 * If the user gives us more than we wanted, we ignore it, but if we
2138 * don't get the minimum length the caller wants, we return EINVAL.
2139 * On success, sopt->sopt_valsize is set to however much we actually
2142 if ((valsize = sopt->sopt_valsize) < minlen)
2145 sopt->sopt_valsize = valsize = len;
2147 if (sopt->sopt_td != NULL)
2148 return (copyin(sopt->sopt_val, buf, valsize));
2150 bcopy(sopt->sopt_val, buf, valsize);
2155 * Kernel version of setsockopt(2).
2157 * XXX: optlen is size_t, not socklen_t
2160 so_setsockopt(struct socket *so, int level, int optname, void *optval,
2163 struct sockopt sopt;
2165 sopt.sopt_level = level;
2166 sopt.sopt_name = optname;
2167 sopt.sopt_dir = SOPT_SET;
2168 sopt.sopt_val = optval;
2169 sopt.sopt_valsize = optlen;
2170 sopt.sopt_td = NULL;
2171 return (sosetopt(so, &sopt));
2175 sosetopt(struct socket *so, struct sockopt *sopt)
2186 if (sopt->sopt_level != SOL_SOCKET) {
2187 if (so->so_proto && so->so_proto->pr_ctloutput)
2188 return ((*so->so_proto->pr_ctloutput)
2190 error = ENOPROTOOPT;
2192 switch (sopt->sopt_name) {
2194 case SO_ACCEPTFILTER:
2195 error = do_setopt_accept_filter(so, sopt);
2201 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
2206 so->so_linger = l.l_linger;
2208 so->so_options |= SO_LINGER;
2210 so->so_options &= ~SO_LINGER;
2217 case SO_USELOOPBACK:
2227 error = sooptcopyin(sopt, &optval, sizeof optval,
2233 so->so_options |= sopt->sopt_name;
2235 so->so_options &= ~sopt->sopt_name;
2240 error = sooptcopyin(sopt, &optval, sizeof optval,
2242 if (optval < 1 || optval > rt_numfibs) {
2246 if ((so->so_proto->pr_domain->dom_family == PF_INET) ||
2247 (so->so_proto->pr_domain->dom_family == PF_ROUTE)) {
2248 so->so_fibnum = optval;
2249 /* Note: ignore error */
2250 if (so->so_proto && so->so_proto->pr_ctloutput)
2251 (*so->so_proto->pr_ctloutput)(so, sopt);
2260 error = sooptcopyin(sopt, &optval, sizeof optval,
2266 * Values < 1 make no sense for any of these options,
2274 switch (sopt->sopt_name) {
2277 if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
2278 &so->so_snd : &so->so_rcv, (u_long)optval,
2279 so, curthread) == 0) {
2283 (sopt->sopt_name == SO_SNDBUF ? &so->so_snd :
2284 &so->so_rcv)->sb_flags &= ~SB_AUTOSIZE;
2288 * Make sure the low-water is never greater than the
2292 SOCKBUF_LOCK(&so->so_snd);
2293 so->so_snd.sb_lowat =
2294 (optval > so->so_snd.sb_hiwat) ?
2295 so->so_snd.sb_hiwat : optval;
2296 SOCKBUF_UNLOCK(&so->so_snd);
2299 SOCKBUF_LOCK(&so->so_rcv);
2300 so->so_rcv.sb_lowat =
2301 (optval > so->so_rcv.sb_hiwat) ?
2302 so->so_rcv.sb_hiwat : optval;
2303 SOCKBUF_UNLOCK(&so->so_rcv);
2311 if (SV_CURPROC_FLAG(SV_ILP32)) {
2312 struct timeval32 tv32;
2314 error = sooptcopyin(sopt, &tv32, sizeof tv32,
2316 CP(tv32, tv, tv_sec);
2317 CP(tv32, tv, tv_usec);
2320 error = sooptcopyin(sopt, &tv, sizeof tv,
2325 /* assert(hz > 0); */
2326 if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
2327 tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
2331 /* assert(tick > 0); */
2332 /* assert(ULONG_MAX - INT_MAX >= 1000000); */
2333 val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
2334 if (val > INT_MAX) {
2338 if (val == 0 && tv.tv_usec != 0)
2341 switch (sopt->sopt_name) {
2343 so->so_snd.sb_timeo = val;
2346 so->so_rcv.sb_timeo = val;
2353 error = sooptcopyin(sopt, &extmac, sizeof extmac,
2357 error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
2365 error = ENOPROTOOPT;
2368 if (error == 0 && so->so_proto != NULL &&
2369 so->so_proto->pr_ctloutput != NULL) {
2370 (void) ((*so->so_proto->pr_ctloutput)
2379 * Helper routine for getsockopt.
2382 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
2390 * Documented get behavior is that we always return a value, possibly
2391 * truncated to fit in the user's buffer. Traditional behavior is
2392 * that we always tell the user precisely how much we copied, rather
2393 * than something useful like the total amount we had available for
2394 * her. Note that this interface is not idempotent; the entire
2395 * answer must generated ahead of time.
2397 valsize = min(len, sopt->sopt_valsize);
2398 sopt->sopt_valsize = valsize;
2399 if (sopt->sopt_val != NULL) {
2400 if (sopt->sopt_td != NULL)
2401 error = copyout(buf, sopt->sopt_val, valsize);
2403 bcopy(buf, sopt->sopt_val, valsize);
2409 sogetopt(struct socket *so, struct sockopt *sopt)
2419 if (sopt->sopt_level != SOL_SOCKET) {
2420 if (so->so_proto && so->so_proto->pr_ctloutput) {
2421 return ((*so->so_proto->pr_ctloutput)
2424 return (ENOPROTOOPT);
2426 switch (sopt->sopt_name) {
2428 case SO_ACCEPTFILTER:
2429 error = do_getopt_accept_filter(so, sopt);
2434 l.l_onoff = so->so_options & SO_LINGER;
2435 l.l_linger = so->so_linger;
2437 error = sooptcopyout(sopt, &l, sizeof l);
2440 case SO_USELOOPBACK:
2452 optval = so->so_options & sopt->sopt_name;
2454 error = sooptcopyout(sopt, &optval, sizeof optval);
2458 optval = so->so_type;
2463 optval = so->so_error;
2469 optval = so->so_snd.sb_hiwat;
2473 optval = so->so_rcv.sb_hiwat;
2477 optval = so->so_snd.sb_lowat;
2481 optval = so->so_rcv.sb_lowat;
2486 optval = (sopt->sopt_name == SO_SNDTIMEO ?
2487 so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
2489 tv.tv_sec = optval / hz;
2490 tv.tv_usec = (optval % hz) * tick;
2492 if (SV_CURPROC_FLAG(SV_ILP32)) {
2493 struct timeval32 tv32;
2495 CP(tv, tv32, tv_sec);
2496 CP(tv, tv32, tv_usec);
2497 error = sooptcopyout(sopt, &tv32, sizeof tv32);
2500 error = sooptcopyout(sopt, &tv, sizeof tv);
2505 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2509 error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
2513 error = sooptcopyout(sopt, &extmac, sizeof extmac);
2521 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2525 error = mac_getsockopt_peerlabel(
2526 sopt->sopt_td->td_ucred, so, &extmac);
2529 error = sooptcopyout(sopt, &extmac, sizeof extmac);
2535 case SO_LISTENQLIMIT:
2536 optval = so->so_qlimit;
2540 optval = so->so_qlen;
2543 case SO_LISTENINCQLEN:
2544 optval = so->so_incqlen;
2548 error = ENOPROTOOPT;
2555 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
2557 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
2559 struct mbuf *m, *m_prev;
2560 int sopt_size = sopt->sopt_valsize;
2562 MGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT, MT_DATA);
2565 if (sopt_size > MLEN) {
2566 MCLGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT);
2567 if ((m->m_flags & M_EXT) == 0) {
2571 m->m_len = min(MCLBYTES, sopt_size);
2573 m->m_len = min(MLEN, sopt_size);
2575 sopt_size -= m->m_len;
2580 MGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT, MT_DATA);
2585 if (sopt_size > MLEN) {
2586 MCLGET(m, sopt->sopt_td != NULL ? M_WAIT :
2588 if ((m->m_flags & M_EXT) == 0) {
2593 m->m_len = min(MCLBYTES, sopt_size);
2595 m->m_len = min(MLEN, sopt_size);
2597 sopt_size -= m->m_len;
2604 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
2606 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
2608 struct mbuf *m0 = m;
2610 if (sopt->sopt_val == NULL)
2612 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2613 if (sopt->sopt_td != NULL) {
2616 error = copyin(sopt->sopt_val, mtod(m, char *),
2623 bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
2624 sopt->sopt_valsize -= m->m_len;
2625 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2628 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
2629 panic("ip6_sooptmcopyin");
2633 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
2635 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
2637 struct mbuf *m0 = m;
2640 if (sopt->sopt_val == NULL)
2642 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2643 if (sopt->sopt_td != NULL) {
2646 error = copyout(mtod(m, char *), sopt->sopt_val,
2653 bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
2654 sopt->sopt_valsize -= m->m_len;
2655 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2656 valsize += m->m_len;
2660 /* enough soopt buffer should be given from user-land */
2664 sopt->sopt_valsize = valsize;
2669 * sohasoutofband(): protocol notifies socket layer of the arrival of new
2670 * out-of-band data, which will then notify socket consumers.
2673 sohasoutofband(struct socket *so)
2676 if (so->so_sigio != NULL)
2677 pgsigio(&so->so_sigio, SIGURG, 0);
2678 selwakeuppri(&so->so_rcv.sb_sel, PSOCK);
2682 sopoll(struct socket *so, int events, struct ucred *active_cred,
2686 return (so->so_proto->pr_usrreqs->pru_sopoll(so, events, active_cred,
2691 sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
2696 SOCKBUF_LOCK(&so->so_snd);
2697 SOCKBUF_LOCK(&so->so_rcv);
2698 if (events & (POLLIN | POLLRDNORM))
2700 revents |= events & (POLLIN | POLLRDNORM);
2702 if (events & POLLINIGNEOF)
2703 if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
2704 !TAILQ_EMPTY(&so->so_comp) || so->so_error)
2705 revents |= POLLINIGNEOF;
2707 if (events & (POLLOUT | POLLWRNORM))
2708 if (sowriteable(so))
2709 revents |= events & (POLLOUT | POLLWRNORM);
2711 if (events & (POLLPRI | POLLRDBAND))
2712 if (so->so_oobmark || (so->so_rcv.sb_state & SBS_RCVATMARK))
2713 revents |= events & (POLLPRI | POLLRDBAND);
2717 (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
2719 selrecord(td, &so->so_rcv.sb_sel);
2720 so->so_rcv.sb_flags |= SB_SEL;
2723 if (events & (POLLOUT | POLLWRNORM)) {
2724 selrecord(td, &so->so_snd.sb_sel);
2725 so->so_snd.sb_flags |= SB_SEL;
2729 SOCKBUF_UNLOCK(&so->so_rcv);
2730 SOCKBUF_UNLOCK(&so->so_snd);
2735 soo_kqfilter(struct file *fp, struct knote *kn)
2737 struct socket *so = kn->kn_fp->f_data;
2740 switch (kn->kn_filter) {
2742 if (so->so_options & SO_ACCEPTCONN)
2743 kn->kn_fop = &solisten_filtops;
2745 kn->kn_fop = &soread_filtops;
2749 kn->kn_fop = &sowrite_filtops;
2757 knlist_add(&sb->sb_sel.si_note, kn, 1);
2758 sb->sb_flags |= SB_KNOTE;
2764 * Some routines that return EOPNOTSUPP for entry points that are not
2765 * supported by a protocol. Fill in as needed.
2768 pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
2775 pru_attach_notsupp(struct socket *so, int proto, struct thread *td)
2782 pru_bind_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
2789 pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
2796 pru_connect2_notsupp(struct socket *so1, struct socket *so2)
2803 pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
2804 struct ifnet *ifp, struct thread *td)
2811 pru_disconnect_notsupp(struct socket *so)
2818 pru_listen_notsupp(struct socket *so, int backlog, struct thread *td)
2825 pru_peeraddr_notsupp(struct socket *so, struct sockaddr **nam)
2832 pru_rcvd_notsupp(struct socket *so, int flags)
2839 pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
2846 pru_send_notsupp(struct socket *so, int flags, struct mbuf *m,
2847 struct sockaddr *addr, struct mbuf *control, struct thread *td)
2854 * This isn't really a ``null'' operation, but it's the default one and
2855 * doesn't do anything destructive.
2858 pru_sense_null(struct socket *so, struct stat *sb)
2861 sb->st_blksize = so->so_snd.sb_hiwat;
2866 pru_shutdown_notsupp(struct socket *so)
2873 pru_sockaddr_notsupp(struct socket *so, struct sockaddr **nam)
2880 pru_sosend_notsupp(struct socket *so, struct sockaddr *addr, struct uio *uio,
2881 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
2888 pru_soreceive_notsupp(struct socket *so, struct sockaddr **paddr,
2889 struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2896 pru_sopoll_notsupp(struct socket *so, int events, struct ucred *cred,
2904 filt_sordetach(struct knote *kn)
2906 struct socket *so = kn->kn_fp->f_data;
2908 SOCKBUF_LOCK(&so->so_rcv);
2909 knlist_remove(&so->so_rcv.sb_sel.si_note, kn, 1);
2910 if (knlist_empty(&so->so_rcv.sb_sel.si_note))
2911 so->so_rcv.sb_flags &= ~SB_KNOTE;
2912 SOCKBUF_UNLOCK(&so->so_rcv);
2917 filt_soread(struct knote *kn, long hint)
2921 so = kn->kn_fp->f_data;
2922 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2924 kn->kn_data = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
2925 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2926 kn->kn_flags |= EV_EOF;
2927 kn->kn_fflags = so->so_error;
2929 } else if (so->so_error) /* temporary udp error */
2931 else if (kn->kn_sfflags & NOTE_LOWAT)
2932 return (kn->kn_data >= kn->kn_sdata);
2934 return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat);
2938 filt_sowdetach(struct knote *kn)
2940 struct socket *so = kn->kn_fp->f_data;
2942 SOCKBUF_LOCK(&so->so_snd);
2943 knlist_remove(&so->so_snd.sb_sel.si_note, kn, 1);
2944 if (knlist_empty(&so->so_snd.sb_sel.si_note))
2945 so->so_snd.sb_flags &= ~SB_KNOTE;
2946 SOCKBUF_UNLOCK(&so->so_snd);
2951 filt_sowrite(struct knote *kn, long hint)
2955 so = kn->kn_fp->f_data;
2956 SOCKBUF_LOCK_ASSERT(&so->so_snd);
2957 kn->kn_data = sbspace(&so->so_snd);
2958 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2959 kn->kn_flags |= EV_EOF;
2960 kn->kn_fflags = so->so_error;
2962 } else if (so->so_error) /* temporary udp error */
2964 else if (((so->so_state & SS_ISCONNECTED) == 0) &&
2965 (so->so_proto->pr_flags & PR_CONNREQUIRED))
2967 else if (kn->kn_sfflags & NOTE_LOWAT)
2968 return (kn->kn_data >= kn->kn_sdata);
2970 return (kn->kn_data >= so->so_snd.sb_lowat);
2975 filt_solisten(struct knote *kn, long hint)
2977 struct socket *so = kn->kn_fp->f_data;
2979 kn->kn_data = so->so_qlen;
2980 return (! TAILQ_EMPTY(&so->so_comp));
2984 socheckuid(struct socket *so, uid_t uid)
2989 if (so->so_cred->cr_uid != uid)
2995 sysctl_somaxconn(SYSCTL_HANDLER_ARGS)
3001 error = sysctl_handle_int(oidp, &val, 0, req);
3002 if (error || !req->newptr )
3005 if (val < 1 || val > USHRT_MAX)
3013 * These functions are used by protocols to notify the socket layer (and its
3014 * consumers) of state changes in the sockets driven by protocol-side events.
3018 * Procedures to manipulate state flags of socket and do appropriate wakeups.
3020 * Normal sequence from the active (originating) side is that
3021 * soisconnecting() is called during processing of connect() call, resulting
3022 * in an eventual call to soisconnected() if/when the connection is
3023 * established. When the connection is torn down soisdisconnecting() is
3024 * called during processing of disconnect() call, and soisdisconnected() is
3025 * called when the connection to the peer is totally severed. The semantics
3026 * of these routines are such that connectionless protocols can call
3027 * soisconnected() and soisdisconnected() only, bypassing the in-progress
3028 * calls when setting up a ``connection'' takes no time.
3030 * From the passive side, a socket is created with two queues of sockets:
3031 * so_incomp for connections in progress and so_comp for connections already
3032 * made and awaiting user acceptance. As a protocol is preparing incoming
3033 * connections, it creates a socket structure queued on so_incomp by calling
3034 * sonewconn(). When the connection is established, soisconnected() is
3035 * called, and transfers the socket structure to so_comp, making it available
3038 * If a socket is closed with sockets on either so_incomp or so_comp, these
3039 * sockets are dropped.
3041 * If higher-level protocols are implemented in the kernel, the wakeups done
3042 * here will sometimes cause software-interrupt process scheduling.
3045 soisconnecting(struct socket *so)
3049 so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
3050 so->so_state |= SS_ISCONNECTING;
3055 soisconnected(struct socket *so)
3057 struct socket *head;
3061 so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
3062 so->so_state |= SS_ISCONNECTED;
3064 if (head != NULL && (so->so_qstate & SQ_INCOMP)) {
3065 if ((so->so_options & SO_ACCEPTFILTER) == 0) {
3067 TAILQ_REMOVE(&head->so_incomp, so, so_list);
3069 so->so_qstate &= ~SQ_INCOMP;
3070 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
3072 so->so_qstate |= SQ_COMP;
3075 wakeup_one(&head->so_timeo);
3079 head->so_accf->so_accept_filter->accf_callback;
3080 so->so_upcallarg = head->so_accf->so_accept_filter_arg;
3081 so->so_rcv.sb_flags |= SB_UPCALL;
3082 so->so_options &= ~SO_ACCEPTFILTER;
3084 so->so_upcall(so, so->so_upcallarg, M_DONTWAIT);
3090 wakeup(&so->so_timeo);
3096 soisdisconnecting(struct socket *so)
3100 * Note: This code assumes that SOCK_LOCK(so) and
3101 * SOCKBUF_LOCK(&so->so_rcv) are the same.
3103 SOCKBUF_LOCK(&so->so_rcv);
3104 so->so_state &= ~SS_ISCONNECTING;
3105 so->so_state |= SS_ISDISCONNECTING;
3106 so->so_rcv.sb_state |= SBS_CANTRCVMORE;
3107 sorwakeup_locked(so);
3108 SOCKBUF_LOCK(&so->so_snd);
3109 so->so_snd.sb_state |= SBS_CANTSENDMORE;
3110 sowwakeup_locked(so);
3111 wakeup(&so->so_timeo);
3115 soisdisconnected(struct socket *so)
3119 * Note: This code assumes that SOCK_LOCK(so) and
3120 * SOCKBUF_LOCK(&so->so_rcv) are the same.
3122 SOCKBUF_LOCK(&so->so_rcv);
3123 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
3124 so->so_state |= SS_ISDISCONNECTED;
3125 so->so_rcv.sb_state |= SBS_CANTRCVMORE;
3126 sorwakeup_locked(so);
3127 SOCKBUF_LOCK(&so->so_snd);
3128 so->so_snd.sb_state |= SBS_CANTSENDMORE;
3129 sbdrop_locked(&so->so_snd, so->so_snd.sb_cc);
3130 sowwakeup_locked(so);
3131 wakeup(&so->so_timeo);
3135 * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
3138 sodupsockaddr(const struct sockaddr *sa, int mflags)
3140 struct sockaddr *sa2;
3142 sa2 = malloc(sa->sa_len, M_SONAME, mflags);
3144 bcopy(sa, sa2, sa->sa_len);
3149 * Create an external-format (``xsocket'') structure using the information in
3150 * the kernel-format socket structure pointed to by so. This is done to
3151 * reduce the spew of irrelevant information over this interface, to isolate
3152 * user code from changes in the kernel structure, and potentially to provide
3153 * information-hiding if we decide that some of this information should be
3154 * hidden from users.
3157 sotoxsocket(struct socket *so, struct xsocket *xso)
3160 xso->xso_len = sizeof *xso;
3162 xso->so_type = so->so_type;
3163 xso->so_options = so->so_options;
3164 xso->so_linger = so->so_linger;
3165 xso->so_state = so->so_state;
3166 xso->so_pcb = so->so_pcb;
3167 xso->xso_protocol = so->so_proto->pr_protocol;
3168 xso->xso_family = so->so_proto->pr_domain->dom_family;
3169 xso->so_qlen = so->so_qlen;
3170 xso->so_incqlen = so->so_incqlen;
3171 xso->so_qlimit = so->so_qlimit;
3172 xso->so_timeo = so->so_timeo;
3173 xso->so_error = so->so_error;
3174 xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
3175 xso->so_oobmark = so->so_oobmark;
3176 sbtoxsockbuf(&so->so_snd, &xso->so_snd);
3177 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
3178 xso->so_uid = so->so_cred->cr_uid;
3183 * Socket accessor functions to provide external consumers with
3184 * a safe interface to socket state
3189 so_listeners_apply_all(struct socket *so, void (*func)(struct socket *, void *), void *arg)
3192 TAILQ_FOREACH(so, &so->so_comp, so_list)
3197 so_sockbuf_rcv(struct socket *so)
3200 return (&so->so_rcv);
3204 so_sockbuf_snd(struct socket *so)
3207 return (&so->so_snd);
3211 so_state_get(const struct socket *so)
3214 return (so->so_state);
3218 so_state_set(struct socket *so, int val)
3225 so_options_get(const struct socket *so)
3228 return (so->so_options);
3232 so_options_set(struct socket *so, int val)
3235 so->so_options = val;
3239 so_error_get(const struct socket *so)
3242 return (so->so_error);
3246 so_error_set(struct socket *so, int val)
3253 so_linger_get(const struct socket *so)
3256 return (so->so_linger);
3260 so_linger_set(struct socket *so, int val)
3263 so->so_linger = val;
3267 so_protosw_get(const struct socket *so)
3270 return (so->so_proto);
3274 so_protosw_set(struct socket *so, struct protosw *val)
3281 so_sorwakeup(struct socket *so)
3288 so_sowwakeup(struct socket *so)
3295 so_sorwakeup_locked(struct socket *so)
3298 sorwakeup_locked(so);
3302 so_sowwakeup_locked(struct socket *so)
3305 sowwakeup_locked(so);
3309 so_lock(struct socket *so)
3315 so_unlock(struct socket *so)