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 int somaxconn = SOMAXCONN;
202 sysctl_somaxconn(SYSCTL_HANDLER_ARGS)
208 error = sysctl_handle_int(oidp, &val, 0, req);
209 if (error || !req->newptr )
212 if (val < 1 || val > USHRT_MAX)
218 SYSCTL_PROC(_kern_ipc, OID_AUTO, soacceptqueue, CTLTYPE_UINT | CTLFLAG_RW,
219 0, sizeof(int), sysctl_somaxconn, "I",
220 "Maximum listen socket pending connection accept queue size");
221 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn,
222 CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_SKIP,
223 0, sizeof(int), sysctl_somaxconn, "I",
224 "Maximum listen socket pending connection accept queue size (compat)");
226 static int numopensockets;
227 SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
228 &numopensockets, 0, "Number of open sockets");
231 * accept_mtx locks down per-socket fields relating to accept queues. See
232 * socketvar.h for an annotation of the protected fields of struct socket.
234 struct mtx accept_mtx;
235 MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
238 * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
241 static struct mtx so_global_mtx;
242 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
245 * General IPC sysctl name space, used by sockets and a variety of other IPC
248 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
251 * Initialize the socket subsystem and set up the socket
254 static uma_zone_t socket_zone;
258 socket_zone_change(void *tag)
261 maxsockets = uma_zone_set_max(socket_zone, maxsockets);
265 socket_hhook_register(int subtype)
268 if (hhook_head_register(HHOOK_TYPE_SOCKET, subtype,
269 &V_socket_hhh[subtype],
270 HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
271 printf("%s: WARNING: unable to register hook\n", __func__);
275 socket_hhook_deregister(int subtype)
278 if (hhook_head_deregister(V_socket_hhh[subtype]) != 0)
279 printf("%s: WARNING: unable to deregister hook\n", __func__);
283 socket_init(void *tag)
286 socket_zone = uma_zcreate("socket", sizeof(struct socket), NULL, NULL,
287 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
288 maxsockets = uma_zone_set_max(socket_zone, maxsockets);
289 uma_zone_set_warning(socket_zone, "kern.ipc.maxsockets limit reached");
290 EVENTHANDLER_REGISTER(maxsockets_change, socket_zone_change, NULL,
291 EVENTHANDLER_PRI_FIRST);
293 SYSINIT(socket, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, socket_init, NULL);
296 socket_vnet_init(const void *unused __unused)
300 /* We expect a contiguous range */
301 for (i = 0; i <= HHOOK_SOCKET_LAST; i++)
302 socket_hhook_register(i);
304 VNET_SYSINIT(socket_vnet_init, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY,
305 socket_vnet_init, NULL);
308 socket_vnet_uninit(const void *unused __unused)
312 for (i = 0; i <= HHOOK_SOCKET_LAST; i++)
313 socket_hhook_deregister(i);
315 VNET_SYSUNINIT(socket_vnet_uninit, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY,
316 socket_vnet_uninit, NULL);
319 * Initialise maxsockets. This SYSINIT must be run after
323 init_maxsockets(void *ignored)
326 TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
327 maxsockets = imax(maxsockets, maxfiles);
329 SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);
332 * Sysctl to get and set the maximum global sockets limit. Notify protocols
333 * of the change so that they can update their dependent limits as required.
336 sysctl_maxsockets(SYSCTL_HANDLER_ARGS)
338 int error, newmaxsockets;
340 newmaxsockets = maxsockets;
341 error = sysctl_handle_int(oidp, &newmaxsockets, 0, req);
342 if (error == 0 && req->newptr) {
343 if (newmaxsockets > maxsockets &&
344 newmaxsockets <= maxfiles) {
345 maxsockets = newmaxsockets;
346 EVENTHANDLER_INVOKE(maxsockets_change);
352 SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets, CTLTYPE_INT|CTLFLAG_RW,
353 &maxsockets, 0, sysctl_maxsockets, "IU",
354 "Maximum number of sockets avaliable");
357 * Socket operation routines. These routines are called by the routines in
358 * sys_socket.c or from a system process, and implement the semantics of
359 * socket operations by switching out to the protocol specific routines.
363 * Get a socket structure from our zone, and initialize it. Note that it
364 * would probably be better to allocate socket and PCB at the same time, but
365 * I'm not convinced that all the protocols can be easily modified to do
368 * soalloc() returns a socket with a ref count of 0.
370 static struct socket *
371 soalloc(struct vnet *vnet)
375 so = uma_zalloc(socket_zone, M_NOWAIT | M_ZERO);
379 if (mac_socket_init(so, M_NOWAIT) != 0) {
380 uma_zfree(socket_zone, so);
384 if (khelp_init_osd(HELPER_CLASS_SOCKET, &so->osd)) {
385 uma_zfree(socket_zone, so);
389 SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
390 SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
391 sx_init(&so->so_snd.sb_sx, "so_snd_sx");
392 sx_init(&so->so_rcv.sb_sx, "so_rcv_sx");
393 TAILQ_INIT(&so->so_aiojobq);
395 VNET_ASSERT(vnet != NULL, ("%s:%d vnet is NULL, so=%p",
396 __func__, __LINE__, so));
399 /* We shouldn't need the so_global_mtx */
400 if (hhook_run_socket(so, NULL, HHOOK_SOCKET_CREATE)) {
401 /* Do we need more comprehensive error returns? */
402 uma_zfree(socket_zone, so);
405 mtx_lock(&so_global_mtx);
406 so->so_gencnt = ++so_gencnt;
409 vnet->vnet_sockcnt++;
411 mtx_unlock(&so_global_mtx);
417 * Free the storage associated with a socket at the socket layer, tear down
418 * locks, labels, etc. All protocol state is assumed already to have been
419 * torn down (and possibly never set up) by the caller.
422 sodealloc(struct socket *so)
425 KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
426 KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
428 mtx_lock(&so_global_mtx);
429 so->so_gencnt = ++so_gencnt;
430 --numopensockets; /* Could be below, but faster here. */
432 VNET_ASSERT(so->so_vnet != NULL, ("%s:%d so_vnet is NULL, so=%p",
433 __func__, __LINE__, so));
434 so->so_vnet->vnet_sockcnt--;
436 mtx_unlock(&so_global_mtx);
437 if (so->so_rcv.sb_hiwat)
438 (void)chgsbsize(so->so_cred->cr_uidinfo,
439 &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
440 if (so->so_snd.sb_hiwat)
441 (void)chgsbsize(so->so_cred->cr_uidinfo,
442 &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
443 /* remove acccept filter if one is present. */
444 if (so->so_accf != NULL)
445 do_setopt_accept_filter(so, NULL);
447 mac_socket_destroy(so);
449 hhook_run_socket(so, NULL, HHOOK_SOCKET_CLOSE);
452 khelp_destroy_osd(&so->osd);
453 sx_destroy(&so->so_snd.sb_sx);
454 sx_destroy(&so->so_rcv.sb_sx);
455 SOCKBUF_LOCK_DESTROY(&so->so_snd);
456 SOCKBUF_LOCK_DESTROY(&so->so_rcv);
457 uma_zfree(socket_zone, so);
461 * socreate returns a socket with a ref count of 1. The socket should be
462 * closed with soclose().
465 socreate(int dom, struct socket **aso, int type, int proto,
466 struct ucred *cred, struct thread *td)
473 prp = pffindproto(dom, proto, type);
475 prp = pffindtype(dom, type);
478 /* No support for domain. */
479 if (pffinddomain(dom) == NULL)
480 return (EAFNOSUPPORT);
481 /* No support for socket type. */
482 if (proto == 0 && type != 0)
484 return (EPROTONOSUPPORT);
486 if (prp->pr_usrreqs->pru_attach == NULL ||
487 prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
488 return (EPROTONOSUPPORT);
490 if (prison_check_af(cred, prp->pr_domain->dom_family) != 0)
491 return (EPROTONOSUPPORT);
493 if (prp->pr_type != type)
495 so = soalloc(CRED_TO_VNET(cred));
499 TAILQ_INIT(&so->so_incomp);
500 TAILQ_INIT(&so->so_comp);
502 so->so_cred = crhold(cred);
503 if ((prp->pr_domain->dom_family == PF_INET) ||
504 (prp->pr_domain->dom_family == PF_INET6) ||
505 (prp->pr_domain->dom_family == PF_ROUTE))
506 so->so_fibnum = td->td_proc->p_fibnum;
511 mac_socket_create(cred, so);
513 knlist_init_mtx(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
514 knlist_init_mtx(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
517 * Auto-sizing of socket buffers is managed by the protocols and
518 * the appropriate flags must be set in the pru_attach function.
520 CURVNET_SET(so->so_vnet);
521 error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
524 KASSERT(so->so_count == 1, ("socreate: so_count %d",
535 static int regression_sonewconn_earlytest = 1;
536 SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW,
537 ®ression_sonewconn_earlytest, 0, "Perform early sonewconn limit test");
541 * When an attempt at a new connection is noted on a socket which accepts
542 * connections, sonewconn is called. If the connection is possible (subject
543 * to space constraints, etc.) then we allocate a new structure, propoerly
544 * linked into the data structure of the original socket, and return this.
545 * Connstatus may be 0, or SS_ISCONFIRMING, or SS_ISCONNECTED.
547 * Note: the ref count on the socket is 0 on return.
550 sonewconn(struct socket *head, int connstatus)
552 static struct timeval lastover;
553 static struct timeval overinterval = { 60, 0 };
554 static int overcount;
560 over = (head->so_qlen > 3 * head->so_qlimit / 2);
563 if (regression_sonewconn_earlytest && over) {
569 if (ratecheck(&lastover, &overinterval)) {
570 log(LOG_DEBUG, "%s: pcb %p: Listen queue overflow: "
571 "%i already in queue awaiting acceptance "
572 "(%d occurrences)\n",
573 __func__, head->so_pcb, head->so_qlen, overcount);
580 VNET_ASSERT(head->so_vnet != NULL, ("%s:%d so_vnet is NULL, head=%p",
581 __func__, __LINE__, head));
582 so = soalloc(head->so_vnet);
584 log(LOG_DEBUG, "%s: pcb %p: New socket allocation failure: "
585 "limit reached or out of memory\n",
586 __func__, head->so_pcb);
589 if ((head->so_options & SO_ACCEPTFILTER) != 0)
592 so->so_type = head->so_type;
593 so->so_options = head->so_options &~ SO_ACCEPTCONN;
594 so->so_linger = head->so_linger;
595 so->so_state = head->so_state | SS_NOFDREF;
596 so->so_fibnum = head->so_fibnum;
597 so->so_proto = head->so_proto;
598 so->so_cred = crhold(head->so_cred);
600 mac_socket_newconn(head, so);
602 knlist_init_mtx(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
603 knlist_init_mtx(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
604 VNET_SO_ASSERT(head);
605 if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat)) {
607 log(LOG_DEBUG, "%s: pcb %p: soreserve() failed\n",
608 __func__, head->so_pcb);
611 if ((*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
613 log(LOG_DEBUG, "%s: pcb %p: pru_attach() failed\n",
614 __func__, head->so_pcb);
617 so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
618 so->so_snd.sb_lowat = head->so_snd.sb_lowat;
619 so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
620 so->so_snd.sb_timeo = head->so_snd.sb_timeo;
621 so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
622 so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
623 so->so_state |= connstatus;
626 * The accept socket may be tearing down but we just
627 * won a race on the ACCEPT_LOCK.
628 * However, if sctp_peeloff() is called on a 1-to-many
629 * style socket, the SO_ACCEPTCONN doesn't need to be set.
631 if (!(head->so_options & SO_ACCEPTCONN) &&
632 ((head->so_proto->pr_protocol != IPPROTO_SCTP) ||
633 (head->so_type != SOCK_SEQPACKET))) {
636 sofree(so); /* NB: returns ACCEPT_UNLOCK'ed. */
640 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
641 so->so_qstate |= SQ_COMP;
645 * Keep removing sockets from the head until there's room for
646 * us to insert on the tail. In pre-locking revisions, this
647 * was a simple if(), but as we could be racing with other
648 * threads and soabort() requires dropping locks, we must
649 * loop waiting for the condition to be true.
651 while (head->so_incqlen > head->so_qlimit) {
653 sp = TAILQ_FIRST(&head->so_incomp);
654 TAILQ_REMOVE(&head->so_incomp, sp, so_list);
656 sp->so_qstate &= ~SQ_INCOMP;
662 TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
663 so->so_qstate |= SQ_INCOMP;
669 wakeup_one(&head->so_timeo);
675 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
679 CURVNET_SET(so->so_vnet);
680 error = (*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td);
686 sobindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
690 CURVNET_SET(so->so_vnet);
691 error = (*so->so_proto->pr_usrreqs->pru_bindat)(fd, so, nam, td);
697 * solisten() transitions a socket from a non-listening state to a listening
698 * state, but can also be used to update the listen queue depth on an
699 * existing listen socket. The protocol will call back into the sockets
700 * layer using solisten_proto_check() and solisten_proto() to check and set
701 * socket-layer listen state. Call backs are used so that the protocol can
702 * acquire both protocol and socket layer locks in whatever order is required
705 * Protocol implementors are advised to hold the socket lock across the
706 * socket-layer test and set to avoid races at the socket layer.
709 solisten(struct socket *so, int backlog, struct thread *td)
713 CURVNET_SET(so->so_vnet);
714 error = (*so->so_proto->pr_usrreqs->pru_listen)(so, backlog, td);
720 solisten_proto_check(struct socket *so)
723 SOCK_LOCK_ASSERT(so);
725 if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
732 solisten_proto(struct socket *so, int backlog)
735 SOCK_LOCK_ASSERT(so);
737 if (backlog < 0 || backlog > somaxconn)
739 so->so_qlimit = backlog;
740 so->so_options |= SO_ACCEPTCONN;
744 * Evaluate the reference count and named references on a socket; if no
745 * references remain, free it. This should be called whenever a reference is
746 * released, such as in sorele(), but also when named reference flags are
747 * cleared in socket or protocol code.
749 * sofree() will free the socket if:
751 * - There are no outstanding file descriptor references or related consumers
754 * - The socket has been closed by user space, if ever open (SS_NOFDREF).
756 * - The protocol does not have an outstanding strong reference on the socket
759 * - The socket is not in a completed connection queue, so a process has been
760 * notified that it is present. If it is removed, the user process may
761 * block in accept() despite select() saying the socket was ready.
764 sofree(struct socket *so)
766 struct protosw *pr = so->so_proto;
769 ACCEPT_LOCK_ASSERT();
770 SOCK_LOCK_ASSERT(so);
772 if ((so->so_state & SS_NOFDREF) == 0 || so->so_count != 0 ||
773 (so->so_state & SS_PROTOREF) || (so->so_qstate & SQ_COMP)) {
781 KASSERT((so->so_qstate & SQ_COMP) != 0 ||
782 (so->so_qstate & SQ_INCOMP) != 0,
783 ("sofree: so_head != NULL, but neither SQ_COMP nor "
785 KASSERT((so->so_qstate & SQ_COMP) == 0 ||
786 (so->so_qstate & SQ_INCOMP) == 0,
787 ("sofree: so->so_qstate is SQ_COMP and also SQ_INCOMP"));
788 TAILQ_REMOVE(&head->so_incomp, so, so_list);
790 so->so_qstate &= ~SQ_INCOMP;
793 KASSERT((so->so_qstate & SQ_COMP) == 0 &&
794 (so->so_qstate & SQ_INCOMP) == 0,
795 ("sofree: so_head == NULL, but still SQ_COMP(%d) or SQ_INCOMP(%d)",
796 so->so_qstate & SQ_COMP, so->so_qstate & SQ_INCOMP));
797 if (so->so_options & SO_ACCEPTCONN) {
798 KASSERT((TAILQ_EMPTY(&so->so_comp)),
799 ("sofree: so_comp populated"));
800 KASSERT((TAILQ_EMPTY(&so->so_incomp)),
801 ("sofree: so_incomp populated"));
807 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
808 (*pr->pr_domain->dom_dispose)(so->so_rcv.sb_mb);
809 if (pr->pr_usrreqs->pru_detach != NULL)
810 (*pr->pr_usrreqs->pru_detach)(so);
813 * From this point on, we assume that no other references to this
814 * socket exist anywhere else in the stack. Therefore, no locks need
815 * to be acquired or held.
817 * We used to do a lot of socket buffer and socket locking here, as
818 * well as invoke sorflush() and perform wakeups. The direct call to
819 * dom_dispose() and sbrelease_internal() are an inlining of what was
820 * necessary from sorflush().
822 * Notice that the socket buffer and kqueue state are torn down
823 * before calling pru_detach. This means that protocols shold not
824 * assume they can perform socket wakeups, etc, in their detach code.
826 sbdestroy(&so->so_snd, so);
827 sbdestroy(&so->so_rcv, so);
828 seldrain(&so->so_snd.sb_sel);
829 seldrain(&so->so_rcv.sb_sel);
830 knlist_destroy(&so->so_rcv.sb_sel.si_note);
831 knlist_destroy(&so->so_snd.sb_sel.si_note);
836 * Close a socket on last file table reference removal. Initiate disconnect
837 * if connected. Free socket when disconnect complete.
839 * This function will sorele() the socket. Note that soclose() may be called
840 * prior to the ref count reaching zero. The actual socket structure will
841 * not be freed until the ref count reaches zero.
844 soclose(struct socket *so)
848 KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
850 CURVNET_SET(so->so_vnet);
851 funsetown(&so->so_sigio);
852 if (so->so_state & SS_ISCONNECTED) {
853 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
854 error = sodisconnect(so);
856 if (error == ENOTCONN)
861 if (so->so_options & SO_LINGER) {
862 if ((so->so_state & SS_ISDISCONNECTING) &&
863 (so->so_state & SS_NBIO))
865 while (so->so_state & SS_ISCONNECTED) {
866 error = tsleep(&so->so_timeo,
867 PSOCK | PCATCH, "soclos",
876 if (so->so_proto->pr_usrreqs->pru_close != NULL)
877 (*so->so_proto->pr_usrreqs->pru_close)(so);
879 if (so->so_options & SO_ACCEPTCONN) {
882 * Prevent new additions to the accept queues due
883 * to ACCEPT_LOCK races while we are draining them.
885 so->so_options &= ~SO_ACCEPTCONN;
886 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
887 TAILQ_REMOVE(&so->so_incomp, sp, so_list);
889 sp->so_qstate &= ~SQ_INCOMP;
895 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
896 TAILQ_REMOVE(&so->so_comp, sp, so_list);
898 sp->so_qstate &= ~SQ_COMP;
904 KASSERT((TAILQ_EMPTY(&so->so_comp)),
905 ("%s: so_comp populated", __func__));
906 KASSERT((TAILQ_EMPTY(&so->so_incomp)),
907 ("%s: so_incomp populated", __func__));
910 KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
911 so->so_state |= SS_NOFDREF;
912 sorele(so); /* NB: Returns with ACCEPT_UNLOCK(). */
918 * soabort() is used to abruptly tear down a connection, such as when a
919 * resource limit is reached (listen queue depth exceeded), or if a listen
920 * socket is closed while there are sockets waiting to be accepted.
922 * This interface is tricky, because it is called on an unreferenced socket,
923 * and must be called only by a thread that has actually removed the socket
924 * from the listen queue it was on, or races with other threads are risked.
926 * This interface will call into the protocol code, so must not be called
927 * with any socket locks held. Protocols do call it while holding their own
928 * recursible protocol mutexes, but this is something that should be subject
929 * to review in the future.
932 soabort(struct socket *so)
936 * In as much as is possible, assert that no references to this
937 * socket are held. This is not quite the same as asserting that the
938 * current thread is responsible for arranging for no references, but
939 * is as close as we can get for now.
941 KASSERT(so->so_count == 0, ("soabort: so_count"));
942 KASSERT((so->so_state & SS_PROTOREF) == 0, ("soabort: SS_PROTOREF"));
943 KASSERT(so->so_state & SS_NOFDREF, ("soabort: !SS_NOFDREF"));
944 KASSERT((so->so_state & SQ_COMP) == 0, ("soabort: SQ_COMP"));
945 KASSERT((so->so_state & SQ_INCOMP) == 0, ("soabort: SQ_INCOMP"));
948 if (so->so_proto->pr_usrreqs->pru_abort != NULL)
949 (*so->so_proto->pr_usrreqs->pru_abort)(so);
956 soaccept(struct socket *so, struct sockaddr **nam)
961 KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
962 so->so_state &= ~SS_NOFDREF;
965 CURVNET_SET(so->so_vnet);
966 error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
972 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
975 return (soconnectat(AT_FDCWD, so, nam, td));
979 soconnectat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
983 if (so->so_options & SO_ACCEPTCONN)
986 CURVNET_SET(so->so_vnet);
988 * If protocol is connection-based, can only connect once.
989 * Otherwise, if connected, try to disconnect first. This allows
990 * user to disconnect by connecting to, e.g., a null address.
992 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
993 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
994 (error = sodisconnect(so)))) {
998 * Prevent accumulated error from previous connection from
1002 if (fd == AT_FDCWD) {
1003 error = (*so->so_proto->pr_usrreqs->pru_connect)(so,
1006 error = (*so->so_proto->pr_usrreqs->pru_connectat)(fd,
1016 soconnect2(struct socket *so1, struct socket *so2)
1020 CURVNET_SET(so1->so_vnet);
1021 error = (*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2);
1027 sodisconnect(struct socket *so)
1031 if ((so->so_state & SS_ISCONNECTED) == 0)
1033 if (so->so_state & SS_ISDISCONNECTING)
1036 error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
1040 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? 0 : SBL_WAIT)
1043 sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1044 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1048 int clen = 0, error, dontroute;
1050 KASSERT(so->so_type == SOCK_DGRAM, ("sosend_dgram: !SOCK_DGRAM"));
1051 KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
1052 ("sosend_dgram: !PR_ATOMIC"));
1055 resid = uio->uio_resid;
1057 resid = top->m_pkthdr.len;
1059 * In theory resid should be unsigned. However, space must be
1060 * signed, as it might be less than 0 if we over-committed, and we
1061 * must use a signed comparison of space and resid. On the other
1062 * hand, a negative resid causes us to loop sending 0-length
1063 * segments to the protocol.
1071 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
1073 td->td_ru.ru_msgsnd++;
1074 if (control != NULL)
1075 clen = control->m_len;
1077 SOCKBUF_LOCK(&so->so_snd);
1078 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1079 SOCKBUF_UNLOCK(&so->so_snd);
1084 error = so->so_error;
1086 SOCKBUF_UNLOCK(&so->so_snd);
1089 if ((so->so_state & SS_ISCONNECTED) == 0) {
1091 * `sendto' and `sendmsg' is allowed on a connection-based
1092 * socket if it supports implied connect. Return ENOTCONN if
1093 * not connected and no address is supplied.
1095 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1096 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1097 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1098 !(resid == 0 && clen != 0)) {
1099 SOCKBUF_UNLOCK(&so->so_snd);
1103 } else if (addr == NULL) {
1104 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1107 error = EDESTADDRREQ;
1108 SOCKBUF_UNLOCK(&so->so_snd);
1114 * Do we need MSG_OOB support in SOCK_DGRAM? Signs here may be a
1115 * problem and need fixing.
1117 space = sbspace(&so->so_snd);
1118 if (flags & MSG_OOB)
1121 SOCKBUF_UNLOCK(&so->so_snd);
1122 if (resid > space) {
1128 if (flags & MSG_EOR)
1129 top->m_flags |= M_EOR;
1132 * Copy the data from userland into a mbuf chain.
1133 * If no data is to be copied in, a single empty mbuf
1136 top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
1137 (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
1139 error = EFAULT; /* only possible error */
1142 space -= resid - uio->uio_resid;
1143 resid = uio->uio_resid;
1145 KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
1147 * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
1152 so->so_options |= SO_DONTROUTE;
1156 * XXX all the SBS_CANTSENDMORE checks previously done could be out
1157 * of date. We could have recieved a reset packet in an interrupt or
1158 * maybe we slept while doing page faults in uiomove() etc. We could
1159 * probably recheck again inside the locking protection here, but
1160 * there are probably other places that this also happens. We must
1164 error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1165 (flags & MSG_OOB) ? PRUS_OOB :
1167 * If the user set MSG_EOF, the protocol understands this flag and
1168 * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
1170 ((flags & MSG_EOF) &&
1171 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1174 /* If there is more to send set PRUS_MORETOCOME */
1175 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1176 top, addr, control, td);
1179 so->so_options &= ~SO_DONTROUTE;
1188 if (control != NULL)
1194 * Send on a socket. If send must go all at once and message is larger than
1195 * send buffering, then hard error. Lock against other senders. If must go
1196 * all at once and not enough room now, then inform user that this would
1197 * block and do nothing. Otherwise, if nonblocking, send as much as
1198 * possible. The data to be sent is described by "uio" if nonzero, otherwise
1199 * by the mbuf chain "top" (which must be null if uio is not). Data provided
1200 * in mbuf chain must be small enough to send all at once.
1202 * Returns nonzero on error, timeout or signal; callers must check for short
1203 * counts if EINTR/ERESTART are returned. Data and control buffers are freed
1207 sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
1208 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1212 int clen = 0, error, dontroute;
1213 int atomic = sosendallatonce(so) || top;
1216 resid = uio->uio_resid;
1218 resid = top->m_pkthdr.len;
1220 * In theory resid should be unsigned. However, space must be
1221 * signed, as it might be less than 0 if we over-committed, and we
1222 * must use a signed comparison of space and resid. On the other
1223 * hand, a negative resid causes us to loop sending 0-length
1224 * segments to the protocol.
1226 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
1227 * type sockets since that's an error.
1229 if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
1235 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
1236 (so->so_proto->pr_flags & PR_ATOMIC);
1238 td->td_ru.ru_msgsnd++;
1239 if (control != NULL)
1240 clen = control->m_len;
1242 error = sblock(&so->so_snd, SBLOCKWAIT(flags));
1248 SOCKBUF_LOCK(&so->so_snd);
1249 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1250 SOCKBUF_UNLOCK(&so->so_snd);
1255 error = so->so_error;
1257 SOCKBUF_UNLOCK(&so->so_snd);
1260 if ((so->so_state & SS_ISCONNECTED) == 0) {
1262 * `sendto' and `sendmsg' is allowed on a connection-
1263 * based socket if it supports implied connect.
1264 * Return ENOTCONN if not connected and no address is
1267 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1268 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1269 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1270 !(resid == 0 && clen != 0)) {
1271 SOCKBUF_UNLOCK(&so->so_snd);
1275 } else if (addr == NULL) {
1276 SOCKBUF_UNLOCK(&so->so_snd);
1277 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1280 error = EDESTADDRREQ;
1284 space = sbspace(&so->so_snd);
1285 if (flags & MSG_OOB)
1287 if ((atomic && resid > so->so_snd.sb_hiwat) ||
1288 clen > so->so_snd.sb_hiwat) {
1289 SOCKBUF_UNLOCK(&so->so_snd);
1293 if (space < resid + clen &&
1294 (atomic || space < so->so_snd.sb_lowat || space < clen)) {
1295 if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO)) {
1296 SOCKBUF_UNLOCK(&so->so_snd);
1297 error = EWOULDBLOCK;
1300 error = sbwait(&so->so_snd);
1301 SOCKBUF_UNLOCK(&so->so_snd);
1306 SOCKBUF_UNLOCK(&so->so_snd);
1311 if (flags & MSG_EOR)
1312 top->m_flags |= M_EOR;
1313 } else if (resid > 0) {
1315 * Copy the data from userland into a mbuf
1316 * chain. If no data is to be copied in,
1317 * a single empty mbuf is returned.
1319 top = m_uiotombuf(uio, M_WAITOK, space,
1320 (atomic ? max_hdr : 0),
1321 (atomic ? M_PKTHDR : 0) |
1322 ((flags & MSG_EOR) ? M_EOR : 0));
1324 error = EFAULT; /* only possible error */
1327 space -= resid - uio->uio_resid;
1328 resid = uio->uio_resid;
1332 so->so_options |= SO_DONTROUTE;
1336 * XXX all the SBS_CANTSENDMORE checks previously
1337 * done could be out of date. We could have recieved
1338 * a reset packet in an interrupt or maybe we slept
1339 * while doing page faults in uiomove() etc. We
1340 * could probably recheck again inside the locking
1341 * protection here, but there are probably other
1342 * places that this also happens. We must rethink
1346 error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1347 (flags & MSG_OOB) ? PRUS_OOB :
1349 * If the user set MSG_EOF, the protocol understands
1350 * this flag and nothing left to send then use
1351 * PRU_SEND_EOF instead of PRU_SEND.
1353 ((flags & MSG_EOF) &&
1354 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1357 /* If there is more to send set PRUS_MORETOCOME. */
1358 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1359 top, addr, control, td);
1362 so->so_options &= ~SO_DONTROUTE;
1370 } while (resid && space > 0);
1374 sbunlock(&so->so_snd);
1378 if (control != NULL)
1384 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
1385 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1389 CURVNET_SET(so->so_vnet);
1390 error = so->so_proto->pr_usrreqs->pru_sosend(so, addr, uio, top,
1391 control, flags, td);
1397 * The part of soreceive() that implements reading non-inline out-of-band
1398 * data from a socket. For more complete comments, see soreceive(), from
1399 * which this code originated.
1401 * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
1402 * unable to return an mbuf chain to the caller.
1405 soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
1407 struct protosw *pr = so->so_proto;
1411 KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
1414 m = m_get(M_WAITOK, MT_DATA);
1415 error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
1419 error = uiomove(mtod(m, void *),
1420 (int) min(uio->uio_resid, m->m_len), uio);
1422 } while (uio->uio_resid && error == 0 && m);
1430 * Following replacement or removal of the first mbuf on the first mbuf chain
1431 * of a socket buffer, push necessary state changes back into the socket
1432 * buffer so that other consumers see the values consistently. 'nextrecord'
1433 * is the callers locally stored value of the original value of
1434 * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
1435 * NOTE: 'nextrecord' may be NULL.
1437 static __inline void
1438 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
1441 SOCKBUF_LOCK_ASSERT(sb);
1443 * First, update for the new value of nextrecord. If necessary, make
1444 * it the first record.
1446 if (sb->sb_mb != NULL)
1447 sb->sb_mb->m_nextpkt = nextrecord;
1449 sb->sb_mb = nextrecord;
1452 * Now update any dependent socket buffer fields to reflect the new
1453 * state. This is an expanded inline of SB_EMPTY_FIXUP(), with the
1454 * addition of a second clause that takes care of the case where
1455 * sb_mb has been updated, but remains the last record.
1457 if (sb->sb_mb == NULL) {
1458 sb->sb_mbtail = NULL;
1459 sb->sb_lastrecord = NULL;
1460 } else if (sb->sb_mb->m_nextpkt == NULL)
1461 sb->sb_lastrecord = sb->sb_mb;
1465 * Implement receive operations on a socket. We depend on the way that
1466 * records are added to the sockbuf by sbappend. In particular, each record
1467 * (mbufs linked through m_next) must begin with an address if the protocol
1468 * so specifies, followed by an optional mbuf or mbufs containing ancillary
1469 * data, and then zero or more mbufs of data. In order to allow parallelism
1470 * between network receive and copying to user space, as well as avoid
1471 * sleeping with a mutex held, we release the socket buffer mutex during the
1472 * user space copy. Although the sockbuf is locked, new data may still be
1473 * appended, and thus we must maintain consistency of the sockbuf during that
1476 * The caller may receive the data as a single mbuf chain by supplying an
1477 * mbuf **mp0 for use in returning the chain. The uio is then used only for
1478 * the count in uio_resid.
1481 soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
1482 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1484 struct mbuf *m, **mp;
1485 int flags, error, offset;
1487 struct protosw *pr = so->so_proto;
1488 struct mbuf *nextrecord;
1490 ssize_t orig_resid = uio->uio_resid;
1495 if (controlp != NULL)
1498 flags = *flagsp &~ MSG_EOR;
1501 if (flags & MSG_OOB)
1502 return (soreceive_rcvoob(so, uio, flags));
1505 if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
1506 && uio->uio_resid) {
1508 (*pr->pr_usrreqs->pru_rcvd)(so, 0);
1511 error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
1516 SOCKBUF_LOCK(&so->so_rcv);
1517 m = so->so_rcv.sb_mb;
1519 * If we have less data than requested, block awaiting more (subject
1520 * to any timeout) if:
1521 * 1. the current count is less than the low water mark, or
1522 * 2. MSG_DONTWAIT is not set
1524 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1525 sbavail(&so->so_rcv) < uio->uio_resid) &&
1526 sbavail(&so->so_rcv) < so->so_rcv.sb_lowat &&
1527 m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
1528 KASSERT(m != NULL || !sbavail(&so->so_rcv),
1529 ("receive: m == %p sbavail == %u",
1530 m, sbavail(&so->so_rcv)));
1534 error = so->so_error;
1535 if ((flags & MSG_PEEK) == 0)
1537 SOCKBUF_UNLOCK(&so->so_rcv);
1540 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1541 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1543 SOCKBUF_UNLOCK(&so->so_rcv);
1548 for (; m != NULL; m = m->m_next)
1549 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
1550 m = so->so_rcv.sb_mb;
1553 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1554 (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1555 SOCKBUF_UNLOCK(&so->so_rcv);
1559 if (uio->uio_resid == 0) {
1560 SOCKBUF_UNLOCK(&so->so_rcv);
1563 if ((so->so_state & SS_NBIO) ||
1564 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1565 SOCKBUF_UNLOCK(&so->so_rcv);
1566 error = EWOULDBLOCK;
1569 SBLASTRECORDCHK(&so->so_rcv);
1570 SBLASTMBUFCHK(&so->so_rcv);
1571 error = sbwait(&so->so_rcv);
1572 SOCKBUF_UNLOCK(&so->so_rcv);
1579 * From this point onward, we maintain 'nextrecord' as a cache of the
1580 * pointer to the next record in the socket buffer. We must keep the
1581 * various socket buffer pointers and local stack versions of the
1582 * pointers in sync, pushing out modifications before dropping the
1583 * socket buffer mutex, and re-reading them when picking it up.
1585 * Otherwise, we will race with the network stack appending new data
1586 * or records onto the socket buffer by using inconsistent/stale
1587 * versions of the field, possibly resulting in socket buffer
1590 * By holding the high-level sblock(), we prevent simultaneous
1591 * readers from pulling off the front of the socket buffer.
1593 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1595 uio->uio_td->td_ru.ru_msgrcv++;
1596 KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
1597 SBLASTRECORDCHK(&so->so_rcv);
1598 SBLASTMBUFCHK(&so->so_rcv);
1599 nextrecord = m->m_nextpkt;
1600 if (pr->pr_flags & PR_ADDR) {
1601 KASSERT(m->m_type == MT_SONAME,
1602 ("m->m_type == %d", m->m_type));
1605 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
1607 if (flags & MSG_PEEK) {
1610 sbfree(&so->so_rcv, m);
1611 so->so_rcv.sb_mb = m_free(m);
1612 m = so->so_rcv.sb_mb;
1613 sockbuf_pushsync(&so->so_rcv, nextrecord);
1618 * Process one or more MT_CONTROL mbufs present before any data mbufs
1619 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
1620 * just copy the data; if !MSG_PEEK, we call into the protocol to
1621 * perform externalization (or freeing if controlp == NULL).
1623 if (m != NULL && m->m_type == MT_CONTROL) {
1624 struct mbuf *cm = NULL, *cmn;
1625 struct mbuf **cme = &cm;
1628 if (flags & MSG_PEEK) {
1629 if (controlp != NULL) {
1630 *controlp = m_copy(m, 0, m->m_len);
1631 controlp = &(*controlp)->m_next;
1635 sbfree(&so->so_rcv, m);
1636 so->so_rcv.sb_mb = m->m_next;
1639 cme = &(*cme)->m_next;
1640 m = so->so_rcv.sb_mb;
1642 } while (m != NULL && m->m_type == MT_CONTROL);
1643 if ((flags & MSG_PEEK) == 0)
1644 sockbuf_pushsync(&so->so_rcv, nextrecord);
1645 while (cm != NULL) {
1648 if (pr->pr_domain->dom_externalize != NULL) {
1649 SOCKBUF_UNLOCK(&so->so_rcv);
1651 error = (*pr->pr_domain->dom_externalize)
1652 (cm, controlp, flags);
1653 SOCKBUF_LOCK(&so->so_rcv);
1654 } else if (controlp != NULL)
1658 if (controlp != NULL) {
1660 while (*controlp != NULL)
1661 controlp = &(*controlp)->m_next;
1666 nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1668 nextrecord = so->so_rcv.sb_mb;
1672 if ((flags & MSG_PEEK) == 0) {
1673 KASSERT(m->m_nextpkt == nextrecord,
1674 ("soreceive: post-control, nextrecord !sync"));
1675 if (nextrecord == NULL) {
1676 KASSERT(so->so_rcv.sb_mb == m,
1677 ("soreceive: post-control, sb_mb!=m"));
1678 KASSERT(so->so_rcv.sb_lastrecord == m,
1679 ("soreceive: post-control, lastrecord!=m"));
1683 if (type == MT_OOBDATA)
1686 if ((flags & MSG_PEEK) == 0) {
1687 KASSERT(so->so_rcv.sb_mb == nextrecord,
1688 ("soreceive: sb_mb != nextrecord"));
1689 if (so->so_rcv.sb_mb == NULL) {
1690 KASSERT(so->so_rcv.sb_lastrecord == NULL,
1691 ("soreceive: sb_lastercord != NULL"));
1695 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1696 SBLASTRECORDCHK(&so->so_rcv);
1697 SBLASTMBUFCHK(&so->so_rcv);
1700 * Now continue to read any data mbufs off of the head of the socket
1701 * buffer until the read request is satisfied. Note that 'type' is
1702 * used to store the type of any mbuf reads that have happened so far
1703 * such that soreceive() can stop reading if the type changes, which
1704 * causes soreceive() to return only one of regular data and inline
1705 * out-of-band data in a single socket receive operation.
1709 while (m != NULL && !(m->m_flags & M_NOTAVAIL) && uio->uio_resid > 0
1712 * If the type of mbuf has changed since the last mbuf
1713 * examined ('type'), end the receive operation.
1715 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1716 if (m->m_type == MT_OOBDATA || m->m_type == MT_CONTROL) {
1717 if (type != m->m_type)
1719 } else if (type == MT_OOBDATA)
1722 KASSERT(m->m_type == MT_DATA,
1723 ("m->m_type == %d", m->m_type));
1724 so->so_rcv.sb_state &= ~SBS_RCVATMARK;
1725 len = uio->uio_resid;
1726 if (so->so_oobmark && len > so->so_oobmark - offset)
1727 len = so->so_oobmark - offset;
1728 if (len > m->m_len - moff)
1729 len = m->m_len - moff;
1731 * If mp is set, just pass back the mbufs. Otherwise copy
1732 * them out via the uio, then free. Sockbuf must be
1733 * consistent here (points to current mbuf, it points to next
1734 * record) when we drop priority; we must note any additions
1735 * to the sockbuf when we block interrupts again.
1738 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1739 SBLASTRECORDCHK(&so->so_rcv);
1740 SBLASTMBUFCHK(&so->so_rcv);
1741 SOCKBUF_UNLOCK(&so->so_rcv);
1742 error = uiomove(mtod(m, char *) + moff, (int)len, uio);
1743 SOCKBUF_LOCK(&so->so_rcv);
1746 * The MT_SONAME mbuf has already been removed
1747 * from the record, so it is necessary to
1748 * remove the data mbufs, if any, to preserve
1749 * the invariant in the case of PR_ADDR that
1750 * requires MT_SONAME mbufs at the head of
1753 if (m && pr->pr_flags & PR_ATOMIC &&
1754 ((flags & MSG_PEEK) == 0))
1755 (void)sbdroprecord_locked(&so->so_rcv);
1756 SOCKBUF_UNLOCK(&so->so_rcv);
1760 uio->uio_resid -= len;
1761 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1762 if (len == m->m_len - moff) {
1763 if (m->m_flags & M_EOR)
1765 if (flags & MSG_PEEK) {
1769 nextrecord = m->m_nextpkt;
1770 sbfree(&so->so_rcv, m);
1772 m->m_nextpkt = NULL;
1775 so->so_rcv.sb_mb = m = m->m_next;
1778 so->so_rcv.sb_mb = m_free(m);
1779 m = so->so_rcv.sb_mb;
1781 sockbuf_pushsync(&so->so_rcv, nextrecord);
1782 SBLASTRECORDCHK(&so->so_rcv);
1783 SBLASTMBUFCHK(&so->so_rcv);
1786 if (flags & MSG_PEEK)
1790 if (flags & MSG_DONTWAIT) {
1791 *mp = m_copym(m, 0, len,
1795 * m_copym() couldn't
1797 * Adjust uio_resid back
1799 * down by len bytes,
1800 * which we didn't end
1801 * up "copying" over).
1803 uio->uio_resid += len;
1807 SOCKBUF_UNLOCK(&so->so_rcv);
1808 *mp = m_copym(m, 0, len,
1810 SOCKBUF_LOCK(&so->so_rcv);
1813 sbcut_locked(&so->so_rcv, len);
1816 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1817 if (so->so_oobmark) {
1818 if ((flags & MSG_PEEK) == 0) {
1819 so->so_oobmark -= len;
1820 if (so->so_oobmark == 0) {
1821 so->so_rcv.sb_state |= SBS_RCVATMARK;
1826 if (offset == so->so_oobmark)
1830 if (flags & MSG_EOR)
1833 * If the MSG_WAITALL flag is set (for non-atomic socket), we
1834 * must not quit until "uio->uio_resid == 0" or an error
1835 * termination. If a signal/timeout occurs, return with a
1836 * short count but without error. Keep sockbuf locked
1837 * against other readers.
1839 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
1840 !sosendallatonce(so) && nextrecord == NULL) {
1841 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1843 so->so_rcv.sb_state & SBS_CANTRCVMORE)
1846 * Notify the protocol that some data has been
1847 * drained before blocking.
1849 if (pr->pr_flags & PR_WANTRCVD) {
1850 SOCKBUF_UNLOCK(&so->so_rcv);
1852 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1853 SOCKBUF_LOCK(&so->so_rcv);
1855 SBLASTRECORDCHK(&so->so_rcv);
1856 SBLASTMBUFCHK(&so->so_rcv);
1858 * We could receive some data while was notifying
1859 * the protocol. Skip blocking in this case.
1861 if (so->so_rcv.sb_mb == NULL) {
1862 error = sbwait(&so->so_rcv);
1864 SOCKBUF_UNLOCK(&so->so_rcv);
1868 m = so->so_rcv.sb_mb;
1870 nextrecord = m->m_nextpkt;
1874 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1875 if (m != NULL && pr->pr_flags & PR_ATOMIC) {
1877 if ((flags & MSG_PEEK) == 0)
1878 (void) sbdroprecord_locked(&so->so_rcv);
1880 if ((flags & MSG_PEEK) == 0) {
1883 * First part is an inline SB_EMPTY_FIXUP(). Second
1884 * part makes sure sb_lastrecord is up-to-date if
1885 * there is still data in the socket buffer.
1887 so->so_rcv.sb_mb = nextrecord;
1888 if (so->so_rcv.sb_mb == NULL) {
1889 so->so_rcv.sb_mbtail = NULL;
1890 so->so_rcv.sb_lastrecord = NULL;
1891 } else if (nextrecord->m_nextpkt == NULL)
1892 so->so_rcv.sb_lastrecord = nextrecord;
1894 SBLASTRECORDCHK(&so->so_rcv);
1895 SBLASTMBUFCHK(&so->so_rcv);
1897 * If soreceive() is being done from the socket callback,
1898 * then don't need to generate ACK to peer to update window,
1899 * since ACK will be generated on return to TCP.
1901 if (!(flags & MSG_SOCALLBCK) &&
1902 (pr->pr_flags & PR_WANTRCVD)) {
1903 SOCKBUF_UNLOCK(&so->so_rcv);
1905 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
1906 SOCKBUF_LOCK(&so->so_rcv);
1909 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1910 if (orig_resid == uio->uio_resid && orig_resid &&
1911 (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
1912 SOCKBUF_UNLOCK(&so->so_rcv);
1915 SOCKBUF_UNLOCK(&so->so_rcv);
1920 sbunlock(&so->so_rcv);
1925 * Optimized version of soreceive() for stream (TCP) sockets.
1926 * XXXAO: (MSG_WAITALL | MSG_PEEK) isn't properly handled.
1929 soreceive_stream(struct socket *so, struct sockaddr **psa, struct uio *uio,
1930 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1932 int len = 0, error = 0, flags, oresid;
1934 struct mbuf *m, *n = NULL;
1936 /* We only do stream sockets. */
1937 if (so->so_type != SOCK_STREAM)
1941 if (controlp != NULL)
1944 flags = *flagsp &~ MSG_EOR;
1947 if (flags & MSG_OOB)
1948 return (soreceive_rcvoob(so, uio, flags));
1954 /* Prevent other readers from entering the socket. */
1955 error = sblock(sb, SBLOCKWAIT(flags));
1960 /* Easy one, no space to copyout anything. */
1961 if (uio->uio_resid == 0) {
1965 oresid = uio->uio_resid;
1967 /* We will never ever get anything unless we are or were connected. */
1968 if (!(so->so_state & (SS_ISCONNECTED|SS_ISDISCONNECTED))) {
1974 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1976 /* Abort if socket has reported problems. */
1978 if (sbavail(sb) > 0)
1980 if (oresid > uio->uio_resid)
1982 error = so->so_error;
1983 if (!(flags & MSG_PEEK))
1988 /* Door is closed. Deliver what is left, if any. */
1989 if (sb->sb_state & SBS_CANTRCVMORE) {
1990 if (sbavail(sb) > 0)
1996 /* Socket buffer is empty and we shall not block. */
1997 if (sbavail(sb) == 0 &&
1998 ((so->so_state & SS_NBIO) || (flags & (MSG_DONTWAIT|MSG_NBIO)))) {
2003 /* Socket buffer got some data that we shall deliver now. */
2004 if (sbavail(sb) > 0 && !(flags & MSG_WAITALL) &&
2005 ((sb->sb_flags & SS_NBIO) ||
2006 (flags & (MSG_DONTWAIT|MSG_NBIO)) ||
2007 sbavail(sb) >= sb->sb_lowat ||
2008 sbavail(sb) >= uio->uio_resid ||
2009 sbavail(sb) >= sb->sb_hiwat) ) {
2013 /* On MSG_WAITALL we must wait until all data or error arrives. */
2014 if ((flags & MSG_WAITALL) &&
2015 (sbavail(sb) >= uio->uio_resid || sbavail(sb) >= sb->sb_hiwat))
2019 * Wait and block until (more) data comes in.
2020 * NB: Drops the sockbuf lock during wait.
2028 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2029 KASSERT(sbavail(sb) > 0, ("%s: sockbuf empty", __func__));
2030 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb == NULL", __func__));
2034 uio->uio_td->td_ru.ru_msgrcv++;
2036 /* Fill uio until full or current end of socket buffer is reached. */
2037 len = min(uio->uio_resid, sbavail(sb));
2039 /* Dequeue as many mbufs as possible. */
2040 if (!(flags & MSG_PEEK) && len >= sb->sb_mb->m_len) {
2044 m_cat(*mp0, sb->sb_mb);
2046 m != NULL && m->m_len <= len;
2048 KASSERT(!(m->m_flags & M_NOTAVAIL),
2049 ("%s: m %p not available", __func__, m));
2051 uio->uio_resid -= m->m_len;
2057 sb->sb_lastrecord = sb->sb_mb;
2058 if (sb->sb_mb == NULL)
2061 /* Copy the remainder. */
2063 KASSERT(sb->sb_mb != NULL,
2064 ("%s: len > 0 && sb->sb_mb empty", __func__));
2066 m = m_copym(sb->sb_mb, 0, len, M_NOWAIT);
2068 len = 0; /* Don't flush data from sockbuf. */
2070 uio->uio_resid -= len;
2081 /* NB: Must unlock socket buffer as uiomove may sleep. */
2083 error = m_mbuftouio(uio, sb->sb_mb, len);
2088 SBLASTRECORDCHK(sb);
2092 * Remove the delivered data from the socket buffer unless we
2093 * were only peeking.
2095 if (!(flags & MSG_PEEK)) {
2097 sbdrop_locked(sb, len);
2099 /* Notify protocol that we drained some data. */
2100 if ((so->so_proto->pr_flags & PR_WANTRCVD) &&
2101 (((flags & MSG_WAITALL) && uio->uio_resid > 0) ||
2102 !(flags & MSG_SOCALLBCK))) {
2105 (*so->so_proto->pr_usrreqs->pru_rcvd)(so, flags);
2111 * For MSG_WAITALL we may have to loop again and wait for
2112 * more data to come in.
2114 if ((flags & MSG_WAITALL) && uio->uio_resid > 0)
2117 SOCKBUF_LOCK_ASSERT(sb);
2118 SBLASTRECORDCHK(sb);
2126 * Optimized version of soreceive() for simple datagram cases from userspace.
2127 * Unlike in the stream case, we're able to drop a datagram if copyout()
2128 * fails, and because we handle datagrams atomically, we don't need to use a
2129 * sleep lock to prevent I/O interlacing.
2132 soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
2133 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2135 struct mbuf *m, *m2;
2138 struct protosw *pr = so->so_proto;
2139 struct mbuf *nextrecord;
2143 if (controlp != NULL)
2146 flags = *flagsp &~ MSG_EOR;
2151 * For any complicated cases, fall back to the full
2152 * soreceive_generic().
2154 if (mp0 != NULL || (flags & MSG_PEEK) || (flags & MSG_OOB))
2155 return (soreceive_generic(so, psa, uio, mp0, controlp,
2159 * Enforce restrictions on use.
2161 KASSERT((pr->pr_flags & PR_WANTRCVD) == 0,
2162 ("soreceive_dgram: wantrcvd"));
2163 KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic"));
2164 KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0,
2165 ("soreceive_dgram: SBS_RCVATMARK"));
2166 KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0,
2167 ("soreceive_dgram: P_CONNREQUIRED"));
2170 * Loop blocking while waiting for a datagram.
2172 SOCKBUF_LOCK(&so->so_rcv);
2173 while ((m = so->so_rcv.sb_mb) == NULL) {
2174 KASSERT(sbavail(&so->so_rcv) == 0,
2175 ("soreceive_dgram: sb_mb NULL but sbavail %u",
2176 sbavail(&so->so_rcv)));
2178 error = so->so_error;
2180 SOCKBUF_UNLOCK(&so->so_rcv);
2183 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
2184 uio->uio_resid == 0) {
2185 SOCKBUF_UNLOCK(&so->so_rcv);
2188 if ((so->so_state & SS_NBIO) ||
2189 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
2190 SOCKBUF_UNLOCK(&so->so_rcv);
2191 return (EWOULDBLOCK);
2193 SBLASTRECORDCHK(&so->so_rcv);
2194 SBLASTMBUFCHK(&so->so_rcv);
2195 error = sbwait(&so->so_rcv);
2197 SOCKBUF_UNLOCK(&so->so_rcv);
2201 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2204 uio->uio_td->td_ru.ru_msgrcv++;
2205 SBLASTRECORDCHK(&so->so_rcv);
2206 SBLASTMBUFCHK(&so->so_rcv);
2207 nextrecord = m->m_nextpkt;
2208 if (nextrecord == NULL) {
2209 KASSERT(so->so_rcv.sb_lastrecord == m,
2210 ("soreceive_dgram: lastrecord != m"));
2213 KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord,
2214 ("soreceive_dgram: m_nextpkt != nextrecord"));
2217 * Pull 'm' and its chain off the front of the packet queue.
2219 so->so_rcv.sb_mb = NULL;
2220 sockbuf_pushsync(&so->so_rcv, nextrecord);
2223 * Walk 'm's chain and free that many bytes from the socket buffer.
2225 for (m2 = m; m2 != NULL; m2 = m2->m_next)
2226 sbfree(&so->so_rcv, m2);
2229 * Do a few last checks before we let go of the lock.
2231 SBLASTRECORDCHK(&so->so_rcv);
2232 SBLASTMBUFCHK(&so->so_rcv);
2233 SOCKBUF_UNLOCK(&so->so_rcv);
2235 if (pr->pr_flags & PR_ADDR) {
2236 KASSERT(m->m_type == MT_SONAME,
2237 ("m->m_type == %d", m->m_type));
2239 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
2244 /* XXXRW: Can this happen? */
2249 * Packet to copyout() is now in 'm' and it is disconnected from the
2252 * Process one or more MT_CONTROL mbufs present before any data mbufs
2253 * in the first mbuf chain on the socket buffer. We call into the
2254 * protocol to perform externalization (or freeing if controlp ==
2257 if (m->m_type == MT_CONTROL) {
2258 struct mbuf *cm = NULL, *cmn;
2259 struct mbuf **cme = &cm;
2265 cme = &(*cme)->m_next;
2267 } while (m != NULL && m->m_type == MT_CONTROL);
2268 while (cm != NULL) {
2271 if (pr->pr_domain->dom_externalize != NULL) {
2272 error = (*pr->pr_domain->dom_externalize)
2273 (cm, controlp, flags);
2274 } else if (controlp != NULL)
2278 if (controlp != NULL) {
2279 while (*controlp != NULL)
2280 controlp = &(*controlp)->m_next;
2285 KASSERT(m->m_type == MT_DATA, ("soreceive_dgram: !data"));
2287 while (m != NULL && uio->uio_resid > 0) {
2288 len = uio->uio_resid;
2291 error = uiomove(mtod(m, char *), (int)len, uio);
2296 if (len == m->m_len)
2312 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
2313 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2317 CURVNET_SET(so->so_vnet);
2318 error = (so->so_proto->pr_usrreqs->pru_soreceive(so, psa, uio, mp0,
2325 soshutdown(struct socket *so, int how)
2327 struct protosw *pr = so->so_proto;
2330 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
2333 CURVNET_SET(so->so_vnet);
2334 if (pr->pr_usrreqs->pru_flush != NULL)
2335 (*pr->pr_usrreqs->pru_flush)(so, how);
2338 if (how != SHUT_RD) {
2339 error = (*pr->pr_usrreqs->pru_shutdown)(so);
2340 wakeup(&so->so_timeo);
2344 wakeup(&so->so_timeo);
2350 sorflush(struct socket *so)
2352 struct sockbuf *sb = &so->so_rcv;
2353 struct protosw *pr = so->so_proto;
2359 * In order to avoid calling dom_dispose with the socket buffer mutex
2360 * held, and in order to generally avoid holding the lock for a long
2361 * time, we make a copy of the socket buffer and clear the original
2362 * (except locks, state). The new socket buffer copy won't have
2363 * initialized locks so we can only call routines that won't use or
2364 * assert those locks.
2366 * Dislodge threads currently blocked in receive and wait to acquire
2367 * a lock against other simultaneous readers before clearing the
2368 * socket buffer. Don't let our acquire be interrupted by a signal
2369 * despite any existing socket disposition on interruptable waiting.
2372 (void) sblock(sb, SBL_WAIT | SBL_NOINTR);
2375 * Invalidate/clear most of the sockbuf structure, but leave selinfo
2376 * and mutex data unchanged.
2379 bzero(&asb, offsetof(struct sockbuf, sb_startzero));
2380 bcopy(&sb->sb_startzero, &asb.sb_startzero,
2381 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2382 bzero(&sb->sb_startzero,
2383 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2388 * Dispose of special rights and flush the socket buffer. Don't call
2389 * any unsafe routines (that rely on locks being initialized) on asb.
2391 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
2392 (*pr->pr_domain->dom_dispose)(asb.sb_mb);
2393 sbrelease_internal(&asb, so);
2397 * Wrapper for Socket established helper hook.
2398 * Parameters: socket, context of the hook point, hook id.
2401 hhook_run_socket(struct socket *so, void *hctx, int32_t h_id)
2403 struct socket_hhook_data hhook_data = {
2410 CURVNET_SET(so->so_vnet);
2411 HHOOKS_RUN_IF(V_socket_hhh[h_id], &hhook_data, &so->osd);
2414 /* Ugly but needed, since hhooks return void for now */
2415 return (hhook_data.status);
2419 * Perhaps this routine, and sooptcopyout(), below, ought to come in an
2420 * additional variant to handle the case where the option value needs to be
2421 * some kind of integer, but not a specific size. In addition to their use
2422 * here, these functions are also called by the protocol-level pr_ctloutput()
2426 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2431 * If the user gives us more than we wanted, we ignore it, but if we
2432 * don't get the minimum length the caller wants, we return EINVAL.
2433 * On success, sopt->sopt_valsize is set to however much we actually
2436 if ((valsize = sopt->sopt_valsize) < minlen)
2439 sopt->sopt_valsize = valsize = len;
2441 if (sopt->sopt_td != NULL)
2442 return (copyin(sopt->sopt_val, buf, valsize));
2444 bcopy(sopt->sopt_val, buf, valsize);
2449 * Kernel version of setsockopt(2).
2451 * XXX: optlen is size_t, not socklen_t
2454 so_setsockopt(struct socket *so, int level, int optname, void *optval,
2457 struct sockopt sopt;
2459 sopt.sopt_level = level;
2460 sopt.sopt_name = optname;
2461 sopt.sopt_dir = SOPT_SET;
2462 sopt.sopt_val = optval;
2463 sopt.sopt_valsize = optlen;
2464 sopt.sopt_td = NULL;
2465 return (sosetopt(so, &sopt));
2469 sosetopt(struct socket *so, struct sockopt *sopt)
2480 CURVNET_SET(so->so_vnet);
2482 if (sopt->sopt_level != SOL_SOCKET) {
2483 if (so->so_proto->pr_ctloutput != NULL) {
2484 error = (*so->so_proto->pr_ctloutput)(so, sopt);
2488 error = ENOPROTOOPT;
2490 switch (sopt->sopt_name) {
2491 case SO_ACCEPTFILTER:
2492 error = do_setopt_accept_filter(so, sopt);
2498 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
2503 so->so_linger = l.l_linger;
2505 so->so_options |= SO_LINGER;
2507 so->so_options &= ~SO_LINGER;
2514 case SO_USELOOPBACK:
2524 error = sooptcopyin(sopt, &optval, sizeof optval,
2530 so->so_options |= sopt->sopt_name;
2532 so->so_options &= ~sopt->sopt_name;
2537 error = sooptcopyin(sopt, &optval, sizeof optval,
2542 if (optval < 0 || optval >= rt_numfibs) {
2546 if (((so->so_proto->pr_domain->dom_family == PF_INET) ||
2547 (so->so_proto->pr_domain->dom_family == PF_INET6) ||
2548 (so->so_proto->pr_domain->dom_family == PF_ROUTE)))
2549 so->so_fibnum = optval;
2554 case SO_USER_COOKIE:
2555 error = sooptcopyin(sopt, &val32, sizeof val32,
2559 so->so_user_cookie = val32;
2566 error = sooptcopyin(sopt, &optval, sizeof optval,
2572 * Values < 1 make no sense for any of these options,
2580 switch (sopt->sopt_name) {
2583 if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
2584 &so->so_snd : &so->so_rcv, (u_long)optval,
2585 so, curthread) == 0) {
2589 (sopt->sopt_name == SO_SNDBUF ? &so->so_snd :
2590 &so->so_rcv)->sb_flags &= ~SB_AUTOSIZE;
2594 * Make sure the low-water is never greater than the
2598 SOCKBUF_LOCK(&so->so_snd);
2599 so->so_snd.sb_lowat =
2600 (optval > so->so_snd.sb_hiwat) ?
2601 so->so_snd.sb_hiwat : optval;
2602 SOCKBUF_UNLOCK(&so->so_snd);
2605 SOCKBUF_LOCK(&so->so_rcv);
2606 so->so_rcv.sb_lowat =
2607 (optval > so->so_rcv.sb_hiwat) ?
2608 so->so_rcv.sb_hiwat : optval;
2609 SOCKBUF_UNLOCK(&so->so_rcv);
2616 #ifdef COMPAT_FREEBSD32
2617 if (SV_CURPROC_FLAG(SV_ILP32)) {
2618 struct timeval32 tv32;
2620 error = sooptcopyin(sopt, &tv32, sizeof tv32,
2622 CP(tv32, tv, tv_sec);
2623 CP(tv32, tv, tv_usec);
2626 error = sooptcopyin(sopt, &tv, sizeof tv,
2630 if (tv.tv_sec < 0 || tv.tv_usec < 0 ||
2631 tv.tv_usec >= 1000000) {
2635 if (tv.tv_sec > INT32_MAX)
2639 switch (sopt->sopt_name) {
2641 so->so_snd.sb_timeo = val;
2644 so->so_rcv.sb_timeo = val;
2651 error = sooptcopyin(sopt, &extmac, sizeof extmac,
2655 error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
2663 if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
2664 error = hhook_run_socket(so, sopt,
2667 error = ENOPROTOOPT;
2670 if (error == 0 && so->so_proto->pr_ctloutput != NULL)
2671 (void)(*so->so_proto->pr_ctloutput)(so, sopt);
2679 * Helper routine for getsockopt.
2682 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
2690 * Documented get behavior is that we always return a value, possibly
2691 * truncated to fit in the user's buffer. Traditional behavior is
2692 * that we always tell the user precisely how much we copied, rather
2693 * than something useful like the total amount we had available for
2694 * her. Note that this interface is not idempotent; the entire
2695 * answer must generated ahead of time.
2697 valsize = min(len, sopt->sopt_valsize);
2698 sopt->sopt_valsize = valsize;
2699 if (sopt->sopt_val != NULL) {
2700 if (sopt->sopt_td != NULL)
2701 error = copyout(buf, sopt->sopt_val, valsize);
2703 bcopy(buf, sopt->sopt_val, valsize);
2709 sogetopt(struct socket *so, struct sockopt *sopt)
2718 CURVNET_SET(so->so_vnet);
2720 if (sopt->sopt_level != SOL_SOCKET) {
2721 if (so->so_proto->pr_ctloutput != NULL)
2722 error = (*so->so_proto->pr_ctloutput)(so, sopt);
2724 error = ENOPROTOOPT;
2728 switch (sopt->sopt_name) {
2729 case SO_ACCEPTFILTER:
2730 error = do_getopt_accept_filter(so, sopt);
2735 l.l_onoff = so->so_options & SO_LINGER;
2736 l.l_linger = so->so_linger;
2738 error = sooptcopyout(sopt, &l, sizeof l);
2741 case SO_USELOOPBACK:
2753 optval = so->so_options & sopt->sopt_name;
2755 error = sooptcopyout(sopt, &optval, sizeof optval);
2759 optval = so->so_type;
2763 optval = so->so_proto->pr_protocol;
2768 optval = so->so_error;
2774 optval = so->so_snd.sb_hiwat;
2778 optval = so->so_rcv.sb_hiwat;
2782 optval = so->so_snd.sb_lowat;
2786 optval = so->so_rcv.sb_lowat;
2791 tv = sbttotv(sopt->sopt_name == SO_SNDTIMEO ?
2792 so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
2793 #ifdef COMPAT_FREEBSD32
2794 if (SV_CURPROC_FLAG(SV_ILP32)) {
2795 struct timeval32 tv32;
2797 CP(tv, tv32, tv_sec);
2798 CP(tv, tv32, tv_usec);
2799 error = sooptcopyout(sopt, &tv32, sizeof tv32);
2802 error = sooptcopyout(sopt, &tv, sizeof tv);
2807 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2811 error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
2815 error = sooptcopyout(sopt, &extmac, sizeof extmac);
2823 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
2827 error = mac_getsockopt_peerlabel(
2828 sopt->sopt_td->td_ucred, so, &extmac);
2831 error = sooptcopyout(sopt, &extmac, sizeof extmac);
2837 case SO_LISTENQLIMIT:
2838 optval = so->so_qlimit;
2842 optval = so->so_qlen;
2845 case SO_LISTENINCQLEN:
2846 optval = so->so_incqlen;
2850 if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
2851 error = hhook_run_socket(so, sopt,
2854 error = ENOPROTOOPT;
2866 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
2868 struct mbuf *m, *m_prev;
2869 int sopt_size = sopt->sopt_valsize;
2871 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
2874 if (sopt_size > MLEN) {
2875 MCLGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT);
2876 if ((m->m_flags & M_EXT) == 0) {
2880 m->m_len = min(MCLBYTES, sopt_size);
2882 m->m_len = min(MLEN, sopt_size);
2884 sopt_size -= m->m_len;
2889 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
2894 if (sopt_size > MLEN) {
2895 MCLGET(m, sopt->sopt_td != NULL ? M_WAITOK :
2897 if ((m->m_flags & M_EXT) == 0) {
2902 m->m_len = min(MCLBYTES, sopt_size);
2904 m->m_len = min(MLEN, sopt_size);
2906 sopt_size -= m->m_len;
2914 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
2916 struct mbuf *m0 = m;
2918 if (sopt->sopt_val == NULL)
2920 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2921 if (sopt->sopt_td != NULL) {
2924 error = copyin(sopt->sopt_val, mtod(m, char *),
2931 bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
2932 sopt->sopt_valsize -= m->m_len;
2933 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2936 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
2937 panic("ip6_sooptmcopyin");
2942 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
2944 struct mbuf *m0 = m;
2947 if (sopt->sopt_val == NULL)
2949 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
2950 if (sopt->sopt_td != NULL) {
2953 error = copyout(mtod(m, char *), sopt->sopt_val,
2960 bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
2961 sopt->sopt_valsize -= m->m_len;
2962 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
2963 valsize += m->m_len;
2967 /* enough soopt buffer should be given from user-land */
2971 sopt->sopt_valsize = valsize;
2976 * sohasoutofband(): protocol notifies socket layer of the arrival of new
2977 * out-of-band data, which will then notify socket consumers.
2980 sohasoutofband(struct socket *so)
2983 if (so->so_sigio != NULL)
2984 pgsigio(&so->so_sigio, SIGURG, 0);
2985 selwakeuppri(&so->so_rcv.sb_sel, PSOCK);
2989 sopoll(struct socket *so, int events, struct ucred *active_cred,
2994 * We do not need to set or assert curvnet as long as everyone uses
2997 return (so->so_proto->pr_usrreqs->pru_sopoll(so, events, active_cred,
3002 sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
3007 SOCKBUF_LOCK(&so->so_snd);
3008 SOCKBUF_LOCK(&so->so_rcv);
3009 if (events & (POLLIN | POLLRDNORM))
3010 if (soreadabledata(so))
3011 revents |= events & (POLLIN | POLLRDNORM);
3013 if (events & (POLLOUT | POLLWRNORM))
3014 if (sowriteable(so))
3015 revents |= events & (POLLOUT | POLLWRNORM);
3017 if (events & (POLLPRI | POLLRDBAND))
3018 if (so->so_oobmark || (so->so_rcv.sb_state & SBS_RCVATMARK))
3019 revents |= events & (POLLPRI | POLLRDBAND);
3021 if ((events & POLLINIGNEOF) == 0) {
3022 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3023 revents |= events & (POLLIN | POLLRDNORM);
3024 if (so->so_snd.sb_state & SBS_CANTSENDMORE)
3030 if (events & (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND)) {
3031 selrecord(td, &so->so_rcv.sb_sel);
3032 so->so_rcv.sb_flags |= SB_SEL;
3035 if (events & (POLLOUT | POLLWRNORM)) {
3036 selrecord(td, &so->so_snd.sb_sel);
3037 so->so_snd.sb_flags |= SB_SEL;
3041 SOCKBUF_UNLOCK(&so->so_rcv);
3042 SOCKBUF_UNLOCK(&so->so_snd);
3047 soo_kqfilter(struct file *fp, struct knote *kn)
3049 struct socket *so = kn->kn_fp->f_data;
3052 switch (kn->kn_filter) {
3054 if (so->so_options & SO_ACCEPTCONN)
3055 kn->kn_fop = &solisten_filtops;
3057 kn->kn_fop = &soread_filtops;
3061 kn->kn_fop = &sowrite_filtops;
3069 knlist_add(&sb->sb_sel.si_note, kn, 1);
3070 sb->sb_flags |= SB_KNOTE;
3076 * Some routines that return EOPNOTSUPP for entry points that are not
3077 * supported by a protocol. Fill in as needed.
3080 pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
3087 pru_attach_notsupp(struct socket *so, int proto, struct thread *td)
3094 pru_bind_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
3101 pru_bindat_notsupp(int fd, struct socket *so, struct sockaddr *nam,
3109 pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
3116 pru_connectat_notsupp(int fd, struct socket *so, struct sockaddr *nam,
3124 pru_connect2_notsupp(struct socket *so1, struct socket *so2)
3131 pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
3132 struct ifnet *ifp, struct thread *td)
3139 pru_disconnect_notsupp(struct socket *so)
3146 pru_listen_notsupp(struct socket *so, int backlog, struct thread *td)
3153 pru_peeraddr_notsupp(struct socket *so, struct sockaddr **nam)
3160 pru_rcvd_notsupp(struct socket *so, int flags)
3167 pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
3174 pru_send_notsupp(struct socket *so, int flags, struct mbuf *m,
3175 struct sockaddr *addr, struct mbuf *control, struct thread *td)
3182 pru_ready_notsupp(struct socket *so, struct mbuf *m, int count)
3185 return (EOPNOTSUPP);
3189 * This isn't really a ``null'' operation, but it's the default one and
3190 * doesn't do anything destructive.
3193 pru_sense_null(struct socket *so, struct stat *sb)
3196 sb->st_blksize = so->so_snd.sb_hiwat;
3201 pru_shutdown_notsupp(struct socket *so)
3208 pru_sockaddr_notsupp(struct socket *so, struct sockaddr **nam)
3215 pru_sosend_notsupp(struct socket *so, struct sockaddr *addr, struct uio *uio,
3216 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
3223 pru_soreceive_notsupp(struct socket *so, struct sockaddr **paddr,
3224 struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
3231 pru_sopoll_notsupp(struct socket *so, int events, struct ucred *cred,
3239 filt_sordetach(struct knote *kn)
3241 struct socket *so = kn->kn_fp->f_data;
3243 SOCKBUF_LOCK(&so->so_rcv);
3244 knlist_remove(&so->so_rcv.sb_sel.si_note, kn, 1);
3245 if (knlist_empty(&so->so_rcv.sb_sel.si_note))
3246 so->so_rcv.sb_flags &= ~SB_KNOTE;
3247 SOCKBUF_UNLOCK(&so->so_rcv);
3252 filt_soread(struct knote *kn, long hint)
3256 so = kn->kn_fp->f_data;
3257 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3259 kn->kn_data = sbavail(&so->so_rcv) - so->so_rcv.sb_ctl;
3260 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3261 kn->kn_flags |= EV_EOF;
3262 kn->kn_fflags = so->so_error;
3264 } else if (so->so_error) /* temporary udp error */
3267 if (kn->kn_sfflags & NOTE_LOWAT) {
3268 if (kn->kn_data >= kn->kn_sdata)
3271 if (sbavail(&so->so_rcv) >= so->so_rcv.sb_lowat)
3275 /* This hook returning non-zero indicates an event, not error */
3276 return (hhook_run_socket(so, NULL, HHOOK_FILT_SOREAD));
3280 filt_sowdetach(struct knote *kn)
3282 struct socket *so = kn->kn_fp->f_data;
3284 SOCKBUF_LOCK(&so->so_snd);
3285 knlist_remove(&so->so_snd.sb_sel.si_note, kn, 1);
3286 if (knlist_empty(&so->so_snd.sb_sel.si_note))
3287 so->so_snd.sb_flags &= ~SB_KNOTE;
3288 SOCKBUF_UNLOCK(&so->so_snd);
3293 filt_sowrite(struct knote *kn, long hint)
3297 so = kn->kn_fp->f_data;
3298 SOCKBUF_LOCK_ASSERT(&so->so_snd);
3299 kn->kn_data = sbspace(&so->so_snd);
3301 hhook_run_socket(so, kn, HHOOK_FILT_SOWRITE);
3303 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
3304 kn->kn_flags |= EV_EOF;
3305 kn->kn_fflags = so->so_error;
3307 } else if (so->so_error) /* temporary udp error */
3309 else if (((so->so_state & SS_ISCONNECTED) == 0) &&
3310 (so->so_proto->pr_flags & PR_CONNREQUIRED))
3312 else if (kn->kn_sfflags & NOTE_LOWAT)
3313 return (kn->kn_data >= kn->kn_sdata);
3315 return (kn->kn_data >= so->so_snd.sb_lowat);
3320 filt_solisten(struct knote *kn, long hint)
3322 struct socket *so = kn->kn_fp->f_data;
3324 kn->kn_data = so->so_qlen;
3325 return (!TAILQ_EMPTY(&so->so_comp));
3329 socheckuid(struct socket *so, uid_t uid)
3334 if (so->so_cred->cr_uid != uid)
3340 * These functions are used by protocols to notify the socket layer (and its
3341 * consumers) of state changes in the sockets driven by protocol-side events.
3345 * Procedures to manipulate state flags of socket and do appropriate wakeups.
3347 * Normal sequence from the active (originating) side is that
3348 * soisconnecting() is called during processing of connect() call, resulting
3349 * in an eventual call to soisconnected() if/when the connection is
3350 * established. When the connection is torn down soisdisconnecting() is
3351 * called during processing of disconnect() call, and soisdisconnected() is
3352 * called when the connection to the peer is totally severed. The semantics
3353 * of these routines are such that connectionless protocols can call
3354 * soisconnected() and soisdisconnected() only, bypassing the in-progress
3355 * calls when setting up a ``connection'' takes no time.
3357 * From the passive side, a socket is created with two queues of sockets:
3358 * so_incomp for connections in progress and so_comp for connections already
3359 * made and awaiting user acceptance. As a protocol is preparing incoming
3360 * connections, it creates a socket structure queued on so_incomp by calling
3361 * sonewconn(). When the connection is established, soisconnected() is
3362 * called, and transfers the socket structure to so_comp, making it available
3365 * If a socket is closed with sockets on either so_incomp or so_comp, these
3366 * sockets are dropped.
3368 * If higher-level protocols are implemented in the kernel, the wakeups done
3369 * here will sometimes cause software-interrupt process scheduling.
3372 soisconnecting(struct socket *so)
3376 so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
3377 so->so_state |= SS_ISCONNECTING;
3382 soisconnected(struct socket *so)
3384 struct socket *head;
3390 so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
3391 so->so_state |= SS_ISCONNECTED;
3393 if (head != NULL && (so->so_qstate & SQ_INCOMP)) {
3394 if ((so->so_options & SO_ACCEPTFILTER) == 0) {
3396 TAILQ_REMOVE(&head->so_incomp, so, so_list);
3398 so->so_qstate &= ~SQ_INCOMP;
3399 TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
3401 so->so_qstate |= SQ_COMP;
3404 wakeup_one(&head->so_timeo);
3407 soupcall_set(so, SO_RCV,
3408 head->so_accf->so_accept_filter->accf_callback,
3409 head->so_accf->so_accept_filter_arg);
3410 so->so_options &= ~SO_ACCEPTFILTER;
3411 ret = head->so_accf->so_accept_filter->accf_callback(so,
3412 head->so_accf->so_accept_filter_arg, M_NOWAIT);
3413 if (ret == SU_ISCONNECTED)
3414 soupcall_clear(so, SO_RCV);
3416 if (ret == SU_ISCONNECTED)
3423 wakeup(&so->so_timeo);
3429 soisdisconnecting(struct socket *so)
3433 * Note: This code assumes that SOCK_LOCK(so) and
3434 * SOCKBUF_LOCK(&so->so_rcv) are the same.
3436 SOCKBUF_LOCK(&so->so_rcv);
3437 so->so_state &= ~SS_ISCONNECTING;
3438 so->so_state |= SS_ISDISCONNECTING;
3439 so->so_rcv.sb_state |= SBS_CANTRCVMORE;
3440 sorwakeup_locked(so);
3441 SOCKBUF_LOCK(&so->so_snd);
3442 so->so_snd.sb_state |= SBS_CANTSENDMORE;
3443 sowwakeup_locked(so);
3444 wakeup(&so->so_timeo);
3448 soisdisconnected(struct socket *so)
3452 * Note: This code assumes that SOCK_LOCK(so) and
3453 * SOCKBUF_LOCK(&so->so_rcv) are the same.
3455 SOCKBUF_LOCK(&so->so_rcv);
3456 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
3457 so->so_state |= SS_ISDISCONNECTED;
3458 so->so_rcv.sb_state |= SBS_CANTRCVMORE;
3459 sorwakeup_locked(so);
3460 SOCKBUF_LOCK(&so->so_snd);
3461 so->so_snd.sb_state |= SBS_CANTSENDMORE;
3462 sbdrop_locked(&so->so_snd, sbused(&so->so_snd));
3463 sowwakeup_locked(so);
3464 wakeup(&so->so_timeo);
3468 * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
3471 sodupsockaddr(const struct sockaddr *sa, int mflags)
3473 struct sockaddr *sa2;
3475 sa2 = malloc(sa->sa_len, M_SONAME, mflags);
3477 bcopy(sa, sa2, sa->sa_len);
3482 * Register per-socket buffer upcalls.
3485 soupcall_set(struct socket *so, int which,
3486 int (*func)(struct socket *, void *, int), void *arg)
3498 panic("soupcall_set: bad which");
3500 SOCKBUF_LOCK_ASSERT(sb);
3502 /* XXX: accf_http actually wants to do this on purpose. */
3503 KASSERT(sb->sb_upcall == NULL, ("soupcall_set: overwriting upcall"));
3505 sb->sb_upcall = func;
3506 sb->sb_upcallarg = arg;
3507 sb->sb_flags |= SB_UPCALL;
3511 soupcall_clear(struct socket *so, int which)
3523 panic("soupcall_clear: bad which");
3525 SOCKBUF_LOCK_ASSERT(sb);
3526 KASSERT(sb->sb_upcall != NULL, ("soupcall_clear: no upcall to clear"));
3527 sb->sb_upcall = NULL;
3528 sb->sb_upcallarg = NULL;
3529 sb->sb_flags &= ~SB_UPCALL;
3533 * Create an external-format (``xsocket'') structure using the information in
3534 * the kernel-format socket structure pointed to by so. This is done to
3535 * reduce the spew of irrelevant information over this interface, to isolate
3536 * user code from changes in the kernel structure, and potentially to provide
3537 * information-hiding if we decide that some of this information should be
3538 * hidden from users.
3541 sotoxsocket(struct socket *so, struct xsocket *xso)
3544 xso->xso_len = sizeof *xso;
3546 xso->so_type = so->so_type;
3547 xso->so_options = so->so_options;
3548 xso->so_linger = so->so_linger;
3549 xso->so_state = so->so_state;
3550 xso->so_pcb = so->so_pcb;
3551 xso->xso_protocol = so->so_proto->pr_protocol;
3552 xso->xso_family = so->so_proto->pr_domain->dom_family;
3553 xso->so_qlen = so->so_qlen;
3554 xso->so_incqlen = so->so_incqlen;
3555 xso->so_qlimit = so->so_qlimit;
3556 xso->so_timeo = so->so_timeo;
3557 xso->so_error = so->so_error;
3558 xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
3559 xso->so_oobmark = so->so_oobmark;
3560 sbtoxsockbuf(&so->so_snd, &xso->so_snd);
3561 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
3562 xso->so_uid = so->so_cred->cr_uid;
3567 * Socket accessor functions to provide external consumers with
3568 * a safe interface to socket state
3573 so_listeners_apply_all(struct socket *so, void (*func)(struct socket *, void *),
3577 TAILQ_FOREACH(so, &so->so_comp, so_list)
3582 so_sockbuf_rcv(struct socket *so)
3585 return (&so->so_rcv);
3589 so_sockbuf_snd(struct socket *so)
3592 return (&so->so_snd);
3596 so_state_get(const struct socket *so)
3599 return (so->so_state);
3603 so_state_set(struct socket *so, int val)
3610 so_options_get(const struct socket *so)
3613 return (so->so_options);
3617 so_options_set(struct socket *so, int val)
3620 so->so_options = val;
3624 so_error_get(const struct socket *so)
3627 return (so->so_error);
3631 so_error_set(struct socket *so, int val)
3638 so_linger_get(const struct socket *so)
3641 return (so->so_linger);
3645 so_linger_set(struct socket *so, int val)
3648 so->so_linger = val;
3652 so_protosw_get(const struct socket *so)
3655 return (so->so_proto);
3659 so_protosw_set(struct socket *so, struct protosw *val)
3666 so_sorwakeup(struct socket *so)
3673 so_sowwakeup(struct socket *so)
3680 so_sorwakeup_locked(struct socket *so)
3683 sorwakeup_locked(so);
3687 so_sowwakeup_locked(struct socket *so)
3690 sowwakeup_locked(so);
3694 so_lock(struct socket *so)
3701 so_unlock(struct socket *so)