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_compat.h"
110 #include <sys/param.h>
111 #include <sys/systm.h>
112 #include <sys/fcntl.h>
113 #include <sys/limits.h>
114 #include <sys/lock.h>
116 #include <sys/malloc.h>
117 #include <sys/mbuf.h>
118 #include <sys/mutex.h>
119 #include <sys/domain.h>
120 #include <sys/file.h> /* for struct knote */
121 #include <sys/hhook.h>
122 #include <sys/kernel.h>
123 #include <sys/khelp.h>
124 #include <sys/event.h>
125 #include <sys/eventhandler.h>
126 #include <sys/poll.h>
127 #include <sys/proc.h>
128 #include <sys/protosw.h>
129 #include <sys/socket.h>
130 #include <sys/socketvar.h>
131 #include <sys/resourcevar.h>
132 #include <net/route.h>
133 #include <sys/signalvar.h>
134 #include <sys/stat.h>
136 #include <sys/sysctl.h>
138 #include <sys/jail.h>
139 #include <sys/syslog.h>
140 #include <netinet/in.h>
142 #include <net/vnet.h>
144 #include <security/mac/mac_framework.h>
148 #ifdef COMPAT_FREEBSD32
149 #include <sys/mount.h>
150 #include <sys/sysent.h>
151 #include <compat/freebsd32/freebsd32.h>
154 static int soreceive_rcvoob(struct socket *so, struct uio *uio,
157 static void filt_sordetach(struct knote *kn);
158 static int filt_soread(struct knote *kn, long hint);
159 static void filt_sowdetach(struct knote *kn);
160 static int filt_sowrite(struct knote *kn, long hint);
161 static int filt_solisten(struct knote *kn, long hint);
162 static int inline hhook_run_socket(struct socket *so, void *hctx, int32_t h_id);
163 fo_kqfilter_t soo_kqfilter;
165 static struct filterops solisten_filtops = {
167 .f_detach = filt_sordetach,
168 .f_event = filt_solisten,
170 static struct filterops soread_filtops = {
172 .f_detach = filt_sordetach,
173 .f_event = filt_soread,
175 static struct filterops sowrite_filtops = {
177 .f_detach = filt_sowdetach,
178 .f_event = filt_sowrite,
181 so_gen_t so_gencnt; /* generation count for sockets */
183 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
184 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
186 #define VNET_SO_ASSERT(so) \
187 VNET_ASSERT(curvnet != NULL, \
188 ("%s:%d curvnet is NULL, so=%p", __func__, __LINE__, (so)));
190 VNET_DEFINE(struct hhook_head *, socket_hhh[HHOOK_SOCKET_LAST + 1]);
191 #define V_socket_hhh VNET(socket_hhh)
194 * Limit on the number of connections in the listen queue waiting
196 * NB: The orginal sysctl somaxconn is still available but hidden
197 * to prevent confusion about the actual purpose of this number.
199 static u_int somaxconn = SOMAXCONN;
202 sysctl_somaxconn(SYSCTL_HANDLER_ARGS)
208 error = sysctl_handle_int(oidp, &val, 0, req);
209 if (error || !req->newptr )
213 * The purpose of the UINT_MAX / 3 limit, is so that the formula
215 * below, will not overflow.
218 if (val < 1 || val > UINT_MAX / 3)
224 SYSCTL_PROC(_kern_ipc, OID_AUTO, soacceptqueue, CTLTYPE_UINT | CTLFLAG_RW,
225 0, sizeof(int), sysctl_somaxconn, "I",
226 "Maximum listen socket pending connection accept queue size");
227 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn,
228 CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_SKIP,
229 0, sizeof(int), sysctl_somaxconn, "I",
230 "Maximum listen socket pending connection accept queue size (compat)");
232 static int numopensockets;
233 SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
234 &numopensockets, 0, "Number of open sockets");
237 * accept_mtx locks down per-socket fields relating to accept queues. See
238 * socketvar.h for an annotation of the protected fields of struct socket.
240 struct mtx accept_mtx;
241 MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
244 * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
247 static struct mtx so_global_mtx;
248 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
251 * General IPC sysctl name space, used by sockets and a variety of other IPC
254 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
257 * Initialize the socket subsystem and set up the socket
260 static uma_zone_t socket_zone;
264 socket_zone_change(void *tag)
267 maxsockets = uma_zone_set_max(socket_zone, maxsockets);
271 socket_hhook_register(int subtype)
274 if (hhook_head_register(HHOOK_TYPE_SOCKET, subtype,
275 &V_socket_hhh[subtype],
276 HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
277 printf("%s: WARNING: unable to register hook\n", __func__);
281 socket_hhook_deregister(int subtype)
284 if (hhook_head_deregister(V_socket_hhh[subtype]) != 0)
285 printf("%s: WARNING: unable to deregister hook\n", __func__);
289 socket_init(void *tag)
292 socket_zone = uma_zcreate("socket", sizeof(struct socket), NULL, NULL,
293 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
294 maxsockets = uma_zone_set_max(socket_zone, maxsockets);
295 uma_zone_set_warning(socket_zone, "kern.ipc.maxsockets limit reached");
296 EVENTHANDLER_REGISTER(maxsockets_change, socket_zone_change, NULL,
297 EVENTHANDLER_PRI_FIRST);
299 SYSINIT(socket, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, socket_init, NULL);
302 socket_vnet_init(const void *unused __unused)
306 /* We expect a contiguous range */
307 for (i = 0; i <= HHOOK_SOCKET_LAST; i++)
308 socket_hhook_register(i);
310 VNET_SYSINIT(socket_vnet_init, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY,
311 socket_vnet_init, NULL);
314 socket_vnet_uninit(const void *unused __unused)
318 for (i = 0; i <= HHOOK_SOCKET_LAST; i++)
319 socket_hhook_deregister(i);
321 VNET_SYSUNINIT(socket_vnet_uninit, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY,
322 socket_vnet_uninit, NULL);
325 * Initialise maxsockets. This SYSINIT must be run after
329 init_maxsockets(void *ignored)
332 TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
333 maxsockets = imax(maxsockets, maxfiles);
335 SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);
338 * Sysctl to get and set the maximum global sockets limit. Notify protocols
339 * of the change so that they can update their dependent limits as required.
342 sysctl_maxsockets(SYSCTL_HANDLER_ARGS)
344 int error, newmaxsockets;
346 newmaxsockets = maxsockets;
347 error = sysctl_handle_int(oidp, &newmaxsockets, 0, req);
348 if (error == 0 && req->newptr) {
349 if (newmaxsockets > maxsockets &&
350 newmaxsockets <= maxfiles) {
351 maxsockets = newmaxsockets;
352 EVENTHANDLER_INVOKE(maxsockets_change);
358 SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets, CTLTYPE_INT|CTLFLAG_RW,
359 &maxsockets, 0, sysctl_maxsockets, "IU",
360 "Maximum number of sockets avaliable");
363 * Socket operation routines. These routines are called by the routines in
364 * sys_socket.c or from a system process, and implement the semantics of
365 * socket operations by switching out to the protocol specific routines.
369 * Get a socket structure from our zone, and initialize it. Note that it
370 * would probably be better to allocate socket and PCB at the same time, but
371 * I'm not convinced that all the protocols can be easily modified to do
374 * soalloc() returns a socket with a ref count of 0.
376 static struct socket *
377 soalloc(struct vnet *vnet)
381 so = uma_zalloc(socket_zone, M_NOWAIT | M_ZERO);
385 if (mac_socket_init(so, M_NOWAIT) != 0) {
386 uma_zfree(socket_zone, so);
390 if (khelp_init_osd(HELPER_CLASS_SOCKET, &so->osd)) {
391 uma_zfree(socket_zone, so);
395 SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
396 SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
397 sx_init(&so->so_snd.sb_sx, "so_snd_sx");
398 sx_init(&so->so_rcv.sb_sx, "so_rcv_sx");
399 TAILQ_INIT(&so->so_aiojobq);
401 VNET_ASSERT(vnet != NULL, ("%s:%d vnet is NULL, so=%p",
402 __func__, __LINE__, so));
405 /* We shouldn't need the so_global_mtx */
406 if (hhook_run_socket(so, NULL, HHOOK_SOCKET_CREATE)) {
407 /* Do we need more comprehensive error returns? */
408 uma_zfree(socket_zone, so);
411 mtx_lock(&so_global_mtx);
412 so->so_gencnt = ++so_gencnt;
415 vnet->vnet_sockcnt++;
417 mtx_unlock(&so_global_mtx);
423 * Free the storage associated with a socket at the socket layer, tear down
424 * locks, labels, etc. All protocol state is assumed already to have been
425 * torn down (and possibly never set up) by the caller.
428 sodealloc(struct socket *so)
431 KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
432 KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
434 mtx_lock(&so_global_mtx);
435 so->so_gencnt = ++so_gencnt;
436 --numopensockets; /* Could be below, but faster here. */
438 VNET_ASSERT(so->so_vnet != NULL, ("%s:%d so_vnet is NULL, so=%p",
439 __func__, __LINE__, so));
440 so->so_vnet->vnet_sockcnt--;
442 mtx_unlock(&so_global_mtx);
443 if (so->so_rcv.sb_hiwat)
444 (void)chgsbsize(so->so_cred->cr_uidinfo,
445 &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
446 if (so->so_snd.sb_hiwat)
447 (void)chgsbsize(so->so_cred->cr_uidinfo,
448 &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
449 /* remove accept filter if one is present. */
450 if (so->so_accf != NULL)
451 do_setopt_accept_filter(so, NULL);
453 mac_socket_destroy(so);
455 hhook_run_socket(so, NULL, HHOOK_SOCKET_CLOSE);
458 khelp_destroy_osd(&so->osd);
459 sx_destroy(&so->so_snd.sb_sx);
460 sx_destroy(&so->so_rcv.sb_sx);
461 SOCKBUF_LOCK_DESTROY(&so->so_snd);
462 SOCKBUF_LOCK_DESTROY(&so->so_rcv);
463 uma_zfree(socket_zone, so);
467 * socreate returns a socket with a ref count of 1. The socket should be
468 * closed with soclose().
471 socreate(int dom, struct socket **aso, int type, int proto,
472 struct ucred *cred, struct thread *td)
479 prp = pffindproto(dom, proto, type);
481 prp = pffindtype(dom, type);
484 /* No support for domain. */
485 if (pffinddomain(dom) == NULL)
486 return (EAFNOSUPPORT);
487 /* No support for socket type. */
488 if (proto == 0 && type != 0)
490 return (EPROTONOSUPPORT);
492 if (prp->pr_usrreqs->pru_attach == NULL ||
493 prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
494 return (EPROTONOSUPPORT);
496 if (prison_check_af(cred, prp->pr_domain->dom_family) != 0)
497 return (EPROTONOSUPPORT);
499 if (prp->pr_type != type)
501 so = soalloc(CRED_TO_VNET(cred));
505 TAILQ_INIT(&so->so_incomp);
506 TAILQ_INIT(&so->so_comp);
508 so->so_cred = crhold(cred);
509 if ((prp->pr_domain->dom_family == PF_INET) ||
510 (prp->pr_domain->dom_family == PF_INET6) ||
511 (prp->pr_domain->dom_family == PF_ROUTE))
512 so->so_fibnum = td->td_proc->p_fibnum;
517 mac_socket_create(cred, so);
519 knlist_init_mtx(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
520 knlist_init_mtx(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
523 * Auto-sizing of socket buffers is managed by the protocols and
524 * the appropriate flags must be set in the pru_attach function.
526 CURVNET_SET(so->so_vnet);
527 error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
530 KASSERT(so->so_count == 1, ("socreate: so_count %d",
541 static int regression_sonewconn_earlytest = 1;
542 SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW,
543 ®ression_sonewconn_earlytest, 0, "Perform early sonewconn limit test");
547 * When an attempt at a new connection is noted on a socket which accepts
548 * connections, sonewconn is called. If the connection is possible (subject
549 * to space constraints, etc.) then we allocate a new structure, propoerly
550 * linked into the data structure of the original socket, and return this.
551 * Connstatus may be 0, or SS_ISCONFIRMING, or SS_ISCONNECTED.
553 * Note: the ref count on the socket is 0 on return.
556 sonewconn(struct socket *head, int connstatus)
558 static struct timeval lastover;
559 static struct timeval overinterval = { 60, 0 };
560 static int overcount;
566 over = (head->so_qlen > 3 * head->so_qlimit / 2);
569 if (regression_sonewconn_earlytest && over) {
575 if (ratecheck(&lastover, &overinterval)) {
576 log(LOG_DEBUG, "%s: pcb %p: Listen queue overflow: "
577 "%i already in queue awaiting acceptance "
578 "(%d occurrences)\n",
579 __func__, head->so_pcb, head->so_qlen, overcount);
586 VNET_ASSERT(head->so_vnet != NULL, ("%s:%d so_vnet is NULL, head=%p",
587 __func__, __LINE__, head));
588 so = soalloc(head->so_vnet);
590 log(LOG_DEBUG, "%s: pcb %p: New socket allocation failure: "
591 "limit reached or out of memory\n",
592 __func__, head->so_pcb);
595 if ((head->so_options & SO_ACCEPTFILTER) != 0)
598 so->so_type = head->so_type;
599 so->so_options = head->so_options &~ SO_ACCEPTCONN;
600 so->so_linger = head->so_linger;
601 so->so_state = head->so_state | SS_NOFDREF;
602 so->so_fibnum = head->so_fibnum;
603 so->so_proto = head->so_proto;
604 so->so_cred = crhold(head->so_cred);
606 mac_socket_newconn(head, so);
608 knlist_init_mtx(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
609 knlist_init_mtx(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
610 VNET_SO_ASSERT(head);
611 if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat)) {
613 log(LOG_DEBUG, "%s: pcb %p: soreserve() failed\n",
614 __func__, head->so_pcb);
617 if ((*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
619 log(LOG_DEBUG, "%s: pcb %p: pru_attach() failed\n",
620 __func__, head->so_pcb);
623 so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
624 so->so_snd.sb_lowat = head->so_snd.sb_lowat;
625 so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
626 so->so_snd.sb_timeo = head->so_snd.sb_timeo;
627 so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
628 so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
629 so->so_state |= connstatus;
632 * The accept socket may be tearing down but we just
633 * won a race on the ACCEPT_LOCK.
634 * However, if sctp_peeloff() is called on a 1-to-many
635 * style socket, the SO_ACCEPTCONN doesn't need to be set.
637 if (!(head->so_options & SO_ACCEPTCONN) &&
638 ((head->so_proto->pr_protocol != IPPROTO_SCTP) ||
639 (head->so_type != SOCK_SEQPACKET))) {
642 sofree(so); /* NB: returns ACCEPT_UNLOCK'ed. */
646 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
647 so->so_qstate |= SQ_COMP;
651 * Keep removing sockets from the head until there's room for
652 * us to insert on the tail. In pre-locking revisions, this
653 * was a simple if(), but as we could be racing with other
654 * threads and soabort() requires dropping locks, we must
655 * loop waiting for the condition to be true.
657 while (head->so_incqlen > head->so_qlimit) {
659 sp = TAILQ_FIRST(&head->so_incomp);
660 TAILQ_REMOVE(&head->so_incomp, sp, so_list);
662 sp->so_qstate &= ~SQ_INCOMP;
668 TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
669 so->so_qstate |= SQ_INCOMP;
675 wakeup_one(&head->so_timeo);
681 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
685 CURVNET_SET(so->so_vnet);
686 error = (*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td);
692 sobindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
696 CURVNET_SET(so->so_vnet);
697 error = (*so->so_proto->pr_usrreqs->pru_bindat)(fd, so, nam, td);
703 * solisten() transitions a socket from a non-listening state to a listening
704 * state, but can also be used to update the listen queue depth on an
705 * existing listen socket. The protocol will call back into the sockets
706 * layer using solisten_proto_check() and solisten_proto() to check and set
707 * socket-layer listen state. Call backs are used so that the protocol can
708 * acquire both protocol and socket layer locks in whatever order is required
711 * Protocol implementors are advised to hold the socket lock across the
712 * socket-layer test and set to avoid races at the socket layer.
715 solisten(struct socket *so, int backlog, struct thread *td)
719 CURVNET_SET(so->so_vnet);
720 error = (*so->so_proto->pr_usrreqs->pru_listen)(so, backlog, td);
726 solisten_proto_check(struct socket *so)
729 SOCK_LOCK_ASSERT(so);
731 if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
738 solisten_proto(struct socket *so, int backlog)
741 SOCK_LOCK_ASSERT(so);
743 if (backlog < 0 || backlog > somaxconn)
745 so->so_qlimit = backlog;
746 so->so_options |= SO_ACCEPTCONN;
750 * Evaluate the reference count and named references on a socket; if no
751 * references remain, free it. This should be called whenever a reference is
752 * released, such as in sorele(), but also when named reference flags are
753 * cleared in socket or protocol code.
755 * sofree() will free the socket if:
757 * - There are no outstanding file descriptor references or related consumers
760 * - The socket has been closed by user space, if ever open (SS_NOFDREF).
762 * - The protocol does not have an outstanding strong reference on the socket
765 * - The socket is not in a completed connection queue, so a process has been
766 * notified that it is present. If it is removed, the user process may
767 * block in accept() despite select() saying the socket was ready.
770 sofree(struct socket *so)
772 struct protosw *pr = so->so_proto;
775 ACCEPT_LOCK_ASSERT();
776 SOCK_LOCK_ASSERT(so);
778 if ((so->so_state & SS_NOFDREF) == 0 || so->so_count != 0 ||
779 (so->so_state & SS_PROTOREF) || (so->so_qstate & SQ_COMP)) {
787 KASSERT((so->so_qstate & SQ_COMP) != 0 ||
788 (so->so_qstate & SQ_INCOMP) != 0,
789 ("sofree: so_head != NULL, but neither SQ_COMP nor "
791 KASSERT((so->so_qstate & SQ_COMP) == 0 ||
792 (so->so_qstate & SQ_INCOMP) == 0,
793 ("sofree: so->so_qstate is SQ_COMP and also SQ_INCOMP"));
794 TAILQ_REMOVE(&head->so_incomp, so, so_list);
796 so->so_qstate &= ~SQ_INCOMP;
799 KASSERT((so->so_qstate & SQ_COMP) == 0 &&
800 (so->so_qstate & SQ_INCOMP) == 0,
801 ("sofree: so_head == NULL, but still SQ_COMP(%d) or SQ_INCOMP(%d)",
802 so->so_qstate & SQ_COMP, so->so_qstate & SQ_INCOMP));
803 if (so->so_options & SO_ACCEPTCONN) {
804 KASSERT((TAILQ_EMPTY(&so->so_comp)),
805 ("sofree: so_comp populated"));
806 KASSERT((TAILQ_EMPTY(&so->so_incomp)),
807 ("sofree: so_incomp populated"));
813 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
814 (*pr->pr_domain->dom_dispose)(so);
815 if (pr->pr_usrreqs->pru_detach != NULL)
816 (*pr->pr_usrreqs->pru_detach)(so);
819 * From this point on, we assume that no other references to this
820 * socket exist anywhere else in the stack. Therefore, no locks need
821 * to be acquired or held.
823 * We used to do a lot of socket buffer and socket locking here, as
824 * well as invoke sorflush() and perform wakeups. The direct call to
825 * dom_dispose() and sbrelease_internal() are an inlining of what was
826 * necessary from sorflush().
828 * Notice that the socket buffer and kqueue state are torn down
829 * before calling pru_detach. This means that protocols shold not
830 * assume they can perform socket wakeups, etc, in their detach code.
832 sbdestroy(&so->so_snd, so);
833 sbdestroy(&so->so_rcv, so);
834 seldrain(&so->so_snd.sb_sel);
835 seldrain(&so->so_rcv.sb_sel);
836 knlist_destroy(&so->so_rcv.sb_sel.si_note);
837 knlist_destroy(&so->so_snd.sb_sel.si_note);
842 * Close a socket on last file table reference removal. Initiate disconnect
843 * if connected. Free socket when disconnect complete.
845 * This function will sorele() the socket. Note that soclose() may be called
846 * prior to the ref count reaching zero. The actual socket structure will
847 * not be freed until the ref count reaches zero.
850 soclose(struct socket *so)
854 KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
856 CURVNET_SET(so->so_vnet);
857 funsetown(&so->so_sigio);
858 if (so->so_state & SS_ISCONNECTED) {
859 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
860 error = sodisconnect(so);
862 if (error == ENOTCONN)
867 if (so->so_options & SO_LINGER) {
868 if ((so->so_state & SS_ISDISCONNECTING) &&
869 (so->so_state & SS_NBIO))
871 while (so->so_state & SS_ISCONNECTED) {
872 error = tsleep(&so->so_timeo,
873 PSOCK | PCATCH, "soclos",
882 if (so->so_proto->pr_usrreqs->pru_close != NULL)
883 (*so->so_proto->pr_usrreqs->pru_close)(so);
885 if (so->so_options & SO_ACCEPTCONN) {
888 * Prevent new additions to the accept queues due
889 * to ACCEPT_LOCK races while we are draining them.
891 so->so_options &= ~SO_ACCEPTCONN;
892 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
893 TAILQ_REMOVE(&so->so_incomp, sp, so_list);
895 sp->so_qstate &= ~SQ_INCOMP;
901 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
902 TAILQ_REMOVE(&so->so_comp, sp, so_list);
904 sp->so_qstate &= ~SQ_COMP;
910 KASSERT((TAILQ_EMPTY(&so->so_comp)),
911 ("%s: so_comp populated", __func__));
912 KASSERT((TAILQ_EMPTY(&so->so_incomp)),
913 ("%s: so_incomp populated", __func__));
916 KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
917 so->so_state |= SS_NOFDREF;
918 sorele(so); /* NB: Returns with ACCEPT_UNLOCK(). */
924 * soabort() is used to abruptly tear down a connection, such as when a
925 * resource limit is reached (listen queue depth exceeded), or if a listen
926 * socket is closed while there are sockets waiting to be accepted.
928 * This interface is tricky, because it is called on an unreferenced socket,
929 * and must be called only by a thread that has actually removed the socket
930 * from the listen queue it was on, or races with other threads are risked.
932 * This interface will call into the protocol code, so must not be called
933 * with any socket locks held. Protocols do call it while holding their own
934 * recursible protocol mutexes, but this is something that should be subject
935 * to review in the future.
938 soabort(struct socket *so)
942 * In as much as is possible, assert that no references to this
943 * socket are held. This is not quite the same as asserting that the
944 * current thread is responsible for arranging for no references, but
945 * is as close as we can get for now.
947 KASSERT(so->so_count == 0, ("soabort: so_count"));
948 KASSERT((so->so_state & SS_PROTOREF) == 0, ("soabort: SS_PROTOREF"));
949 KASSERT(so->so_state & SS_NOFDREF, ("soabort: !SS_NOFDREF"));
950 KASSERT((so->so_state & SQ_COMP) == 0, ("soabort: SQ_COMP"));
951 KASSERT((so->so_state & SQ_INCOMP) == 0, ("soabort: SQ_INCOMP"));
954 if (so->so_proto->pr_usrreqs->pru_abort != NULL)
955 (*so->so_proto->pr_usrreqs->pru_abort)(so);
962 soaccept(struct socket *so, struct sockaddr **nam)
967 KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
968 so->so_state &= ~SS_NOFDREF;
971 CURVNET_SET(so->so_vnet);
972 error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
978 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
981 return (soconnectat(AT_FDCWD, so, nam, td));
985 soconnectat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
989 if (so->so_options & SO_ACCEPTCONN)
992 CURVNET_SET(so->so_vnet);
994 * If protocol is connection-based, can only connect once.
995 * Otherwise, if connected, try to disconnect first. This allows
996 * user to disconnect by connecting to, e.g., a null address.
998 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
999 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
1000 (error = sodisconnect(so)))) {
1004 * Prevent accumulated error from previous connection from
1008 if (fd == AT_FDCWD) {
1009 error = (*so->so_proto->pr_usrreqs->pru_connect)(so,
1012 error = (*so->so_proto->pr_usrreqs->pru_connectat)(fd,
1022 soconnect2(struct socket *so1, struct socket *so2)
1026 CURVNET_SET(so1->so_vnet);
1027 error = (*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2);
1033 sodisconnect(struct socket *so)
1037 if ((so->so_state & SS_ISCONNECTED) == 0)
1039 if (so->so_state & SS_ISDISCONNECTING)
1042 error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
1046 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? 0 : SBL_WAIT)
1049 sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1050 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1054 int clen = 0, error, dontroute;
1056 KASSERT(so->so_type == SOCK_DGRAM, ("sosend_dgram: !SOCK_DGRAM"));
1057 KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
1058 ("sosend_dgram: !PR_ATOMIC"));
1061 resid = uio->uio_resid;
1063 resid = top->m_pkthdr.len;
1065 * In theory resid should be unsigned. However, space must be
1066 * signed, as it might be less than 0 if we over-committed, and we
1067 * must use a signed comparison of space and resid. On the other
1068 * hand, a negative resid causes us to loop sending 0-length
1069 * segments to the protocol.
1077 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
1079 td->td_ru.ru_msgsnd++;
1080 if (control != NULL)
1081 clen = control->m_len;
1083 SOCKBUF_LOCK(&so->so_snd);
1084 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1085 SOCKBUF_UNLOCK(&so->so_snd);
1090 error = so->so_error;
1092 SOCKBUF_UNLOCK(&so->so_snd);
1095 if ((so->so_state & SS_ISCONNECTED) == 0) {
1097 * `sendto' and `sendmsg' is allowed on a connection-based
1098 * socket if it supports implied connect. Return ENOTCONN if
1099 * not connected and no address is supplied.
1101 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1102 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1103 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1104 !(resid == 0 && clen != 0)) {
1105 SOCKBUF_UNLOCK(&so->so_snd);
1109 } else if (addr == NULL) {
1110 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1113 error = EDESTADDRREQ;
1114 SOCKBUF_UNLOCK(&so->so_snd);
1120 * Do we need MSG_OOB support in SOCK_DGRAM? Signs here may be a
1121 * problem and need fixing.
1123 space = sbspace(&so->so_snd);
1124 if (flags & MSG_OOB)
1127 SOCKBUF_UNLOCK(&so->so_snd);
1128 if (resid > space) {
1134 if (flags & MSG_EOR)
1135 top->m_flags |= M_EOR;
1138 * Copy the data from userland into a mbuf chain.
1139 * If no data is to be copied in, a single empty mbuf
1142 top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
1143 (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
1145 error = EFAULT; /* only possible error */
1148 space -= resid - uio->uio_resid;
1149 resid = uio->uio_resid;
1151 KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
1153 * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
1158 so->so_options |= SO_DONTROUTE;
1162 * XXX all the SBS_CANTSENDMORE checks previously done could be out
1163 * of date. We could have recieved a reset packet in an interrupt or
1164 * maybe we slept while doing page faults in uiomove() etc. We could
1165 * probably recheck again inside the locking protection here, but
1166 * there are probably other places that this also happens. We must
1170 error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1171 (flags & MSG_OOB) ? PRUS_OOB :
1173 * If the user set MSG_EOF, the protocol understands this flag and
1174 * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
1176 ((flags & MSG_EOF) &&
1177 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1180 /* If there is more to send set PRUS_MORETOCOME */
1181 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1182 top, addr, control, td);
1185 so->so_options &= ~SO_DONTROUTE;
1194 if (control != NULL)
1200 * Send on a socket. If send must go all at once and message is larger than
1201 * send buffering, then hard error. Lock against other senders. If must go
1202 * all at once and not enough room now, then inform user that this would
1203 * block and do nothing. Otherwise, if nonblocking, send as much as
1204 * possible. The data to be sent is described by "uio" if nonzero, otherwise
1205 * by the mbuf chain "top" (which must be null if uio is not). Data provided
1206 * in mbuf chain must be small enough to send all at once.
1208 * Returns nonzero on error, timeout or signal; callers must check for short
1209 * counts if EINTR/ERESTART are returned. Data and control buffers are freed
1213 sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
1214 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1218 int clen = 0, error, dontroute;
1219 int atomic = sosendallatonce(so) || top;
1222 resid = uio->uio_resid;
1224 resid = top->m_pkthdr.len;
1226 * In theory resid should be unsigned. However, space must be
1227 * signed, as it might be less than 0 if we over-committed, and we
1228 * must use a signed comparison of space and resid. On the other
1229 * hand, a negative resid causes us to loop sending 0-length
1230 * segments to the protocol.
1232 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
1233 * type sockets since that's an error.
1235 if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
1241 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
1242 (so->so_proto->pr_flags & PR_ATOMIC);
1244 td->td_ru.ru_msgsnd++;
1245 if (control != NULL)
1246 clen = control->m_len;
1248 error = sblock(&so->so_snd, SBLOCKWAIT(flags));
1254 SOCKBUF_LOCK(&so->so_snd);
1255 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1256 SOCKBUF_UNLOCK(&so->so_snd);
1261 error = so->so_error;
1263 SOCKBUF_UNLOCK(&so->so_snd);
1266 if ((so->so_state & SS_ISCONNECTED) == 0) {
1268 * `sendto' and `sendmsg' is allowed on a connection-
1269 * based socket if it supports implied connect.
1270 * Return ENOTCONN if not connected and no address is
1273 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1274 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1275 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1276 !(resid == 0 && clen != 0)) {
1277 SOCKBUF_UNLOCK(&so->so_snd);
1281 } else if (addr == NULL) {
1282 SOCKBUF_UNLOCK(&so->so_snd);
1283 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1286 error = EDESTADDRREQ;
1290 space = sbspace(&so->so_snd);
1291 if (flags & MSG_OOB)
1293 if ((atomic && resid > so->so_snd.sb_hiwat) ||
1294 clen > so->so_snd.sb_hiwat) {
1295 SOCKBUF_UNLOCK(&so->so_snd);
1299 if (space < resid + clen &&
1300 (atomic || space < so->so_snd.sb_lowat || space < clen)) {
1301 if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO)) {
1302 SOCKBUF_UNLOCK(&so->so_snd);
1303 error = EWOULDBLOCK;
1306 error = sbwait(&so->so_snd);
1307 SOCKBUF_UNLOCK(&so->so_snd);
1312 SOCKBUF_UNLOCK(&so->so_snd);
1317 if (flags & MSG_EOR)
1318 top->m_flags |= M_EOR;
1321 * Copy the data from userland into a mbuf
1322 * chain. If resid is 0, which can happen
1323 * only if we have control to send, then
1324 * a single empty mbuf is returned. This
1325 * is a workaround to prevent protocol send
1328 top = m_uiotombuf(uio, M_WAITOK, space,
1329 (atomic ? max_hdr : 0),
1330 (atomic ? M_PKTHDR : 0) |
1331 ((flags & MSG_EOR) ? M_EOR : 0));
1333 error = EFAULT; /* only possible error */
1336 space -= resid - uio->uio_resid;
1337 resid = uio->uio_resid;
1341 so->so_options |= SO_DONTROUTE;
1345 * XXX all the SBS_CANTSENDMORE checks previously
1346 * done could be out of date. We could have recieved
1347 * a reset packet in an interrupt or maybe we slept
1348 * while doing page faults in uiomove() etc. We
1349 * could probably recheck again inside the locking
1350 * protection here, but there are probably other
1351 * places that this also happens. We must rethink
1355 error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1356 (flags & MSG_OOB) ? PRUS_OOB :
1358 * If the user set MSG_EOF, the protocol understands
1359 * this flag and nothing left to send then use
1360 * PRU_SEND_EOF instead of PRU_SEND.
1362 ((flags & MSG_EOF) &&
1363 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1366 /* If there is more to send set PRUS_MORETOCOME. */
1367 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1368 top, addr, control, td);
1371 so->so_options &= ~SO_DONTROUTE;
1379 } while (resid && space > 0);
1383 sbunlock(&so->so_snd);
1387 if (control != NULL)
1393 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
1394 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1398 CURVNET_SET(so->so_vnet);
1399 error = so->so_proto->pr_usrreqs->pru_sosend(so, addr, uio, top,
1400 control, flags, td);
1406 * The part of soreceive() that implements reading non-inline out-of-band
1407 * data from a socket. For more complete comments, see soreceive(), from
1408 * which this code originated.
1410 * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
1411 * unable to return an mbuf chain to the caller.
1414 soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
1416 struct protosw *pr = so->so_proto;
1420 KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
1423 m = m_get(M_WAITOK, MT_DATA);
1424 error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
1428 error = uiomove(mtod(m, void *),
1429 (int) min(uio->uio_resid, m->m_len), uio);
1431 } while (uio->uio_resid && error == 0 && m);
1439 * Following replacement or removal of the first mbuf on the first mbuf chain
1440 * of a socket buffer, push necessary state changes back into the socket
1441 * buffer so that other consumers see the values consistently. 'nextrecord'
1442 * is the callers locally stored value of the original value of
1443 * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
1444 * NOTE: 'nextrecord' may be NULL.
1446 static __inline void
1447 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
1450 SOCKBUF_LOCK_ASSERT(sb);
1452 * First, update for the new value of nextrecord. If necessary, make
1453 * it the first record.
1455 if (sb->sb_mb != NULL)
1456 sb->sb_mb->m_nextpkt = nextrecord;
1458 sb->sb_mb = nextrecord;
1461 * Now update any dependent socket buffer fields to reflect the new
1462 * state. This is an expanded inline of SB_EMPTY_FIXUP(), with the
1463 * addition of a second clause that takes care of the case where
1464 * sb_mb has been updated, but remains the last record.
1466 if (sb->sb_mb == NULL) {
1467 sb->sb_mbtail = NULL;
1468 sb->sb_lastrecord = NULL;
1469 } else if (sb->sb_mb->m_nextpkt == NULL)
1470 sb->sb_lastrecord = sb->sb_mb;
1474 * Implement receive operations on a socket. We depend on the way that
1475 * records are added to the sockbuf by sbappend. In particular, each record
1476 * (mbufs linked through m_next) must begin with an address if the protocol
1477 * so specifies, followed by an optional mbuf or mbufs containing ancillary
1478 * data, and then zero or more mbufs of data. In order to allow parallelism
1479 * between network receive and copying to user space, as well as avoid
1480 * sleeping with a mutex held, we release the socket buffer mutex during the
1481 * user space copy. Although the sockbuf is locked, new data may still be
1482 * appended, and thus we must maintain consistency of the sockbuf during that
1485 * The caller may receive the data as a single mbuf chain by supplying an
1486 * mbuf **mp0 for use in returning the chain. The uio is then used only for
1487 * the count in uio_resid.
1490 soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
1491 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1493 struct mbuf *m, **mp;
1494 int flags, error, offset;
1496 struct protosw *pr = so->so_proto;
1497 struct mbuf *nextrecord;
1499 ssize_t orig_resid = uio->uio_resid;
1504 if (controlp != NULL)
1507 flags = *flagsp &~ MSG_EOR;
1510 if (flags & MSG_OOB)
1511 return (soreceive_rcvoob(so, uio, flags));
1514 if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
1515 && uio->uio_resid) {
1517 (*pr->pr_usrreqs->pru_rcvd)(so, 0);
1520 error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
1525 SOCKBUF_LOCK(&so->so_rcv);
1526 m = so->so_rcv.sb_mb;
1528 * If we have less data than requested, block awaiting more (subject
1529 * to any timeout) if:
1530 * 1. the current count is less than the low water mark, or
1531 * 2. MSG_DONTWAIT is not set
1533 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1534 sbavail(&so->so_rcv) < uio->uio_resid) &&
1535 sbavail(&so->so_rcv) < so->so_rcv.sb_lowat &&
1536 m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
1537 KASSERT(m != NULL || !sbavail(&so->so_rcv),
1538 ("receive: m == %p sbavail == %u",
1539 m, sbavail(&so->so_rcv)));
1543 error = so->so_error;
1544 if ((flags & MSG_PEEK) == 0)
1546 SOCKBUF_UNLOCK(&so->so_rcv);
1549 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1550 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1552 SOCKBUF_UNLOCK(&so->so_rcv);
1557 for (; m != NULL; m = m->m_next)
1558 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
1559 m = so->so_rcv.sb_mb;
1562 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1563 (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1564 SOCKBUF_UNLOCK(&so->so_rcv);
1568 if (uio->uio_resid == 0) {
1569 SOCKBUF_UNLOCK(&so->so_rcv);
1572 if ((so->so_state & SS_NBIO) ||
1573 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1574 SOCKBUF_UNLOCK(&so->so_rcv);
1575 error = EWOULDBLOCK;
1578 SBLASTRECORDCHK(&so->so_rcv);
1579 SBLASTMBUFCHK(&so->so_rcv);
1580 error = sbwait(&so->so_rcv);
1581 SOCKBUF_UNLOCK(&so->so_rcv);
1588 * From this point onward, we maintain 'nextrecord' as a cache of the
1589 * pointer to the next record in the socket buffer. We must keep the
1590 * various socket buffer pointers and local stack versions of the
1591 * pointers in sync, pushing out modifications before dropping the
1592 * socket buffer mutex, and re-reading them when picking it up.
1594 * Otherwise, we will race with the network stack appending new data
1595 * or records onto the socket buffer by using inconsistent/stale
1596 * versions of the field, possibly resulting in socket buffer
1599 * By holding the high-level sblock(), we prevent simultaneous
1600 * readers from pulling off the front of the socket buffer.
1602 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1604 uio->uio_td->td_ru.ru_msgrcv++;
1605 KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
1606 SBLASTRECORDCHK(&so->so_rcv);
1607 SBLASTMBUFCHK(&so->so_rcv);
1608 nextrecord = m->m_nextpkt;
1609 if (pr->pr_flags & PR_ADDR) {
1610 KASSERT(m->m_type == MT_SONAME,
1611 ("m->m_type == %d", m->m_type));
1614 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
1616 if (flags & MSG_PEEK) {
1619 sbfree(&so->so_rcv, m);
1620 so->so_rcv.sb_mb = m_free(m);
1621 m = so->so_rcv.sb_mb;
1622 sockbuf_pushsync(&so->so_rcv, nextrecord);
1627 * Process one or more MT_CONTROL mbufs present before any data mbufs
1628 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
1629 * just copy the data; if !MSG_PEEK, we call into the protocol to
1630 * perform externalization (or freeing if controlp == NULL).
1632 if (m != NULL && m->m_type == MT_CONTROL) {
1633 struct mbuf *cm = NULL, *cmn;
1634 struct mbuf **cme = &cm;
1637 if (flags & MSG_PEEK) {
1638 if (controlp != NULL) {
1639 *controlp = m_copy(m, 0, m->m_len);
1640 controlp = &(*controlp)->m_next;
1644 sbfree(&so->so_rcv, m);
1645 so->so_rcv.sb_mb = m->m_next;
1648 cme = &(*cme)->m_next;
1649 m = so->so_rcv.sb_mb;
1651 } while (m != NULL && m->m_type == MT_CONTROL);
1652 if ((flags & MSG_PEEK) == 0)
1653 sockbuf_pushsync(&so->so_rcv, nextrecord);
1654 while (cm != NULL) {
1657 if (pr->pr_domain->dom_externalize != NULL) {
1658 SOCKBUF_UNLOCK(&so->so_rcv);
1660 error = (*pr->pr_domain->dom_externalize)
1661 (cm, controlp, flags);
1662 SOCKBUF_LOCK(&so->so_rcv);
1663 } else if (controlp != NULL)
1667 if (controlp != NULL) {
1669 while (*controlp != NULL)
1670 controlp = &(*controlp)->m_next;
1675 nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1677 nextrecord = so->so_rcv.sb_mb;
1681 if ((flags & MSG_PEEK) == 0) {
1682 KASSERT(m->m_nextpkt == nextrecord,
1683 ("soreceive: post-control, nextrecord !sync"));
1684 if (nextrecord == NULL) {
1685 KASSERT(so->so_rcv.sb_mb == m,
1686 ("soreceive: post-control, sb_mb!=m"));
1687 KASSERT(so->so_rcv.sb_lastrecord == m,
1688 ("soreceive: post-control, lastrecord!=m"));
1692 if (type == MT_OOBDATA)
1695 if ((flags & MSG_PEEK) == 0) {
1696 KASSERT(so->so_rcv.sb_mb == nextrecord,
1697 ("soreceive: sb_mb != nextrecord"));
1698 if (so->so_rcv.sb_mb == NULL) {
1699 KASSERT(so->so_rcv.sb_lastrecord == NULL,
1700 ("soreceive: sb_lastercord != NULL"));
1704 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1705 SBLASTRECORDCHK(&so->so_rcv);
1706 SBLASTMBUFCHK(&so->so_rcv);
1709 * Now continue to read any data mbufs off of the head of the socket
1710 * buffer until the read request is satisfied. Note that 'type' is
1711 * used to store the type of any mbuf reads that have happened so far
1712 * such that soreceive() can stop reading if the type changes, which
1713 * causes soreceive() to return only one of regular data and inline
1714 * out-of-band data in a single socket receive operation.
1718 while (m != NULL && !(m->m_flags & M_NOTAVAIL) && uio->uio_resid > 0
1721 * If the type of mbuf has changed since the last mbuf
1722 * examined ('type'), end the receive operation.
1724 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1725 if (m->m_type == MT_OOBDATA || m->m_type == MT_CONTROL) {
1726 if (type != m->m_type)
1728 } else if (type == MT_OOBDATA)
1731 KASSERT(m->m_type == MT_DATA,
1732 ("m->m_type == %d", m->m_type));
1733 so->so_rcv.sb_state &= ~SBS_RCVATMARK;
1734 len = uio->uio_resid;
1735 if (so->so_oobmark && len > so->so_oobmark - offset)
1736 len = so->so_oobmark - offset;
1737 if (len > m->m_len - moff)
1738 len = m->m_len - moff;
1740 * If mp is set, just pass back the mbufs. Otherwise copy
1741 * them out via the uio, then free. Sockbuf must be
1742 * consistent here (points to current mbuf, it points to next
1743 * record) when we drop priority; we must note any additions
1744 * to the sockbuf when we block interrupts again.
1747 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1748 SBLASTRECORDCHK(&so->so_rcv);
1749 SBLASTMBUFCHK(&so->so_rcv);
1750 SOCKBUF_UNLOCK(&so->so_rcv);
1751 error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1752 SOCKBUF_LOCK(&so->so_rcv);
1755 * The MT_SONAME mbuf has already been removed
1756 * from the record, so it is necessary to
1757 * remove the data mbufs, if any, to preserve
1758 * the invariant in the case of PR_ADDR that
1759 * requires MT_SONAME mbufs at the head of
1762 if (m && pr->pr_flags & PR_ATOMIC &&
1763 ((flags & MSG_PEEK) == 0))
1764 (void)sbdroprecord_locked(&so->so_rcv);
1765 SOCKBUF_UNLOCK(&so->so_rcv);
1769 uio->uio_resid -= len;
1770 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1771 if (len == m->m_len - moff) {
1772 if (m->m_flags & M_EOR)
1774 if (flags & MSG_PEEK) {
1778 nextrecord = m->m_nextpkt;
1779 sbfree(&so->so_rcv, m);
1781 m->m_nextpkt = NULL;
1784 so->so_rcv.sb_mb = m = m->m_next;
1787 so->so_rcv.sb_mb = m_free(m);
1788 m = so->so_rcv.sb_mb;
1790 sockbuf_pushsync(&so->so_rcv, nextrecord);
1791 SBLASTRECORDCHK(&so->so_rcv);
1792 SBLASTMBUFCHK(&so->so_rcv);
1795 if (flags & MSG_PEEK)
1799 if (flags & MSG_DONTWAIT) {
1800 *mp = m_copym(m, 0, len,
1804 * m_copym() couldn't
1806 * Adjust uio_resid back
1808 * down by len bytes,
1809 * which we didn't end
1810 * up "copying" over).
1812 uio->uio_resid += len;
1816 SOCKBUF_UNLOCK(&so->so_rcv);
1817 *mp = m_copym(m, 0, len,
1819 SOCKBUF_LOCK(&so->so_rcv);
1822 sbcut_locked(&so->so_rcv, len);
1825 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1826 if (so->so_oobmark) {
1827 if ((flags & MSG_PEEK) == 0) {
1828 so->so_oobmark -= len;
1829 if (so->so_oobmark == 0) {
1830 so->so_rcv.sb_state |= SBS_RCVATMARK;
1835 if (offset == so->so_oobmark)
1839 if (flags & MSG_EOR)
1842 * If the MSG_WAITALL flag is set (for non-atomic socket), we
1843 * must not quit until "uio->uio_resid == 0" or an error
1844 * termination. If a signal/timeout occurs, return with a
1845 * short count but without error. Keep sockbuf locked
1846 * against other readers.
1848 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1849 !sosendallatonce(so) && nextrecord == NULL) {
1850 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1852 so->so_rcv.sb_state & SBS_CANTRCVMORE)
1855 * Notify the protocol that some data has been
1856 * drained before blocking.
1858 if (pr->pr_flags & PR_WANTRCVD) {
1859 SOCKBUF_UNLOCK(&so->so_rcv);
1861 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1862 SOCKBUF_LOCK(&so->so_rcv);
1864 SBLASTRECORDCHK(&so->so_rcv);
1865 SBLASTMBUFCHK(&so->so_rcv);
1867 * We could receive some data while was notifying
1868 * the protocol. Skip blocking in this case.
1870 if (so->so_rcv.sb_mb == NULL) {
1871 error = sbwait(&so->so_rcv);
1873 SOCKBUF_UNLOCK(&so->so_rcv);
1877 m = so->so_rcv.sb_mb;
1879 nextrecord = m->m_nextpkt;
1883 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1884 if (m != NULL && pr->pr_flags & PR_ATOMIC) {
1886 if ((flags & MSG_PEEK) == 0)
1887 (void) sbdroprecord_locked(&so->so_rcv);
1889 if ((flags & MSG_PEEK) == 0) {
1892 * First part is an inline SB_EMPTY_FIXUP(). Second
1893 * part makes sure sb_lastrecord is up-to-date if
1894 * there is still data in the socket buffer.
1896 so->so_rcv.sb_mb = nextrecord;
1897 if (so->so_rcv.sb_mb == NULL) {
1898 so->so_rcv.sb_mbtail = NULL;
1899 so->so_rcv.sb_lastrecord = NULL;
1900 } else if (nextrecord->m_nextpkt == NULL)
1901 so->so_rcv.sb_lastrecord = nextrecord;
1903 SBLASTRECORDCHK(&so->so_rcv);
1904 SBLASTMBUFCHK(&so->so_rcv);
1906 * If soreceive() is being done from the socket callback,
1907 * then don't need to generate ACK to peer to update window,
1908 * since ACK will be generated on return to TCP.
1910 if (!(flags & MSG_SOCALLBCK) &&
1911 (pr->pr_flags & PR_WANTRCVD)) {
1912 SOCKBUF_UNLOCK(&so->so_rcv);
1914 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1915 SOCKBUF_LOCK(&so->so_rcv);
1918 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1919 if (orig_resid == uio->uio_resid && orig_resid &&
1920 (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
1921 SOCKBUF_UNLOCK(&so->so_rcv);
1924 SOCKBUF_UNLOCK(&so->so_rcv);
1929 sbunlock(&so->so_rcv);
1934 * Optimized version of soreceive() for stream (TCP) sockets.
1935 * XXXAO: (MSG_WAITALL | MSG_PEEK) isn't properly handled.
1938 soreceive_stream(struct socket *so, struct sockaddr **psa, struct uio *uio,
1939 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1941 int len = 0, error = 0, flags, oresid;
1943 struct mbuf *m, *n = NULL;
1945 /* We only do stream sockets. */
1946 if (so->so_type != SOCK_STREAM)
1950 if (controlp != NULL)
1953 flags = *flagsp &~ MSG_EOR;
1956 if (flags & MSG_OOB)
1957 return (soreceive_rcvoob(so, uio, flags));
1963 /* Prevent other readers from entering the socket. */
1964 error = sblock(sb, SBLOCKWAIT(flags));
1969 /* Easy one, no space to copyout anything. */
1970 if (uio->uio_resid == 0) {
1974 oresid = uio->uio_resid;
1976 /* We will never ever get anything unless we are or were connected. */
1977 if (!(so->so_state & (SS_ISCONNECTED|SS_ISDISCONNECTED))) {
1983 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1985 /* Abort if socket has reported problems. */
1987 if (sbavail(sb) > 0)
1989 if (oresid > uio->uio_resid)
1991 error = so->so_error;
1992 if (!(flags & MSG_PEEK))
1997 /* Door is closed. Deliver what is left, if any. */
1998 if (sb->sb_state & SBS_CANTRCVMORE) {
1999 if (sbavail(sb) > 0)
2005 /* Socket buffer is empty and we shall not block. */
2006 if (sbavail(sb) == 0 &&
2007 ((so->so_state & SS_NBIO) || (flags & (MSG_DONTWAIT|MSG_NBIO)))) {
2012 /* Socket buffer got some data that we shall deliver now. */
2013 if (sbavail(sb) > 0 && !(flags & MSG_WAITALL) &&
2014 ((so->so_state & SS_NBIO) ||
2015 (flags & (MSG_DONTWAIT|MSG_NBIO)) ||
2016 sbavail(sb) >= sb->sb_lowat ||
2017 sbavail(sb) >= uio->uio_resid ||
2018 sbavail(sb) >= sb->sb_hiwat) ) {
2022 /* On MSG_WAITALL we must wait until all data or error arrives. */
2023 if ((flags & MSG_WAITALL) &&
2024 (sbavail(sb) >= uio->uio_resid || sbavail(sb) >= sb->sb_hiwat))
2028 * Wait and block until (more) data comes in.
2029 * NB: Drops the sockbuf lock during wait.
2037 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2038 KASSERT(sbavail(sb) > 0, ("%s: sockbuf empty", __func__));
2039 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb == NULL", __func__));
2043 uio->uio_td->td_ru.ru_msgrcv++;
2045 /* Fill uio until full or current end of socket buffer is reached. */
2046 len = min(uio->uio_resid, sbavail(sb));
2048 /* Dequeue as many mbufs as possible. */
2049 if (!(flags & MSG_PEEK) && len >= sb->sb_mb->m_len) {
2053 m_cat(*mp0, sb->sb_mb);
2055 m != NULL && m->m_len <= len;
2057 KASSERT(!(m->m_flags & M_NOTAVAIL),
2058 ("%s: m %p not available", __func__, m));
2060 uio->uio_resid -= m->m_len;
2066 sb->sb_lastrecord = sb->sb_mb;
2067 if (sb->sb_mb == NULL)
2070 /* Copy the remainder. */
2072 KASSERT(sb->sb_mb != NULL,
2073 ("%s: len > 0 && sb->sb_mb empty", __func__));
2075 m = m_copym(sb->sb_mb, 0, len, M_NOWAIT);
2077 len = 0; /* Don't flush data from sockbuf. */
2079 uio->uio_resid -= len;
2090 /* NB: Must unlock socket buffer as uiomove may sleep. */
2092 error = m_mbuftouio(uio, sb->sb_mb, len);
2097 SBLASTRECORDCHK(sb);
2101 * Remove the delivered data from the socket buffer unless we
2102 * were only peeking.
2104 if (!(flags & MSG_PEEK)) {
2106 sbdrop_locked(sb, len);
2108 /* Notify protocol that we drained some data. */
2109 if ((so->so_proto->pr_flags & PR_WANTRCVD) &&
2110 (((flags & MSG_WAITALL) && uio->uio_resid > 0) ||
2111 !(flags & MSG_SOCALLBCK))) {
2114 (*so->so_proto->pr_usrreqs->pru_rcvd)(so, flags);
2120 * For MSG_WAITALL we may have to loop again and wait for
2121 * more data to come in.
2123 if ((flags & MSG_WAITALL) && uio->uio_resid > 0)
2126 SOCKBUF_LOCK_ASSERT(sb);
2127 SBLASTRECORDCHK(sb);
2135 * Optimized version of soreceive() for simple datagram cases from userspace.
2136 * Unlike in the stream case, we're able to drop a datagram if copyout()
2137 * fails, and because we handle datagrams atomically, we don't need to use a
2138 * sleep lock to prevent I/O interlacing.
2141 soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
2142 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2144 struct mbuf *m, *m2;
2147 struct protosw *pr = so->so_proto;
2148 struct mbuf *nextrecord;
2152 if (controlp != NULL)
2155 flags = *flagsp &~ MSG_EOR;
2160 * For any complicated cases, fall back to the full
2161 * soreceive_generic().
2163 if (mp0 != NULL || (flags & MSG_PEEK) || (flags & MSG_OOB))
2164 return (soreceive_generic(so, psa, uio, mp0, controlp,
2168 * Enforce restrictions on use.
2170 KASSERT((pr->pr_flags & PR_WANTRCVD) == 0,
2171 ("soreceive_dgram: wantrcvd"));
2172 KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic"));
2173 KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0,
2174 ("soreceive_dgram: SBS_RCVATMARK"));
2175 KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0,
2176 ("soreceive_dgram: P_CONNREQUIRED"));
2179 * Loop blocking while waiting for a datagram.
2181 SOCKBUF_LOCK(&so->so_rcv);
2182 while ((m = so->so_rcv.sb_mb) == NULL) {
2183 KASSERT(sbavail(&so->so_rcv) == 0,
2184 ("soreceive_dgram: sb_mb NULL but sbavail %u",
2185 sbavail(&so->so_rcv)));
2187 error = so->so_error;
2189 SOCKBUF_UNLOCK(&so->so_rcv);
2192 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
2193 uio->uio_resid == 0) {
2194 SOCKBUF_UNLOCK(&so->so_rcv);
2197 if ((so->so_state & SS_NBIO) ||
2198 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
2199 SOCKBUF_UNLOCK(&so->so_rcv);
2200 return (EWOULDBLOCK);
2202 SBLASTRECORDCHK(&so->so_rcv);
2203 SBLASTMBUFCHK(&so->so_rcv);
2204 error = sbwait(&so->so_rcv);
2206 SOCKBUF_UNLOCK(&so->so_rcv);
2210 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2213 uio->uio_td->td_ru.ru_msgrcv++;
2214 SBLASTRECORDCHK(&so->so_rcv);
2215 SBLASTMBUFCHK(&so->so_rcv);
2216 nextrecord = m->m_nextpkt;
2217 if (nextrecord == NULL) {
2218 KASSERT(so->so_rcv.sb_lastrecord == m,
2219 ("soreceive_dgram: lastrecord != m"));
2222 KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord,
2223 ("soreceive_dgram: m_nextpkt != nextrecord"));
2226 * Pull 'm' and its chain off the front of the packet queue.
2228 so->so_rcv.sb_mb = NULL;
2229 sockbuf_pushsync(&so->so_rcv, nextrecord);
2232 * Walk 'm's chain and free that many bytes from the socket buffer.
2234 for (m2 = m; m2 != NULL; m2 = m2->m_next)
2235 sbfree(&so->so_rcv, m2);
2238 * Do a few last checks before we let go of the lock.
2240 SBLASTRECORDCHK(&so->so_rcv);
2241 SBLASTMBUFCHK(&so->so_rcv);
2242 SOCKBUF_UNLOCK(&so->so_rcv);
2244 if (pr->pr_flags & PR_ADDR) {
2245 KASSERT(m->m_type == MT_SONAME,
2246 ("m->m_type == %d", m->m_type));
2248 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
2253 /* XXXRW: Can this happen? */
2258 * Packet to copyout() is now in 'm' and it is disconnected from the
2261 * Process one or more MT_CONTROL mbufs present before any data mbufs
2262 * in the first mbuf chain on the socket buffer. We call into the
2263 * protocol to perform externalization (or freeing if controlp ==
2264 * NULL). In some cases there can be only MT_CONTROL mbufs without
2267 if (m->m_type == MT_CONTROL) {
2268 struct mbuf *cm = NULL, *cmn;
2269 struct mbuf **cme = &cm;
2275 cme = &(*cme)->m_next;
2277 } while (m != NULL && m->m_type == MT_CONTROL);
2278 while (cm != NULL) {
2281 if (pr->pr_domain->dom_externalize != NULL) {
2282 error = (*pr->pr_domain->dom_externalize)
2283 (cm, controlp, flags);
2284 } else if (controlp != NULL)
2288 if (controlp != NULL) {
2289 while (*controlp != NULL)
2290 controlp = &(*controlp)->m_next;
2295 KASSERT(m == NULL || m->m_type == MT_DATA,
2296 ("soreceive_dgram: !data"));
2297 while (m != NULL && uio->uio_resid > 0) {
2298 len = uio->uio_resid;
2301 error = uiomove(mtod(m, char *), (int)len, uio);
2306 if (len == m->m_len)
2323 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
2324 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2328 CURVNET_SET(so->so_vnet);
2329 error = (so->so_proto->pr_usrreqs->pru_soreceive(so, psa, uio, mp0,
2336 soshutdown(struct socket *so, int how)
2338 struct protosw *pr = so->so_proto;
2341 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
2344 (SS_ISCONNECTED | SS_ISCONNECTING | SS_ISDISCONNECTING)) == 0)
2347 CURVNET_SET(so->so_vnet);
2348 if (pr->pr_usrreqs->pru_flush != NULL)
2349 (*pr->pr_usrreqs->pru_flush)(so, how);
2352 if (how != SHUT_RD) {
2353 error = (*pr->pr_usrreqs->pru_shutdown)(so);
2354 wakeup(&so->so_timeo);
2358 wakeup(&so->so_timeo);
2364 sorflush(struct socket *so)
2366 struct sockbuf *sb = &so->so_rcv;
2367 struct protosw *pr = so->so_proto;
2373 * In order to avoid calling dom_dispose with the socket buffer mutex
2374 * held, and in order to generally avoid holding the lock for a long
2375 * time, we make a copy of the socket buffer and clear the original
2376 * (except locks, state). The new socket buffer copy won't have
2377 * initialized locks so we can only call routines that won't use or
2378 * assert those locks.
2380 * Dislodge threads currently blocked in receive and wait to acquire
2381 * a lock against other simultaneous readers before clearing the
2382 * socket buffer. Don't let our acquire be interrupted by a signal
2383 * despite any existing socket disposition on interruptable waiting.
2386 (void) sblock(sb, SBL_WAIT | SBL_NOINTR);
2389 * Invalidate/clear most of the sockbuf structure, but leave selinfo
2390 * and mutex data unchanged.
2393 bzero(&aso, sizeof(aso));
2394 aso.so_pcb = so->so_pcb;
2395 bcopy(&sb->sb_startzero, &aso.so_rcv.sb_startzero,
2396 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2397 bzero(&sb->sb_startzero,
2398 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2403 * Dispose of special rights and flush the copied socket. Don't call
2404 * any unsafe routines (that rely on locks being initialized) on aso.
2406 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
2407 (*pr->pr_domain->dom_dispose)(&aso);
2408 sbrelease_internal(&aso.so_rcv, so);
2412 * Wrapper for Socket established helper hook.
2413 * Parameters: socket, context of the hook point, hook id.
2416 hhook_run_socket(struct socket *so, void *hctx, int32_t h_id)
2418 struct socket_hhook_data hhook_data = {
2425 CURVNET_SET(so->so_vnet);
2426 HHOOKS_RUN_IF(V_socket_hhh[h_id], &hhook_data, &so->osd);
2429 /* Ugly but needed, since hhooks return void for now */
2430 return (hhook_data.status);
2434 * Perhaps this routine, and sooptcopyout(), below, ought to come in an
2435 * additional variant to handle the case where the option value needs to be
2436 * some kind of integer, but not a specific size. In addition to their use
2437 * here, these functions are also called by the protocol-level pr_ctloutput()
2441 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2446 * If the user gives us more than we wanted, we ignore it, but if we
2447 * don't get the minimum length the caller wants, we return EINVAL.
2448 * On success, sopt->sopt_valsize is set to however much we actually
2451 if ((valsize = sopt->sopt_valsize) < minlen)
2454 sopt->sopt_valsize = valsize = len;
2456 if (sopt->sopt_td != NULL)
2457 return (copyin(sopt->sopt_val, buf, valsize));
2459 bcopy(sopt->sopt_val, buf, valsize);
2464 * Kernel version of setsockopt(2).
2466 * XXX: optlen is size_t, not socklen_t
2469 so_setsockopt(struct socket *so, int level, int optname, void *optval,
2472 struct sockopt sopt;
2474 sopt.sopt_level = level;
2475 sopt.sopt_name = optname;
2476 sopt.sopt_dir = SOPT_SET;
2477 sopt.sopt_val = optval;
2478 sopt.sopt_valsize = optlen;
2479 sopt.sopt_td = NULL;
2480 return (sosetopt(so, &sopt));
2484 sosetopt(struct socket *so, struct sockopt *sopt)
2495 CURVNET_SET(so->so_vnet);
2497 if (sopt->sopt_level != SOL_SOCKET) {
2498 if (so->so_proto->pr_ctloutput != NULL) {
2499 error = (*so->so_proto->pr_ctloutput)(so, sopt);
2503 error = ENOPROTOOPT;
2505 switch (sopt->sopt_name) {
2506 case SO_ACCEPTFILTER:
2507 error = do_setopt_accept_filter(so, sopt);
2513 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
2518 so->so_linger = l.l_linger;
2520 so->so_options |= SO_LINGER;
2522 so->so_options &= ~SO_LINGER;
2529 case SO_USELOOPBACK:
2539 error = sooptcopyin(sopt, &optval, sizeof optval,
2545 so->so_options |= sopt->sopt_name;
2547 so->so_options &= ~sopt->sopt_name;
2552 error = sooptcopyin(sopt, &optval, sizeof optval,
2557 if (optval < 0 || optval >= rt_numfibs) {
2561 if (((so->so_proto->pr_domain->dom_family == PF_INET) ||
2562 (so->so_proto->pr_domain->dom_family == PF_INET6) ||
2563 (so->so_proto->pr_domain->dom_family == PF_ROUTE)))
2564 so->so_fibnum = optval;
2569 case SO_USER_COOKIE:
2570 error = sooptcopyin(sopt, &val32, sizeof val32,
2574 so->so_user_cookie = val32;
2581 error = sooptcopyin(sopt, &optval, sizeof optval,
2587 * Values < 1 make no sense for any of these options,
2595 switch (sopt->sopt_name) {
2598 if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
2599 &so->so_snd : &so->so_rcv, (u_long)optval,
2600 so, curthread) == 0) {
2604 (sopt->sopt_name == SO_SNDBUF ? &so->so_snd :
2605 &so->so_rcv)->sb_flags &= ~SB_AUTOSIZE;
2609 * Make sure the low-water is never greater than the
2613 SOCKBUF_LOCK(&so->so_snd);
2614 so->so_snd.sb_lowat =
2615 (optval > so->so_snd.sb_hiwat) ?
2616 so->so_snd.sb_hiwat : optval;
2617 SOCKBUF_UNLOCK(&so->so_snd);
2620 SOCKBUF_LOCK(&so->so_rcv);
2621 so->so_rcv.sb_lowat =
2622 (optval > so->so_rcv.sb_hiwat) ?
2623 so->so_rcv.sb_hiwat : optval;
2624 SOCKBUF_UNLOCK(&so->so_rcv);
2631 #ifdef COMPAT_FREEBSD32
2632 if (SV_CURPROC_FLAG(SV_ILP32)) {
2633 struct timeval32 tv32;
2635 error = sooptcopyin(sopt, &tv32, sizeof tv32,
2637 CP(tv32, tv, tv_sec);
2638 CP(tv32, tv, tv_usec);
2641 error = sooptcopyin(sopt, &tv, sizeof tv,
2645 if (tv.tv_sec < 0 || tv.tv_usec < 0 ||
2646 tv.tv_usec >= 1000000) {
2650 if (tv.tv_sec > INT32_MAX)
2654 switch (sopt->sopt_name) {
2656 so->so_snd.sb_timeo = val;
2659 so->so_rcv.sb_timeo = val;
2666 error = sooptcopyin(sopt, &extmac, sizeof extmac,
2670 error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
2678 if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
2679 error = hhook_run_socket(so, sopt,
2682 error = ENOPROTOOPT;
2685 if (error == 0 && so->so_proto->pr_ctloutput != NULL)
2686 (void)(*so->so_proto->pr_ctloutput)(so, sopt);
2694 * Helper routine for getsockopt.
2697 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
2705 * Documented get behavior is that we always return a value, possibly
2706 * truncated to fit in the user's buffer. Traditional behavior is
2707 * that we always tell the user precisely how much we copied, rather
2708 * than something useful like the total amount we had available for
2709 * her. Note that this interface is not idempotent; the entire
2710 * answer must generated ahead of time.
2712 valsize = min(len, sopt->sopt_valsize);
2713 sopt->sopt_valsize = valsize;
2714 if (sopt->sopt_val != NULL) {
2715 if (sopt->sopt_td != NULL)
2716 error = copyout(buf, sopt->sopt_val, valsize);
2718 bcopy(buf, sopt->sopt_val, valsize);
2724 sogetopt(struct socket *so, struct sockopt *sopt)
2733 CURVNET_SET(so->so_vnet);
2735 if (sopt->sopt_level != SOL_SOCKET) {
2736 if (so->so_proto->pr_ctloutput != NULL)
2737 error = (*so->so_proto->pr_ctloutput)(so, sopt);
2739 error = ENOPROTOOPT;
2743 switch (sopt->sopt_name) {
2744 case SO_ACCEPTFILTER:
2745 error = do_getopt_accept_filter(so, sopt);
2750 l.l_onoff = so->so_options & SO_LINGER;
2751 l.l_linger = so->so_linger;
2753 error = sooptcopyout(sopt, &l, sizeof l);
2756 case SO_USELOOPBACK:
2768 optval = so->so_options & sopt->sopt_name;
2770 error = sooptcopyout(sopt, &optval, sizeof optval);
2774 optval = so->so_type;
2778 optval = so->so_proto->pr_protocol;
2783 optval = so->so_error;
2789 optval = so->so_snd.sb_hiwat;
2793 optval = so->so_rcv.sb_hiwat;
2797 optval = so->so_snd.sb_lowat;
2801 optval = so->so_rcv.sb_lowat;
2806 tv = sbttotv(sopt->sopt_name == SO_SNDTIMEO ?
2807 so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
2808 #ifdef COMPAT_FREEBSD32
2809 if (SV_CURPROC_FLAG(SV_ILP32)) {
2810 struct timeval32 tv32;
2812 CP(tv, tv32, tv_sec);
2813 CP(tv, tv32, tv_usec);
2814 error = sooptcopyout(sopt, &tv32, sizeof tv32);
2817 error = sooptcopyout(sopt, &tv, sizeof tv);
2822 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2826 error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
2830 error = sooptcopyout(sopt, &extmac, sizeof extmac);
2838 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2842 error = mac_getsockopt_peerlabel(
2843 sopt->sopt_td->td_ucred, so, &extmac);
2846 error = sooptcopyout(sopt, &extmac, sizeof extmac);
2852 case SO_LISTENQLIMIT:
2853 optval = so->so_qlimit;
2857 optval = so->so_qlen;
2860 case SO_LISTENINCQLEN:
2861 optval = so->so_incqlen;
2865 if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
2866 error = hhook_run_socket(so, sopt,
2869 error = ENOPROTOOPT;
2881 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
2883 struct mbuf *m, *m_prev;
2884 int sopt_size = sopt->sopt_valsize;
2886 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
2889 if (sopt_size > MLEN) {
2890 MCLGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT);
2891 if ((m->m_flags & M_EXT) == 0) {
2895 m->m_len = min(MCLBYTES, sopt_size);
2897 m->m_len = min(MLEN, sopt_size);
2899 sopt_size -= m->m_len;
2904 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
2909 if (sopt_size > MLEN) {
2910 MCLGET(m, sopt->sopt_td != NULL ? M_WAITOK :
2912 if ((m->m_flags & M_EXT) == 0) {
2917 m->m_len = min(MCLBYTES, sopt_size);
2919 m->m_len = min(MLEN, sopt_size);
2921 sopt_size -= m->m_len;
2929 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
2931 struct mbuf *m0 = m;
2933 if (sopt->sopt_val == NULL)
2935 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2936 if (sopt->sopt_td != NULL) {
2939 error = copyin(sopt->sopt_val, mtod(m, char *),
2946 bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
2947 sopt->sopt_valsize -= m->m_len;
2948 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2951 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
2952 panic("ip6_sooptmcopyin");
2957 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
2959 struct mbuf *m0 = m;
2962 if (sopt->sopt_val == NULL)
2964 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2965 if (sopt->sopt_td != NULL) {
2968 error = copyout(mtod(m, char *), sopt->sopt_val,
2975 bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
2976 sopt->sopt_valsize -= m->m_len;
2977 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2978 valsize += m->m_len;
2982 /* enough soopt buffer should be given from user-land */
2986 sopt->sopt_valsize = valsize;
2991 * sohasoutofband(): protocol notifies socket layer of the arrival of new
2992 * out-of-band data, which will then notify socket consumers.
2995 sohasoutofband(struct socket *so)
2998 if (so->so_sigio != NULL)
2999 pgsigio(&so->so_sigio, SIGURG, 0);
3000 selwakeuppri(&so->so_rcv.sb_sel, PSOCK);
3004 sopoll(struct socket *so, int events, struct ucred *active_cred,
3009 * We do not need to set or assert curvnet as long as everyone uses
3012 return (so->so_proto->pr_usrreqs->pru_sopoll(so, events, active_cred,
3017 sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
3022 SOCKBUF_LOCK(&so->so_snd);
3023 SOCKBUF_LOCK(&so->so_rcv);
3024 if (events & (POLLIN | POLLRDNORM))
3025 if (soreadabledata(so))
3026 revents |= events & (POLLIN | POLLRDNORM);
3028 if (events & (POLLOUT | POLLWRNORM))
3029 if (sowriteable(so))
3030 revents |= events & (POLLOUT | POLLWRNORM);
3032 if (events & (POLLPRI | POLLRDBAND))
3033 if (so->so_oobmark || (so->so_rcv.sb_state & SBS_RCVATMARK))
3034 revents |= events & (POLLPRI | POLLRDBAND);
3036 if ((events & POLLINIGNEOF) == 0) {
3037 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3038 revents |= events & (POLLIN | POLLRDNORM);
3039 if (so->so_snd.sb_state & SBS_CANTSENDMORE)
3045 if (events & (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND)) {
3046 selrecord(td, &so->so_rcv.sb_sel);
3047 so->so_rcv.sb_flags |= SB_SEL;
3050 if (events & (POLLOUT | POLLWRNORM)) {
3051 selrecord(td, &so->so_snd.sb_sel);
3052 so->so_snd.sb_flags |= SB_SEL;
3056 SOCKBUF_UNLOCK(&so->so_rcv);
3057 SOCKBUF_UNLOCK(&so->so_snd);
3062 soo_kqfilter(struct file *fp, struct knote *kn)
3064 struct socket *so = kn->kn_fp->f_data;
3067 switch (kn->kn_filter) {
3069 if (so->so_options & SO_ACCEPTCONN)
3070 kn->kn_fop = &solisten_filtops;
3072 kn->kn_fop = &soread_filtops;
3076 kn->kn_fop = &sowrite_filtops;
3084 knlist_add(&sb->sb_sel.si_note, kn, 1);
3085 sb->sb_flags |= SB_KNOTE;
3091 * Some routines that return EOPNOTSUPP for entry points that are not
3092 * supported by a protocol. Fill in as needed.
3095 pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
3102 pru_attach_notsupp(struct socket *so, int proto, struct thread *td)
3109 pru_bind_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
3116 pru_bindat_notsupp(int fd, struct socket *so, struct sockaddr *nam,
3124 pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
3131 pru_connectat_notsupp(int fd, struct socket *so, struct sockaddr *nam,
3139 pru_connect2_notsupp(struct socket *so1, struct socket *so2)
3146 pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
3147 struct ifnet *ifp, struct thread *td)
3154 pru_disconnect_notsupp(struct socket *so)
3161 pru_listen_notsupp(struct socket *so, int backlog, struct thread *td)
3168 pru_peeraddr_notsupp(struct socket *so, struct sockaddr **nam)
3175 pru_rcvd_notsupp(struct socket *so, int flags)
3182 pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
3189 pru_send_notsupp(struct socket *so, int flags, struct mbuf *m,
3190 struct sockaddr *addr, struct mbuf *control, struct thread *td)
3197 pru_ready_notsupp(struct socket *so, struct mbuf *m, int count)
3200 return (EOPNOTSUPP);
3204 * This isn't really a ``null'' operation, but it's the default one and
3205 * doesn't do anything destructive.
3208 pru_sense_null(struct socket *so, struct stat *sb)
3211 sb->st_blksize = so->so_snd.sb_hiwat;
3216 pru_shutdown_notsupp(struct socket *so)
3223 pru_sockaddr_notsupp(struct socket *so, struct sockaddr **nam)
3230 pru_sosend_notsupp(struct socket *so, struct sockaddr *addr, struct uio *uio,
3231 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
3238 pru_soreceive_notsupp(struct socket *so, struct sockaddr **paddr,
3239 struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
3246 pru_sopoll_notsupp(struct socket *so, int events, struct ucred *cred,
3254 filt_sordetach(struct knote *kn)
3256 struct socket *so = kn->kn_fp->f_data;
3258 SOCKBUF_LOCK(&so->so_rcv);
3259 knlist_remove(&so->so_rcv.sb_sel.si_note, kn, 1);
3260 if (knlist_empty(&so->so_rcv.sb_sel.si_note))
3261 so->so_rcv.sb_flags &= ~SB_KNOTE;
3262 SOCKBUF_UNLOCK(&so->so_rcv);
3267 filt_soread(struct knote *kn, long hint)
3271 so = kn->kn_fp->f_data;
3272 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3274 kn->kn_data = sbavail(&so->so_rcv) - so->so_rcv.sb_ctl;
3275 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3276 kn->kn_flags |= EV_EOF;
3277 kn->kn_fflags = so->so_error;
3279 } else if (so->so_error) /* temporary udp error */
3282 if (kn->kn_sfflags & NOTE_LOWAT) {
3283 if (kn->kn_data >= kn->kn_sdata)
3286 if (sbavail(&so->so_rcv) >= so->so_rcv.sb_lowat)
3290 /* This hook returning non-zero indicates an event, not error */
3291 return (hhook_run_socket(so, NULL, HHOOK_FILT_SOREAD));
3295 filt_sowdetach(struct knote *kn)
3297 struct socket *so = kn->kn_fp->f_data;
3299 SOCKBUF_LOCK(&so->so_snd);
3300 knlist_remove(&so->so_snd.sb_sel.si_note, kn, 1);
3301 if (knlist_empty(&so->so_snd.sb_sel.si_note))
3302 so->so_snd.sb_flags &= ~SB_KNOTE;
3303 SOCKBUF_UNLOCK(&so->so_snd);
3308 filt_sowrite(struct knote *kn, long hint)
3312 so = kn->kn_fp->f_data;
3313 SOCKBUF_LOCK_ASSERT(&so->so_snd);
3314 kn->kn_data = sbspace(&so->so_snd);
3316 hhook_run_socket(so, kn, HHOOK_FILT_SOWRITE);
3318 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
3319 kn->kn_flags |= EV_EOF;
3320 kn->kn_fflags = so->so_error;
3322 } else if (so->so_error) /* temporary udp error */
3324 else if (((so->so_state & SS_ISCONNECTED) == 0) &&
3325 (so->so_proto->pr_flags & PR_CONNREQUIRED))
3327 else if (kn->kn_sfflags & NOTE_LOWAT)
3328 return (kn->kn_data >= kn->kn_sdata);
3330 return (kn->kn_data >= so->so_snd.sb_lowat);
3335 filt_solisten(struct knote *kn, long hint)
3337 struct socket *so = kn->kn_fp->f_data;
3339 kn->kn_data = so->so_qlen;
3340 return (!TAILQ_EMPTY(&so->so_comp));
3344 socheckuid(struct socket *so, uid_t uid)
3349 if (so->so_cred->cr_uid != uid)
3355 * These functions are used by protocols to notify the socket layer (and its
3356 * consumers) of state changes in the sockets driven by protocol-side events.
3360 * Procedures to manipulate state flags of socket and do appropriate wakeups.
3362 * Normal sequence from the active (originating) side is that
3363 * soisconnecting() is called during processing of connect() call, resulting
3364 * in an eventual call to soisconnected() if/when the connection is
3365 * established. When the connection is torn down soisdisconnecting() is
3366 * called during processing of disconnect() call, and soisdisconnected() is
3367 * called when the connection to the peer is totally severed. The semantics
3368 * of these routines are such that connectionless protocols can call
3369 * soisconnected() and soisdisconnected() only, bypassing the in-progress
3370 * calls when setting up a ``connection'' takes no time.
3372 * From the passive side, a socket is created with two queues of sockets:
3373 * so_incomp for connections in progress and so_comp for connections already
3374 * made and awaiting user acceptance. As a protocol is preparing incoming
3375 * connections, it creates a socket structure queued on so_incomp by calling
3376 * sonewconn(). When the connection is established, soisconnected() is
3377 * called, and transfers the socket structure to so_comp, making it available
3380 * If a socket is closed with sockets on either so_incomp or so_comp, these
3381 * sockets are dropped.
3383 * If higher-level protocols are implemented in the kernel, the wakeups done
3384 * here will sometimes cause software-interrupt process scheduling.
3387 soisconnecting(struct socket *so)
3391 so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
3392 so->so_state |= SS_ISCONNECTING;
3397 soisconnected(struct socket *so)
3399 struct socket *head;
3405 so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
3406 so->so_state |= SS_ISCONNECTED;
3408 if (head != NULL && (so->so_qstate & SQ_INCOMP)) {
3409 if ((so->so_options & SO_ACCEPTFILTER) == 0) {
3411 TAILQ_REMOVE(&head->so_incomp, so, so_list);
3413 so->so_qstate &= ~SQ_INCOMP;
3414 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
3416 so->so_qstate |= SQ_COMP;
3419 wakeup_one(&head->so_timeo);
3422 soupcall_set(so, SO_RCV,
3423 head->so_accf->so_accept_filter->accf_callback,
3424 head->so_accf->so_accept_filter_arg);
3425 so->so_options &= ~SO_ACCEPTFILTER;
3426 ret = head->so_accf->so_accept_filter->accf_callback(so,
3427 head->so_accf->so_accept_filter_arg, M_NOWAIT);
3428 if (ret == SU_ISCONNECTED)
3429 soupcall_clear(so, SO_RCV);
3431 if (ret == SU_ISCONNECTED)
3438 wakeup(&so->so_timeo);
3444 soisdisconnecting(struct socket *so)
3448 * Note: This code assumes that SOCK_LOCK(so) and
3449 * SOCKBUF_LOCK(&so->so_rcv) are the same.
3451 SOCKBUF_LOCK(&so->so_rcv);
3452 so->so_state &= ~SS_ISCONNECTING;
3453 so->so_state |= SS_ISDISCONNECTING;
3454 socantrcvmore_locked(so);
3455 SOCKBUF_LOCK(&so->so_snd);
3456 socantsendmore_locked(so);
3457 wakeup(&so->so_timeo);
3461 soisdisconnected(struct socket *so)
3465 * Note: This code assumes that SOCK_LOCK(so) and
3466 * SOCKBUF_LOCK(&so->so_rcv) are the same.
3468 SOCKBUF_LOCK(&so->so_rcv);
3469 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
3470 so->so_state |= SS_ISDISCONNECTED;
3471 socantrcvmore_locked(so);
3472 SOCKBUF_LOCK(&so->so_snd);
3473 sbdrop_locked(&so->so_snd, sbused(&so->so_snd));
3474 socantsendmore_locked(so);
3475 wakeup(&so->so_timeo);
3479 * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
3482 sodupsockaddr(const struct sockaddr *sa, int mflags)
3484 struct sockaddr *sa2;
3486 sa2 = malloc(sa->sa_len, M_SONAME, mflags);
3488 bcopy(sa, sa2, sa->sa_len);
3493 * Register per-socket buffer upcalls.
3496 soupcall_set(struct socket *so, int which,
3497 int (*func)(struct socket *, void *, int), void *arg)
3509 panic("soupcall_set: bad which");
3511 SOCKBUF_LOCK_ASSERT(sb);
3513 /* XXX: accf_http actually wants to do this on purpose. */
3514 KASSERT(sb->sb_upcall == NULL, ("soupcall_set: overwriting upcall"));
3516 sb->sb_upcall = func;
3517 sb->sb_upcallarg = arg;
3518 sb->sb_flags |= SB_UPCALL;
3522 soupcall_clear(struct socket *so, int which)
3534 panic("soupcall_clear: bad which");
3536 SOCKBUF_LOCK_ASSERT(sb);
3537 KASSERT(sb->sb_upcall != NULL, ("soupcall_clear: no upcall to clear"));
3538 sb->sb_upcall = NULL;
3539 sb->sb_upcallarg = NULL;
3540 sb->sb_flags &= ~SB_UPCALL;
3544 * Create an external-format (``xsocket'') structure using the information in
3545 * the kernel-format socket structure pointed to by so. This is done to
3546 * reduce the spew of irrelevant information over this interface, to isolate
3547 * user code from changes in the kernel structure, and potentially to provide
3548 * information-hiding if we decide that some of this information should be
3549 * hidden from users.
3552 sotoxsocket(struct socket *so, struct xsocket *xso)
3555 xso->xso_len = sizeof *xso;
3557 xso->so_type = so->so_type;
3558 xso->so_options = so->so_options;
3559 xso->so_linger = so->so_linger;
3560 xso->so_state = so->so_state;
3561 xso->so_pcb = so->so_pcb;
3562 xso->xso_protocol = so->so_proto->pr_protocol;
3563 xso->xso_family = so->so_proto->pr_domain->dom_family;
3564 xso->so_qlen = so->so_qlen;
3565 xso->so_incqlen = so->so_incqlen;
3566 xso->so_qlimit = so->so_qlimit;
3567 xso->so_timeo = so->so_timeo;
3568 xso->so_error = so->so_error;
3569 xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
3570 xso->so_oobmark = so->so_oobmark;
3571 sbtoxsockbuf(&so->so_snd, &xso->so_snd);
3572 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
3573 xso->so_uid = so->so_cred->cr_uid;
3578 * Socket accessor functions to provide external consumers with
3579 * a safe interface to socket state
3584 so_listeners_apply_all(struct socket *so, void (*func)(struct socket *, void *),
3588 TAILQ_FOREACH(so, &so->so_comp, so_list)
3593 so_sockbuf_rcv(struct socket *so)
3596 return (&so->so_rcv);
3600 so_sockbuf_snd(struct socket *so)
3603 return (&so->so_snd);
3607 so_state_get(const struct socket *so)
3610 return (so->so_state);
3614 so_state_set(struct socket *so, int val)
3621 so_options_get(const struct socket *so)
3624 return (so->so_options);
3628 so_options_set(struct socket *so, int val)
3631 so->so_options = val;
3635 so_error_get(const struct socket *so)
3638 return (so->so_error);
3642 so_error_set(struct socket *so, int val)
3649 so_linger_get(const struct socket *so)
3652 return (so->so_linger);
3656 so_linger_set(struct socket *so, int val)
3659 so->so_linger = val;
3663 so_protosw_get(const struct socket *so)
3666 return (so->so_proto);
3670 so_protosw_set(struct socket *so, struct protosw *val)
3677 so_sorwakeup(struct socket *so)
3684 so_sowwakeup(struct socket *so)
3691 so_sorwakeup_locked(struct socket *so)
3694 sorwakeup_locked(so);
3698 so_sowwakeup_locked(struct socket *so)
3701 sowwakeup_locked(so);
3705 so_lock(struct socket *so)
3712 so_unlock(struct socket *so)