2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1988, 1990, 1993
5 * The Regents of the University of California.
6 * Copyright (c) 2004 The FreeBSD Foundation
7 * Copyright (c) 2004-2008 Robert N. M. Watson
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)uipc_socket.c 8.3 (Berkeley) 4/15/94
38 * Comments on the socket life cycle:
40 * soalloc() sets of socket layer state for a socket, called only by
41 * socreate() and sonewconn(). Socket layer private.
43 * sodealloc() tears down socket layer state for a socket, called only by
44 * sofree() and sonewconn(). Socket layer private.
46 * pru_attach() associates protocol layer state with an allocated socket;
47 * called only once, may fail, aborting socket allocation. This is called
48 * from socreate() and sonewconn(). Socket layer private.
50 * pru_detach() disassociates protocol layer state from an attached socket,
51 * and will be called exactly once for sockets in which pru_attach() has
52 * been successfully called. If pru_attach() returned an error,
53 * pru_detach() will not be called. Socket layer private.
55 * pru_abort() and pru_close() notify the protocol layer that the last
56 * consumer of a socket is starting to tear down the socket, and that the
57 * protocol should terminate the connection. Historically, pru_abort() also
58 * detached protocol state from the socket state, but this is no longer the
61 * socreate() creates a socket and attaches protocol state. This is a public
62 * interface that may be used by socket layer consumers to create new
65 * sonewconn() creates a socket and attaches protocol state. This is a
66 * public interface that may be used by protocols to create new sockets when
67 * a new connection is received and will be available for accept() on a
70 * soclose() destroys a socket after possibly waiting for it to disconnect.
71 * This is a public interface that socket consumers should use to close and
72 * release a socket when done with it.
74 * soabort() destroys a socket without waiting for it to disconnect (used
75 * only for incoming connections that are already partially or fully
76 * connected). This is used internally by the socket layer when clearing
77 * listen socket queues (due to overflow or close on the listen socket), but
78 * is also a public interface protocols may use to abort connections in
79 * their incomplete listen queues should they no longer be required. Sockets
80 * placed in completed connection listen queues should not be aborted for
81 * reasons described in the comment above the soclose() implementation. This
82 * is not a general purpose close routine, and except in the specific
83 * circumstances described here, should not be used.
85 * sofree() will free a socket and its protocol state if all references on
86 * the socket have been released, and is the public interface to attempt to
87 * free a socket when a reference is removed. This is a socket layer private
90 * NOTE: In addition to socreate() and soclose(), which provide a single
91 * socket reference to the consumer to be managed as required, there are two
92 * calls to explicitly manage socket references, soref(), and sorele().
93 * Currently, these are generally required only when transitioning a socket
94 * from a listen queue to a file descriptor, in order to prevent garbage
95 * collection of the socket at an untimely moment. For a number of reasons,
96 * these interfaces are not preferred, and should be avoided.
98 * NOTE: With regard to VNETs the general rule is that callers do not set
99 * curvnet. Exceptions to this rule include soabort(), sodisconnect(),
100 * sofree() (and with that sorele(), sotryfree()), as well as sonewconn()
101 * and sorflush(), which are usually called from a pre-set VNET context.
102 * sopoll() currently does not need a VNET context to be set.
105 #include <sys/cdefs.h>
106 __FBSDID("$FreeBSD$");
108 #include "opt_inet.h"
109 #include "opt_inet6.h"
110 #include "opt_kern_tls.h"
111 #include "opt_sctp.h"
113 #include <sys/param.h>
114 #include <sys/systm.h>
115 #include <sys/fcntl.h>
116 #include <sys/limits.h>
117 #include <sys/lock.h>
119 #include <sys/malloc.h>
120 #include <sys/mbuf.h>
121 #include <sys/mutex.h>
122 #include <sys/domain.h>
123 #include <sys/file.h> /* for struct knote */
124 #include <sys/hhook.h>
125 #include <sys/kernel.h>
126 #include <sys/khelp.h>
127 #include <sys/ktls.h>
128 #include <sys/event.h>
129 #include <sys/eventhandler.h>
130 #include <sys/poll.h>
131 #include <sys/proc.h>
132 #include <sys/protosw.h>
133 #include <sys/socket.h>
134 #include <sys/socketvar.h>
135 #include <sys/resourcevar.h>
136 #include <net/route.h>
137 #include <sys/signalvar.h>
138 #include <sys/stat.h>
140 #include <sys/sysctl.h>
141 #include <sys/taskqueue.h>
143 #include <sys/jail.h>
144 #include <sys/syslog.h>
145 #include <netinet/in.h>
146 #include <netinet/tcp.h>
148 #include <net/vnet.h>
149 #include <net/if.h> /* XXXGL: net_epoch should move out there */
150 #include <net/if_var.h> /* XXXGL: net_epoch should move out there */
152 #include <security/mac/mac_framework.h>
156 #ifdef COMPAT_FREEBSD32
157 #include <sys/mount.h>
158 #include <sys/sysent.h>
159 #include <compat/freebsd32/freebsd32.h>
162 static int soreceive_rcvoob(struct socket *so, struct uio *uio,
164 static void so_rdknl_lock(void *);
165 static void so_rdknl_unlock(void *);
166 static void so_rdknl_assert_locked(void *);
167 static void so_rdknl_assert_unlocked(void *);
168 static void so_wrknl_lock(void *);
169 static void so_wrknl_unlock(void *);
170 static void so_wrknl_assert_locked(void *);
171 static void so_wrknl_assert_unlocked(void *);
173 static void filt_sordetach(struct knote *kn);
174 static int filt_soread(struct knote *kn, long hint);
175 static void filt_sowdetach(struct knote *kn);
176 static int filt_sowrite(struct knote *kn, long hint);
177 static int filt_soempty(struct knote *kn, long hint);
178 static int inline hhook_run_socket(struct socket *so, void *hctx, int32_t h_id);
179 fo_kqfilter_t soo_kqfilter;
181 static struct filterops soread_filtops = {
183 .f_detach = filt_sordetach,
184 .f_event = filt_soread,
186 static struct filterops sowrite_filtops = {
188 .f_detach = filt_sowdetach,
189 .f_event = filt_sowrite,
191 static struct filterops soempty_filtops = {
193 .f_detach = filt_sowdetach,
194 .f_event = filt_soempty,
197 so_gen_t so_gencnt; /* generation count for sockets */
199 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
200 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
202 #define VNET_SO_ASSERT(so) \
203 VNET_ASSERT(curvnet != NULL, \
204 ("%s:%d curvnet is NULL, so=%p", __func__, __LINE__, (so)));
206 VNET_DEFINE(struct hhook_head *, socket_hhh[HHOOK_SOCKET_LAST + 1]);
207 #define V_socket_hhh VNET(socket_hhh)
210 * Limit on the number of connections in the listen queue waiting
212 * NB: The original sysctl somaxconn is still available but hidden
213 * to prevent confusion about the actual purpose of this number.
215 static u_int somaxconn = SOMAXCONN;
218 sysctl_somaxconn(SYSCTL_HANDLER_ARGS)
224 error = sysctl_handle_int(oidp, &val, 0, req);
225 if (error || !req->newptr )
229 * The purpose of the UINT_MAX / 3 limit, is so that the formula
231 * below, will not overflow.
234 if (val < 1 || val > UINT_MAX / 3)
240 SYSCTL_PROC(_kern_ipc, OID_AUTO, soacceptqueue, CTLTYPE_UINT | CTLFLAG_RW,
241 0, sizeof(int), sysctl_somaxconn, "I",
242 "Maximum listen socket pending connection accept queue size");
243 SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn,
244 CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_SKIP,
245 0, sizeof(int), sysctl_somaxconn, "I",
246 "Maximum listen socket pending connection accept queue size (compat)");
248 static int numopensockets;
249 SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
250 &numopensockets, 0, "Number of open sockets");
253 * accept_mtx locks down per-socket fields relating to accept queues. See
254 * socketvar.h for an annotation of the protected fields of struct socket.
256 struct mtx accept_mtx;
257 MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
260 * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
263 static struct mtx so_global_mtx;
264 MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
267 * General IPC sysctl name space, used by sockets and a variety of other IPC
270 SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
273 * Initialize the socket subsystem and set up the socket
276 static uma_zone_t socket_zone;
280 socket_zone_change(void *tag)
283 maxsockets = uma_zone_set_max(socket_zone, maxsockets);
287 socket_hhook_register(int subtype)
290 if (hhook_head_register(HHOOK_TYPE_SOCKET, subtype,
291 &V_socket_hhh[subtype],
292 HHOOK_NOWAIT|HHOOK_HEADISINVNET) != 0)
293 printf("%s: WARNING: unable to register hook\n", __func__);
297 socket_hhook_deregister(int subtype)
300 if (hhook_head_deregister(V_socket_hhh[subtype]) != 0)
301 printf("%s: WARNING: unable to deregister hook\n", __func__);
305 socket_init(void *tag)
308 socket_zone = uma_zcreate("socket", sizeof(struct socket), NULL, NULL,
309 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
310 maxsockets = uma_zone_set_max(socket_zone, maxsockets);
311 uma_zone_set_warning(socket_zone, "kern.ipc.maxsockets limit reached");
312 EVENTHANDLER_REGISTER(maxsockets_change, socket_zone_change, NULL,
313 EVENTHANDLER_PRI_FIRST);
315 SYSINIT(socket, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY, socket_init, NULL);
318 socket_vnet_init(const void *unused __unused)
322 /* We expect a contiguous range */
323 for (i = 0; i <= HHOOK_SOCKET_LAST; i++)
324 socket_hhook_register(i);
326 VNET_SYSINIT(socket_vnet_init, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY,
327 socket_vnet_init, NULL);
330 socket_vnet_uninit(const void *unused __unused)
334 for (i = 0; i <= HHOOK_SOCKET_LAST; i++)
335 socket_hhook_deregister(i);
337 VNET_SYSUNINIT(socket_vnet_uninit, SI_SUB_PROTO_DOMAININIT, SI_ORDER_ANY,
338 socket_vnet_uninit, NULL);
341 * Initialise maxsockets. This SYSINIT must be run after
345 init_maxsockets(void *ignored)
348 TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
349 maxsockets = imax(maxsockets, maxfiles);
351 SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);
354 * Sysctl to get and set the maximum global sockets limit. Notify protocols
355 * of the change so that they can update their dependent limits as required.
358 sysctl_maxsockets(SYSCTL_HANDLER_ARGS)
360 int error, newmaxsockets;
362 newmaxsockets = maxsockets;
363 error = sysctl_handle_int(oidp, &newmaxsockets, 0, req);
364 if (error == 0 && req->newptr) {
365 if (newmaxsockets > maxsockets &&
366 newmaxsockets <= maxfiles) {
367 maxsockets = newmaxsockets;
368 EVENTHANDLER_INVOKE(maxsockets_change);
374 SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets, CTLTYPE_INT|CTLFLAG_RW,
375 &maxsockets, 0, sysctl_maxsockets, "IU",
376 "Maximum number of sockets available");
379 * Socket operation routines. These routines are called by the routines in
380 * sys_socket.c or from a system process, and implement the semantics of
381 * socket operations by switching out to the protocol specific routines.
385 * Get a socket structure from our zone, and initialize it. Note that it
386 * would probably be better to allocate socket and PCB at the same time, but
387 * I'm not convinced that all the protocols can be easily modified to do
390 * soalloc() returns a socket with a ref count of 0.
392 static struct socket *
393 soalloc(struct vnet *vnet)
397 so = uma_zalloc(socket_zone, M_NOWAIT | M_ZERO);
401 if (mac_socket_init(so, M_NOWAIT) != 0) {
402 uma_zfree(socket_zone, so);
406 if (khelp_init_osd(HELPER_CLASS_SOCKET, &so->osd)) {
407 uma_zfree(socket_zone, so);
412 * The socket locking protocol allows to lock 2 sockets at a time,
413 * however, the first one must be a listening socket. WITNESS lacks
414 * a feature to change class of an existing lock, so we use DUPOK.
416 mtx_init(&so->so_lock, "socket", NULL, MTX_DEF | MTX_DUPOK);
417 SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
418 SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
419 so->so_rcv.sb_sel = &so->so_rdsel;
420 so->so_snd.sb_sel = &so->so_wrsel;
421 sx_init(&so->so_snd.sb_sx, "so_snd_sx");
422 sx_init(&so->so_rcv.sb_sx, "so_rcv_sx");
423 TAILQ_INIT(&so->so_snd.sb_aiojobq);
424 TAILQ_INIT(&so->so_rcv.sb_aiojobq);
425 TASK_INIT(&so->so_snd.sb_aiotask, 0, soaio_snd, so);
426 TASK_INIT(&so->so_rcv.sb_aiotask, 0, soaio_rcv, so);
428 VNET_ASSERT(vnet != NULL, ("%s:%d vnet is NULL, so=%p",
429 __func__, __LINE__, so));
432 /* We shouldn't need the so_global_mtx */
433 if (hhook_run_socket(so, NULL, HHOOK_SOCKET_CREATE)) {
434 /* Do we need more comprehensive error returns? */
435 uma_zfree(socket_zone, so);
438 mtx_lock(&so_global_mtx);
439 so->so_gencnt = ++so_gencnt;
442 vnet->vnet_sockcnt++;
444 mtx_unlock(&so_global_mtx);
450 * Free the storage associated with a socket at the socket layer, tear down
451 * locks, labels, etc. All protocol state is assumed already to have been
452 * torn down (and possibly never set up) by the caller.
455 sodealloc(struct socket *so)
458 KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
459 KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
461 mtx_lock(&so_global_mtx);
462 so->so_gencnt = ++so_gencnt;
463 --numopensockets; /* Could be below, but faster here. */
465 VNET_ASSERT(so->so_vnet != NULL, ("%s:%d so_vnet is NULL, so=%p",
466 __func__, __LINE__, so));
467 so->so_vnet->vnet_sockcnt--;
469 mtx_unlock(&so_global_mtx);
471 mac_socket_destroy(so);
473 hhook_run_socket(so, NULL, HHOOK_SOCKET_CLOSE);
476 khelp_destroy_osd(&so->osd);
477 if (SOLISTENING(so)) {
478 if (so->sol_accept_filter != NULL)
479 accept_filt_setopt(so, NULL);
481 if (so->so_rcv.sb_hiwat)
482 (void)chgsbsize(so->so_cred->cr_uidinfo,
483 &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
484 if (so->so_snd.sb_hiwat)
485 (void)chgsbsize(so->so_cred->cr_uidinfo,
486 &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
487 sx_destroy(&so->so_snd.sb_sx);
488 sx_destroy(&so->so_rcv.sb_sx);
489 SOCKBUF_LOCK_DESTROY(&so->so_snd);
490 SOCKBUF_LOCK_DESTROY(&so->so_rcv);
492 mtx_destroy(&so->so_lock);
493 uma_zfree(socket_zone, so);
497 * socreate returns a socket with a ref count of 1. The socket should be
498 * closed with soclose().
501 socreate(int dom, struct socket **aso, int type, int proto,
502 struct ucred *cred, struct thread *td)
509 prp = pffindproto(dom, proto, type);
511 prp = pffindtype(dom, type);
514 /* No support for domain. */
515 if (pffinddomain(dom) == NULL)
516 return (EAFNOSUPPORT);
517 /* No support for socket type. */
518 if (proto == 0 && type != 0)
520 return (EPROTONOSUPPORT);
522 if (prp->pr_usrreqs->pru_attach == NULL ||
523 prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
524 return (EPROTONOSUPPORT);
526 if (prison_check_af(cred, prp->pr_domain->dom_family) != 0)
527 return (EPROTONOSUPPORT);
529 if (prp->pr_type != type)
531 so = soalloc(CRED_TO_VNET(cred));
536 so->so_cred = crhold(cred);
537 if ((prp->pr_domain->dom_family == PF_INET) ||
538 (prp->pr_domain->dom_family == PF_INET6) ||
539 (prp->pr_domain->dom_family == PF_ROUTE))
540 so->so_fibnum = td->td_proc->p_fibnum;
545 mac_socket_create(cred, so);
547 knlist_init(&so->so_rdsel.si_note, so, so_rdknl_lock, so_rdknl_unlock,
548 so_rdknl_assert_locked, so_rdknl_assert_unlocked);
549 knlist_init(&so->so_wrsel.si_note, so, so_wrknl_lock, so_wrknl_unlock,
550 so_wrknl_assert_locked, so_wrknl_assert_unlocked);
552 * Auto-sizing of socket buffers is managed by the protocols and
553 * the appropriate flags must be set in the pru_attach function.
555 CURVNET_SET(so->so_vnet);
556 error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
568 static int regression_sonewconn_earlytest = 1;
569 SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW,
570 ®ression_sonewconn_earlytest, 0, "Perform early sonewconn limit test");
574 * When an attempt at a new connection is noted on a socket which accepts
575 * connections, sonewconn is called. If the connection is possible (subject
576 * to space constraints, etc.) then we allocate a new structure, properly
577 * linked into the data structure of the original socket, and return this.
578 * Connstatus may be 0, or SS_ISCONFIRMING, or SS_ISCONNECTED.
580 * Note: the ref count on the socket is 0 on return.
583 sonewconn(struct socket *head, int connstatus)
585 static struct timeval lastover;
586 static struct timeval overinterval = { 60, 0 };
587 static int overcount;
593 over = (head->sol_qlen > 3 * head->sol_qlimit / 2);
594 SOLISTEN_UNLOCK(head);
596 if (regression_sonewconn_earlytest && over) {
602 if (ratecheck(&lastover, &overinterval)) {
603 log(LOG_DEBUG, "%s: pcb %p: Listen queue overflow: "
604 "%i already in queue awaiting acceptance "
605 "(%d occurrences)\n",
606 __func__, head->so_pcb, head->sol_qlen, overcount);
613 VNET_ASSERT(head->so_vnet != NULL, ("%s: so %p vnet is NULL",
615 so = soalloc(head->so_vnet);
617 log(LOG_DEBUG, "%s: pcb %p: New socket allocation failure: "
618 "limit reached or out of memory\n",
619 __func__, head->so_pcb);
622 so->so_listen = head;
623 so->so_type = head->so_type;
624 so->so_linger = head->so_linger;
625 so->so_state = head->so_state | SS_NOFDREF;
626 so->so_fibnum = head->so_fibnum;
627 so->so_proto = head->so_proto;
628 so->so_cred = crhold(head->so_cred);
630 mac_socket_newconn(head, so);
632 knlist_init(&so->so_rdsel.si_note, so, so_rdknl_lock, so_rdknl_unlock,
633 so_rdknl_assert_locked, so_rdknl_assert_unlocked);
634 knlist_init(&so->so_wrsel.si_note, so, so_wrknl_lock, so_wrknl_unlock,
635 so_wrknl_assert_locked, so_wrknl_assert_unlocked);
636 VNET_SO_ASSERT(head);
637 if (soreserve(so, head->sol_sbsnd_hiwat, head->sol_sbrcv_hiwat)) {
639 log(LOG_DEBUG, "%s: pcb %p: soreserve() failed\n",
640 __func__, head->so_pcb);
643 if ((*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
645 log(LOG_DEBUG, "%s: pcb %p: pru_attach() failed\n",
646 __func__, head->so_pcb);
649 so->so_rcv.sb_lowat = head->sol_sbrcv_lowat;
650 so->so_snd.sb_lowat = head->sol_sbsnd_lowat;
651 so->so_rcv.sb_timeo = head->sol_sbrcv_timeo;
652 so->so_snd.sb_timeo = head->sol_sbsnd_timeo;
653 so->so_rcv.sb_flags |= head->sol_sbrcv_flags & SB_AUTOSIZE;
654 so->so_snd.sb_flags |= head->sol_sbsnd_flags & SB_AUTOSIZE;
657 if (head->sol_accept_filter != NULL)
659 so->so_state |= connstatus;
660 so->so_options = head->so_options & ~SO_ACCEPTCONN;
661 soref(head); /* A socket on (in)complete queue refs head. */
663 TAILQ_INSERT_TAIL(&head->sol_comp, so, so_list);
664 so->so_qstate = SQ_COMP;
666 solisten_wakeup(head); /* unlocks */
669 * Keep removing sockets from the head until there's room for
670 * us to insert on the tail. In pre-locking revisions, this
671 * was a simple if(), but as we could be racing with other
672 * threads and soabort() requires dropping locks, we must
673 * loop waiting for the condition to be true.
675 while (head->sol_incqlen > head->sol_qlimit) {
678 sp = TAILQ_FIRST(&head->sol_incomp);
679 TAILQ_REMOVE(&head->sol_incomp, sp, so_list);
682 sp->so_qstate = SQ_NONE;
683 sp->so_listen = NULL;
685 sorele(head); /* does SOLISTEN_UNLOCK, head stays */
689 TAILQ_INSERT_TAIL(&head->sol_incomp, so, so_list);
690 so->so_qstate = SQ_INCOMP;
692 SOLISTEN_UNLOCK(head);
699 * Socket part of sctp_peeloff(). Detach a new socket from an
700 * association. The new socket is returned with a reference.
703 sopeeloff(struct socket *head)
707 VNET_ASSERT(head->so_vnet != NULL, ("%s:%d so_vnet is NULL, head=%p",
708 __func__, __LINE__, head));
709 so = soalloc(head->so_vnet);
711 log(LOG_DEBUG, "%s: pcb %p: New socket allocation failure: "
712 "limit reached or out of memory\n",
713 __func__, head->so_pcb);
716 so->so_type = head->so_type;
717 so->so_options = head->so_options;
718 so->so_linger = head->so_linger;
719 so->so_state = (head->so_state & SS_NBIO) | SS_ISCONNECTED;
720 so->so_fibnum = head->so_fibnum;
721 so->so_proto = head->so_proto;
722 so->so_cred = crhold(head->so_cred);
724 mac_socket_newconn(head, so);
726 knlist_init(&so->so_rdsel.si_note, so, so_rdknl_lock, so_rdknl_unlock,
727 so_rdknl_assert_locked, so_rdknl_assert_unlocked);
728 knlist_init(&so->so_wrsel.si_note, so, so_wrknl_lock, so_wrknl_unlock,
729 so_wrknl_assert_locked, so_wrknl_assert_unlocked);
730 VNET_SO_ASSERT(head);
731 if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat)) {
733 log(LOG_DEBUG, "%s: pcb %p: soreserve() failed\n",
734 __func__, head->so_pcb);
737 if ((*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
739 log(LOG_DEBUG, "%s: pcb %p: pru_attach() failed\n",
740 __func__, head->so_pcb);
743 so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
744 so->so_snd.sb_lowat = head->so_snd.sb_lowat;
745 so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
746 so->so_snd.sb_timeo = head->so_snd.sb_timeo;
747 so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
748 so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
757 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
761 CURVNET_SET(so->so_vnet);
762 error = (*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td);
768 sobindat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
772 CURVNET_SET(so->so_vnet);
773 error = (*so->so_proto->pr_usrreqs->pru_bindat)(fd, so, nam, td);
779 * solisten() transitions a socket from a non-listening state to a listening
780 * state, but can also be used to update the listen queue depth on an
781 * existing listen socket. The protocol will call back into the sockets
782 * layer using solisten_proto_check() and solisten_proto() to check and set
783 * socket-layer listen state. Call backs are used so that the protocol can
784 * acquire both protocol and socket layer locks in whatever order is required
787 * Protocol implementors are advised to hold the socket lock across the
788 * socket-layer test and set to avoid races at the socket layer.
791 solisten(struct socket *so, int backlog, struct thread *td)
795 CURVNET_SET(so->so_vnet);
796 error = (*so->so_proto->pr_usrreqs->pru_listen)(so, backlog, td);
802 solisten_proto_check(struct socket *so)
805 SOCK_LOCK_ASSERT(so);
807 if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
814 solisten_proto(struct socket *so, int backlog)
816 int sbrcv_lowat, sbsnd_lowat;
817 u_int sbrcv_hiwat, sbsnd_hiwat;
818 short sbrcv_flags, sbsnd_flags;
819 sbintime_t sbrcv_timeo, sbsnd_timeo;
821 SOCK_LOCK_ASSERT(so);
827 * Change this socket to listening state.
829 sbrcv_lowat = so->so_rcv.sb_lowat;
830 sbsnd_lowat = so->so_snd.sb_lowat;
831 sbrcv_hiwat = so->so_rcv.sb_hiwat;
832 sbsnd_hiwat = so->so_snd.sb_hiwat;
833 sbrcv_flags = so->so_rcv.sb_flags;
834 sbsnd_flags = so->so_snd.sb_flags;
835 sbrcv_timeo = so->so_rcv.sb_timeo;
836 sbsnd_timeo = so->so_snd.sb_timeo;
838 sbdestroy(&so->so_snd, so);
839 sbdestroy(&so->so_rcv, so);
840 sx_destroy(&so->so_snd.sb_sx);
841 sx_destroy(&so->so_rcv.sb_sx);
842 SOCKBUF_LOCK_DESTROY(&so->so_snd);
843 SOCKBUF_LOCK_DESTROY(&so->so_rcv);
847 sizeof(struct socket) - offsetof(struct socket, so_rcv));
850 so->sol_sbrcv_lowat = sbrcv_lowat;
851 so->sol_sbsnd_lowat = sbsnd_lowat;
852 so->sol_sbrcv_hiwat = sbrcv_hiwat;
853 so->sol_sbsnd_hiwat = sbsnd_hiwat;
854 so->sol_sbrcv_flags = sbrcv_flags;
855 so->sol_sbsnd_flags = sbsnd_flags;
856 so->sol_sbrcv_timeo = sbrcv_timeo;
857 so->sol_sbsnd_timeo = sbsnd_timeo;
859 so->sol_qlen = so->sol_incqlen = 0;
860 TAILQ_INIT(&so->sol_incomp);
861 TAILQ_INIT(&so->sol_comp);
863 so->sol_accept_filter = NULL;
864 so->sol_accept_filter_arg = NULL;
865 so->sol_accept_filter_str = NULL;
867 so->sol_upcall = NULL;
868 so->sol_upcallarg = NULL;
870 so->so_options |= SO_ACCEPTCONN;
873 if (backlog < 0 || backlog > somaxconn)
875 so->sol_qlimit = backlog;
879 * Wakeup listeners/subsystems once we have a complete connection.
880 * Enters with lock, returns unlocked.
883 solisten_wakeup(struct socket *sol)
886 if (sol->sol_upcall != NULL)
887 (void )sol->sol_upcall(sol, sol->sol_upcallarg, M_NOWAIT);
889 selwakeuppri(&sol->so_rdsel, PSOCK);
890 KNOTE_LOCKED(&sol->so_rdsel.si_note, 0);
892 SOLISTEN_UNLOCK(sol);
893 wakeup_one(&sol->sol_comp);
894 if ((sol->so_state & SS_ASYNC) && sol->so_sigio != NULL)
895 pgsigio(&sol->so_sigio, SIGIO, 0);
899 * Return single connection off a listening socket queue. Main consumer of
900 * the function is kern_accept4(). Some modules, that do their own accept
901 * management also use the function.
903 * Listening socket must be locked on entry and is returned unlocked on
905 * The flags argument is set of accept4(2) flags and ACCEPT4_INHERIT.
908 solisten_dequeue(struct socket *head, struct socket **ret, int flags)
913 SOLISTEN_LOCK_ASSERT(head);
915 while (!(head->so_state & SS_NBIO) && TAILQ_EMPTY(&head->sol_comp) &&
916 head->so_error == 0) {
917 error = msleep(&head->sol_comp, &head->so_lock, PSOCK | PCATCH,
920 SOLISTEN_UNLOCK(head);
924 if (head->so_error) {
925 error = head->so_error;
927 } else if ((head->so_state & SS_NBIO) && TAILQ_EMPTY(&head->sol_comp))
932 SOLISTEN_UNLOCK(head);
935 so = TAILQ_FIRST(&head->sol_comp);
937 KASSERT(so->so_qstate == SQ_COMP,
938 ("%s: so %p not SQ_COMP", __func__, so));
941 so->so_qstate = SQ_NONE;
942 so->so_listen = NULL;
943 TAILQ_REMOVE(&head->sol_comp, so, so_list);
944 if (flags & ACCEPT4_INHERIT)
945 so->so_state |= (head->so_state & SS_NBIO);
947 so->so_state |= (flags & SOCK_NONBLOCK) ? SS_NBIO : 0;
956 * Evaluate the reference count and named references on a socket; if no
957 * references remain, free it. This should be called whenever a reference is
958 * released, such as in sorele(), but also when named reference flags are
959 * cleared in socket or protocol code.
961 * sofree() will free the socket if:
963 * - There are no outstanding file descriptor references or related consumers
966 * - The socket has been closed by user space, if ever open (SS_NOFDREF).
968 * - The protocol does not have an outstanding strong reference on the socket
971 * - The socket is not in a completed connection queue, so a process has been
972 * notified that it is present. If it is removed, the user process may
973 * block in accept() despite select() saying the socket was ready.
976 sofree(struct socket *so)
978 struct protosw *pr = so->so_proto;
980 SOCK_LOCK_ASSERT(so);
982 if ((so->so_state & SS_NOFDREF) == 0 || so->so_count != 0 ||
983 (so->so_state & SS_PROTOREF) || (so->so_qstate == SQ_COMP)) {
988 if (!SOLISTENING(so) && so->so_qstate == SQ_INCOMP) {
992 KASSERT(sol, ("%s: so %p on incomp of NULL", __func__, so));
995 * To solve race between close of a listening socket and
996 * a socket on its incomplete queue, we need to lock both.
997 * The order is first listening socket, then regular.
998 * Since we don't have SS_NOFDREF neither SS_PROTOREF, this
999 * function and the listening socket are the only pointers
1000 * to so. To preserve so and sol, we reference both and then
1002 * After relock the socket may not move to so_comp since it
1003 * doesn't have PCB already, but it may be removed from
1004 * so_incomp. If that happens, we share responsiblity on
1005 * freeing the socket, but soclose() has already removed
1013 if (so->so_qstate == SQ_INCOMP) {
1014 KASSERT(so->so_listen == sol,
1015 ("%s: so %p migrated out of sol %p",
1016 __func__, so, sol));
1017 TAILQ_REMOVE(&sol->sol_incomp, so, so_list);
1019 /* This is guarenteed not to be the last. */
1020 refcount_release(&sol->so_count);
1021 so->so_qstate = SQ_NONE;
1022 so->so_listen = NULL;
1024 KASSERT(so->so_listen == NULL,
1025 ("%s: so %p not on (in)comp with so_listen",
1028 KASSERT(so->so_count == 1,
1029 ("%s: so %p count %u", __func__, so, so->so_count));
1032 if (SOLISTENING(so))
1033 so->so_error = ECONNABORTED;
1036 if (so->so_dtor != NULL)
1040 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
1041 (*pr->pr_domain->dom_dispose)(so);
1042 if (pr->pr_usrreqs->pru_detach != NULL)
1043 (*pr->pr_usrreqs->pru_detach)(so);
1046 * From this point on, we assume that no other references to this
1047 * socket exist anywhere else in the stack. Therefore, no locks need
1048 * to be acquired or held.
1050 * We used to do a lot of socket buffer and socket locking here, as
1051 * well as invoke sorflush() and perform wakeups. The direct call to
1052 * dom_dispose() and sbdestroy() are an inlining of what was
1053 * necessary from sorflush().
1055 * Notice that the socket buffer and kqueue state are torn down
1056 * before calling pru_detach. This means that protocols shold not
1057 * assume they can perform socket wakeups, etc, in their detach code.
1059 if (!SOLISTENING(so)) {
1060 sbdestroy(&so->so_snd, so);
1061 sbdestroy(&so->so_rcv, so);
1063 seldrain(&so->so_rdsel);
1064 seldrain(&so->so_wrsel);
1065 knlist_destroy(&so->so_rdsel.si_note);
1066 knlist_destroy(&so->so_wrsel.si_note);
1071 * Close a socket on last file table reference removal. Initiate disconnect
1072 * if connected. Free socket when disconnect complete.
1074 * This function will sorele() the socket. Note that soclose() may be called
1075 * prior to the ref count reaching zero. The actual socket structure will
1076 * not be freed until the ref count reaches zero.
1079 soclose(struct socket *so)
1081 struct accept_queue lqueue;
1085 KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
1087 CURVNET_SET(so->so_vnet);
1088 funsetown(&so->so_sigio);
1089 if (so->so_state & SS_ISCONNECTED) {
1090 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
1091 error = sodisconnect(so);
1093 if (error == ENOTCONN)
1098 if (so->so_options & SO_LINGER) {
1099 if ((so->so_state & SS_ISDISCONNECTING) &&
1100 (so->so_state & SS_NBIO))
1102 while (so->so_state & SS_ISCONNECTED) {
1103 error = tsleep(&so->so_timeo,
1104 PSOCK | PCATCH, "soclos",
1105 so->so_linger * hz);
1113 if (so->so_proto->pr_usrreqs->pru_close != NULL)
1114 (*so->so_proto->pr_usrreqs->pru_close)(so);
1117 if ((listening = (so->so_options & SO_ACCEPTCONN))) {
1120 TAILQ_INIT(&lqueue);
1121 TAILQ_SWAP(&lqueue, &so->sol_incomp, socket, so_list);
1122 TAILQ_CONCAT(&lqueue, &so->sol_comp, so_list);
1124 so->sol_qlen = so->sol_incqlen = 0;
1126 TAILQ_FOREACH(sp, &lqueue, so_list) {
1128 sp->so_qstate = SQ_NONE;
1129 sp->so_listen = NULL;
1131 /* Guaranteed not to be the last. */
1132 refcount_release(&so->so_count);
1135 KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
1136 so->so_state |= SS_NOFDREF;
1139 struct socket *sp, *tsp;
1141 TAILQ_FOREACH_SAFE(sp, &lqueue, so_list, tsp) {
1143 if (sp->so_count == 0) {
1147 /* sp is now in sofree() */
1156 * soabort() is used to abruptly tear down a connection, such as when a
1157 * resource limit is reached (listen queue depth exceeded), or if a listen
1158 * socket is closed while there are sockets waiting to be accepted.
1160 * This interface is tricky, because it is called on an unreferenced socket,
1161 * and must be called only by a thread that has actually removed the socket
1162 * from the listen queue it was on, or races with other threads are risked.
1164 * This interface will call into the protocol code, so must not be called
1165 * with any socket locks held. Protocols do call it while holding their own
1166 * recursible protocol mutexes, but this is something that should be subject
1167 * to review in the future.
1170 soabort(struct socket *so)
1174 * In as much as is possible, assert that no references to this
1175 * socket are held. This is not quite the same as asserting that the
1176 * current thread is responsible for arranging for no references, but
1177 * is as close as we can get for now.
1179 KASSERT(so->so_count == 0, ("soabort: so_count"));
1180 KASSERT((so->so_state & SS_PROTOREF) == 0, ("soabort: SS_PROTOREF"));
1181 KASSERT(so->so_state & SS_NOFDREF, ("soabort: !SS_NOFDREF"));
1184 if (so->so_proto->pr_usrreqs->pru_abort != NULL)
1185 (*so->so_proto->pr_usrreqs->pru_abort)(so);
1191 soaccept(struct socket *so, struct sockaddr **nam)
1196 KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
1197 so->so_state &= ~SS_NOFDREF;
1200 CURVNET_SET(so->so_vnet);
1201 error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
1207 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
1210 return (soconnectat(AT_FDCWD, so, nam, td));
1214 soconnectat(int fd, struct socket *so, struct sockaddr *nam, struct thread *td)
1218 if (so->so_options & SO_ACCEPTCONN)
1219 return (EOPNOTSUPP);
1221 CURVNET_SET(so->so_vnet);
1223 * If protocol is connection-based, can only connect once.
1224 * Otherwise, if connected, try to disconnect first. This allows
1225 * user to disconnect by connecting to, e.g., a null address.
1227 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
1228 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
1229 (error = sodisconnect(so)))) {
1233 * Prevent accumulated error from previous connection from
1237 if (fd == AT_FDCWD) {
1238 error = (*so->so_proto->pr_usrreqs->pru_connect)(so,
1241 error = (*so->so_proto->pr_usrreqs->pru_connectat)(fd,
1251 soconnect2(struct socket *so1, struct socket *so2)
1255 CURVNET_SET(so1->so_vnet);
1256 error = (*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2);
1262 sodisconnect(struct socket *so)
1266 if ((so->so_state & SS_ISCONNECTED) == 0)
1268 if (so->so_state & SS_ISDISCONNECTING)
1271 error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
1275 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? 0 : SBL_WAIT)
1278 sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
1279 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1283 int clen = 0, error, dontroute;
1285 KASSERT(so->so_type == SOCK_DGRAM, ("sosend_dgram: !SOCK_DGRAM"));
1286 KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
1287 ("sosend_dgram: !PR_ATOMIC"));
1290 resid = uio->uio_resid;
1292 resid = top->m_pkthdr.len;
1294 * In theory resid should be unsigned. However, space must be
1295 * signed, as it might be less than 0 if we over-committed, and we
1296 * must use a signed comparison of space and resid. On the other
1297 * hand, a negative resid causes us to loop sending 0-length
1298 * segments to the protocol.
1306 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
1308 td->td_ru.ru_msgsnd++;
1309 if (control != NULL)
1310 clen = control->m_len;
1312 SOCKBUF_LOCK(&so->so_snd);
1313 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1314 SOCKBUF_UNLOCK(&so->so_snd);
1319 error = so->so_error;
1321 SOCKBUF_UNLOCK(&so->so_snd);
1324 if ((so->so_state & SS_ISCONNECTED) == 0) {
1326 * `sendto' and `sendmsg' is allowed on a connection-based
1327 * socket if it supports implied connect. Return ENOTCONN if
1328 * not connected and no address is supplied.
1330 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1331 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1332 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1333 !(resid == 0 && clen != 0)) {
1334 SOCKBUF_UNLOCK(&so->so_snd);
1338 } else if (addr == NULL) {
1339 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1342 error = EDESTADDRREQ;
1343 SOCKBUF_UNLOCK(&so->so_snd);
1349 * Do we need MSG_OOB support in SOCK_DGRAM? Signs here may be a
1350 * problem and need fixing.
1352 space = sbspace(&so->so_snd);
1353 if (flags & MSG_OOB)
1356 SOCKBUF_UNLOCK(&so->so_snd);
1357 if (resid > space) {
1363 if (flags & MSG_EOR)
1364 top->m_flags |= M_EOR;
1367 * Copy the data from userland into a mbuf chain.
1368 * If no data is to be copied in, a single empty mbuf
1371 top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
1372 (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
1374 error = EFAULT; /* only possible error */
1377 space -= resid - uio->uio_resid;
1378 resid = uio->uio_resid;
1380 KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
1382 * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
1387 so->so_options |= SO_DONTROUTE;
1391 * XXX all the SBS_CANTSENDMORE checks previously done could be out
1392 * of date. We could have received a reset packet in an interrupt or
1393 * maybe we slept while doing page faults in uiomove() etc. We could
1394 * probably recheck again inside the locking protection here, but
1395 * there are probably other places that this also happens. We must
1399 error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1400 (flags & MSG_OOB) ? PRUS_OOB :
1402 * If the user set MSG_EOF, the protocol understands this flag and
1403 * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
1405 ((flags & MSG_EOF) &&
1406 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1409 /* If there is more to send set PRUS_MORETOCOME */
1410 (flags & MSG_MORETOCOME) ||
1411 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
1412 top, addr, control, td);
1415 so->so_options &= ~SO_DONTROUTE;
1424 if (control != NULL)
1430 * Send on a socket. If send must go all at once and message is larger than
1431 * send buffering, then hard error. Lock against other senders. If must go
1432 * all at once and not enough room now, then inform user that this would
1433 * block and do nothing. Otherwise, if nonblocking, send as much as
1434 * possible. The data to be sent is described by "uio" if nonzero, otherwise
1435 * by the mbuf chain "top" (which must be null if uio is not). Data provided
1436 * in mbuf chain must be small enough to send all at once.
1438 * Returns nonzero on error, timeout or signal; callers must check for short
1439 * counts if EINTR/ERESTART are returned. Data and control buffers are freed
1443 sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
1444 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1448 int clen = 0, error, dontroute;
1449 int atomic = sosendallatonce(so) || top;
1452 struct ktls_session *tls;
1453 int tls_enq_cnt, tls_pruflag;
1457 tls_rtype = TLS_RLTYPE_APP;
1460 resid = uio->uio_resid;
1462 resid = top->m_pkthdr.len;
1464 * In theory resid should be unsigned. However, space must be
1465 * signed, as it might be less than 0 if we over-committed, and we
1466 * must use a signed comparison of space and resid. On the other
1467 * hand, a negative resid causes us to loop sending 0-length
1468 * segments to the protocol.
1470 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
1471 * type sockets since that's an error.
1473 if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
1479 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
1480 (so->so_proto->pr_flags & PR_ATOMIC);
1482 td->td_ru.ru_msgsnd++;
1483 if (control != NULL)
1484 clen = control->m_len;
1486 error = sblock(&so->so_snd, SBLOCKWAIT(flags));
1492 tls = ktls_hold(so->so_snd.sb_tls_info);
1494 if (tls->sw_encrypt != NULL)
1495 tls_pruflag = PRUS_NOTREADY;
1497 if (control != NULL) {
1498 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1500 if (clen >= sizeof(*cm) &&
1501 cm->cmsg_type == TLS_SET_RECORD_TYPE) {
1502 tls_rtype = *((uint8_t *)CMSG_DATA(cm));
1514 SOCKBUF_LOCK(&so->so_snd);
1515 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
1516 SOCKBUF_UNLOCK(&so->so_snd);
1521 error = so->so_error;
1523 SOCKBUF_UNLOCK(&so->so_snd);
1526 if ((so->so_state & SS_ISCONNECTED) == 0) {
1528 * `sendto' and `sendmsg' is allowed on a connection-
1529 * based socket if it supports implied connect.
1530 * Return ENOTCONN if not connected and no address is
1533 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
1534 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
1535 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
1536 !(resid == 0 && clen != 0)) {
1537 SOCKBUF_UNLOCK(&so->so_snd);
1541 } else if (addr == NULL) {
1542 SOCKBUF_UNLOCK(&so->so_snd);
1543 if (so->so_proto->pr_flags & PR_CONNREQUIRED)
1546 error = EDESTADDRREQ;
1550 space = sbspace(&so->so_snd);
1551 if (flags & MSG_OOB)
1553 if ((atomic && resid > so->so_snd.sb_hiwat) ||
1554 clen > so->so_snd.sb_hiwat) {
1555 SOCKBUF_UNLOCK(&so->so_snd);
1559 if (space < resid + clen &&
1560 (atomic || space < so->so_snd.sb_lowat || space < clen)) {
1561 if ((so->so_state & SS_NBIO) ||
1562 (flags & (MSG_NBIO | MSG_DONTWAIT)) != 0) {
1563 SOCKBUF_UNLOCK(&so->so_snd);
1564 error = EWOULDBLOCK;
1567 error = sbwait(&so->so_snd);
1568 SOCKBUF_UNLOCK(&so->so_snd);
1573 SOCKBUF_UNLOCK(&so->so_snd);
1578 if (flags & MSG_EOR)
1579 top->m_flags |= M_EOR;
1582 * Copy the data from userland into a mbuf
1583 * chain. If resid is 0, which can happen
1584 * only if we have control to send, then
1585 * a single empty mbuf is returned. This
1586 * is a workaround to prevent protocol send
1591 top = m_uiotombuf(uio, M_WAITOK, space,
1592 tls->params.max_frame_len,
1594 ((flags & MSG_EOR) ? M_EOR : 0));
1596 error = ktls_frame(top, tls,
1597 &tls_enq_cnt, tls_rtype);
1603 tls_rtype = TLS_RLTYPE_APP;
1606 top = m_uiotombuf(uio, M_WAITOK, space,
1607 (atomic ? max_hdr : 0),
1608 (atomic ? M_PKTHDR : 0) |
1609 ((flags & MSG_EOR) ? M_EOR : 0));
1611 error = EFAULT; /* only possible error */
1614 space -= resid - uio->uio_resid;
1615 resid = uio->uio_resid;
1619 so->so_options |= SO_DONTROUTE;
1623 * XXX all the SBS_CANTSENDMORE checks previously
1624 * done could be out of date. We could have received
1625 * a reset packet in an interrupt or maybe we slept
1626 * while doing page faults in uiomove() etc. We
1627 * could probably recheck again inside the locking
1628 * protection here, but there are probably other
1629 * places that this also happens. We must rethink
1634 pru_flag = (flags & MSG_OOB) ? PRUS_OOB :
1636 * If the user set MSG_EOF, the protocol understands
1637 * this flag and nothing left to send then use
1638 * PRU_SEND_EOF instead of PRU_SEND.
1640 ((flags & MSG_EOF) &&
1641 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
1644 /* If there is more to send set PRUS_MORETOCOME. */
1645 (flags & MSG_MORETOCOME) ||
1646 (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0;
1649 pru_flag |= tls_pruflag;
1652 error = (*so->so_proto->pr_usrreqs->pru_send)(so,
1653 pru_flag, top, addr, control, td);
1657 so->so_options &= ~SO_DONTROUTE;
1662 if (tls != NULL && tls->sw_encrypt != NULL) {
1664 * Note that error is intentionally
1667 * Like sendfile(), we rely on the
1668 * completion routine (pru_ready())
1669 * to free the mbufs in the event that
1670 * pru_send() encountered an error and
1671 * did not append them to the sockbuf.
1674 ktls_enqueue(top, so, tls_enq_cnt);
1682 } while (resid && space > 0);
1686 sbunlock(&so->so_snd);
1694 if (control != NULL)
1700 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
1701 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
1705 CURVNET_SET(so->so_vnet);
1706 if (!SOLISTENING(so))
1707 error = so->so_proto->pr_usrreqs->pru_sosend(so, addr, uio,
1708 top, control, flags, td);
1719 * The part of soreceive() that implements reading non-inline out-of-band
1720 * data from a socket. For more complete comments, see soreceive(), from
1721 * which this code originated.
1723 * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
1724 * unable to return an mbuf chain to the caller.
1727 soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
1729 struct protosw *pr = so->so_proto;
1733 KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
1736 m = m_get(M_WAITOK, MT_DATA);
1737 error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
1741 error = uiomove(mtod(m, void *),
1742 (int) min(uio->uio_resid, m->m_len), uio);
1744 } while (uio->uio_resid && error == 0 && m);
1752 * Following replacement or removal of the first mbuf on the first mbuf chain
1753 * of a socket buffer, push necessary state changes back into the socket
1754 * buffer so that other consumers see the values consistently. 'nextrecord'
1755 * is the callers locally stored value of the original value of
1756 * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
1757 * NOTE: 'nextrecord' may be NULL.
1759 static __inline void
1760 sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
1763 SOCKBUF_LOCK_ASSERT(sb);
1765 * First, update for the new value of nextrecord. If necessary, make
1766 * it the first record.
1768 if (sb->sb_mb != NULL)
1769 sb->sb_mb->m_nextpkt = nextrecord;
1771 sb->sb_mb = nextrecord;
1774 * Now update any dependent socket buffer fields to reflect the new
1775 * state. This is an expanded inline of SB_EMPTY_FIXUP(), with the
1776 * addition of a second clause that takes care of the case where
1777 * sb_mb has been updated, but remains the last record.
1779 if (sb->sb_mb == NULL) {
1780 sb->sb_mbtail = NULL;
1781 sb->sb_lastrecord = NULL;
1782 } else if (sb->sb_mb->m_nextpkt == NULL)
1783 sb->sb_lastrecord = sb->sb_mb;
1787 * Implement receive operations on a socket. We depend on the way that
1788 * records are added to the sockbuf by sbappend. In particular, each record
1789 * (mbufs linked through m_next) must begin with an address if the protocol
1790 * so specifies, followed by an optional mbuf or mbufs containing ancillary
1791 * data, and then zero or more mbufs of data. In order to allow parallelism
1792 * between network receive and copying to user space, as well as avoid
1793 * sleeping with a mutex held, we release the socket buffer mutex during the
1794 * user space copy. Although the sockbuf is locked, new data may still be
1795 * appended, and thus we must maintain consistency of the sockbuf during that
1798 * The caller may receive the data as a single mbuf chain by supplying an
1799 * mbuf **mp0 for use in returning the chain. The uio is then used only for
1800 * the count in uio_resid.
1803 soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
1804 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1806 struct mbuf *m, **mp;
1807 int flags, error, offset;
1809 struct protosw *pr = so->so_proto;
1810 struct mbuf *nextrecord;
1812 ssize_t orig_resid = uio->uio_resid;
1817 if (controlp != NULL)
1820 flags = *flagsp &~ MSG_EOR;
1823 if (flags & MSG_OOB)
1824 return (soreceive_rcvoob(so, uio, flags));
1827 if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
1828 && uio->uio_resid) {
1830 (*pr->pr_usrreqs->pru_rcvd)(so, 0);
1833 error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
1838 SOCKBUF_LOCK(&so->so_rcv);
1839 m = so->so_rcv.sb_mb;
1841 * If we have less data than requested, block awaiting more (subject
1842 * to any timeout) if:
1843 * 1. the current count is less than the low water mark, or
1844 * 2. MSG_DONTWAIT is not set
1846 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
1847 sbavail(&so->so_rcv) < uio->uio_resid) &&
1848 sbavail(&so->so_rcv) < so->so_rcv.sb_lowat &&
1849 m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
1850 KASSERT(m != NULL || !sbavail(&so->so_rcv),
1851 ("receive: m == %p sbavail == %u",
1852 m, sbavail(&so->so_rcv)));
1856 error = so->so_error;
1857 if ((flags & MSG_PEEK) == 0)
1859 SOCKBUF_UNLOCK(&so->so_rcv);
1862 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1863 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1865 SOCKBUF_UNLOCK(&so->so_rcv);
1870 for (; m != NULL; m = m->m_next)
1871 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
1872 m = so->so_rcv.sb_mb;
1875 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
1876 (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
1877 SOCKBUF_UNLOCK(&so->so_rcv);
1881 if (uio->uio_resid == 0) {
1882 SOCKBUF_UNLOCK(&so->so_rcv);
1885 if ((so->so_state & SS_NBIO) ||
1886 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
1887 SOCKBUF_UNLOCK(&so->so_rcv);
1888 error = EWOULDBLOCK;
1891 SBLASTRECORDCHK(&so->so_rcv);
1892 SBLASTMBUFCHK(&so->so_rcv);
1893 error = sbwait(&so->so_rcv);
1894 SOCKBUF_UNLOCK(&so->so_rcv);
1901 * From this point onward, we maintain 'nextrecord' as a cache of the
1902 * pointer to the next record in the socket buffer. We must keep the
1903 * various socket buffer pointers and local stack versions of the
1904 * pointers in sync, pushing out modifications before dropping the
1905 * socket buffer mutex, and re-reading them when picking it up.
1907 * Otherwise, we will race with the network stack appending new data
1908 * or records onto the socket buffer by using inconsistent/stale
1909 * versions of the field, possibly resulting in socket buffer
1912 * By holding the high-level sblock(), we prevent simultaneous
1913 * readers from pulling off the front of the socket buffer.
1915 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1917 uio->uio_td->td_ru.ru_msgrcv++;
1918 KASSERT(m == so->so_rcv.sb_mb, ("soreceive: m != so->so_rcv.sb_mb"));
1919 SBLASTRECORDCHK(&so->so_rcv);
1920 SBLASTMBUFCHK(&so->so_rcv);
1921 nextrecord = m->m_nextpkt;
1922 if (pr->pr_flags & PR_ADDR) {
1923 KASSERT(m->m_type == MT_SONAME,
1924 ("m->m_type == %d", m->m_type));
1927 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
1929 if (flags & MSG_PEEK) {
1932 sbfree(&so->so_rcv, m);
1933 so->so_rcv.sb_mb = m_free(m);
1934 m = so->so_rcv.sb_mb;
1935 sockbuf_pushsync(&so->so_rcv, nextrecord);
1940 * Process one or more MT_CONTROL mbufs present before any data mbufs
1941 * in the first mbuf chain on the socket buffer. If MSG_PEEK, we
1942 * just copy the data; if !MSG_PEEK, we call into the protocol to
1943 * perform externalization (or freeing if controlp == NULL).
1945 if (m != NULL && m->m_type == MT_CONTROL) {
1946 struct mbuf *cm = NULL, *cmn;
1947 struct mbuf **cme = &cm;
1950 if (flags & MSG_PEEK) {
1951 if (controlp != NULL) {
1952 *controlp = m_copym(m, 0, m->m_len,
1954 controlp = &(*controlp)->m_next;
1958 sbfree(&so->so_rcv, m);
1959 so->so_rcv.sb_mb = m->m_next;
1962 cme = &(*cme)->m_next;
1963 m = so->so_rcv.sb_mb;
1965 } while (m != NULL && m->m_type == MT_CONTROL);
1966 if ((flags & MSG_PEEK) == 0)
1967 sockbuf_pushsync(&so->so_rcv, nextrecord);
1968 while (cm != NULL) {
1971 if (pr->pr_domain->dom_externalize != NULL) {
1972 SOCKBUF_UNLOCK(&so->so_rcv);
1974 error = (*pr->pr_domain->dom_externalize)
1975 (cm, controlp, flags);
1976 SOCKBUF_LOCK(&so->so_rcv);
1977 } else if (controlp != NULL)
1981 if (controlp != NULL) {
1983 while (*controlp != NULL)
1984 controlp = &(*controlp)->m_next;
1989 nextrecord = so->so_rcv.sb_mb->m_nextpkt;
1991 nextrecord = so->so_rcv.sb_mb;
1995 if ((flags & MSG_PEEK) == 0) {
1996 KASSERT(m->m_nextpkt == nextrecord,
1997 ("soreceive: post-control, nextrecord !sync"));
1998 if (nextrecord == NULL) {
1999 KASSERT(so->so_rcv.sb_mb == m,
2000 ("soreceive: post-control, sb_mb!=m"));
2001 KASSERT(so->so_rcv.sb_lastrecord == m,
2002 ("soreceive: post-control, lastrecord!=m"));
2006 if (type == MT_OOBDATA)
2009 if ((flags & MSG_PEEK) == 0) {
2010 KASSERT(so->so_rcv.sb_mb == nextrecord,
2011 ("soreceive: sb_mb != nextrecord"));
2012 if (so->so_rcv.sb_mb == NULL) {
2013 KASSERT(so->so_rcv.sb_lastrecord == NULL,
2014 ("soreceive: sb_lastercord != NULL"));
2018 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2019 SBLASTRECORDCHK(&so->so_rcv);
2020 SBLASTMBUFCHK(&so->so_rcv);
2023 * Now continue to read any data mbufs off of the head of the socket
2024 * buffer until the read request is satisfied. Note that 'type' is
2025 * used to store the type of any mbuf reads that have happened so far
2026 * such that soreceive() can stop reading if the type changes, which
2027 * causes soreceive() to return only one of regular data and inline
2028 * out-of-band data in a single socket receive operation.
2032 while (m != NULL && !(m->m_flags & M_NOTAVAIL) && uio->uio_resid > 0
2035 * If the type of mbuf has changed since the last mbuf
2036 * examined ('type'), end the receive operation.
2038 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2039 if (m->m_type == MT_OOBDATA || m->m_type == MT_CONTROL) {
2040 if (type != m->m_type)
2042 } else if (type == MT_OOBDATA)
2045 KASSERT(m->m_type == MT_DATA,
2046 ("m->m_type == %d", m->m_type));
2047 so->so_rcv.sb_state &= ~SBS_RCVATMARK;
2048 len = uio->uio_resid;
2049 if (so->so_oobmark && len > so->so_oobmark - offset)
2050 len = so->so_oobmark - offset;
2051 if (len > m->m_len - moff)
2052 len = m->m_len - moff;
2054 * If mp is set, just pass back the mbufs. Otherwise copy
2055 * them out via the uio, then free. Sockbuf must be
2056 * consistent here (points to current mbuf, it points to next
2057 * record) when we drop priority; we must note any additions
2058 * to the sockbuf when we block interrupts again.
2061 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2062 SBLASTRECORDCHK(&so->so_rcv);
2063 SBLASTMBUFCHK(&so->so_rcv);
2064 SOCKBUF_UNLOCK(&so->so_rcv);
2065 if ((m->m_flags & M_NOMAP) != 0)
2066 error = m_unmappedtouio(m, moff, uio, (int)len);
2068 error = uiomove(mtod(m, char *) + moff,
2070 SOCKBUF_LOCK(&so->so_rcv);
2073 * The MT_SONAME mbuf has already been removed
2074 * from the record, so it is necessary to
2075 * remove the data mbufs, if any, to preserve
2076 * the invariant in the case of PR_ADDR that
2077 * requires MT_SONAME mbufs at the head of
2080 if (pr->pr_flags & PR_ATOMIC &&
2081 ((flags & MSG_PEEK) == 0))
2082 (void)sbdroprecord_locked(&so->so_rcv);
2083 SOCKBUF_UNLOCK(&so->so_rcv);
2087 uio->uio_resid -= len;
2088 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2089 if (len == m->m_len - moff) {
2090 if (m->m_flags & M_EOR)
2092 if (flags & MSG_PEEK) {
2096 nextrecord = m->m_nextpkt;
2097 sbfree(&so->so_rcv, m);
2099 m->m_nextpkt = NULL;
2102 so->so_rcv.sb_mb = m = m->m_next;
2105 so->so_rcv.sb_mb = m_free(m);
2106 m = so->so_rcv.sb_mb;
2108 sockbuf_pushsync(&so->so_rcv, nextrecord);
2109 SBLASTRECORDCHK(&so->so_rcv);
2110 SBLASTMBUFCHK(&so->so_rcv);
2113 if (flags & MSG_PEEK)
2117 if (flags & MSG_DONTWAIT) {
2118 *mp = m_copym(m, 0, len,
2122 * m_copym() couldn't
2124 * Adjust uio_resid back
2126 * down by len bytes,
2127 * which we didn't end
2128 * up "copying" over).
2130 uio->uio_resid += len;
2134 SOCKBUF_UNLOCK(&so->so_rcv);
2135 *mp = m_copym(m, 0, len,
2137 SOCKBUF_LOCK(&so->so_rcv);
2140 sbcut_locked(&so->so_rcv, len);
2143 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2144 if (so->so_oobmark) {
2145 if ((flags & MSG_PEEK) == 0) {
2146 so->so_oobmark -= len;
2147 if (so->so_oobmark == 0) {
2148 so->so_rcv.sb_state |= SBS_RCVATMARK;
2153 if (offset == so->so_oobmark)
2157 if (flags & MSG_EOR)
2160 * If the MSG_WAITALL flag is set (for non-atomic socket), we
2161 * must not quit until "uio->uio_resid == 0" or an error
2162 * termination. If a signal/timeout occurs, return with a
2163 * short count but without error. Keep sockbuf locked
2164 * against other readers.
2166 while (flags & MSG_WAITALL && m == NULL && uio->uio_resid > 0 &&
2167 !sosendallatonce(so) && nextrecord == NULL) {
2168 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2170 so->so_rcv.sb_state & SBS_CANTRCVMORE)
2173 * Notify the protocol that some data has been
2174 * drained before blocking.
2176 if (pr->pr_flags & PR_WANTRCVD) {
2177 SOCKBUF_UNLOCK(&so->so_rcv);
2179 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
2180 SOCKBUF_LOCK(&so->so_rcv);
2182 SBLASTRECORDCHK(&so->so_rcv);
2183 SBLASTMBUFCHK(&so->so_rcv);
2185 * We could receive some data while was notifying
2186 * the protocol. Skip blocking in this case.
2188 if (so->so_rcv.sb_mb == NULL) {
2189 error = sbwait(&so->so_rcv);
2191 SOCKBUF_UNLOCK(&so->so_rcv);
2195 m = so->so_rcv.sb_mb;
2197 nextrecord = m->m_nextpkt;
2201 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2202 if (m != NULL && pr->pr_flags & PR_ATOMIC) {
2204 if ((flags & MSG_PEEK) == 0)
2205 (void) sbdroprecord_locked(&so->so_rcv);
2207 if ((flags & MSG_PEEK) == 0) {
2210 * First part is an inline SB_EMPTY_FIXUP(). Second
2211 * part makes sure sb_lastrecord is up-to-date if
2212 * there is still data in the socket buffer.
2214 so->so_rcv.sb_mb = nextrecord;
2215 if (so->so_rcv.sb_mb == NULL) {
2216 so->so_rcv.sb_mbtail = NULL;
2217 so->so_rcv.sb_lastrecord = NULL;
2218 } else if (nextrecord->m_nextpkt == NULL)
2219 so->so_rcv.sb_lastrecord = nextrecord;
2221 SBLASTRECORDCHK(&so->so_rcv);
2222 SBLASTMBUFCHK(&so->so_rcv);
2224 * If soreceive() is being done from the socket callback,
2225 * then don't need to generate ACK to peer to update window,
2226 * since ACK will be generated on return to TCP.
2228 if (!(flags & MSG_SOCALLBCK) &&
2229 (pr->pr_flags & PR_WANTRCVD)) {
2230 SOCKBUF_UNLOCK(&so->so_rcv);
2232 (*pr->pr_usrreqs->pru_rcvd)(so, flags);
2233 SOCKBUF_LOCK(&so->so_rcv);
2236 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2237 if (orig_resid == uio->uio_resid && orig_resid &&
2238 (flags & MSG_EOR) == 0 && (so->so_rcv.sb_state & SBS_CANTRCVMORE) == 0) {
2239 SOCKBUF_UNLOCK(&so->so_rcv);
2242 SOCKBUF_UNLOCK(&so->so_rcv);
2247 sbunlock(&so->so_rcv);
2252 * Optimized version of soreceive() for stream (TCP) sockets.
2255 soreceive_stream(struct socket *so, struct sockaddr **psa, struct uio *uio,
2256 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2258 int len = 0, error = 0, flags, oresid;
2260 struct mbuf *m, *n = NULL;
2262 /* We only do stream sockets. */
2263 if (so->so_type != SOCK_STREAM)
2268 flags = *flagsp &~ MSG_EOR;
2271 if (controlp != NULL)
2273 if (flags & MSG_OOB)
2274 return (soreceive_rcvoob(so, uio, flags));
2280 /* Prevent other readers from entering the socket. */
2281 error = sblock(sb, SBLOCKWAIT(flags));
2286 /* Easy one, no space to copyout anything. */
2287 if (uio->uio_resid == 0) {
2291 oresid = uio->uio_resid;
2293 /* We will never ever get anything unless we are or were connected. */
2294 if (!(so->so_state & (SS_ISCONNECTED|SS_ISDISCONNECTED))) {
2300 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2302 /* Abort if socket has reported problems. */
2304 if (sbavail(sb) > 0)
2306 if (oresid > uio->uio_resid)
2308 error = so->so_error;
2309 if (!(flags & MSG_PEEK))
2314 /* Door is closed. Deliver what is left, if any. */
2315 if (sb->sb_state & SBS_CANTRCVMORE) {
2316 if (sbavail(sb) > 0)
2322 /* Socket buffer is empty and we shall not block. */
2323 if (sbavail(sb) == 0 &&
2324 ((so->so_state & SS_NBIO) || (flags & (MSG_DONTWAIT|MSG_NBIO)))) {
2329 /* Socket buffer got some data that we shall deliver now. */
2330 if (sbavail(sb) > 0 && !(flags & MSG_WAITALL) &&
2331 ((so->so_state & SS_NBIO) ||
2332 (flags & (MSG_DONTWAIT|MSG_NBIO)) ||
2333 sbavail(sb) >= sb->sb_lowat ||
2334 sbavail(sb) >= uio->uio_resid ||
2335 sbavail(sb) >= sb->sb_hiwat) ) {
2339 /* On MSG_WAITALL we must wait until all data or error arrives. */
2340 if ((flags & MSG_WAITALL) &&
2341 (sbavail(sb) >= uio->uio_resid || sbavail(sb) >= sb->sb_hiwat))
2345 * Wait and block until (more) data comes in.
2346 * NB: Drops the sockbuf lock during wait.
2354 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2355 KASSERT(sbavail(sb) > 0, ("%s: sockbuf empty", __func__));
2356 KASSERT(sb->sb_mb != NULL, ("%s: sb_mb == NULL", __func__));
2360 uio->uio_td->td_ru.ru_msgrcv++;
2362 /* Fill uio until full or current end of socket buffer is reached. */
2363 len = min(uio->uio_resid, sbavail(sb));
2365 /* Dequeue as many mbufs as possible. */
2366 if (!(flags & MSG_PEEK) && len >= sb->sb_mb->m_len) {
2370 m_cat(*mp0, sb->sb_mb);
2372 m != NULL && m->m_len <= len;
2374 KASSERT(!(m->m_flags & M_NOTAVAIL),
2375 ("%s: m %p not available", __func__, m));
2377 uio->uio_resid -= m->m_len;
2383 sb->sb_lastrecord = sb->sb_mb;
2384 if (sb->sb_mb == NULL)
2387 /* Copy the remainder. */
2389 KASSERT(sb->sb_mb != NULL,
2390 ("%s: len > 0 && sb->sb_mb empty", __func__));
2392 m = m_copym(sb->sb_mb, 0, len, M_NOWAIT);
2394 len = 0; /* Don't flush data from sockbuf. */
2396 uio->uio_resid -= len;
2407 /* NB: Must unlock socket buffer as uiomove may sleep. */
2409 error = m_mbuftouio(uio, sb->sb_mb, len);
2414 SBLASTRECORDCHK(sb);
2418 * Remove the delivered data from the socket buffer unless we
2419 * were only peeking.
2421 if (!(flags & MSG_PEEK)) {
2423 sbdrop_locked(sb, len);
2425 /* Notify protocol that we drained some data. */
2426 if ((so->so_proto->pr_flags & PR_WANTRCVD) &&
2427 (((flags & MSG_WAITALL) && uio->uio_resid > 0) ||
2428 !(flags & MSG_SOCALLBCK))) {
2431 (*so->so_proto->pr_usrreqs->pru_rcvd)(so, flags);
2437 * For MSG_WAITALL we may have to loop again and wait for
2438 * more data to come in.
2440 if ((flags & MSG_WAITALL) && uio->uio_resid > 0)
2443 SOCKBUF_LOCK_ASSERT(sb);
2444 SBLASTRECORDCHK(sb);
2452 * Optimized version of soreceive() for simple datagram cases from userspace.
2453 * Unlike in the stream case, we're able to drop a datagram if copyout()
2454 * fails, and because we handle datagrams atomically, we don't need to use a
2455 * sleep lock to prevent I/O interlacing.
2458 soreceive_dgram(struct socket *so, struct sockaddr **psa, struct uio *uio,
2459 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2461 struct mbuf *m, *m2;
2464 struct protosw *pr = so->so_proto;
2465 struct mbuf *nextrecord;
2469 if (controlp != NULL)
2472 flags = *flagsp &~ MSG_EOR;
2477 * For any complicated cases, fall back to the full
2478 * soreceive_generic().
2480 if (mp0 != NULL || (flags & MSG_PEEK) || (flags & MSG_OOB))
2481 return (soreceive_generic(so, psa, uio, mp0, controlp,
2485 * Enforce restrictions on use.
2487 KASSERT((pr->pr_flags & PR_WANTRCVD) == 0,
2488 ("soreceive_dgram: wantrcvd"));
2489 KASSERT(pr->pr_flags & PR_ATOMIC, ("soreceive_dgram: !atomic"));
2490 KASSERT((so->so_rcv.sb_state & SBS_RCVATMARK) == 0,
2491 ("soreceive_dgram: SBS_RCVATMARK"));
2492 KASSERT((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0,
2493 ("soreceive_dgram: P_CONNREQUIRED"));
2496 * Loop blocking while waiting for a datagram.
2498 SOCKBUF_LOCK(&so->so_rcv);
2499 while ((m = so->so_rcv.sb_mb) == NULL) {
2500 KASSERT(sbavail(&so->so_rcv) == 0,
2501 ("soreceive_dgram: sb_mb NULL but sbavail %u",
2502 sbavail(&so->so_rcv)));
2504 error = so->so_error;
2506 SOCKBUF_UNLOCK(&so->so_rcv);
2509 if (so->so_rcv.sb_state & SBS_CANTRCVMORE ||
2510 uio->uio_resid == 0) {
2511 SOCKBUF_UNLOCK(&so->so_rcv);
2514 if ((so->so_state & SS_NBIO) ||
2515 (flags & (MSG_DONTWAIT|MSG_NBIO))) {
2516 SOCKBUF_UNLOCK(&so->so_rcv);
2517 return (EWOULDBLOCK);
2519 SBLASTRECORDCHK(&so->so_rcv);
2520 SBLASTMBUFCHK(&so->so_rcv);
2521 error = sbwait(&so->so_rcv);
2523 SOCKBUF_UNLOCK(&so->so_rcv);
2527 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
2530 uio->uio_td->td_ru.ru_msgrcv++;
2531 SBLASTRECORDCHK(&so->so_rcv);
2532 SBLASTMBUFCHK(&so->so_rcv);
2533 nextrecord = m->m_nextpkt;
2534 if (nextrecord == NULL) {
2535 KASSERT(so->so_rcv.sb_lastrecord == m,
2536 ("soreceive_dgram: lastrecord != m"));
2539 KASSERT(so->so_rcv.sb_mb->m_nextpkt == nextrecord,
2540 ("soreceive_dgram: m_nextpkt != nextrecord"));
2543 * Pull 'm' and its chain off the front of the packet queue.
2545 so->so_rcv.sb_mb = NULL;
2546 sockbuf_pushsync(&so->so_rcv, nextrecord);
2549 * Walk 'm's chain and free that many bytes from the socket buffer.
2551 for (m2 = m; m2 != NULL; m2 = m2->m_next)
2552 sbfree(&so->so_rcv, m2);
2555 * Do a few last checks before we let go of the lock.
2557 SBLASTRECORDCHK(&so->so_rcv);
2558 SBLASTMBUFCHK(&so->so_rcv);
2559 SOCKBUF_UNLOCK(&so->so_rcv);
2561 if (pr->pr_flags & PR_ADDR) {
2562 KASSERT(m->m_type == MT_SONAME,
2563 ("m->m_type == %d", m->m_type));
2565 *psa = sodupsockaddr(mtod(m, struct sockaddr *),
2570 /* XXXRW: Can this happen? */
2575 * Packet to copyout() is now in 'm' and it is disconnected from the
2578 * Process one or more MT_CONTROL mbufs present before any data mbufs
2579 * in the first mbuf chain on the socket buffer. We call into the
2580 * protocol to perform externalization (or freeing if controlp ==
2581 * NULL). In some cases there can be only MT_CONTROL mbufs without
2584 if (m->m_type == MT_CONTROL) {
2585 struct mbuf *cm = NULL, *cmn;
2586 struct mbuf **cme = &cm;
2592 cme = &(*cme)->m_next;
2594 } while (m != NULL && m->m_type == MT_CONTROL);
2595 while (cm != NULL) {
2598 if (pr->pr_domain->dom_externalize != NULL) {
2599 error = (*pr->pr_domain->dom_externalize)
2600 (cm, controlp, flags);
2601 } else if (controlp != NULL)
2605 if (controlp != NULL) {
2606 while (*controlp != NULL)
2607 controlp = &(*controlp)->m_next;
2612 KASSERT(m == NULL || m->m_type == MT_DATA,
2613 ("soreceive_dgram: !data"));
2614 while (m != NULL && uio->uio_resid > 0) {
2615 len = uio->uio_resid;
2618 error = uiomove(mtod(m, char *), (int)len, uio);
2623 if (len == m->m_len)
2640 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
2641 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
2645 CURVNET_SET(so->so_vnet);
2646 if (!SOLISTENING(so))
2647 error = (so->so_proto->pr_usrreqs->pru_soreceive(so, psa, uio,
2648 mp0, controlp, flagsp));
2656 soshutdown(struct socket *so, int how)
2658 struct protosw *pr = so->so_proto;
2659 int error, soerror_enotconn;
2661 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
2664 soerror_enotconn = 0;
2666 (SS_ISCONNECTED | SS_ISCONNECTING | SS_ISDISCONNECTING)) == 0) {
2668 * POSIX mandates us to return ENOTCONN when shutdown(2) is
2669 * invoked on a datagram sockets, however historically we would
2670 * actually tear socket down. This is known to be leveraged by
2671 * some applications to unblock process waiting in recvXXX(2)
2672 * by other process that it shares that socket with. Try to meet
2673 * both backward-compatibility and POSIX requirements by forcing
2674 * ENOTCONN but still asking protocol to perform pru_shutdown().
2676 if (so->so_type != SOCK_DGRAM && !SOLISTENING(so))
2678 soerror_enotconn = 1;
2681 if (SOLISTENING(so)) {
2682 if (how != SHUT_WR) {
2684 so->so_error = ECONNABORTED;
2685 solisten_wakeup(so); /* unlocks so */
2690 CURVNET_SET(so->so_vnet);
2691 if (pr->pr_usrreqs->pru_flush != NULL)
2692 (*pr->pr_usrreqs->pru_flush)(so, how);
2695 if (how != SHUT_RD) {
2696 error = (*pr->pr_usrreqs->pru_shutdown)(so);
2697 wakeup(&so->so_timeo);
2699 return ((error == 0 && soerror_enotconn) ? ENOTCONN : error);
2701 wakeup(&so->so_timeo);
2705 return (soerror_enotconn ? ENOTCONN : 0);
2709 sorflush(struct socket *so)
2711 struct sockbuf *sb = &so->so_rcv;
2712 struct protosw *pr = so->so_proto;
2718 * In order to avoid calling dom_dispose with the socket buffer mutex
2719 * held, and in order to generally avoid holding the lock for a long
2720 * time, we make a copy of the socket buffer and clear the original
2721 * (except locks, state). The new socket buffer copy won't have
2722 * initialized locks so we can only call routines that won't use or
2723 * assert those locks.
2725 * Dislodge threads currently blocked in receive and wait to acquire
2726 * a lock against other simultaneous readers before clearing the
2727 * socket buffer. Don't let our acquire be interrupted by a signal
2728 * despite any existing socket disposition on interruptable waiting.
2731 (void) sblock(sb, SBL_WAIT | SBL_NOINTR);
2734 * Invalidate/clear most of the sockbuf structure, but leave selinfo
2735 * and mutex data unchanged.
2738 bzero(&aso, sizeof(aso));
2739 aso.so_pcb = so->so_pcb;
2740 bcopy(&sb->sb_startzero, &aso.so_rcv.sb_startzero,
2741 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2742 bzero(&sb->sb_startzero,
2743 sizeof(*sb) - offsetof(struct sockbuf, sb_startzero));
2748 * Dispose of special rights and flush the copied socket. Don't call
2749 * any unsafe routines (that rely on locks being initialized) on aso.
2751 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
2752 (*pr->pr_domain->dom_dispose)(&aso);
2753 sbrelease_internal(&aso.so_rcv, so);
2757 * Wrapper for Socket established helper hook.
2758 * Parameters: socket, context of the hook point, hook id.
2761 hhook_run_socket(struct socket *so, void *hctx, int32_t h_id)
2763 struct socket_hhook_data hhook_data = {
2770 CURVNET_SET(so->so_vnet);
2771 HHOOKS_RUN_IF(V_socket_hhh[h_id], &hhook_data, &so->osd);
2774 /* Ugly but needed, since hhooks return void for now */
2775 return (hhook_data.status);
2779 * Perhaps this routine, and sooptcopyout(), below, ought to come in an
2780 * additional variant to handle the case where the option value needs to be
2781 * some kind of integer, but not a specific size. In addition to their use
2782 * here, these functions are also called by the protocol-level pr_ctloutput()
2786 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
2791 * If the user gives us more than we wanted, we ignore it, but if we
2792 * don't get the minimum length the caller wants, we return EINVAL.
2793 * On success, sopt->sopt_valsize is set to however much we actually
2796 if ((valsize = sopt->sopt_valsize) < minlen)
2799 sopt->sopt_valsize = valsize = len;
2801 if (sopt->sopt_td != NULL)
2802 return (copyin(sopt->sopt_val, buf, valsize));
2804 bcopy(sopt->sopt_val, buf, valsize);
2809 * Kernel version of setsockopt(2).
2811 * XXX: optlen is size_t, not socklen_t
2814 so_setsockopt(struct socket *so, int level, int optname, void *optval,
2817 struct sockopt sopt;
2819 sopt.sopt_level = level;
2820 sopt.sopt_name = optname;
2821 sopt.sopt_dir = SOPT_SET;
2822 sopt.sopt_val = optval;
2823 sopt.sopt_valsize = optlen;
2824 sopt.sopt_td = NULL;
2825 return (sosetopt(so, &sopt));
2829 sosetopt(struct socket *so, struct sockopt *sopt)
2840 CURVNET_SET(so->so_vnet);
2842 if (sopt->sopt_level != SOL_SOCKET) {
2843 if (so->so_proto->pr_ctloutput != NULL)
2844 error = (*so->so_proto->pr_ctloutput)(so, sopt);
2846 error = ENOPROTOOPT;
2848 switch (sopt->sopt_name) {
2849 case SO_ACCEPTFILTER:
2850 error = accept_filt_setopt(so, sopt);
2856 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
2859 if (l.l_linger < 0 ||
2860 l.l_linger > USHRT_MAX ||
2861 l.l_linger > (INT_MAX / hz)) {
2866 so->so_linger = l.l_linger;
2868 so->so_options |= SO_LINGER;
2870 so->so_options &= ~SO_LINGER;
2877 case SO_USELOOPBACK:
2881 case SO_REUSEPORT_LB:
2888 error = sooptcopyin(sopt, &optval, sizeof optval,
2894 so->so_options |= sopt->sopt_name;
2896 so->so_options &= ~sopt->sopt_name;
2901 error = sooptcopyin(sopt, &optval, sizeof optval,
2906 if (optval < 0 || optval >= rt_numfibs) {
2910 if (((so->so_proto->pr_domain->dom_family == PF_INET) ||
2911 (so->so_proto->pr_domain->dom_family == PF_INET6) ||
2912 (so->so_proto->pr_domain->dom_family == PF_ROUTE)))
2913 so->so_fibnum = optval;
2918 case SO_USER_COOKIE:
2919 error = sooptcopyin(sopt, &val32, sizeof val32,
2923 so->so_user_cookie = val32;
2930 error = sooptcopyin(sopt, &optval, sizeof optval,
2936 * Values < 1 make no sense for any of these options,
2944 error = sbsetopt(so, sopt->sopt_name, optval);
2949 #ifdef COMPAT_FREEBSD32
2950 if (SV_CURPROC_FLAG(SV_ILP32)) {
2951 struct timeval32 tv32;
2953 error = sooptcopyin(sopt, &tv32, sizeof tv32,
2955 CP(tv32, tv, tv_sec);
2956 CP(tv32, tv, tv_usec);
2959 error = sooptcopyin(sopt, &tv, sizeof tv,
2963 if (tv.tv_sec < 0 || tv.tv_usec < 0 ||
2964 tv.tv_usec >= 1000000) {
2968 if (tv.tv_sec > INT32_MAX)
2972 switch (sopt->sopt_name) {
2974 so->so_snd.sb_timeo = val;
2977 so->so_rcv.sb_timeo = val;
2984 error = sooptcopyin(sopt, &extmac, sizeof extmac,
2988 error = mac_setsockopt_label(sopt->sopt_td->td_ucred,
2996 error = sooptcopyin(sopt, &optval, sizeof optval,
3000 if (optval < 0 || optval > SO_TS_CLOCK_MAX) {
3004 so->so_ts_clock = optval;
3007 case SO_MAX_PACING_RATE:
3008 error = sooptcopyin(sopt, &val32, sizeof(val32),
3012 so->so_max_pacing_rate = val32;
3016 if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
3017 error = hhook_run_socket(so, sopt,
3020 error = ENOPROTOOPT;
3023 if (error == 0 && so->so_proto->pr_ctloutput != NULL)
3024 (void)(*so->so_proto->pr_ctloutput)(so, sopt);
3032 * Helper routine for getsockopt.
3035 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
3043 * Documented get behavior is that we always return a value, possibly
3044 * truncated to fit in the user's buffer. Traditional behavior is
3045 * that we always tell the user precisely how much we copied, rather
3046 * than something useful like the total amount we had available for
3047 * her. Note that this interface is not idempotent; the entire
3048 * answer must be generated ahead of time.
3050 valsize = min(len, sopt->sopt_valsize);
3051 sopt->sopt_valsize = valsize;
3052 if (sopt->sopt_val != NULL) {
3053 if (sopt->sopt_td != NULL)
3054 error = copyout(buf, sopt->sopt_val, valsize);
3056 bcopy(buf, sopt->sopt_val, valsize);
3062 sogetopt(struct socket *so, struct sockopt *sopt)
3071 CURVNET_SET(so->so_vnet);
3073 if (sopt->sopt_level != SOL_SOCKET) {
3074 if (so->so_proto->pr_ctloutput != NULL)
3075 error = (*so->so_proto->pr_ctloutput)(so, sopt);
3077 error = ENOPROTOOPT;
3081 switch (sopt->sopt_name) {
3082 case SO_ACCEPTFILTER:
3083 error = accept_filt_getopt(so, sopt);
3088 l.l_onoff = so->so_options & SO_LINGER;
3089 l.l_linger = so->so_linger;
3091 error = sooptcopyout(sopt, &l, sizeof l);
3094 case SO_USELOOPBACK:
3100 case SO_REUSEPORT_LB:
3107 optval = so->so_options & sopt->sopt_name;
3109 error = sooptcopyout(sopt, &optval, sizeof optval);
3113 optval = so->so_proto->pr_domain->dom_family;
3117 optval = so->so_type;
3121 optval = so->so_proto->pr_protocol;
3126 optval = so->so_error;
3132 optval = SOLISTENING(so) ? so->sol_sbsnd_hiwat :
3133 so->so_snd.sb_hiwat;
3137 optval = SOLISTENING(so) ? so->sol_sbrcv_hiwat :
3138 so->so_rcv.sb_hiwat;
3142 optval = SOLISTENING(so) ? so->sol_sbsnd_lowat :
3143 so->so_snd.sb_lowat;
3147 optval = SOLISTENING(so) ? so->sol_sbrcv_lowat :
3148 so->so_rcv.sb_lowat;
3153 tv = sbttotv(sopt->sopt_name == SO_SNDTIMEO ?
3154 so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
3155 #ifdef COMPAT_FREEBSD32
3156 if (SV_CURPROC_FLAG(SV_ILP32)) {
3157 struct timeval32 tv32;
3159 CP(tv, tv32, tv_sec);
3160 CP(tv, tv32, tv_usec);
3161 error = sooptcopyout(sopt, &tv32, sizeof tv32);
3164 error = sooptcopyout(sopt, &tv, sizeof tv);
3169 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
3173 error = mac_getsockopt_label(sopt->sopt_td->td_ucred,
3177 error = sooptcopyout(sopt, &extmac, sizeof extmac);
3185 error = sooptcopyin(sopt, &extmac, sizeof(extmac),
3189 error = mac_getsockopt_peerlabel(
3190 sopt->sopt_td->td_ucred, so, &extmac);
3193 error = sooptcopyout(sopt, &extmac, sizeof extmac);
3199 case SO_LISTENQLIMIT:
3200 optval = SOLISTENING(so) ? so->sol_qlimit : 0;
3204 optval = SOLISTENING(so) ? so->sol_qlen : 0;
3207 case SO_LISTENINCQLEN:
3208 optval = SOLISTENING(so) ? so->sol_incqlen : 0;
3212 optval = so->so_ts_clock;
3215 case SO_MAX_PACING_RATE:
3216 optval = so->so_max_pacing_rate;
3220 if (V_socket_hhh[HHOOK_SOCKET_OPT]->hhh_nhooks > 0)
3221 error = hhook_run_socket(so, sopt,
3224 error = ENOPROTOOPT;
3236 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
3238 struct mbuf *m, *m_prev;
3239 int sopt_size = sopt->sopt_valsize;
3241 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
3244 if (sopt_size > MLEN) {
3245 MCLGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT);
3246 if ((m->m_flags & M_EXT) == 0) {
3250 m->m_len = min(MCLBYTES, sopt_size);
3252 m->m_len = min(MLEN, sopt_size);
3254 sopt_size -= m->m_len;
3259 MGET(m, sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
3264 if (sopt_size > MLEN) {
3265 MCLGET(m, sopt->sopt_td != NULL ? M_WAITOK :
3267 if ((m->m_flags & M_EXT) == 0) {
3272 m->m_len = min(MCLBYTES, sopt_size);
3274 m->m_len = min(MLEN, sopt_size);
3276 sopt_size -= m->m_len;
3284 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
3286 struct mbuf *m0 = m;
3288 if (sopt->sopt_val == NULL)
3290 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
3291 if (sopt->sopt_td != NULL) {
3294 error = copyin(sopt->sopt_val, mtod(m, char *),
3301 bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
3302 sopt->sopt_valsize -= m->m_len;
3303 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
3306 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
3307 panic("ip6_sooptmcopyin");
3312 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
3314 struct mbuf *m0 = m;
3317 if (sopt->sopt_val == NULL)
3319 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
3320 if (sopt->sopt_td != NULL) {
3323 error = copyout(mtod(m, char *), sopt->sopt_val,
3330 bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
3331 sopt->sopt_valsize -= m->m_len;
3332 sopt->sopt_val = (char *)sopt->sopt_val + m->m_len;
3333 valsize += m->m_len;
3337 /* enough soopt buffer should be given from user-land */
3341 sopt->sopt_valsize = valsize;
3346 * sohasoutofband(): protocol notifies socket layer of the arrival of new
3347 * out-of-band data, which will then notify socket consumers.
3350 sohasoutofband(struct socket *so)
3353 if (so->so_sigio != NULL)
3354 pgsigio(&so->so_sigio, SIGURG, 0);
3355 selwakeuppri(&so->so_rdsel, PSOCK);
3359 sopoll(struct socket *so, int events, struct ucred *active_cred,
3364 * We do not need to set or assert curvnet as long as everyone uses
3367 return (so->so_proto->pr_usrreqs->pru_sopoll(so, events, active_cred,
3372 sopoll_generic(struct socket *so, int events, struct ucred *active_cred,
3378 if (SOLISTENING(so)) {
3379 if (!(events & (POLLIN | POLLRDNORM)))
3381 else if (!TAILQ_EMPTY(&so->sol_comp))
3382 revents = events & (POLLIN | POLLRDNORM);
3383 else if ((events & POLLINIGNEOF) == 0 && so->so_error)
3384 revents = (events & (POLLIN | POLLRDNORM)) | POLLHUP;
3386 selrecord(td, &so->so_rdsel);
3391 SOCKBUF_LOCK(&so->so_snd);
3392 SOCKBUF_LOCK(&so->so_rcv);
3393 if (events & (POLLIN | POLLRDNORM))
3394 if (soreadabledata(so))
3395 revents |= events & (POLLIN | POLLRDNORM);
3396 if (events & (POLLOUT | POLLWRNORM))
3397 if (sowriteable(so))
3398 revents |= events & (POLLOUT | POLLWRNORM);
3399 if (events & (POLLPRI | POLLRDBAND))
3400 if (so->so_oobmark ||
3401 (so->so_rcv.sb_state & SBS_RCVATMARK))
3402 revents |= events & (POLLPRI | POLLRDBAND);
3403 if ((events & POLLINIGNEOF) == 0) {
3404 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3405 revents |= events & (POLLIN | POLLRDNORM);
3406 if (so->so_snd.sb_state & SBS_CANTSENDMORE)
3412 (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND)) {
3413 selrecord(td, &so->so_rdsel);
3414 so->so_rcv.sb_flags |= SB_SEL;
3416 if (events & (POLLOUT | POLLWRNORM)) {
3417 selrecord(td, &so->so_wrsel);
3418 so->so_snd.sb_flags |= SB_SEL;
3421 SOCKBUF_UNLOCK(&so->so_rcv);
3422 SOCKBUF_UNLOCK(&so->so_snd);
3429 soo_kqfilter(struct file *fp, struct knote *kn)
3431 struct socket *so = kn->kn_fp->f_data;
3435 switch (kn->kn_filter) {
3437 kn->kn_fop = &soread_filtops;
3438 knl = &so->so_rdsel.si_note;
3442 kn->kn_fop = &sowrite_filtops;
3443 knl = &so->so_wrsel.si_note;
3447 kn->kn_fop = &soempty_filtops;
3448 knl = &so->so_wrsel.si_note;
3456 if (SOLISTENING(so)) {
3457 knlist_add(knl, kn, 1);
3460 knlist_add(knl, kn, 1);
3461 sb->sb_flags |= SB_KNOTE;
3469 * Some routines that return EOPNOTSUPP for entry points that are not
3470 * supported by a protocol. Fill in as needed.
3473 pru_accept_notsupp(struct socket *so, struct sockaddr **nam)
3480 pru_aio_queue_notsupp(struct socket *so, struct kaiocb *job)
3487 pru_attach_notsupp(struct socket *so, int proto, struct thread *td)
3494 pru_bind_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
3501 pru_bindat_notsupp(int fd, struct socket *so, struct sockaddr *nam,
3509 pru_connect_notsupp(struct socket *so, struct sockaddr *nam, struct thread *td)
3516 pru_connectat_notsupp(int fd, struct socket *so, struct sockaddr *nam,
3524 pru_connect2_notsupp(struct socket *so1, struct socket *so2)
3531 pru_control_notsupp(struct socket *so, u_long cmd, caddr_t data,
3532 struct ifnet *ifp, struct thread *td)
3539 pru_disconnect_notsupp(struct socket *so)
3546 pru_listen_notsupp(struct socket *so, int backlog, struct thread *td)
3553 pru_peeraddr_notsupp(struct socket *so, struct sockaddr **nam)
3560 pru_rcvd_notsupp(struct socket *so, int flags)
3567 pru_rcvoob_notsupp(struct socket *so, struct mbuf *m, int flags)
3574 pru_send_notsupp(struct socket *so, int flags, struct mbuf *m,
3575 struct sockaddr *addr, struct mbuf *control, struct thread *td)
3582 pru_ready_notsupp(struct socket *so, struct mbuf *m, int count)
3585 return (EOPNOTSUPP);
3589 * This isn't really a ``null'' operation, but it's the default one and
3590 * doesn't do anything destructive.
3593 pru_sense_null(struct socket *so, struct stat *sb)
3596 sb->st_blksize = so->so_snd.sb_hiwat;
3601 pru_shutdown_notsupp(struct socket *so)
3608 pru_sockaddr_notsupp(struct socket *so, struct sockaddr **nam)
3615 pru_sosend_notsupp(struct socket *so, struct sockaddr *addr, struct uio *uio,
3616 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
3623 pru_soreceive_notsupp(struct socket *so, struct sockaddr **paddr,
3624 struct uio *uio, struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
3631 pru_sopoll_notsupp(struct socket *so, int events, struct ucred *cred,
3639 filt_sordetach(struct knote *kn)
3641 struct socket *so = kn->kn_fp->f_data;
3644 knlist_remove(&so->so_rdsel.si_note, kn, 1);
3645 if (!SOLISTENING(so) && knlist_empty(&so->so_rdsel.si_note))
3646 so->so_rcv.sb_flags &= ~SB_KNOTE;
3647 so_rdknl_unlock(so);
3652 filt_soread(struct knote *kn, long hint)
3656 so = kn->kn_fp->f_data;
3658 if (SOLISTENING(so)) {
3659 SOCK_LOCK_ASSERT(so);
3660 kn->kn_data = so->sol_qlen;
3662 kn->kn_flags |= EV_EOF;
3663 kn->kn_fflags = so->so_error;
3666 return (!TAILQ_EMPTY(&so->sol_comp));
3669 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
3671 kn->kn_data = sbavail(&so->so_rcv) - so->so_rcv.sb_ctl;
3672 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
3673 kn->kn_flags |= EV_EOF;
3674 kn->kn_fflags = so->so_error;
3676 } else if (so->so_error) /* temporary udp error */
3679 if (kn->kn_sfflags & NOTE_LOWAT) {
3680 if (kn->kn_data >= kn->kn_sdata)
3682 } else if (sbavail(&so->so_rcv) >= so->so_rcv.sb_lowat)
3685 /* This hook returning non-zero indicates an event, not error */
3686 return (hhook_run_socket(so, NULL, HHOOK_FILT_SOREAD));
3690 filt_sowdetach(struct knote *kn)
3692 struct socket *so = kn->kn_fp->f_data;
3695 knlist_remove(&so->so_wrsel.si_note, kn, 1);
3696 if (!SOLISTENING(so) && knlist_empty(&so->so_wrsel.si_note))
3697 so->so_snd.sb_flags &= ~SB_KNOTE;
3698 so_wrknl_unlock(so);
3703 filt_sowrite(struct knote *kn, long hint)
3707 so = kn->kn_fp->f_data;
3709 if (SOLISTENING(so))
3712 SOCKBUF_LOCK_ASSERT(&so->so_snd);
3713 kn->kn_data = sbspace(&so->so_snd);
3715 hhook_run_socket(so, kn, HHOOK_FILT_SOWRITE);
3717 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
3718 kn->kn_flags |= EV_EOF;
3719 kn->kn_fflags = so->so_error;
3721 } else if (so->so_error) /* temporary udp error */
3723 else if (((so->so_state & SS_ISCONNECTED) == 0) &&
3724 (so->so_proto->pr_flags & PR_CONNREQUIRED))
3726 else if (kn->kn_sfflags & NOTE_LOWAT)
3727 return (kn->kn_data >= kn->kn_sdata);
3729 return (kn->kn_data >= so->so_snd.sb_lowat);
3733 filt_soempty(struct knote *kn, long hint)
3737 so = kn->kn_fp->f_data;
3739 if (SOLISTENING(so))
3742 SOCKBUF_LOCK_ASSERT(&so->so_snd);
3743 kn->kn_data = sbused(&so->so_snd);
3745 if (kn->kn_data == 0)
3752 socheckuid(struct socket *so, uid_t uid)
3757 if (so->so_cred->cr_uid != uid)
3763 * These functions are used by protocols to notify the socket layer (and its
3764 * consumers) of state changes in the sockets driven by protocol-side events.
3768 * Procedures to manipulate state flags of socket and do appropriate wakeups.
3770 * Normal sequence from the active (originating) side is that
3771 * soisconnecting() is called during processing of connect() call, resulting
3772 * in an eventual call to soisconnected() if/when the connection is
3773 * established. When the connection is torn down soisdisconnecting() is
3774 * called during processing of disconnect() call, and soisdisconnected() is
3775 * called when the connection to the peer is totally severed. The semantics
3776 * of these routines are such that connectionless protocols can call
3777 * soisconnected() and soisdisconnected() only, bypassing the in-progress
3778 * calls when setting up a ``connection'' takes no time.
3780 * From the passive side, a socket is created with two queues of sockets:
3781 * so_incomp for connections in progress and so_comp for connections already
3782 * made and awaiting user acceptance. As a protocol is preparing incoming
3783 * connections, it creates a socket structure queued on so_incomp by calling
3784 * sonewconn(). When the connection is established, soisconnected() is
3785 * called, and transfers the socket structure to so_comp, making it available
3788 * If a socket is closed with sockets on either so_incomp or so_comp, these
3789 * sockets are dropped.
3791 * If higher-level protocols are implemented in the kernel, the wakeups done
3792 * here will sometimes cause software-interrupt process scheduling.
3795 soisconnecting(struct socket *so)
3799 so->so_state &= ~(SS_ISCONNECTED|SS_ISDISCONNECTING);
3800 so->so_state |= SS_ISCONNECTING;
3805 soisconnected(struct socket *so)
3809 so->so_state &= ~(SS_ISCONNECTING|SS_ISDISCONNECTING|SS_ISCONFIRMING);
3810 so->so_state |= SS_ISCONNECTED;
3812 if (so->so_qstate == SQ_INCOMP) {
3813 struct socket *head = so->so_listen;
3816 KASSERT(head, ("%s: so %p on incomp of NULL", __func__, so));
3818 * Promoting a socket from incomplete queue to complete, we
3819 * need to go through reverse order of locking. We first do
3820 * trylock, and if that doesn't succeed, we go the hard way
3821 * leaving a reference and rechecking consistency after proper
3824 if (__predict_false(SOLISTEN_TRYLOCK(head) == 0)) {
3827 SOLISTEN_LOCK(head);
3829 if (__predict_false(head != so->so_listen)) {
3831 * The socket went off the listen queue,
3832 * should be lost race to close(2) of sol.
3833 * The socket is about to soabort().
3839 /* Not the last one, as so holds a ref. */
3840 refcount_release(&head->so_count);
3843 if ((so->so_options & SO_ACCEPTFILTER) == 0) {
3844 TAILQ_REMOVE(&head->sol_incomp, so, so_list);
3845 head->sol_incqlen--;
3846 TAILQ_INSERT_TAIL(&head->sol_comp, so, so_list);
3848 so->so_qstate = SQ_COMP;
3850 solisten_wakeup(head); /* unlocks */
3852 SOCKBUF_LOCK(&so->so_rcv);
3853 soupcall_set(so, SO_RCV,
3854 head->sol_accept_filter->accf_callback,
3855 head->sol_accept_filter_arg);
3856 so->so_options &= ~SO_ACCEPTFILTER;
3857 ret = head->sol_accept_filter->accf_callback(so,
3858 head->sol_accept_filter_arg, M_NOWAIT);
3859 if (ret == SU_ISCONNECTED) {
3860 soupcall_clear(so, SO_RCV);
3861 SOCKBUF_UNLOCK(&so->so_rcv);
3864 SOCKBUF_UNLOCK(&so->so_rcv);
3866 SOLISTEN_UNLOCK(head);
3871 wakeup(&so->so_timeo);
3877 soisdisconnecting(struct socket *so)
3881 so->so_state &= ~SS_ISCONNECTING;
3882 so->so_state |= SS_ISDISCONNECTING;
3884 if (!SOLISTENING(so)) {
3885 SOCKBUF_LOCK(&so->so_rcv);
3886 socantrcvmore_locked(so);
3887 SOCKBUF_LOCK(&so->so_snd);
3888 socantsendmore_locked(so);
3891 wakeup(&so->so_timeo);
3895 soisdisconnected(struct socket *so)
3899 so->so_state &= ~(SS_ISCONNECTING|SS_ISCONNECTED|SS_ISDISCONNECTING);
3900 so->so_state |= SS_ISDISCONNECTED;
3902 if (!SOLISTENING(so)) {
3904 SOCKBUF_LOCK(&so->so_rcv);
3905 socantrcvmore_locked(so);
3906 SOCKBUF_LOCK(&so->so_snd);
3907 sbdrop_locked(&so->so_snd, sbused(&so->so_snd));
3908 socantsendmore_locked(so);
3911 wakeup(&so->so_timeo);
3915 * Make a copy of a sockaddr in a malloced buffer of type M_SONAME.
3918 sodupsockaddr(const struct sockaddr *sa, int mflags)
3920 struct sockaddr *sa2;
3922 sa2 = malloc(sa->sa_len, M_SONAME, mflags);
3924 bcopy(sa, sa2, sa->sa_len);
3929 * Register per-socket destructor.
3932 sodtor_set(struct socket *so, so_dtor_t *func)
3935 SOCK_LOCK_ASSERT(so);
3940 * Register per-socket buffer upcalls.
3943 soupcall_set(struct socket *so, int which, so_upcall_t func, void *arg)
3947 KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so));
3957 panic("soupcall_set: bad which");
3959 SOCKBUF_LOCK_ASSERT(sb);
3960 sb->sb_upcall = func;
3961 sb->sb_upcallarg = arg;
3962 sb->sb_flags |= SB_UPCALL;
3966 soupcall_clear(struct socket *so, int which)
3970 KASSERT(!SOLISTENING(so), ("%s: so %p listening", __func__, so));
3980 panic("soupcall_clear: bad which");
3982 SOCKBUF_LOCK_ASSERT(sb);
3983 KASSERT(sb->sb_upcall != NULL,
3984 ("%s: so %p no upcall to clear", __func__, so));
3985 sb->sb_upcall = NULL;
3986 sb->sb_upcallarg = NULL;
3987 sb->sb_flags &= ~SB_UPCALL;
3991 solisten_upcall_set(struct socket *so, so_upcall_t func, void *arg)
3994 SOLISTEN_LOCK_ASSERT(so);
3995 so->sol_upcall = func;
3996 so->sol_upcallarg = arg;
4000 so_rdknl_lock(void *arg)
4002 struct socket *so = arg;
4004 if (SOLISTENING(so))
4007 SOCKBUF_LOCK(&so->so_rcv);
4011 so_rdknl_unlock(void *arg)
4013 struct socket *so = arg;
4015 if (SOLISTENING(so))
4018 SOCKBUF_UNLOCK(&so->so_rcv);
4022 so_rdknl_assert_locked(void *arg)
4024 struct socket *so = arg;
4026 if (SOLISTENING(so))
4027 SOCK_LOCK_ASSERT(so);
4029 SOCKBUF_LOCK_ASSERT(&so->so_rcv);
4033 so_rdknl_assert_unlocked(void *arg)
4035 struct socket *so = arg;
4037 if (SOLISTENING(so))
4038 SOCK_UNLOCK_ASSERT(so);
4040 SOCKBUF_UNLOCK_ASSERT(&so->so_rcv);
4044 so_wrknl_lock(void *arg)
4046 struct socket *so = arg;
4048 if (SOLISTENING(so))
4051 SOCKBUF_LOCK(&so->so_snd);
4055 so_wrknl_unlock(void *arg)
4057 struct socket *so = arg;
4059 if (SOLISTENING(so))
4062 SOCKBUF_UNLOCK(&so->so_snd);
4066 so_wrknl_assert_locked(void *arg)
4068 struct socket *so = arg;
4070 if (SOLISTENING(so))
4071 SOCK_LOCK_ASSERT(so);
4073 SOCKBUF_LOCK_ASSERT(&so->so_snd);
4077 so_wrknl_assert_unlocked(void *arg)
4079 struct socket *so = arg;
4081 if (SOLISTENING(so))
4082 SOCK_UNLOCK_ASSERT(so);
4084 SOCKBUF_UNLOCK_ASSERT(&so->so_snd);
4088 * Create an external-format (``xsocket'') structure using the information in
4089 * the kernel-format socket structure pointed to by so. This is done to
4090 * reduce the spew of irrelevant information over this interface, to isolate
4091 * user code from changes in the kernel structure, and potentially to provide
4092 * information-hiding if we decide that some of this information should be
4093 * hidden from users.
4096 sotoxsocket(struct socket *so, struct xsocket *xso)
4099 bzero(xso, sizeof(*xso));
4100 xso->xso_len = sizeof *xso;
4101 xso->xso_so = (uintptr_t)so;
4102 xso->so_type = so->so_type;
4103 xso->so_options = so->so_options;
4104 xso->so_linger = so->so_linger;
4105 xso->so_state = so->so_state;
4106 xso->so_pcb = (uintptr_t)so->so_pcb;
4107 xso->xso_protocol = so->so_proto->pr_protocol;
4108 xso->xso_family = so->so_proto->pr_domain->dom_family;
4109 xso->so_timeo = so->so_timeo;
4110 xso->so_error = so->so_error;
4111 xso->so_uid = so->so_cred->cr_uid;
4112 xso->so_pgid = so->so_sigio ? so->so_sigio->sio_pgid : 0;
4113 if (SOLISTENING(so)) {
4114 xso->so_qlen = so->sol_qlen;
4115 xso->so_incqlen = so->sol_incqlen;
4116 xso->so_qlimit = so->sol_qlimit;
4117 xso->so_oobmark = 0;
4119 xso->so_state |= so->so_qstate;
4120 xso->so_qlen = xso->so_incqlen = xso->so_qlimit = 0;
4121 xso->so_oobmark = so->so_oobmark;
4122 sbtoxsockbuf(&so->so_snd, &xso->so_snd);
4123 sbtoxsockbuf(&so->so_rcv, &xso->so_rcv);
4128 so_sockbuf_rcv(struct socket *so)
4131 return (&so->so_rcv);
4135 so_sockbuf_snd(struct socket *so)
4138 return (&so->so_snd);
4142 so_state_get(const struct socket *so)
4145 return (so->so_state);
4149 so_state_set(struct socket *so, int val)
4156 so_options_get(const struct socket *so)
4159 return (so->so_options);
4163 so_options_set(struct socket *so, int val)
4166 so->so_options = val;
4170 so_error_get(const struct socket *so)
4173 return (so->so_error);
4177 so_error_set(struct socket *so, int val)
4184 so_linger_get(const struct socket *so)
4187 return (so->so_linger);
4191 so_linger_set(struct socket *so, int val)
4194 KASSERT(val >= 0 && val <= USHRT_MAX && val <= (INT_MAX / hz),
4195 ("%s: val %d out of range", __func__, val));
4197 so->so_linger = val;
4201 so_protosw_get(const struct socket *so)
4204 return (so->so_proto);
4208 so_protosw_set(struct socket *so, struct protosw *val)
4215 so_sorwakeup(struct socket *so)
4222 so_sowwakeup(struct socket *so)
4229 so_sorwakeup_locked(struct socket *so)
4232 sorwakeup_locked(so);
4236 so_sowwakeup_locked(struct socket *so)
4239 sowwakeup_locked(so);
4243 so_lock(struct socket *so)
4250 so_unlock(struct socket *so)