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
190 * NB: The orginal sysctl somaxconn is still available but hidden
191 * to prevent confusion about the actual purpose of this number.
193 static int somaxconn = SOMAXCONN;
196 sysctl_somaxconn(SYSCTL_HANDLER_ARGS)
202 error = sysctl_handle_int(oidp, &val, 0, req);
203 if (error || !req->newptr )
206 if (val < 1 || val > USHRT_MAX)
212 SYSCTL_PROC(_kern_ipc, OID_AUTO, soacceptqueue, CTLTYPE_UINT | CTLFLAG_RW,
213 0, sizeof(int), sysctl_somaxconn, "I",
214 "Maximum listen socket pending connection accept queue size");
215 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn,
216 CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_SKIP,
217 0, sizeof(int), sysctl_somaxconn, "I",
218 "Maximum listen socket pending connection accept queue size (compat)");
220 static int numopensockets;
221 SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
222 &numopensockets, 0, "Number of open sockets");
224 #if defined(SOCKET_SEND_COW) || defined(SOCKET_RECV_PFLIP)
225 SYSCTL_NODE(_kern_ipc, OID_AUTO, zero_copy, CTLFLAG_RD, 0,
226 "Zero copy controls");
227 #ifdef SOCKET_RECV_PFLIP
228 int so_zero_copy_receive = 1;
229 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, receive, CTLFLAG_RW,
230 &so_zero_copy_receive, 0, "Enable zero copy receive");
232 #ifdef SOCKET_SEND_COW
233 int so_zero_copy_send = 1;
234 SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, send, CTLFLAG_RW,
235 &so_zero_copy_send, 0, "Enable zero copy send");
236 #endif /* SOCKET_SEND_COW */
237 #endif /* SOCKET_SEND_COW || SOCKET_RECV_PFLIP */
240 * accept_mtx locks down per-socket fields relating to accept queues. See
241 * socketvar.h for an annotation of the protected fields of struct socket.
243 struct mtx accept_mtx;
244 MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
247 * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
250 static struct mtx so_global_mtx;
251 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
254 * General IPC sysctl name space, used by sockets and a variety of other IPC
257 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
260 * Initialize the socket subsystem and set up the socket
263 static uma_zone_t socket_zone;
267 socket_zone_change(void *tag)
270 maxsockets = uma_zone_set_max(socket_zone, maxsockets);
274 socket_init(void *tag)
277 socket_zone = uma_zcreate("socket", sizeof(struct socket), NULL, NULL,
278 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
279 maxsockets = uma_zone_set_max(socket_zone, maxsockets);
280 uma_zone_set_warning(socket_zone, "kern.ipc.maxsockets limit reached");
281 EVENTHANDLER_REGISTER(maxsockets_change, socket_zone_change, NULL,
282 EVENTHANDLER_PRI_FIRST);
284 SYSINIT(socket, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, socket_init, NULL);
287 * Initialise maxsockets. This SYSINIT must be run after
291 init_maxsockets(void *ignored)
294 TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
295 maxsockets = imax(maxsockets, maxfiles);
297 SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);
300 * Sysctl to get and set the maximum global sockets limit. Notify protocols
301 * of the change so that they can update their dependent limits as required.
304 sysctl_maxsockets(SYSCTL_HANDLER_ARGS)
306 int error, newmaxsockets;
308 newmaxsockets = maxsockets;
309 error = sysctl_handle_int(oidp, &newmaxsockets, 0, req);
310 if (error == 0 && req->newptr) {
311 if (newmaxsockets > maxsockets &&
312 newmaxsockets <= maxfiles) {
313 maxsockets = newmaxsockets;
314 EVENTHANDLER_INVOKE(maxsockets_change);
320 SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets, CTLTYPE_INT|CTLFLAG_RW,
321 &maxsockets, 0, sysctl_maxsockets, "IU",
322 "Maximum number of sockets avaliable");
325 * Socket operation routines. These routines are called by the routines in
326 * sys_socket.c or from a system process, and implement the semantics of
327 * socket operations by switching out to the protocol specific routines.
331 * Get a socket structure from our zone, and initialize it. Note that it
332 * would probably be better to allocate socket and PCB at the same time, but
333 * I'm not convinced that all the protocols can be easily modified to do
336 * soalloc() returns a socket with a ref count of 0.
338 static struct socket *
339 soalloc(struct vnet *vnet)
343 so = uma_zalloc(socket_zone, M_NOWAIT | M_ZERO);
347 if (mac_socket_init(so, M_NOWAIT) != 0) {
348 uma_zfree(socket_zone, so);
352 SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
353 SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
354 sx_init(&so->so_snd.sb_sx, "so_snd_sx");
355 sx_init(&so->so_rcv.sb_sx, "so_rcv_sx");
356 TAILQ_INIT(&so->so_aiojobq);
357 mtx_lock(&so_global_mtx);
358 so->so_gencnt = ++so_gencnt;
361 VNET_ASSERT(vnet != NULL, ("%s:%d vnet is NULL, so=%p",
362 __func__, __LINE__, so));
363 vnet->vnet_sockcnt++;
366 mtx_unlock(&so_global_mtx);
371 * Free the storage associated with a socket at the socket layer, tear down
372 * locks, labels, etc. All protocol state is assumed already to have been
373 * torn down (and possibly never set up) by the caller.
376 sodealloc(struct socket *so)
379 KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
380 KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
382 mtx_lock(&so_global_mtx);
383 so->so_gencnt = ++so_gencnt;
384 --numopensockets; /* Could be below, but faster here. */
386 VNET_ASSERT(so->so_vnet != NULL, ("%s:%d so_vnet is NULL, so=%p",
387 __func__, __LINE__, so));
388 so->so_vnet->vnet_sockcnt--;
390 mtx_unlock(&so_global_mtx);
391 if (so->so_rcv.sb_hiwat)
392 (void)chgsbsize(so->so_cred->cr_uidinfo,
393 &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
394 if (so->so_snd.sb_hiwat)
395 (void)chgsbsize(so->so_cred->cr_uidinfo,
396 &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
398 /* remove acccept filter if one is present. */
399 if (so->so_accf != NULL)
400 do_setopt_accept_filter(so, NULL);
403 mac_socket_destroy(so);
406 sx_destroy(&so->so_snd.sb_sx);
407 sx_destroy(&so->so_rcv.sb_sx);
408 SOCKBUF_LOCK_DESTROY(&so->so_snd);
409 SOCKBUF_LOCK_DESTROY(&so->so_rcv);
410 uma_zfree(socket_zone, so);
414 * socreate returns a socket with a ref count of 1. The socket should be
415 * closed with soclose().
418 socreate(int dom, struct socket **aso, int type, int proto,
419 struct ucred *cred, struct thread *td)
426 prp = pffindproto(dom, proto, type);
428 prp = pffindtype(dom, type);
431 /* No support for domain. */
432 if (pffinddomain(dom) == NULL)
433 return (EAFNOSUPPORT);
434 /* No support for socket type. */
435 if (proto == 0 && type != 0)
437 return (EPROTONOSUPPORT);
439 if (prp->pr_usrreqs->pru_attach == NULL ||
440 prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
441 return (EPROTONOSUPPORT);
443 if (prison_check_af(cred, prp->pr_domain->dom_family) != 0)
444 return (EPROTONOSUPPORT);
446 if (prp->pr_type != type)
448 so = soalloc(CRED_TO_VNET(cred));
452 TAILQ_INIT(&so->so_incomp);
453 TAILQ_INIT(&so->so_comp);
455 so->so_cred = crhold(cred);
456 if ((prp->pr_domain->dom_family == PF_INET) ||
457 (prp->pr_domain->dom_family == PF_INET6) ||
458 (prp->pr_domain->dom_family == PF_ROUTE))
459 so->so_fibnum = td->td_proc->p_fibnum;
464 mac_socket_create(cred, so);
466 knlist_init_mtx(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
467 knlist_init_mtx(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
470 * Auto-sizing of socket buffers is managed by the protocols and
471 * the appropriate flags must be set in the pru_attach function.
473 CURVNET_SET(so->so_vnet);
474 error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
477 KASSERT(so->so_count == 1, ("socreate: so_count %d",
488 static int regression_sonewconn_earlytest = 1;
489 SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW,
490 ®ression_sonewconn_earlytest, 0, "Perform early sonewconn limit test");
494 * When an attempt at a new connection is noted on a socket which accepts
495 * connections, sonewconn is called. If the connection is possible (subject
496 * to space constraints, etc.) then we allocate a new structure, propoerly
497 * linked into the data structure of the original socket, and return this.
498 * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
500 * Note: the ref count on the socket is 0 on return.
503 sonewconn(struct socket *head, int connstatus)
509 over = (head->so_qlen > 3 * head->so_qlimit / 2);
512 if (regression_sonewconn_earlytest && over) {
516 log(LOG_DEBUG, "%s: pcb %p: Listen queue overflow: "
517 "%i already in queue awaiting acceptance\n",
518 __func__, head->so_pcb, over);
521 VNET_ASSERT(head->so_vnet != NULL, ("%s:%d so_vnet is NULL, head=%p",
522 __func__, __LINE__, head));
523 so = soalloc(head->so_vnet);
525 log(LOG_DEBUG, "%s: pcb %p: New socket allocation failure: "
526 "limit reached or out of memory\n",
527 __func__, head->so_pcb);
530 if ((head->so_options & SO_ACCEPTFILTER) != 0)
533 so->so_type = head->so_type;
534 so->so_options = head->so_options &~ SO_ACCEPTCONN;
535 so->so_linger = head->so_linger;
536 so->so_state = head->so_state | SS_NOFDREF;
537 so->so_fibnum = head->so_fibnum;
538 so->so_proto = head->so_proto;
539 so->so_cred = crhold(head->so_cred);
541 mac_socket_newconn(head, so);
543 knlist_init_mtx(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
544 knlist_init_mtx(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
545 VNET_SO_ASSERT(head);
546 if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat)) {
548 log(LOG_DEBUG, "%s: pcb %p: soreserve() failed\n",
549 __func__, head->so_pcb);
552 if ((*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
554 log(LOG_DEBUG, "%s: pcb %p: pru_attach() failed\n",
555 __func__, head->so_pcb);
558 so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
559 so->so_snd.sb_lowat = head->so_snd.sb_lowat;
560 so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
561 so->so_snd.sb_timeo = head->so_snd.sb_timeo;
562 so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
563 so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
564 so->so_state |= connstatus;
567 * The accept socket may be tearing down but we just
568 * won a race on the ACCEPT_LOCK.
569 * However, if sctp_peeloff() is called on a 1-to-many
570 * style socket, the SO_ACCEPTCONN doesn't need to be set.
572 if (!(head->so_options & SO_ACCEPTCONN) &&
573 ((head->so_proto->pr_protocol != IPPROTO_SCTP) ||
574 (head->so_type != SOCK_SEQPACKET))) {
577 sofree(so); /* NB: returns ACCEPT_UNLOCK'ed. */
581 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
582 so->so_qstate |= SQ_COMP;
586 * Keep removing sockets from the head until there's room for
587 * us to insert on the tail. In pre-locking revisions, this
588 * was a simple if(), but as we could be racing with other
589 * threads and soabort() requires dropping locks, we must
590 * loop waiting for the condition to be true.
592 while (head->so_incqlen > head->so_qlimit) {
594 sp = TAILQ_FIRST(&head->so_incomp);
595 TAILQ_REMOVE(&head->so_incomp, sp, so_list);
597 sp->so_qstate &= ~SQ_INCOMP;
603 TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
604 so->so_qstate |= SQ_INCOMP;
610 wakeup_one(&head->so_timeo);
616 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
620 CURVNET_SET(so->so_vnet);
621 error = (*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td);
627 sobindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
631 CURVNET_SET(so->so_vnet);
632 error = (*so->so_proto->pr_usrreqs->pru_bindat)(fd, so, nam, td);
638 * solisten() transitions a socket from a non-listening state to a listening
639 * state, but can also be used to update the listen queue depth on an
640 * existing listen socket. The protocol will call back into the sockets
641 * layer using solisten_proto_check() and solisten_proto() to check and set
642 * socket-layer listen state. Call backs are used so that the protocol can
643 * acquire both protocol and socket layer locks in whatever order is required
646 * Protocol implementors are advised to hold the socket lock across the
647 * socket-layer test and set to avoid races at the socket layer.
650 solisten(struct socket *so, int backlog, struct thread *td)
654 CURVNET_SET(so->so_vnet);
655 error = (*so->so_proto->pr_usrreqs->pru_listen)(so, backlog, td);
661 solisten_proto_check(struct socket *so)
664 SOCK_LOCK_ASSERT(so);
666 if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
673 solisten_proto(struct socket *so, int backlog)
676 SOCK_LOCK_ASSERT(so);
678 if (backlog < 0 || backlog > somaxconn)
680 so->so_qlimit = backlog;
681 so->so_options |= SO_ACCEPTCONN;
685 * Evaluate the reference count and named references on a socket; if no
686 * references remain, free it. This should be called whenever a reference is
687 * released, such as in sorele(), but also when named reference flags are
688 * cleared in socket or protocol code.
690 * sofree() will free the socket if:
692 * - There are no outstanding file descriptor references or related consumers
695 * - The socket has been closed by user space, if ever open (SS_NOFDREF).
697 * - The protocol does not have an outstanding strong reference on the socket
700 * - The socket is not in a completed connection queue, so a process has been
701 * notified that it is present. If it is removed, the user process may
702 * block in accept() despite select() saying the socket was ready.
705 sofree(struct socket *so)
707 struct protosw *pr = so->so_proto;
710 ACCEPT_LOCK_ASSERT();
711 SOCK_LOCK_ASSERT(so);
713 if ((so->so_state & SS_NOFDREF) == 0 || so->so_count != 0 ||
714 (so->so_state & SS_PROTOREF) || (so->so_qstate & SQ_COMP)) {
722 KASSERT((so->so_qstate & SQ_COMP) != 0 ||
723 (so->so_qstate & SQ_INCOMP) != 0,
724 ("sofree: so_head != NULL, but neither SQ_COMP nor "
726 KASSERT((so->so_qstate & SQ_COMP) == 0 ||
727 (so->so_qstate & SQ_INCOMP) == 0,
728 ("sofree: so->so_qstate is SQ_COMP and also SQ_INCOMP"));
729 TAILQ_REMOVE(&head->so_incomp, so, so_list);
731 so->so_qstate &= ~SQ_INCOMP;
734 KASSERT((so->so_qstate & SQ_COMP) == 0 &&
735 (so->so_qstate & SQ_INCOMP) == 0,
736 ("sofree: so_head == NULL, but still SQ_COMP(%d) or SQ_INCOMP(%d)",
737 so->so_qstate & SQ_COMP, so->so_qstate & SQ_INCOMP));
738 if (so->so_options & SO_ACCEPTCONN) {
739 KASSERT((TAILQ_EMPTY(&so->so_comp)),
740 ("sofree: so_comp populated"));
741 KASSERT((TAILQ_EMPTY(&so->so_incomp)),
742 ("sofree: so_incomp populated"));
748 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
749 (*pr->pr_domain->dom_dispose)(so->so_rcv.sb_mb);
750 if (pr->pr_usrreqs->pru_detach != NULL)
751 (*pr->pr_usrreqs->pru_detach)(so);
754 * From this point on, we assume that no other references to this
755 * socket exist anywhere else in the stack. Therefore, no locks need
756 * to be acquired or held.
758 * We used to do a lot of socket buffer and socket locking here, as
759 * well as invoke sorflush() and perform wakeups. The direct call to
760 * dom_dispose() and sbrelease_internal() are an inlining of what was
761 * necessary from sorflush().
763 * Notice that the socket buffer and kqueue state are torn down
764 * before calling pru_detach. This means that protocols shold not
765 * assume they can perform socket wakeups, etc, in their detach code.
767 sbdestroy(&so->so_snd, so);
768 sbdestroy(&so->so_rcv, so);
769 seldrain(&so->so_snd.sb_sel);
770 seldrain(&so->so_rcv.sb_sel);
771 knlist_destroy(&so->so_rcv.sb_sel.si_note);
772 knlist_destroy(&so->so_snd.sb_sel.si_note);
777 * Close a socket on last file table reference removal. Initiate disconnect
778 * if connected. Free socket when disconnect complete.
780 * This function will sorele() the socket. Note that soclose() may be called
781 * prior to the ref count reaching zero. The actual socket structure will
782 * not be freed until the ref count reaches zero.
785 soclose(struct socket *so)
789 KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
791 CURVNET_SET(so->so_vnet);
792 funsetown(&so->so_sigio);
793 if (so->so_state & SS_ISCONNECTED) {
794 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
795 error = sodisconnect(so);
797 if (error == ENOTCONN)
802 if (so->so_options & SO_LINGER) {
803 if ((so->so_state & SS_ISDISCONNECTING) &&
804 (so->so_state & SS_NBIO))
806 while (so->so_state & SS_ISCONNECTED) {
807 error = tsleep(&so->so_timeo,
808 PSOCK | PCATCH, "soclos",
817 if (so->so_proto->pr_usrreqs->pru_close != NULL)
818 (*so->so_proto->pr_usrreqs->pru_close)(so);
820 if (so->so_options & SO_ACCEPTCONN) {
823 * Prevent new additions to the accept queues due
824 * to ACCEPT_LOCK races while we are draining them.
826 so->so_options &= ~SO_ACCEPTCONN;
827 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
828 TAILQ_REMOVE(&so->so_incomp, sp, so_list);
830 sp->so_qstate &= ~SQ_INCOMP;
836 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
837 TAILQ_REMOVE(&so->so_comp, sp, so_list);
839 sp->so_qstate &= ~SQ_COMP;
845 KASSERT((TAILQ_EMPTY(&so->so_comp)),
846 ("%s: so_comp populated", __func__));
847 KASSERT((TAILQ_EMPTY(&so->so_incomp)),
848 ("%s: so_incomp populated", __func__));
851 KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
852 so->so_state |= SS_NOFDREF;
853 sorele(so); /* NB: Returns with ACCEPT_UNLOCK(). */
859 * soabort() is used to abruptly tear down a connection, such as when a
860 * resource limit is reached (listen queue depth exceeded), or if a listen
861 * socket is closed while there are sockets waiting to be accepted.
863 * This interface is tricky, because it is called on an unreferenced socket,
864 * and must be called only by a thread that has actually removed the socket
865 * from the listen queue it was on, or races with other threads are risked.
867 * This interface will call into the protocol code, so must not be called
868 * with any socket locks held. Protocols do call it while holding their own
869 * recursible protocol mutexes, but this is something that should be subject
870 * to review in the future.
873 soabort(struct socket *so)
877 * In as much as is possible, assert that no references to this
878 * socket are held. This is not quite the same as asserting that the
879 * current thread is responsible for arranging for no references, but
880 * is as close as we can get for now.
882 KASSERT(so->so_count == 0, ("soabort: so_count"));
883 KASSERT((so->so_state & SS_PROTOREF) == 0, ("soabort: SS_PROTOREF"));
884 KASSERT(so->so_state & SS_NOFDREF, ("soabort: !SS_NOFDREF"));
885 KASSERT((so->so_state & SQ_COMP) == 0, ("soabort: SQ_COMP"));
886 KASSERT((so->so_state & SQ_INCOMP) == 0, ("soabort: SQ_INCOMP"));
889 if (so->so_proto->pr_usrreqs->pru_abort != NULL)
890 (*so->so_proto->pr_usrreqs->pru_abort)(so);
897 soaccept(struct socket *so, struct sockaddr **nam)
902 KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
903 so->so_state &= ~SS_NOFDREF;
906 CURVNET_SET(so->so_vnet);
907 error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
913 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
916 return (soconnectat(AT_FDCWD, so, nam, td));
920 soconnectat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
924 if (so->so_options & SO_ACCEPTCONN)
927 CURVNET_SET(so->so_vnet);
929 * If protocol is connection-based, can only connect once.
930 * Otherwise, if connected, try to disconnect first. This allows
931 * user to disconnect by connecting to, e.g., a null address.
933 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
934 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
935 (error = sodisconnect(so)))) {
939 * Prevent accumulated error from previous connection from
943 if (fd == AT_FDCWD) {
944 error = (*so->so_proto->pr_usrreqs->pru_connect)(so,
947 error = (*so->so_proto->pr_usrreqs->pru_connectat)(fd,
957 soconnect2(struct socket *so1, struct socket *so2)
961 CURVNET_SET(so1->so_vnet);
962 error = (*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2);
968 sodisconnect(struct socket *so)
972 if ((so->so_state & SS_ISCONNECTED) == 0)
974 if (so->so_state & SS_ISDISCONNECTING)
977 error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
981 #ifdef SOCKET_SEND_COW
982 struct so_zerocopy_stats{
987 struct so_zerocopy_stats so_zerocp_stats = {0,0,0};
990 * sosend_copyin() is only used if zero copy sockets are enabled. Otherwise
991 * sosend_dgram() and sosend_generic() use m_uiotombuf().
993 * sosend_copyin() accepts a uio and prepares an mbuf chain holding part or
994 * all of the data referenced by the uio. If desired, it uses zero-copy.
995 * *space will be updated to reflect data copied in.
997 * NB: If atomic I/O is requested, the caller must already have checked that
998 * space can hold resid bytes.
1000 * NB: In the event of an error, the caller may need to free the partial
1001 * chain pointed to by *mpp. The contents of both *uio and *space may be
1002 * modified even in the case of an error.
1005 sosend_copyin(struct uio *uio, struct mbuf **retmp, int atomic, long *space,
1008 struct mbuf *m, **mp, *top;
1014 *retmp = top = NULL;
1017 resid = uio->uio_resid;
1021 if (resid >= MINCLSIZE) {
1023 m = m_gethdr(M_WAITOK, MT_DATA);
1024 m->m_pkthdr.len = 0;
1025 m->m_pkthdr.rcvif = NULL;
1027 m = m_get(M_WAITOK, MT_DATA);
1028 if (so_zero_copy_send &&
1029 resid >= PAGE_SIZE &&
1030 *space >= PAGE_SIZE &&
1031 uio->uio_iov->iov_len >= PAGE_SIZE) {
1032 so_zerocp_stats.size_ok++;
1033 so_zerocp_stats.align_ok++;
1034 cow_send = socow_setup(m, uio);
1038 m_clget(m, M_WAITOK);
1039 len = min(min(MCLBYTES, resid), *space);
1043 m = m_gethdr(M_WAITOK, MT_DATA);
1044 m->m_pkthdr.len = 0;
1045 m->m_pkthdr.rcvif = NULL;
1047 len = min(min(MHLEN, resid), *space);
1049 * For datagram protocols, leave room
1050 * for protocol headers in first mbuf.
1052 if (atomic && m && len < MHLEN)
1055 m = m_get(M_WAITOK, MT_DATA);
1056 len = min(min(MLEN, resid), *space);
1068 error = uiomove(mtod(m, void *), (int)len, uio);
1069 resid = uio->uio_resid;
1072 top->m_pkthdr.len += len;
1077 if (flags & MSG_EOR)
1078 top->m_flags |= M_EOR;
1081 } while (*space > 0 && atomic);
1086 #endif /* SOCKET_SEND_COW */
1088 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? 0 : SBL_WAIT)
1091 sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1092 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1096 int clen = 0, error, dontroute;
1097 #ifdef SOCKET_SEND_COW
1098 int atomic = sosendallatonce(so) || top;
1101 KASSERT(so->so_type == SOCK_DGRAM, ("sosend_dgram: !SOCK_DGRAM"));
1102 KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
1103 ("sosend_dgram: !PR_ATOMIC"));
1106 resid = uio->uio_resid;
1108 resid = top->m_pkthdr.len;
1110 * In theory resid should be unsigned. However, space must be
1111 * signed, as it might be less than 0 if we over-committed, and we
1112 * must use a signed comparison of space and resid. On the other
1113 * hand, a negative resid causes us to loop sending 0-length
1114 * segments to the protocol.
1122 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
1124 td->td_ru.ru_msgsnd++;
1125 if (control != NULL)
1126 clen = control->m_len;
1128 SOCKBUF_LOCK(&so->so_snd);
1129 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1130 SOCKBUF_UNLOCK(&so->so_snd);
1135 error = so->so_error;
1137 SOCKBUF_UNLOCK(&so->so_snd);
1140 if ((so->so_state & SS_ISCONNECTED) == 0) {
1142 * `sendto' and `sendmsg' is allowed on a connection-based
1143 * socket if it supports implied connect. Return ENOTCONN if
1144 * not connected and no address is supplied.
1146 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1147 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1148 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1149 !(resid == 0 && clen != 0)) {
1150 SOCKBUF_UNLOCK(&so->so_snd);
1154 } else if (addr == NULL) {
1155 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1158 error = EDESTADDRREQ;
1159 SOCKBUF_UNLOCK(&so->so_snd);
1165 * Do we need MSG_OOB support in SOCK_DGRAM? Signs here may be a
1166 * problem and need fixing.
1168 space = sbspace(&so->so_snd);
1169 if (flags & MSG_OOB)
1172 SOCKBUF_UNLOCK(&so->so_snd);
1173 if (resid > space) {
1179 if (flags & MSG_EOR)
1180 top->m_flags |= M_EOR;
1182 #ifdef SOCKET_SEND_COW
1183 error = sosend_copyin(uio, &top, atomic, &space, flags);
1188 * Copy the data from userland into a mbuf chain.
1189 * If no data is to be copied in, a single empty mbuf
1192 top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
1193 (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
1195 error = EFAULT; /* only possible error */
1198 space -= resid - uio->uio_resid;
1199 #endif /* SOCKET_SEND_COW */
1200 resid = uio->uio_resid;
1202 KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
1204 * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
1209 so->so_options |= SO_DONTROUTE;
1213 * XXX all the SBS_CANTSENDMORE checks previously done could be out
1214 * of date. We could have recieved a reset packet in an interrupt or
1215 * maybe we slept while doing page faults in uiomove() etc. We could
1216 * probably recheck again inside the locking protection here, but
1217 * there are probably other places that this also happens. We must
1221 error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1222 (flags & MSG_OOB) ? PRUS_OOB :
1224 * If the user set MSG_EOF, the protocol understands this flag and
1225 * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
1227 ((flags & MSG_EOF) &&
1228 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1231 /* If there is more to send set PRUS_MORETOCOME */
1232 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1233 top, addr, control, td);
1236 so->so_options &= ~SO_DONTROUTE;
1245 if (control != NULL)
1251 * Send on a socket. If send must go all at once and message is larger than
1252 * send buffering, then hard error. Lock against other senders. If must go
1253 * all at once and not enough room now, then inform user that this would
1254 * block and do nothing. Otherwise, if nonblocking, send as much as
1255 * possible. The data to be sent is described by "uio" if nonzero, otherwise
1256 * by the mbuf chain "top" (which must be null if uio is not). Data provided
1257 * in mbuf chain must be small enough to send all at once.
1259 * Returns nonzero on error, timeout or signal; callers must check for short
1260 * counts if EINTR/ERESTART are returned. Data and control buffers are freed
1264 sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
1265 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1269 int clen = 0, error, dontroute;
1270 int atomic = sosendallatonce(so) || top;
1273 resid = uio->uio_resid;
1275 resid = top->m_pkthdr.len;
1277 * In theory resid should be unsigned. However, space must be
1278 * signed, as it might be less than 0 if we over-committed, and we
1279 * must use a signed comparison of space and resid. On the other
1280 * hand, a negative resid causes us to loop sending 0-length
1281 * segments to the protocol.
1283 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
1284 * type sockets since that's an error.
1286 if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
1292 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
1293 (so->so_proto->pr_flags & PR_ATOMIC);
1295 td->td_ru.ru_msgsnd++;
1296 if (control != NULL)
1297 clen = control->m_len;
1299 error = sblock(&so->so_snd, SBLOCKWAIT(flags));
1305 SOCKBUF_LOCK(&so->so_snd);
1306 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1307 SOCKBUF_UNLOCK(&so->so_snd);
1312 error = so->so_error;
1314 SOCKBUF_UNLOCK(&so->so_snd);
1317 if ((so->so_state & SS_ISCONNECTED) == 0) {
1319 * `sendto' and `sendmsg' is allowed on a connection-
1320 * based socket if it supports implied connect.
1321 * Return ENOTCONN if not connected and no address is
1324 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1325 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1326 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1327 !(resid == 0 && clen != 0)) {
1328 SOCKBUF_UNLOCK(&so->so_snd);
1332 } else if (addr == NULL) {
1333 SOCKBUF_UNLOCK(&so->so_snd);
1334 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1337 error = EDESTADDRREQ;
1341 space = sbspace(&so->so_snd);
1342 if (flags & MSG_OOB)
1344 if ((atomic && resid > so->so_snd.sb_hiwat) ||
1345 clen > so->so_snd.sb_hiwat) {
1346 SOCKBUF_UNLOCK(&so->so_snd);
1350 if (space < resid + clen &&
1351 (atomic || space < so->so_snd.sb_lowat || space < clen)) {
1352 if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO)) {
1353 SOCKBUF_UNLOCK(&so->so_snd);
1354 error = EWOULDBLOCK;
1357 error = sbwait(&so->so_snd);
1358 SOCKBUF_UNLOCK(&so->so_snd);
1363 SOCKBUF_UNLOCK(&so->so_snd);
1368 if (flags & MSG_EOR)
1369 top->m_flags |= M_EOR;
1371 #ifdef SOCKET_SEND_COW
1372 error = sosend_copyin(uio, &top, atomic,
1378 * Copy the data from userland into a mbuf
1379 * chain. If no data is to be copied in,
1380 * a single empty mbuf is returned.
1382 top = m_uiotombuf(uio, M_WAITOK, space,
1383 (atomic ? max_hdr : 0),
1384 (atomic ? M_PKTHDR : 0) |
1385 ((flags & MSG_EOR) ? M_EOR : 0));
1387 error = EFAULT; /* only possible error */
1390 space -= resid - uio->uio_resid;
1391 #endif /* SOCKET_SEND_COW */
1392 resid = uio->uio_resid;
1396 so->so_options |= SO_DONTROUTE;
1400 * XXX all the SBS_CANTSENDMORE checks previously
1401 * done could be out of date. We could have recieved
1402 * a reset packet in an interrupt or maybe we slept
1403 * while doing page faults in uiomove() etc. We
1404 * could probably recheck again inside the locking
1405 * protection here, but there are probably other
1406 * places that this also happens. We must rethink
1410 error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1411 (flags & MSG_OOB) ? PRUS_OOB :
1413 * If the user set MSG_EOF, the protocol understands
1414 * this flag and nothing left to send then use
1415 * PRU_SEND_EOF instead of PRU_SEND.
1417 ((flags & MSG_EOF) &&
1418 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1421 /* If there is more to send set PRUS_MORETOCOME. */
1422 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1423 top, addr, control, td);
1426 so->so_options &= ~SO_DONTROUTE;
1434 } while (resid && space > 0);
1438 sbunlock(&so->so_snd);
1442 if (control != NULL)
1448 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
1449 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1453 CURVNET_SET(so->so_vnet);
1454 error = so->so_proto->pr_usrreqs->pru_sosend(so, addr, uio, top,
1455 control, flags, td);
1461 * The part of soreceive() that implements reading non-inline out-of-band
1462 * data from a socket. For more complete comments, see soreceive(), from
1463 * which this code originated.
1465 * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
1466 * unable to return an mbuf chain to the caller.
1469 soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
1471 struct protosw *pr = so->so_proto;
1475 KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
1478 m = m_get(M_WAITOK, MT_DATA);
1479 error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
1483 #ifdef SOCKET_RECV_PFLIP
1484 if (so_zero_copy_receive) {
1487 if ((m->m_flags & M_EXT)
1488 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1493 error = uiomoveco(mtod(m, void *),
1494 min(uio->uio_resid, m->m_len), uio, disposable);
1496 #endif /* SOCKET_RECV_PFLIP */
1497 error = uiomove(mtod(m, void *),
1498 (int) min(uio->uio_resid, m->m_len), uio);
1500 } while (uio->uio_resid && error == 0 && m);
1508 * Following replacement or removal of the first mbuf on the first mbuf chain
1509 * of a socket buffer, push necessary state changes back into the socket
1510 * buffer so that other consumers see the values consistently. 'nextrecord'
1511 * is the callers locally stored value of the original value of
1512 * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
1513 * NOTE: 'nextrecord' may be NULL.
1515 static __inline void
1516 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
1519 SOCKBUF_LOCK_ASSERT(sb);
1521 * First, update for the new value of nextrecord. If necessary, make
1522 * it the first record.
1524 if (sb->sb_mb != NULL)
1525 sb->sb_mb->m_nextpkt = nextrecord;
1527 sb->sb_mb = nextrecord;
1530 * Now update any dependent socket buffer fields to reflect the new
1531 * state. This is an expanded inline of SB_EMPTY_FIXUP(), with the
1532 * addition of a second clause that takes care of the case where
1533 * sb_mb has been updated, but remains the last record.
1535 if (sb->sb_mb == NULL) {
1536 sb->sb_mbtail = NULL;
1537 sb->sb_lastrecord = NULL;
1538 } else if (sb->sb_mb->m_nextpkt == NULL)
1539 sb->sb_lastrecord = sb->sb_mb;
1543 * Implement receive operations on a socket. We depend on the way that
1544 * records are added to the sockbuf by sbappend. In particular, each record
1545 * (mbufs linked through m_next) must begin with an address if the protocol
1546 * so specifies, followed by an optional mbuf or mbufs containing ancillary
1547 * data, and then zero or more mbufs of data. In order to allow parallelism
1548 * between network receive and copying to user space, as well as avoid
1549 * sleeping with a mutex held, we release the socket buffer mutex during the
1550 * user space copy. Although the sockbuf is locked, new data may still be
1551 * appended, and thus we must maintain consistency of the sockbuf during that
1554 * The caller may receive the data as a single mbuf chain by supplying an
1555 * mbuf **mp0 for use in returning the chain. The uio is then used only for
1556 * the count in uio_resid.
1559 soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
1560 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1562 struct mbuf *m, **mp;
1563 int flags, error, offset;
1565 struct protosw *pr = so->so_proto;
1566 struct mbuf *nextrecord;
1568 ssize_t orig_resid = uio->uio_resid;
1573 if (controlp != NULL)
1576 flags = *flagsp &~ MSG_EOR;
1579 if (flags & MSG_OOB)
1580 return (soreceive_rcvoob(so, uio, flags));
1583 if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
1584 && uio->uio_resid) {
1586 (*pr->pr_usrreqs->pru_rcvd)(so, 0);
1589 error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
1594 SOCKBUF_LOCK(&so->so_rcv);
1595 m = so->so_rcv.sb_mb;
1597 * If we have less data than requested, block awaiting more (subject
1598 * to any timeout) if:
1599 * 1. the current count is less than the low water mark, or
1600 * 2. MSG_DONTWAIT is not set
1602 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1603 so->so_rcv.sb_cc < uio->uio_resid) &&
1604 so->so_rcv.sb_cc < so->so_rcv.sb_lowat &&
1605 m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
1606 KASSERT(m != NULL || !so->so_rcv.sb_cc,
1607 ("receive: m == %p so->so_rcv.sb_cc == %u",
1608 m, so->so_rcv.sb_cc));
1612 error = so->so_error;
1613 if ((flags & MSG_PEEK) == 0)
1615 SOCKBUF_UNLOCK(&so->so_rcv);
1618 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1619 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1621 SOCKBUF_UNLOCK(&so->so_rcv);
1626 for (; m != NULL; m = m->m_next)
1627 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
1628 m = so->so_rcv.sb_mb;
1631 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1632 (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1633 SOCKBUF_UNLOCK(&so->so_rcv);
1637 if (uio->uio_resid == 0) {
1638 SOCKBUF_UNLOCK(&so->so_rcv);
1641 if ((so->so_state & SS_NBIO) ||
1642 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1643 SOCKBUF_UNLOCK(&so->so_rcv);
1644 error = EWOULDBLOCK;
1647 SBLASTRECORDCHK(&so->so_rcv);
1648 SBLASTMBUFCHK(&so->so_rcv);
1649 error = sbwait(&so->so_rcv);
1650 SOCKBUF_UNLOCK(&so->so_rcv);
1657 * From this point onward, we maintain 'nextrecord' as a cache of the
1658 * pointer to the next record in the socket buffer. We must keep the
1659 * various socket buffer pointers and local stack versions of the
1660 * pointers in sync, pushing out modifications before dropping the
1661 * socket buffer mutex, and re-reading them when picking it up.
1663 * Otherwise, we will race with the network stack appending new data
1664 * or records onto the socket buffer by using inconsistent/stale
1665 * versions of the field, possibly resulting in socket buffer
1668 * By holding the high-level sblock(), we prevent simultaneous
1669 * readers from pulling off the front of the socket buffer.
1671 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1673 uio->uio_td->td_ru.ru_msgrcv++;
1674 KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
1675 SBLASTRECORDCHK(&so->so_rcv);
1676 SBLASTMBUFCHK(&so->so_rcv);
1677 nextrecord = m->m_nextpkt;
1678 if (pr->pr_flags & PR_ADDR) {
1679 KASSERT(m->m_type == MT_SONAME,
1680 ("m->m_type == %d", m->m_type));
1683 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
1685 if (flags & MSG_PEEK) {
1688 sbfree(&so->so_rcv, m);
1689 so->so_rcv.sb_mb = m_free(m);
1690 m = so->so_rcv.sb_mb;
1691 sockbuf_pushsync(&so->so_rcv, nextrecord);
1696 * Process one or more MT_CONTROL mbufs present before any data mbufs
1697 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
1698 * just copy the data; if !MSG_PEEK, we call into the protocol to
1699 * perform externalization (or freeing if controlp == NULL).
1701 if (m != NULL && m->m_type == MT_CONTROL) {
1702 struct mbuf *cm = NULL, *cmn;
1703 struct mbuf **cme = &cm;
1706 if (flags & MSG_PEEK) {
1707 if (controlp != NULL) {
1708 *controlp = m_copy(m, 0, m->m_len);
1709 controlp = &(*controlp)->m_next;
1713 sbfree(&so->so_rcv, m);
1714 so->so_rcv.sb_mb = m->m_next;
1717 cme = &(*cme)->m_next;
1718 m = so->so_rcv.sb_mb;
1720 } while (m != NULL && m->m_type == MT_CONTROL);
1721 if ((flags & MSG_PEEK) == 0)
1722 sockbuf_pushsync(&so->so_rcv, nextrecord);
1723 while (cm != NULL) {
1726 if (pr->pr_domain->dom_externalize != NULL) {
1727 SOCKBUF_UNLOCK(&so->so_rcv);
1729 error = (*pr->pr_domain->dom_externalize)
1730 (cm, controlp, flags);
1731 SOCKBUF_LOCK(&so->so_rcv);
1732 } else if (controlp != NULL)
1736 if (controlp != NULL) {
1738 while (*controlp != NULL)
1739 controlp = &(*controlp)->m_next;
1744 nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1746 nextrecord = so->so_rcv.sb_mb;
1750 if ((flags & MSG_PEEK) == 0) {
1751 KASSERT(m->m_nextpkt == nextrecord,
1752 ("soreceive: post-control, nextrecord !sync"));
1753 if (nextrecord == NULL) {
1754 KASSERT(so->so_rcv.sb_mb == m,
1755 ("soreceive: post-control, sb_mb!=m"));
1756 KASSERT(so->so_rcv.sb_lastrecord == m,
1757 ("soreceive: post-control, lastrecord!=m"));
1761 if (type == MT_OOBDATA)
1764 if ((flags & MSG_PEEK) == 0) {
1765 KASSERT(so->so_rcv.sb_mb == nextrecord,
1766 ("soreceive: sb_mb != nextrecord"));
1767 if (so->so_rcv.sb_mb == NULL) {
1768 KASSERT(so->so_rcv.sb_lastrecord == NULL,
1769 ("soreceive: sb_lastercord != NULL"));
1773 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1774 SBLASTRECORDCHK(&so->so_rcv);
1775 SBLASTMBUFCHK(&so->so_rcv);
1778 * Now continue to read any data mbufs off of the head of the socket
1779 * buffer until the read request is satisfied. Note that 'type' is
1780 * used to store the type of any mbuf reads that have happened so far
1781 * such that soreceive() can stop reading if the type changes, which
1782 * causes soreceive() to return only one of regular data and inline
1783 * out-of-band data in a single socket receive operation.
1787 while (m != NULL && uio->uio_resid > 0 && error == 0) {
1789 * If the type of mbuf has changed since the last mbuf
1790 * examined ('type'), end the receive operation.
1792 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1793 if (m->m_type == MT_OOBDATA || m->m_type == MT_CONTROL) {
1794 if (type != m->m_type)
1796 } else if (type == MT_OOBDATA)
1799 KASSERT(m->m_type == MT_DATA,
1800 ("m->m_type == %d", m->m_type));
1801 so->so_rcv.sb_state &= ~SBS_RCVATMARK;
1802 len = uio->uio_resid;
1803 if (so->so_oobmark && len > so->so_oobmark - offset)
1804 len = so->so_oobmark - offset;
1805 if (len > m->m_len - moff)
1806 len = m->m_len - moff;
1808 * If mp is set, just pass back the mbufs. Otherwise copy
1809 * them out via the uio, then free. Sockbuf must be
1810 * consistent here (points to current mbuf, it points to next
1811 * record) when we drop priority; we must note any additions
1812 * to the sockbuf when we block interrupts again.
1815 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1816 SBLASTRECORDCHK(&so->so_rcv);
1817 SBLASTMBUFCHK(&so->so_rcv);
1818 SOCKBUF_UNLOCK(&so->so_rcv);
1819 #ifdef SOCKET_RECV_PFLIP
1820 if (so_zero_copy_receive) {
1823 if ((m->m_flags & M_EXT)
1824 && (m->m_ext.ext_type == EXT_DISPOSABLE))
1829 error = uiomoveco(mtod(m, char *) + moff,
1830 (int)len, uio, disposable);
1832 #endif /* SOCKET_RECV_PFLIP */
1833 error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1834 SOCKBUF_LOCK(&so->so_rcv);
1837 * The MT_SONAME mbuf has already been removed
1838 * from the record, so it is necessary to
1839 * remove the data mbufs, if any, to preserve
1840 * the invariant in the case of PR_ADDR that
1841 * requires MT_SONAME mbufs at the head of
1844 if (m && pr->pr_flags & PR_ATOMIC &&
1845 ((flags & MSG_PEEK) == 0))
1846 (void)sbdroprecord_locked(&so->so_rcv);
1847 SOCKBUF_UNLOCK(&so->so_rcv);
1851 uio->uio_resid -= len;
1852 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1853 if (len == m->m_len - moff) {
1854 if (m->m_flags & M_EOR)
1856 if (flags & MSG_PEEK) {
1860 nextrecord = m->m_nextpkt;
1861 sbfree(&so->so_rcv, m);
1863 m->m_nextpkt = NULL;
1866 so->so_rcv.sb_mb = m = m->m_next;
1869 so->so_rcv.sb_mb = m_free(m);
1870 m = so->so_rcv.sb_mb;
1872 sockbuf_pushsync(&so->so_rcv, nextrecord);
1873 SBLASTRECORDCHK(&so->so_rcv);
1874 SBLASTMBUFCHK(&so->so_rcv);
1877 if (flags & MSG_PEEK)
1883 if (flags & MSG_DONTWAIT)
1884 copy_flag = M_NOWAIT;
1887 if (copy_flag == M_WAITOK)
1888 SOCKBUF_UNLOCK(&so->so_rcv);
1889 *mp = m_copym(m, 0, len, copy_flag);
1890 if (copy_flag == M_WAITOK)
1891 SOCKBUF_LOCK(&so->so_rcv);
1894 * m_copym() couldn't
1895 * allocate an mbuf. Adjust
1896 * uio_resid back (it was
1897 * adjusted down by len
1898 * bytes, which we didn't end
1899 * up "copying" over).
1901 uio->uio_resid += len;
1907 so->so_rcv.sb_cc -= len;
1910 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1911 if (so->so_oobmark) {
1912 if ((flags & MSG_PEEK) == 0) {
1913 so->so_oobmark -= len;
1914 if (so->so_oobmark == 0) {
1915 so->so_rcv.sb_state |= SBS_RCVATMARK;
1920 if (offset == so->so_oobmark)
1924 if (flags & MSG_EOR)
1927 * If the MSG_WAITALL flag is set (for non-atomic socket), we
1928 * must not quit until "uio->uio_resid == 0" or an error
1929 * termination. If a signal/timeout occurs, return with a
1930 * short count but without error. Keep sockbuf locked
1931 * against other readers.
1933 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1934 !sosendallatonce(so) && nextrecord == NULL) {
1935 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1937 so->so_rcv.sb_state & SBS_CANTRCVMORE)
1940 * Notify the protocol that some data has been
1941 * drained before blocking.
1943 if (pr->pr_flags & PR_WANTRCVD) {
1944 SOCKBUF_UNLOCK(&so->so_rcv);
1946 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1947 SOCKBUF_LOCK(&so->so_rcv);
1949 SBLASTRECORDCHK(&so->so_rcv);
1950 SBLASTMBUFCHK(&so->so_rcv);
1952 * We could receive some data while was notifying
1953 * the protocol. Skip blocking in this case.
1955 if (so->so_rcv.sb_mb == NULL) {
1956 error = sbwait(&so->so_rcv);
1958 SOCKBUF_UNLOCK(&so->so_rcv);
1962 m = so->so_rcv.sb_mb;
1964 nextrecord = m->m_nextpkt;
1968 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1969 if (m != NULL && pr->pr_flags & PR_ATOMIC) {
1971 if ((flags & MSG_PEEK) == 0)
1972 (void) sbdroprecord_locked(&so->so_rcv);
1974 if ((flags & MSG_PEEK) == 0) {
1977 * First part is an inline SB_EMPTY_FIXUP(). Second
1978 * part makes sure sb_lastrecord is up-to-date if
1979 * there is still data in the socket buffer.
1981 so->so_rcv.sb_mb = nextrecord;
1982 if (so->so_rcv.sb_mb == NULL) {
1983 so->so_rcv.sb_mbtail = NULL;
1984 so->so_rcv.sb_lastrecord = NULL;
1985 } else if (nextrecord->m_nextpkt == NULL)
1986 so->so_rcv.sb_lastrecord = nextrecord;
1988 SBLASTRECORDCHK(&so->so_rcv);
1989 SBLASTMBUFCHK(&so->so_rcv);
1991 * If soreceive() is being done from the socket callback,
1992 * then don't need to generate ACK to peer to update window,
1993 * since ACK will be generated on return to TCP.
1995 if (!(flags & MSG_SOCALLBCK) &&
1996 (pr->pr_flags & PR_WANTRCVD)) {
1997 SOCKBUF_UNLOCK(&so->so_rcv);
1999 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
2000 SOCKBUF_LOCK(&so->so_rcv);
2003 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2004 if (orig_resid == uio->uio_resid && orig_resid &&
2005 (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
2006 SOCKBUF_UNLOCK(&so->so_rcv);
2009 SOCKBUF_UNLOCK(&so->so_rcv);
2014 sbunlock(&so->so_rcv);
2019 * Optimized version of soreceive() for stream (TCP) sockets.
2020 * XXXAO: (MSG_WAITALL | MSG_PEEK) isn't properly handled.
2023 soreceive_stream(struct socket *so, struct sockaddr **psa, struct uio *uio,
2024 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2026 int len = 0, error = 0, flags, oresid;
2028 struct mbuf *m, *n = NULL;
2030 /* We only do stream sockets. */
2031 if (so->so_type != SOCK_STREAM)
2035 if (controlp != NULL)
2038 flags = *flagsp &~ MSG_EOR;
2041 if (flags & MSG_OOB)
2042 return (soreceive_rcvoob(so, uio, flags));
2048 /* Prevent other readers from entering the socket. */
2049 error = sblock(sb, SBLOCKWAIT(flags));
2054 /* Easy one, no space to copyout anything. */
2055 if (uio->uio_resid == 0) {
2059 oresid = uio->uio_resid;
2061 /* We will never ever get anything unless we are or were connected. */
2062 if (!(so->so_state & (SS_ISCONNECTED|SS_ISDISCONNECTED))) {
2068 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2070 /* Abort if socket has reported problems. */
2074 if (oresid > uio->uio_resid)
2076 error = so->so_error;
2077 if (!(flags & MSG_PEEK))
2082 /* Door is closed. Deliver what is left, if any. */
2083 if (sb->sb_state & SBS_CANTRCVMORE) {
2090 /* Socket buffer is empty and we shall not block. */
2091 if (sb->sb_cc == 0 &&
2092 ((so->so_state & SS_NBIO) || (flags & (MSG_DONTWAIT|MSG_NBIO)))) {
2097 /* Socket buffer got some data that we shall deliver now. */
2098 if (sb->sb_cc > 0 && !(flags & MSG_WAITALL) &&
2099 ((sb->sb_flags & SS_NBIO) ||
2100 (flags & (MSG_DONTWAIT|MSG_NBIO)) ||
2101 sb->sb_cc >= sb->sb_lowat ||
2102 sb->sb_cc >= uio->uio_resid ||
2103 sb->sb_cc >= sb->sb_hiwat) ) {
2107 /* On MSG_WAITALL we must wait until all data or error arrives. */
2108 if ((flags & MSG_WAITALL) &&
2109 (sb->sb_cc >= uio->uio_resid || sb->sb_cc >= sb->sb_hiwat))
2113 * Wait and block until (more) data comes in.
2114 * NB: Drops the sockbuf lock during wait.
2122 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2123 KASSERT(sb->sb_cc > 0, ("%s: sockbuf empty", __func__));
2124 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb == NULL", __func__));
2128 uio->uio_td->td_ru.ru_msgrcv++;
2130 /* Fill uio until full or current end of socket buffer is reached. */
2131 len = min(uio->uio_resid, sb->sb_cc);
2133 /* Dequeue as many mbufs as possible. */
2134 if (!(flags & MSG_PEEK) && len >= sb->sb_mb->m_len) {
2138 m_cat(*mp0, sb->sb_mb);
2140 m != NULL && m->m_len <= len;
2143 uio->uio_resid -= m->m_len;
2149 sb->sb_lastrecord = sb->sb_mb;
2150 if (sb->sb_mb == NULL)
2153 /* Copy the remainder. */
2155 KASSERT(sb->sb_mb != NULL,
2156 ("%s: len > 0 && sb->sb_mb empty", __func__));
2158 m = m_copym(sb->sb_mb, 0, len, M_NOWAIT);
2160 len = 0; /* Don't flush data from sockbuf. */
2162 uio->uio_resid -= len;
2173 /* NB: Must unlock socket buffer as uiomove may sleep. */
2175 error = m_mbuftouio(uio, sb->sb_mb, len);
2180 SBLASTRECORDCHK(sb);
2184 * Remove the delivered data from the socket buffer unless we
2185 * were only peeking.
2187 if (!(flags & MSG_PEEK)) {
2189 sbdrop_locked(sb, len);
2191 /* Notify protocol that we drained some data. */
2192 if ((so->so_proto->pr_flags & PR_WANTRCVD) &&
2193 (((flags & MSG_WAITALL) && uio->uio_resid > 0) ||
2194 !(flags & MSG_SOCALLBCK))) {
2197 (*so->so_proto->pr_usrreqs->pru_rcvd)(so, flags);
2203 * For MSG_WAITALL we may have to loop again and wait for
2204 * more data to come in.
2206 if ((flags & MSG_WAITALL) && uio->uio_resid > 0)
2209 SOCKBUF_LOCK_ASSERT(sb);
2210 SBLASTRECORDCHK(sb);
2218 * Optimized version of soreceive() for simple datagram cases from userspace.
2219 * Unlike in the stream case, we're able to drop a datagram if copyout()
2220 * fails, and because we handle datagrams atomically, we don't need to use a
2221 * sleep lock to prevent I/O interlacing.
2224 soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
2225 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2227 struct mbuf *m, *m2;
2230 struct protosw *pr = so->so_proto;
2231 struct mbuf *nextrecord;
2235 if (controlp != NULL)
2238 flags = *flagsp &~ MSG_EOR;
2243 * For any complicated cases, fall back to the full
2244 * soreceive_generic().
2246 if (mp0 != NULL || (flags & MSG_PEEK) || (flags & MSG_OOB))
2247 return (soreceive_generic(so, psa, uio, mp0, controlp,
2251 * Enforce restrictions on use.
2253 KASSERT((pr->pr_flags & PR_WANTRCVD) == 0,
2254 ("soreceive_dgram: wantrcvd"));
2255 KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic"));
2256 KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0,
2257 ("soreceive_dgram: SBS_RCVATMARK"));
2258 KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0,
2259 ("soreceive_dgram: P_CONNREQUIRED"));
2262 * Loop blocking while waiting for a datagram.
2264 SOCKBUF_LOCK(&so->so_rcv);
2265 while ((m = so->so_rcv.sb_mb) == NULL) {
2266 KASSERT(so->so_rcv.sb_cc == 0,
2267 ("soreceive_dgram: sb_mb NULL but sb_cc %u",
2270 error = so->so_error;
2272 SOCKBUF_UNLOCK(&so->so_rcv);
2275 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
2276 uio->uio_resid == 0) {
2277 SOCKBUF_UNLOCK(&so->so_rcv);
2280 if ((so->so_state & SS_NBIO) ||
2281 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
2282 SOCKBUF_UNLOCK(&so->so_rcv);
2283 return (EWOULDBLOCK);
2285 SBLASTRECORDCHK(&so->so_rcv);
2286 SBLASTMBUFCHK(&so->so_rcv);
2287 error = sbwait(&so->so_rcv);
2289 SOCKBUF_UNLOCK(&so->so_rcv);
2293 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2296 uio->uio_td->td_ru.ru_msgrcv++;
2297 SBLASTRECORDCHK(&so->so_rcv);
2298 SBLASTMBUFCHK(&so->so_rcv);
2299 nextrecord = m->m_nextpkt;
2300 if (nextrecord == NULL) {
2301 KASSERT(so->so_rcv.sb_lastrecord == m,
2302 ("soreceive_dgram: lastrecord != m"));
2305 KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord,
2306 ("soreceive_dgram: m_nextpkt != nextrecord"));
2309 * Pull 'm' and its chain off the front of the packet queue.
2311 so->so_rcv.sb_mb = NULL;
2312 sockbuf_pushsync(&so->so_rcv, nextrecord);
2315 * Walk 'm's chain and free that many bytes from the socket buffer.
2317 for (m2 = m; m2 != NULL; m2 = m2->m_next)
2318 sbfree(&so->so_rcv, m2);
2321 * Do a few last checks before we let go of the lock.
2323 SBLASTRECORDCHK(&so->so_rcv);
2324 SBLASTMBUFCHK(&so->so_rcv);
2325 SOCKBUF_UNLOCK(&so->so_rcv);
2327 if (pr->pr_flags & PR_ADDR) {
2328 KASSERT(m->m_type == MT_SONAME,
2329 ("m->m_type == %d", m->m_type));
2331 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
2336 /* XXXRW: Can this happen? */
2341 * Packet to copyout() is now in 'm' and it is disconnected from the
2344 * Process one or more MT_CONTROL mbufs present before any data mbufs
2345 * in the first mbuf chain on the socket buffer. We call into the
2346 * protocol to perform externalization (or freeing if controlp ==
2349 if (m->m_type == MT_CONTROL) {
2350 struct mbuf *cm = NULL, *cmn;
2351 struct mbuf **cme = &cm;
2357 cme = &(*cme)->m_next;
2359 } while (m != NULL && m->m_type == MT_CONTROL);
2360 while (cm != NULL) {
2363 if (pr->pr_domain->dom_externalize != NULL) {
2364 error = (*pr->pr_domain->dom_externalize)
2365 (cm, controlp, flags);
2366 } else if (controlp != NULL)
2370 if (controlp != NULL) {
2371 while (*controlp != NULL)
2372 controlp = &(*controlp)->m_next;
2377 KASSERT(m->m_type == MT_DATA, ("soreceive_dgram: !data"));
2379 while (m != NULL && uio->uio_resid > 0) {
2380 len = uio->uio_resid;
2383 error = uiomove(mtod(m, char *), (int)len, uio);
2388 if (len == m->m_len)
2404 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
2405 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2409 CURVNET_SET(so->so_vnet);
2410 error = (so->so_proto->pr_usrreqs->pru_soreceive(so, psa, uio, mp0,
2417 soshutdown(struct socket *so, int how)
2419 struct protosw *pr = so->so_proto;
2422 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
2425 CURVNET_SET(so->so_vnet);
2426 if (pr->pr_usrreqs->pru_flush != NULL)
2427 (*pr->pr_usrreqs->pru_flush)(so, how);
2430 if (how != SHUT_RD) {
2431 error = (*pr->pr_usrreqs->pru_shutdown)(so);
2440 sorflush(struct socket *so)
2442 struct sockbuf *sb = &so->so_rcv;
2443 struct protosw *pr = so->so_proto;
2449 * In order to avoid calling dom_dispose with the socket buffer mutex
2450 * held, and in order to generally avoid holding the lock for a long
2451 * time, we make a copy of the socket buffer and clear the original
2452 * (except locks, state). The new socket buffer copy won't have
2453 * initialized locks so we can only call routines that won't use or
2454 * assert those locks.
2456 * Dislodge threads currently blocked in receive and wait to acquire
2457 * a lock against other simultaneous readers before clearing the
2458 * socket buffer. Don't let our acquire be interrupted by a signal
2459 * despite any existing socket disposition on interruptable waiting.
2462 (void) sblock(sb, SBL_WAIT | SBL_NOINTR);
2465 * Invalidate/clear most of the sockbuf structure, but leave selinfo
2466 * and mutex data unchanged.
2469 bzero(&asb, offsetof(struct sockbuf, sb_startzero));
2470 bcopy(&sb->sb_startzero, &asb.sb_startzero,
2471 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2472 bzero(&sb->sb_startzero,
2473 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2478 * Dispose of special rights and flush the socket buffer. Don't call
2479 * any unsafe routines (that rely on locks being initialized) on asb.
2481 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
2482 (*pr->pr_domain->dom_dispose)(asb.sb_mb);
2483 sbrelease_internal(&asb, so);
2487 * Perhaps this routine, and sooptcopyout(), below, ought to come in an
2488 * additional variant to handle the case where the option value needs to be
2489 * some kind of integer, but not a specific size. In addition to their use
2490 * here, these functions are also called by the protocol-level pr_ctloutput()
2494 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2499 * If the user gives us more than we wanted, we ignore it, but if we
2500 * don't get the minimum length the caller wants, we return EINVAL.
2501 * On success, sopt->sopt_valsize is set to however much we actually
2504 if ((valsize = sopt->sopt_valsize) < minlen)
2507 sopt->sopt_valsize = valsize = len;
2509 if (sopt->sopt_td != NULL)
2510 return (copyin(sopt->sopt_val, buf, valsize));
2512 bcopy(sopt->sopt_val, buf, valsize);
2517 * Kernel version of setsockopt(2).
2519 * XXX: optlen is size_t, not socklen_t
2522 so_setsockopt(struct socket *so, int level, int optname, void *optval,
2525 struct sockopt sopt;
2527 sopt.sopt_level = level;
2528 sopt.sopt_name = optname;
2529 sopt.sopt_dir = SOPT_SET;
2530 sopt.sopt_val = optval;
2531 sopt.sopt_valsize = optlen;
2532 sopt.sopt_td = NULL;
2533 return (sosetopt(so, &sopt));
2537 sosetopt(struct socket *so, struct sockopt *sopt)
2548 CURVNET_SET(so->so_vnet);
2550 if (sopt->sopt_level != SOL_SOCKET) {
2551 if (so->so_proto->pr_ctloutput != NULL) {
2552 error = (*so->so_proto->pr_ctloutput)(so, sopt);
2556 error = ENOPROTOOPT;
2558 switch (sopt->sopt_name) {
2560 case SO_ACCEPTFILTER:
2561 error = do_setopt_accept_filter(so, sopt);
2567 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
2572 so->so_linger = l.l_linger;
2574 so->so_options |= SO_LINGER;
2576 so->so_options &= ~SO_LINGER;
2583 case SO_USELOOPBACK:
2593 error = sooptcopyin(sopt, &optval, sizeof optval,
2599 so->so_options |= sopt->sopt_name;
2601 so->so_options &= ~sopt->sopt_name;
2606 error = sooptcopyin(sopt, &optval, sizeof optval,
2611 if (optval < 0 || optval >= rt_numfibs) {
2615 if (((so->so_proto->pr_domain->dom_family == PF_INET) ||
2616 (so->so_proto->pr_domain->dom_family == PF_INET6) ||
2617 (so->so_proto->pr_domain->dom_family == PF_ROUTE)))
2618 so->so_fibnum = optval;
2623 case SO_USER_COOKIE:
2624 error = sooptcopyin(sopt, &val32, sizeof val32,
2628 so->so_user_cookie = val32;
2635 error = sooptcopyin(sopt, &optval, sizeof optval,
2641 * Values < 1 make no sense for any of these options,
2649 switch (sopt->sopt_name) {
2652 if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
2653 &so->so_snd : &so->so_rcv, (u_long)optval,
2654 so, curthread) == 0) {
2658 (sopt->sopt_name == SO_SNDBUF ? &so->so_snd :
2659 &so->so_rcv)->sb_flags &= ~SB_AUTOSIZE;
2663 * Make sure the low-water is never greater than the
2667 SOCKBUF_LOCK(&so->so_snd);
2668 so->so_snd.sb_lowat =
2669 (optval > so->so_snd.sb_hiwat) ?
2670 so->so_snd.sb_hiwat : optval;
2671 SOCKBUF_UNLOCK(&so->so_snd);
2674 SOCKBUF_LOCK(&so->so_rcv);
2675 so->so_rcv.sb_lowat =
2676 (optval > so->so_rcv.sb_hiwat) ?
2677 so->so_rcv.sb_hiwat : optval;
2678 SOCKBUF_UNLOCK(&so->so_rcv);
2685 #ifdef COMPAT_FREEBSD32
2686 if (SV_CURPROC_FLAG(SV_ILP32)) {
2687 struct timeval32 tv32;
2689 error = sooptcopyin(sopt, &tv32, sizeof tv32,
2691 CP(tv32, tv, tv_sec);
2692 CP(tv32, tv, tv_usec);
2695 error = sooptcopyin(sopt, &tv, sizeof tv,
2700 /* assert(hz > 0); */
2701 if (tv.tv_sec < 0 || tv.tv_sec > INT_MAX / hz ||
2702 tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
2706 /* assert(tick > 0); */
2707 /* assert(ULONG_MAX - INT_MAX >= 1000000); */
2708 val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
2709 if (val > INT_MAX) {
2713 if (val == 0 && tv.tv_usec != 0)
2716 switch (sopt->sopt_name) {
2718 so->so_snd.sb_timeo = val;
2721 so->so_rcv.sb_timeo = val;
2728 error = sooptcopyin(sopt, &extmac, sizeof extmac,
2732 error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
2740 error = ENOPROTOOPT;
2743 if (error == 0 && so->so_proto->pr_ctloutput != NULL)
2744 (void)(*so->so_proto->pr_ctloutput)(so, sopt);
2752 * Helper routine for getsockopt.
2755 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
2763 * Documented get behavior is that we always return a value, possibly
2764 * truncated to fit in the user's buffer. Traditional behavior is
2765 * that we always tell the user precisely how much we copied, rather
2766 * than something useful like the total amount we had available for
2767 * her. Note that this interface is not idempotent; the entire
2768 * answer must generated ahead of time.
2770 valsize = min(len, sopt->sopt_valsize);
2771 sopt->sopt_valsize = valsize;
2772 if (sopt->sopt_val != NULL) {
2773 if (sopt->sopt_td != NULL)
2774 error = copyout(buf, sopt->sopt_val, valsize);
2776 bcopy(buf, sopt->sopt_val, valsize);
2782 sogetopt(struct socket *so, struct sockopt *sopt)
2791 CURVNET_SET(so->so_vnet);
2793 if (sopt->sopt_level != SOL_SOCKET) {
2794 if (so->so_proto->pr_ctloutput != NULL)
2795 error = (*so->so_proto->pr_ctloutput)(so, sopt);
2797 error = ENOPROTOOPT;
2801 switch (sopt->sopt_name) {
2803 case SO_ACCEPTFILTER:
2804 error = do_getopt_accept_filter(so, sopt);
2809 l.l_onoff = so->so_options & SO_LINGER;
2810 l.l_linger = so->so_linger;
2812 error = sooptcopyout(sopt, &l, sizeof l);
2815 case SO_USELOOPBACK:
2827 optval = so->so_options & sopt->sopt_name;
2829 error = sooptcopyout(sopt, &optval, sizeof optval);
2833 optval = so->so_type;
2837 optval = so->so_proto->pr_protocol;
2842 optval = so->so_error;
2848 optval = so->so_snd.sb_hiwat;
2852 optval = so->so_rcv.sb_hiwat;
2856 optval = so->so_snd.sb_lowat;
2860 optval = so->so_rcv.sb_lowat;
2865 optval = (sopt->sopt_name == SO_SNDTIMEO ?
2866 so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
2868 tv.tv_sec = optval / hz;
2869 tv.tv_usec = (optval % hz) * tick;
2870 #ifdef COMPAT_FREEBSD32
2871 if (SV_CURPROC_FLAG(SV_ILP32)) {
2872 struct timeval32 tv32;
2874 CP(tv, tv32, tv_sec);
2875 CP(tv, tv32, tv_usec);
2876 error = sooptcopyout(sopt, &tv32, sizeof tv32);
2879 error = sooptcopyout(sopt, &tv, sizeof tv);
2884 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2888 error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
2892 error = sooptcopyout(sopt, &extmac, sizeof extmac);
2900 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2904 error = mac_getsockopt_peerlabel(
2905 sopt->sopt_td->td_ucred, so, &extmac);
2908 error = sooptcopyout(sopt, &extmac, sizeof extmac);
2914 case SO_LISTENQLIMIT:
2915 optval = so->so_qlimit;
2919 optval = so->so_qlen;
2922 case SO_LISTENINCQLEN:
2923 optval = so->so_incqlen;
2927 error = ENOPROTOOPT;
2939 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
2941 struct mbuf *m, *m_prev;
2942 int sopt_size = sopt->sopt_valsize;
2944 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
2947 if (sopt_size > MLEN) {
2948 MCLGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT);
2949 if ((m->m_flags & M_EXT) == 0) {
2953 m->m_len = min(MCLBYTES, sopt_size);
2955 m->m_len = min(MLEN, sopt_size);
2957 sopt_size -= m->m_len;
2962 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
2967 if (sopt_size > MLEN) {
2968 MCLGET(m, sopt->sopt_td != NULL ? M_WAITOK :
2970 if ((m->m_flags & M_EXT) == 0) {
2975 m->m_len = min(MCLBYTES, sopt_size);
2977 m->m_len = min(MLEN, sopt_size);
2979 sopt_size -= m->m_len;
2987 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
2989 struct mbuf *m0 = m;
2991 if (sopt->sopt_val == NULL)
2993 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2994 if (sopt->sopt_td != NULL) {
2997 error = copyin(sopt->sopt_val, mtod(m, char *),
3004 bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
3005 sopt->sopt_valsize -= m->m_len;
3006 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
3009 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
3010 panic("ip6_sooptmcopyin");
3015 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
3017 struct mbuf *m0 = m;
3020 if (sopt->sopt_val == NULL)
3022 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
3023 if (sopt->sopt_td != NULL) {
3026 error = copyout(mtod(m, char *), sopt->sopt_val,
3033 bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
3034 sopt->sopt_valsize -= m->m_len;
3035 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
3036 valsize += m->m_len;
3040 /* enough soopt buffer should be given from user-land */
3044 sopt->sopt_valsize = valsize;
3049 * sohasoutofband(): protocol notifies socket layer of the arrival of new
3050 * out-of-band data, which will then notify socket consumers.
3053 sohasoutofband(struct socket *so)
3056 if (so->so_sigio != NULL)
3057 pgsigio(&so->so_sigio, SIGURG, 0);
3058 selwakeuppri(&so->so_rcv.sb_sel, PSOCK);
3062 sopoll(struct socket *so, int events, struct ucred *active_cred,
3067 * We do not need to set or assert curvnet as long as everyone uses
3070 return (so->so_proto->pr_usrreqs->pru_sopoll(so, events, active_cred,
3075 sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
3080 SOCKBUF_LOCK(&so->so_snd);
3081 SOCKBUF_LOCK(&so->so_rcv);
3082 if (events & (POLLIN | POLLRDNORM))
3083 if (soreadabledata(so))
3084 revents |= events & (POLLIN | POLLRDNORM);
3086 if (events & (POLLOUT | POLLWRNORM))
3087 if (sowriteable(so))
3088 revents |= events & (POLLOUT | POLLWRNORM);
3090 if (events & (POLLPRI | POLLRDBAND))
3091 if (so->so_oobmark || (so->so_rcv.sb_state & SBS_RCVATMARK))
3092 revents |= events & (POLLPRI | POLLRDBAND);
3094 if ((events & POLLINIGNEOF) == 0) {
3095 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3096 revents |= events & (POLLIN | POLLRDNORM);
3097 if (so->so_snd.sb_state & SBS_CANTSENDMORE)
3103 if (events & (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND)) {
3104 selrecord(td, &so->so_rcv.sb_sel);
3105 so->so_rcv.sb_flags |= SB_SEL;
3108 if (events & (POLLOUT | POLLWRNORM)) {
3109 selrecord(td, &so->so_snd.sb_sel);
3110 so->so_snd.sb_flags |= SB_SEL;
3114 SOCKBUF_UNLOCK(&so->so_rcv);
3115 SOCKBUF_UNLOCK(&so->so_snd);
3120 soo_kqfilter(struct file *fp, struct knote *kn)
3122 struct socket *so = kn->kn_fp->f_data;
3125 switch (kn->kn_filter) {
3127 if (so->so_options & SO_ACCEPTCONN)
3128 kn->kn_fop = &solisten_filtops;
3130 kn->kn_fop = &soread_filtops;
3134 kn->kn_fop = &sowrite_filtops;
3142 knlist_add(&sb->sb_sel.si_note, kn, 1);
3143 sb->sb_flags |= SB_KNOTE;
3149 * Some routines that return EOPNOTSUPP for entry points that are not
3150 * supported by a protocol. Fill in as needed.
3153 pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
3160 pru_attach_notsupp(struct socket *so, int proto, struct thread *td)
3167 pru_bind_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
3174 pru_bindat_notsupp(int fd, struct socket *so, struct sockaddr *nam,
3182 pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
3189 pru_connectat_notsupp(int fd, struct socket *so, struct sockaddr *nam,
3197 pru_connect2_notsupp(struct socket *so1, struct socket *so2)
3204 pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
3205 struct ifnet *ifp, struct thread *td)
3212 pru_disconnect_notsupp(struct socket *so)
3219 pru_listen_notsupp(struct socket *so, int backlog, struct thread *td)
3226 pru_peeraddr_notsupp(struct socket *so, struct sockaddr **nam)
3233 pru_rcvd_notsupp(struct socket *so, int flags)
3240 pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
3247 pru_send_notsupp(struct socket *so, int flags, struct mbuf *m,
3248 struct sockaddr *addr, struct mbuf *control, struct thread *td)
3255 * This isn't really a ``null'' operation, but it's the default one and
3256 * doesn't do anything destructive.
3259 pru_sense_null(struct socket *so, struct stat *sb)
3262 sb->st_blksize = so->so_snd.sb_hiwat;
3267 pru_shutdown_notsupp(struct socket *so)
3274 pru_sockaddr_notsupp(struct socket *so, struct sockaddr **nam)
3281 pru_sosend_notsupp(struct socket *so, struct sockaddr *addr, struct uio *uio,
3282 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
3289 pru_soreceive_notsupp(struct socket *so, struct sockaddr **paddr,
3290 struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
3297 pru_sopoll_notsupp(struct socket *so, int events, struct ucred *cred,
3305 filt_sordetach(struct knote *kn)
3307 struct socket *so = kn->kn_fp->f_data;
3309 SOCKBUF_LOCK(&so->so_rcv);
3310 knlist_remove(&so->so_rcv.sb_sel.si_note, kn, 1);
3311 if (knlist_empty(&so->so_rcv.sb_sel.si_note))
3312 so->so_rcv.sb_flags &= ~SB_KNOTE;
3313 SOCKBUF_UNLOCK(&so->so_rcv);
3318 filt_soread(struct knote *kn, long hint)
3322 so = kn->kn_fp->f_data;
3323 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3325 kn->kn_data = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
3326 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3327 kn->kn_flags |= EV_EOF;
3328 kn->kn_fflags = so->so_error;
3330 } else if (so->so_error) /* temporary udp error */
3332 else if (kn->kn_sfflags & NOTE_LOWAT)
3333 return (kn->kn_data >= kn->kn_sdata);
3335 return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat);
3339 filt_sowdetach(struct knote *kn)
3341 struct socket *so = kn->kn_fp->f_data;
3343 SOCKBUF_LOCK(&so->so_snd);
3344 knlist_remove(&so->so_snd.sb_sel.si_note, kn, 1);
3345 if (knlist_empty(&so->so_snd.sb_sel.si_note))
3346 so->so_snd.sb_flags &= ~SB_KNOTE;
3347 SOCKBUF_UNLOCK(&so->so_snd);
3352 filt_sowrite(struct knote *kn, long hint)
3356 so = kn->kn_fp->f_data;
3357 SOCKBUF_LOCK_ASSERT(&so->so_snd);
3358 kn->kn_data = sbspace(&so->so_snd);
3359 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
3360 kn->kn_flags |= EV_EOF;
3361 kn->kn_fflags = so->so_error;
3363 } else if (so->so_error) /* temporary udp error */
3365 else if (((so->so_state & SS_ISCONNECTED) == 0) &&
3366 (so->so_proto->pr_flags & PR_CONNREQUIRED))
3368 else if (kn->kn_sfflags & NOTE_LOWAT)
3369 return (kn->kn_data >= kn->kn_sdata);
3371 return (kn->kn_data >= so->so_snd.sb_lowat);
3376 filt_solisten(struct knote *kn, long hint)
3378 struct socket *so = kn->kn_fp->f_data;
3380 kn->kn_data = so->so_qlen;
3381 return (!TAILQ_EMPTY(&so->so_comp));
3385 socheckuid(struct socket *so, uid_t uid)
3390 if (so->so_cred->cr_uid != uid)
3396 * These functions are used by protocols to notify the socket layer (and its
3397 * consumers) of state changes in the sockets driven by protocol-side events.
3401 * Procedures to manipulate state flags of socket and do appropriate wakeups.
3403 * Normal sequence from the active (originating) side is that
3404 * soisconnecting() is called during processing of connect() call, resulting
3405 * in an eventual call to soisconnected() if/when the connection is
3406 * established. When the connection is torn down soisdisconnecting() is
3407 * called during processing of disconnect() call, and soisdisconnected() is
3408 * called when the connection to the peer is totally severed. The semantics
3409 * of these routines are such that connectionless protocols can call
3410 * soisconnected() and soisdisconnected() only, bypassing the in-progress
3411 * calls when setting up a ``connection'' takes no time.
3413 * From the passive side, a socket is created with two queues of sockets:
3414 * so_incomp for connections in progress and so_comp for connections already
3415 * made and awaiting user acceptance. As a protocol is preparing incoming
3416 * connections, it creates a socket structure queued on so_incomp by calling
3417 * sonewconn(). When the connection is established, soisconnected() is
3418 * called, and transfers the socket structure to so_comp, making it available
3421 * If a socket is closed with sockets on either so_incomp or so_comp, these
3422 * sockets are dropped.
3424 * If higher-level protocols are implemented in the kernel, the wakeups done
3425 * here will sometimes cause software-interrupt process scheduling.
3428 soisconnecting(struct socket *so)
3432 so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
3433 so->so_state |= SS_ISCONNECTING;
3438 soisconnected(struct socket *so)
3440 struct socket *head;
3446 so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
3447 so->so_state |= SS_ISCONNECTED;
3449 if (head != NULL && (so->so_qstate & SQ_INCOMP)) {
3450 if ((so->so_options & SO_ACCEPTFILTER) == 0) {
3452 TAILQ_REMOVE(&head->so_incomp, so, so_list);
3454 so->so_qstate &= ~SQ_INCOMP;
3455 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
3457 so->so_qstate |= SQ_COMP;
3460 wakeup_one(&head->so_timeo);
3463 soupcall_set(so, SO_RCV,
3464 head->so_accf->so_accept_filter->accf_callback,
3465 head->so_accf->so_accept_filter_arg);
3466 so->so_options &= ~SO_ACCEPTFILTER;
3467 ret = head->so_accf->so_accept_filter->accf_callback(so,
3468 head->so_accf->so_accept_filter_arg, M_NOWAIT);
3469 if (ret == SU_ISCONNECTED)
3470 soupcall_clear(so, SO_RCV);
3472 if (ret == SU_ISCONNECTED)
3479 wakeup(&so->so_timeo);
3485 soisdisconnecting(struct socket *so)
3489 * Note: This code assumes that SOCK_LOCK(so) and
3490 * SOCKBUF_LOCK(&so->so_rcv) are the same.
3492 SOCKBUF_LOCK(&so->so_rcv);
3493 so->so_state &= ~SS_ISCONNECTING;
3494 so->so_state |= SS_ISDISCONNECTING;
3495 so->so_rcv.sb_state |= SBS_CANTRCVMORE;
3496 sorwakeup_locked(so);
3497 SOCKBUF_LOCK(&so->so_snd);
3498 so->so_snd.sb_state |= SBS_CANTSENDMORE;
3499 sowwakeup_locked(so);
3500 wakeup(&so->so_timeo);
3504 soisdisconnected(struct socket *so)
3508 * Note: This code assumes that SOCK_LOCK(so) and
3509 * SOCKBUF_LOCK(&so->so_rcv) are the same.
3511 SOCKBUF_LOCK(&so->so_rcv);
3512 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
3513 so->so_state |= SS_ISDISCONNECTED;
3514 so->so_rcv.sb_state |= SBS_CANTRCVMORE;
3515 sorwakeup_locked(so);
3516 SOCKBUF_LOCK(&so->so_snd);
3517 so->so_snd.sb_state |= SBS_CANTSENDMORE;
3518 sbdrop_locked(&so->so_snd, so->so_snd.sb_cc);
3519 sowwakeup_locked(so);
3520 wakeup(&so->so_timeo);
3524 * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
3527 sodupsockaddr(const struct sockaddr *sa, int mflags)
3529 struct sockaddr *sa2;
3531 sa2 = malloc(sa->sa_len, M_SONAME, mflags);
3533 bcopy(sa, sa2, sa->sa_len);
3538 * Register per-socket buffer upcalls.
3541 soupcall_set(struct socket *so, int which,
3542 int (*func)(struct socket *, void *, int), void *arg)
3554 panic("soupcall_set: bad which");
3556 SOCKBUF_LOCK_ASSERT(sb);
3558 /* XXX: accf_http actually wants to do this on purpose. */
3559 KASSERT(sb->sb_upcall == NULL, ("soupcall_set: overwriting upcall"));
3561 sb->sb_upcall = func;
3562 sb->sb_upcallarg = arg;
3563 sb->sb_flags |= SB_UPCALL;
3567 soupcall_clear(struct socket *so, int which)
3579 panic("soupcall_clear: bad which");
3581 SOCKBUF_LOCK_ASSERT(sb);
3582 KASSERT(sb->sb_upcall != NULL, ("soupcall_clear: no upcall to clear"));
3583 sb->sb_upcall = NULL;
3584 sb->sb_upcallarg = NULL;
3585 sb->sb_flags &= ~SB_UPCALL;
3589 * Create an external-format (``xsocket'') structure using the information in
3590 * the kernel-format socket structure pointed to by so. This is done to
3591 * reduce the spew of irrelevant information over this interface, to isolate
3592 * user code from changes in the kernel structure, and potentially to provide
3593 * information-hiding if we decide that some of this information should be
3594 * hidden from users.
3597 sotoxsocket(struct socket *so, struct xsocket *xso)
3600 xso->xso_len = sizeof *xso;
3602 xso->so_type = so->so_type;
3603 xso->so_options = so->so_options;
3604 xso->so_linger = so->so_linger;
3605 xso->so_state = so->so_state;
3606 xso->so_pcb = so->so_pcb;
3607 xso->xso_protocol = so->so_proto->pr_protocol;
3608 xso->xso_family = so->so_proto->pr_domain->dom_family;
3609 xso->so_qlen = so->so_qlen;
3610 xso->so_incqlen = so->so_incqlen;
3611 xso->so_qlimit = so->so_qlimit;
3612 xso->so_timeo = so->so_timeo;
3613 xso->so_error = so->so_error;
3614 xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
3615 xso->so_oobmark = so->so_oobmark;
3616 sbtoxsockbuf(&so->so_snd, &xso->so_snd);
3617 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
3618 xso->so_uid = so->so_cred->cr_uid;
3623 * Socket accessor functions to provide external consumers with
3624 * a safe interface to socket state
3629 so_listeners_apply_all(struct socket *so, void (*func)(struct socket *, void *),
3633 TAILQ_FOREACH(so, &so->so_comp, so_list)
3638 so_sockbuf_rcv(struct socket *so)
3641 return (&so->so_rcv);
3645 so_sockbuf_snd(struct socket *so)
3648 return (&so->so_snd);
3652 so_state_get(const struct socket *so)
3655 return (so->so_state);
3659 so_state_set(struct socket *so, int val)
3666 so_options_get(const struct socket *so)
3669 return (so->so_options);
3673 so_options_set(struct socket *so, int val)
3676 so->so_options = val;
3680 so_error_get(const struct socket *so)
3683 return (so->so_error);
3687 so_error_set(struct socket *so, int val)
3694 so_linger_get(const struct socket *so)
3697 return (so->so_linger);
3701 so_linger_set(struct socket *so, int val)
3704 so->so_linger = val;
3708 so_protosw_get(const struct socket *so)
3711 return (so->so_proto);
3715 so_protosw_set(struct socket *so, struct protosw *val)
3722 so_sorwakeup(struct socket *so)
3729 so_sowwakeup(struct socket *so)
3736 so_sorwakeup_locked(struct socket *so)
3739 sorwakeup_locked(so);
3743 so_sowwakeup_locked(struct socket *so)
3746 sowwakeup_locked(so);
3750 so_lock(struct socket *so)
3757 so_unlock(struct socket *so)