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"
102 #include "opt_zero.h"
103 #include "opt_compat.h"
105 #include <sys/param.h>
106 #include <sys/systm.h>
107 #include <sys/fcntl.h>
108 #include <sys/limits.h>
109 #include <sys/lock.h>
111 #include <sys/malloc.h>
112 #include <sys/mbuf.h>
113 #include <sys/mutex.h>
114 #include <sys/domain.h>
115 #include <sys/file.h> /* for struct knote */
116 #include <sys/kernel.h>
117 #include <sys/event.h>
118 #include <sys/eventhandler.h>
119 #include <sys/poll.h>
120 #include <sys/proc.h>
121 #include <sys/protosw.h>
122 #include <sys/socket.h>
123 #include <sys/socketvar.h>
124 #include <sys/resourcevar.h>
125 #include <net/route.h>
126 #include <sys/signalvar.h>
127 #include <sys/stat.h>
129 #include <sys/sysctl.h>
131 #include <sys/jail.h>
132 #include <sys/vimage.h>
134 #include <security/mac/mac_framework.h>
139 #include <sys/mount.h>
140 #include <sys/sysent.h>
141 #include <compat/freebsd32/freebsd32.h>
144 static int soreceive_rcvoob(struct socket *so, struct uio *uio,
147 static void filt_sordetach(struct knote *kn);
148 static int filt_soread(struct knote *kn, long hint);
149 static void filt_sowdetach(struct knote *kn);
150 static int filt_sowrite(struct knote *kn, long hint);
151 static int filt_solisten(struct knote *kn, long hint);
153 static struct filterops solisten_filtops =
154 { 1, NULL, filt_sordetach, filt_solisten };
155 static struct filterops soread_filtops =
156 { 1, NULL, filt_sordetach, filt_soread };
157 static struct filterops sowrite_filtops =
158 { 1, NULL, filt_sowdetach, filt_sowrite };
160 uma_zone_t socket_zone;
161 so_gen_t so_gencnt; /* generation count for sockets */
165 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
166 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
168 static int somaxconn = SOMAXCONN;
169 static int sysctl_somaxconn(SYSCTL_HANDLER_ARGS);
170 /* XXX: we dont have SYSCTL_USHORT */
171 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLTYPE_UINT | CTLFLAG_RW,
172 0, sizeof(int), sysctl_somaxconn, "I", "Maximum pending socket connection "
174 static int numopensockets;
175 SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
176 &numopensockets, 0, "Number of open sockets");
177 #ifdef ZERO_COPY_SOCKETS
178 /* These aren't static because they're used in other files. */
179 int so_zero_copy_send = 1;
180 int so_zero_copy_receive = 1;
181 SYSCTL_NODE(_kern_ipc, OID_AUTO, zero_copy, CTLFLAG_RD, 0,
182 "Zero copy controls");
183 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, receive, CTLFLAG_RW,
184 &so_zero_copy_receive, 0, "Enable zero copy receive");
185 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, send, CTLFLAG_RW,
186 &so_zero_copy_send, 0, "Enable zero copy send");
187 #endif /* ZERO_COPY_SOCKETS */
190 * accept_mtx locks down per-socket fields relating to accept queues. See
191 * socketvar.h for an annotation of the protected fields of struct socket.
193 struct mtx accept_mtx;
194 MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
197 * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
200 static struct mtx so_global_mtx;
201 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
204 * General IPC sysctl name space, used by sockets and a variety of other IPC
207 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
210 * Sysctl to get and set the maximum global sockets limit. Notify protocols
211 * of the change so that they can update their dependent limits as required.
214 sysctl_maxsockets(SYSCTL_HANDLER_ARGS)
216 int error, newmaxsockets;
218 newmaxsockets = maxsockets;
219 error = sysctl_handle_int(oidp, &newmaxsockets, 0, req);
220 if (error == 0 && req->newptr) {
221 if (newmaxsockets > maxsockets) {
222 maxsockets = newmaxsockets;
223 if (maxsockets > ((maxfiles / 4) * 3)) {
224 maxfiles = (maxsockets * 5) / 4;
225 maxfilesperproc = (maxfiles * 9) / 10;
227 EVENTHANDLER_INVOKE(maxsockets_change);
234 SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets, CTLTYPE_INT|CTLFLAG_RW,
235 &maxsockets, 0, sysctl_maxsockets, "IU",
236 "Maximum number of sockets avaliable");
239 * Initialise maxsockets. This SYSINIT must be run after
243 init_maxsockets(void *ignored)
246 TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
247 maxsockets = imax(maxsockets, imax(maxfiles, nmbclusters));
249 SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);
252 * Socket operation routines. These routines are called by the routines in
253 * sys_socket.c or from a system process, and implement the semantics of
254 * socket operations by switching out to the protocol specific routines.
258 * Get a socket structure from our zone, and initialize it. Note that it
259 * would probably be better to allocate socket and PCB at the same time, but
260 * I'm not convinced that all the protocols can be easily modified to do
263 * soalloc() returns a socket with a ref count of 0.
265 static struct socket *
266 soalloc(struct vnet *vnet)
270 so = uma_zalloc(socket_zone, M_NOWAIT | M_ZERO);
274 if (mac_socket_init(so, M_NOWAIT) != 0) {
275 uma_zfree(socket_zone, so);
279 SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
280 SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
281 sx_init(&so->so_snd.sb_sx, "so_snd_sx");
282 sx_init(&so->so_rcv.sb_sx, "so_rcv_sx");
283 TAILQ_INIT(&so->so_aiojobq);
284 mtx_lock(&so_global_mtx);
285 so->so_gencnt = ++so_gencnt;
288 ++vnet->sockcnt; /* Locked with so_global_mtx. */
291 mtx_unlock(&so_global_mtx);
296 * Free the storage associated with a socket at the socket layer, tear down
297 * locks, labels, etc. All protocol state is assumed already to have been
298 * torn down (and possibly never set up) by the caller.
301 sodealloc(struct socket *so)
304 KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
305 KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
307 mtx_lock(&so_global_mtx);
308 so->so_gencnt = ++so_gencnt;
309 --numopensockets; /* Could be below, but faster here. */
311 --so->so_vnet->sockcnt;
313 mtx_unlock(&so_global_mtx);
314 if (so->so_rcv.sb_hiwat)
315 (void)chgsbsize(so->so_cred->cr_uidinfo,
316 &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
317 if (so->so_snd.sb_hiwat)
318 (void)chgsbsize(so->so_cred->cr_uidinfo,
319 &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
321 /* remove acccept filter if one is present. */
322 if (so->so_accf != NULL)
323 do_setopt_accept_filter(so, NULL);
326 mac_socket_destroy(so);
329 sx_destroy(&so->so_snd.sb_sx);
330 sx_destroy(&so->so_rcv.sb_sx);
331 SOCKBUF_LOCK_DESTROY(&so->so_snd);
332 SOCKBUF_LOCK_DESTROY(&so->so_rcv);
333 uma_zfree(socket_zone, so);
337 * socreate returns a socket with a ref count of 1. The socket should be
338 * closed with soclose().
341 socreate(int dom, struct socket **aso, int type, int proto,
342 struct ucred *cred, struct thread *td)
349 prp = pffindproto(dom, proto, type);
351 prp = pffindtype(dom, type);
353 if (prp == NULL || prp->pr_usrreqs->pru_attach == NULL ||
354 prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
355 return (EPROTONOSUPPORT);
357 if (prison_check_af(cred, prp->pr_domain->dom_family) != 0)
358 return (EPROTONOSUPPORT);
360 if (prp->pr_type != type)
362 so = soalloc(TD_TO_VNET(td));
366 TAILQ_INIT(&so->so_incomp);
367 TAILQ_INIT(&so->so_comp);
369 so->so_cred = crhold(cred);
370 if ((prp->pr_domain->dom_family == PF_INET) ||
371 (prp->pr_domain->dom_family == PF_ROUTE))
372 so->so_fibnum = td->td_proc->p_fibnum;
377 mac_socket_create(cred, so);
379 knlist_init(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv),
381 knlist_init(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd),
385 * Auto-sizing of socket buffers is managed by the protocols and
386 * the appropriate flags must be set in the pru_attach function.
388 CURVNET_SET(so->so_vnet);
389 error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
392 KASSERT(so->so_count == 1, ("socreate: so_count %d",
403 static int regression_sonewconn_earlytest = 1;
404 SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW,
405 ®ression_sonewconn_earlytest, 0, "Perform early sonewconn limit test");
409 * When an attempt at a new connection is noted on a socket which accepts
410 * connections, sonewconn is called. If the connection is possible (subject
411 * to space constraints, etc.) then we allocate a new structure, propoerly
412 * linked into the data structure of the original socket, and return this.
413 * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
415 * Note: the ref count on the socket is 0 on return.
418 sonewconn(struct socket *head, int connstatus)
424 over = (head->so_qlen > 3 * head->so_qlimit / 2);
427 if (regression_sonewconn_earlytest && over)
432 VNET_ASSERT(head->so_vnet);
433 so = soalloc(head->so_vnet);
436 if ((head->so_options & SO_ACCEPTFILTER) != 0)
439 so->so_type = head->so_type;
440 so->so_options = head->so_options &~ SO_ACCEPTCONN;
441 so->so_linger = head->so_linger;
442 so->so_state = head->so_state | SS_NOFDREF;
443 so->so_proto = head->so_proto;
444 so->so_cred = crhold(head->so_cred);
446 mac_socket_newconn(head, so);
448 knlist_init(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv),
450 knlist_init(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd),
452 if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat) ||
453 (*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
457 so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
458 so->so_snd.sb_lowat = head->so_snd.sb_lowat;
459 so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
460 so->so_snd.sb_timeo = head->so_snd.sb_timeo;
461 so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
462 so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
463 so->so_state |= connstatus;
466 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
467 so->so_qstate |= SQ_COMP;
471 * Keep removing sockets from the head until there's room for
472 * us to insert on the tail. In pre-locking revisions, this
473 * was a simple if(), but as we could be racing with other
474 * threads and soabort() requires dropping locks, we must
475 * loop waiting for the condition to be true.
477 while (head->so_incqlen > head->so_qlimit) {
479 sp = TAILQ_FIRST(&head->so_incomp);
480 TAILQ_REMOVE(&head->so_incomp, sp, so_list);
482 sp->so_qstate &= ~SQ_INCOMP;
488 TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
489 so->so_qstate |= SQ_INCOMP;
495 wakeup_one(&head->so_timeo);
501 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
505 CURVNET_SET(so->so_vnet);
506 error = (*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td);
512 * solisten() transitions a socket from a non-listening state to a listening
513 * state, but can also be used to update the listen queue depth on an
514 * existing listen socket. The protocol will call back into the sockets
515 * layer using solisten_proto_check() and solisten_proto() to check and set
516 * socket-layer listen state. Call backs are used so that the protocol can
517 * acquire both protocol and socket layer locks in whatever order is required
520 * Protocol implementors are advised to hold the socket lock across the
521 * socket-layer test and set to avoid races at the socket layer.
524 solisten(struct socket *so, int backlog, struct thread *td)
527 return ((*so->so_proto->pr_usrreqs->pru_listen)(so, backlog, td));
531 solisten_proto_check(struct socket *so)
534 SOCK_LOCK_ASSERT(so);
536 if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
543 solisten_proto(struct socket *so, int backlog)
546 SOCK_LOCK_ASSERT(so);
548 if (backlog < 0 || backlog > somaxconn)
550 so->so_qlimit = backlog;
551 so->so_options |= SO_ACCEPTCONN;
555 * Attempt to free a socket. This should really be sotryfree().
557 * sofree() will succeed if:
559 * - There are no outstanding file descriptor references or related consumers
562 * - The socket has been closed by user space, if ever open (SS_NOFDREF).
564 * - The protocol does not have an outstanding strong reference on the socket
567 * - The socket is not in a completed connection queue, so a process has been
568 * notified that it is present. If it is removed, the user process may
569 * block in accept() despite select() saying the socket was ready.
571 * Otherwise, it will quietly abort so that a future call to sofree(), when
572 * conditions are right, can succeed.
575 sofree(struct socket *so)
577 struct protosw *pr = so->so_proto;
580 ACCEPT_LOCK_ASSERT();
581 SOCK_LOCK_ASSERT(so);
583 if ((so->so_state & SS_NOFDREF) == 0 || so->so_count != 0 ||
584 (so->so_state & SS_PROTOREF) || (so->so_qstate & SQ_COMP)) {
592 KASSERT((so->so_qstate & SQ_COMP) != 0 ||
593 (so->so_qstate & SQ_INCOMP) != 0,
594 ("sofree: so_head != NULL, but neither SQ_COMP nor "
596 KASSERT((so->so_qstate & SQ_COMP) == 0 ||
597 (so->so_qstate & SQ_INCOMP) == 0,
598 ("sofree: so->so_qstate is SQ_COMP and also SQ_INCOMP"));
599 TAILQ_REMOVE(&head->so_incomp, so, so_list);
601 so->so_qstate &= ~SQ_INCOMP;
604 KASSERT((so->so_qstate & SQ_COMP) == 0 &&
605 (so->so_qstate & SQ_INCOMP) == 0,
606 ("sofree: so_head == NULL, but still SQ_COMP(%d) or SQ_INCOMP(%d)",
607 so->so_qstate & SQ_COMP, so->so_qstate & SQ_INCOMP));
608 if (so->so_options & SO_ACCEPTCONN) {
609 KASSERT((TAILQ_EMPTY(&so->so_comp)), ("sofree: so_comp populated"));
610 KASSERT((TAILQ_EMPTY(&so->so_incomp)), ("sofree: so_comp populated"));
615 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
616 (*pr->pr_domain->dom_dispose)(so->so_rcv.sb_mb);
617 if (pr->pr_usrreqs->pru_detach != NULL)
618 (*pr->pr_usrreqs->pru_detach)(so);
621 * From this point on, we assume that no other references to this
622 * socket exist anywhere else in the stack. Therefore, no locks need
623 * to be acquired or held.
625 * We used to do a lot of socket buffer and socket locking here, as
626 * well as invoke sorflush() and perform wakeups. The direct call to
627 * dom_dispose() and sbrelease_internal() are an inlining of what was
628 * necessary from sorflush().
630 * Notice that the socket buffer and kqueue state are torn down
631 * before calling pru_detach. This means that protocols shold not
632 * assume they can perform socket wakeups, etc, in their detach code.
634 sbdestroy(&so->so_snd, so);
635 sbdestroy(&so->so_rcv, so);
636 knlist_destroy(&so->so_rcv.sb_sel.si_note);
637 knlist_destroy(&so->so_snd.sb_sel.si_note);
642 * Close a socket on last file table reference removal. Initiate disconnect
643 * if connected. Free socket when disconnect complete.
645 * This function will sorele() the socket. Note that soclose() may be called
646 * prior to the ref count reaching zero. The actual socket structure will
647 * not be freed until the ref count reaches zero.
650 soclose(struct socket *so)
654 KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
656 CURVNET_SET(so->so_vnet);
657 funsetown(&so->so_sigio);
658 if (so->so_state & SS_ISCONNECTED) {
659 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
660 error = sodisconnect(so);
664 if (so->so_options & SO_LINGER) {
665 if ((so->so_state & SS_ISDISCONNECTING) &&
666 (so->so_state & SS_NBIO))
668 while (so->so_state & SS_ISCONNECTED) {
669 error = tsleep(&so->so_timeo,
670 PSOCK | PCATCH, "soclos", so->so_linger * hz);
678 if (so->so_proto->pr_usrreqs->pru_close != NULL)
679 (*so->so_proto->pr_usrreqs->pru_close)(so);
680 if (so->so_options & SO_ACCEPTCONN) {
683 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
684 TAILQ_REMOVE(&so->so_incomp, sp, so_list);
686 sp->so_qstate &= ~SQ_INCOMP;
692 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
693 TAILQ_REMOVE(&so->so_comp, sp, so_list);
695 sp->so_qstate &= ~SQ_COMP;
705 KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
706 so->so_state |= SS_NOFDREF;
713 * soabort() is used to abruptly tear down a connection, such as when a
714 * resource limit is reached (listen queue depth exceeded), or if a listen
715 * socket is closed while there are sockets waiting to be accepted.
717 * This interface is tricky, because it is called on an unreferenced socket,
718 * and must be called only by a thread that has actually removed the socket
719 * from the listen queue it was on, or races with other threads are risked.
721 * This interface will call into the protocol code, so must not be called
722 * with any socket locks held. Protocols do call it while holding their own
723 * recursible protocol mutexes, but this is something that should be subject
724 * to review in the future.
727 soabort(struct socket *so)
731 * In as much as is possible, assert that no references to this
732 * socket are held. This is not quite the same as asserting that the
733 * current thread is responsible for arranging for no references, but
734 * is as close as we can get for now.
736 KASSERT(so->so_count == 0, ("soabort: so_count"));
737 KASSERT((so->so_state & SS_PROTOREF) == 0, ("soabort: SS_PROTOREF"));
738 KASSERT(so->so_state & SS_NOFDREF, ("soabort: !SS_NOFDREF"));
739 KASSERT((so->so_state & SQ_COMP) == 0, ("soabort: SQ_COMP"));
740 KASSERT((so->so_state & SQ_INCOMP) == 0, ("soabort: SQ_INCOMP"));
742 if (so->so_proto->pr_usrreqs->pru_abort != NULL)
743 (*so->so_proto->pr_usrreqs->pru_abort)(so);
750 soaccept(struct socket *so, struct sockaddr **nam)
755 KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
756 so->so_state &= ~SS_NOFDREF;
758 error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
763 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
767 if (so->so_options & SO_ACCEPTCONN)
770 * If protocol is connection-based, can only connect once.
771 * Otherwise, if connected, try to disconnect first. This allows
772 * user to disconnect by connecting to, e.g., a null address.
774 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
775 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
776 (error = sodisconnect(so)))) {
780 * Prevent accumulated error from previous connection from
784 CURVNET_SET(so->so_vnet);
785 error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, td);
793 soconnect2(struct socket *so1, struct socket *so2)
796 return ((*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2));
800 sodisconnect(struct socket *so)
804 if ((so->so_state & SS_ISCONNECTED) == 0)
806 if (so->so_state & SS_ISDISCONNECTING)
808 error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
812 #ifdef ZERO_COPY_SOCKETS
813 struct so_zerocopy_stats{
818 struct so_zerocopy_stats so_zerocp_stats = {0,0,0};
819 #include <netinet/in.h>
820 #include <net/route.h>
821 #include <netinet/in_pcb.h>
823 #include <vm/vm_page.h>
824 #include <vm/vm_object.h>
827 * sosend_copyin() is only used if zero copy sockets are enabled. Otherwise
828 * sosend_dgram() and sosend_generic() use m_uiotombuf().
830 * sosend_copyin() accepts a uio and prepares an mbuf chain holding part or
831 * all of the data referenced by the uio. If desired, it uses zero-copy.
832 * *space will be updated to reflect data copied in.
834 * NB: If atomic I/O is requested, the caller must already have checked that
835 * space can hold resid bytes.
837 * NB: In the event of an error, the caller may need to free the partial
838 * chain pointed to by *mpp. The contents of both *uio and *space may be
839 * modified even in the case of an error.
842 sosend_copyin(struct uio *uio, struct mbuf **retmp, int atomic, long *space,
845 struct mbuf *m, **mp, *top;
848 #ifdef ZERO_COPY_SOCKETS
855 resid = uio->uio_resid;
858 #ifdef ZERO_COPY_SOCKETS
860 #endif /* ZERO_COPY_SOCKETS */
861 if (resid >= MINCLSIZE) {
862 #ifdef ZERO_COPY_SOCKETS
864 m = m_gethdr(M_WAITOK, MT_DATA);
866 m->m_pkthdr.rcvif = NULL;
868 m = m_get(M_WAITOK, MT_DATA);
869 if (so_zero_copy_send &&
872 uio->uio_iov->iov_len>=PAGE_SIZE) {
873 so_zerocp_stats.size_ok++;
874 so_zerocp_stats.align_ok++;
875 cow_send = socow_setup(m, uio);
879 m_clget(m, M_WAITOK);
880 len = min(min(MCLBYTES, resid), *space);
882 #else /* ZERO_COPY_SOCKETS */
884 m = m_getcl(M_WAIT, MT_DATA, M_PKTHDR);
886 m->m_pkthdr.rcvif = NULL;
888 m = m_getcl(M_WAIT, MT_DATA, 0);
889 len = min(min(MCLBYTES, resid), *space);
890 #endif /* ZERO_COPY_SOCKETS */
893 m = m_gethdr(M_WAIT, MT_DATA);
895 m->m_pkthdr.rcvif = NULL;
897 len = min(min(MHLEN, resid), *space);
899 * For datagram protocols, leave room
900 * for protocol headers in first mbuf.
902 if (atomic && m && len < MHLEN)
905 m = m_get(M_WAIT, MT_DATA);
906 len = min(min(MLEN, resid), *space);
915 #ifdef ZERO_COPY_SOCKETS
919 #endif /* ZERO_COPY_SOCKETS */
920 error = uiomove(mtod(m, void *), (int)len, uio);
921 resid = uio->uio_resid;
924 top->m_pkthdr.len += len;
930 top->m_flags |= M_EOR;
933 } while (*space > 0 && atomic);
938 #endif /*ZERO_COPY_SOCKETS*/
940 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? 0 : SBL_WAIT)
943 sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
944 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
947 int clen = 0, error, dontroute;
948 #ifdef ZERO_COPY_SOCKETS
949 int atomic = sosendallatonce(so) || top;
952 KASSERT(so->so_type == SOCK_DGRAM, ("sodgram_send: !SOCK_DGRAM"));
953 KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
954 ("sodgram_send: !PR_ATOMIC"));
957 resid = uio->uio_resid;
959 resid = top->m_pkthdr.len;
961 * In theory resid should be unsigned. However, space must be
962 * signed, as it might be less than 0 if we over-committed, and we
963 * must use a signed comparison of space and resid. On the other
964 * hand, a negative resid causes us to loop sending 0-length
965 * segments to the protocol.
967 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
968 * type sockets since that's an error.
976 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
978 td->td_ru.ru_msgsnd++;
980 clen = control->m_len;
982 SOCKBUF_LOCK(&so->so_snd);
983 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
984 SOCKBUF_UNLOCK(&so->so_snd);
989 error = so->so_error;
991 SOCKBUF_UNLOCK(&so->so_snd);
994 if ((so->so_state & SS_ISCONNECTED) == 0) {
996 * `sendto' and `sendmsg' is allowed on a connection-based
997 * socket if it supports implied connect. Return ENOTCONN if
998 * not connected and no address is supplied.
1000 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1001 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1002 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1003 !(resid == 0 && clen != 0)) {
1004 SOCKBUF_UNLOCK(&so->so_snd);
1008 } else if (addr == NULL) {
1009 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1012 error = EDESTADDRREQ;
1013 SOCKBUF_UNLOCK(&so->so_snd);
1019 * Do we need MSG_OOB support in SOCK_DGRAM? Signs here may be a
1020 * problem and need fixing.
1022 space = sbspace(&so->so_snd);
1023 if (flags & MSG_OOB)
1026 SOCKBUF_UNLOCK(&so->so_snd);
1027 if (resid > space) {
1033 if (flags & MSG_EOR)
1034 top->m_flags |= M_EOR;
1036 #ifdef ZERO_COPY_SOCKETS
1037 error = sosend_copyin(uio, &top, atomic, &space, flags);
1042 * Copy the data from userland into a mbuf chain.
1043 * If no data is to be copied in, a single empty mbuf
1046 top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
1047 (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
1049 error = EFAULT; /* only possible error */
1052 space -= resid - uio->uio_resid;
1054 resid = uio->uio_resid;
1056 KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
1058 * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
1063 so->so_options |= SO_DONTROUTE;
1067 * XXX all the SBS_CANTSENDMORE checks previously done could be out
1068 * of date. We could have recieved a reset packet in an interrupt or
1069 * maybe we slept while doing page faults in uiomove() etc. We could
1070 * probably recheck again inside the locking protection here, but
1071 * there are probably other places that this also happens. We must
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 understands this flag and
1078 * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
1080 ((flags & MSG_EOF) &&
1081 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1084 /* If there is more to send set PRUS_MORETOCOME */
1085 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1086 top, addr, control, td);
1089 so->so_options &= ~SO_DONTROUTE;
1098 if (control != NULL)
1104 * Send on a socket. If send must go all at once and message is larger than
1105 * send buffering, then hard error. Lock against other senders. If must go
1106 * all at once and not enough room now, then inform user that this would
1107 * block and do nothing. Otherwise, if nonblocking, send as much as
1108 * possible. The data to be sent is described by "uio" if nonzero, otherwise
1109 * by the mbuf chain "top" (which must be null if uio is not). Data provided
1110 * in mbuf chain must be small enough to send all at once.
1112 * Returns nonzero on error, timeout or signal; callers must check for short
1113 * counts if EINTR/ERESTART are returned. Data and control buffers are freed
1117 sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
1118 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1121 int clen = 0, error, dontroute;
1122 int atomic = sosendallatonce(so) || top;
1125 resid = uio->uio_resid;
1127 resid = top->m_pkthdr.len;
1129 * In theory resid should be unsigned. However, space must be
1130 * signed, as it might be less than 0 if we over-committed, and we
1131 * must use a signed comparison of space and resid. On the other
1132 * hand, a negative resid causes us to loop sending 0-length
1133 * segments to the protocol.
1135 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
1136 * type sockets since that's an error.
1138 if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
1144 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
1145 (so->so_proto->pr_flags & PR_ATOMIC);
1147 td->td_ru.ru_msgsnd++;
1148 if (control != NULL)
1149 clen = control->m_len;
1151 error = sblock(&so->so_snd, SBLOCKWAIT(flags));
1157 SOCKBUF_LOCK(&so->so_snd);
1158 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1159 SOCKBUF_UNLOCK(&so->so_snd);
1164 error = so->so_error;
1166 SOCKBUF_UNLOCK(&so->so_snd);
1169 if ((so->so_state & SS_ISCONNECTED) == 0) {
1171 * `sendto' and `sendmsg' is allowed on a connection-
1172 * based socket if it supports implied connect.
1173 * Return ENOTCONN if not connected and no address is
1176 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1177 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1178 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1179 !(resid == 0 && clen != 0)) {
1180 SOCKBUF_UNLOCK(&so->so_snd);
1184 } else if (addr == NULL) {
1185 SOCKBUF_UNLOCK(&so->so_snd);
1186 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1189 error = EDESTADDRREQ;
1193 space = sbspace(&so->so_snd);
1194 if (flags & MSG_OOB)
1196 if ((atomic && resid > so->so_snd.sb_hiwat) ||
1197 clen > so->so_snd.sb_hiwat) {
1198 SOCKBUF_UNLOCK(&so->so_snd);
1202 if (space < resid + clen &&
1203 (atomic || space < so->so_snd.sb_lowat || space < clen)) {
1204 if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO)) {
1205 SOCKBUF_UNLOCK(&so->so_snd);
1206 error = EWOULDBLOCK;
1209 error = sbwait(&so->so_snd);
1210 SOCKBUF_UNLOCK(&so->so_snd);
1215 SOCKBUF_UNLOCK(&so->so_snd);
1220 if (flags & MSG_EOR)
1221 top->m_flags |= M_EOR;
1223 #ifdef ZERO_COPY_SOCKETS
1224 error = sosend_copyin(uio, &top, atomic,
1230 * Copy the data from userland into a mbuf
1231 * chain. If no data is to be copied in,
1232 * a single empty mbuf is returned.
1234 top = m_uiotombuf(uio, M_WAITOK, space,
1235 (atomic ? max_hdr : 0),
1236 (atomic ? M_PKTHDR : 0) |
1237 ((flags & MSG_EOR) ? M_EOR : 0));
1239 error = EFAULT; /* only possible error */
1242 space -= resid - uio->uio_resid;
1244 resid = uio->uio_resid;
1248 so->so_options |= SO_DONTROUTE;
1252 * XXX all the SBS_CANTSENDMORE checks previously
1253 * done could be out of date. We could have recieved
1254 * a reset packet in an interrupt or maybe we slept
1255 * while doing page faults in uiomove() etc. We
1256 * could probably recheck again inside the locking
1257 * protection here, but there are probably other
1258 * places that this also happens. We must rethink
1261 error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1262 (flags & MSG_OOB) ? PRUS_OOB :
1264 * If the user set MSG_EOF, the protocol understands
1265 * this flag and nothing left to send then use
1266 * PRU_SEND_EOF instead of PRU_SEND.
1268 ((flags & MSG_EOF) &&
1269 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1272 /* If there is more to send set PRUS_MORETOCOME. */
1273 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1274 top, addr, control, td);
1277 so->so_options &= ~SO_DONTROUTE;
1285 } while (resid && space > 0);
1289 sbunlock(&so->so_snd);
1293 if (control != NULL)
1299 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
1300 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1304 CURVNET_SET(so->so_vnet);
1305 error = so->so_proto->pr_usrreqs->pru_sosend(so, addr, uio, top,
1306 control, flags, td);
1312 * The part of soreceive() that implements reading non-inline out-of-band
1313 * data from a socket. For more complete comments, see soreceive(), from
1314 * which this code originated.
1316 * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
1317 * unable to return an mbuf chain to the caller.
1320 soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
1322 struct protosw *pr = so->so_proto;
1326 KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
1328 m = m_get(M_WAIT, MT_DATA);
1329 error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
1333 #ifdef ZERO_COPY_SOCKETS
1334 if (so_zero_copy_receive) {
1337 if ((m->m_flags & M_EXT)
1338 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1343 error = uiomoveco(mtod(m, void *),
1344 min(uio->uio_resid, m->m_len),
1347 #endif /* ZERO_COPY_SOCKETS */
1348 error = uiomove(mtod(m, void *),
1349 (int) min(uio->uio_resid, m->m_len), uio);
1351 } while (uio->uio_resid && error == 0 && m);
1359 * Following replacement or removal of the first mbuf on the first mbuf chain
1360 * of a socket buffer, push necessary state changes back into the socket
1361 * buffer so that other consumers see the values consistently. 'nextrecord'
1362 * is the callers locally stored value of the original value of
1363 * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
1364 * NOTE: 'nextrecord' may be NULL.
1366 static __inline void
1367 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
1370 SOCKBUF_LOCK_ASSERT(sb);
1372 * First, update for the new value of nextrecord. If necessary, make
1373 * it the first record.
1375 if (sb->sb_mb != NULL)
1376 sb->sb_mb->m_nextpkt = nextrecord;
1378 sb->sb_mb = nextrecord;
1381 * Now update any dependent socket buffer fields to reflect the new
1382 * state. This is an expanded inline of SB_EMPTY_FIXUP(), with the
1383 * addition of a second clause that takes care of the case where
1384 * sb_mb has been updated, but remains the last record.
1386 if (sb->sb_mb == NULL) {
1387 sb->sb_mbtail = NULL;
1388 sb->sb_lastrecord = NULL;
1389 } else if (sb->sb_mb->m_nextpkt == NULL)
1390 sb->sb_lastrecord = sb->sb_mb;
1395 * Implement receive operations on a socket. We depend on the way that
1396 * records are added to the sockbuf by sbappend. In particular, each record
1397 * (mbufs linked through m_next) must begin with an address if the protocol
1398 * so specifies, followed by an optional mbuf or mbufs containing ancillary
1399 * data, and then zero or more mbufs of data. In order to allow parallelism
1400 * between network receive and copying to user space, as well as avoid
1401 * sleeping with a mutex held, we release the socket buffer mutex during the
1402 * user space copy. Although the sockbuf is locked, new data may still be
1403 * appended, and thus we must maintain consistency of the sockbuf during that
1406 * The caller may receive the data as a single mbuf chain by supplying an
1407 * mbuf **mp0 for use in returning the chain. The uio is then used only for
1408 * the count in uio_resid.
1411 soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
1412 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1414 struct mbuf *m, **mp;
1415 int flags, len, error, offset;
1416 struct protosw *pr = so->so_proto;
1417 struct mbuf *nextrecord;
1419 int orig_resid = uio->uio_resid;
1424 if (controlp != NULL)
1427 flags = *flagsp &~ MSG_EOR;
1430 if (flags & MSG_OOB)
1431 return (soreceive_rcvoob(so, uio, flags));
1434 if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
1436 (*pr->pr_usrreqs->pru_rcvd)(so, 0);
1438 error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
1443 SOCKBUF_LOCK(&so->so_rcv);
1444 m = so->so_rcv.sb_mb;
1446 * If we have less data than requested, block awaiting more (subject
1447 * to any timeout) if:
1448 * 1. the current count is less than the low water mark, or
1449 * 2. MSG_WAITALL is set, and it is possible to do the entire
1450 * receive operation at once if we block (resid <= hiwat).
1451 * 3. MSG_DONTWAIT is not set
1452 * If MSG_WAITALL is set but resid is larger than the receive buffer,
1453 * we have to do the receive in sections, and thus risk returning a
1454 * short count if a timeout or signal occurs after we start.
1456 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1457 so->so_rcv.sb_cc < uio->uio_resid) &&
1458 (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
1459 ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
1460 m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
1461 KASSERT(m != NULL || !so->so_rcv.sb_cc,
1462 ("receive: m == %p so->so_rcv.sb_cc == %u",
1463 m, so->so_rcv.sb_cc));
1467 error = so->so_error;
1468 if ((flags & MSG_PEEK) == 0)
1470 SOCKBUF_UNLOCK(&so->so_rcv);
1473 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1474 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1476 SOCKBUF_UNLOCK(&so->so_rcv);
1481 for (; m != NULL; m = m->m_next)
1482 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
1483 m = so->so_rcv.sb_mb;
1486 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1487 (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1488 SOCKBUF_UNLOCK(&so->so_rcv);
1492 if (uio->uio_resid == 0) {
1493 SOCKBUF_UNLOCK(&so->so_rcv);
1496 if ((so->so_state & SS_NBIO) ||
1497 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1498 SOCKBUF_UNLOCK(&so->so_rcv);
1499 error = EWOULDBLOCK;
1502 SBLASTRECORDCHK(&so->so_rcv);
1503 SBLASTMBUFCHK(&so->so_rcv);
1504 error = sbwait(&so->so_rcv);
1505 SOCKBUF_UNLOCK(&so->so_rcv);
1512 * From this point onward, we maintain 'nextrecord' as a cache of the
1513 * pointer to the next record in the socket buffer. We must keep the
1514 * various socket buffer pointers and local stack versions of the
1515 * pointers in sync, pushing out modifications before dropping the
1516 * socket buffer mutex, and re-reading them when picking it up.
1518 * Otherwise, we will race with the network stack appending new data
1519 * or records onto the socket buffer by using inconsistent/stale
1520 * versions of the field, possibly resulting in socket buffer
1523 * By holding the high-level sblock(), we prevent simultaneous
1524 * readers from pulling off the front of the socket buffer.
1526 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1528 uio->uio_td->td_ru.ru_msgrcv++;
1529 KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
1530 SBLASTRECORDCHK(&so->so_rcv);
1531 SBLASTMBUFCHK(&so->so_rcv);
1532 nextrecord = m->m_nextpkt;
1533 if (pr->pr_flags & PR_ADDR) {
1534 KASSERT(m->m_type == MT_SONAME,
1535 ("m->m_type == %d", m->m_type));
1538 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
1540 if (flags & MSG_PEEK) {
1543 sbfree(&so->so_rcv, m);
1544 so->so_rcv.sb_mb = m_free(m);
1545 m = so->so_rcv.sb_mb;
1546 sockbuf_pushsync(&so->so_rcv, nextrecord);
1551 * Process one or more MT_CONTROL mbufs present before any data mbufs
1552 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
1553 * just copy the data; if !MSG_PEEK, we call into the protocol to
1554 * perform externalization (or freeing if controlp == NULL).
1556 if (m != NULL && m->m_type == MT_CONTROL) {
1557 struct mbuf *cm = NULL, *cmn;
1558 struct mbuf **cme = &cm;
1561 if (flags & MSG_PEEK) {
1562 if (controlp != NULL) {
1563 *controlp = m_copy(m, 0, m->m_len);
1564 controlp = &(*controlp)->m_next;
1568 sbfree(&so->so_rcv, m);
1569 so->so_rcv.sb_mb = m->m_next;
1572 cme = &(*cme)->m_next;
1573 m = so->so_rcv.sb_mb;
1575 } while (m != NULL && m->m_type == MT_CONTROL);
1576 if ((flags & MSG_PEEK) == 0)
1577 sockbuf_pushsync(&so->so_rcv, nextrecord);
1578 while (cm != NULL) {
1581 if (pr->pr_domain->dom_externalize != NULL) {
1582 SOCKBUF_UNLOCK(&so->so_rcv);
1583 error = (*pr->pr_domain->dom_externalize)
1585 SOCKBUF_LOCK(&so->so_rcv);
1586 } else if (controlp != NULL)
1590 if (controlp != NULL) {
1592 while (*controlp != NULL)
1593 controlp = &(*controlp)->m_next;
1598 nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1600 nextrecord = so->so_rcv.sb_mb;
1604 if ((flags & MSG_PEEK) == 0) {
1605 KASSERT(m->m_nextpkt == nextrecord,
1606 ("soreceive: post-control, nextrecord !sync"));
1607 if (nextrecord == NULL) {
1608 KASSERT(so->so_rcv.sb_mb == m,
1609 ("soreceive: post-control, sb_mb!=m"));
1610 KASSERT(so->so_rcv.sb_lastrecord == m,
1611 ("soreceive: post-control, lastrecord!=m"));
1615 if (type == MT_OOBDATA)
1618 if ((flags & MSG_PEEK) == 0) {
1619 KASSERT(so->so_rcv.sb_mb == nextrecord,
1620 ("soreceive: sb_mb != nextrecord"));
1621 if (so->so_rcv.sb_mb == NULL) {
1622 KASSERT(so->so_rcv.sb_lastrecord == NULL,
1623 ("soreceive: sb_lastercord != NULL"));
1627 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1628 SBLASTRECORDCHK(&so->so_rcv);
1629 SBLASTMBUFCHK(&so->so_rcv);
1632 * Now continue to read any data mbufs off of the head of the socket
1633 * buffer until the read request is satisfied. Note that 'type' is
1634 * used to store the type of any mbuf reads that have happened so far
1635 * such that soreceive() can stop reading if the type changes, which
1636 * causes soreceive() to return only one of regular data and inline
1637 * out-of-band data in a single socket receive operation.
1641 while (m != NULL && uio->uio_resid > 0 && error == 0) {
1643 * If the type of mbuf has changed since the last mbuf
1644 * examined ('type'), end the receive operation.
1646 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1647 if (m->m_type == MT_OOBDATA) {
1648 if (type != MT_OOBDATA)
1650 } else if (type == MT_OOBDATA)
1653 KASSERT(m->m_type == MT_DATA,
1654 ("m->m_type == %d", m->m_type));
1655 so->so_rcv.sb_state &= ~SBS_RCVATMARK;
1656 len = uio->uio_resid;
1657 if (so->so_oobmark && len > so->so_oobmark - offset)
1658 len = so->so_oobmark - offset;
1659 if (len > m->m_len - moff)
1660 len = m->m_len - moff;
1662 * If mp is set, just pass back the mbufs. Otherwise copy
1663 * them out via the uio, then free. Sockbuf must be
1664 * consistent here (points to current mbuf, it points to next
1665 * record) when we drop priority; we must note any additions
1666 * to the sockbuf when we block interrupts again.
1669 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1670 SBLASTRECORDCHK(&so->so_rcv);
1671 SBLASTMBUFCHK(&so->so_rcv);
1672 SOCKBUF_UNLOCK(&so->so_rcv);
1673 #ifdef ZERO_COPY_SOCKETS
1674 if (so_zero_copy_receive) {
1677 if ((m->m_flags & M_EXT)
1678 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1683 error = uiomoveco(mtod(m, char *) + moff,
1687 #endif /* ZERO_COPY_SOCKETS */
1688 error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1689 SOCKBUF_LOCK(&so->so_rcv);
1692 * The MT_SONAME mbuf has already been removed
1693 * from the record, so it is necessary to
1694 * remove the data mbufs, if any, to preserve
1695 * the invariant in the case of PR_ADDR that
1696 * requires MT_SONAME mbufs at the head of
1699 if (m && pr->pr_flags & PR_ATOMIC &&
1700 ((flags & MSG_PEEK) == 0))
1701 (void)sbdroprecord_locked(&so->so_rcv);
1702 SOCKBUF_UNLOCK(&so->so_rcv);
1706 uio->uio_resid -= len;
1707 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1708 if (len == m->m_len - moff) {
1709 if (m->m_flags & M_EOR)
1711 if (flags & MSG_PEEK) {
1715 nextrecord = m->m_nextpkt;
1716 sbfree(&so->so_rcv, m);
1720 so->so_rcv.sb_mb = m = m->m_next;
1723 so->so_rcv.sb_mb = m_free(m);
1724 m = so->so_rcv.sb_mb;
1726 sockbuf_pushsync(&so->so_rcv, nextrecord);
1727 SBLASTRECORDCHK(&so->so_rcv);
1728 SBLASTMBUFCHK(&so->so_rcv);
1731 if (flags & MSG_PEEK)
1737 if (flags & MSG_DONTWAIT)
1738 copy_flag = M_DONTWAIT;
1741 if (copy_flag == M_WAIT)
1742 SOCKBUF_UNLOCK(&so->so_rcv);
1743 *mp = m_copym(m, 0, len, copy_flag);
1744 if (copy_flag == M_WAIT)
1745 SOCKBUF_LOCK(&so->so_rcv);
1748 * m_copym() couldn't
1749 * allocate an mbuf. Adjust
1750 * uio_resid back (it was
1751 * adjusted down by len
1752 * bytes, which we didn't end
1753 * up "copying" over).
1755 uio->uio_resid += len;
1761 so->so_rcv.sb_cc -= len;
1764 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1765 if (so->so_oobmark) {
1766 if ((flags & MSG_PEEK) == 0) {
1767 so->so_oobmark -= len;
1768 if (so->so_oobmark == 0) {
1769 so->so_rcv.sb_state |= SBS_RCVATMARK;
1774 if (offset == so->so_oobmark)
1778 if (flags & MSG_EOR)
1781 * If the MSG_WAITALL flag is set (for non-atomic socket), we
1782 * must not quit until "uio->uio_resid == 0" or an error
1783 * termination. If a signal/timeout occurs, return with a
1784 * short count but without error. Keep sockbuf locked
1785 * against other readers.
1787 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1788 !sosendallatonce(so) && nextrecord == NULL) {
1789 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1790 if (so->so_error || so->so_rcv.sb_state & SBS_CANTRCVMORE)
1793 * Notify the protocol that some data has been
1794 * drained before blocking.
1796 if (pr->pr_flags & PR_WANTRCVD) {
1797 SOCKBUF_UNLOCK(&so->so_rcv);
1798 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1799 SOCKBUF_LOCK(&so->so_rcv);
1801 SBLASTRECORDCHK(&so->so_rcv);
1802 SBLASTMBUFCHK(&so->so_rcv);
1803 error = sbwait(&so->so_rcv);
1805 SOCKBUF_UNLOCK(&so->so_rcv);
1808 m = so->so_rcv.sb_mb;
1810 nextrecord = m->m_nextpkt;
1814 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1815 if (m != NULL && pr->pr_flags & PR_ATOMIC) {
1817 if ((flags & MSG_PEEK) == 0)
1818 (void) sbdroprecord_locked(&so->so_rcv);
1820 if ((flags & MSG_PEEK) == 0) {
1823 * First part is an inline SB_EMPTY_FIXUP(). Second
1824 * part makes sure sb_lastrecord is up-to-date if
1825 * there is still data in the socket buffer.
1827 so->so_rcv.sb_mb = nextrecord;
1828 if (so->so_rcv.sb_mb == NULL) {
1829 so->so_rcv.sb_mbtail = NULL;
1830 so->so_rcv.sb_lastrecord = NULL;
1831 } else if (nextrecord->m_nextpkt == NULL)
1832 so->so_rcv.sb_lastrecord = nextrecord;
1834 SBLASTRECORDCHK(&so->so_rcv);
1835 SBLASTMBUFCHK(&so->so_rcv);
1837 * If soreceive() is being done from the socket callback,
1838 * then don't need to generate ACK to peer to update window,
1839 * since ACK will be generated on return to TCP.
1841 if (!(flags & MSG_SOCALLBCK) &&
1842 (pr->pr_flags & PR_WANTRCVD)) {
1843 SOCKBUF_UNLOCK(&so->so_rcv);
1844 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1845 SOCKBUF_LOCK(&so->so_rcv);
1848 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1849 if (orig_resid == uio->uio_resid && orig_resid &&
1850 (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
1851 SOCKBUF_UNLOCK(&so->so_rcv);
1854 SOCKBUF_UNLOCK(&so->so_rcv);
1859 sbunlock(&so->so_rcv);
1864 * Optimized version of soreceive() for simple datagram cases from userspace.
1865 * Unlike in the stream case, we're able to drop a datagram if copyout()
1866 * fails, and because we handle datagrams atomically, we don't need to use a
1867 * sleep lock to prevent I/O interlacing.
1870 soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
1871 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1873 struct mbuf *m, *m2;
1874 int flags, len, error;
1875 struct protosw *pr = so->so_proto;
1876 struct mbuf *nextrecord;
1880 if (controlp != NULL)
1883 flags = *flagsp &~ MSG_EOR;
1888 * For any complicated cases, fall back to the full
1889 * soreceive_generic().
1891 if (mp0 != NULL || (flags & MSG_PEEK) || (flags & MSG_OOB))
1892 return (soreceive_generic(so, psa, uio, mp0, controlp,
1896 * Enforce restrictions on use.
1898 KASSERT((pr->pr_flags & PR_WANTRCVD) == 0,
1899 ("soreceive_dgram: wantrcvd"));
1900 KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic"));
1901 KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0,
1902 ("soreceive_dgram: SBS_RCVATMARK"));
1903 KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0,
1904 ("soreceive_dgram: P_CONNREQUIRED"));
1907 * Loop blocking while waiting for a datagram.
1909 SOCKBUF_LOCK(&so->so_rcv);
1910 while ((m = so->so_rcv.sb_mb) == NULL) {
1911 KASSERT(so->so_rcv.sb_cc == 0,
1912 ("soreceive_dgram: sb_mb NULL but sb_cc %u",
1915 error = so->so_error;
1917 SOCKBUF_UNLOCK(&so->so_rcv);
1920 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
1921 uio->uio_resid == 0) {
1922 SOCKBUF_UNLOCK(&so->so_rcv);
1925 if ((so->so_state & SS_NBIO) ||
1926 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1927 SOCKBUF_UNLOCK(&so->so_rcv);
1928 return (EWOULDBLOCK);
1930 SBLASTRECORDCHK(&so->so_rcv);
1931 SBLASTMBUFCHK(&so->so_rcv);
1932 error = sbwait(&so->so_rcv);
1934 SOCKBUF_UNLOCK(&so->so_rcv);
1938 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1941 uio->uio_td->td_ru.ru_msgrcv++;
1942 SBLASTRECORDCHK(&so->so_rcv);
1943 SBLASTMBUFCHK(&so->so_rcv);
1944 nextrecord = m->m_nextpkt;
1945 if (nextrecord == NULL) {
1946 KASSERT(so->so_rcv.sb_lastrecord == m,
1947 ("soreceive_dgram: lastrecord != m"));
1950 KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord,
1951 ("soreceive_dgram: m_nextpkt != nextrecord"));
1954 * Pull 'm' and its chain off the front of the packet queue.
1956 so->so_rcv.sb_mb = NULL;
1957 sockbuf_pushsync(&so->so_rcv, nextrecord);
1960 * Walk 'm's chain and free that many bytes from the socket buffer.
1962 for (m2 = m; m2 != NULL; m2 = m2->m_next)
1963 sbfree(&so->so_rcv, m2);
1966 * Do a few last checks before we let go of the lock.
1968 SBLASTRECORDCHK(&so->so_rcv);
1969 SBLASTMBUFCHK(&so->so_rcv);
1970 SOCKBUF_UNLOCK(&so->so_rcv);
1972 if (pr->pr_flags & PR_ADDR) {
1973 KASSERT(m->m_type == MT_SONAME,
1974 ("m->m_type == %d", m->m_type));
1976 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
1981 /* XXXRW: Can this happen? */
1986 * Packet to copyout() is now in 'm' and it is disconnected from the
1989 * Process one or more MT_CONTROL mbufs present before any data mbufs
1990 * in the first mbuf chain on the socket buffer. We call into the
1991 * protocol to perform externalization (or freeing if controlp ==
1994 if (m->m_type == MT_CONTROL) {
1995 struct mbuf *cm = NULL, *cmn;
1996 struct mbuf **cme = &cm;
2002 cme = &(*cme)->m_next;
2004 } while (m != NULL && m->m_type == MT_CONTROL);
2005 while (cm != NULL) {
2008 if (pr->pr_domain->dom_externalize != NULL) {
2009 error = (*pr->pr_domain->dom_externalize)
2011 } else if (controlp != NULL)
2015 if (controlp != NULL) {
2016 while (*controlp != NULL)
2017 controlp = &(*controlp)->m_next;
2022 KASSERT(m->m_type == MT_DATA, ("soreceive_dgram: !data"));
2024 while (m != NULL && uio->uio_resid > 0) {
2025 len = uio->uio_resid;
2028 error = uiomove(mtod(m, char *), (int)len, uio);
2044 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
2045 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2048 return (so->so_proto->pr_usrreqs->pru_soreceive(so, psa, uio, mp0,
2053 soshutdown(struct socket *so, int how)
2055 struct protosw *pr = so->so_proto;
2058 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
2060 if (pr->pr_usrreqs->pru_flush != NULL) {
2061 (*pr->pr_usrreqs->pru_flush)(so, how);
2065 if (how != SHUT_RD) {
2066 CURVNET_SET(so->so_vnet);
2067 error = (*pr->pr_usrreqs->pru_shutdown)(so);
2075 sorflush(struct socket *so)
2077 struct sockbuf *sb = &so->so_rcv;
2078 struct protosw *pr = so->so_proto;
2082 * In order to avoid calling dom_dispose with the socket buffer mutex
2083 * held, and in order to generally avoid holding the lock for a long
2084 * time, we make a copy of the socket buffer and clear the original
2085 * (except locks, state). The new socket buffer copy won't have
2086 * initialized locks so we can only call routines that won't use or
2087 * assert those locks.
2089 * Dislodge threads currently blocked in receive and wait to acquire
2090 * a lock against other simultaneous readers before clearing the
2091 * socket buffer. Don't let our acquire be interrupted by a signal
2092 * despite any existing socket disposition on interruptable waiting.
2094 CURVNET_SET(so->so_vnet);
2096 (void) sblock(sb, SBL_WAIT | SBL_NOINTR);
2099 * Invalidate/clear most of the sockbuf structure, but leave selinfo
2100 * and mutex data unchanged.
2103 bzero(&asb, offsetof(struct sockbuf, sb_startzero));
2104 bcopy(&sb->sb_startzero, &asb.sb_startzero,
2105 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2106 bzero(&sb->sb_startzero,
2107 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2112 * Dispose of special rights and flush the socket buffer. Don't call
2113 * any unsafe routines (that rely on locks being initialized) on asb.
2115 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
2116 (*pr->pr_domain->dom_dispose)(asb.sb_mb);
2117 sbrelease_internal(&asb, so);
2122 * Perhaps this routine, and sooptcopyout(), below, ought to come in an
2123 * additional variant to handle the case where the option value needs to be
2124 * some kind of integer, but not a specific size. In addition to their use
2125 * here, these functions are also called by the protocol-level pr_ctloutput()
2129 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2134 * If the user gives us more than we wanted, we ignore it, but if we
2135 * don't get the minimum length the caller wants, we return EINVAL.
2136 * On success, sopt->sopt_valsize is set to however much we actually
2139 if ((valsize = sopt->sopt_valsize) < minlen)
2142 sopt->sopt_valsize = valsize = len;
2144 if (sopt->sopt_td != NULL)
2145 return (copyin(sopt->sopt_val, buf, valsize));
2147 bcopy(sopt->sopt_val, buf, valsize);
2152 * Kernel version of setsockopt(2).
2154 * XXX: optlen is size_t, not socklen_t
2157 so_setsockopt(struct socket *so, int level, int optname, void *optval,
2160 struct sockopt sopt;
2162 sopt.sopt_level = level;
2163 sopt.sopt_name = optname;
2164 sopt.sopt_dir = SOPT_SET;
2165 sopt.sopt_val = optval;
2166 sopt.sopt_valsize = optlen;
2167 sopt.sopt_td = NULL;
2168 return (sosetopt(so, &sopt));
2172 sosetopt(struct socket *so, struct sockopt *sopt)
2183 if (sopt->sopt_level != SOL_SOCKET) {
2184 if (so->so_proto && so->so_proto->pr_ctloutput)
2185 return ((*so->so_proto->pr_ctloutput)
2187 error = ENOPROTOOPT;
2189 switch (sopt->sopt_name) {
2191 case SO_ACCEPTFILTER:
2192 error = do_setopt_accept_filter(so, sopt);
2198 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
2203 so->so_linger = l.l_linger;
2205 so->so_options |= SO_LINGER;
2207 so->so_options &= ~SO_LINGER;
2214 case SO_USELOOPBACK:
2224 error = sooptcopyin(sopt, &optval, sizeof optval,
2230 so->so_options |= sopt->sopt_name;
2232 so->so_options &= ~sopt->sopt_name;
2237 error = sooptcopyin(sopt, &optval, sizeof optval,
2239 if (optval < 1 || optval > rt_numfibs) {
2243 if ((so->so_proto->pr_domain->dom_family == PF_INET) ||
2244 (so->so_proto->pr_domain->dom_family == PF_ROUTE)) {
2245 so->so_fibnum = optval;
2246 /* Note: ignore error */
2247 if (so->so_proto && so->so_proto->pr_ctloutput)
2248 (*so->so_proto->pr_ctloutput)(so, sopt);
2257 error = sooptcopyin(sopt, &optval, sizeof optval,
2263 * Values < 1 make no sense for any of these options,
2271 switch (sopt->sopt_name) {
2274 if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
2275 &so->so_snd : &so->so_rcv, (u_long)optval,
2276 so, curthread) == 0) {
2280 (sopt->sopt_name == SO_SNDBUF ? &so->so_snd :
2281 &so->so_rcv)->sb_flags &= ~SB_AUTOSIZE;
2285 * Make sure the low-water is never greater than the
2289 SOCKBUF_LOCK(&so->so_snd);
2290 so->so_snd.sb_lowat =
2291 (optval > so->so_snd.sb_hiwat) ?
2292 so->so_snd.sb_hiwat : optval;
2293 SOCKBUF_UNLOCK(&so->so_snd);
2296 SOCKBUF_LOCK(&so->so_rcv);
2297 so->so_rcv.sb_lowat =
2298 (optval > so->so_rcv.sb_hiwat) ?
2299 so->so_rcv.sb_hiwat : optval;
2300 SOCKBUF_UNLOCK(&so->so_rcv);
2308 if (SV_CURPROC_FLAG(SV_ILP32)) {
2309 struct timeval32 tv32;
2311 error = sooptcopyin(sopt, &tv32, sizeof tv32,
2313 CP(tv32, tv, tv_sec);
2314 CP(tv32, tv, tv_usec);
2317 error = sooptcopyin(sopt, &tv, sizeof tv,
2322 /* assert(hz > 0); */
2323 if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
2324 tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
2328 /* assert(tick > 0); */
2329 /* assert(ULONG_MAX - INT_MAX >= 1000000); */
2330 val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
2331 if (val > INT_MAX) {
2335 if (val == 0 && tv.tv_usec != 0)
2338 switch (sopt->sopt_name) {
2340 so->so_snd.sb_timeo = val;
2343 so->so_rcv.sb_timeo = val;
2350 error = sooptcopyin(sopt, &extmac, sizeof extmac,
2354 error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
2362 error = ENOPROTOOPT;
2365 if (error == 0 && so->so_proto != NULL &&
2366 so->so_proto->pr_ctloutput != NULL) {
2367 (void) ((*so->so_proto->pr_ctloutput)
2376 * Helper routine for getsockopt.
2379 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
2387 * Documented get behavior is that we always return a value, possibly
2388 * truncated to fit in the user's buffer. Traditional behavior is
2389 * that we always tell the user precisely how much we copied, rather
2390 * than something useful like the total amount we had available for
2391 * her. Note that this interface is not idempotent; the entire
2392 * answer must generated ahead of time.
2394 valsize = min(len, sopt->sopt_valsize);
2395 sopt->sopt_valsize = valsize;
2396 if (sopt->sopt_val != NULL) {
2397 if (sopt->sopt_td != NULL)
2398 error = copyout(buf, sopt->sopt_val, valsize);
2400 bcopy(buf, sopt->sopt_val, valsize);
2406 sogetopt(struct socket *so, struct sockopt *sopt)
2416 if (sopt->sopt_level != SOL_SOCKET) {
2417 if (so->so_proto && so->so_proto->pr_ctloutput) {
2418 return ((*so->so_proto->pr_ctloutput)
2421 return (ENOPROTOOPT);
2423 switch (sopt->sopt_name) {
2425 case SO_ACCEPTFILTER:
2426 error = do_getopt_accept_filter(so, sopt);
2431 l.l_onoff = so->so_options & SO_LINGER;
2432 l.l_linger = so->so_linger;
2434 error = sooptcopyout(sopt, &l, sizeof l);
2437 case SO_USELOOPBACK:
2449 optval = so->so_options & sopt->sopt_name;
2451 error = sooptcopyout(sopt, &optval, sizeof optval);
2455 optval = so->so_type;
2460 optval = so->so_error;
2466 optval = so->so_snd.sb_hiwat;
2470 optval = so->so_rcv.sb_hiwat;
2474 optval = so->so_snd.sb_lowat;
2478 optval = so->so_rcv.sb_lowat;
2483 optval = (sopt->sopt_name == SO_SNDTIMEO ?
2484 so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
2486 tv.tv_sec = optval / hz;
2487 tv.tv_usec = (optval % hz) * tick;
2489 if (SV_CURPROC_FLAG(SV_ILP32)) {
2490 struct timeval32 tv32;
2492 CP(tv, tv32, tv_sec);
2493 CP(tv, tv32, tv_usec);
2494 error = sooptcopyout(sopt, &tv32, sizeof tv32);
2497 error = sooptcopyout(sopt, &tv, sizeof tv);
2502 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2506 error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
2510 error = sooptcopyout(sopt, &extmac, sizeof extmac);
2518 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2522 error = mac_getsockopt_peerlabel(
2523 sopt->sopt_td->td_ucred, so, &extmac);
2526 error = sooptcopyout(sopt, &extmac, sizeof extmac);
2532 case SO_LISTENQLIMIT:
2533 optval = so->so_qlimit;
2537 optval = so->so_qlen;
2540 case SO_LISTENINCQLEN:
2541 optval = so->so_incqlen;
2545 error = ENOPROTOOPT;
2552 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
2554 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
2556 struct mbuf *m, *m_prev;
2557 int sopt_size = sopt->sopt_valsize;
2559 MGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT, MT_DATA);
2562 if (sopt_size > MLEN) {
2563 MCLGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT);
2564 if ((m->m_flags & M_EXT) == 0) {
2568 m->m_len = min(MCLBYTES, sopt_size);
2570 m->m_len = min(MLEN, sopt_size);
2572 sopt_size -= m->m_len;
2577 MGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT, MT_DATA);
2582 if (sopt_size > MLEN) {
2583 MCLGET(m, sopt->sopt_td != NULL ? M_WAIT :
2585 if ((m->m_flags & M_EXT) == 0) {
2590 m->m_len = min(MCLBYTES, sopt_size);
2592 m->m_len = min(MLEN, sopt_size);
2594 sopt_size -= m->m_len;
2601 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
2603 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
2605 struct mbuf *m0 = m;
2607 if (sopt->sopt_val == NULL)
2609 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2610 if (sopt->sopt_td != NULL) {
2613 error = copyin(sopt->sopt_val, mtod(m, char *),
2620 bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
2621 sopt->sopt_valsize -= m->m_len;
2622 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2625 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
2626 panic("ip6_sooptmcopyin");
2630 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
2632 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
2634 struct mbuf *m0 = m;
2637 if (sopt->sopt_val == NULL)
2639 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2640 if (sopt->sopt_td != NULL) {
2643 error = copyout(mtod(m, char *), sopt->sopt_val,
2650 bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
2651 sopt->sopt_valsize -= m->m_len;
2652 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2653 valsize += m->m_len;
2657 /* enough soopt buffer should be given from user-land */
2661 sopt->sopt_valsize = valsize;
2666 * sohasoutofband(): protocol notifies socket layer of the arrival of new
2667 * out-of-band data, which will then notify socket consumers.
2670 sohasoutofband(struct socket *so)
2673 if (so->so_sigio != NULL)
2674 pgsigio(&so->so_sigio, SIGURG, 0);
2675 selwakeuppri(&so->so_rcv.sb_sel, PSOCK);
2679 sopoll(struct socket *so, int events, struct ucred *active_cred,
2683 return (so->so_proto->pr_usrreqs->pru_sopoll(so, events, active_cred,
2688 sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
2693 SOCKBUF_LOCK(&so->so_snd);
2694 SOCKBUF_LOCK(&so->so_rcv);
2695 if (events & (POLLIN | POLLRDNORM))
2697 revents |= events & (POLLIN | POLLRDNORM);
2699 if (events & POLLINIGNEOF)
2700 if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
2701 !TAILQ_EMPTY(&so->so_comp) || so->so_error)
2702 revents |= POLLINIGNEOF;
2704 if (events & (POLLOUT | POLLWRNORM))
2705 if (sowriteable(so))
2706 revents |= events & (POLLOUT | POLLWRNORM);
2708 if (events & (POLLPRI | POLLRDBAND))
2709 if (so->so_oobmark || (so->so_rcv.sb_state & SBS_RCVATMARK))
2710 revents |= events & (POLLPRI | POLLRDBAND);
2714 (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
2716 selrecord(td, &so->so_rcv.sb_sel);
2717 so->so_rcv.sb_flags |= SB_SEL;
2720 if (events & (POLLOUT | POLLWRNORM)) {
2721 selrecord(td, &so->so_snd.sb_sel);
2722 so->so_snd.sb_flags |= SB_SEL;
2726 SOCKBUF_UNLOCK(&so->so_rcv);
2727 SOCKBUF_UNLOCK(&so->so_snd);
2732 soo_kqfilter(struct file *fp, struct knote *kn)
2734 struct socket *so = kn->kn_fp->f_data;
2737 switch (kn->kn_filter) {
2739 if (so->so_options & SO_ACCEPTCONN)
2740 kn->kn_fop = &solisten_filtops;
2742 kn->kn_fop = &soread_filtops;
2746 kn->kn_fop = &sowrite_filtops;
2754 knlist_add(&sb->sb_sel.si_note, kn, 1);
2755 sb->sb_flags |= SB_KNOTE;
2761 * Some routines that return EOPNOTSUPP for entry points that are not
2762 * supported by a protocol. Fill in as needed.
2765 pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
2772 pru_attach_notsupp(struct socket *so, int proto, struct thread *td)
2779 pru_bind_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
2786 pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
2793 pru_connect2_notsupp(struct socket *so1, struct socket *so2)
2800 pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
2801 struct ifnet *ifp, struct thread *td)
2808 pru_disconnect_notsupp(struct socket *so)
2815 pru_listen_notsupp(struct socket *so, int backlog, struct thread *td)
2822 pru_peeraddr_notsupp(struct socket *so, struct sockaddr **nam)
2829 pru_rcvd_notsupp(struct socket *so, int flags)
2836 pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
2843 pru_send_notsupp(struct socket *so, int flags, struct mbuf *m,
2844 struct sockaddr *addr, struct mbuf *control, struct thread *td)
2851 * This isn't really a ``null'' operation, but it's the default one and
2852 * doesn't do anything destructive.
2855 pru_sense_null(struct socket *so, struct stat *sb)
2858 sb->st_blksize = so->so_snd.sb_hiwat;
2863 pru_shutdown_notsupp(struct socket *so)
2870 pru_sockaddr_notsupp(struct socket *so, struct sockaddr **nam)
2877 pru_sosend_notsupp(struct socket *so, struct sockaddr *addr, struct uio *uio,
2878 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
2885 pru_soreceive_notsupp(struct socket *so, struct sockaddr **paddr,
2886 struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2893 pru_sopoll_notsupp(struct socket *so, int events, struct ucred *cred,
2901 filt_sordetach(struct knote *kn)
2903 struct socket *so = kn->kn_fp->f_data;
2905 SOCKBUF_LOCK(&so->so_rcv);
2906 knlist_remove(&so->so_rcv.sb_sel.si_note, kn, 1);
2907 if (knlist_empty(&so->so_rcv.sb_sel.si_note))
2908 so->so_rcv.sb_flags &= ~SB_KNOTE;
2909 SOCKBUF_UNLOCK(&so->so_rcv);
2914 filt_soread(struct knote *kn, long hint)
2918 so = kn->kn_fp->f_data;
2919 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2921 kn->kn_data = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
2922 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2923 kn->kn_flags |= EV_EOF;
2924 kn->kn_fflags = so->so_error;
2926 } else if (so->so_error) /* temporary udp error */
2928 else if (kn->kn_sfflags & NOTE_LOWAT)
2929 return (kn->kn_data >= kn->kn_sdata);
2931 return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat);
2935 filt_sowdetach(struct knote *kn)
2937 struct socket *so = kn->kn_fp->f_data;
2939 SOCKBUF_LOCK(&so->so_snd);
2940 knlist_remove(&so->so_snd.sb_sel.si_note, kn, 1);
2941 if (knlist_empty(&so->so_snd.sb_sel.si_note))
2942 so->so_snd.sb_flags &= ~SB_KNOTE;
2943 SOCKBUF_UNLOCK(&so->so_snd);
2948 filt_sowrite(struct knote *kn, long hint)
2952 so = kn->kn_fp->f_data;
2953 SOCKBUF_LOCK_ASSERT(&so->so_snd);
2954 kn->kn_data = sbspace(&so->so_snd);
2955 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2956 kn->kn_flags |= EV_EOF;
2957 kn->kn_fflags = so->so_error;
2959 } else if (so->so_error) /* temporary udp error */
2961 else if (((so->so_state & SS_ISCONNECTED) == 0) &&
2962 (so->so_proto->pr_flags & PR_CONNREQUIRED))
2964 else if (kn->kn_sfflags & NOTE_LOWAT)
2965 return (kn->kn_data >= kn->kn_sdata);
2967 return (kn->kn_data >= so->so_snd.sb_lowat);
2972 filt_solisten(struct knote *kn, long hint)
2974 struct socket *so = kn->kn_fp->f_data;
2976 kn->kn_data = so->so_qlen;
2977 return (! TAILQ_EMPTY(&so->so_comp));
2981 socheckuid(struct socket *so, uid_t uid)
2986 if (so->so_cred->cr_uid != uid)
2992 sysctl_somaxconn(SYSCTL_HANDLER_ARGS)
2998 error = sysctl_handle_int(oidp, &val, 0, req);
2999 if (error || !req->newptr )
3002 if (val < 1 || val > USHRT_MAX)
3010 * These functions are used by protocols to notify the socket layer (and its
3011 * consumers) of state changes in the sockets driven by protocol-side events.
3015 * Procedures to manipulate state flags of socket and do appropriate wakeups.
3017 * Normal sequence from the active (originating) side is that
3018 * soisconnecting() is called during processing of connect() call, resulting
3019 * in an eventual call to soisconnected() if/when the connection is
3020 * established. When the connection is torn down soisdisconnecting() is
3021 * called during processing of disconnect() call, and soisdisconnected() is
3022 * called when the connection to the peer is totally severed. The semantics
3023 * of these routines are such that connectionless protocols can call
3024 * soisconnected() and soisdisconnected() only, bypassing the in-progress
3025 * calls when setting up a ``connection'' takes no time.
3027 * From the passive side, a socket is created with two queues of sockets:
3028 * so_incomp for connections in progress and so_comp for connections already
3029 * made and awaiting user acceptance. As a protocol is preparing incoming
3030 * connections, it creates a socket structure queued on so_incomp by calling
3031 * sonewconn(). When the connection is established, soisconnected() is
3032 * called, and transfers the socket structure to so_comp, making it available
3035 * If a socket is closed with sockets on either so_incomp or so_comp, these
3036 * sockets are dropped.
3038 * If higher-level protocols are implemented in the kernel, the wakeups done
3039 * here will sometimes cause software-interrupt process scheduling.
3042 soisconnecting(struct socket *so)
3046 so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
3047 so->so_state |= SS_ISCONNECTING;
3052 soisconnected(struct socket *so)
3054 struct socket *head;
3060 so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
3061 so->so_state |= SS_ISCONNECTED;
3063 if (head != NULL && (so->so_qstate & SQ_INCOMP)) {
3064 if ((so->so_options & SO_ACCEPTFILTER) == 0) {
3066 TAILQ_REMOVE(&head->so_incomp, so, so_list);
3068 so->so_qstate &= ~SQ_INCOMP;
3069 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
3071 so->so_qstate |= SQ_COMP;
3074 wakeup_one(&head->so_timeo);
3077 soupcall_set(so, SO_RCV,
3078 head->so_accf->so_accept_filter->accf_callback,
3079 head->so_accf->so_accept_filter_arg);
3080 so->so_options &= ~SO_ACCEPTFILTER;
3081 ret = head->so_accf->so_accept_filter->accf_callback(so,
3082 head->so_accf->so_accept_filter_arg, M_DONTWAIT);
3083 if (ret == SU_ISCONNECTED)
3084 soupcall_clear(so, SO_RCV);
3086 if (ret == SU_ISCONNECTED)
3093 wakeup(&so->so_timeo);
3099 soisdisconnecting(struct socket *so)
3103 * Note: This code assumes that SOCK_LOCK(so) and
3104 * SOCKBUF_LOCK(&so->so_rcv) are the same.
3106 SOCKBUF_LOCK(&so->so_rcv);
3107 so->so_state &= ~SS_ISCONNECTING;
3108 so->so_state |= SS_ISDISCONNECTING;
3109 so->so_rcv.sb_state |= SBS_CANTRCVMORE;
3110 sorwakeup_locked(so);
3111 SOCKBUF_LOCK(&so->so_snd);
3112 so->so_snd.sb_state |= SBS_CANTSENDMORE;
3113 sowwakeup_locked(so);
3114 wakeup(&so->so_timeo);
3118 soisdisconnected(struct socket *so)
3122 * Note: This code assumes that SOCK_LOCK(so) and
3123 * SOCKBUF_LOCK(&so->so_rcv) are the same.
3125 SOCKBUF_LOCK(&so->so_rcv);
3126 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
3127 so->so_state |= SS_ISDISCONNECTED;
3128 so->so_rcv.sb_state |= SBS_CANTRCVMORE;
3129 sorwakeup_locked(so);
3130 SOCKBUF_LOCK(&so->so_snd);
3131 so->so_snd.sb_state |= SBS_CANTSENDMORE;
3132 sbdrop_locked(&so->so_snd, so->so_snd.sb_cc);
3133 sowwakeup_locked(so);
3134 wakeup(&so->so_timeo);
3138 * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
3141 sodupsockaddr(const struct sockaddr *sa, int mflags)
3143 struct sockaddr *sa2;
3145 sa2 = malloc(sa->sa_len, M_SONAME, mflags);
3147 bcopy(sa, sa2, sa->sa_len);
3152 * Register per-socket buffer upcalls.
3155 soupcall_set(struct socket *so, int which,
3156 int (*func)(struct socket *, void *, int), void *arg)
3168 panic("soupcall_set: bad which");
3170 SOCKBUF_LOCK_ASSERT(sb);
3172 /* XXX: accf_http actually wants to do this on purpose. */
3173 KASSERT(sb->sb_upcall == NULL, ("soupcall_set: overwriting upcall"));
3175 sb->sb_upcall = func;
3176 sb->sb_upcallarg = arg;
3177 sb->sb_flags |= SB_UPCALL;
3181 soupcall_clear(struct socket *so, int which)
3193 panic("soupcall_clear: bad which");
3195 SOCKBUF_LOCK_ASSERT(sb);
3196 KASSERT(sb->sb_upcall != NULL, ("soupcall_clear: no upcall to clear"));
3197 sb->sb_upcall = NULL;
3198 sb->sb_upcallarg = NULL;
3199 sb->sb_flags &= ~SB_UPCALL;
3203 * Create an external-format (``xsocket'') structure using the information in
3204 * the kernel-format socket structure pointed to by so. This is done to
3205 * reduce the spew of irrelevant information over this interface, to isolate
3206 * user code from changes in the kernel structure, and potentially to provide
3207 * information-hiding if we decide that some of this information should be
3208 * hidden from users.
3211 sotoxsocket(struct socket *so, struct xsocket *xso)
3214 xso->xso_len = sizeof *xso;
3216 xso->so_type = so->so_type;
3217 xso->so_options = so->so_options;
3218 xso->so_linger = so->so_linger;
3219 xso->so_state = so->so_state;
3220 xso->so_pcb = so->so_pcb;
3221 xso->xso_protocol = so->so_proto->pr_protocol;
3222 xso->xso_family = so->so_proto->pr_domain->dom_family;
3223 xso->so_qlen = so->so_qlen;
3224 xso->so_incqlen = so->so_incqlen;
3225 xso->so_qlimit = so->so_qlimit;
3226 xso->so_timeo = so->so_timeo;
3227 xso->so_error = so->so_error;
3228 xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
3229 xso->so_oobmark = so->so_oobmark;
3230 sbtoxsockbuf(&so->so_snd, &xso->so_snd);
3231 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
3232 xso->so_uid = so->so_cred->cr_uid;
3237 * Socket accessor functions to provide external consumers with
3238 * a safe interface to socket state
3243 so_listeners_apply_all(struct socket *so, void (*func)(struct socket *, void *), void *arg)
3246 TAILQ_FOREACH(so, &so->so_comp, so_list)
3251 so_sockbuf_rcv(struct socket *so)
3254 return (&so->so_rcv);
3258 so_sockbuf_snd(struct socket *so)
3261 return (&so->so_snd);
3265 so_state_get(const struct socket *so)
3268 return (so->so_state);
3272 so_state_set(struct socket *so, int val)
3279 so_options_get(const struct socket *so)
3282 return (so->so_options);
3286 so_options_set(struct socket *so, int val)
3289 so->so_options = val;
3293 so_error_get(const struct socket *so)
3296 return (so->so_error);
3300 so_error_set(struct socket *so, int val)
3307 so_linger_get(const struct socket *so)
3310 return (so->so_linger);
3314 so_linger_set(struct socket *so, int val)
3317 so->so_linger = val;
3321 so_protosw_get(const struct socket *so)
3324 return (so->so_proto);
3328 so_protosw_set(struct socket *so, struct protosw *val)
3335 so_sorwakeup(struct socket *so)
3342 so_sowwakeup(struct socket *so)
3349 so_sorwakeup_locked(struct socket *so)
3352 sorwakeup_locked(so);
3356 so_sowwakeup_locked(struct socket *so)
3359 sowwakeup_locked(so);
3363 so_lock(struct socket *so)
3369 so_unlock(struct socket *so)