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.
96 * NOTE: With regard to VNETs the general rule is that callers do not set
97 * curvnet. Exceptions to this rule include soabort(), sodisconnect(),
98 * sofree() (and with that sorele(), sotryfree()), as well as sonewconn()
99 * and sorflush(), which are usually called from a pre-set VNET context.
100 * sopoll() currently does not need a VNET context to be set.
103 #include <sys/cdefs.h>
104 __FBSDID("$FreeBSD$");
106 #include "opt_inet.h"
107 #include "opt_inet6.h"
108 #include "opt_zero.h"
109 #include "opt_compat.h"
111 #include <sys/param.h>
112 #include <sys/systm.h>
113 #include <sys/fcntl.h>
114 #include <sys/limits.h>
115 #include <sys/lock.h>
117 #include <sys/malloc.h>
118 #include <sys/mbuf.h>
119 #include <sys/mutex.h>
120 #include <sys/domain.h>
121 #include <sys/file.h> /* for struct knote */
122 #include <sys/kernel.h>
123 #include <sys/event.h>
124 #include <sys/eventhandler.h>
125 #include <sys/poll.h>
126 #include <sys/proc.h>
127 #include <sys/protosw.h>
128 #include <sys/socket.h>
129 #include <sys/socketvar.h>
130 #include <sys/resourcevar.h>
131 #include <net/route.h>
132 #include <sys/signalvar.h>
133 #include <sys/stat.h>
135 #include <sys/sysctl.h>
137 #include <sys/jail.h>
138 #include <sys/syslog.h>
139 #include <netinet/in.h>
141 #include <net/vnet.h>
143 #include <security/mac/mac_framework.h>
147 #ifdef COMPAT_FREEBSD32
148 #include <sys/mount.h>
149 #include <sys/sysent.h>
150 #include <compat/freebsd32/freebsd32.h>
153 static int soreceive_rcvoob(struct socket *so, struct uio *uio,
156 static void filt_sordetach(struct knote *kn);
157 static int filt_soread(struct knote *kn, long hint);
158 static void filt_sowdetach(struct knote *kn);
159 static int filt_sowrite(struct knote *kn, long hint);
160 static int filt_solisten(struct knote *kn, long hint);
162 static struct filterops solisten_filtops = {
164 .f_detach = filt_sordetach,
165 .f_event = filt_solisten,
167 static struct filterops soread_filtops = {
169 .f_detach = filt_sordetach,
170 .f_event = filt_soread,
172 static struct filterops sowrite_filtops = {
174 .f_detach = filt_sowdetach,
175 .f_event = filt_sowrite,
178 so_gen_t so_gencnt; /* generation count for sockets */
180 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
181 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
183 #define VNET_SO_ASSERT(so) \
184 VNET_ASSERT(curvnet != NULL, \
185 ("%s:%d curvnet is NULL, so=%p", __func__, __LINE__, (so)));
188 * Limit on the number of connections in the listen queue waiting
191 static int somaxconn = SOMAXCONN;
194 sysctl_somaxconn(SYSCTL_HANDLER_ARGS)
200 error = sysctl_handle_int(oidp, &val, 0, req);
201 if (error || !req->newptr )
204 if (val < 1 || val > USHRT_MAX)
210 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLTYPE_UINT | CTLFLAG_RW,
211 0, sizeof(int), sysctl_somaxconn, "I",
212 "Maximum listen socket pending connection accept queue size");
214 static int numopensockets;
215 SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
216 &numopensockets, 0, "Number of open sockets");
218 #ifdef ZERO_COPY_SOCKETS
219 /* These aren't static because they're used in other files. */
220 int so_zero_copy_send = 1;
221 int so_zero_copy_receive = 1;
222 SYSCTL_NODE(_kern_ipc, OID_AUTO, zero_copy, CTLFLAG_RD, 0,
223 "Zero copy controls");
224 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, receive, CTLFLAG_RW,
225 &so_zero_copy_receive, 0, "Enable zero copy receive");
226 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, send, CTLFLAG_RW,
227 &so_zero_copy_send, 0, "Enable zero copy send");
228 #endif /* ZERO_COPY_SOCKETS */
231 * accept_mtx locks down per-socket fields relating to accept queues. See
232 * socketvar.h for an annotation of the protected fields of struct socket.
234 struct mtx accept_mtx;
235 MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
238 * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
241 static struct mtx so_global_mtx;
242 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
245 * General IPC sysctl name space, used by sockets and a variety of other IPC
248 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
251 * Initialize the socket subsystem and set up the socket
254 uma_zone_t socket_zone;
258 socket_zone_change(void *tag)
261 uma_zone_set_max(socket_zone, maxsockets);
265 socket_init(void *tag)
268 socket_zone = uma_zcreate("socket", sizeof(struct socket), NULL, NULL,
269 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
270 uma_zone_set_max(socket_zone, maxsockets);
271 EVENTHANDLER_REGISTER(maxsockets_change, socket_zone_change, NULL,
272 EVENTHANDLER_PRI_FIRST);
274 SYSINIT(socket, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, socket_init, NULL);
277 * Initialise maxsockets. This SYSINIT must be run after
281 init_maxsockets(void *ignored)
284 TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
285 maxsockets = imax(maxsockets, imax(maxfiles, nmbclusters));
287 SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);
290 * Sysctl to get and set the maximum global sockets limit. Notify protocols
291 * of the change so that they can update their dependent limits as required.
294 sysctl_maxsockets(SYSCTL_HANDLER_ARGS)
296 int error, newmaxsockets;
298 newmaxsockets = maxsockets;
299 error = sysctl_handle_int(oidp, &newmaxsockets, 0, req);
300 if (error == 0 && req->newptr) {
301 if (newmaxsockets > maxsockets) {
302 maxsockets = newmaxsockets;
303 if (maxsockets > ((maxfiles / 4) * 3)) {
304 maxfiles = (maxsockets * 5) / 4;
305 maxfilesperproc = (maxfiles * 9) / 10;
307 EVENTHANDLER_INVOKE(maxsockets_change);
313 SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets, CTLTYPE_INT|CTLFLAG_RW,
314 &maxsockets, 0, sysctl_maxsockets, "IU",
315 "Maximum number of sockets avaliable");
318 * Socket operation routines. These routines are called by the routines in
319 * sys_socket.c or from a system process, and implement the semantics of
320 * socket operations by switching out to the protocol specific routines.
324 * Get a socket structure from our zone, and initialize it. Note that it
325 * would probably be better to allocate socket and PCB at the same time, but
326 * I'm not convinced that all the protocols can be easily modified to do
329 * soalloc() returns a socket with a ref count of 0.
331 static struct socket *
332 soalloc(struct vnet *vnet)
336 so = uma_zalloc(socket_zone, M_NOWAIT | M_ZERO);
340 if (mac_socket_init(so, M_NOWAIT) != 0) {
341 uma_zfree(socket_zone, so);
345 SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
346 SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
347 sx_init(&so->so_snd.sb_sx, "so_snd_sx");
348 sx_init(&so->so_rcv.sb_sx, "so_rcv_sx");
349 TAILQ_INIT(&so->so_aiojobq);
350 mtx_lock(&so_global_mtx);
351 so->so_gencnt = ++so_gencnt;
354 VNET_ASSERT(vnet != NULL, ("%s:%d vnet is NULL, so=%p",
355 __func__, __LINE__, so));
356 vnet->vnet_sockcnt++;
359 mtx_unlock(&so_global_mtx);
364 * Free the storage associated with a socket at the socket layer, tear down
365 * locks, labels, etc. All protocol state is assumed already to have been
366 * torn down (and possibly never set up) by the caller.
369 sodealloc(struct socket *so)
372 KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
373 KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
375 mtx_lock(&so_global_mtx);
376 so->so_gencnt = ++so_gencnt;
377 --numopensockets; /* Could be below, but faster here. */
379 VNET_ASSERT(so->so_vnet != NULL, ("%s:%d so_vnet is NULL, so=%p",
380 __func__, __LINE__, so));
381 so->so_vnet->vnet_sockcnt--;
383 mtx_unlock(&so_global_mtx);
384 if (so->so_rcv.sb_hiwat)
385 (void)chgsbsize(so->so_cred->cr_uidinfo,
386 &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
387 if (so->so_snd.sb_hiwat)
388 (void)chgsbsize(so->so_cred->cr_uidinfo,
389 &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
391 /* remove acccept filter if one is present. */
392 if (so->so_accf != NULL)
393 do_setopt_accept_filter(so, NULL);
396 mac_socket_destroy(so);
399 sx_destroy(&so->so_snd.sb_sx);
400 sx_destroy(&so->so_rcv.sb_sx);
401 SOCKBUF_LOCK_DESTROY(&so->so_snd);
402 SOCKBUF_LOCK_DESTROY(&so->so_rcv);
403 uma_zfree(socket_zone, so);
407 * socreate returns a socket with a ref count of 1. The socket should be
408 * closed with soclose().
411 socreate(int dom, struct socket **aso, int type, int proto,
412 struct ucred *cred, struct thread *td)
419 prp = pffindproto(dom, proto, type);
421 prp = pffindtype(dom, type);
423 if (prp == NULL || prp->pr_usrreqs->pru_attach == NULL ||
424 prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
425 return (EPROTONOSUPPORT);
427 if (prison_check_af(cred, prp->pr_domain->dom_family) != 0)
428 return (EPROTONOSUPPORT);
430 if (prp->pr_type != type)
432 so = soalloc(CRED_TO_VNET(cred));
436 TAILQ_INIT(&so->so_incomp);
437 TAILQ_INIT(&so->so_comp);
439 so->so_cred = crhold(cred);
440 if ((prp->pr_domain->dom_family == PF_INET) ||
441 (prp->pr_domain->dom_family == PF_INET6) ||
442 (prp->pr_domain->dom_family == PF_ROUTE))
443 so->so_fibnum = td->td_proc->p_fibnum;
448 mac_socket_create(cred, so);
450 knlist_init_mtx(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
451 knlist_init_mtx(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
454 * Auto-sizing of socket buffers is managed by the protocols and
455 * the appropriate flags must be set in the pru_attach function.
457 CURVNET_SET(so->so_vnet);
458 error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
461 KASSERT(so->so_count == 1, ("socreate: so_count %d",
472 static int regression_sonewconn_earlytest = 1;
473 SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW,
474 ®ression_sonewconn_earlytest, 0, "Perform early sonewconn limit test");
478 * When an attempt at a new connection is noted on a socket which accepts
479 * connections, sonewconn is called. If the connection is possible (subject
480 * to space constraints, etc.) then we allocate a new structure, propoerly
481 * linked into the data structure of the original socket, and return this.
482 * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
484 * Note: the ref count on the socket is 0 on return.
487 sonewconn(struct socket *head, int connstatus)
493 over = (head->so_qlen > 3 * head->so_qlimit / 2);
496 if (regression_sonewconn_earlytest && over) {
500 log(LOG_DEBUG, "%s: pcb %p: Listen queue overflow: "
501 "%i already in queue awaiting acceptance\n",
502 __func__, head->so_pcb, head->so_qlen);
505 VNET_ASSERT(head->so_vnet != NULL, ("%s:%d so_vnet is NULL, head=%p",
506 __func__, __LINE__, head));
507 so = soalloc(head->so_vnet);
509 log(LOG_DEBUG, "%s: pcb %p: New socket allocation failure: "
510 "limit reached or out of memory\n",
511 __func__, head->so_pcb);
514 if ((head->so_options & SO_ACCEPTFILTER) != 0)
517 so->so_type = head->so_type;
518 so->so_options = head->so_options &~ SO_ACCEPTCONN;
519 so->so_linger = head->so_linger;
520 so->so_state = head->so_state | SS_NOFDREF;
521 so->so_fibnum = head->so_fibnum;
522 so->so_proto = head->so_proto;
523 so->so_cred = crhold(head->so_cred);
525 mac_socket_newconn(head, so);
527 knlist_init_mtx(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
528 knlist_init_mtx(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
529 VNET_SO_ASSERT(head);
530 if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat)) {
532 log(LOG_DEBUG, "%s: pcb %p: soreserve() failed\n",
533 __func__, head->so_pcb);
536 if ((*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
538 log(LOG_DEBUG, "%s: pcb %p: pru_attach() failed\n",
539 __func__, head->so_pcb);
542 so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
543 so->so_snd.sb_lowat = head->so_snd.sb_lowat;
544 so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
545 so->so_snd.sb_timeo = head->so_snd.sb_timeo;
546 so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
547 so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
548 so->so_state |= connstatus;
551 * The accept socket may be tearing down but we just
552 * won a race on the ACCEPT_LOCK.
553 * However, if sctp_peeloff() is called on a 1-to-many
554 * style socket, the SO_ACCEPTCONN doesn't need to be set.
556 if (!(head->so_options & SO_ACCEPTCONN) &&
557 ((head->so_proto->pr_protocol != IPPROTO_SCTP) ||
558 (head->so_type != SOCK_SEQPACKET))) {
561 sofree(so); /* NB: returns ACCEPT_UNLOCK'ed. */
565 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
566 so->so_qstate |= SQ_COMP;
570 * Keep removing sockets from the head until there's room for
571 * us to insert on the tail. In pre-locking revisions, this
572 * was a simple if(), but as we could be racing with other
573 * threads and soabort() requires dropping locks, we must
574 * loop waiting for the condition to be true.
576 while (head->so_incqlen > head->so_qlimit) {
578 sp = TAILQ_FIRST(&head->so_incomp);
579 TAILQ_REMOVE(&head->so_incomp, sp, so_list);
581 sp->so_qstate &= ~SQ_INCOMP;
587 TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
588 so->so_qstate |= SQ_INCOMP;
594 wakeup_one(&head->so_timeo);
600 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
604 CURVNET_SET(so->so_vnet);
605 error = (*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td);
611 * solisten() transitions a socket from a non-listening state to a listening
612 * state, but can also be used to update the listen queue depth on an
613 * existing listen socket. The protocol will call back into the sockets
614 * layer using solisten_proto_check() and solisten_proto() to check and set
615 * socket-layer listen state. Call backs are used so that the protocol can
616 * acquire both protocol and socket layer locks in whatever order is required
619 * Protocol implementors are advised to hold the socket lock across the
620 * socket-layer test and set to avoid races at the socket layer.
623 solisten(struct socket *so, int backlog, struct thread *td)
627 CURVNET_SET(so->so_vnet);
628 error = (*so->so_proto->pr_usrreqs->pru_listen)(so, backlog, td);
634 solisten_proto_check(struct socket *so)
637 SOCK_LOCK_ASSERT(so);
639 if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
646 solisten_proto(struct socket *so, int backlog)
649 SOCK_LOCK_ASSERT(so);
651 if (backlog < 0 || backlog > somaxconn)
653 so->so_qlimit = backlog;
654 so->so_options |= SO_ACCEPTCONN;
658 * Evaluate the reference count and named references on a socket; if no
659 * references remain, free it. This should be called whenever a reference is
660 * released, such as in sorele(), but also when named reference flags are
661 * cleared in socket or protocol code.
663 * sofree() will free the socket if:
665 * - There are no outstanding file descriptor references or related consumers
668 * - The socket has been closed by user space, if ever open (SS_NOFDREF).
670 * - The protocol does not have an outstanding strong reference on the socket
673 * - The socket is not in a completed connection queue, so a process has been
674 * notified that it is present. If it is removed, the user process may
675 * block in accept() despite select() saying the socket was ready.
678 sofree(struct socket *so)
680 struct protosw *pr = so->so_proto;
683 ACCEPT_LOCK_ASSERT();
684 SOCK_LOCK_ASSERT(so);
686 if ((so->so_state & SS_NOFDREF) == 0 || so->so_count != 0 ||
687 (so->so_state & SS_PROTOREF) || (so->so_qstate & SQ_COMP)) {
695 KASSERT((so->so_qstate & SQ_COMP) != 0 ||
696 (so->so_qstate & SQ_INCOMP) != 0,
697 ("sofree: so_head != NULL, but neither SQ_COMP nor "
699 KASSERT((so->so_qstate & SQ_COMP) == 0 ||
700 (so->so_qstate & SQ_INCOMP) == 0,
701 ("sofree: so->so_qstate is SQ_COMP and also SQ_INCOMP"));
702 TAILQ_REMOVE(&head->so_incomp, so, so_list);
704 so->so_qstate &= ~SQ_INCOMP;
707 KASSERT((so->so_qstate & SQ_COMP) == 0 &&
708 (so->so_qstate & SQ_INCOMP) == 0,
709 ("sofree: so_head == NULL, but still SQ_COMP(%d) or SQ_INCOMP(%d)",
710 so->so_qstate & SQ_COMP, so->so_qstate & SQ_INCOMP));
711 if (so->so_options & SO_ACCEPTCONN) {
712 KASSERT((TAILQ_EMPTY(&so->so_comp)), ("sofree: so_comp populated"));
713 KASSERT((TAILQ_EMPTY(&so->so_incomp)), ("sofree: so_incomp populated"));
719 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
720 (*pr->pr_domain->dom_dispose)(so->so_rcv.sb_mb);
721 if (pr->pr_usrreqs->pru_detach != NULL)
722 (*pr->pr_usrreqs->pru_detach)(so);
725 * From this point on, we assume that no other references to this
726 * socket exist anywhere else in the stack. Therefore, no locks need
727 * to be acquired or held.
729 * We used to do a lot of socket buffer and socket locking here, as
730 * well as invoke sorflush() and perform wakeups. The direct call to
731 * dom_dispose() and sbrelease_internal() are an inlining of what was
732 * necessary from sorflush().
734 * Notice that the socket buffer and kqueue state are torn down
735 * before calling pru_detach. This means that protocols shold not
736 * assume they can perform socket wakeups, etc, in their detach code.
738 sbdestroy(&so->so_snd, so);
739 sbdestroy(&so->so_rcv, so);
740 seldrain(&so->so_snd.sb_sel);
741 seldrain(&so->so_rcv.sb_sel);
742 knlist_destroy(&so->so_rcv.sb_sel.si_note);
743 knlist_destroy(&so->so_snd.sb_sel.si_note);
748 * Close a socket on last file table reference removal. Initiate disconnect
749 * if connected. Free socket when disconnect complete.
751 * This function will sorele() the socket. Note that soclose() may be called
752 * prior to the ref count reaching zero. The actual socket structure will
753 * not be freed until the ref count reaches zero.
756 soclose(struct socket *so)
760 KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
762 CURVNET_SET(so->so_vnet);
763 funsetown(&so->so_sigio);
764 if (so->so_state & SS_ISCONNECTED) {
765 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
766 error = sodisconnect(so);
768 if (error == ENOTCONN)
773 if (so->so_options & SO_LINGER) {
774 if ((so->so_state & SS_ISDISCONNECTING) &&
775 (so->so_state & SS_NBIO))
777 while (so->so_state & SS_ISCONNECTED) {
778 error = tsleep(&so->so_timeo,
779 PSOCK | PCATCH, "soclos", so->so_linger * hz);
787 if (so->so_proto->pr_usrreqs->pru_close != NULL)
788 (*so->so_proto->pr_usrreqs->pru_close)(so);
790 if (so->so_options & SO_ACCEPTCONN) {
793 * Prevent new additions to the accept queues due
794 * to ACCEPT_LOCK races while we are draining them.
796 so->so_options &= ~SO_ACCEPTCONN;
797 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
798 TAILQ_REMOVE(&so->so_incomp, sp, so_list);
800 sp->so_qstate &= ~SQ_INCOMP;
806 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
807 TAILQ_REMOVE(&so->so_comp, sp, so_list);
809 sp->so_qstate &= ~SQ_COMP;
815 KASSERT((TAILQ_EMPTY(&so->so_comp)),
816 ("%s: so_comp populated", __func__));
817 KASSERT((TAILQ_EMPTY(&so->so_incomp)),
818 ("%s: so_incomp populated", __func__));
821 KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
822 so->so_state |= SS_NOFDREF;
823 sorele(so); /* NB: Returns with ACCEPT_UNLOCK(). */
829 * soabort() is used to abruptly tear down a connection, such as when a
830 * resource limit is reached (listen queue depth exceeded), or if a listen
831 * socket is closed while there are sockets waiting to be accepted.
833 * This interface is tricky, because it is called on an unreferenced socket,
834 * and must be called only by a thread that has actually removed the socket
835 * from the listen queue it was on, or races with other threads are risked.
837 * This interface will call into the protocol code, so must not be called
838 * with any socket locks held. Protocols do call it while holding their own
839 * recursible protocol mutexes, but this is something that should be subject
840 * to review in the future.
843 soabort(struct socket *so)
847 * In as much as is possible, assert that no references to this
848 * socket are held. This is not quite the same as asserting that the
849 * current thread is responsible for arranging for no references, but
850 * is as close as we can get for now.
852 KASSERT(so->so_count == 0, ("soabort: so_count"));
853 KASSERT((so->so_state & SS_PROTOREF) == 0, ("soabort: SS_PROTOREF"));
854 KASSERT(so->so_state & SS_NOFDREF, ("soabort: !SS_NOFDREF"));
855 KASSERT((so->so_state & SQ_COMP) == 0, ("soabort: SQ_COMP"));
856 KASSERT((so->so_state & SQ_INCOMP) == 0, ("soabort: SQ_INCOMP"));
859 if (so->so_proto->pr_usrreqs->pru_abort != NULL)
860 (*so->so_proto->pr_usrreqs->pru_abort)(so);
867 soaccept(struct socket *so, struct sockaddr **nam)
872 KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
873 so->so_state &= ~SS_NOFDREF;
876 CURVNET_SET(so->so_vnet);
877 error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
883 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
887 if (so->so_options & SO_ACCEPTCONN)
890 CURVNET_SET(so->so_vnet);
892 * If protocol is connection-based, can only connect once.
893 * Otherwise, if connected, try to disconnect first. This allows
894 * user to disconnect by connecting to, e.g., a null address.
896 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
897 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
898 (error = sodisconnect(so)))) {
902 * Prevent accumulated error from previous connection from
906 error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, td);
914 soconnect2(struct socket *so1, struct socket *so2)
918 CURVNET_SET(so1->so_vnet);
919 error = (*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2);
925 sodisconnect(struct socket *so)
929 if ((so->so_state & SS_ISCONNECTED) == 0)
931 if (so->so_state & SS_ISDISCONNECTING)
934 error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
938 #ifdef ZERO_COPY_SOCKETS
939 struct so_zerocopy_stats{
944 struct so_zerocopy_stats so_zerocp_stats = {0,0,0};
947 * sosend_copyin() is only used if zero copy sockets are enabled. Otherwise
948 * sosend_dgram() and sosend_generic() use m_uiotombuf().
950 * sosend_copyin() accepts a uio and prepares an mbuf chain holding part or
951 * all of the data referenced by the uio. If desired, it uses zero-copy.
952 * *space will be updated to reflect data copied in.
954 * NB: If atomic I/O is requested, the caller must already have checked that
955 * space can hold resid bytes.
957 * NB: In the event of an error, the caller may need to free the partial
958 * chain pointed to by *mpp. The contents of both *uio and *space may be
959 * modified even in the case of an error.
962 sosend_copyin(struct uio *uio, struct mbuf **retmp, int atomic, long *space,
965 struct mbuf *m, **mp, *top;
974 resid = uio->uio_resid;
978 if (resid >= MINCLSIZE) {
980 m = m_gethdr(M_WAITOK, MT_DATA);
982 m->m_pkthdr.rcvif = NULL;
984 m = m_get(M_WAITOK, MT_DATA);
985 if (so_zero_copy_send &&
986 resid >= PAGE_SIZE &&
987 *space >= PAGE_SIZE &&
988 uio->uio_iov->iov_len >= PAGE_SIZE) {
989 so_zerocp_stats.size_ok++;
990 so_zerocp_stats.align_ok++;
991 cow_send = socow_setup(m, uio);
995 m_clget(m, M_WAITOK);
996 len = min(min(MCLBYTES, resid), *space);
1000 m = m_gethdr(M_WAIT, MT_DATA);
1001 m->m_pkthdr.len = 0;
1002 m->m_pkthdr.rcvif = NULL;
1004 len = min(min(MHLEN, resid), *space);
1006 * For datagram protocols, leave room
1007 * for protocol headers in first mbuf.
1009 if (atomic && m && len < MHLEN)
1012 m = m_get(M_WAIT, MT_DATA);
1013 len = min(min(MLEN, resid), *space);
1025 error = uiomove(mtod(m, void *), (int)len, uio);
1026 resid = uio->uio_resid;
1029 top->m_pkthdr.len += len;
1034 if (flags & MSG_EOR)
1035 top->m_flags |= M_EOR;
1038 } while (*space > 0 && atomic);
1043 #endif /* ZERO_COPY_SOCKETS */
1045 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? 0 : SBL_WAIT)
1048 sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1049 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1053 int clen = 0, error, dontroute;
1054 #ifdef ZERO_COPY_SOCKETS
1055 int atomic = sosendallatonce(so) || top;
1058 KASSERT(so->so_type == SOCK_DGRAM, ("sodgram_send: !SOCK_DGRAM"));
1059 KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
1060 ("sodgram_send: !PR_ATOMIC"));
1063 resid = uio->uio_resid;
1065 resid = top->m_pkthdr.len;
1067 * In theory resid should be unsigned. However, space must be
1068 * signed, as it might be less than 0 if we over-committed, and we
1069 * must use a signed comparison of space and resid. On the other
1070 * hand, a negative resid causes us to loop sending 0-length
1071 * segments to the protocol.
1079 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
1081 td->td_ru.ru_msgsnd++;
1082 if (control != NULL)
1083 clen = control->m_len;
1085 SOCKBUF_LOCK(&so->so_snd);
1086 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1087 SOCKBUF_UNLOCK(&so->so_snd);
1092 error = so->so_error;
1094 SOCKBUF_UNLOCK(&so->so_snd);
1097 if ((so->so_state & SS_ISCONNECTED) == 0) {
1099 * `sendto' and `sendmsg' is allowed on a connection-based
1100 * socket if it supports implied connect. Return ENOTCONN if
1101 * not connected and no address is supplied.
1103 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1104 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1105 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1106 !(resid == 0 && clen != 0)) {
1107 SOCKBUF_UNLOCK(&so->so_snd);
1111 } else if (addr == NULL) {
1112 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1115 error = EDESTADDRREQ;
1116 SOCKBUF_UNLOCK(&so->so_snd);
1122 * Do we need MSG_OOB support in SOCK_DGRAM? Signs here may be a
1123 * problem and need fixing.
1125 space = sbspace(&so->so_snd);
1126 if (flags & MSG_OOB)
1129 SOCKBUF_UNLOCK(&so->so_snd);
1130 if (resid > space) {
1136 if (flags & MSG_EOR)
1137 top->m_flags |= M_EOR;
1139 #ifdef ZERO_COPY_SOCKETS
1140 error = sosend_copyin(uio, &top, atomic, &space, flags);
1145 * Copy the data from userland into a mbuf chain.
1146 * If no data is to be copied in, a single empty mbuf
1149 top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
1150 (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
1152 error = EFAULT; /* only possible error */
1155 space -= resid - uio->uio_resid;
1157 resid = uio->uio_resid;
1159 KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
1161 * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
1166 so->so_options |= SO_DONTROUTE;
1170 * XXX all the SBS_CANTSENDMORE checks previously done could be out
1171 * of date. We could have recieved a reset packet in an interrupt or
1172 * maybe we slept while doing page faults in uiomove() etc. We could
1173 * probably recheck again inside the locking protection here, but
1174 * there are probably other places that this also happens. We must
1178 error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1179 (flags & MSG_OOB) ? PRUS_OOB :
1181 * If the user set MSG_EOF, the protocol understands this flag and
1182 * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
1184 ((flags & MSG_EOF) &&
1185 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1188 /* If there is more to send set PRUS_MORETOCOME */
1189 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1190 top, addr, control, td);
1193 so->so_options &= ~SO_DONTROUTE;
1202 if (control != NULL)
1208 * Send on a socket. If send must go all at once and message is larger than
1209 * send buffering, then hard error. Lock against other senders. If must go
1210 * all at once and not enough room now, then inform user that this would
1211 * block and do nothing. Otherwise, if nonblocking, send as much as
1212 * possible. The data to be sent is described by "uio" if nonzero, otherwise
1213 * by the mbuf chain "top" (which must be null if uio is not). Data provided
1214 * in mbuf chain must be small enough to send all at once.
1216 * Returns nonzero on error, timeout or signal; callers must check for short
1217 * counts if EINTR/ERESTART are returned. Data and control buffers are freed
1221 sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
1222 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1226 int clen = 0, error, dontroute;
1227 int atomic = sosendallatonce(so) || top;
1230 resid = uio->uio_resid;
1232 resid = top->m_pkthdr.len;
1234 * In theory resid should be unsigned. However, space must be
1235 * signed, as it might be less than 0 if we over-committed, and we
1236 * must use a signed comparison of space and resid. On the other
1237 * hand, a negative resid causes us to loop sending 0-length
1238 * segments to the protocol.
1240 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
1241 * type sockets since that's an error.
1243 if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
1249 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
1250 (so->so_proto->pr_flags & PR_ATOMIC);
1252 td->td_ru.ru_msgsnd++;
1253 if (control != NULL)
1254 clen = control->m_len;
1256 error = sblock(&so->so_snd, SBLOCKWAIT(flags));
1262 SOCKBUF_LOCK(&so->so_snd);
1263 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1264 SOCKBUF_UNLOCK(&so->so_snd);
1269 error = so->so_error;
1271 SOCKBUF_UNLOCK(&so->so_snd);
1274 if ((so->so_state & SS_ISCONNECTED) == 0) {
1276 * `sendto' and `sendmsg' is allowed on a connection-
1277 * based socket if it supports implied connect.
1278 * Return ENOTCONN if not connected and no address is
1281 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1282 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1283 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1284 !(resid == 0 && clen != 0)) {
1285 SOCKBUF_UNLOCK(&so->so_snd);
1289 } else if (addr == NULL) {
1290 SOCKBUF_UNLOCK(&so->so_snd);
1291 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1294 error = EDESTADDRREQ;
1298 space = sbspace(&so->so_snd);
1299 if (flags & MSG_OOB)
1301 if ((atomic && resid > so->so_snd.sb_hiwat) ||
1302 clen > so->so_snd.sb_hiwat) {
1303 SOCKBUF_UNLOCK(&so->so_snd);
1307 if (space < resid + clen &&
1308 (atomic || space < so->so_snd.sb_lowat || space < clen)) {
1309 if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO)) {
1310 SOCKBUF_UNLOCK(&so->so_snd);
1311 error = EWOULDBLOCK;
1314 error = sbwait(&so->so_snd);
1315 SOCKBUF_UNLOCK(&so->so_snd);
1320 SOCKBUF_UNLOCK(&so->so_snd);
1325 if (flags & MSG_EOR)
1326 top->m_flags |= M_EOR;
1328 #ifdef ZERO_COPY_SOCKETS
1329 error = sosend_copyin(uio, &top, atomic,
1335 * Copy the data from userland into a mbuf
1336 * chain. If no data is to be copied in,
1337 * a single empty mbuf is returned.
1339 top = m_uiotombuf(uio, M_WAITOK, space,
1340 (atomic ? max_hdr : 0),
1341 (atomic ? M_PKTHDR : 0) |
1342 ((flags & MSG_EOR) ? M_EOR : 0));
1344 error = EFAULT; /* only possible error */
1347 space -= resid - uio->uio_resid;
1349 resid = uio->uio_resid;
1353 so->so_options |= SO_DONTROUTE;
1357 * XXX all the SBS_CANTSENDMORE checks previously
1358 * done could be out of date. We could have recieved
1359 * a reset packet in an interrupt or maybe we slept
1360 * while doing page faults in uiomove() etc. We
1361 * could probably recheck again inside the locking
1362 * protection here, but there are probably other
1363 * places that this also happens. We must rethink
1367 error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1368 (flags & MSG_OOB) ? PRUS_OOB :
1370 * If the user set MSG_EOF, the protocol understands
1371 * this flag and nothing left to send then use
1372 * PRU_SEND_EOF instead of PRU_SEND.
1374 ((flags & MSG_EOF) &&
1375 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1378 /* If there is more to send set PRUS_MORETOCOME. */
1379 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1380 top, addr, control, td);
1383 so->so_options &= ~SO_DONTROUTE;
1391 } while (resid && space > 0);
1395 sbunlock(&so->so_snd);
1399 if (control != NULL)
1405 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
1406 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1410 CURVNET_SET(so->so_vnet);
1411 error = so->so_proto->pr_usrreqs->pru_sosend(so, addr, uio, top,
1412 control, flags, td);
1418 * The part of soreceive() that implements reading non-inline out-of-band
1419 * data from a socket. For more complete comments, see soreceive(), from
1420 * which this code originated.
1422 * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
1423 * unable to return an mbuf chain to the caller.
1426 soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
1428 struct protosw *pr = so->so_proto;
1432 KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
1435 m = m_get(M_WAIT, MT_DATA);
1436 error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
1440 #ifdef ZERO_COPY_SOCKETS
1441 if (so_zero_copy_receive) {
1444 if ((m->m_flags & M_EXT)
1445 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1450 error = uiomoveco(mtod(m, void *),
1451 min(uio->uio_resid, m->m_len),
1454 #endif /* ZERO_COPY_SOCKETS */
1455 error = uiomove(mtod(m, void *),
1456 (int) min(uio->uio_resid, m->m_len), uio);
1458 } while (uio->uio_resid && error == 0 && m);
1466 * Following replacement or removal of the first mbuf on the first mbuf chain
1467 * of a socket buffer, push necessary state changes back into the socket
1468 * buffer so that other consumers see the values consistently. 'nextrecord'
1469 * is the callers locally stored value of the original value of
1470 * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
1471 * NOTE: 'nextrecord' may be NULL.
1473 static __inline void
1474 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
1477 SOCKBUF_LOCK_ASSERT(sb);
1479 * First, update for the new value of nextrecord. If necessary, make
1480 * it the first record.
1482 if (sb->sb_mb != NULL)
1483 sb->sb_mb->m_nextpkt = nextrecord;
1485 sb->sb_mb = nextrecord;
1488 * Now update any dependent socket buffer fields to reflect the new
1489 * state. This is an expanded inline of SB_EMPTY_FIXUP(), with the
1490 * addition of a second clause that takes care of the case where
1491 * sb_mb has been updated, but remains the last record.
1493 if (sb->sb_mb == NULL) {
1494 sb->sb_mbtail = NULL;
1495 sb->sb_lastrecord = NULL;
1496 } else if (sb->sb_mb->m_nextpkt == NULL)
1497 sb->sb_lastrecord = sb->sb_mb;
1502 * Implement receive operations on a socket. We depend on the way that
1503 * records are added to the sockbuf by sbappend. In particular, each record
1504 * (mbufs linked through m_next) must begin with an address if the protocol
1505 * so specifies, followed by an optional mbuf or mbufs containing ancillary
1506 * data, and then zero or more mbufs of data. In order to allow parallelism
1507 * between network receive and copying to user space, as well as avoid
1508 * sleeping with a mutex held, we release the socket buffer mutex during the
1509 * user space copy. Although the sockbuf is locked, new data may still be
1510 * appended, and thus we must maintain consistency of the sockbuf during that
1513 * The caller may receive the data as a single mbuf chain by supplying an
1514 * mbuf **mp0 for use in returning the chain. The uio is then used only for
1515 * the count in uio_resid.
1518 soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
1519 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1521 struct mbuf *m, **mp;
1522 int flags, error, offset;
1524 struct protosw *pr = so->so_proto;
1525 struct mbuf *nextrecord;
1527 ssize_t orig_resid = uio->uio_resid;
1532 if (controlp != NULL)
1535 flags = *flagsp &~ MSG_EOR;
1538 if (flags & MSG_OOB)
1539 return (soreceive_rcvoob(so, uio, flags));
1542 if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
1543 && uio->uio_resid) {
1545 (*pr->pr_usrreqs->pru_rcvd)(so, 0);
1548 error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
1553 SOCKBUF_LOCK(&so->so_rcv);
1554 m = so->so_rcv.sb_mb;
1556 * If we have less data than requested, block awaiting more (subject
1557 * to any timeout) if:
1558 * 1. the current count is less than the low water mark, or
1559 * 2. MSG_DONTWAIT is not set
1561 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1562 so->so_rcv.sb_cc < uio->uio_resid) &&
1563 so->so_rcv.sb_cc < so->so_rcv.sb_lowat &&
1564 m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
1565 KASSERT(m != NULL || !so->so_rcv.sb_cc,
1566 ("receive: m == %p so->so_rcv.sb_cc == %u",
1567 m, so->so_rcv.sb_cc));
1571 error = so->so_error;
1572 if ((flags & MSG_PEEK) == 0)
1574 SOCKBUF_UNLOCK(&so->so_rcv);
1577 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1578 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1580 SOCKBUF_UNLOCK(&so->so_rcv);
1585 for (; m != NULL; m = m->m_next)
1586 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
1587 m = so->so_rcv.sb_mb;
1590 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1591 (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1592 SOCKBUF_UNLOCK(&so->so_rcv);
1596 if (uio->uio_resid == 0) {
1597 SOCKBUF_UNLOCK(&so->so_rcv);
1600 if ((so->so_state & SS_NBIO) ||
1601 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1602 SOCKBUF_UNLOCK(&so->so_rcv);
1603 error = EWOULDBLOCK;
1606 SBLASTRECORDCHK(&so->so_rcv);
1607 SBLASTMBUFCHK(&so->so_rcv);
1608 error = sbwait(&so->so_rcv);
1609 SOCKBUF_UNLOCK(&so->so_rcv);
1616 * From this point onward, we maintain 'nextrecord' as a cache of the
1617 * pointer to the next record in the socket buffer. We must keep the
1618 * various socket buffer pointers and local stack versions of the
1619 * pointers in sync, pushing out modifications before dropping the
1620 * socket buffer mutex, and re-reading them when picking it up.
1622 * Otherwise, we will race with the network stack appending new data
1623 * or records onto the socket buffer by using inconsistent/stale
1624 * versions of the field, possibly resulting in socket buffer
1627 * By holding the high-level sblock(), we prevent simultaneous
1628 * readers from pulling off the front of the socket buffer.
1630 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1632 uio->uio_td->td_ru.ru_msgrcv++;
1633 KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
1634 SBLASTRECORDCHK(&so->so_rcv);
1635 SBLASTMBUFCHK(&so->so_rcv);
1636 nextrecord = m->m_nextpkt;
1637 if (pr->pr_flags & PR_ADDR) {
1638 KASSERT(m->m_type == MT_SONAME,
1639 ("m->m_type == %d", m->m_type));
1642 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
1644 if (flags & MSG_PEEK) {
1647 sbfree(&so->so_rcv, m);
1648 so->so_rcv.sb_mb = m_free(m);
1649 m = so->so_rcv.sb_mb;
1650 sockbuf_pushsync(&so->so_rcv, nextrecord);
1655 * Process one or more MT_CONTROL mbufs present before any data mbufs
1656 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
1657 * just copy the data; if !MSG_PEEK, we call into the protocol to
1658 * perform externalization (or freeing if controlp == NULL).
1660 if (m != NULL && m->m_type == MT_CONTROL) {
1661 struct mbuf *cm = NULL, *cmn;
1662 struct mbuf **cme = &cm;
1665 if (flags & MSG_PEEK) {
1666 if (controlp != NULL) {
1667 *controlp = m_copy(m, 0, m->m_len);
1668 controlp = &(*controlp)->m_next;
1672 sbfree(&so->so_rcv, m);
1673 so->so_rcv.sb_mb = m->m_next;
1676 cme = &(*cme)->m_next;
1677 m = so->so_rcv.sb_mb;
1679 } while (m != NULL && m->m_type == MT_CONTROL);
1680 if ((flags & MSG_PEEK) == 0)
1681 sockbuf_pushsync(&so->so_rcv, nextrecord);
1682 while (cm != NULL) {
1685 if (pr->pr_domain->dom_externalize != NULL) {
1686 SOCKBUF_UNLOCK(&so->so_rcv);
1688 error = (*pr->pr_domain->dom_externalize)
1690 SOCKBUF_LOCK(&so->so_rcv);
1691 } else if (controlp != NULL)
1695 if (controlp != NULL) {
1697 while (*controlp != NULL)
1698 controlp = &(*controlp)->m_next;
1703 nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1705 nextrecord = so->so_rcv.sb_mb;
1709 if ((flags & MSG_PEEK) == 0) {
1710 KASSERT(m->m_nextpkt == nextrecord,
1711 ("soreceive: post-control, nextrecord !sync"));
1712 if (nextrecord == NULL) {
1713 KASSERT(so->so_rcv.sb_mb == m,
1714 ("soreceive: post-control, sb_mb!=m"));
1715 KASSERT(so->so_rcv.sb_lastrecord == m,
1716 ("soreceive: post-control, lastrecord!=m"));
1720 if (type == MT_OOBDATA)
1723 if ((flags & MSG_PEEK) == 0) {
1724 KASSERT(so->so_rcv.sb_mb == nextrecord,
1725 ("soreceive: sb_mb != nextrecord"));
1726 if (so->so_rcv.sb_mb == NULL) {
1727 KASSERT(so->so_rcv.sb_lastrecord == NULL,
1728 ("soreceive: sb_lastercord != NULL"));
1732 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1733 SBLASTRECORDCHK(&so->so_rcv);
1734 SBLASTMBUFCHK(&so->so_rcv);
1737 * Now continue to read any data mbufs off of the head of the socket
1738 * buffer until the read request is satisfied. Note that 'type' is
1739 * used to store the type of any mbuf reads that have happened so far
1740 * such that soreceive() can stop reading if the type changes, which
1741 * causes soreceive() to return only one of regular data and inline
1742 * out-of-band data in a single socket receive operation.
1746 while (m != NULL && uio->uio_resid > 0 && error == 0) {
1748 * If the type of mbuf has changed since the last mbuf
1749 * examined ('type'), end the receive operation.
1751 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1752 if (m->m_type == MT_OOBDATA || m->m_type == MT_CONTROL) {
1753 if (type != m->m_type)
1755 } else if (type == MT_OOBDATA)
1758 KASSERT(m->m_type == MT_DATA,
1759 ("m->m_type == %d", m->m_type));
1760 so->so_rcv.sb_state &= ~SBS_RCVATMARK;
1761 len = uio->uio_resid;
1762 if (so->so_oobmark && len > so->so_oobmark - offset)
1763 len = so->so_oobmark - offset;
1764 if (len > m->m_len - moff)
1765 len = m->m_len - moff;
1767 * If mp is set, just pass back the mbufs. Otherwise copy
1768 * them out via the uio, then free. Sockbuf must be
1769 * consistent here (points to current mbuf, it points to next
1770 * record) when we drop priority; we must note any additions
1771 * to the sockbuf when we block interrupts again.
1774 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1775 SBLASTRECORDCHK(&so->so_rcv);
1776 SBLASTMBUFCHK(&so->so_rcv);
1777 SOCKBUF_UNLOCK(&so->so_rcv);
1778 #ifdef ZERO_COPY_SOCKETS
1779 if (so_zero_copy_receive) {
1782 if ((m->m_flags & M_EXT)
1783 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1788 error = uiomoveco(mtod(m, char *) + moff,
1792 #endif /* ZERO_COPY_SOCKETS */
1793 error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1794 SOCKBUF_LOCK(&so->so_rcv);
1797 * The MT_SONAME mbuf has already been removed
1798 * from the record, so it is necessary to
1799 * remove the data mbufs, if any, to preserve
1800 * the invariant in the case of PR_ADDR that
1801 * requires MT_SONAME mbufs at the head of
1804 if (m && pr->pr_flags & PR_ATOMIC &&
1805 ((flags & MSG_PEEK) == 0))
1806 (void)sbdroprecord_locked(&so->so_rcv);
1807 SOCKBUF_UNLOCK(&so->so_rcv);
1811 uio->uio_resid -= len;
1812 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1813 if (len == m->m_len - moff) {
1814 if (m->m_flags & M_EOR)
1816 if (flags & MSG_PEEK) {
1820 nextrecord = m->m_nextpkt;
1821 sbfree(&so->so_rcv, m);
1825 so->so_rcv.sb_mb = m = m->m_next;
1828 so->so_rcv.sb_mb = m_free(m);
1829 m = so->so_rcv.sb_mb;
1831 sockbuf_pushsync(&so->so_rcv, nextrecord);
1832 SBLASTRECORDCHK(&so->so_rcv);
1833 SBLASTMBUFCHK(&so->so_rcv);
1836 if (flags & MSG_PEEK)
1842 if (flags & MSG_DONTWAIT)
1843 copy_flag = M_DONTWAIT;
1846 if (copy_flag == M_WAIT)
1847 SOCKBUF_UNLOCK(&so->so_rcv);
1848 *mp = m_copym(m, 0, len, copy_flag);
1849 if (copy_flag == M_WAIT)
1850 SOCKBUF_LOCK(&so->so_rcv);
1853 * m_copym() couldn't
1854 * allocate an mbuf. Adjust
1855 * uio_resid back (it was
1856 * adjusted down by len
1857 * bytes, which we didn't end
1858 * up "copying" over).
1860 uio->uio_resid += len;
1866 so->so_rcv.sb_cc -= len;
1869 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1870 if (so->so_oobmark) {
1871 if ((flags & MSG_PEEK) == 0) {
1872 so->so_oobmark -= len;
1873 if (so->so_oobmark == 0) {
1874 so->so_rcv.sb_state |= SBS_RCVATMARK;
1879 if (offset == so->so_oobmark)
1883 if (flags & MSG_EOR)
1886 * If the MSG_WAITALL flag is set (for non-atomic socket), we
1887 * must not quit until "uio->uio_resid == 0" or an error
1888 * termination. If a signal/timeout occurs, return with a
1889 * short count but without error. Keep sockbuf locked
1890 * against other readers.
1892 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1893 !sosendallatonce(so) && nextrecord == NULL) {
1894 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1895 if (so->so_error || so->so_rcv.sb_state & SBS_CANTRCVMORE)
1898 * Notify the protocol that some data has been
1899 * drained before blocking.
1901 if (pr->pr_flags & PR_WANTRCVD) {
1902 SOCKBUF_UNLOCK(&so->so_rcv);
1904 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1905 SOCKBUF_LOCK(&so->so_rcv);
1907 SBLASTRECORDCHK(&so->so_rcv);
1908 SBLASTMBUFCHK(&so->so_rcv);
1910 * We could receive some data while was notifying
1911 * the protocol. Skip blocking in this case.
1913 if (so->so_rcv.sb_mb == NULL) {
1914 error = sbwait(&so->so_rcv);
1916 SOCKBUF_UNLOCK(&so->so_rcv);
1920 m = so->so_rcv.sb_mb;
1922 nextrecord = m->m_nextpkt;
1926 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1927 if (m != NULL && pr->pr_flags & PR_ATOMIC) {
1929 if ((flags & MSG_PEEK) == 0)
1930 (void) sbdroprecord_locked(&so->so_rcv);
1932 if ((flags & MSG_PEEK) == 0) {
1935 * First part is an inline SB_EMPTY_FIXUP(). Second
1936 * part makes sure sb_lastrecord is up-to-date if
1937 * there is still data in the socket buffer.
1939 so->so_rcv.sb_mb = nextrecord;
1940 if (so->so_rcv.sb_mb == NULL) {
1941 so->so_rcv.sb_mbtail = NULL;
1942 so->so_rcv.sb_lastrecord = NULL;
1943 } else if (nextrecord->m_nextpkt == NULL)
1944 so->so_rcv.sb_lastrecord = nextrecord;
1946 SBLASTRECORDCHK(&so->so_rcv);
1947 SBLASTMBUFCHK(&so->so_rcv);
1949 * If soreceive() is being done from the socket callback,
1950 * then don't need to generate ACK to peer to update window,
1951 * since ACK will be generated on return to TCP.
1953 if (!(flags & MSG_SOCALLBCK) &&
1954 (pr->pr_flags & PR_WANTRCVD)) {
1955 SOCKBUF_UNLOCK(&so->so_rcv);
1957 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1958 SOCKBUF_LOCK(&so->so_rcv);
1961 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1962 if (orig_resid == uio->uio_resid && orig_resid &&
1963 (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
1964 SOCKBUF_UNLOCK(&so->so_rcv);
1967 SOCKBUF_UNLOCK(&so->so_rcv);
1972 sbunlock(&so->so_rcv);
1977 * Optimized version of soreceive() for stream (TCP) sockets.
1978 * XXXAO: (MSG_WAITALL | MSG_PEEK) isn't properly handled.
1981 soreceive_stream(struct socket *so, struct sockaddr **psa, struct uio *uio,
1982 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1984 int len = 0, error = 0, flags, oresid;
1986 struct mbuf *m, *n = NULL;
1988 /* We only do stream sockets. */
1989 if (so->so_type != SOCK_STREAM)
1993 if (controlp != NULL)
1996 flags = *flagsp &~ MSG_EOR;
1999 if (flags & MSG_OOB)
2000 return (soreceive_rcvoob(so, uio, flags));
2006 /* Prevent other readers from entering the socket. */
2007 error = sblock(sb, SBLOCKWAIT(flags));
2012 /* Easy one, no space to copyout anything. */
2013 if (uio->uio_resid == 0) {
2017 oresid = uio->uio_resid;
2019 /* We will never ever get anything unless we are or were connected. */
2020 if (!(so->so_state & (SS_ISCONNECTED|SS_ISDISCONNECTED))) {
2026 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2028 /* Abort if socket has reported problems. */
2032 if (oresid > uio->uio_resid)
2034 error = so->so_error;
2035 if (!(flags & MSG_PEEK))
2040 /* Door is closed. Deliver what is left, if any. */
2041 if (sb->sb_state & SBS_CANTRCVMORE) {
2048 /* Socket buffer is empty and we shall not block. */
2049 if (sb->sb_cc == 0 &&
2050 ((so->so_state & SS_NBIO) || (flags & (MSG_DONTWAIT|MSG_NBIO)))) {
2055 /* Socket buffer got some data that we shall deliver now. */
2056 if (sb->sb_cc > 0 && !(flags & MSG_WAITALL) &&
2057 ((sb->sb_flags & SS_NBIO) ||
2058 (flags & (MSG_DONTWAIT|MSG_NBIO)) ||
2059 sb->sb_cc >= sb->sb_lowat ||
2060 sb->sb_cc >= uio->uio_resid ||
2061 sb->sb_cc >= sb->sb_hiwat) ) {
2065 /* On MSG_WAITALL we must wait until all data or error arrives. */
2066 if ((flags & MSG_WAITALL) &&
2067 (sb->sb_cc >= uio->uio_resid || sb->sb_cc >= sb->sb_hiwat))
2071 * Wait and block until (more) data comes in.
2072 * NB: Drops the sockbuf lock during wait.
2080 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2081 KASSERT(sb->sb_cc > 0, ("%s: sockbuf empty", __func__));
2082 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb == NULL", __func__));
2086 uio->uio_td->td_ru.ru_msgrcv++;
2088 /* Fill uio until full or current end of socket buffer is reached. */
2089 len = min(uio->uio_resid, sb->sb_cc);
2091 /* Dequeue as many mbufs as possible. */
2092 if (!(flags & MSG_PEEK) && len >= sb->sb_mb->m_len) {
2096 m_cat(*mp0, sb->sb_mb);
2098 m != NULL && m->m_len <= len;
2101 uio->uio_resid -= m->m_len;
2107 sb->sb_lastrecord = sb->sb_mb;
2108 if (sb->sb_mb == NULL)
2111 /* Copy the remainder. */
2113 KASSERT(sb->sb_mb != NULL,
2114 ("%s: len > 0 && sb->sb_mb empty", __func__));
2116 m = m_copym(sb->sb_mb, 0, len, M_DONTWAIT);
2118 len = 0; /* Don't flush data from sockbuf. */
2120 uio->uio_resid -= len;
2131 /* NB: Must unlock socket buffer as uiomove may sleep. */
2133 error = m_mbuftouio(uio, sb->sb_mb, len);
2138 SBLASTRECORDCHK(sb);
2142 * Remove the delivered data from the socket buffer unless we
2143 * were only peeking.
2145 if (!(flags & MSG_PEEK)) {
2147 sbdrop_locked(sb, len);
2149 /* Notify protocol that we drained some data. */
2150 if ((so->so_proto->pr_flags & PR_WANTRCVD) &&
2151 (((flags & MSG_WAITALL) && uio->uio_resid > 0) ||
2152 !(flags & MSG_SOCALLBCK))) {
2155 (*so->so_proto->pr_usrreqs->pru_rcvd)(so, flags);
2161 * For MSG_WAITALL we may have to loop again and wait for
2162 * more data to come in.
2164 if ((flags & MSG_WAITALL) && uio->uio_resid > 0)
2167 SOCKBUF_LOCK_ASSERT(sb);
2168 SBLASTRECORDCHK(sb);
2176 * Optimized version of soreceive() for simple datagram cases from userspace.
2177 * Unlike in the stream case, we're able to drop a datagram if copyout()
2178 * fails, and because we handle datagrams atomically, we don't need to use a
2179 * sleep lock to prevent I/O interlacing.
2182 soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
2183 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2185 struct mbuf *m, *m2;
2188 struct protosw *pr = so->so_proto;
2189 struct mbuf *nextrecord;
2193 if (controlp != NULL)
2196 flags = *flagsp &~ MSG_EOR;
2201 * For any complicated cases, fall back to the full
2202 * soreceive_generic().
2204 if (mp0 != NULL || (flags & MSG_PEEK) || (flags & MSG_OOB))
2205 return (soreceive_generic(so, psa, uio, mp0, controlp,
2209 * Enforce restrictions on use.
2211 KASSERT((pr->pr_flags & PR_WANTRCVD) == 0,
2212 ("soreceive_dgram: wantrcvd"));
2213 KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic"));
2214 KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0,
2215 ("soreceive_dgram: SBS_RCVATMARK"));
2216 KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0,
2217 ("soreceive_dgram: P_CONNREQUIRED"));
2220 * Loop blocking while waiting for a datagram.
2222 SOCKBUF_LOCK(&so->so_rcv);
2223 while ((m = so->so_rcv.sb_mb) == NULL) {
2224 KASSERT(so->so_rcv.sb_cc == 0,
2225 ("soreceive_dgram: sb_mb NULL but sb_cc %u",
2228 error = so->so_error;
2230 SOCKBUF_UNLOCK(&so->so_rcv);
2233 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
2234 uio->uio_resid == 0) {
2235 SOCKBUF_UNLOCK(&so->so_rcv);
2238 if ((so->so_state & SS_NBIO) ||
2239 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
2240 SOCKBUF_UNLOCK(&so->so_rcv);
2241 return (EWOULDBLOCK);
2243 SBLASTRECORDCHK(&so->so_rcv);
2244 SBLASTMBUFCHK(&so->so_rcv);
2245 error = sbwait(&so->so_rcv);
2247 SOCKBUF_UNLOCK(&so->so_rcv);
2251 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2254 uio->uio_td->td_ru.ru_msgrcv++;
2255 SBLASTRECORDCHK(&so->so_rcv);
2256 SBLASTMBUFCHK(&so->so_rcv);
2257 nextrecord = m->m_nextpkt;
2258 if (nextrecord == NULL) {
2259 KASSERT(so->so_rcv.sb_lastrecord == m,
2260 ("soreceive_dgram: lastrecord != m"));
2263 KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord,
2264 ("soreceive_dgram: m_nextpkt != nextrecord"));
2267 * Pull 'm' and its chain off the front of the packet queue.
2269 so->so_rcv.sb_mb = NULL;
2270 sockbuf_pushsync(&so->so_rcv, nextrecord);
2273 * Walk 'm's chain and free that many bytes from the socket buffer.
2275 for (m2 = m; m2 != NULL; m2 = m2->m_next)
2276 sbfree(&so->so_rcv, m2);
2279 * Do a few last checks before we let go of the lock.
2281 SBLASTRECORDCHK(&so->so_rcv);
2282 SBLASTMBUFCHK(&so->so_rcv);
2283 SOCKBUF_UNLOCK(&so->so_rcv);
2285 if (pr->pr_flags & PR_ADDR) {
2286 KASSERT(m->m_type == MT_SONAME,
2287 ("m->m_type == %d", m->m_type));
2289 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
2294 /* XXXRW: Can this happen? */
2299 * Packet to copyout() is now in 'm' and it is disconnected from the
2302 * Process one or more MT_CONTROL mbufs present before any data mbufs
2303 * in the first mbuf chain on the socket buffer. We call into the
2304 * protocol to perform externalization (or freeing if controlp ==
2307 if (m->m_type == MT_CONTROL) {
2308 struct mbuf *cm = NULL, *cmn;
2309 struct mbuf **cme = &cm;
2315 cme = &(*cme)->m_next;
2317 } while (m != NULL && m->m_type == MT_CONTROL);
2318 while (cm != NULL) {
2321 if (pr->pr_domain->dom_externalize != NULL) {
2322 error = (*pr->pr_domain->dom_externalize)
2324 } else if (controlp != NULL)
2328 if (controlp != NULL) {
2329 while (*controlp != NULL)
2330 controlp = &(*controlp)->m_next;
2335 KASSERT(m->m_type == MT_DATA, ("soreceive_dgram: !data"));
2337 while (m != NULL && uio->uio_resid > 0) {
2338 len = uio->uio_resid;
2341 error = uiomove(mtod(m, char *), (int)len, uio);
2346 if (len == m->m_len)
2362 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
2363 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2367 CURVNET_SET(so->so_vnet);
2368 error = (so->so_proto->pr_usrreqs->pru_soreceive(so, psa, uio, mp0,
2375 soshutdown(struct socket *so, int how)
2377 struct protosw *pr = so->so_proto;
2380 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
2383 CURVNET_SET(so->so_vnet);
2384 if (pr->pr_usrreqs->pru_flush != NULL) {
2385 (*pr->pr_usrreqs->pru_flush)(so, how);
2389 if (how != SHUT_RD) {
2390 error = (*pr->pr_usrreqs->pru_shutdown)(so);
2391 wakeup(&so->so_timeo);
2395 wakeup(&so->so_timeo);
2401 sorflush(struct socket *so)
2403 struct sockbuf *sb = &so->so_rcv;
2404 struct protosw *pr = so->so_proto;
2410 * In order to avoid calling dom_dispose with the socket buffer mutex
2411 * held, and in order to generally avoid holding the lock for a long
2412 * time, we make a copy of the socket buffer and clear the original
2413 * (except locks, state). The new socket buffer copy won't have
2414 * initialized locks so we can only call routines that won't use or
2415 * assert those locks.
2417 * Dislodge threads currently blocked in receive and wait to acquire
2418 * a lock against other simultaneous readers before clearing the
2419 * socket buffer. Don't let our acquire be interrupted by a signal
2420 * despite any existing socket disposition on interruptable waiting.
2423 (void) sblock(sb, SBL_WAIT | SBL_NOINTR);
2426 * Invalidate/clear most of the sockbuf structure, but leave selinfo
2427 * and mutex data unchanged.
2430 bzero(&asb, offsetof(struct sockbuf, sb_startzero));
2431 bcopy(&sb->sb_startzero, &asb.sb_startzero,
2432 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2433 bzero(&sb->sb_startzero,
2434 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2439 * Dispose of special rights and flush the socket buffer. Don't call
2440 * any unsafe routines (that rely on locks being initialized) on asb.
2442 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
2443 (*pr->pr_domain->dom_dispose)(asb.sb_mb);
2444 sbrelease_internal(&asb, so);
2448 * Perhaps this routine, and sooptcopyout(), below, ought to come in an
2449 * additional variant to handle the case where the option value needs to be
2450 * some kind of integer, but not a specific size. In addition to their use
2451 * here, these functions are also called by the protocol-level pr_ctloutput()
2455 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2460 * If the user gives us more than we wanted, we ignore it, but if we
2461 * don't get the minimum length the caller wants, we return EINVAL.
2462 * On success, sopt->sopt_valsize is set to however much we actually
2465 if ((valsize = sopt->sopt_valsize) < minlen)
2468 sopt->sopt_valsize = valsize = len;
2470 if (sopt->sopt_td != NULL)
2471 return (copyin(sopt->sopt_val, buf, valsize));
2473 bcopy(sopt->sopt_val, buf, valsize);
2478 * Kernel version of setsockopt(2).
2480 * XXX: optlen is size_t, not socklen_t
2483 so_setsockopt(struct socket *so, int level, int optname, void *optval,
2486 struct sockopt sopt;
2488 sopt.sopt_level = level;
2489 sopt.sopt_name = optname;
2490 sopt.sopt_dir = SOPT_SET;
2491 sopt.sopt_val = optval;
2492 sopt.sopt_valsize = optlen;
2493 sopt.sopt_td = NULL;
2494 return (sosetopt(so, &sopt));
2498 sosetopt(struct socket *so, struct sockopt *sopt)
2509 CURVNET_SET(so->so_vnet);
2511 if (sopt->sopt_level != SOL_SOCKET) {
2512 if (so->so_proto->pr_ctloutput != NULL) {
2513 error = (*so->so_proto->pr_ctloutput)(so, sopt);
2517 error = ENOPROTOOPT;
2519 switch (sopt->sopt_name) {
2521 case SO_ACCEPTFILTER:
2522 error = do_setopt_accept_filter(so, sopt);
2528 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
2533 so->so_linger = l.l_linger;
2535 so->so_options |= SO_LINGER;
2537 so->so_options &= ~SO_LINGER;
2544 case SO_USELOOPBACK:
2554 error = sooptcopyin(sopt, &optval, sizeof optval,
2560 so->so_options |= sopt->sopt_name;
2562 so->so_options &= ~sopt->sopt_name;
2567 error = sooptcopyin(sopt, &optval, sizeof optval,
2572 if (optval < 0 || optval >= rt_numfibs) {
2576 if (((so->so_proto->pr_domain->dom_family == PF_INET) ||
2577 (so->so_proto->pr_domain->dom_family == PF_INET6) ||
2578 (so->so_proto->pr_domain->dom_family == PF_ROUTE)))
2579 so->so_fibnum = optval;
2584 case SO_USER_COOKIE:
2585 error = sooptcopyin(sopt, &val32, sizeof val32,
2589 so->so_user_cookie = val32;
2596 error = sooptcopyin(sopt, &optval, sizeof optval,
2602 * Values < 1 make no sense for any of these options,
2610 switch (sopt->sopt_name) {
2613 if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
2614 &so->so_snd : &so->so_rcv, (u_long)optval,
2615 so, curthread) == 0) {
2619 (sopt->sopt_name == SO_SNDBUF ? &so->so_snd :
2620 &so->so_rcv)->sb_flags &= ~SB_AUTOSIZE;
2624 * Make sure the low-water is never greater than the
2628 SOCKBUF_LOCK(&so->so_snd);
2629 so->so_snd.sb_lowat =
2630 (optval > so->so_snd.sb_hiwat) ?
2631 so->so_snd.sb_hiwat : optval;
2632 SOCKBUF_UNLOCK(&so->so_snd);
2635 SOCKBUF_LOCK(&so->so_rcv);
2636 so->so_rcv.sb_lowat =
2637 (optval > so->so_rcv.sb_hiwat) ?
2638 so->so_rcv.sb_hiwat : optval;
2639 SOCKBUF_UNLOCK(&so->so_rcv);
2646 #ifdef COMPAT_FREEBSD32
2647 if (SV_CURPROC_FLAG(SV_ILP32)) {
2648 struct timeval32 tv32;
2650 error = sooptcopyin(sopt, &tv32, sizeof tv32,
2652 CP(tv32, tv, tv_sec);
2653 CP(tv32, tv, tv_usec);
2656 error = sooptcopyin(sopt, &tv, sizeof tv,
2661 /* assert(hz > 0); */
2662 if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
2663 tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
2667 /* assert(tick > 0); */
2668 /* assert(ULONG_MAX - INT_MAX >= 1000000); */
2669 val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
2670 if (val > INT_MAX) {
2674 if (val == 0 && tv.tv_usec != 0)
2677 switch (sopt->sopt_name) {
2679 so->so_snd.sb_timeo = val;
2682 so->so_rcv.sb_timeo = val;
2689 error = sooptcopyin(sopt, &extmac, sizeof extmac,
2693 error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
2701 error = ENOPROTOOPT;
2704 if (error == 0 && so->so_proto->pr_ctloutput != NULL)
2705 (void)(*so->so_proto->pr_ctloutput)(so, sopt);
2713 * Helper routine for getsockopt.
2716 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
2724 * Documented get behavior is that we always return a value, possibly
2725 * truncated to fit in the user's buffer. Traditional behavior is
2726 * that we always tell the user precisely how much we copied, rather
2727 * than something useful like the total amount we had available for
2728 * her. Note that this interface is not idempotent; the entire
2729 * answer must generated ahead of time.
2731 valsize = min(len, sopt->sopt_valsize);
2732 sopt->sopt_valsize = valsize;
2733 if (sopt->sopt_val != NULL) {
2734 if (sopt->sopt_td != NULL)
2735 error = copyout(buf, sopt->sopt_val, valsize);
2737 bcopy(buf, sopt->sopt_val, valsize);
2743 sogetopt(struct socket *so, struct sockopt *sopt)
2752 CURVNET_SET(so->so_vnet);
2754 if (sopt->sopt_level != SOL_SOCKET) {
2755 if (so->so_proto->pr_ctloutput != NULL)
2756 error = (*so->so_proto->pr_ctloutput)(so, sopt);
2758 error = ENOPROTOOPT;
2762 switch (sopt->sopt_name) {
2764 case SO_ACCEPTFILTER:
2765 error = do_getopt_accept_filter(so, sopt);
2770 l.l_onoff = so->so_options & SO_LINGER;
2771 l.l_linger = so->so_linger;
2773 error = sooptcopyout(sopt, &l, sizeof l);
2776 case SO_USELOOPBACK:
2788 optval = so->so_options & sopt->sopt_name;
2790 error = sooptcopyout(sopt, &optval, sizeof optval);
2794 optval = so->so_type;
2798 optval = so->so_proto->pr_protocol;
2803 optval = so->so_error;
2809 optval = so->so_snd.sb_hiwat;
2813 optval = so->so_rcv.sb_hiwat;
2817 optval = so->so_snd.sb_lowat;
2821 optval = so->so_rcv.sb_lowat;
2826 optval = (sopt->sopt_name == SO_SNDTIMEO ?
2827 so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
2829 tv.tv_sec = optval / hz;
2830 tv.tv_usec = (optval % hz) * tick;
2831 #ifdef COMPAT_FREEBSD32
2832 if (SV_CURPROC_FLAG(SV_ILP32)) {
2833 struct timeval32 tv32;
2835 CP(tv, tv32, tv_sec);
2836 CP(tv, tv32, tv_usec);
2837 error = sooptcopyout(sopt, &tv32, sizeof tv32);
2840 error = sooptcopyout(sopt, &tv, sizeof tv);
2845 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2849 error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
2853 error = sooptcopyout(sopt, &extmac, sizeof extmac);
2861 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2865 error = mac_getsockopt_peerlabel(
2866 sopt->sopt_td->td_ucred, so, &extmac);
2869 error = sooptcopyout(sopt, &extmac, sizeof extmac);
2875 case SO_LISTENQLIMIT:
2876 optval = so->so_qlimit;
2880 optval = so->so_qlen;
2883 case SO_LISTENINCQLEN:
2884 optval = so->so_incqlen;
2888 error = ENOPROTOOPT;
2899 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
2901 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
2903 struct mbuf *m, *m_prev;
2904 int sopt_size = sopt->sopt_valsize;
2906 MGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT, MT_DATA);
2909 if (sopt_size > MLEN) {
2910 MCLGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT);
2911 if ((m->m_flags & M_EXT) == 0) {
2915 m->m_len = min(MCLBYTES, sopt_size);
2917 m->m_len = min(MLEN, sopt_size);
2919 sopt_size -= m->m_len;
2924 MGET(m, sopt->sopt_td ? M_WAIT : M_DONTWAIT, MT_DATA);
2929 if (sopt_size > MLEN) {
2930 MCLGET(m, sopt->sopt_td != NULL ? M_WAIT :
2932 if ((m->m_flags & M_EXT) == 0) {
2937 m->m_len = min(MCLBYTES, sopt_size);
2939 m->m_len = min(MLEN, sopt_size);
2941 sopt_size -= m->m_len;
2948 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
2950 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
2952 struct mbuf *m0 = m;
2954 if (sopt->sopt_val == NULL)
2956 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2957 if (sopt->sopt_td != NULL) {
2960 error = copyin(sopt->sopt_val, mtod(m, char *),
2967 bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
2968 sopt->sopt_valsize -= m->m_len;
2969 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2972 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
2973 panic("ip6_sooptmcopyin");
2977 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
2979 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
2981 struct mbuf *m0 = m;
2984 if (sopt->sopt_val == NULL)
2986 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2987 if (sopt->sopt_td != NULL) {
2990 error = copyout(mtod(m, char *), sopt->sopt_val,
2997 bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
2998 sopt->sopt_valsize -= m->m_len;
2999 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
3000 valsize += m->m_len;
3004 /* enough soopt buffer should be given from user-land */
3008 sopt->sopt_valsize = valsize;
3013 * sohasoutofband(): protocol notifies socket layer of the arrival of new
3014 * out-of-band data, which will then notify socket consumers.
3017 sohasoutofband(struct socket *so)
3020 if (so->so_sigio != NULL)
3021 pgsigio(&so->so_sigio, SIGURG, 0);
3022 selwakeuppri(&so->so_rcv.sb_sel, PSOCK);
3026 sopoll(struct socket *so, int events, struct ucred *active_cred,
3031 * We do not need to set or assert curvnet as long as everyone uses
3034 return (so->so_proto->pr_usrreqs->pru_sopoll(so, events, active_cred,
3039 sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
3044 SOCKBUF_LOCK(&so->so_snd);
3045 SOCKBUF_LOCK(&so->so_rcv);
3046 if (events & (POLLIN | POLLRDNORM))
3047 if (soreadabledata(so))
3048 revents |= events & (POLLIN | POLLRDNORM);
3050 if (events & (POLLOUT | POLLWRNORM))
3051 if (sowriteable(so))
3052 revents |= events & (POLLOUT | POLLWRNORM);
3054 if (events & (POLLPRI | POLLRDBAND))
3055 if (so->so_oobmark || (so->so_rcv.sb_state & SBS_RCVATMARK))
3056 revents |= events & (POLLPRI | POLLRDBAND);
3058 if ((events & POLLINIGNEOF) == 0) {
3059 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3060 revents |= events & (POLLIN | POLLRDNORM);
3061 if (so->so_snd.sb_state & SBS_CANTSENDMORE)
3067 if (events & (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND)) {
3068 selrecord(td, &so->so_rcv.sb_sel);
3069 so->so_rcv.sb_flags |= SB_SEL;
3072 if (events & (POLLOUT | POLLWRNORM)) {
3073 selrecord(td, &so->so_snd.sb_sel);
3074 so->so_snd.sb_flags |= SB_SEL;
3078 SOCKBUF_UNLOCK(&so->so_rcv);
3079 SOCKBUF_UNLOCK(&so->so_snd);
3084 soo_kqfilter(struct file *fp, struct knote *kn)
3086 struct socket *so = kn->kn_fp->f_data;
3089 switch (kn->kn_filter) {
3091 if (so->so_options & SO_ACCEPTCONN)
3092 kn->kn_fop = &solisten_filtops;
3094 kn->kn_fop = &soread_filtops;
3098 kn->kn_fop = &sowrite_filtops;
3106 knlist_add(&sb->sb_sel.si_note, kn, 1);
3107 sb->sb_flags |= SB_KNOTE;
3113 * Some routines that return EOPNOTSUPP for entry points that are not
3114 * supported by a protocol. Fill in as needed.
3117 pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
3124 pru_attach_notsupp(struct socket *so, int proto, struct thread *td)
3131 pru_bind_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
3138 pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
3145 pru_connect2_notsupp(struct socket *so1, struct socket *so2)
3152 pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
3153 struct ifnet *ifp, struct thread *td)
3160 pru_disconnect_notsupp(struct socket *so)
3167 pru_listen_notsupp(struct socket *so, int backlog, struct thread *td)
3174 pru_peeraddr_notsupp(struct socket *so, struct sockaddr **nam)
3181 pru_rcvd_notsupp(struct socket *so, int flags)
3188 pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
3195 pru_send_notsupp(struct socket *so, int flags, struct mbuf *m,
3196 struct sockaddr *addr, struct mbuf *control, struct thread *td)
3203 * This isn't really a ``null'' operation, but it's the default one and
3204 * doesn't do anything destructive.
3207 pru_sense_null(struct socket *so, struct stat *sb)
3210 sb->st_blksize = so->so_snd.sb_hiwat;
3215 pru_shutdown_notsupp(struct socket *so)
3222 pru_sockaddr_notsupp(struct socket *so, struct sockaddr **nam)
3229 pru_sosend_notsupp(struct socket *so, struct sockaddr *addr, struct uio *uio,
3230 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
3237 pru_soreceive_notsupp(struct socket *so, struct sockaddr **paddr,
3238 struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
3245 pru_sopoll_notsupp(struct socket *so, int events, struct ucred *cred,
3253 filt_sordetach(struct knote *kn)
3255 struct socket *so = kn->kn_fp->f_data;
3257 SOCKBUF_LOCK(&so->so_rcv);
3258 knlist_remove(&so->so_rcv.sb_sel.si_note, kn, 1);
3259 if (knlist_empty(&so->so_rcv.sb_sel.si_note))
3260 so->so_rcv.sb_flags &= ~SB_KNOTE;
3261 SOCKBUF_UNLOCK(&so->so_rcv);
3266 filt_soread(struct knote *kn, long hint)
3270 so = kn->kn_fp->f_data;
3271 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3273 kn->kn_data = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
3274 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3275 kn->kn_flags |= EV_EOF;
3276 kn->kn_fflags = so->so_error;
3278 } else if (so->so_error) /* temporary udp error */
3280 else if (kn->kn_sfflags & NOTE_LOWAT)
3281 return (kn->kn_data >= kn->kn_sdata);
3283 return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat);
3287 filt_sowdetach(struct knote *kn)
3289 struct socket *so = kn->kn_fp->f_data;
3291 SOCKBUF_LOCK(&so->so_snd);
3292 knlist_remove(&so->so_snd.sb_sel.si_note, kn, 1);
3293 if (knlist_empty(&so->so_snd.sb_sel.si_note))
3294 so->so_snd.sb_flags &= ~SB_KNOTE;
3295 SOCKBUF_UNLOCK(&so->so_snd);
3300 filt_sowrite(struct knote *kn, long hint)
3304 so = kn->kn_fp->f_data;
3305 SOCKBUF_LOCK_ASSERT(&so->so_snd);
3306 kn->kn_data = sbspace(&so->so_snd);
3307 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
3308 kn->kn_flags |= EV_EOF;
3309 kn->kn_fflags = so->so_error;
3311 } else if (so->so_error) /* temporary udp error */
3313 else if (((so->so_state & SS_ISCONNECTED) == 0) &&
3314 (so->so_proto->pr_flags & PR_CONNREQUIRED))
3316 else if (kn->kn_sfflags & NOTE_LOWAT)
3317 return (kn->kn_data >= kn->kn_sdata);
3319 return (kn->kn_data >= so->so_snd.sb_lowat);
3324 filt_solisten(struct knote *kn, long hint)
3326 struct socket *so = kn->kn_fp->f_data;
3328 kn->kn_data = so->so_qlen;
3329 return (! TAILQ_EMPTY(&so->so_comp));
3333 socheckuid(struct socket *so, uid_t uid)
3338 if (so->so_cred->cr_uid != uid)
3344 * These functions are used by protocols to notify the socket layer (and its
3345 * consumers) of state changes in the sockets driven by protocol-side events.
3349 * Procedures to manipulate state flags of socket and do appropriate wakeups.
3351 * Normal sequence from the active (originating) side is that
3352 * soisconnecting() is called during processing of connect() call, resulting
3353 * in an eventual call to soisconnected() if/when the connection is
3354 * established. When the connection is torn down soisdisconnecting() is
3355 * called during processing of disconnect() call, and soisdisconnected() is
3356 * called when the connection to the peer is totally severed. The semantics
3357 * of these routines are such that connectionless protocols can call
3358 * soisconnected() and soisdisconnected() only, bypassing the in-progress
3359 * calls when setting up a ``connection'' takes no time.
3361 * From the passive side, a socket is created with two queues of sockets:
3362 * so_incomp for connections in progress and so_comp for connections already
3363 * made and awaiting user acceptance. As a protocol is preparing incoming
3364 * connections, it creates a socket structure queued on so_incomp by calling
3365 * sonewconn(). When the connection is established, soisconnected() is
3366 * called, and transfers the socket structure to so_comp, making it available
3369 * If a socket is closed with sockets on either so_incomp or so_comp, these
3370 * sockets are dropped.
3372 * If higher-level protocols are implemented in the kernel, the wakeups done
3373 * here will sometimes cause software-interrupt process scheduling.
3376 soisconnecting(struct socket *so)
3380 so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
3381 so->so_state |= SS_ISCONNECTING;
3386 soisconnected(struct socket *so)
3388 struct socket *head;
3394 so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
3395 so->so_state |= SS_ISCONNECTED;
3397 if (head != NULL && (so->so_qstate & SQ_INCOMP)) {
3398 if ((so->so_options & SO_ACCEPTFILTER) == 0) {
3400 TAILQ_REMOVE(&head->so_incomp, so, so_list);
3402 so->so_qstate &= ~SQ_INCOMP;
3403 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
3405 so->so_qstate |= SQ_COMP;
3408 wakeup_one(&head->so_timeo);
3411 soupcall_set(so, SO_RCV,
3412 head->so_accf->so_accept_filter->accf_callback,
3413 head->so_accf->so_accept_filter_arg);
3414 so->so_options &= ~SO_ACCEPTFILTER;
3415 ret = head->so_accf->so_accept_filter->accf_callback(so,
3416 head->so_accf->so_accept_filter_arg, M_DONTWAIT);
3417 if (ret == SU_ISCONNECTED)
3418 soupcall_clear(so, SO_RCV);
3420 if (ret == SU_ISCONNECTED)
3427 wakeup(&so->so_timeo);
3433 soisdisconnecting(struct socket *so)
3437 * Note: This code assumes that SOCK_LOCK(so) and
3438 * SOCKBUF_LOCK(&so->so_rcv) are the same.
3440 SOCKBUF_LOCK(&so->so_rcv);
3441 so->so_state &= ~SS_ISCONNECTING;
3442 so->so_state |= SS_ISDISCONNECTING;
3443 so->so_rcv.sb_state |= SBS_CANTRCVMORE;
3444 sorwakeup_locked(so);
3445 SOCKBUF_LOCK(&so->so_snd);
3446 so->so_snd.sb_state |= SBS_CANTSENDMORE;
3447 sowwakeup_locked(so);
3448 wakeup(&so->so_timeo);
3452 soisdisconnected(struct socket *so)
3456 * Note: This code assumes that SOCK_LOCK(so) and
3457 * SOCKBUF_LOCK(&so->so_rcv) are the same.
3459 SOCKBUF_LOCK(&so->so_rcv);
3460 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
3461 so->so_state |= SS_ISDISCONNECTED;
3462 so->so_rcv.sb_state |= SBS_CANTRCVMORE;
3463 sorwakeup_locked(so);
3464 SOCKBUF_LOCK(&so->so_snd);
3465 so->so_snd.sb_state |= SBS_CANTSENDMORE;
3466 sbdrop_locked(&so->so_snd, so->so_snd.sb_cc);
3467 sowwakeup_locked(so);
3468 wakeup(&so->so_timeo);
3472 * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
3475 sodupsockaddr(const struct sockaddr *sa, int mflags)
3477 struct sockaddr *sa2;
3479 sa2 = malloc(sa->sa_len, M_SONAME, mflags);
3481 bcopy(sa, sa2, sa->sa_len);
3486 * Register per-socket buffer upcalls.
3489 soupcall_set(struct socket *so, int which,
3490 int (*func)(struct socket *, void *, int), void *arg)
3502 panic("soupcall_set: bad which");
3504 SOCKBUF_LOCK_ASSERT(sb);
3506 /* XXX: accf_http actually wants to do this on purpose. */
3507 KASSERT(sb->sb_upcall == NULL, ("soupcall_set: overwriting upcall"));
3509 sb->sb_upcall = func;
3510 sb->sb_upcallarg = arg;
3511 sb->sb_flags |= SB_UPCALL;
3515 soupcall_clear(struct socket *so, int which)
3527 panic("soupcall_clear: bad which");
3529 SOCKBUF_LOCK_ASSERT(sb);
3530 KASSERT(sb->sb_upcall != NULL, ("soupcall_clear: no upcall to clear"));
3531 sb->sb_upcall = NULL;
3532 sb->sb_upcallarg = NULL;
3533 sb->sb_flags &= ~SB_UPCALL;
3537 * Create an external-format (``xsocket'') structure using the information in
3538 * the kernel-format socket structure pointed to by so. This is done to
3539 * reduce the spew of irrelevant information over this interface, to isolate
3540 * user code from changes in the kernel structure, and potentially to provide
3541 * information-hiding if we decide that some of this information should be
3542 * hidden from users.
3545 sotoxsocket(struct socket *so, struct xsocket *xso)
3548 xso->xso_len = sizeof *xso;
3550 xso->so_type = so->so_type;
3551 xso->so_options = so->so_options;
3552 xso->so_linger = so->so_linger;
3553 xso->so_state = so->so_state;
3554 xso->so_pcb = so->so_pcb;
3555 xso->xso_protocol = so->so_proto->pr_protocol;
3556 xso->xso_family = so->so_proto->pr_domain->dom_family;
3557 xso->so_qlen = so->so_qlen;
3558 xso->so_incqlen = so->so_incqlen;
3559 xso->so_qlimit = so->so_qlimit;
3560 xso->so_timeo = so->so_timeo;
3561 xso->so_error = so->so_error;
3562 xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
3563 xso->so_oobmark = so->so_oobmark;
3564 sbtoxsockbuf(&so->so_snd, &xso->so_snd);
3565 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
3566 xso->so_uid = so->so_cred->cr_uid;
3571 * Socket accessor functions to provide external consumers with
3572 * a safe interface to socket state
3577 so_listeners_apply_all(struct socket *so, void (*func)(struct socket *, void *), void *arg)
3580 TAILQ_FOREACH(so, &so->so_comp, so_list)
3585 so_sockbuf_rcv(struct socket *so)
3588 return (&so->so_rcv);
3592 so_sockbuf_snd(struct socket *so)
3595 return (&so->so_snd);
3599 so_state_get(const struct socket *so)
3602 return (so->so_state);
3606 so_state_set(struct socket *so, int val)
3613 so_options_get(const struct socket *so)
3616 return (so->so_options);
3620 so_options_set(struct socket *so, int val)
3623 so->so_options = val;
3627 so_error_get(const struct socket *so)
3630 return (so->so_error);
3634 so_error_set(struct socket *so, int val)
3641 so_linger_get(const struct socket *so)
3644 return (so->so_linger);
3648 so_linger_set(struct socket *so, int val)
3651 so->so_linger = val;
3655 so_protosw_get(const struct socket *so)
3658 return (so->so_proto);
3662 so_protosw_set(struct socket *so, struct protosw *val)
3669 so_sorwakeup(struct socket *so)
3676 so_sowwakeup(struct socket *so)
3683 so_sorwakeup_locked(struct socket *so)
3686 sorwakeup_locked(so);
3690 so_sowwakeup_locked(struct socket *so)
3693 sowwakeup_locked(so);
3697 so_lock(struct socket *so)
3703 so_unlock(struct socket *so)